use std::{fmt, time::Duration};
use serde::{Deserialize, Serialize};
use stateknot_core::{
AgentAdmission, ArtifactRef, Checkpoint, CheckpointHead, CheckpointId, CompiledGraph,
DeliveryFence, Digest, DurableTimer, DurableTimerRecord, DurableWait, FencingEpoch,
InterruptRecord, InterruptRequest, JournalEvent, JournalExpectation, JournalHead,
JournalPayload, ModelInvocation, NodeAttempt, OutboxAttempt, OutboxAttemptCompletion,
OutboxAttemptStart, OutboxDelivery, OutboxDestinationRef, PendingNodeResult,
PendingNodeResultHead, QuarantineId, RunFence, RunId, RunLease, RunLifecycle, RunRevision,
RunTransition, SchedulerReservationId, SchedulerShardId, Superstep, TenantId, Timestamp,
ToolInvocation,
};
use crate::StoreError;
const SCHEDULER_FAIRNESS_POLICY_DIGEST_DOMAIN: &[u8] = b"stateknot.scheduler-fairness-policy.v1\0";
#[derive(Clone, Eq, PartialEq)]
pub struct ArtifactStorageLocator {
storage_namespace: Box<str>,
object_key: Box<str>,
object_version: Option<Box<str>>,
object_etag: Option<Box<str>>,
}
impl ArtifactStorageLocator {
pub const MAX_STORAGE_NAMESPACE_BYTES: usize = 128;
pub const MAX_OBJECT_KEY_BYTES: usize = 1024;
pub const MAX_OBJECT_VERSION_BYTES: usize = 1024;
pub const MAX_OBJECT_ETAG_BYTES: usize = 1024;
pub fn new(
storage_namespace: impl Into<String>,
object_key: impl Into<String>,
object_version: Option<String>,
object_etag: Option<String>,
) -> Result<Self, StoreError> {
let storage_namespace = storage_namespace.into();
let object_key = object_key.into();
validate_storage_namespace(&storage_namespace)?;
validate_object_key(&object_key)?;
let object_version =
validate_opaque_locator_value(object_version, Self::MAX_OBJECT_VERSION_BYTES)?;
let object_etag = validate_opaque_locator_value(object_etag, Self::MAX_OBJECT_ETAG_BYTES)?;
Ok(Self {
storage_namespace: storage_namespace.into_boxed_str(),
object_key: object_key.into_boxed_str(),
object_version,
object_etag,
})
}
#[must_use]
pub fn storage_namespace(&self) -> &str {
&self.storage_namespace
}
#[must_use]
pub fn object_key(&self) -> &str {
&self.object_key
}
#[must_use]
pub fn object_version(&self) -> Option<&str> {
self.object_version.as_deref()
}
#[must_use]
pub fn object_etag(&self) -> Option<&str> {
self.object_etag.as_deref()
}
}
impl fmt::Debug for ArtifactStorageLocator {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ArtifactStorageLocator")
.field("coordinates", &"<redacted>")
.field("has_object_version", &self.object_version.is_some())
.field("has_object_etag", &self.object_etag.is_some())
.finish_non_exhaustive()
}
}
#[derive(Clone, Eq, PartialEq)]
pub struct ArtifactRegistration {
registration_key: Digest,
artifact: ArtifactRef,
locator: ArtifactStorageLocator,
}
impl ArtifactRegistration {
#[must_use]
pub const fn new(
registration_key: Digest,
artifact: ArtifactRef,
locator: ArtifactStorageLocator,
) -> Self {
Self {
registration_key,
artifact,
locator,
}
}
#[must_use]
pub const fn registration_key(&self) -> Digest {
self.registration_key
}
#[must_use]
pub const fn artifact(&self) -> &ArtifactRef {
&self.artifact
}
#[must_use]
pub const fn locator(&self) -> &ArtifactStorageLocator {
&self.locator
}
}
impl fmt::Debug for ArtifactRegistration {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ArtifactRegistration")
.field("identity", self.artifact.identity())
.field("locator", &self.locator)
.finish_non_exhaustive()
}
}
#[derive(Clone, Eq, PartialEq)]
pub struct StoredArtifact {
pub(crate) registration: ArtifactRegistration,
pub(crate) registered_at: Timestamp,
}
impl StoredArtifact {
#[must_use]
pub const fn new(registration: ArtifactRegistration, registered_at: Timestamp) -> Self {
Self {
registration,
registered_at,
}
}
#[must_use]
pub const fn registration(&self) -> &ArtifactRegistration {
&self.registration
}
#[must_use]
pub const fn artifact(&self) -> &ArtifactRef {
self.registration.artifact()
}
#[must_use]
pub const fn locator(&self) -> &ArtifactStorageLocator {
self.registration.locator()
}
#[must_use]
pub const fn registered_at(&self) -> Timestamp {
self.registered_at
}
}
impl fmt::Debug for StoredArtifact {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("StoredArtifact")
.field("identity", self.artifact().identity())
.field("registered_at", &self.registered_at)
.field("locator", self.locator())
.finish_non_exhaustive()
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ArtifactRegistrationOutcome {
Registered(StoredArtifact),
Idempotent(StoredArtifact),
}
impl ArtifactRegistrationOutcome {
#[must_use]
pub const fn stored(&self) -> &StoredArtifact {
match self {
Self::Registered(stored) | Self::Idempotent(stored) => stored,
}
}
}
fn validate_storage_namespace(value: &str) -> Result<(), StoreError> {
if value.is_empty()
|| value.len() > ArtifactStorageLocator::MAX_STORAGE_NAMESPACE_BYTES
|| value == "."
|| value == ".."
|| !value.as_bytes()[0].is_ascii_alphanumeric()
|| value
.bytes()
.any(|byte| !byte.is_ascii_alphanumeric() && !matches!(byte, b'.' | b'_' | b':' | b'-'))
{
return Err(StoreError::InvalidArtifactStorageLocator);
}
Ok(())
}
fn validate_object_key(value: &str) -> Result<(), StoreError> {
if value.is_empty()
|| value.len() > ArtifactStorageLocator::MAX_OBJECT_KEY_BYTES
|| value.starts_with('/')
|| value.ends_with('/')
|| value.chars().any(|character| {
character == '\\'
|| character.is_control()
|| matches!(character, '\u{FDD0}'..='\u{FDEF}')
|| (character as u32 & 0xFFFE) == 0xFFFE
})
|| value
.split('/')
.any(|segment| segment.is_empty() || matches!(segment, "." | ".."))
{
return Err(StoreError::InvalidArtifactStorageLocator);
}
Ok(())
}
fn validate_opaque_locator_value(
value: Option<String>,
maximum_bytes: usize,
) -> Result<Option<Box<str>>, StoreError> {
value
.map(|value| {
if value.is_empty()
|| value.len() > maximum_bytes
|| !value
.bytes()
.all(|byte| byte.is_ascii_graphic() || byte == b' ')
{
return Err(StoreError::InvalidArtifactStorageLocator);
}
Ok(value.into_boxed_str())
})
.transpose()
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SchedulerFairnessPolicyRegistration {
shard_id: SchedulerShardId,
policy_digest: Digest,
policy_bytes: Box<[u8]>,
cycle_length: u16,
}
impl SchedulerFairnessPolicyRegistration {
pub const MAX_POLICY_BYTES: usize = 262_144;
pub const MAX_CYCLE_LENGTH: u16 = 4096;
pub fn new(
shard_id: SchedulerShardId,
policy_bytes: impl Into<Vec<u8>>,
cycle_length: u16,
) -> Result<Self, StoreError> {
let policy_bytes = policy_bytes.into();
if policy_bytes.is_empty()
|| policy_bytes.len() > Self::MAX_POLICY_BYTES
|| cycle_length == 0
|| cycle_length > Self::MAX_CYCLE_LENGTH
{
return Err(StoreError::InvalidSchedulerFairnessPolicy);
}
let mut preimage =
Vec::with_capacity(SCHEDULER_FAIRNESS_POLICY_DIGEST_DOMAIN.len() + policy_bytes.len());
preimage.extend_from_slice(SCHEDULER_FAIRNESS_POLICY_DIGEST_DOMAIN);
preimage.extend_from_slice(&policy_bytes);
Ok(Self {
shard_id,
policy_digest: Digest::sha256(preimage),
policy_bytes: policy_bytes.into_boxed_slice(),
cycle_length,
})
}
#[must_use]
pub const fn shard_id(&self) -> &SchedulerShardId {
&self.shard_id
}
#[must_use]
pub const fn policy_digest(&self) -> Digest {
self.policy_digest
}
#[must_use]
pub const fn policy_bytes(&self) -> &[u8] {
&self.policy_bytes
}
#[must_use]
pub const fn cycle_length(&self) -> u16 {
self.cycle_length
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct StoredSchedulerFairnessPolicy {
pub(crate) registration: SchedulerFairnessPolicyRegistration,
pub(crate) registered_at: Timestamp,
}
impl StoredSchedulerFairnessPolicy {
#[must_use]
pub const fn registration(&self) -> &SchedulerFairnessPolicyRegistration {
&self.registration
}
#[must_use]
pub const fn registered_at(&self) -> Timestamp {
self.registered_at
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum SchedulerFairnessPolicyRegistrationOutcome {
Registered(StoredSchedulerFairnessPolicy),
Idempotent(StoredSchedulerFairnessPolicy),
}
impl SchedulerFairnessPolicyRegistrationOutcome {
#[must_use]
pub const fn policy(&self) -> &StoredSchedulerFairnessPolicy {
match self {
Self::Registered(policy) | Self::Idempotent(policy) => policy,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SchedulerFairnessReservation {
pub(crate) shard_id: SchedulerShardId,
pub(crate) reservation_id: SchedulerReservationId,
pub(crate) policy_digest: Digest,
pub(crate) sequence: u64,
pub(crate) slot: u16,
pub(crate) reserved_at: Timestamp,
}
impl SchedulerFairnessReservation {
#[must_use]
pub const fn shard_id(&self) -> &SchedulerShardId {
&self.shard_id
}
#[must_use]
pub const fn reservation_id(&self) -> SchedulerReservationId {
self.reservation_id
}
#[must_use]
pub const fn policy_digest(&self) -> Digest {
self.policy_digest
}
#[must_use]
pub const fn sequence(&self) -> u64 {
self.sequence
}
#[must_use]
pub const fn slot(&self) -> u16 {
self.slot
}
#[must_use]
pub const fn reserved_at(&self) -> Timestamp {
self.reserved_at
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SchedulerFairnessRetentionPolicy {
retain_for: Duration,
batch_size: u16,
}
impl SchedulerFairnessRetentionPolicy {
pub const MIN_RETAIN_FOR: Duration = Duration::from_secs(60 * 60);
pub const MAX_RETAIN_FOR: Duration = Duration::from_secs(366 * 24 * 60 * 60);
pub const MAX_BATCH_SIZE: u16 = 10_000;
pub const fn new(retain_for: Duration, batch_size: u16) -> Result<Self, StoreError> {
if retain_for.as_nanos() < Self::MIN_RETAIN_FOR.as_nanos()
|| retain_for.as_nanos() > Self::MAX_RETAIN_FOR.as_nanos()
|| batch_size == 0
|| batch_size > Self::MAX_BATCH_SIZE
{
return Err(StoreError::InvalidSchedulerFairnessRetention);
}
Ok(Self {
retain_for,
batch_size,
})
}
#[must_use]
pub const fn retain_for(self) -> Duration {
self.retain_for
}
#[must_use]
pub const fn batch_size(self) -> u16 {
self.batch_size
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SchedulerFairnessRetentionReport {
pub(crate) observed_at: Timestamp,
pub(crate) cutoff: Timestamp,
pub(crate) deleted: u16,
}
impl SchedulerFairnessRetentionReport {
#[must_use]
pub const fn observed_at(self) -> Timestamp {
self.observed_at
}
#[must_use]
pub const fn cutoff(self) -> Timestamp {
self.cutoff
}
#[must_use]
pub const fn deleted(self) -> u16 {
self.deleted
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct StoredGraphDefinition {
pub(crate) tenant_id: TenantId,
pub(crate) graph: CompiledGraph,
pub(crate) registered_at: Timestamp,
}
impl StoredGraphDefinition {
#[must_use]
pub const fn tenant_id(&self) -> &TenantId {
&self.tenant_id
}
#[must_use]
pub const fn graph(&self) -> &CompiledGraph {
&self.graph
}
#[must_use]
pub const fn registered_at(&self) -> Timestamp {
self.registered_at
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum GraphDefinitionRegistrationOutcome {
Registered(StoredGraphDefinition),
Idempotent(StoredGraphDefinition),
}
impl GraphDefinitionRegistrationOutcome {
#[must_use]
pub const fn definition(&self) -> &StoredGraphDefinition {
match self {
Self::Registered(definition) | Self::Idempotent(definition) => definition,
}
}
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum RunQuarantineCause {
IntegrityFailure,
UnsupportedSchema,
MissingArtifact,
CrossTenantReference,
ProjectionMismatch,
FencingEpochExhausted,
OperatorPolicy,
}
impl RunQuarantineCause {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::IntegrityFailure => "integrity_failure",
Self::UnsupportedSchema => "unsupported_schema",
Self::MissingArtifact => "missing_artifact",
Self::CrossTenantReference => "cross_tenant_reference",
Self::ProjectionMismatch => "projection_mismatch",
Self::FencingEpochExhausted => "fencing_epoch_exhausted",
Self::OperatorPolicy => "operator_policy",
}
}
}
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct RunQuarantineComponent(Box<str>);
impl RunQuarantineComponent {
pub const MAX_LEN: usize = 128;
pub fn new(value: impl Into<String>) -> Result<Self, StoreError> {
let value = value.into();
if value.is_empty()
|| value.len() > Self::MAX_LEN
|| value.bytes().any(|byte| {
!byte.is_ascii_lowercase()
&& !byte.is_ascii_digit()
&& !matches!(byte, b'.' | b'_' | b':' | b'-')
})
{
return Err(StoreError::InvalidRunQuarantineComponent);
}
Ok(Self(value.into_boxed_str()))
}
pub fn from_corrupt_store_error(error: &StoreError) -> Result<Self, StoreError> {
let record = error
.corrupt_record()
.ok_or(StoreError::InvalidRunQuarantineRequest)?;
let mut component = String::with_capacity("store.".len() + record.len());
component.push_str("store.");
let mut previous_separator = false;
for byte in record.bytes() {
let normalized = if byte.is_ascii_alphanumeric() {
byte.to_ascii_lowercase()
} else if matches!(byte, b'.' | b':' | b'-') {
byte
} else {
b'_'
};
if normalized == b'_' {
if previous_separator {
continue;
}
previous_separator = true;
} else {
previous_separator = false;
}
component.push(char::from(normalized));
}
while component.ends_with('_') {
component.pop();
}
Self::new(component)
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RunQuarantineRequest {
pub(crate) tenant_id: TenantId,
pub(crate) run_id: RunId,
pub(crate) quarantine_id: QuarantineId,
pub(crate) expectation: JournalExpectation,
pub(crate) cause: RunQuarantineCause,
pub(crate) component: RunQuarantineComponent,
pub(crate) evidence_digest: Digest,
pub(crate) expected_fence: Option<RunFence>,
}
impl RunQuarantineRequest {
pub fn new(
tenant_id: TenantId,
run_id: RunId,
quarantine_id: QuarantineId,
expectation: JournalExpectation,
cause: RunQuarantineCause,
component: RunQuarantineComponent,
evidence_digest: Digest,
) -> Result<Self, StoreError> {
if expectation
.head()
.is_some_and(|head| head.tenant_id() != &tenant_id || head.run_id() != run_id)
{
return Err(StoreError::InvalidRunQuarantineRequest);
}
Ok(Self {
tenant_id,
run_id,
quarantine_id,
expectation,
cause,
component,
evidence_digest,
expected_fence: None,
})
}
pub fn with_expected_fence(mut self, fence: RunFence) -> Result<Self, StoreError> {
if fence.tenant_id() != &self.tenant_id || fence.run_id() != self.run_id {
return Err(StoreError::InvalidRunQuarantineRequest);
}
if self
.expected_fence
.as_ref()
.is_some_and(|expected| expected != &fence)
{
return Err(StoreError::InvalidRunQuarantineRequest);
}
self.expected_fence = Some(fence);
Ok(self)
}
#[must_use]
pub const fn tenant_id(&self) -> &TenantId {
&self.tenant_id
}
#[must_use]
pub const fn run_id(&self) -> RunId {
self.run_id
}
#[must_use]
pub const fn quarantine_id(&self) -> QuarantineId {
self.quarantine_id
}
#[must_use]
pub const fn expectation(&self) -> &JournalExpectation {
&self.expectation
}
#[must_use]
pub const fn cause(&self) -> RunQuarantineCause {
self.cause
}
#[must_use]
pub const fn component(&self) -> &RunQuarantineComponent {
&self.component
}
#[must_use]
pub const fn evidence_digest(&self) -> Digest {
self.evidence_digest
}
#[must_use]
pub const fn expected_fence(&self) -> Option<&RunFence> {
self.expected_fence.as_ref()
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CorruptionQuarantineContext {
pub(crate) tenant_id: TenantId,
pub(crate) run_id: RunId,
pub(crate) quarantine_id: QuarantineId,
pub(crate) expectation: JournalExpectation,
pub(crate) evidence_digest: Digest,
pub(crate) expected_fence: Option<RunFence>,
}
impl CorruptionQuarantineContext {
pub fn new(
tenant_id: TenantId,
run_id: RunId,
quarantine_id: QuarantineId,
expectation: JournalExpectation,
evidence_digest: Digest,
) -> Result<Self, StoreError> {
if expectation
.head()
.is_some_and(|head| head.tenant_id() != &tenant_id || head.run_id() != run_id)
{
return Err(StoreError::InvalidRunQuarantineRequest);
}
Ok(Self {
tenant_id,
run_id,
quarantine_id,
expectation,
evidence_digest,
expected_fence: None,
})
}
pub fn with_expected_fence(mut self, fence: RunFence) -> Result<Self, StoreError> {
if fence.tenant_id() != &self.tenant_id || fence.run_id() != self.run_id {
return Err(StoreError::InvalidClaimedRunRecoveryContext);
}
if self
.expected_fence
.as_ref()
.is_some_and(|expected| expected != &fence)
{
return Err(StoreError::InvalidClaimedRunRecoveryContext);
}
self.expected_fence = Some(fence);
Ok(self)
}
#[must_use]
pub const fn tenant_id(&self) -> &TenantId {
&self.tenant_id
}
#[must_use]
pub const fn run_id(&self) -> RunId {
self.run_id
}
#[must_use]
pub const fn quarantine_id(&self) -> QuarantineId {
self.quarantine_id
}
#[must_use]
pub const fn expectation(&self) -> &JournalExpectation {
&self.expectation
}
#[must_use]
pub const fn evidence_digest(&self) -> Digest {
self.evidence_digest
}
#[must_use]
pub const fn expected_fence(&self) -> Option<&RunFence> {
self.expected_fence.as_ref()
}
pub(crate) fn into_request(
self,
component: RunQuarantineComponent,
) -> Result<RunQuarantineRequest, StoreError> {
let request = RunQuarantineRequest::new(
self.tenant_id,
self.run_id,
self.quarantine_id,
self.expectation,
RunQuarantineCause::IntegrityFailure,
component,
self.evidence_digest,
)?;
match self.expected_fence {
Some(fence) => request.with_expected_fence(fence),
None => Ok(request),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RunQuarantine {
pub(crate) request: RunQuarantineRequest,
pub(crate) quarantined_at: Timestamp,
pub(crate) digest: Digest,
}
impl RunQuarantine {
#[must_use]
pub const fn request(&self) -> &RunQuarantineRequest {
&self.request
}
#[must_use]
pub const fn quarantined_at(&self) -> Timestamp {
self.quarantined_at
}
#[must_use]
pub const fn digest(&self) -> Digest {
self.digest
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum RunQuarantineCommitOutcome {
Committed(RunQuarantine),
Idempotent(RunQuarantine),
}
impl RunQuarantineCommitOutcome {
#[must_use]
pub const fn quarantine(&self) -> &RunQuarantine {
match self {
Self::Committed(quarantine) | Self::Idempotent(quarantine) => quarantine,
}
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum AdmissionOutcome {
Committed(RunLifecycle),
Idempotent(RunLifecycle),
}
impl AdmissionOutcome {
#[must_use]
pub const fn lifecycle(&self) -> &RunLifecycle {
match self {
Self::Committed(lifecycle) | Self::Idempotent(lifecycle) => lifecycle,
}
}
}
#[derive(Clone, Debug)]
pub struct StoredAgentAdmission {
pub(crate) admission: AgentAdmission,
pub(crate) run: StoredRun,
pub(crate) event: JournalEvent,
pub(crate) checkpoint: Checkpoint,
}
impl StoredAgentAdmission {
#[must_use]
pub const fn admission(&self) -> &AgentAdmission {
&self.admission
}
#[must_use]
pub const fn run(&self) -> &StoredRun {
&self.run
}
#[must_use]
pub const fn event(&self) -> &JournalEvent {
&self.event
}
#[must_use]
pub const fn checkpoint(&self) -> &Checkpoint {
&self.checkpoint
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum AgentAdmissionCommitOutcome {
Committed(StoredAgentAdmission),
Idempotent(StoredAgentAdmission),
}
impl AgentAdmissionCommitOutcome {
#[must_use]
pub const fn stored(&self) -> &StoredAgentAdmission {
match self {
Self::Committed(stored) | Self::Idempotent(stored) => stored,
}
}
}
#[derive(Clone, Debug)]
pub struct StoredAgentSubmission {
pub(crate) key_digest: Digest,
pub(crate) submission_digest: Digest,
pub(crate) admission: StoredAgentAdmission,
pub(crate) created_at: Timestamp,
}
impl StoredAgentSubmission {
#[must_use]
pub const fn key_digest(&self) -> Digest {
self.key_digest
}
#[must_use]
pub const fn submission_digest(&self) -> Digest {
self.submission_digest
}
#[must_use]
pub const fn admission(&self) -> &StoredAgentAdmission {
&self.admission
}
#[must_use]
pub const fn created_at(&self) -> Timestamp {
self.created_at
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum AgentSubmissionCommitOutcome {
Committed(StoredAgentSubmission),
Idempotent(StoredAgentSubmission),
}
impl AgentSubmissionCommitOutcome {
#[must_use]
pub const fn stored(&self) -> &StoredAgentSubmission {
match self {
Self::Committed(stored) | Self::Idempotent(stored) => stored,
}
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum AppendOutcome {
Committed(JournalEvent),
Idempotent(JournalEvent),
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum CheckpointCommitOutcome {
Committed {
event: JournalEvent,
checkpoint: Checkpoint,
},
Idempotent {
event: JournalEvent,
checkpoint: Checkpoint,
},
}
impl CheckpointCommitOutcome {
#[must_use]
pub const fn event(&self) -> &JournalEvent {
match self {
Self::Committed { event, .. } | Self::Idempotent { event, .. } => event,
}
}
#[must_use]
pub const fn checkpoint(&self) -> &Checkpoint {
match self {
Self::Committed { checkpoint, .. } | Self::Idempotent { checkpoint, .. } => checkpoint,
}
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum WaitCheckpointCommitOutcome {
Committed {
event: JournalEvent,
checkpoint: Checkpoint,
waits: Vec<DurableWait>,
},
Idempotent {
event: JournalEvent,
checkpoint: Checkpoint,
waits: Vec<DurableWait>,
},
}
impl WaitCheckpointCommitOutcome {
#[must_use]
pub const fn event(&self) -> &JournalEvent {
match self {
Self::Committed { event, .. } | Self::Idempotent { event, .. } => event,
}
}
#[must_use]
pub const fn checkpoint(&self) -> &Checkpoint {
match self {
Self::Committed { checkpoint, .. } | Self::Idempotent { checkpoint, .. } => checkpoint,
}
}
#[must_use]
pub fn waits(&self) -> &[DurableWait] {
match self {
Self::Committed { waits, .. } | Self::Idempotent { waits, .. } => waits,
}
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum InterruptResolutionCommitOutcome {
Committed {
event: JournalEvent,
record: InterruptRecord,
},
Idempotent {
event: JournalEvent,
record: InterruptRecord,
},
}
impl InterruptResolutionCommitOutcome {
#[must_use]
pub const fn event(&self) -> &JournalEvent {
match self {
Self::Committed { event, .. } | Self::Idempotent { event, .. } => event,
}
}
#[must_use]
pub const fn record(&self) -> &InterruptRecord {
match self {
Self::Committed { record, .. } | Self::Idempotent { record, .. } => record,
}
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum TimerFiringCommitOutcome {
Committed {
event: JournalEvent,
record: DurableTimerRecord,
},
Idempotent {
event: JournalEvent,
record: DurableTimerRecord,
},
}
impl TimerFiringCommitOutcome {
#[must_use]
pub const fn event(&self) -> &JournalEvent {
match self {
Self::Committed { event, .. } | Self::Idempotent { event, .. } => event,
}
}
#[must_use]
pub const fn record(&self) -> &DurableTimerRecord {
match self {
Self::Committed { record, .. } | Self::Idempotent { record, .. } => record,
}
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum WaitAbandonmentReason {
RunCancellation,
RunFailure,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct WaitAbandonment {
pub(crate) wait: DurableWait,
pub(crate) reason: WaitAbandonmentReason,
pub(crate) journal: JournalHead,
pub(crate) digest: Digest,
}
impl WaitAbandonment {
#[must_use]
pub const fn wait(&self) -> &DurableWait {
&self.wait
}
#[must_use]
pub const fn reason(&self) -> WaitAbandonmentReason {
self.reason
}
#[must_use]
pub const fn journal(&self) -> &JournalHead {
&self.journal
}
#[must_use]
pub const fn digest(&self) -> Digest {
self.digest
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum WaitAbandonmentCommitOutcome {
Committed {
event: JournalEvent,
abandonments: Vec<WaitAbandonment>,
},
Idempotent {
event: JournalEvent,
abandonments: Vec<WaitAbandonment>,
},
}
impl WaitAbandonmentCommitOutcome {
#[must_use]
pub const fn event(&self) -> &JournalEvent {
match self {
Self::Committed { event, .. } | Self::Idempotent { event, .. } => event,
}
}
#[must_use]
pub fn abandonments(&self) -> &[WaitAbandonment] {
match self {
Self::Committed { abandonments, .. } | Self::Idempotent { abandonments, .. } => {
abandonments
}
}
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum BarrierCommitOutcome {
Committed {
event: JournalEvent,
checkpoint: Checkpoint,
},
Idempotent {
event: JournalEvent,
checkpoint: Checkpoint,
},
}
impl BarrierCommitOutcome {
#[must_use]
pub const fn event(&self) -> &JournalEvent {
match self {
Self::Committed { event, .. } | Self::Idempotent { event, .. } => event,
}
}
#[must_use]
pub const fn checkpoint(&self) -> &Checkpoint {
match self {
Self::Committed { checkpoint, .. } | Self::Idempotent { checkpoint, .. } => checkpoint,
}
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum ToolInvocationCommitOutcome {
Committed {
event: JournalEvent,
invocation: ToolInvocation,
},
Idempotent {
event: JournalEvent,
invocation: ToolInvocation,
},
}
impl ToolInvocationCommitOutcome {
#[must_use]
pub const fn event(&self) -> &JournalEvent {
match self {
Self::Committed { event, .. } | Self::Idempotent { event, .. } => event,
}
}
#[must_use]
pub const fn invocation(&self) -> &ToolInvocation {
match self {
Self::Committed { invocation, .. } | Self::Idempotent { invocation, .. } => invocation,
}
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum ModelInvocationCommitOutcome {
Committed {
event: JournalEvent,
invocation: ModelInvocation,
},
Idempotent {
event: JournalEvent,
invocation: ModelInvocation,
},
}
impl ModelInvocationCommitOutcome {
#[must_use]
pub const fn event(&self) -> &JournalEvent {
match self {
Self::Committed { event, .. } | Self::Idempotent { event, .. } => event,
}
}
#[must_use]
pub const fn invocation(&self) -> &ModelInvocation {
match self {
Self::Committed { invocation, .. } | Self::Idempotent { invocation, .. } => invocation,
}
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum PendingNodeResultCommitOutcome {
Committed {
event: JournalEvent,
result: PendingNodeResult,
},
Idempotent {
event: JournalEvent,
result: PendingNodeResult,
},
}
impl PendingNodeResultCommitOutcome {
#[must_use]
pub const fn event(&self) -> &JournalEvent {
match self {
Self::Committed { event, .. } | Self::Idempotent { event, .. } => event,
}
}
#[must_use]
pub const fn result(&self) -> &PendingNodeResult {
match self {
Self::Committed { result, .. } | Self::Idempotent { result, .. } => result,
}
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum NodeAttemptCommitOutcome {
Committed {
event: JournalEvent,
attempt: NodeAttempt,
},
Idempotent {
event: JournalEvent,
attempt: NodeAttempt,
},
}
impl NodeAttemptCommitOutcome {
#[must_use]
pub const fn event(&self) -> &JournalEvent {
match self {
Self::Committed { event, .. } | Self::Idempotent { event, .. } => event,
}
}
#[must_use]
pub const fn attempt(&self) -> &NodeAttempt {
match self {
Self::Committed { attempt, .. } | Self::Idempotent { attempt, .. } => attempt,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct StoredOutboxDestination {
pub(crate) destination: OutboxDestinationRef,
pub(crate) config: JournalPayload,
pub(crate) created_at: Timestamp,
}
impl StoredOutboxDestination {
#[must_use]
pub const fn destination(&self) -> &OutboxDestinationRef {
&self.destination
}
#[must_use]
pub const fn config(&self) -> &JournalPayload {
&self.config
}
#[must_use]
pub const fn created_at(&self) -> Timestamp {
self.created_at
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum OutboxDestinationRegistrationOutcome {
Registered(StoredOutboxDestination),
Idempotent(StoredOutboxDestination),
}
impl OutboxDestinationRegistrationOutcome {
#[must_use]
pub const fn destination(&self) -> &StoredOutboxDestination {
match self {
Self::Registered(destination) | Self::Idempotent(destination) => destination,
}
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum OutboxEnqueueOutcome {
Committed {
event: JournalEvent,
deliveries: Vec<OutboxDelivery>,
},
Idempotent {
event: JournalEvent,
deliveries: Vec<OutboxDelivery>,
},
}
impl OutboxEnqueueOutcome {
#[must_use]
pub const fn event(&self) -> &JournalEvent {
match self {
Self::Committed { event, .. } | Self::Idempotent { event, .. } => event,
}
}
#[must_use]
pub fn deliveries(&self) -> &[OutboxDelivery] {
match self {
Self::Committed { deliveries, .. } | Self::Idempotent { deliveries, .. } => deliveries,
}
}
}
#[derive(Clone, Debug)]
pub struct OutboxClaim {
pub(crate) destination: StoredOutboxDestination,
pub(crate) delivery: OutboxDelivery,
pub(crate) start: OutboxAttemptStart,
}
impl OutboxClaim {
#[must_use]
pub const fn destination(&self) -> &StoredOutboxDestination {
&self.destination
}
#[must_use]
pub const fn delivery(&self) -> &OutboxDelivery {
&self.delivery
}
#[must_use]
pub const fn start(&self) -> &OutboxAttemptStart {
&self.start
}
#[must_use]
pub const fn fence(&self) -> &DeliveryFence {
self.start.fence()
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum OutboxClaimOutcome {
Claimed(OutboxClaim),
Idempotent(OutboxClaim),
NoWork,
}
impl OutboxClaimOutcome {
#[must_use]
pub const fn claim(&self) -> Option<&OutboxClaim> {
match self {
Self::Claimed(claim) | Self::Idempotent(claim) => Some(claim),
Self::NoWork => None,
}
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum OutboxCompletionOutcome {
Committed {
attempt: OutboxAttempt,
},
Idempotent {
attempt: OutboxAttempt,
},
}
impl OutboxCompletionOutcome {
#[must_use]
pub const fn attempt(&self) -> &OutboxAttempt {
match self {
Self::Committed { attempt } | Self::Idempotent { attempt } => attempt,
}
}
#[must_use]
pub const fn completion(&self) -> Option<&OutboxAttemptCompletion> {
self.attempt().completion()
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct OutboxAttemptHistoryPageSize(u8);
impl OutboxAttemptHistoryPageSize {
pub const MAX: u8 = 16;
pub const fn new(value: u8) -> Result<Self, StoreError> {
if value == 0 || value > Self::MAX {
return Err(StoreError::InvalidOutboxAttemptPageSize);
}
Ok(Self(value))
}
#[must_use]
pub const fn get(self) -> u8 {
self.0
}
}
#[derive(Clone, Debug)]
pub struct OutboxAttemptHistoryPage {
pub(crate) records: Vec<OutboxAttempt>,
pub(crate) has_more: bool,
}
impl OutboxAttemptHistoryPage {
#[must_use]
pub fn records(&self) -> &[OutboxAttempt] {
&self.records
}
#[must_use]
pub const fn has_more(&self) -> bool {
self.has_more
}
#[must_use]
pub fn next_cursor(&self) -> Option<OutboxAttempt> {
self.records.last().cloned()
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct NodeAttemptHistoryPageSize(u8);
impl NodeAttemptHistoryPageSize {
pub const MAX: u8 = 2;
pub const fn new(value: u8) -> Result<Self, StoreError> {
if value == 0 || value > Self::MAX {
return Err(StoreError::InvalidNodeAttemptPageSize);
}
Ok(Self(value))
}
#[must_use]
pub const fn get(self) -> u8 {
self.0
}
}
#[derive(Clone, Debug)]
pub struct NodeAttemptHistoryPage {
pub(crate) records: Vec<NodeAttempt>,
pub(crate) has_more: bool,
}
impl NodeAttemptHistoryPage {
#[must_use]
pub fn records(&self) -> &[NodeAttempt] {
&self.records
}
#[must_use]
pub const fn has_more(&self) -> bool {
self.has_more
}
#[must_use]
pub fn next_cursor(&self) -> Option<NodeAttempt> {
self.records.last().cloned()
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct PendingNodeResultPageSize(u8);
impl PendingNodeResultPageSize {
pub const MAX: u8 = 2;
pub const fn new(value: u8) -> Result<Self, StoreError> {
if value == 0 || value > Self::MAX {
return Err(StoreError::InvalidPendingNodeResultPageSize);
}
Ok(Self(value))
}
#[must_use]
pub const fn get(self) -> u8 {
self.0
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PendingNodeResultPageCursor {
pub(crate) base_checkpoint: CheckpointHead,
pub(crate) snapshot_journal_head: JournalHead,
pub(crate) after: PendingNodeResultHead,
}
impl PendingNodeResultPageCursor {
#[must_use]
pub const fn base_checkpoint(&self) -> &CheckpointHead {
&self.base_checkpoint
}
#[must_use]
pub const fn snapshot_journal_head(&self) -> &JournalHead {
&self.snapshot_journal_head
}
#[must_use]
pub const fn after(&self) -> &PendingNodeResultHead {
&self.after
}
}
#[derive(Clone, Debug)]
pub struct PendingNodeResultPage {
pub(crate) base_checkpoint: CheckpointHead,
pub(crate) snapshot_journal_head: JournalHead,
pub(crate) records: Vec<PendingNodeResult>,
pub(crate) has_more: bool,
}
impl PendingNodeResultPage {
#[must_use]
pub const fn base_checkpoint(&self) -> &CheckpointHead {
&self.base_checkpoint
}
#[must_use]
pub const fn snapshot_journal_head(&self) -> &JournalHead {
&self.snapshot_journal_head
}
#[must_use]
pub fn records(&self) -> &[PendingNodeResult] {
&self.records
}
#[must_use]
pub fn into_records(self) -> Vec<PendingNodeResult> {
self.records
}
#[must_use]
pub const fn has_more(&self) -> bool {
self.has_more
}
#[must_use]
pub fn next_cursor(&self) -> Option<PendingNodeResultPageCursor> {
self.records
.last()
.map(|result| PendingNodeResultPageCursor {
base_checkpoint: self.base_checkpoint.clone(),
snapshot_journal_head: self.snapshot_journal_head.clone(),
after: result.head(),
})
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct ModelInvocationHistoryPageSize(u8);
impl ModelInvocationHistoryPageSize {
pub const MAX: u8 = 1;
pub const fn new(value: u8) -> Result<Self, StoreError> {
if value != Self::MAX {
return Err(StoreError::InvalidModelInvocationPageSize);
}
Ok(Self(value))
}
#[must_use]
pub const fn get(self) -> u8 {
self.0
}
}
#[derive(Clone, Debug)]
pub struct ModelInvocationHistoryPage {
pub(crate) records: Vec<ModelInvocation>,
pub(crate) has_more: bool,
}
impl ModelInvocationHistoryPage {
#[must_use]
pub fn records(&self) -> &[ModelInvocation] {
&self.records
}
#[must_use]
pub const fn has_more(&self) -> bool {
self.has_more
}
#[must_use]
pub fn next_cursor(&self) -> Option<ModelInvocation> {
self.records.last().cloned()
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct ToolInvocationHistoryPageSize(u8);
impl ToolInvocationHistoryPageSize {
pub const MAX: u8 = 2;
pub const fn new(value: u8) -> Result<Self, StoreError> {
if value == 0 || value > Self::MAX {
return Err(StoreError::InvalidToolInvocationPageSize);
}
Ok(Self(value))
}
#[must_use]
pub const fn get(self) -> u8 {
self.0
}
}
#[derive(Clone, Debug)]
pub struct ToolInvocationHistoryPage {
pub(crate) records: Vec<ToolInvocation>,
pub(crate) has_more: bool,
}
impl ToolInvocationHistoryPage {
#[must_use]
pub fn records(&self) -> &[ToolInvocation] {
&self.records
}
#[must_use]
pub const fn has_more(&self) -> bool {
self.has_more
}
#[must_use]
pub fn next_cursor(&self) -> Option<ToolInvocation> {
self.records.last().cloned()
}
}
impl AppendOutcome {
#[must_use]
pub const fn event(&self) -> &JournalEvent {
match self {
Self::Committed(event) | Self::Idempotent(event) => event,
}
}
}
#[allow(clippy::large_enum_variant)]
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum RunProjection {
Unchanged,
Transition {
expected_revision: RunRevision,
transition: RunTransition,
},
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CheckpointPointer {
pub(crate) checkpoint_id: CheckpointId,
pub(crate) superstep: Superstep,
pub(crate) digest: Digest,
}
impl CheckpointPointer {
#[must_use]
pub const fn checkpoint_id(&self) -> CheckpointId {
self.checkpoint_id
}
#[must_use]
pub const fn superstep(&self) -> Superstep {
self.superstep
}
#[must_use]
pub const fn digest(&self) -> Digest {
self.digest
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct CheckpointLineagePageSize(u8);
impl CheckpointLineagePageSize {
pub const MAX: u8 = 8;
pub const fn new(value: u8) -> Result<Self, StoreError> {
if value == 0 || value > Self::MAX {
return Err(StoreError::InvalidCheckpointPageSize);
}
Ok(Self(value))
}
#[must_use]
pub const fn get(self) -> u8 {
self.0
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CheckpointLineagePage {
pub(crate) checkpoints: Vec<Checkpoint>,
pub(crate) next_cursor: Option<CheckpointHead>,
}
impl CheckpointLineagePage {
#[must_use]
pub fn checkpoints(&self) -> &[Checkpoint] {
&self.checkpoints
}
#[must_use]
pub const fn has_more(&self) -> bool {
self.next_cursor.is_some()
}
#[must_use]
pub fn next_cursor(&self) -> Option<CheckpointHead> {
self.next_cursor.clone()
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct GraphReplayLimits {
maximum_barrier_result_bytes: usize,
}
impl GraphReplayLimits {
pub const HARD_MAXIMUM_BARRIER_RESULT_BYTES: usize = 512 * 1024 * 1024;
pub const fn new(maximum_barrier_result_bytes: usize) -> Result<Self, StoreError> {
if maximum_barrier_result_bytes == 0
|| maximum_barrier_result_bytes > Self::HARD_MAXIMUM_BARRIER_RESULT_BYTES
{
return Err(StoreError::InvalidGraphReplayLimits);
}
Ok(Self {
maximum_barrier_result_bytes,
})
}
#[must_use]
pub const fn maximum_barrier_result_bytes(self) -> usize {
self.maximum_barrier_result_bytes
}
}
impl Default for GraphReplayLimits {
fn default() -> Self {
Self {
maximum_barrier_result_bytes: 64 * 1024 * 1024,
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct GraphReplayReport {
pub(crate) checkpoints_validated: u64,
pub(crate) barriers_replayed: u64,
pub(crate) results_replayed: u64,
pub(crate) maximum_barrier_result_bytes: usize,
}
impl GraphReplayReport {
#[must_use]
pub const fn checkpoints_validated(self) -> u64 {
self.checkpoints_validated
}
#[must_use]
pub const fn barriers_replayed(self) -> u64 {
self.barriers_replayed
}
#[must_use]
pub const fn results_replayed(self) -> u64 {
self.results_replayed
}
#[must_use]
pub const fn maximum_barrier_result_bytes(self) -> usize {
self.maximum_barrier_result_bytes
}
}
impl RunProjection {
#[must_use]
pub const fn unchanged() -> Self {
Self::Unchanged
}
#[must_use]
pub const fn transition(expected_revision: RunRevision, transition: RunTransition) -> Self {
Self::Transition {
expected_revision,
transition,
}
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct WaitDiscoveryPageSize(u8);
impl WaitDiscoveryPageSize {
pub const MAX: u8 = 16;
pub const fn new(value: u8) -> Result<Self, StoreError> {
if value == 0 || value > Self::MAX {
return Err(StoreError::InvalidWaitDiscoveryPageSize);
}
Ok(Self(value))
}
#[must_use]
pub const fn get(self) -> u8 {
self.0
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DueTimerPageCursor {
pub(crate) tenant_id: stateknot_core::TenantId,
pub(crate) snapshot_at: Timestamp,
pub(crate) due_at: Timestamp,
pub(crate) run_id: stateknot_core::RunId,
pub(crate) timer_id: stateknot_core::TimerId,
}
#[derive(Clone, Debug)]
pub struct DueTimerPage {
pub(crate) tenant_id: stateknot_core::TenantId,
pub(crate) snapshot_at: Timestamp,
pub(crate) records: Vec<DurableTimer>,
pub(crate) has_more: bool,
}
impl DueTimerPage {
#[must_use]
pub const fn snapshot_at(&self) -> Timestamp {
self.snapshot_at
}
#[must_use]
pub fn records(&self) -> &[DurableTimer] {
&self.records
}
#[must_use]
pub const fn has_more(&self) -> bool {
self.has_more
}
#[must_use]
pub fn next_cursor(&self) -> Option<DueTimerPageCursor> {
self.records.last().map(|timer| DueTimerPageCursor {
tenant_id: self.tenant_id.clone(),
snapshot_at: self.snapshot_at,
due_at: timer.marker().due_at(),
run_id: timer.intent().run_id(),
timer_id: timer.marker().timer_id(),
})
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ExpiredInterruptPageCursor {
pub(crate) tenant_id: stateknot_core::TenantId,
pub(crate) snapshot_at: Timestamp,
pub(crate) expires_at: Timestamp,
pub(crate) run_id: stateknot_core::RunId,
pub(crate) interrupt_id: stateknot_core::InterruptId,
}
#[derive(Clone, Debug)]
pub struct ExpiredInterruptPage {
pub(crate) tenant_id: stateknot_core::TenantId,
pub(crate) snapshot_at: Timestamp,
pub(crate) records: Vec<InterruptRequest>,
pub(crate) has_more: bool,
}
impl ExpiredInterruptPage {
#[must_use]
pub const fn snapshot_at(&self) -> Timestamp {
self.snapshot_at
}
#[must_use]
pub fn records(&self) -> &[InterruptRequest] {
&self.records
}
#[must_use]
pub const fn has_more(&self) -> bool {
self.has_more
}
#[must_use]
pub fn next_cursor(&self) -> Option<ExpiredInterruptPageCursor> {
let request = self.records.last()?;
Some(ExpiredInterruptPageCursor {
tenant_id: self.tenant_id.clone(),
snapshot_at: self.snapshot_at,
expires_at: request.marker().expires_at()?,
run_id: request.intent().run_id(),
interrupt_id: request.marker().interrupt_id(),
})
}
}
#[derive(Clone, Debug)]
pub struct StoredRun {
pub(crate) lifecycle: RunLifecycle,
pub(crate) journal_head: Option<JournalHead>,
pub(crate) lease: Option<RunLease>,
pub(crate) last_fencing_epoch: Option<FencingEpoch>,
pub(crate) checkpoint: Option<CheckpointPointer>,
pub(crate) scheduler_ready_at: Option<stateknot_core::Timestamp>,
pub(crate) scheduler_not_before: Option<stateknot_core::Timestamp>,
pub(crate) wait_set_digest: Option<Digest>,
pub(crate) unresolved_wait_count: u8,
pub(crate) next_timer_due_at: Option<Timestamp>,
pub(crate) next_interrupt_expiry_at: Option<Timestamp>,
pub(crate) quarantined: bool,
}
impl StoredRun {
#[must_use]
pub const fn lifecycle(&self) -> &RunLifecycle {
&self.lifecycle
}
#[must_use]
pub const fn journal_head(&self) -> Option<&JournalHead> {
self.journal_head.as_ref()
}
#[must_use]
pub const fn lease(&self) -> Option<&RunLease> {
self.lease.as_ref()
}
#[must_use]
pub const fn last_fencing_epoch(&self) -> Option<FencingEpoch> {
self.last_fencing_epoch
}
#[must_use]
pub const fn checkpoint(&self) -> Option<&CheckpointPointer> {
self.checkpoint.as_ref()
}
#[must_use]
pub const fn scheduler_ready_at(&self) -> Option<stateknot_core::Timestamp> {
self.scheduler_ready_at
}
#[must_use]
pub const fn scheduler_not_before(&self) -> Option<stateknot_core::Timestamp> {
self.scheduler_not_before
}
#[must_use]
pub const fn wait_set_digest(&self) -> Option<Digest> {
self.wait_set_digest
}
#[must_use]
pub const fn unresolved_wait_count(&self) -> u8 {
self.unresolved_wait_count
}
#[must_use]
pub const fn next_timer_due_at(&self) -> Option<Timestamp> {
self.next_timer_due_at
}
#[must_use]
pub const fn next_interrupt_expiry_at(&self) -> Option<Timestamp> {
self.next_interrupt_expiry_at
}
#[must_use]
pub const fn is_quarantined(&self) -> bool {
self.quarantined
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct RunnableRunPageSize(u8);
impl RunnableRunPageSize {
pub const MAX: u8 = 16;
pub const fn new(value: u8) -> Result<Self, StoreError> {
if value == 0 || value > Self::MAX {
return Err(StoreError::InvalidRunnableRunPageSize);
}
Ok(Self(value))
}
#[must_use]
pub const fn get(self) -> u8 {
self.0
}
}
#[derive(Clone, Debug)]
pub struct RunnableRunCandidate {
pub(crate) run: StoredRun,
pub(crate) ready_at: stateknot_core::Timestamp,
pub(crate) available_at: stateknot_core::Timestamp,
}
impl RunnableRunCandidate {
#[must_use]
pub const fn run(&self) -> &StoredRun {
&self.run
}
#[must_use]
pub const fn ready_at(&self) -> stateknot_core::Timestamp {
self.ready_at
}
#[must_use]
pub const fn available_at(&self) -> stateknot_core::Timestamp {
self.available_at
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RunnableRunPageCursor {
pub(crate) tenant_id: stateknot_core::TenantId,
pub(crate) snapshot_at: stateknot_core::Timestamp,
pub(crate) available_at: stateknot_core::Timestamp,
pub(crate) run_id: stateknot_core::RunId,
}
#[derive(Clone, Debug)]
pub struct RunnableRunPage {
pub(crate) tenant_id: stateknot_core::TenantId,
pub(crate) snapshot_at: stateknot_core::Timestamp,
pub(crate) records: Vec<RunnableRunCandidate>,
pub(crate) has_more: bool,
}
impl RunnableRunPage {
#[must_use]
pub const fn snapshot_at(&self) -> stateknot_core::Timestamp {
self.snapshot_at
}
#[must_use]
pub fn records(&self) -> &[RunnableRunCandidate] {
&self.records
}
#[must_use]
pub const fn has_more(&self) -> bool {
self.has_more
}
#[must_use]
pub fn next_cursor(&self) -> Option<RunnableRunPageCursor> {
self.records.last().map(|candidate| RunnableRunPageCursor {
tenant_id: self.tenant_id.clone(),
snapshot_at: self.snapshot_at,
available_at: candidate.available_at,
run_id: candidate.run.lifecycle().provenance().run_id(),
})
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum LeaseRenewalOutcome {
Renewed(RunLease),
Idempotent(RunLease),
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LiveLeaseObservation {
pub(crate) lease: RunLease,
pub(crate) observed_at: Timestamp,
}
impl LiveLeaseObservation {
#[must_use]
pub const fn lease(&self) -> &RunLease {
&self.lease
}
#[must_use]
pub const fn observed_at(&self) -> Timestamp {
self.observed_at
}
#[must_use]
pub fn into_parts(self) -> (RunLease, Timestamp) {
(self.lease, self.observed_at)
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum LeaseClaimOutcome {
Claimed(RunLease),
Idempotent(RunLease),
}
impl LeaseClaimOutcome {
#[must_use]
pub const fn lease(&self) -> &RunLease {
match self {
Self::Claimed(lease) | Self::Idempotent(lease) => lease,
}
}
}
impl LeaseRenewalOutcome {
#[must_use]
pub const fn lease(&self) -> &RunLease {
match self {
Self::Renewed(lease) | Self::Idempotent(lease) => lease,
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum LeaseReleaseOutcome {
Released,
Idempotent,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum DelayedRetryScheduleOutcome {
Scheduled {
not_before: Timestamp,
},
Idempotent {
not_before: Timestamp,
},
Due {
not_before: Timestamp,
},
}
impl DelayedRetryScheduleOutcome {
#[must_use]
pub const fn not_before(self) -> Timestamp {
match self {
Self::Scheduled { not_before }
| Self::Idempotent { not_before }
| Self::Due { not_before } => not_before,
}
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct JournalPageSize(u16);
impl JournalPageSize {
pub const MAX: u16 = 1_000;
pub const fn new(value: u16) -> Result<Self, StoreError> {
if value == 0 || value > Self::MAX {
return Err(StoreError::InvalidPageSize);
}
Ok(Self(value))
}
#[must_use]
pub const fn get(self) -> u16 {
self.0
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct JournalPage {
pub(crate) events: Vec<JournalEvent>,
pub(crate) has_more: bool,
}
impl JournalPage {
#[must_use]
pub fn events(&self) -> &[JournalEvent] {
&self.events
}
#[must_use]
pub const fn has_more(&self) -> bool {
self.has_more
}
#[must_use]
pub fn next_cursor(&self) -> Option<JournalHead> {
self.events.last().map(JournalEvent::head)
}
}