Skip to main content

webizen_runtime/
kernel.rs

1use crate::clock::FixedStepClock;
2use crate::diffusion::{DiffusionConfig, DiffusionField};
3use crate::error::RuntimeError;
4use crate::snapshot::{SharedFrameBuffer, SimulationSnapshot};
5use crossbeam_channel::{Receiver, Sender, TrySendError};
6use std::time::Duration;
7
8pub trait ComputeBackend {
9    fn step(&mut self, epoch: u64) -> Result<SimulationSnapshot, RuntimeError>;
10
11    fn reconfigure(&mut self, _config: DiffusionConfig) -> Result<(), RuntimeError> {
12        Ok(())
13    }
14
15    fn shared_frames(&self) -> Option<SharedFrameBuffer> {
16        None
17    }
18}
19
20#[derive(Debug, Clone)]
21pub struct LedgerRecord {
22    pub epoch: u64,
23    pub dimensions: (u32, u32),
24    pub state_hash: crate::snapshot::StateHash,
25}
26
27impl LedgerRecord {
28    /// Constructs from snapshot.
29    pub fn from_snapshot(snapshot: &SimulationSnapshot) -> Self {
30        Self {
31            epoch: snapshot.epoch,
32            dimensions: snapshot.dimensions,
33            state_hash: snapshot.state_hash,
34        }
35    }
36}
37
38pub trait LedgerSink: Send + Sync {
39    fn record(&self, record: LedgerRecord);
40}
41
42#[derive(Debug, Clone)]
43pub struct ChannelLedgerSink {
44    sender: Sender<LedgerRecord>,
45}
46
47impl ChannelLedgerSink {
48    /// Bounded constructor.
49    pub fn bounded(capacity: usize) -> (Self, Receiver<LedgerRecord>) {
50        let (sender, receiver) = crossbeam_channel::bounded(capacity);
51        (Self { sender }, receiver)
52    }
53}
54
55impl LedgerSink for ChannelLedgerSink {
56    fn record(&self, record: LedgerRecord) {
57        match self.sender.try_send(record) {
58            Ok(_) | Err(TrySendError::Full(_)) | Err(TrySendError::Disconnected(_)) => {}
59        }
60    }
61}
62
63#[derive(Debug, Clone, Copy)]
64pub enum RuntimeCommand {
65    Reconfigure(DiffusionConfig),
66}
67
68#[derive(Default)]
69pub struct NullLedgerSink;
70
71impl LedgerSink for NullLedgerSink {
72    fn record(&self, _record: LedgerRecord) {}
73}
74
75pub struct SimulationKernel<B, L>
76where
77    B: ComputeBackend,
78    L: LedgerSink,
79{
80    clock: FixedStepClock,
81    field: DiffusionField,
82    backend: B,
83    ledger: L,
84    latest_snapshot: Option<SimulationSnapshot>,
85    command_rx: Receiver<RuntimeCommand>,
86    snapshot_tx: Sender<SimulationSnapshot>,
87}
88
89impl<B, L> SimulationKernel<B, L>
90where
91    B: ComputeBackend,
92    L: LedgerSink,
93{
94    /// Creates a new instance.
95    pub fn new(
96        timestep: Duration,
97        config: DiffusionConfig,
98        backend: B,
99        ledger: L,
100    ) -> (Self, Receiver<SimulationSnapshot>, Sender<RuntimeCommand>) {
101        let (command_tx, command_rx) = crossbeam_channel::bounded(16);
102        let (snapshot_tx, snapshot_rx) = crossbeam_channel::bounded(1);
103        let kernel = Self {
104            clock: FixedStepClock::new(timestep),
105            field: DiffusionField::new((config.width, config.height)),
106            backend,
107            ledger,
108            latest_snapshot: None,
109            command_rx,
110            snapshot_tx,
111        };
112        (kernel, snapshot_rx, command_tx)
113    }
114
115    /// Advances by elapsed time.
116    pub fn advance_elapsed(&mut self, elapsed: Duration) -> Result<usize, RuntimeError> {
117        self.drain_control_plane()?;
118        let ticks = self.clock.push_elapsed(elapsed);
119        for _ in 0..ticks {
120            self.tick_once()?;
121        }
122        Ok(ticks)
123    }
124
125    /// Latest snapshot.
126    pub fn latest_snapshot(&self) -> Option<&SimulationSnapshot> {
127        self.latest_snapshot.as_ref()
128    }
129
130    /// Field.
131    pub fn field(&self) -> DiffusionField {
132        self.field
133    }
134
135    /// Shared frames.
136    pub fn shared_frames(&self) -> Option<SharedFrameBuffer> {
137        self.backend.shared_frames()
138    }
139
140    fn tick_once(&mut self) -> Result<(), RuntimeError> {
141        let next_epoch = self.field.epoch + 1;
142        let snapshot = self.backend.step(next_epoch)?;
143        self.field.epoch = snapshot.epoch;
144        self.ledger.record(LedgerRecord::from_snapshot(&snapshot));
145        let _ = self.snapshot_tx.try_send(snapshot.clone());
146        self.latest_snapshot = Some(snapshot);
147        Ok(())
148    }
149
150    fn drain_control_plane(&mut self) -> Result<(), RuntimeError> {
151        while let Ok(command) = self.command_rx.try_recv() {
152            match command {
153                RuntimeCommand::Reconfigure(config) => {
154                    self.backend.reconfigure(config)?;
155                    self.field = DiffusionField::new((config.width, config.height));
156                    self.latest_snapshot = None;
157                }
158            }
159        }
160
161        Ok(())
162    }
163}
164
165#[cfg(test)]
166mod tests {
167    use super::{ComputeBackend, NullLedgerSink, SimulationKernel};
168    use crate::diffusion::DiffusionConfig;
169    use crate::snapshot::{FrameHandle, SimulationSnapshot};
170    use crate::RuntimeError;
171    use std::time::Duration;
172
173    struct MockBackend;
174
175    impl ComputeBackend for MockBackend {
176        fn step(&mut self, epoch: u64) -> Result<SimulationSnapshot, RuntimeError> {
177            Ok(SimulationSnapshot {
178                epoch,
179                dimensions: (4, 4),
180                state_hash: [epoch as u8; 32],
181                frame: FrameHandle::CpuRgbaSlot((epoch as u8) & 1),
182            })
183        }
184    }
185
186    #[test]
187    fn kernel_only_steps_on_complete_ticks() {
188        let (mut kernel, _, _) = SimulationKernel::new(
189            Duration::from_millis(16),
190            DiffusionConfig {
191                width: 4,
192                height: 4,
193                diffusion_rate: 0.2,
194            },
195            MockBackend,
196            NullLedgerSink::default(),
197        );
198
199        assert_eq!(kernel.advance_elapsed(Duration::from_millis(8)).unwrap(), 0);
200        assert!(kernel.latest_snapshot().is_none());
201
202        assert_eq!(
203            kernel.advance_elapsed(Duration::from_millis(24)).unwrap(),
204            2
205        );
206        assert_eq!(kernel.field().epoch, 2);
207        assert_eq!(kernel.latest_snapshot().unwrap().epoch, 2);
208    }
209}