fission-core 0.4.0

Core runtime, state, actions, effects, resources, input, and UI model for Fission
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
use crate::{
    action::video::{
        VideoPause, VideoPlay, VideoSeek, VideoSetMuted, VideoSetRate, VideoSetVolume, VideoStop,
    },
    async_runtime::{
        JobRef, JobRequestPayload, JobSpec, ServiceBindings, ServiceSlot, ServiceSpec,
        ServiceStartPayload,
    },
    context::{Effects, ReducerContext},
    effect::{ActionInput, Effect, EffectEnvelope},
    ui::Widget,
    Action, ActionEnvelope, ActionId, BoxedReducer, GlobalState,
};
use anyhow::{anyhow, Result};
use fission_ir::WidgetId;
use serde::Serialize;
use std::any::TypeId;
use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;

/// The canonical 3-argument handler signature for modern reducers.
///
/// ```rust,ignore
/// fn handle_increment(state: &mut Counter, _: Increment, _ctx: &mut ReducerContext<Counter>) {
///     state.count += 1;
/// }
/// ```
pub type Handler<S, A> = for<'a, 'b, 'c> fn(&mut S, A, &mut ReducerContext<'a, 'b, 'c, S>);

/// Trait that allows both 2-argument (legacy) and 3-argument (modern) handler
/// functions to be used with [`ActionRegistry::register`] and
/// [`BuildCtxHandle::bind`](crate::build::BuildCtxHandle::bind).
pub trait IntoHandler<S: GlobalState, A> {
    /// Invoke the handler with the given state, action, and context.
    fn call<'a, 'b, 'c>(&self, state: &mut S, action: A, ctx: &mut ReducerContext<'a, 'b, 'c, S>);
}

// Impl for Legacy (2-arg)
impl<S: GlobalState, A> IntoHandler<S, A> for fn(&mut S, A) {
    fn call<'a, 'b, 'c>(&self, state: &mut S, action: A, _ctx: &mut ReducerContext<'a, 'b, 'c, S>) {
        (self)(state, action);
    }
}

// Impl for Modern (3-arg)
impl<S: GlobalState, A> IntoHandler<S, A>
    for for<'a, 'b, 'c> fn(&mut S, A, &mut ReducerContext<'a, 'b, 'c, S>)
{
    fn call<'a, 'b, 'c>(&self, state: &mut S, action: A, ctx: &mut ReducerContext<'a, 'b, 'c, S>) {
        (self)(state, action, ctx);
    }
}

// Internal typed reducer storage
type TypedReducer<S> = Box<
    dyn for<'a, 'b, 'c> Fn(
            &mut S,
            &ActionEnvelope,
            WidgetId,
            &mut Effects<'a, S>,
            &'b ActionInput,
        ) -> Result<()>
        + Send
        + Sync,
>;

/// A per-frame collection of action handlers registered during widget building.
///
/// `ActionRegistry` is populated by [`BuildCtxHandle::bind`](crate::build::BuildCtxHandle::bind)
/// calls. After the widget
/// tree is built, the registry is absorbed into the [`Runtime`](crate::Runtime)
/// via [`Runtime::absorb_registry`](crate::Runtime::absorb_registry).
pub struct ActionRegistry<S: GlobalState> {
    handlers: BTreeMap<ActionId, Vec<TypedReducer<S>>>,
    runtime_handlers: BTreeMap<ActionId, Vec<BoxedReducer>>,
}

impl<S: GlobalState> Default for ActionRegistry<S> {
    fn default() -> Self {
        Self {
            handlers: BTreeMap::new(),
            runtime_handlers: BTreeMap::new(),
        }
    }
}

