oxide-k 0.3.0

Oxide Kernel - micro-kernel core for the Rust Oxide Agent-Native OS
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
//! # Secure Message Bus
//!
//! An asynchronous message-passing layer for inter-module communication.
//!
//! The bus is built on top of `tokio::sync::mpsc` channels. Modules publish
//! [`Envelope`]s onto the bus and receive routed messages on their own receivers.
//! Every envelope carries provenance metadata (source, timestamp, correlation id)
//! so the kernel can enforce access control and provide an audit trail.
//!
//! ## Topology
//!
//! ```text
//! +--------+   send()   +-----------+   route   +-----------+
//! | Sender | ---------> | MessageBus| --------> | Subscriber|
//! +--------+            +-----------+           +-----------+
//! ```
//!
//! For the bootstrap implementation the bus performs broadcast-style routing:
//! every subscriber receives a clone of each published envelope. This is the
//! simplest model that satisfies the kernel's needs for now; targeted routing
//! and capability-based access control will be layered on top in later
//! iterations.

use std::collections::HashSet;
use std::sync::Arc;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use tokio::sync::{mpsc, RwLock};
use uuid::Uuid;

use crate::error::{KernelError, Result};

// ---------------------------------------------------------------------------
// Capability tokens
// ---------------------------------------------------------------------------

/// An opaque capability token that grants a module the right to publish on
/// the bus.
///
/// Capabilities are strings (e.g. `"browser:navigate"`, `"llm:complete"`).
/// The bus maintains a **grant set**; `publish_with_capability` rejects any
/// token not present in the set. Use [`MessageBus::grant_capability`] to
/// register allowed tokens.
///
/// The unguarded [`MessageBus::publish`] remains available for internal
/// kernel use and backward compatibility.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Capability(pub String);

impl Capability {
    /// Create a capability from any string.
    pub fn new(s: impl Into<String>) -> Self {
        Self(s.into())
    }
}

/// A command instructs a module (or the kernel) to perform an action.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Command {
    /// Request a module to start.
    Start {
        /// The target module id.
        module_id: String,
    },
    /// Request a module to stop.
    Stop {
        /// The target module id.
        module_id: String,
    },
    /// Invoke a named method on a module with an arbitrary JSON payload.
    Invoke {
        /// The target module id.
        module_id: String,
        /// The method name to invoke.
        method: String,
        /// Method arguments encoded as JSON.
        payload: serde_json::Value,
    },
    /// A heartbeat ping used to verify subscribers are alive.
    Ping,
}

/// An event reports something that has already happened.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Event {
    /// A module has finished starting.
    ModuleStarted {
        /// The module id that just started.
        module_id: String,
    },
    /// A module has stopped.
    ModuleStopped {
        /// The module id that just stopped.
        module_id: String,
    },
    /// A module emitted a generic, semi-structured event.
    Custom {
        /// The module id that emitted the event.
        module_id: String,
        /// Event kind, free-form for now.
        kind: String,
        /// Payload encoded as JSON.
        payload: serde_json::Value,
    },
    /// A heartbeat pong matching a [`Command::Ping`].
    Pong {
        /// The id of the responder.
        from: String,
    },
}

/// The payload carried by an [`Envelope`].
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Message {
    /// A command sent to a module.
    Command(Command),
    /// An event emitted by a module.
    Event(Event),
}

/// An envelope wraps a [`Message`] with provenance metadata.
///
/// Every message routed through the bus is wrapped in an [`Envelope`]. The
/// metadata fields make the bus auditable and enable future capability checks.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Envelope {
    /// Unique identifier of this envelope.
    pub id: Uuid,
    /// Source module / subsystem name.
    pub source: String,
    /// Optional correlation id to tie a command to its response event.
    pub correlation_id: Option<Uuid>,
    /// Time the envelope was created.
    pub timestamp: DateTime<Utc>,
    /// The actual message payload.
    pub message: Message,
}

impl Envelope {
    /// Wrap a [`Message`] in a new envelope tagged with the given source.
    pub fn new(source: impl Into<String>, message: Message) -> Self {
        Self {
            id: Uuid::new_v4(),
            source: source.into(),
            correlation_id: None,
            timestamp: Utc::now(),
            message,
        }
    }

    /// Builder helper to attach a correlation id.
    #[must_use]
    pub fn with_correlation_id(mut self, correlation_id: Uuid) -> Self {
        self.correlation_id = Some(correlation_id);
        self
    }
}

/// The capacity of every subscriber channel.
///
/// Small enough to surface back-pressure quickly, large enough to absorb short
/// bursts. Tuned later based on real workloads.
const DEFAULT_SUBSCRIBER_CAPACITY: usize = 128;

