proxima-core 0.1.0

Foundation primitives for the proxima workspace: error, ring, arena, time, markers
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
//! Foundation primitives for the proxima workspace — the layer everything else
//! is built out of, and the one crate that cannot itself be expressed as a pipe
//! (`proxima_primitives::Pipe` is defined one level up, on top of this).
//!
//! Every module carries the finest tier it can reach, so a bare-metal consumer
//! takes a subset rather than a fork:
//!
//! - **unconditional, down to no_std + no-alloc:** [`arch`], [`datagram_batch`],
//!   [`factory::Named`], [`markers`], [`per_core`], [`ring`], [`time`]. The
//!   buffered ones ([`datagram_batch`], [`per_core`], [`ring`]) carry an inline
//!   fixed-cap form sized by `build.rs` alongside the heap form behind `alloc`.
//!   CI builds both `--features alloc` and bare `--no-default-features` for
//!   `thumbv7m-none-eabi` (`scripts/thumbv7m-cliff-gate.sh`).
//! - **`alloc`:** [`arena`], [`batch`]
//! - **`std`:** `buffer`, `signal`, and the [`factory`] registry (`registry`
//!   / `config`) and `live`, which ride their own default-off features
//! - **orthogonal gates:** `io` (`io-async`) is no-alloc for the traits and
//!   `alloc` for `Prepend`; `park` (`park`) is no_std but needs an OS futex;
//!   [`histogram`] needs 64-bit atomics, so it is absent on cortex-m.
//!
//! [`ProximaError`] is the shared error type. It carries two surfaces: the
//! `String`-payload variants (`Decode(String)`, `Config(String)`, …) that most
//! of the workspace still constructs, and the typed `*Kind` variants
//! (`DecodeKind(DecodeError)`, `ConfigKind(ConfigError)`, …) that let a caller
//! match on the failure without parsing a message. **Typed is the convention**;
//! this crate constructs only typed kinds. The `String` variants remain until
//! their owning crates migrate, and render identically either way.
//!
//! Typed sources are erased through
//! `Box<dyn core::error::Error + Send + Sync + 'static>` so the sub-enum surface
//! is uniform regardless of whether the underlying source is `std::io::Error`,
//! `serde_json::Error`, `FromUtf8Error`, … `core::error::Error` is stable since
//! Rust 1.81 and the workspace is edition 2024 (1.85+), so it is always
//! available.

#![cfg_attr(not(feature = "std"), no_std)]

#[cfg(feature = "alloc")]
extern crate alloc;

#[cfg(feature = "alloc")]
pub mod accept_rule;
pub mod arch;
#[cfg(feature = "alloc")]
pub mod arena;
pub mod kv_decision;
pub mod ring;
#[cfg(feature = "alloc")]
pub mod serving_state;
// per-worker BytesMut reservoir; std-only (thread_local has no no_std
// analog). folded in from the former proxima-lib satellite crate.
#[cfg(feature = "alloc")]
pub mod batch;
#[cfg(feature = "std")]
pub mod buffer;
pub mod datagram_batch;
pub mod factory;
// histogram accumulates count/sum/buckets in AtomicU64; targets without
// 64-bit atomics (cortex-m thumbv7m/em) can't back it lock-free, so gate it out
// there — no_std consumers with 64-bit atomics still get it.
#[cfg(target_has_atomic = "64")]
pub mod histogram;
#[cfg(feature = "io-async")]
pub mod io;
pub mod markers;
#[cfg(feature = "park")]
pub mod park;
pub mod per_core;
// std tier only for now: the waiter store is a std Mutex. the no_std
// tier needs a bounded waiter table over SlotPark — deliberate follow-on.
#[cfg(feature = "std")]
pub mod signal;
// runtime-agnostic timer primitives (folded from the former proxima-time
// crate). Unconditional: compiles at every tier, falling back to a
// panics-on-use driver when no `time-driver-*` feature/profile is active.
pub mod time;
// lock-free live-swappable cell (arc-swap); std-tier, opt-in via `live`.
#[cfg(feature = "live")]
pub mod live;

/// Build-time sizing constants emitted by `build.rs` from `proxima-core.toml`
/// (principle 12). Only the `no_std + no-alloc` tier is bounded by these; the
/// alloc tier grows dynamically.
pub mod sized {
    include!(concat!(env!("OUT_DIR"), "/proxima_core_sized.rs"));
}