impl<S: GlobalState> ActionRegistry<S> {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn register<A: Action, H: IntoHandler<S, A> + Send + Sync + 'static>(
        &mut self,
        handler: H,
    ) {
        let action_id = A::static_id();

        let typed_reducer: TypedReducer<S> = Box::new(
            move |state: &mut S,
                  envelope: &ActionEnvelope,
                  _target,
                  effects,
                  input|
                  -> Result<()> {
                let action: A = serde_json::from_slice(&envelope.payload)
                    .map_err(|e| anyhow!("Failed to deserialize action: {}", e))?;

                let mut ctx = ReducerContext { effects, input };

                handler.call(state, action, &mut ctx);
                Ok(())
            },
        );

        self.handlers
            .entry(action_id)
            .or_default()
            .push(typed_reducer);
    }

    pub(crate) fn register_runtime_reducer(&mut self, action_id: ActionId, reducer: BoxedReducer) {
        self.runtime_handlers
            .entry(action_id)
            .or_default()
            .push(reducer);
    }

    pub fn dispatch_with_input(
        &mut self,
        state: &mut S,
        action: &ActionEnvelope,
        target: WidgetId,
        input: &ActionInput,
    ) -> Result<Vec<EffectEnvelope>> {
        let mut effects_builder = Effects::new_headless(0);
        let target: WidgetId = target.into();
        if let Some(reducers) = self.handlers.get_mut(&action.id) {
            for reducer in reducers {
                reducer(state, action, target, &mut effects_builder, input)?;
            }
        }
        Ok(effects_builder.out)
    }

    pub fn dispatch(
        &mut self,
        state: &mut S,
        action: &ActionEnvelope,
        target: WidgetId,
    ) -> Result<Vec<EffectEnvelope>> {
        self.dispatch_with_input(state, action, target, &ActionInput::None)
    }

    pub(crate) fn into_runtime_reducers(self) -> HashMap<ActionId, Vec<BoxedReducer>> {
        let mut runtime_reducers: HashMap<ActionId, Vec<BoxedReducer>> = HashMap::new();
        let state_type_id = TypeId::of::<S>();

        for (action_id, mut reducers) in self.runtime_handlers {
            runtime_reducers
                .entry(action_id)
                .or_default()
                .append(&mut reducers);
        }

        for (action_id, typed_reducers) in self.handlers {
            for typed_reducer in typed_reducers {
                let boxed_reducer: BoxedReducer = Box::new(
                    move |app_states: &mut HashMap<TypeId, Box<dyn GlobalState>>,
                          action: &ActionEnvelope,
                          target: WidgetId,
                          out_effects: &mut Vec<EffectEnvelope>,
                          input: &ActionInput|
                          -> Result<()> {
                        if let Some(state_box) = app_states.get_mut(&state_type_id) {
                            let concrete_state =
                                state_box.downcast_mut::<S>().ok_or_else(|| {
                                    anyhow!("Failed to downcast GlobalState to concrete type")
                                })?;

                            let mut effects_builder = Effects::new_headless(0);

                            typed_reducer(
                                concrete_state,
                                action,
                                target,
                                &mut effects_builder,
                                input,
                            )?;

                            out_effects.extend(effects_builder.out);

                            Ok(())
                        } else {
                            anyhow::bail!("Target GlobalState for reducer not found in runtime.");
                        }
                    },
                );

                runtime_reducers
                    .entry(action_id)
                    .or_default()
                    .push(boxed_reducer);
            }
        }
        runtime_reducers
    }
}

/// Identifies which visual property an animation targets.
///
/// Built-in properties have well-known default values (e.g. opacity defaults
/// to 1.0, translation defaults to 0.0). Custom properties use 0.0.
///
/// # Example
///
/// ```rust,ignore
/// ctx.anim_for(widget_id).request(AnimationRequest {
///     property: AnimationPropertyId::Opacity,
///     from: AnimationStartValue::Current,
///     to: 0.0,
///     duration_ms: 300,
///     repeat: false,
///     delay_ms: 0,
/// });
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum AnimationPropertyId {
    Opacity,
    TranslateX,
    TranslateY,
    Scale,
    Rotation,
    Custom(Arc<str>),
}

impl AnimationPropertyId {
    pub fn opacity() -> Self {
        Self::Opacity
    }
    pub fn translate_x() -> Self {
        Self::TranslateX
    }
    pub fn translate_y() -> Self {
        Self::TranslateY
    }
    pub fn scale() -> Self {
        Self::Scale
    }
    pub fn rotation() -> Self {
        Self::Rotation
    }
    pub fn custom(name: impl Into<String>) -> Self {
        Self::Custom(Arc::from(name.into()))
    }
    pub fn default_value(&self) -> f32 {
        match self {
            Self::Opacity => 1.0,
            Self::Scale => 1.0,
            Self::TranslateX | Self::TranslateY | Self::Rotation | Self::Custom(_) => 0.0,
        }
    }
}

/// Where an animation starts from.
#[derive(Clone, Debug)]
pub enum AnimationStartValue {
    /// Start from an explicit value.
    Explicit(f32),
    /// Start from whatever the current animated value is.
    Current,
}

/// A request to animate a visual property on a widget.
///
/// Registered via [`BuildCtx::request_animation_for`] or
/// [`AnimCtx::request`].
/// Easing function applied to animation progress before interpolation.
#[derive(Clone, Debug, PartialEq)]
pub enum EasingFunction {
    Linear,
    EaseIn,
    EaseOut,
    EaseInOut,
    CubicBezier(f32, f32, f32, f32),
}