/// A subscription returned by [`MessageBus::subscribe`].
///
/// Holding the [`Subscription`] alive keeps the underlying channel open. When it
/// is dropped, the subscriber is removed from the bus on the next publish.
pub struct Subscription {
    /// Receiver end of the subscriber channel.
    pub receiver: mpsc::Receiver<Envelope>,
    /// Stable id for this subscription. Useful for diagnostics.
    pub id: Uuid,
}

/// The kernel-internal message bus.
///
/// `MessageBus` is cheaply cloneable; clones share the same underlying state and
/// can be handed out to modules and subsystems freely.
#[derive(Clone, Default)]
pub struct MessageBus {
    inner: Arc<BusInner>,
}

#[derive(Default)]
struct BusInner {
    subscribers: RwLock<Vec<Subscriber>>,
    /// Granted capability tokens. Empty means "no ACL enforced" for the
    /// unguarded `publish`; `publish_with_capability` always checks this set.
    granted: RwLock<HashSet<String>>,
}

struct Subscriber {
    id: Uuid,
    tx: mpsc::Sender<Envelope>,
}

impl MessageBus {
    /// Construct a new, empty bus.
    pub fn new() -> Self {
        Self::default()
    }

    // -----------------------------------------------------------------------
    // Capability management
    // -----------------------------------------------------------------------

    /// Grant a capability token. After this call, any source holding `cap`
    /// may call [`Self::publish_with_capability`] successfully.
    pub async fn grant_capability(&self, cap: Capability) {
        self.inner.granted.write().await.insert(cap.0);
    }

    /// Revoke a previously granted capability.
    pub async fn revoke_capability(&self, cap: &Capability) {
        self.inner.granted.write().await.remove(&cap.0);
    }

    /// Publish an [`Envelope`] **only if `cap` has been granted**.
    ///
    /// Returns [`KernelError::Denied`] if the capability is not in the grant
    /// set. On success, routes the envelope identically to [`Self::publish`].
    pub async fn publish_with_capability(
        &self,
        envelope: Envelope,
        cap: &Capability,
    ) -> Result<()> {
        let granted = self.inner.granted.read().await;
        if !granted.contains(&cap.0) {
            return Err(KernelError::Denied {
                publisher: envelope.source.clone(),
                capability: cap.0.clone(),
            });
        }
        drop(granted);
        self.publish(envelope).await
    }

    // -----------------------------------------------------------------------
    // Subscribers
    // -----------------------------------------------------------------------

    /// Register a new subscriber and return a [`Subscription`] handle.
    pub async fn subscribe(&self) -> Subscription {
        let (tx, rx) = mpsc::channel(DEFAULT_SUBSCRIBER_CAPACITY);
        let id = Uuid::new_v4();
        self.inner
            .subscribers
            .write()
            .await
            .push(Subscriber { id, tx });
        Subscription { receiver: rx, id }
    }

    /// Publish an [`Envelope`] to every subscriber.
    ///
    /// Subscribers whose channels are closed are silently dropped. If a
    /// subscriber's channel is full the message is dropped *for that
    /// subscriber only* and a warning is traced; this prevents one slow
    /// subscriber from blocking the whole bus.
    pub async fn publish(&self, envelope: Envelope) -> Result<()> {
        let mut subs = self.inner.subscribers.write().await;
        let mut alive = Vec::with_capacity(subs.len());

        for sub in subs.drain(..) {
            if sub.tx.is_closed() {
                tracing::debug!(subscriber = %sub.id, "dropping closed subscriber");
                continue;
            }
            match sub.tx.try_send(envelope.clone()) {
                Ok(()) => alive.push(sub),
                Err(mpsc::error::TrySendError::Full(_)) => {
                    tracing::warn!(subscriber = %sub.id, "subscriber channel full; message dropped");
                    alive.push(sub);
                }
                Err(mpsc::error::TrySendError::Closed(_)) => {
                    tracing::debug!(subscriber = %sub.id, "subscriber closed during publish");
                }
            }
        }

        *subs = alive;
        Ok(())
    }

    /// Convenience helper: wrap a [`Command`] in an [`Envelope`] and publish it.
    pub async fn send_command(&self, source: impl Into<String>, command: Command) -> Result<Uuid> {
        let envelope = Envelope::new(source, Message::Command(command));
        let id = envelope.id;
        self.publish(envelope).await?;
        Ok(id)
    }

    /// Convenience helper: wrap an [`Event`] in an [`Envelope`] and publish it.
    pub async fn emit_event(&self, source: impl Into<String>, event: Event) -> Result<Uuid> {
        let envelope = Envelope::new(source, Message::Event(event));
        let id = envelope.id;
        self.publish(envelope).await?;
        Ok(id)
    }

    /// Returns the number of live subscribers (best-effort).
    pub async fn subscriber_count(&self) -> usize {
        self.inner.subscribers.read().await.len()
    }
}

