⚠️ VeridianOS Kernel Documentation - This is low-level kernel code. All functions are unsafe unless explicitly marked otherwise. no_std

veridian_kernel/pkg/
async_types.rs

1//! Async Runtime Type Definitions for VeridianOS
2//!
3//! Defines the kernel-side contract for user-space async runtime primitives.
4//! These types describe task states, priorities, channels, and timers that the
5//! kernel's scheduler exposes to user-space async runtimes.
6//!
7//! TODO(user-space): The actual async runtime implementation requires
8//! user-space process execution. This module provides the type definitions
9//! that both kernel scheduler primitives and user-space runtimes agree upon.
10
11// User-space async runtime contract -- see TODO(user-space) above
12
13// ============================================================================
14// TaskState
15// ============================================================================
16
17/// Execution state of an asynchronous task.
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum TaskState {
20    /// Task has been created but is waiting to be scheduled.
21    Pending,
22    /// Task is currently executing on a CPU.
23    Running,
24    /// Task has finished successfully.
25    Completed,
26    /// Task was cancelled before completion.
27    Cancelled,
28    /// Task encountered an error during execution.
29    Failed,
30}
31
32impl TaskState {
33    /// Returns `true` if this state is terminal (the task will not run again).
34    pub fn is_terminal(&self) -> bool {
35        matches!(self, Self::Completed | Self::Cancelled | Self::Failed)
36    }
37}
38
39// ============================================================================
40// TaskPriority
41// ============================================================================
42
43/// Priority level for an asynchronous task.
44///
45/// Higher priority tasks are scheduled before lower priority tasks when
46/// contending for CPU time.
47#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
48pub enum TaskPriority {
49    /// Background tasks with the lowest scheduling priority.
50    Low,
51    /// Default priority for most tasks.
52    Normal,
53    /// Elevated priority for latency-sensitive tasks.
54    High,
55    /// Highest priority for time-critical operations.
56    Critical,
57}
58
59impl TaskPriority {
60    /// Return a numeric priority level (0 = Low, 3 = Critical).
61    pub fn as_u8(&self) -> u8 {
62        match self {
63            Self::Low => 0,
64            Self::Normal => 1,
65            Self::High => 2,
66            Self::Critical => 3,
67        }
68    }
69}
70
71// ============================================================================
72// TaskHandle
73// ============================================================================
74
75/// Handle to a scheduled asynchronous task.
76///
77/// Combines the task's unique identifier with its current state and priority,
78/// allowing the caller to inspect and manage task lifecycle.
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80pub struct TaskHandle {
81    /// Unique task identifier.
82    pub id: u64,
83    /// Current execution state.
84    pub state: TaskState,
85    /// Scheduling priority.
86    pub priority: TaskPriority,
87}
88
89impl TaskHandle {
90    /// Create a new task handle in the `Pending` state with `Normal` priority.
91    pub fn new(id: u64) -> Self {
92        Self {
93            id,
94            state: TaskState::Pending,
95            priority: TaskPriority::Normal,
96        }
97    }
98
99    /// Create a new task handle in the `Pending` state with the given priority.
100    pub fn with_priority(id: u64, priority: TaskPriority) -> Self {
101        Self {
102            id,
103            state: TaskState::Pending,
104            priority,
105        }
106    }
107
108    /// Returns `true` if the task has reached a terminal state.
109    pub fn is_done(&self) -> bool {
110        self.state.is_terminal()
111    }
112}
113
114// ============================================================================
115// ChannelConfig
116// ============================================================================
117
118/// Configuration for an asynchronous communication channel.
119#[derive(Debug, Clone, Copy, PartialEq, Eq)]
120pub struct ChannelConfig {
121    /// Maximum number of messages the channel can buffer.
122    pub capacity: usize,
123    /// Whether this channel supports broadcast (one-to-many) delivery.
124    pub allow_broadcast: bool,
125}
126
127impl ChannelConfig {
128    /// Create a point-to-point channel configuration with the given capacity.
129    pub fn new(capacity: usize) -> Self {
130        Self {
131            capacity,
132            allow_broadcast: false,
133        }
134    }
135
136    /// Create a broadcast-capable channel configuration with the given
137    /// capacity.
138    pub fn with_broadcast(capacity: usize) -> Self {
139        Self {
140            capacity,
141            allow_broadcast: true,
142        }
143    }
144}
145
146// ============================================================================
147// TimerMode / TimerSpec
148// ============================================================================
149
150/// Determines whether a timer fires once or repeatedly.
151#[derive(Debug, Clone, Copy, PartialEq, Eq)]
152pub enum TimerMode {
153    /// Fire once after the specified duration.
154    OneShot,
155    /// Fire repeatedly at the specified interval.
156    Repeating,
157}
158
159/// Specification for an asynchronous timer.
160#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161pub struct TimerSpec {
162    /// Duration or interval in milliseconds.
163    pub duration_ms: u64,
164    /// Whether this timer fires once or repeats.
165    pub mode: TimerMode,
166}
167
168impl TimerSpec {
169    /// Create a one-shot timer that fires after the given duration.
170    pub fn one_shot(duration_ms: u64) -> Self {
171        Self {
172            duration_ms,
173            mode: TimerMode::OneShot,
174        }
175    }
176
177    /// Create a repeating timer that fires at the given interval.
178    pub fn repeating(duration_ms: u64) -> Self {
179        Self {
180            duration_ms,
181            mode: TimerMode::Repeating,
182        }
183    }
184}
185
186// ============================================================================
187// AsyncRuntimeConfig
188// ============================================================================
189
190/// Configuration for a user-space async runtime instance.
191///
192/// Provides tuning parameters that the kernel uses when allocating scheduler
193/// resources for a process's async runtime.
194#[derive(Debug, Clone, Copy, PartialEq, Eq)]
195pub struct AsyncRuntimeConfig {
196    /// Maximum number of concurrent async tasks.
197    pub max_tasks: usize,
198    /// Default priority for newly spawned tasks.
199    pub default_priority: TaskPriority,
200    /// Timer resolution in milliseconds (minimum timer granularity).
201    pub timer_resolution_ms: u64,
202}
203
204impl AsyncRuntimeConfig {
205    /// Create a configuration with sensible defaults.
206    ///
207    /// Defaults: 256 max tasks, `Normal` priority, 1 ms timer resolution.
208    pub fn new() -> Self {
209        Self {
210            max_tasks: 256,
211            default_priority: TaskPriority::Normal,
212            timer_resolution_ms: 1,
213        }
214    }
215
216    /// Return a new configuration with the given maximum task count.
217    pub fn with_max_tasks(mut self, max_tasks: usize) -> Self {
218        self.max_tasks = max_tasks;
219        self
220    }
221}
222
223impl Default for AsyncRuntimeConfig {
224    fn default() -> Self {
225        Self::new()
226    }
227}