v0.3.6-pre.002

This commit is contained in:
2026-09-01 10:45:39 +02:00
parent ecfc30a94b
commit a25d8dd55a
17 changed files with 1087 additions and 18 deletions

View File

@@ -0,0 +1,44 @@
// file: crates/ksp-job-api/src/cancellation.rs
// version: 1
/// Runtime-neutral cloneable token carrying cooperative cancellation intent.
#[derive(Clone)]
pub struct JobCancellationToken {
requested: std::sync::Arc<std::sync::atomic::AtomicBool>,
}
impl JobCancellationToken {
/// Creates a token with no cancellation request.
#[must_use]
pub fn new() -> Self {
return Self { requested: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)) };
}
/// Requests cancellation and returns `true` only for the first request shared by all clones.
#[must_use]
pub fn cancel(&self) -> bool {
return !self.requested.swap(true, std::sync::atomic::Ordering::AcqRel);
}
/// Reports whether cancellation has been requested through any clone.
#[must_use]
pub fn is_cancellation_requested(&self) -> bool {
return self.requested.load(std::sync::atomic::Ordering::Acquire);
}
}
impl std::default::Default for JobCancellationToken {
fn default() -> Self {
return Self::new();
}
}
impl std::fmt::Debug for JobCancellationToken {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
return formatter.debug_struct("JobCancellationToken").field("cancellation_requested", &self.is_cancellation_requested()).finish();
}
}
#[cfg(test)]
#[path = "../unit_tests/cancellation.rs"]
mod tests;

View File

@@ -0,0 +1,9 @@
// file: crates/ksp-job-api/src/error.rs
// version: 1
/// Error code used when a Job identifier violates its bounded safe-code contract.
pub const ERROR_CODE_JOB_ID_INVALID: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("job_api", "job_id_invalid");
/// Error code used when a Job kind code violates its bounded safe-code contract.
pub const ERROR_CODE_JOB_KIND_INVALID: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("job_api", "job_kind_invalid");
/// Error code used when a requested Job lifecycle transition is not allowed.
pub const ERROR_CODE_JOB_TRANSITION_INVALID: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("job_api", "job_transition_invalid");

View File