impl Default for EasingFunction {
    fn default() -> Self {
        Self::EaseInOut
    }
}

impl EasingFunction {
    /// Map a linear progress value `t` in [0, 1] to an eased value.
    pub fn apply(&self, t: f32) -> f32 {
        match self {
            Self::Linear => t,
            Self::EaseIn => t * t,
            Self::EaseOut => 1.0 - (1.0 - t) * (1.0 - t),
            Self::EaseInOut => {
                if t < 0.5 {
                    2.0 * t * t
                } else {
                    1.0 - (-2.0 * t + 2.0).powi(2) / 2.0
                }
            }
            Self::CubicBezier(_x1, y1, _x2, y2) => {
                // Simplified cubic bezier approximation (y-axis only)
                let t2 = t * t;
                let t3 = t2 * t;
                3.0 * (1.0 - t) * (1.0 - t) * t * y1 + 3.0 * (1.0 - t) * t2 * y2 + t3
            }
        }
    }
}
#[derive(Clone, Debug)]
pub struct AnimationRequest {
    /// The property to animate.
    pub property: AnimationPropertyId,
    /// Starting value.
    pub from: AnimationStartValue,
    /// Target value.
    pub to: f32,
    /// Duration in milliseconds.
    pub duration_ms: u64,
    /// Whether to loop the animation.
    pub repeat: bool,
    /// Delay before the animation starts (in milliseconds).
    pub delay_ms: u64,
    /// Optional preferred redraw cadence for this animation (in milliseconds).
    ///
    /// This is primarily useful for low-priority repeating effects such as
    /// loading indicators that do not need full frame-rate updates.
    pub frame_interval_ms: Option<u64>,
    pub easing: EasingFunction,
}

/// Registration data for a [`Video`](crate::ui::Video) widget collected during
/// widget building.
#[derive(Clone, Debug)]
pub struct VideoRegistration {
    /// The stable widget identity of the video node.
    pub node_id: WidgetId,
    /// URL or asset path to the video file.
    pub source: String,
    /// Whether to start playing automatically.
    pub autoplay: bool,
    /// Whether to loop playback.
    pub loop_playback: bool,
}

/// Registration data for a platform web view collected during widget building.
#[derive(Clone, Debug)]
pub struct WebRegistration {
    /// The stable widget identity of the web view node.
    pub node_id: WidgetId,
    /// The URL to load.
    pub url: String,
    /// Optional custom user-agent string.
    pub user_agent: Option<String>,
}

/// Z-order layer for portal entries.
///
/// Portals are sorted by layer (then by registration order within a layer).
/// Higher layers paint on top of lower layers.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum PortalLayer {
    /// Default overlay layer.
    Default = 0,
    /// Modal dialog layer.
    Modal = 100,
    /// Flyout / dropdown layer.
    Flyout = 200,
    /// Toast notification layer (topmost).
    Toast = 300,
}

/// An entry in the portal overlay stack.
///
/// Created by [`BuildCtx::register_portal`] and friends.
#[derive(Clone, Debug)]
pub struct PortalEntry {
    /// Which overlay layer this portal belongs to.
    pub layer: PortalLayer,
    /// Insertion order (for stable ordering within a layer).
    pub seq: u64,
    /// Optional stable identity.
    pub id: Option<WidgetId>,
    /// The portal's widget tree.
    pub node: Widget,
}

/// The mutable context available during `impl From<Component> for Widget`.
///
#[derive(Clone, Copy)]
pub struct VideoControlCtx {
    pub(crate) target: WidgetId,
}

impl VideoControlCtx {
    pub fn play(&self) -> ActionEnvelope {
        let action = VideoPlay {
            target: self.target,
        };
        ActionEnvelope {
            id: VideoPlay::static_id(),
            payload: action.encode(),
        }
    }

    pub fn pause(&self) -> ActionEnvelope {
        let action = VideoPause {
            target: self.target,
        };
        ActionEnvelope {
            id: VideoPause::static_id(),
            payload: action.encode(),
        }
    }

    pub fn stop(&self) -> ActionEnvelope {
        let action = VideoStop {
            target: self.target,
        };
        ActionEnvelope {
            id: VideoStop::static_id(),
            payload: action.encode(),
        }
    }

    pub fn seek_to(&self, position_ms: u64) -> ActionEnvelope {
        let action = VideoSeek {
            target: self.target,
            position_ms,
        };
        ActionEnvelope {
            id: VideoSeek::static_id(),
            payload: action.encode(),
        }
    }

