rustclamp_core/lib.rs
1//! Minimal shared contracts for Clamp applications.
2
3#![forbid(unsafe_code)]
4#![deny(missing_docs)]
5
6use std::time::SystemTime;
7
8mod reference;
9
10pub use reference::{ParseReferenceError, Reference};
11
12/// A stable identifier for an application architecture blueprint.
13#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
14pub struct ApplicationId(&'static str);
15
16impl ApplicationId {
17 /// Creates an identifier from a stable, source-defined name.
18 pub const fn new(name: &'static str) -> Self {
19 Self(name)
20 }
21
22 /// Returns the stable application name.
23 pub const fn as_str(self) -> &'static str {
24 self.0
25 }
26}
27
28/// A stable identifier for one runnable application projection.
29#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
30pub struct ProcessId(&'static str);
31
32impl ProcessId {
33 /// Creates an identifier from a stable, source-defined name.
34 pub const fn new(name: &'static str) -> Self {
35 Self(name)
36 }
37
38 /// Returns the stable process name.
39 pub const fn as_str(self) -> &'static str {
40 self.0
41 }
42}
43
44/// A stable identifier for a process execution root.
45#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
46pub struct ExecutionId(&'static str);
47
48impl ExecutionId {
49 /// Creates an identifier from a stable, source-defined name.
50 pub const fn new(name: &'static str) -> Self {
51 Self(name)
52 }
53
54 /// Returns the stable execution name.
55 pub const fn as_str(self) -> &'static str {
56 self.0
57 }
58}
59
60/// A stable identifier for a declared application module.
61#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
62pub struct ModuleId(&'static str);
63
64impl ModuleId {
65 /// Creates an identifier from a stable, source-defined name.
66 pub const fn new(name: &'static str) -> Self {
67 Self(name)
68 }
69
70 /// Returns the stable module name.
71 pub const fn as_str(self) -> &'static str {
72 self.0
73 }
74}
75
76/// A stable identifier for a capability contract.
77#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
78pub struct CapabilityId(&'static str);
79
80impl CapabilityId {
81 /// Creates an identifier from a stable, source-defined name.
82 pub const fn new(name: &'static str) -> Self {
83 Self(name)
84 }
85
86 /// Returns the stable capability name.
87 pub const fn as_str(self) -> &'static str {
88 self.0
89 }
90}
91
92/// A stable identifier for a qualifier that distinguishes capability instances.
93#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
94pub struct QualifierId(&'static str);
95
96impl QualifierId {
97 /// Creates an identifier from a stable, source-defined name.
98 pub const fn new(name: &'static str) -> Self {
99 Self(name)
100 }
101
102 /// Returns the stable qualifier name.
103 pub const fn as_str(self) -> &'static str {
104 self.0
105 }
106}
107
108/// A stable identifier for a composition-time contribution kind.
109#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
110pub struct ContributionId(&'static str);
111
112impl ContributionId {
113 /// Creates an identifier from a stable, source-defined name.
114 pub const fn new(name: &'static str) -> Self {
115 Self(name)
116 }
117
118 /// Returns the stable contribution name.
119 pub const fn as_str(self) -> &'static str {
120 self.0
121 }
122}
123
124/// A stable identifier for a domain-specific contribution target.
125#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
126pub struct ContributionTargetId(&'static str);
127
128impl ContributionTargetId {
129 /// Creates an identifier from a stable, source-defined name.
130 pub const fn new(name: &'static str) -> Self {
131 Self(name)
132 }
133
134 /// Returns the stable target name.
135 pub const fn as_str(self) -> &'static str {
136 self.0
137 }
138}
139
140/// Gives a typed qualifier a stable semantic identity.
141pub trait Qualifier {
142 /// Stable semantic identifier; not a display label.
143 const ID: QualifierId;
144}
145
146/// Associates a capability marker with its value type and stable identity.
147pub trait Capability {
148 /// The typed value that satisfies this capability.
149 type Value: ?Sized;
150
151 /// Stable semantic identifier; not a display label.
152 const ID: CapabilityId;
153}
154
155/// Identifies a module that can participate in additive architecture contracts.
156///
157/// This contract describes module identity only. It does not impose a
158/// constructor, lifecycle, health, or shutdown API.
159pub trait Module {
160 /// Stable semantic identifier; not a display label.
161 const ID: ModuleId;
162}
163
164/// Identity available to a lifecycle participant without exposing a runtime.
165#[derive(Clone, Copy, Debug, Eq, PartialEq)]
166pub struct LifecycleContext {
167 application: ApplicationId,
168 process: ProcessId,
169}
170
171impl LifecycleContext {
172 /// Creates a context for one application's process lifecycle.
173 pub const fn new(application: ApplicationId, process: ProcessId) -> Self {
174 Self {
175 application,
176 process,
177 }
178 }
179
180 /// Returns the application whose lifecycle is being coordinated.
181 pub const fn application(self) -> ApplicationId {
182 self.application
183 }
184
185 /// Returns the process whose lifecycle is being coordinated.
186 pub const fn process(self) -> ProcessId {
187 self.process
188 }
189}
190
191/// Opts a module into resource preparation before its process starts.
192pub trait Initialize: Module {
193 /// An implementation-defined preparation error.
194 type Error;
195
196 /// Prepares resources; this does not mean the module is accepting work.
197 fn initialize(&mut self, context: &LifecycleContext) -> Result<(), Self::Error>;
198}
199
200/// Opts a module into activation after initialization succeeds.
201pub trait Start: Module {
202 /// An implementation-defined activation error.
203 type Error;
204
205 /// Activates the module for its selected process.
206 fn start(&mut self, context: &LifecycleContext) -> Result<(), Self::Error>;
207}
208
209/// Opts a module into the readiness check after activation.
210pub trait Ready: Module {
211 /// An implementation-defined readiness error.
212 type Error;
213
214 /// Confirms this participant is ready; process policy decides global readiness.
215 fn ready(&mut self, context: &LifecycleContext) -> Result<(), Self::Error>;
216}
217
218/// Opts a module into graceful shutdown before it is stopped.
219pub trait Drain: Module {
220 /// An implementation-defined drain error.
221 type Error;
222
223 /// Finishes accepted work after process admission has closed.
224 fn drain(&mut self, context: &LifecycleContext) -> Result<(), Self::Error>;
225}
226
227/// Opts a module into teardown after draining.
228pub trait Stop: Module {
229 /// An implementation-defined teardown error.
230 type Error;
231
232 /// Releases resources or execution mechanisms owned by this participant.
233 fn stop(&mut self, context: &LifecycleContext) -> Result<(), Self::Error>;
234}
235
236/// Declares that a module requires one capability.
237///
238/// The default leaves provider selection to composition validation. A module
239/// may name a preferred provider explicitly when its architecture requires it.
240pub trait Requires<C: Capability>: Module {
241 /// Explicit provider identity, or `None` when resolution should be unique.
242 const SELECTED_PROVIDER: Option<ModuleId> = None;
243}
244
245/// Declares and exposes one capability provided by a module.
246pub trait Provides<C: Capability>: Module {
247 /// Returns the value satisfying this capability requirement.
248 fn provided_value(&self) -> &C::Value;
249}
250
251/// Describes a composition-time declaration consumed by a domain target.
252pub trait Contribution {
253 /// Stable semantic identity; not a display label.
254 const ID: ContributionId;
255
256 /// Whether dropping this declaration without a consumer is an error.
257 const REQUIRED: bool = true;
258}
259
260/// A domain-owned compiler from declarations to a runtime representation.
261///
262/// The target owns validation, conflict rules, ordering, and its empty-input
263/// behavior. Core does not prescribe any of those semantics.
264pub trait ContributionTarget {
265 /// The declaration type accepted by this target.
266 type Contribution: Contribution;
267
268 /// The representation retained for runtime execution.
269 type Runtime;
270
271 /// A structured, target-specific assembly error.
272 type Error;
273
274 /// Stable semantic identity; not a display label.
275 const ID: ContributionTargetId;
276
277 /// Validates, orders, and compiles declarations into the runtime form.
278 fn build(
279 &self,
280 contributions: &[(ModuleId, Self::Contribution)],
281 ) -> Result<Self::Runtime, Self::Error>;
282}
283
284/// A source of wall-clock time required by application behavior.
285///
286/// Implementations may be production clocks, deterministic test clocks, or
287/// adapters around an application-owned time source. The contract does not
288/// prescribe ownership, synchronization, or a runtime.
289///
290/// Clocks are `Send + Sync`, so a resolved `&dyn Clock` can be shared with
291/// worker threads, spawned tasks and scheduled jobs.
292pub trait Clock: Send + Sync {
293 /// Returns the current wall-clock time.
294 fn now(&self) -> SystemTime;
295}
296
297/// The operating system's wall clock ([`SystemTime::now`]).
298#[derive(Clone, Copy, Debug, Default)]
299pub struct SystemClock;
300
301impl Clock for SystemClock {
302 fn now(&self) -> SystemTime {
303 SystemTime::now()
304 }
305}
306
307/// A clock that only moves when told to: for tests and simulations.
308///
309/// Set and advance it through a shared reference while the code under test
310/// reads it through `&dyn Clock`.
311#[derive(Debug)]
312pub struct ManualClock(std::sync::Mutex<SystemTime>);
313
314impl ManualClock {
315 /// Creates a clock stopped at `now`.
316 pub const fn new(now: SystemTime) -> Self {
317 Self(std::sync::Mutex::new(now))
318 }
319
320 /// Moves the clock to `now` (backwards too).
321 pub fn set(&self, now: SystemTime) {
322 *self.lock() = now;
323 }
324
325 /// Moves the clock forward by `by`.
326 ///
327 /// # Panics
328 ///
329 /// If the result overflows `SystemTime`.
330 pub fn advance(&self, by: std::time::Duration) {
331 let mut now = self.lock();
332 *now = now
333 .checked_add(by)
334 .expect("ManualClock advanced past SystemTime range");
335 }
336
337 fn lock(&self) -> std::sync::MutexGuard<'_, SystemTime> {
338 self.0
339 .lock()
340 .unwrap_or_else(std::sync::PoisonError::into_inner)
341 }
342}
343
344impl Clock for ManualClock {
345 fn now(&self) -> SystemTime {
346 *self.lock()
347 }
348}
349
350/// Marker type that identifies the [`Clock`] capability to the Kernel.
351#[derive(Clone, Copy, Debug, Default)]
352pub struct ClockCapability;
353
354impl Capability for ClockCapability {
355 type Value = dyn Clock;
356
357 const ID: CapabilityId = CapabilityId::new("rustclamp.core.clock");
358}