@@ -0,0 +1,76 @@
// file: crates/ksp-job-api/src/identity.rs
// version: 1
/// Maximum UTF-8 byte length admitted for one Job identifier.
pub const MAX_JOB_ID_BYTES: usize = 128;
/// Maximum UTF-8 byte length admitted for one Job kind code.
pub const MAX_JOB_KIND_CODE_BYTES: usize = 128;
/// Bounded caller-supplied identity of one logical Job and its controlled resumptions.
#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct JobId(std::string::String);
impl JobId {
/// Creates one non-empty Job identifier using the KSP safe-code alphabet.
pub fn new(value: impl std::convert::Into<std::string::String>) -> crate::Result<Self> {
let value = value.into();
if !valid_job_code(value.as_str(), crate::MAX_JOB_ID_BYTES) {
return std::result::Result::Err(identity_error(crate::ERROR_CODE_JOB_ID_INVALID, "job_id"));
}
return std::result::Result::Ok(Self(value));
}
/// Returns the validated Job identifier.
#[must_use]
pub fn as_str(&self) -> &str {
return self.0.as_str();
}
}
impl std::fmt::Debug for JobId {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
return formatter.write_str("JobId(..)");
}
}
/// Bounded stable code identifying one concrete family of Jobs.
#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct JobKindCode(std::string::String);
impl JobKindCode {
/// Creates one non-empty Job kind using the KSP safe-code alphabet.
pub fn new(value: impl std::convert::Into<std::string::String>) -> crate::Result<Self> {
let value = value.into();
if !valid_job_code(value.as_str(), crate::MAX_JOB_KIND_CODE_BYTES) {
return std::result::Result::Err(identity_error(crate::ERROR_CODE_JOB_KIND_INVALID, "job_kind"));
}
return std::result::Result::Ok(Self(value));
}
/// Returns the validated stable Job kind code.
#[must_use]
pub fn as_str(&self) -> &str {
return self.0.as_str();
}
}
impl std::fmt::Debug for JobKindCode {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
return formatter.debug_tuple("JobKindCode").field(&self.0).finish();
}
}
fn identity_error(code: crate::ErrorCode, field: &'static str) -> crate::Error {
return crate::Error::new(code, "invalid bounded Job identity").with_context("field", field);
}
fn valid_job_code(value: &str, maximum_len: usize) -> bool {
if value.is_empty() || value.len() > maximum_len {
return false;
}
return value.bytes().all(|byte| return byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.' | b':'));
}
#[cfg(test)]
#[path = "../unit_tests/identity.rs"]
mod tests;

View File

@@ -0,0 +1,49 @@
// file: crates/ksp-job-api/src/lib.rs
// version: 1
#![warn(missing_docs)]
#![deny(unreachable_pub)]
#![forbid(unsafe_code)]
//! Passive runtime-neutral lifecycle contracts for bounded KSP Jobs.
//!
//! This foundation owns validated Job identity, explicit lifecycle transitions
//! and cooperative cancellation intent. Notification delivery, concrete Job
//! behavior, runtime spawning, Transport, Store and Worker contracts remain
//! outside this crate.
mod cancellation;
mod error;
mod identity;
mod lifecycle;
/// Runtime-neutral cloneable token carrying cooperative cancellation intent.
pub use self::cancellation::JobCancellationToken;
/// Error code used when a Job identifier violates its bounded safe-code contract.
pub use self::error::ERROR_CODE_JOB_ID_INVALID;
/// Error code used when a Job kind code violates its bounded safe-code contract.
pub use self::error::ERROR_CODE_JOB_KIND_INVALID;
/// Error code used when a requested Job lifecycle transition is not allowed.
pub use self::error::ERROR_CODE_JOB_TRANSITION_INVALID;
/// Bounded caller-supplied identity of one logical Job and its controlled resumptions.
pub use self::identity::JobId;
/// Bounded stable code identifying one concrete family of Jobs.
pub use self::identity::JobKindCode;
/// Maximum UTF-8 byte length admitted for one Job identifier.
pub use self::identity::MAX_JOB_ID_BYTES;
/// Maximum UTF-8 byte length admitted for one Job kind code.
pub use self::identity::MAX_JOB_KIND_CODE_BYTES;
/// Completion classification of a Job that reached its normal terminal state.
pub use self::lifecycle::JobCompletion;
/// Passive owner of one Job identity and its validated lifecycle state.
pub use self::lifecycle::JobLifecycle;
/// Current lifecycle state of one bounded Job.
pub use self::lifecycle::JobState;
/// Common KSP error type used by Job-facing contracts.
pub use ksp_core_lib::Error;
/// Stable structured code identifying a KSP error category and condition.
pub use ksp_core_lib::ErrorCode;
/// Structured contextual field attached to a KSP error.
pub use ksp_core_lib::ErrorContext;
/// Common KSP result alias using [`Error`].
pub use ksp_core_lib::Result;

View File

@@ -0,0 +1,168 @@
// file: crates/ksp-job-api/src/lifecycle.rs
// version: 1
/// Completion classification of a Job that reached its normal terminal state.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum JobCompletion {
/// Every selected candidate or unit of work reached a durable complete result.
Complete,
/// The Job terminated normally while retaining one or more explicitly observable gaps.
Partial,
}
impl JobCompletion {
/// Returns the stable safe code for this completion classification.
#[must_use]
pub const fn code(&self) -> &'static str {
return match self {
Self::Complete => "complete",
Self::Partial => "partial",
};
}
}
/// Current lifecycle state of one bounded Job.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum JobState {
/// The Job was admitted but has not started producing work.
Created,
/// The Job is actively producing or draining normal work.
Running,
/// Cancellation was observed and new work must no longer be admitted.
Cancelling,
/// The Job reached a normal terminal state with an explicit completion classification.
Completed(crate::JobCompletion),
/// The Job reached its cooperative cancellation terminal state.
Cancelled,
/// The Job reached a terminal failure state.
Failed,
}
impl JobState {
/// Returns the stable safe lifecycle code without rendering Job data.
#[must_use]
pub const fn code(&self) -> &'static str {
return match self {
Self::Created => "created",
Self::Running => "running",
Self::Cancelling => "cancelling",
Self::Completed(_) => "completed",
Self::Cancelled => "cancelled",
Self::Failed => "failed",
};
}
/// Returns the normal completion classification when the state is [`Self::Completed`].
#[must_use]
pub const fn completion(&self) -> std::option::Option<crate::JobCompletion> {
return match self {
Self::Completed(completion) => std::option::Option::Some(*completion),
_ => std::option::Option::None,
};
}
/// Reports whether no later lifecycle transition is permitted.
#[must_use]
pub const fn is_terminal(&self) -> bool {
return matches!(self, Self::Completed(_) | Self::Cancelled | Self::Failed);
}
}
/// Passive owner of one Job identity and its validated lifecycle state.
#[derive(Eq, PartialEq)]
pub struct JobLifecycle {
id: crate::JobId,
kind: crate::JobKindCode,
state: crate::JobState,
}
impl JobLifecycle {
/// Creates one lifecycle in [`JobState::Created`] state.
#[must_use]
pub const fn new(id: crate::JobId, kind: crate::JobKindCode) -> Self {
return Self { id, kind, state: crate::JobState::Created };
}
/// Returns the logical Job identity.
#[must_use]
pub const fn id(&self) -> &crate::JobId {
return &self.id;
}
/// Returns the stable Job family code.
#[must_use]
pub const fn kind(&self) -> &crate::JobKindCode {
return &self.kind;
}
/// Returns the current lifecycle state.
#[must_use]
pub const fn state(&self) -> crate::JobState {
return self.state;
}
/// Transitions a newly created Job into its running state.
pub fn start(&mut self) -> crate::Result<()> {
return self.transition(crate::JobState::Running);
}
/// Records that a running Job observed cooperative cancellation intent.
pub fn mark_cancelling(&mut self) -> crate::Result<()> {
return self.transition(crate::JobState::Cancelling);
}
/// Completes a running or cancelling Job with its explicit normal outcome.
pub fn complete(&mut self, completion: crate::JobCompletion) -> crate::Result<()> {
return self.transition(crate::JobState::Completed(completion));
}
/// Marks a created or cancelling Job as cooperatively cancelled.
pub fn mark_cancelled(&mut self) -> crate::Result<()> {
return self.transition(crate::JobState::Cancelled);
}
/// Marks a running or cancelling Job as failed.
pub fn fail(&mut self) -> crate::Result<()> {
return self.transition(crate::JobState::Failed);
}
fn transition(&mut self, target: crate::JobState) -> crate::Result<()> {
if !allowed_transition(self.state, target) {
return std::result::Result::Err(transition_error(self.state, target));
}
self.state = target;
return std::result::Result::Ok(());
}
}
impl std::fmt::Debug for JobLifecycle {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
return formatter.debug_struct("JobLifecycle").field("id", &self.id).field("kind", &self.kind).field("state", &self.state).finish();
}
}
fn allowed_transition(source: crate::JobState, target: crate::JobState) -> bool {
return matches!(
(source, target),
(crate::JobState::Created, crate::JobState::Running)
| (crate::JobState::Created, crate::JobState::Cancelled)
| (crate::JobState::Running, crate::JobState::Cancelling)
| (crate::JobState::Running, crate::JobState::Completed(_))
| (crate::JobState::Running, crate::JobState::Failed)
| (crate::JobState::Cancelling, crate::JobState::Completed(_))
| (crate::JobState::Cancelling, crate::JobState::Cancelled)
| (crate::JobState::Cancelling, crate::JobState::Failed)
);
}
fn transition_error(source: crate::JobState, target: crate::JobState) -> crate::Error {
return crate::Error::new(crate::ERROR_CODE_JOB_TRANSITION_INVALID, "invalid Job lifecycle transition")
.with_context("source_state", source.code())
.with_context("target_state", target.code());
}
#[cfg(test)]
#[path = "../unit_tests/lifecycle.rs"]
mod tests;