    pub fn set_rate(&self, rate: f32) -> ActionEnvelope {
        let action = VideoSetRate {
            target: self.target,
            rate,
        };
        ActionEnvelope {
            id: VideoSetRate::static_id(),
            payload: action.encode(),
        }
    }

    pub fn set_volume(&self, volume: f32) -> ActionEnvelope {
        let action = VideoSetVolume {
            target: self.target,
            volume,
        };
        ActionEnvelope {
            id: VideoSetVolume::static_id(),
            payload: action.encode(),
        }
    }

    pub fn set_muted(&self, muted: bool) -> ActionEnvelope {
        let action = VideoSetMuted {
            target: self.target,
            muted,
        };
        ActionEnvelope {
            id: VideoSetMuted::static_id(),
            payload: action.encode(),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct ResourceKey(String);

impl ResourceKey {
    pub fn new(name: impl Into<String>) -> Self {
        Self(name.into())
    }

    pub fn widget(name: impl AsRef<str>, id: WidgetId) -> Self {
        Self(format!("widget:{}:{}", id.as_u128(), name.as_ref()))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ResourcePolicy {
    PreserveOnChange,
    RestartOnChange,
}

impl Default for ResourcePolicy {
    fn default() -> Self {
        Self::RestartOnChange
    }
}

#[derive(Clone, Debug, PartialEq)]
pub struct RuntimeResourceDeclaration {
    pub key: String,
    pub deps: Option<Vec<u8>>,
    pub policy: ResourcePolicy,
    pub kind: RuntimeResourceKind,
}

#[derive(Clone, Debug, PartialEq)]
pub enum RuntimeResourceKind {
    Job(JobResource),
    Service(ServiceResource),
    Timer(TimerResource),
}

#[derive(Clone, Debug, PartialEq)]
pub struct JobResource {
    pub key: ResourceKey,
    pub effect: EffectEnvelope,
    pub deps: Option<Vec<u8>>,
    pub policy: ResourcePolicy,
}

impl JobResource {
    pub fn new<J: JobSpec>(key: ResourceKey, job: JobRef<J>, request: J::Request) -> Self {
        let payload =
            serde_json::to_vec(&request).expect("job resource request serialization must succeed");
        Self {
            key,
            effect: EffectEnvelope {
                req_id: 0,
                effect: Effect::Job(JobRequestPayload {
                    job_name: job.name.to_string(),
                    payload,
                }),
                on_ok: None,
                on_err: None,
                service_bindings: None,
                resource: None,
            },
            deps: None,
            policy: ResourcePolicy::RestartOnChange,
        }
    }

    pub fn deps<T: Serialize>(mut self, deps: T) -> Self {
        self.deps =
            Some(serde_json::to_vec(&deps).expect("resource deps serialization must succeed"));
        self
    }

    pub fn preserve_on_change(mut self) -> Self {
        self.policy = ResourcePolicy::PreserveOnChange;
        self
    }

    pub fn restart_on_change(mut self) -> Self {
        self.policy = ResourcePolicy::RestartOnChange;
        self
    }

    pub fn on_ok(mut self, action: ActionEnvelope) -> Self {
        self.effect.on_ok = Some(action);
        self
    }

    pub fn on_err(mut self, action: ActionEnvelope) -> Self {
        self.effect.on_err = Some(action);
        self
    }
}

#[derive(Clone, Debug, PartialEq)]
pub struct ServiceResource {
    pub key: ResourceKey,
    pub effect: EffectEnvelope,
    pub deps: Option<Vec<u8>>,
    pub policy: ResourcePolicy,
}

impl ServiceResource {
    pub fn new<Svc: ServiceSpec>(
        key: ResourceKey,
        slot: ServiceSlot<Svc>,
        config: Svc::Config,
    ) -> Self {
        let config = serde_json::to_vec(&config)
            .expect("service resource config serialization must succeed");
        Self {
            key,
            effect: EffectEnvelope {
                req_id: 0,
                effect: Effect::StartService(ServiceStartPayload {
                    service_name: slot.ty.name.to_string(),
                    slot_key: slot.slot_key().to_string(),
                    config,
                }),
                on_ok: None,
                on_err: None,
                service_bindings: Some(ServiceBindings::default()),
                resource: None,
            },
            deps: None,
            policy: ResourcePolicy::RestartOnChange,
        }
    }

    pub fn deps<T: Serialize>(mut self, deps: T) -> Self {
        self.deps =
            Some(serde_json::to_vec(&deps).expect("resource deps serialization must succeed"));
        self
    }

    pub fn preserve_on_change(mut self) -> Self {
        self.policy = ResourcePolicy::PreserveOnChange;
        self
    }

    pub fn restart_on_change(mut self) -> Self {
        self.policy = ResourcePolicy::RestartOnChange;
        self
    }

    pub fn on_started(mut self, action: ActionEnvelope) -> Self {
        if let Some(bindings) = self.effect.service_bindings.as_mut() {
            bindings.on_started = Some(action);
        }
        self
    }

    pub fn on_start_failed(mut self, action: ActionEnvelope) -> Self {
        if let Some(bindings) = self.effect.service_bindings.as_mut() {
            bindings.on_start_failed = Some(action);
        }
        self
    }

    pub fn on_event(mut self, action: ActionEnvelope) -> Self {
        if let Some(bindings) = self.effect.service_bindings.as_mut() {
            bindings.on_event = Some(action);
        }
        self
    }

    pub fn on_stopped(mut self, action: ActionEnvelope) -> Self {
        if let Some(bindings) = self.effect.service_bindings.as_mut() {
            bindings.on_stopped = Some(action);
        }
        self
    }

    pub fn on_command_ok(mut self, action: ActionEnvelope) -> Self {
        if let Some(bindings) = self.effect.service_bindings.as_mut() {
            bindings.on_command_ok = Some(action);
        }
        self
    }

    pub fn on_command_err(mut self, action: ActionEnvelope) -> Self {
        if let Some(bindings) = self.effect.service_bindings.as_mut() {
            bindings.on_command_err = Some(action);
        }
        self
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TimerResource {
    pub key: ResourceKey,
    pub interval_ms: u64,
    pub payload: Vec<u8>,
    pub on_tick: Option<ActionEnvelope>,
    pub deps: Option<Vec<u8>>,
    pub immediate: bool,
    pub policy: ResourcePolicy,
}

impl TimerResource {
    pub fn new<T: Serialize>(key: ResourceKey, interval: std::time::Duration, payload: T) -> Self {
        Self {
            key,
            interval_ms: interval.as_millis() as u64,
            payload: serde_json::to_vec(&payload)
                .expect("timer resource payload serialization must succeed"),
            on_tick: None,
            deps: None,
            immediate: false,
            policy: ResourcePolicy::RestartOnChange,
        }
    }

    pub fn deps<T: Serialize>(mut self, deps: T) -> Self {
        self.deps =
            Some(serde_json::to_vec(&deps).expect("resource deps serialization must succeed"));
        self
    }

    pub fn preserve_on_change(mut self) -> Self {
        self.policy = ResourcePolicy::PreserveOnChange;
        self
    }

    pub fn restart_on_change(mut self) -> Self {
        self.policy = ResourcePolicy::RestartOnChange;
        self
    }

    pub fn immediate(mut self) -> Self {
        self.immediate = true;
        self
    }

    pub fn on_tick(mut self, action: ActionEnvelope) -> Self {
        self.on_tick = Some(action);
        self
    }
}

#[derive(Default)]
pub struct ResourceRegistry {
    declarations: Vec<RuntimeResourceDeclaration>,
    seen_keys: HashMap<String, usize>,
}

impl ResourceRegistry {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn job(&mut self, resource: JobResource) {
        self.push(RuntimeResourceDeclaration {
            key: resource.key.as_str().to_string(),
            deps: resource.deps.clone(),
            policy: resource.policy,
            kind: RuntimeResourceKind::Job(resource),
        });
    }

    pub fn service(&mut self, resource: ServiceResource) {
        self.push(RuntimeResourceDeclaration {
            key: resource.key.as_str().to_string(),
            deps: resource.deps.clone(),
            policy: resource.policy,
            kind: RuntimeResourceKind::Service(resource),
        });
    }

    pub fn timer(&mut self, resource: TimerResource) {
        self.push(RuntimeResourceDeclaration {
            key: resource.key.as_str().to_string(),
            deps: resource.deps.clone(),
            policy: resource.policy,
            kind: RuntimeResourceKind::Timer(resource),
        });
    }

    pub fn take(&mut self) -> Vec<RuntimeResourceDeclaration> {
        self.seen_keys.clear();
        std::mem::take(&mut self.declarations)
    }

    fn push(&mut self, declaration: RuntimeResourceDeclaration) {
        if let Some(index) = self.seen_keys.get(&declaration.key) {
            panic!(
                "duplicate runtime resource declaration for key '{}' at index {}",
                declaration.key, index
            );
        }
        let index = self.declarations.len();
        self.seen_keys.insert(declaration.key.clone(), index);
        self.declarations.push(declaration);
    }
}