impl std::fmt::Debug for MessageBus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MessageBus").finish_non_exhaustive()
    }
}

// `From<mpsc::error::SendError<T>>` is hard to implement generically because
// `T` would have to be `'static`. Instead we expose a small helper that callers
// can use when they explicitly want to convert a send failure.
impl<T> From<mpsc::error::SendError<T>> for KernelError {
    fn from(err: mpsc::error::SendError<T>) -> Self {
        KernelError::Bus(format!("channel send failed: {err}"))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn publish_delivers_to_all_subscribers() {
        let bus = MessageBus::new();
        let mut sub_a = bus.subscribe().await;
        let mut sub_b = bus.subscribe().await;
        assert_eq!(bus.subscriber_count().await, 2);

        bus.send_command("test", Command::Ping).await.unwrap();

        let a = sub_a.receiver.recv().await.expect("a received");
        let b = sub_b.receiver.recv().await.expect("b received");
        assert!(matches!(a.message, Message::Command(Command::Ping)));
        assert!(matches!(b.message, Message::Command(Command::Ping)));
    }

    #[tokio::test]
    async fn closed_subscribers_are_pruned() {
        let bus = MessageBus::new();
        {
            let _sub = bus.subscribe().await;
            assert_eq!(bus.subscriber_count().await, 1);
        }
        // Dropping the subscription closes the receiver end. The bus prunes it
        // on the next publish.
        bus.emit_event("test", Event::Pong { from: "x".into() })
            .await
            .unwrap();
        assert_eq!(bus.subscriber_count().await, 0);
    }

    #[tokio::test]
    async fn envelope_carries_provenance() {
        let bus = MessageBus::new();
        let mut sub = bus.subscribe().await;

        bus.emit_event(
            "kernel",
            Event::ModuleStarted {
                module_id: "echo".into(),
            },
        )
        .await
        .unwrap();

        let env = sub.receiver.recv().await.unwrap();
        assert_eq!(env.source, "kernel");
        assert!(env.id != Uuid::nil());
        match env.message {
            Message::Event(Event::ModuleStarted { module_id }) => {
                assert_eq!(module_id, "echo");
            }
            other => panic!("unexpected message: {other:?}"),
        }
    }

    #[tokio::test]
    async fn correlation_id_round_trips() {
        let bus = MessageBus::new();
        let mut sub = bus.subscribe().await;
        let cid = Uuid::new_v4();

        let env = Envelope::new("test", Message::Command(Command::Ping)).with_correlation_id(cid);
        bus.publish(env).await.unwrap();

        let received = sub.receiver.recv().await.unwrap();
        assert_eq!(received.correlation_id, Some(cid));
    }

    // -------------------------------------------------------------------
    // Capability ACL tests (R-19)
    // -------------------------------------------------------------------

    #[tokio::test]
    async fn granted_capability_allows_publish() {
        let bus = MessageBus::new();
        let mut sub = bus.subscribe().await;

        let cap = Capability::new("browser:navigate");
        bus.grant_capability(cap.clone()).await;

        let env = Envelope::new("browser-module", Message::Command(Command::Ping));
        bus.publish_with_capability(env, &cap).await.unwrap();

        let recv = sub.receiver.recv().await.unwrap();
        assert!(matches!(recv.message, Message::Command(Command::Ping)));
    }

    #[tokio::test]
    async fn unganted_capability_returns_denied() {
        let bus = MessageBus::new();
        let cap = Capability::new("llm:complete");
        // Not granted — no call to grant_capability.
        let env = Envelope::new("llm-module", Message::Command(Command::Ping));
        let err = bus.publish_with_capability(env, &cap).await.unwrap_err();
        assert!(
            matches!(err, KernelError::Denied { .. }),
            "expected Denied, got {err}"
        );
    }

    #[tokio::test]
    async fn revoked_capability_is_denied() {
        let bus = MessageBus::new();
        let cap = Capability::new("mirror:sync");
        bus.grant_capability(cap.clone()).await;
        bus.revoke_capability(&cap).await;

        let env = Envelope::new("mirror-module", Message::Command(Command::Ping));
        let err = bus.publish_with_capability(env, &cap).await.unwrap_err();
        assert!(matches!(err, KernelError::Denied { .. }));
    }

    #[tokio::test]
    async fn unguarded_publish_bypasses_acl() {
        // The plain publish() must still work regardless of grant set.
        let bus = MessageBus::new();
        let mut sub = bus.subscribe().await;
        bus.send_command("kernel-internal", Command::Ping)
            .await
            .unwrap();
        let recv = sub.receiver.recv().await.unwrap();
        assert!(matches!(recv.message, Message::Command(Command::Ping)));
    }
}