use ff_core::contracts::{
MarkLeaseExpiredArgs, MarkLeaseExpiredResult, RenewLeaseArgs, RenewLeaseResult,
RevokeLeaseArgs, RevokeLeaseResult,
};
use crate::error::ScriptError;
use ff_core::keys::ExecKeyContext;
use ff_core::types::TimestampMs;
use crate::result::{FcallResult, FromFcallResult};
impl FromFcallResult for RenewLeaseResult {
fn from_fcall_result(raw: &ferriskey::Value) -> Result<Self, ScriptError> {
let r = FcallResult::parse(raw)?.into_success()?;
let expires_str = r.field_str(0);
let expires_ms: i64 = expires_str
.parse()
.map_err(|_| ScriptError::Parse(format!("invalid expires_at: {expires_str}")))?;
Ok(RenewLeaseResult::Renewed {
expires_at: TimestampMs::from_millis(expires_ms),
})
}
}
impl FromFcallResult for MarkLeaseExpiredResult {
fn from_fcall_result(raw: &ferriskey::Value) -> Result<Self, ScriptError> {
let r = FcallResult::parse(raw)?.into_success()?;
match r.status.as_str() {
"OK" => Ok(MarkLeaseExpiredResult::MarkedExpired),
"ALREADY_SATISFIED" => Ok(MarkLeaseExpiredResult::AlreadySatisfied {
reason: r.field_str(0),
}),
other => Err(ScriptError::Parse(format!(
"unexpected status from ff_mark_lease_expired_if_due: {other}"
))),
}
}
}
impl FromFcallResult for RevokeLeaseResult {
fn from_fcall_result(raw: &ferriskey::Value) -> Result<Self, ScriptError> {
let r = FcallResult::parse(raw)?.into_success()?;
match r.status.as_str() {
"OK" => {
Ok(RevokeLeaseResult::Revoked {
lease_id: r.field_str(1),
lease_epoch: r.field_str(2),
})
}
"ALREADY_SATISFIED" => Ok(RevokeLeaseResult::AlreadySatisfied {
reason: r.field_str(0),
}),
other => Err(ScriptError::Parse(format!(
"unexpected status from ff_revoke_lease: {other}"
))),
}
}
}
ff_function! {
pub ff_renew_lease(args: RenewLeaseArgs) -> RenewLeaseResult {
keys(ctx: &ExecKeyContext) {
ctx.core(),
ctx.lease_current(),
ctx.lease_history(),
format!("ff:idx:{}:lease_expiry", ctx.hash_tag()),
}
argv {
args.execution_id.to_string(),
args.attempt_index.to_string(),
args.attempt_id.to_string(),
args.lease_id.to_string(),
args.lease_epoch.to_string(),
args.lease_ttl_ms.to_string(),
args.lease_history_grace_ms.to_string(),
}
}
pub ff_mark_lease_expired_if_due(args: MarkLeaseExpiredArgs) -> MarkLeaseExpiredResult {
keys(ctx: &ExecKeyContext) {
ctx.core(),
ctx.lease_current(),
format!("ff:idx:{}:lease_expiry", ctx.hash_tag()),
ctx.lease_history(),
}
argv {
args.execution_id.to_string(),
}
}
pub ff_revoke_lease(args: RevokeLeaseArgs) -> RevokeLeaseResult {
keys(ctx: &ExecKeyContext) {
ctx.core(),
ctx.lease_current(),
ctx.lease_history(),
format!("ff:idx:{}:lease_expiry", ctx.hash_tag()),
format!("ff:idx:{}:worker:{}:leases", ctx.hash_tag(), args.worker_instance_id),
}
argv {
args.execution_id.to_string(),
args.expected_lease_id.as_deref().unwrap_or("").to_string(),
args.reason.clone(),
}
}
}