use std::{fmt, sync::OnceLock, time::Duration};
use polyc_capability::{Capability, CapabilitySet};
use polyc_proto::proto::polychrome::harness::v1::{
ExecutionCapabilities as WireExecutionCapabilities, ExecutionGrant as WireExecutionGrant,
ExecutionLabel as WireExecutionLabel, ExecutionStep as WireExecutionStep,
harness_message::Frame as HarnessFrame,
};
use polyc_state::{
cancel::CancellationToken,
command::FencingToken,
context::CallContext,
deadline::{Clock, MonotonicInstant, ProductionClock},
id::{AttemptId, OwnerId},
model_attempt::{ModelConversationId, TenantId},
};
pub const MAX_LABELED_STEPS: u32 = 4096;
pub const MAX_EXECUTION_BUDGET: Duration = Duration::from_hours(1);
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ExecutionError {
#[error("the fenced Execution protocol requires {field}: {reason}")]
Malformed {
field: String,
reason: String,
},
#[error("this build speaks Execution protocol {current}, and the peer declared {declared}")]
VersionMismatch {
declared: ExecutionProtocolVersion,
current: ExecutionProtocolVersion,
},
#[error(
"this frame names execution {execution} attempt {attempt}, and this session runs {expected_execution} attempt {expected_attempt}"
)]
ForeignAttempt {
execution: ExecutionId,
attempt: AttemptId,
expected_execution: ExecutionId,
expected_attempt: AttemptId,
},
#[error("this frame presents fence {presented}, and this session holds {current}")]
StaleFence {
presented: FencingToken,
current: FencingToken,
},
#[error("step {index} was already admitted on this attempt")]
DuplicateStep {
index: u64,
},
#[error("this frame is step {index}, and the next step of this attempt is {expected}")]
OutOfOrderStep {
index: u64,
expected: u64,
},
#[error("step {index} derives to another identity than the one this frame carries")]
ForgedStepId {
index: u64,
},
#[error("this attempt is granted {granted} labeled steps, and step {index} is past that")]
StepBudgetExhausted {
index: u64,
granted: u32,
},
#[error("this grant names capabilities this build does not recognize: {unknown}")]
UnknownCapability {
unknown: String,
},
#[error("this grant is for Execution audience {declared}, but this workload is {expected}")]
WrongAudience {
declared: ExecutionAudience,
expected: ExecutionAudience,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ExecutionProtocolVersion(u32);
impl ExecutionProtocolVersion {
pub const CURRENT: Self = Self(3);
#[must_use]
pub const fn new(version: u32) -> Self {
Self(version)
}
#[must_use]
pub const fn get(self) -> u32 {
self.0
}
}
impl fmt::Display for ExecutionProtocolVersion {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "v{}", self.0)
}
}
pub const fn check_execution_version(
declared: ExecutionProtocolVersion,
) -> Result<(), ExecutionError> {
if declared.get() == ExecutionProtocolVersion::CURRENT.get() {
return Ok(());
}
Err(ExecutionError::VersionMismatch {
declared,
current: ExecutionProtocolVersion::CURRENT,
})
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ExecutionId(String);
impl ExecutionId {
#[must_use]
pub fn new(value: impl Into<String>) -> Self {
Self(value.into())
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ExecutionAudience(String);
impl ExecutionAudience {
pub fn new(value: impl Into<String>) -> Result<Self, ExecutionError> {
let value = value.into();
if value.is_empty() {
return Err(ExecutionError::Malformed {
field: "audience".to_owned(),
reason: "a grant with no recipient can be replayed at any harness".to_owned(),
});
}
Ok(Self(value))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for ExecutionAudience {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.0)
}
}
impl fmt::Display for ExecutionId {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.0)
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct StepId(String);
impl StepId {
#[must_use]
pub fn derive(execution: &ExecutionId, attempt: &AttemptId, index: u64) -> Self {
use sha2::Digest as _;
let mut hasher = sha2::Sha256::new();
hasher.update(b"polychrome.execution.step.v1");
for part in [execution.as_str().as_bytes(), attempt.as_str().as_bytes()] {
hasher.update(u64::try_from(part.len()).unwrap_or(u64::MAX).to_be_bytes());
hasher.update(part);
}
hasher.update(index.to_be_bytes());
Self(hex::encode(hasher.finalize()))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for StepId {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.0)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExecutionIdentity {
execution: ExecutionId,
attempt: AttemptId,
fence: FencingToken,
}
impl ExecutionIdentity {
pub fn new(
execution: ExecutionId,
attempt: AttemptId,
fence: FencingToken,
) -> Result<Self, ExecutionError> {
if execution.is_empty() {
return Err(ExecutionError::Malformed {
field: "execution_id".to_owned(),
reason: "an execution identity is what a resumed attempt is the same execution as"
.to_owned(),
});
}
if attempt.is_empty() {
return Err(ExecutionError::Malformed {
field: "attempt_id".to_owned(),
reason: "an attempt identity is what makes an ambiguous outcome reconcilable"
.to_owned(),
});
}
if fence == FencingToken::UNCLAIMED {
return Err(ExecutionError::Malformed {
field: "fence".to_owned(),
reason: "the unclaimed token names no ownership epoch, so nothing could refuse a \
superseded owner"
.to_owned(),
});
}
Ok(Self {
execution,
attempt,
fence,
})
}
#[must_use]
pub const fn execution(&self) -> &ExecutionId {
&self.execution
}
#[must_use]
pub const fn attempt(&self) -> &AttemptId {
&self.attempt
}
#[must_use]
pub const fn fence(&self) -> FencingToken {
self.fence
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExecutionStep {
index: u64,
id: StepId,
}
impl ExecutionStep {
#[must_use]
pub fn at(identity: &ExecutionIdentity, index: u64) -> Self {
Self {
id: StepId::derive(identity.execution(), identity.attempt(), index),
index,
}
}
#[must_use]
pub const fn index(&self) -> u64 {
self.index
}
#[must_use]
pub const fn id(&self) -> &StepId {
&self.id
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ExecutionCapabilities {
granted: CapabilitySet,
max_labeled_steps: u32,
}
impl ExecutionCapabilities {
pub fn new(granted: CapabilitySet, max_labeled_steps: u32) -> Result<Self, ExecutionError> {
if max_labeled_steps == 0 || max_labeled_steps > MAX_LABELED_STEPS {
return Err(ExecutionError::Malformed {
field: "max_labeled_steps".to_owned(),
reason: format!(
"a ceiling of {max_labeled_steps} is outside 1..={MAX_LABELED_STEPS}; this \
contract refuses a ceiling it cannot grant rather than clamping one the \
sender would believe it received"
),
});
}
Ok(Self {
granted,
max_labeled_steps,
})
}
#[must_use]
pub const fn granted(self) -> CapabilitySet {
self.granted
}
#[must_use]
pub const fn permits(self, capability: Capability) -> bool {
self.granted.contains(capability)
}
#[must_use]
pub const fn max_labeled_steps(self) -> u32 {
self.max_labeled_steps
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExecutionGrant {
opening: ExecutionLabel,
owner: OwnerId,
claim_attempt: AttemptId,
tenant: TenantId,
conversation: ModelConversationId,
audience: ExecutionAudience,
last_committed_step: Option<ExecutionLabel>,
budget: Duration,
capabilities: ExecutionCapabilities,
}
impl ExecutionGrant {
#[allow(clippy::too_many_arguments)]
pub fn new(
identity: ExecutionIdentity,
owner: OwnerId,
claim_attempt: AttemptId,
audience: ExecutionAudience,
last_committed_step: Option<ExecutionLabel>,
budget: Duration,
capabilities: ExecutionCapabilities,
tenant: TenantId,
conversation: ModelConversationId,
) -> Result<Self, ExecutionError> {
Self::from_declared(
ExecutionLabel::new(identity, 0),
owner,
claim_attempt,
audience,
last_committed_step,
budget,
capabilities,
tenant,
conversation,
)
}
#[allow(clippy::too_many_arguments)]
fn from_declared(
opening: ExecutionLabel,
owner: OwnerId,
claim_attempt: AttemptId,
audience: ExecutionAudience,
last_committed_step: Option<ExecutionLabel>,
budget: Duration,
capabilities: ExecutionCapabilities,
tenant: TenantId,
conversation: ModelConversationId,
) -> Result<Self, ExecutionError> {
if opening.step().index() != 0 {
return Err(ExecutionError::OutOfOrderStep {
index: opening.step().index(),
expected: 0,
});
}
let expected_opening = StepId::derive(
opening.identity().execution(),
opening.identity().attempt(),
opening.step().index(),
);
if opening.step().id() != &expected_opening {
return Err(ExecutionError::ForgedStepId {
index: opening.step().index(),
});
}
if owner.is_empty() {
return Err(ExecutionError::Malformed {
field: "owner_id".to_owned(),
reason: "the owner is who holds the fence this attempt runs under".to_owned(),
});
}
if claim_attempt.is_empty() {
return Err(ExecutionError::Malformed {
field: "claim_attempt_id".to_owned(),
reason: "the durable claim attempt is the proof this dispatch was authorized"
.to_owned(),
});
}
if tenant.is_empty() || conversation.is_empty() {
return Err(ExecutionError::Malformed {
field: "model_authority".to_owned(),
reason: "Control must explicitly bind verified tenant and conversation authority"
.to_owned(),
});
}
if let Some(committed) = &last_committed_step {
check_execution_version(committed.version())?;
if committed.step().index() == 0 {
return Err(ExecutionError::Malformed {
field: "last_committed_step".to_owned(),
reason: "step zero opens an attempt and is not a committed outcome".to_owned(),
});
}
if committed.identity().execution() != opening.identity().execution() {
return Err(ExecutionError::ForeignAttempt {
execution: committed.identity().execution().clone(),
attempt: committed.identity().attempt().clone(),
expected_execution: opening.identity().execution().clone(),
expected_attempt: opening.identity().attempt().clone(),
});
}
if committed.identity().attempt() == opening.identity().attempt() {
return Err(ExecutionError::Malformed {
field: "last_committed_step.attempt_id".to_owned(),
reason: "a resumed attempt must be fresh, not resume itself".to_owned(),
});
}
if committed.identity().fence() > opening.identity().fence() {
return Err(ExecutionError::StaleFence {
presented: committed.identity().fence(),
current: opening.identity().fence(),
});
}
let expected = StepId::derive(
committed.identity().execution(),
committed.identity().attempt(),
committed.step().index(),
);
if committed.step().id() != &expected {
return Err(ExecutionError::ForgedStepId {
index: committed.step().index(),
});
}
}
if budget.is_zero() || budget > MAX_EXECUTION_BUDGET {
return Err(ExecutionError::Malformed {
field: "budget_nanos".to_owned(),
reason: format!(
"a budget of {budget:?} is outside 1ns..={MAX_EXECUTION_BUDGET:?}; an attempt \
that outlives every takeover window makes the fence decorative"
),
});
}
Ok(Self {
opening,
owner,
claim_attempt,
tenant,
conversation,
audience,
last_committed_step,
budget,
capabilities,
})
}
#[must_use]
pub const fn opening(&self) -> &ExecutionLabel {
&self.opening
}
#[must_use]
pub const fn identity(&self) -> &ExecutionIdentity {
self.opening.identity()
}
#[must_use]
pub const fn owner(&self) -> &OwnerId {
&self.owner
}
#[must_use]
pub const fn claim_attempt(&self) -> &AttemptId {
&self.claim_attempt
}
#[must_use]
pub const fn tenant(&self) -> &TenantId {
&self.tenant
}
#[must_use]
pub const fn conversation(&self) -> &ModelConversationId {
&self.conversation
}
#[must_use]
pub const fn audience(&self) -> &ExecutionAudience {
&self.audience
}
#[must_use]
pub const fn last_committed_step(&self) -> Option<&ExecutionLabel> {
self.last_committed_step.as_ref()
}
#[must_use]
pub const fn budget(&self) -> Duration {
self.budget
}
#[must_use]
pub const fn capabilities(&self) -> ExecutionCapabilities {
self.capabilities
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExecutionLabel {
version: ExecutionProtocolVersion,
identity: ExecutionIdentity,
step: ExecutionStep,
}
impl ExecutionLabel {
#[must_use]
pub fn new(identity: ExecutionIdentity, index: u64) -> Self {
let step = ExecutionStep::at(&identity, index);
Self {
version: ExecutionProtocolVersion::CURRENT,
identity,
step,
}
}
#[must_use]
pub const fn version(&self) -> ExecutionProtocolVersion {
self.version
}
#[must_use]
pub const fn identity(&self) -> &ExecutionIdentity {
&self.identity
}
#[must_use]
pub const fn step(&self) -> &ExecutionStep {
&self.step
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FrameClass {
Proposal,
Ephemeral,
Reply,
}
#[must_use]
pub const fn classify_frame(frame: &HarnessFrame) -> FrameClass {
match frame {
HarnessFrame::Input(_)
| HarnessFrame::Batch(_)
| HarnessFrame::Failed(_)
| HarnessFrame::PaidFetchRequest(_)
| HarnessFrame::ControlPlaneToolRequest(_)
| HarnessFrame::DispatchMutationRequest(_)
| HarnessFrame::PeerCallRequest(_)
| HarnessFrame::StepOutcomeProposal(_)
| HarnessFrame::ModelRequest(_) => FrameClass::Proposal,
HarnessFrame::Delta(_) => FrameClass::Ephemeral,
HarnessFrame::PaidFetchResponse(_)
| HarnessFrame::ControlPlaneToolResponse(_)
| HarnessFrame::DispatchMutationResponse(_)
| HarnessFrame::PeerCallResponse(_)
| HarnessFrame::StepCommitReceipt(_)
| HarnessFrame::ModelResponse(_) => FrameClass::Reply,
}
}
#[derive(Debug, Clone)]
pub struct ExecutionSession {
identity: ExecutionIdentity,
capabilities: ExecutionCapabilities,
context: CallContext,
high: u64,
}
impl ExecutionSession {
#[must_use]
pub fn open(grant: &ExecutionGrant, now: MonotonicInstant) -> Self {
Self {
identity: grant.identity().clone(),
capabilities: grant.capabilities(),
context: CallContext::from_origin_relative_budget(
grant.budget(),
CancellationToken::new(),
)
.in_frame(now),
high: grant
.last_committed_step()
.map_or(0, |committed| committed.step().index()),
}
}
pub fn admit(
grant: &ExecutionGrant,
expected_audience: &ExecutionAudience,
now: MonotonicInstant,
) -> Result<Self, ExecutionError> {
check_execution_version(grant.opening().version())?;
if grant.audience() != expected_audience {
return Err(ExecutionError::WrongAudience {
declared: grant.audience().clone(),
expected: expected_audience.clone(),
});
}
Ok(Self::open(grant, now))
}
pub fn check_opening_envelope(&self, label: &ExecutionLabel) -> Result<(), ExecutionError> {
check_execution_version(label.version())?;
self.check_identity(label.identity())?;
self.check_step_id(label.step())?;
if label.step().index() != 0 {
return Err(ExecutionError::OutOfOrderStep {
index: label.step().index(),
expected: 0,
});
}
Ok(())
}
#[must_use]
pub const fn identity(&self) -> &ExecutionIdentity {
&self.identity
}
#[must_use]
pub const fn capabilities(&self) -> ExecutionCapabilities {
self.capabilities
}
#[must_use]
pub const fn permits(&self, capability: Capability) -> bool {
self.capabilities.permits(capability)
}
#[must_use]
pub const fn call_context(&self) -> &CallContext {
&self.context
}
pub fn cancel(&self) {
self.context.cancellation().cancel();
}
#[must_use]
pub const fn high_step(&self) -> u64 {
self.high
}
pub fn stamp_proposal(&mut self) -> Result<ExecutionLabel, ExecutionError> {
let index = self.high.saturating_add(1);
self.check_within_grant(index)?;
self.high = index;
Ok(ExecutionLabel::new(self.identity.clone(), index))
}
#[must_use]
pub fn stamp_ephemeral(&self) -> ExecutionLabel {
ExecutionLabel::new(self.identity.clone(), self.high.saturating_add(1))
}
#[must_use]
pub fn stamp_reply(&self, proposal: &ExecutionLabel) -> ExecutionLabel {
ExecutionLabel::new(self.identity.clone(), proposal.step().index())
}
pub fn admit_frame(
&mut self,
label: &ExecutionLabel,
class: FrameClass,
) -> Result<(), ExecutionError> {
check_execution_version(label.version())?;
self.check_identity(label.identity())?;
self.check_step_id(label.step())?;
let index = label.step().index();
match class {
FrameClass::Proposal => {
let expected = self.high.saturating_add(1);
if index == self.high {
return Err(ExecutionError::DuplicateStep { index });
}
if index != expected {
return Err(ExecutionError::OutOfOrderStep { index, expected });
}
self.check_within_grant(index)?;
self.high = index;
}
FrameClass::Ephemeral => {
let expected = self.high.saturating_add(1);
if index != expected {
return Err(ExecutionError::OutOfOrderStep { index, expected });
}
}
FrameClass::Reply => {
if index == 0 || index > self.high {
return Err(ExecutionError::OutOfOrderStep {
index,
expected: self.high,
});
}
}
}
Ok(())
}
pub fn admit_reply(
&mut self,
label: &ExecutionLabel,
expected_step: u64,
) -> Result<(), ExecutionError> {
self.admit_frame(label, FrameClass::Reply)?;
if label.step().index() != expected_step {
return Err(ExecutionError::OutOfOrderStep {
index: label.step().index(),
expected: expected_step,
});
}
Ok(())
}
fn check_identity(&self, presented: &ExecutionIdentity) -> Result<(), ExecutionError> {
if presented.execution() != self.identity.execution()
|| presented.attempt() != self.identity.attempt()
{
return Err(ExecutionError::ForeignAttempt {
execution: presented.execution().clone(),
attempt: presented.attempt().clone(),
expected_execution: self.identity.execution().clone(),
expected_attempt: self.identity.attempt().clone(),
});
}
if presented.fence() != self.identity.fence() {
return Err(ExecutionError::StaleFence {
presented: presented.fence(),
current: self.identity.fence(),
});
}
Ok(())
}
fn check_step_id(&self, step: &ExecutionStep) -> Result<(), ExecutionError> {
if *step.id()
!= StepId::derive(
self.identity.execution(),
self.identity.attempt(),
step.index(),
)
{
return Err(ExecutionError::ForgedStepId {
index: step.index(),
});
}
Ok(())
}
fn check_within_grant(&self, index: u64) -> Result<(), ExecutionError> {
if index >= u64::from(self.capabilities.max_labeled_steps()) {
return Err(ExecutionError::StepBudgetExhausted {
index,
granted: self.capabilities.max_labeled_steps(),
});
}
Ok(())
}
}
impl From<&ExecutionStep> for WireExecutionStep {
fn from(value: &ExecutionStep) -> Self {
Self {
index: value.index(),
step_id: value.id().as_str().to_owned(),
__buffa_unknown_fields: buffa::UnknownFields::default(),
}
}
}
impl From<&WireExecutionStep> for ExecutionStep {
fn from(value: &WireExecutionStep) -> Self {
Self {
index: value.index,
id: StepId(value.step_id.clone()),
}
}
}
impl From<&ExecutionCapabilities> for WireExecutionCapabilities {
fn from(value: &ExecutionCapabilities) -> Self {
Self {
granted: value
.granted()
.names()
.into_iter()
.map(str::to_owned)
.collect(),
max_labeled_steps: value.max_labeled_steps(),
__buffa_unknown_fields: buffa::UnknownFields::default(),
}
}
}
impl TryFrom<&WireExecutionCapabilities> for ExecutionCapabilities {
type Error = ExecutionError;
fn try_from(value: &WireExecutionCapabilities) -> Result<Self, Self::Error> {
let (granted, unknown) =
CapabilitySet::from_names(value.granted.iter().map(String::as_str));
if !unknown.is_empty() {
return Err(ExecutionError::UnknownCapability {
unknown: unknown.join(", "),
});
}
Self::new(granted, value.max_labeled_steps)
}
}
impl From<&ExecutionGrant> for WireExecutionGrant {
fn from(value: &ExecutionGrant) -> Self {
Self {
opening: buffa::MessageField::some(WireExecutionLabel::from(value.opening())),
owner_id: value.owner().as_str().to_owned(),
last_committed_step: value
.last_committed_step()
.map(WireExecutionLabel::from)
.into(),
budget_nanos: u64::try_from(value.budget().as_nanos()).unwrap_or(u64::MAX),
capabilities: buffa::MessageField::some(WireExecutionCapabilities::from(
&value.capabilities(),
)),
claim_attempt_id: value.claim_attempt().as_str().to_owned(),
audience: value.audience().as_str().to_owned(),
tenant_id: value.tenant().as_str().to_owned(),
conversation_id: value.conversation().as_str().to_owned(),
__buffa_unknown_fields: buffa::UnknownFields::default(),
}
}
}
impl TryFrom<&WireExecutionGrant> for ExecutionGrant {
type Error = ExecutionError;
fn try_from(value: &WireExecutionGrant) -> Result<Self, Self::Error> {
let capabilities =
value
.capabilities
.as_option()
.ok_or_else(|| ExecutionError::Malformed {
field: "capabilities".to_owned(),
reason: "an attempt with no declared grant would hold whatever it could reach"
.to_owned(),
})?;
let opening = value
.opening
.as_option()
.ok_or_else(|| ExecutionError::Malformed {
field: "opening".to_owned(),
reason: "the grant names the execution, attempt, and fence this turn runs as"
.to_owned(),
})?;
Self::from_declared(
ExecutionLabel::try_from(opening)?,
OwnerId::new(value.owner_id.clone()),
AttemptId::new(value.claim_attempt_id.clone()),
ExecutionAudience::new(value.audience.clone())?,
value
.last_committed_step
.as_option()
.map(ExecutionLabel::try_from)
.transpose()?,
Duration::from_nanos(value.budget_nanos),
ExecutionCapabilities::try_from(capabilities)?,
TenantId::new(value.tenant_id.clone()),
ModelConversationId::new(value.conversation_id.clone()),
)
}
}
impl From<&ExecutionLabel> for WireExecutionLabel {
fn from(value: &ExecutionLabel) -> Self {
Self {
protocol_version: value.version().get(),
execution_id: value.identity().execution().as_str().to_owned(),
attempt_id: value.identity().attempt().as_str().to_owned(),
fence: value.identity().fence().get(),
step: buffa::MessageField::some(WireExecutionStep::from(value.step())),
__buffa_unknown_fields: buffa::UnknownFields::default(),
}
}
}
impl TryFrom<&WireExecutionLabel> for ExecutionLabel {
type Error = ExecutionError;
fn try_from(value: &WireExecutionLabel) -> Result<Self, Self::Error> {
let step = value
.step
.as_option()
.ok_or_else(|| ExecutionError::Malformed {
field: "step".to_owned(),
reason: "an unnumbered frame has no place in the attempt's sequence".to_owned(),
})?;
Ok(Self {
version: ExecutionProtocolVersion::new(value.protocol_version),
identity: ExecutionIdentity::new(
ExecutionId::new(value.execution_id.clone()),
AttemptId::new(value.attempt_id.clone()),
FencingToken::new(value.fence),
)?,
step: ExecutionStep::from(step),
})
}
}
#[must_use]
pub fn now() -> MonotonicInstant {
static CLOCK: OnceLock<ProductionClock> = OnceLock::new();
CLOCK.get_or_init(ProductionClock::new).now()
}
#[must_use]
pub fn connect_error_from_execution(error: &ExecutionError) -> connectrpc::ConnectError {
let message = error.to_string();
match error {
ExecutionError::Malformed { .. }
| ExecutionError::VersionMismatch { .. }
| ExecutionError::UnknownCapability { .. }
| ExecutionError::ForgedStepId { .. }
| ExecutionError::WrongAudience { .. } => {
connectrpc::ConnectError::invalid_argument(message)
}
ExecutionError::ForeignAttempt { .. }
| ExecutionError::StaleFence { .. }
| ExecutionError::DuplicateStep { .. }
| ExecutionError::OutOfOrderStep { .. }
| ExecutionError::StepBudgetExhausted { .. } => {
connectrpc::ConnectError::failed_precondition(message)
}
}
}
pub fn required_label(
label: Option<&WireExecutionLabel>,
) -> Result<ExecutionLabel, ExecutionError> {
let wire = label.ok_or_else(|| ExecutionError::Malformed {
field: "label".to_owned(),
reason: "every frame declares the execution, attempt, fence, and step it belongs to"
.to_owned(),
})?;
ExecutionLabel::try_from(wire)
}
pub fn required_grant(
grant: Option<&WireExecutionGrant>,
) -> Result<ExecutionGrant, ExecutionError> {
let wire = grant.ok_or_else(|| ExecutionError::Malformed {
field: "execution".to_owned(),
reason: "a turn that runs under no grant holds no bounded capability and no budget"
.to_owned(),
})?;
ExecutionGrant::try_from(wire)
}
#[cfg(test)]
mod tests;