#[cfg(feature = "registry")]
pub use factory::FactoryRegistry;
pub use factory::Named;
#[cfg(feature = "config")]
pub use factory::{Composition, Factory, FactorySpec};
#[cfg(feature = "alloc")]
pub use serving_state::{ServingFsmError, ServingState};

#[cfg(feature = "alloc")]
use alloc::boxed::Box;
#[cfg(feature = "alloc")]
use alloc::string::String;

use core::time::Duration;

use thiserror::Error;

/// Erased source for typed sub-enum variants. Concrete error types
/// (`std::io::Error`, `serde_json::Error`, `FromUtf8Error`, `ParseIntError`,
/// etc.) all impl `core::error::Error` and box cleanly through this alias.
#[cfg(feature = "alloc")]
pub type ErrorSource = Box<dyn core::error::Error + Send + Sync + 'static>;

// ---------------------------------------------------------------------------
// Typed sub-enums (alongside the legacy String variants)
// ---------------------------------------------------------------------------

/// Decode failure during wire / format parsing.
#[derive(Debug, Error)]
#[cfg(feature = "alloc")]
pub enum DecodeError {
    #[error("missing header terminator")]
    MissingHeaderTerminator,
    #[error("empty status line")]
    EmptyStatusLine,
    #[error("malformed status line: {raw}")]
    MalformedStatusLine { raw: String },
    #[error("chunked: size CRLF missing")]
    ChunkedSizeMissing,
    #[error("chunked: payload short")]
    ChunkedPayloadShort,
    #[error("not utf-8 ({context}): {source}")]
    NotUtf8 {
        context: &'static str,
        source: ErrorSource,
    },
    #[error("parse {context}: {source}")]
    Parse {
        context: &'static str,
        source: ErrorSource,
    },
    #[error("missing required field: {field}")]
    MissingField { field: &'static str },
    #[error("decode ({context}): {source}")]
    Other {
        context: &'static str,
        source: ErrorSource,
    },
}

/// Encode failure during wire / format serialization.
#[derive(Debug, Error)]
#[cfg(feature = "alloc")]
pub enum EncodeError {
    #[error("json encode: {source}")]
    Json { source: ErrorSource },
    #[error("format convert ({context}): {source}")]
    FormatConvert {
        context: &'static str,
        source: ErrorSource,
    },
    #[error("render ({context}): {source}")]
    Render {
        context: &'static str,
        source: ErrorSource,
    },
    #[error("base64: {source}")]
    Base64 { source: ErrorSource },
    #[error("requires base64 string input")]
    RequiresBase64Input,
    #[error("encode ({context}): {source}")]
    Other {
        context: &'static str,
        source: ErrorSource,
    },
}

/// Upstream / I/O-side failure.
#[derive(Debug, Error)]
#[cfg(feature = "alloc")]
pub enum UpstreamError {
    #[error("io ({operation}): {source}")]
    Io {
        operation: &'static str,
        source: ErrorSource,
    },
    #[error("upstream returned status {status}")]
    BadStatus { status: u16 },
    #[error("upstream cancelled")]
    Cancelled,
    #[error("protocol ({context}): {source}")]
    Protocol {
        context: &'static str,
        source: ErrorSource,
    },
    #[error("connect ({context}): {source}")]
    Connect {
        context: &'static str,
        source: ErrorSource,
    },
    #[error("upstream ({context}): {source}")]
    Other {
        context: &'static str,
        source: ErrorSource,
    },
}

/// Configuration / spec error.
#[derive(Debug, Error)]
#[cfg(feature = "alloc")]
pub enum ConfigError {
    #[error("{component}: requires field '{field}'")]
    RequiredField {
        component: &'static str,
        field: &'static str,
    },
    #[error("{component}: requires an inner pipe")]
    MissingInnerPipe { component: &'static str },
    #[error("no upstreams configured")]
    NoUpstreams,
    #[error("parse ({context}): {source}")]
    Parse {
        context: &'static str,
        source: ErrorSource,
    },
    #[error("spawn failed ({context}): {source}")]
    SpawnFailed {
        context: &'static str,
        source: ErrorSource,
    },
    #[error("config ({context}): {source}")]
    Other {
        context: &'static str,
        source: ErrorSource,
    },
}

/// Body-stream / worker-side failure.
#[derive(Debug, Error)]
#[cfg(feature = "alloc")]
pub enum BodyError {
    #[error("body cancelled")]
    Cancelled,
    #[error("worker dropped sender ({context})")]
    WorkerDropped { context: &'static str },
    #[error("worker panicked ({context})")]
    WorkerPanic { context: &'static str },
    #[error("serialize ({context}): {source}")]
    Serialize {
        context: &'static str,
        source: ErrorSource,
    },
    #[error("body ({context}): {source}")]
    Other {
        context: &'static str,
        source: ErrorSource,
    },
}

/// Resource-not-found error.
#[derive(Debug, Error)]
#[cfg(feature = "alloc")]
pub enum NotFoundError {
    #[error("no pipe registered as '{name}'")]
    Pipe { name: String },
    #[error("{kind} '{name}' not found")]
    Resource { kind: &'static str, name: String },
}

/// Registry-level error (factories, listen protocols, codecs).
#[derive(Debug, Error)]
#[cfg(feature = "alloc")]
pub enum RegistryError {
    #[error("no {kind} named '{name}'")]
    NotRegistered { kind: &'static str, name: String },
    #[error("{kind} '{name}' already registered")]
    AlreadyRegistered { kind: &'static str, name: String },
}

/// Recording / replay sink-side error.
#[derive(Debug, Error)]
#[cfg(feature = "alloc")]
pub enum RecordError {
    #[error("recording io ({operation}): {source}")]
    Io {
        operation: &'static str,
        source: ErrorSource,
    },
    #[error("recording codec ({operation}): {source}")]
    Codec {
        operation: &'static str,
        source: ErrorSource,
    },
    #[error("recording frame exceeds u32::MAX bytes")]
    FrameTooLarge,
    #[error("recording version mismatch: expected {expected}, got {got}")]
    VersionMismatch { expected: u8, got: u8 },
    #[error("recording buffer full at capacity {capacity}")]
    BufferFull { capacity: usize },
}

// ---------------------------------------------------------------------------
// ProximaError — legacy String-payload variants + new typed variants
// ---------------------------------------------------------------------------

#[derive(Debug, Error)]
pub enum ProximaError {
    /// Legacy String-payload variants. Construct via `ProximaError::Decode(...)`
    /// today; migrate to `ProximaError::DecodeKind(DecodeError::...)` over time.
    #[error("upstream error: {0}")]
    #[cfg(feature = "alloc")]
    Upstream(String),

    #[error("timeout after {0:?}")]
    Timeout(Duration),

    #[error("rate limited")]
    RateLimited,

    #[error("no upstream had data")]
    NoData,

    #[error("config: {0}")]
    #[cfg(feature = "alloc")]
    Config(String),

    #[error("io: {0}")]
    #[cfg(feature = "std")]
    Io(#[from] std::io::Error),

    #[error("decode: {0}")]
    #[cfg(feature = "alloc")]
    Decode(String),

    #[error("encode: {0}")]
    #[cfg(feature = "alloc")]
    Encode(String),

    #[error("body stream: {0}")]
    #[cfg(feature = "alloc")]
    Body(String),

    #[error("not found: {0}")]
    #[cfg(feature = "alloc")]
    NotFound(String),

    /// A deliberate refusal, not a failure — the payload is the response
    /// body verbatim (e.g. a `filter` predicate's `RejectMode::Drop`, which
    /// renders as 403 with this payload as the body).
    #[error("forbidden: {0}")]
    #[cfg(feature = "alloc")]
    Forbidden(String),

    #[error("registry: {0}")]
    #[cfg(feature = "alloc")]
    Registry(String),

    #[error("retries exhausted after {attempts} attempts: {last}")]
    #[cfg(feature = "alloc")]
    RetriesExhausted { attempts: usize, last: String },

    #[error("recording: {0}")]
    #[cfg(feature = "alloc")]
    Record(String),

    #[error("replay miss: {fingerprint}")]
    #[cfg(feature = "alloc")]
    ReplayMiss { fingerprint: String },

    /// Typed payload variants. Carry sub-enum kinds with concrete fields
    /// (e.g. `Decode(format!("missing field 'name'"))` becomes
    /// `DecodeKind(DecodeError::MissingField { field: "name" })`). Match
    /// callers can now inspect the kind without parsing strings.
    #[error("decode: {0}")]
    #[cfg(feature = "alloc")]
    DecodeKind(#[from] DecodeError),

    #[error("encode: {0}")]
    #[cfg(feature = "alloc")]
    EncodeKind(#[from] EncodeError),

    #[error("upstream: {0}")]
    #[cfg(feature = "alloc")]
    UpstreamKind(#[from] UpstreamError),

    #[error("config: {0}")]
    #[cfg(feature = "alloc")]
    ConfigKind(#[from] ConfigError),

    #[error("body: {0}")]
    #[cfg(feature = "alloc")]
    BodyKind(#[from] BodyError),

    #[error("not found: {0}")]
    #[cfg(feature = "alloc")]
    NotFoundKind(#[from] NotFoundError),

    #[error("registry: {0}")]
    #[cfg(feature = "alloc")]
    RegistryKind(#[from] RegistryError),

    #[error("recording: {0}")]
    #[cfg(feature = "alloc")]
    RecordKind(#[from] RecordError),
}

impl ProximaError {
    /// Whether this error class is worth retrying. Covers both legacy and
    /// typed variants — the heuristic matches `Upstream*` (transient I/O),
    /// `Timeout`, `Body*` (worker churn), and (under std) `Io`.
    #[must_use]
    pub fn is_retryable(&self) -> bool {
        match self {
            Self::Timeout(_) => true,
            Self::RateLimited => false,
            #[cfg(feature = "alloc")]
            Self::Upstream(_) | Self::Body(_) => true,
            #[cfg(feature = "std")]
            Self::Io(_) => true,
            #[cfg(feature = "alloc")]
            Self::UpstreamKind(kind) => !matches!(kind, UpstreamError::BadStatus { .. }),
            #[cfg(feature = "alloc")]
            Self::BodyKind(kind) => matches!(
                kind,
                BodyError::WorkerDropped { .. } | BodyError::WorkerPanic { .. }
            ),
            _ => false,
        }
    }
}

pub type ProximaResult<T> = Result<T, ProximaError>;

#[cfg(test)]
#[cfg(feature = "alloc")]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use alloc::format;

    #[test]
    fn timeout_is_retryable() {
        assert!(ProximaError::Timeout(Duration::from_secs(1)).is_retryable());
    }

    #[test]
    fn rate_limited_is_not_retryable() {
        assert!(!ProximaError::RateLimited.is_retryable());
    }

    #[test]
    fn legacy_upstream_is_retryable() {
        assert!(ProximaError::Upstream("transient".into()).is_retryable());
    }

    #[test]
    fn typed_upstream_io_is_retryable_but_bad_status_is_not() {
        let io = UpstreamError::Io {
            operation: "read",
            source: Box::new(LightweightTestError("transient")),
        };
        assert!(ProximaError::from(io).is_retryable());

        let bad = UpstreamError::BadStatus { status: 500 };
        assert!(!ProximaError::from(bad).is_retryable());
    }

    #[test]
    fn decode_kind_carries_typed_payload() {
        let err = DecodeError::MissingField {
            field: "pipeline_id",
        };
        let display = format!("{}", err);
        assert!(display.contains("pipeline_id"));
    }

    #[test]
    fn from_decode_error_to_proxima_error_via_from_impl() {
        let err: ProximaError = DecodeError::EmptyStatusLine.into();
        assert!(matches!(
            err,
            ProximaError::DecodeKind(DecodeError::EmptyStatusLine)
        ));
    }

    #[test]
    fn config_required_field_renders_component_and_field() {
        let err = ConfigError::RequiredField {
            component: "auth",
            field: "allow",
        };
        let display = format!("{}", err);
        assert!(display.contains("auth"));
        assert!(display.contains("allow"));
    }

    #[test]
    fn registry_not_registered_uses_kind_and_name() {
        let err = RegistryError::NotRegistered {
            kind: "codec factory",
            name: "json".into(),
        };
        let display = format!("{}", err);
        assert!(display.contains("codec factory"));
        assert!(display.contains("json"));
    }

    #[test]
    fn record_version_mismatch_carries_numbers() {
        let err = RecordError::VersionMismatch {
            expected: 3,
            got: 2,
        };
        let display = format!("{}", err);
        assert!(display.contains('3'));
        assert!(display.contains('2'));
    }

    #[derive(Debug)]
    struct LightweightTestError(&'static str);
    impl core::fmt::Display for LightweightTestError {
        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            f.write_str(self.0)
        }
    }
    impl core::error::Error for LightweightTestError {}
}