#![forbid(unsafe_code)]
#![warn(missing_docs)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used))]
#[cfg(any(test, feature = "conformance"))]
#[cfg_attr(docsrs, doc(cfg(feature = "conformance")))]
pub mod conformance;
pub mod memory;
pub mod prelude {
pub use crate::{
AgentStore, CommandReceipt, CommandStore, EffectTransition, InMemoryStore, LeaseStore,
LeaseToken, LoadedBranch, NewEffect, NewSpendEntry, OwnerId, PendingCommandReceipt,
PoolName, SessionStore, SpendStore, StepCommit, StepCommitResult, StoreError,
TerminalRunStatus,
};
}
use allen_types::ids::{
CommandId, EffectId, EntryId, InvalidIdError, OwnerFence, RunId, ScopeEpochs, SessionId,
SessionRevision, TenantId,
};
use allen_types::journal::{EffectEvent, EffectRecord, IllegalEffectTransition};
use allen_types::lifecycle::CommandSettlement;
use allen_types::money::{BillingClass, CostBasis, MicroUsd, SpendCategory};
use allen_types::session::{RunStatus, SessionEntry};
use futures_util::future::BoxFuture;
use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;
use std::time::Duration;
pub use memory::InMemoryStore;
macro_rules! store_string_id {
($(#[$meta:meta])* $name:ident) => {
$(#[$meta])*
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct $name(String);
impl $name {
pub fn try_new(value: impl Into<String>) -> Result<Self, InvalidIdError> {
let value = value.into();
if value.trim().is_empty() {
return Err(InvalidIdError::Empty);
}
if value.contains('\0') {
return Err(InvalidIdError::ContainsNul);
}
Ok(Self(value))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn into_inner(self) -> String {
self.0
}
}
impl fmt::Display for $name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl AsRef<str> for $name {
fn as_ref(&self) -> &str {
&self.0
}
}
impl TryFrom<String> for $name {
type Error = InvalidIdError;
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::try_new(value)
}
}
impl TryFrom<&str> for $name {
type Error = InvalidIdError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Self::try_new(value)
}
}
impl FromStr for $name {
type Err = InvalidIdError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::try_new(s)
}
}
impl From<$name> for String {
fn from(value: $name) -> Self {
value.0
}
}
};
}
store_string_id!(
OwnerId
);
store_string_id!(
PoolName
);
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TerminalRunStatus {
Completed,
Failed,
Cancelled,
Parked,
}
impl TerminalRunStatus {
#[must_use]
pub const fn as_run_status(self) -> RunStatus {
match self {
Self::Completed => RunStatus::Completed,
Self::Failed => RunStatus::Failed,
Self::Cancelled => RunStatus::Cancelled,
Self::Parked => RunStatus::Parked,
}
}
#[must_use]
pub const fn as_str(self) -> &'static str {
self.as_run_status().as_str()
}
}
impl From<TerminalRunStatus> for RunStatus {
fn from(status: TerminalRunStatus) -> Self {
status.as_run_status()
}
}
impl fmt::Display for TerminalRunStatus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct LeaseToken {
tenant_id: TenantId,
session_id: SessionId,
run_id: RunId,
owner_id: OwnerId,
fence: OwnerFence,
expires_at_ms: i64,
}
impl LeaseToken {
#[must_use]
pub fn from_backend(
tenant_id: TenantId,
session_id: SessionId,
run_id: RunId,
owner_id: OwnerId,
fence: OwnerFence,
expires_at_ms: i64,
) -> Self {
Self {
tenant_id,
session_id,
run_id,
owner_id,
fence,
expires_at_ms,
}
}
#[must_use]
pub fn tenant_id(&self) -> &TenantId {
&self.tenant_id
}
#[must_use]
pub fn session_id(&self) -> &SessionId {
&self.session_id
}
#[must_use]
pub fn run_id(&self) -> &RunId {
&self.run_id
}
#[must_use]
pub fn owner_id(&self) -> &OwnerId {
&self.owner_id
}
#[must_use]
pub const fn fence(&self) -> OwnerFence {
self.fence
}
#[must_use]
pub const fn expires_at_ms(&self) -> i64 {
self.expires_at_ms
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct CommandReceipt {
pub tenant_id: TenantId,
pub session_id: SessionId,
pub command_id: CommandId,
pub settlement: CommandSettlement,
pub resulting_revision: SessionRevision,
pub epochs: ScopeEpochs,
pub payload_json: serde_json::Value,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PendingCommandReceipt {
pub command_id: CommandId,
pub settlement: CommandSettlement,
pub payload_json: serde_json::Value,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct NewEffect {
pub effect_id: EffectId,
pub idempotency_key: String,
pub action_sha256: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct EffectTransition {
pub effect_id: EffectId,
pub event: EffectEvent,
pub result_digest: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct NewSpendEntry {
pub billing_class: BillingClass,
pub category: SpendCategory,
pub cost: MicroUsd,
pub basis: CostBasis,
pub recorded_at_ms: i64,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StepCommit {
pub expected_revision: SessionRevision,
pub entries: Vec<SessionEntry>,
pub new_leaf: Option<EntryId>,
pub bump_branch_epoch: bool,
pub bump_activity_epoch: bool,
pub prepare_effects: Vec<NewEffect>,
pub effect_transitions: Vec<EffectTransition>,
pub spend: Vec<NewSpendEntry>,
pub receipt: Option<PendingCommandReceipt>,
}
impl StepCommit {
#[must_use]
pub fn empty(expected_revision: SessionRevision) -> Self {
Self {
expected_revision,
entries: Vec::new(),
new_leaf: None,
bump_branch_epoch: false,
bump_activity_epoch: false,
prepare_effects: Vec::new(),
effect_transitions: Vec::new(),
spend: Vec::new(),
receipt: None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct StepCommitResult {
pub new_revision: SessionRevision,
pub epochs: ScopeEpochs,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LoadedBranch {
pub revision: SessionRevision,
pub epochs: ScopeEpochs,
pub entries: Vec<SessionEntry>,
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum StoreError {
NotFound(String),
TenantMismatch,
StaleFence {
expected: OwnerFence,
actual: OwnerFence,
},
RevisionConflict {
expected: SessionRevision,
actual: SessionRevision,
},
LeaseHeldByOther {
expires_at_ms: i64,
},
IllegalTransition(IllegalEffectTransition),
DuplicateIdempotencyKey(String),
SchemaDrift(String),
Backend(String),
}
impl From<IllegalEffectTransition> for StoreError {
fn from(err: IllegalEffectTransition) -> Self {
Self::IllegalTransition(err)
}
}
impl fmt::Display for StoreError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NotFound(msg)
| Self::DuplicateIdempotencyKey(msg)
| Self::SchemaDrift(msg)
| Self::Backend(msg) => f.write_str(msg),
Self::IllegalTransition(err) => err.fmt(f),
Self::TenantMismatch => f.write_str("tenant mismatch"),
Self::StaleFence { expected, actual } => {
write!(f, "stale owner fence: expected {expected}, actual {actual}")
}
Self::RevisionConflict { expected, actual } => write!(
f,
"session revision conflict: expected {expected}, actual {actual}"
),
Self::LeaseHeldByOther { expires_at_ms } => {
write!(f, "lease held by another owner until {expires_at_ms}")
}
}
}
}
impl std::error::Error for StoreError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::IllegalTransition(err) => Some(err),
_ => None,
}
}
}
pub trait LeaseStore: Send + Sync {
fn enqueue_run<'a>(
&'a self,
tenant_id: &'a TenantId,
session_id: &'a SessionId,
run_id: &'a RunId,
pool_name: &'a PoolName,
) -> BoxFuture<'a, Result<(), StoreError>>;
fn acquire_session_lease<'a>(
&'a self,
tenant_id: &'a TenantId,
session_id: &'a SessionId,
owner_id: &'a OwnerId,
ttl: Duration,
) -> BoxFuture<'a, Result<LeaseToken, StoreError>>;
fn claim_queued_run<'a>(
&'a self,
owner_id: &'a OwnerId,
pool_name: &'a PoolName,
ttl: Duration,
) -> BoxFuture<'a, Result<Option<LeaseToken>, StoreError>>;
fn reclaim_expired_run<'a>(
&'a self,
owner_id: &'a OwnerId,
pool_name: &'a PoolName,
ttl: Duration,
) -> BoxFuture<'a, Result<Option<LeaseToken>, StoreError>>;
fn renew_lease<'a>(
&'a self,
lease: &'a LeaseToken,
ttl: Duration,
) -> BoxFuture<'a, Result<LeaseToken, StoreError>>;
fn finish_run<'a>(
&'a self,
lease: &'a LeaseToken,
status: TerminalRunStatus,
summary_code: Option<&'a str>,
) -> BoxFuture<'a, Result<(), StoreError>>;
fn recover_expired_run<'a>(
&'a self,
tenant_id: &'a TenantId,
run_id: &'a RunId,
new_owner_id: &'a OwnerId,
ttl: Duration,
) -> BoxFuture<'a, Result<(LeaseToken, Vec<EffectRecord>), StoreError>>;
fn force_recover_run<'a>(
&'a self,
tenant_id: &'a TenantId,
run_id: &'a RunId,
new_owner_id: &'a OwnerId,
ttl: Duration,
) -> BoxFuture<'a, Result<LeaseToken, StoreError>>;
}
pub trait CommandStore: Send + Sync {
fn lookup_receipt<'a>(
&'a self,
tenant_id: &'a TenantId,
session_id: &'a SessionId,
command_id: &'a CommandId,
) -> BoxFuture<'a, Result<Option<CommandReceipt>, StoreError>>;
fn commit_step<'a>(
&'a self,
lease: &'a LeaseToken,
commit: StepCommit,
) -> BoxFuture<'a, Result<StepCommitResult, StoreError>>;
fn list_unknown_effects<'a>(
&'a self,
tenant_id: &'a TenantId,
run_id: &'a RunId,
) -> BoxFuture<'a, Result<Vec<EffectRecord>, StoreError>>;
fn list_claimed_effects<'a>(
&'a self,
tenant_id: &'a TenantId,
run_id: &'a RunId,
) -> BoxFuture<'a, Result<Vec<EffectRecord>, StoreError>>;
}
pub trait SessionStore: Send + Sync {
fn create_session<'a>(
&'a self,
tenant_id: &'a TenantId,
session_id: &'a SessionId,
parent_session_id: Option<&'a SessionId>,
) -> BoxFuture<'a, Result<StepCommitResult, StoreError>>;
fn load_branch<'a>(
&'a self,
tenant_id: &'a TenantId,
session_id: &'a SessionId,
leaf: Option<&'a EntryId>,
) -> BoxFuture<'a, Result<LoadedBranch, StoreError>>;
}
pub trait SpendStore: Send + Sync {
fn sum_spend_since<'a>(
&'a self,
tenant_id: &'a TenantId,
since_ms: i64,
billing_class: Option<BillingClass>,
) -> BoxFuture<'a, Result<MicroUsd, StoreError>>;
fn sum_run_spend<'a>(
&'a self,
tenant_id: &'a TenantId,
run_id: &'a RunId,
) -> BoxFuture<'a, Result<MicroUsd, StoreError>>;
}
pub trait AgentStore: LeaseStore + CommandStore + SessionStore + SpendStore {}
impl<T: LeaseStore + CommandStore + SessionStore + SpendStore> AgentStore for T {}
impl<T: LeaseStore + ?Sized> LeaseStore for std::sync::Arc<T> {
fn enqueue_run<'a>(
&'a self,
tenant_id: &'a TenantId,
session_id: &'a SessionId,
run_id: &'a RunId,
pool_name: &'a PoolName,
) -> BoxFuture<'a, Result<(), StoreError>> {
(**self).enqueue_run(tenant_id, session_id, run_id, pool_name)
}
fn acquire_session_lease<'a>(
&'a self,
tenant_id: &'a TenantId,
session_id: &'a SessionId,
owner_id: &'a OwnerId,
ttl: Duration,
) -> BoxFuture<'a, Result<LeaseToken, StoreError>> {
(**self).acquire_session_lease(tenant_id, session_id, owner_id, ttl)
}
fn claim_queued_run<'a>(
&'a self,
owner_id: &'a OwnerId,
pool_name: &'a PoolName,
ttl: Duration,
) -> BoxFuture<'a, Result<Option<LeaseToken>, StoreError>> {
(**self).claim_queued_run(owner_id, pool_name, ttl)
}
fn reclaim_expired_run<'a>(
&'a self,
owner_id: &'a OwnerId,
pool_name: &'a PoolName,
ttl: Duration,
) -> BoxFuture<'a, Result<Option<LeaseToken>, StoreError>> {
(**self).reclaim_expired_run(owner_id, pool_name, ttl)
}
fn renew_lease<'a>(
&'a self,
lease: &'a LeaseToken,
ttl: Duration,
) -> BoxFuture<'a, Result<LeaseToken, StoreError>> {
(**self).renew_lease(lease, ttl)
}
fn finish_run<'a>(
&'a self,
lease: &'a LeaseToken,
status: TerminalRunStatus,
summary_code: Option<&'a str>,
) -> BoxFuture<'a, Result<(), StoreError>> {
(**self).finish_run(lease, status, summary_code)
}
fn recover_expired_run<'a>(
&'a self,
tenant_id: &'a TenantId,
run_id: &'a RunId,
new_owner_id: &'a OwnerId,
ttl: Duration,
) -> BoxFuture<'a, Result<(LeaseToken, Vec<EffectRecord>), StoreError>> {
(**self).recover_expired_run(tenant_id, run_id, new_owner_id, ttl)
}
fn force_recover_run<'a>(
&'a self,
tenant_id: &'a TenantId,
run_id: &'a RunId,
new_owner_id: &'a OwnerId,
ttl: Duration,
) -> BoxFuture<'a, Result<LeaseToken, StoreError>> {
(**self).force_recover_run(tenant_id, run_id, new_owner_id, ttl)
}
}
impl<T: CommandStore + ?Sized> CommandStore for std::sync::Arc<T> {
fn lookup_receipt<'a>(
&'a self,
tenant_id: &'a TenantId,
session_id: &'a SessionId,
command_id: &'a CommandId,
) -> BoxFuture<'a, Result<Option<CommandReceipt>, StoreError>> {
(**self).lookup_receipt(tenant_id, session_id, command_id)
}
fn commit_step<'a>(
&'a self,
lease: &'a LeaseToken,
commit: StepCommit,
) -> BoxFuture<'a, Result<StepCommitResult, StoreError>> {
(**self).commit_step(lease, commit)
}
fn list_unknown_effects<'a>(
&'a self,
tenant_id: &'a TenantId,
run_id: &'a RunId,
) -> BoxFuture<'a, Result<Vec<EffectRecord>, StoreError>> {
(**self).list_unknown_effects(tenant_id, run_id)
}
fn list_claimed_effects<'a>(
&'a self,
tenant_id: &'a TenantId,
run_id: &'a RunId,
) -> BoxFuture<'a, Result<Vec<EffectRecord>, StoreError>> {
(**self).list_claimed_effects(tenant_id, run_id)
}
}
impl<T: SessionStore + ?Sized> SessionStore for std::sync::Arc<T> {
fn create_session<'a>(
&'a self,
tenant_id: &'a TenantId,
session_id: &'a SessionId,
parent_session_id: Option<&'a SessionId>,
) -> BoxFuture<'a, Result<StepCommitResult, StoreError>> {
(**self).create_session(tenant_id, session_id, parent_session_id)
}
fn load_branch<'a>(
&'a self,
tenant_id: &'a TenantId,
session_id: &'a SessionId,
leaf: Option<&'a EntryId>,
) -> BoxFuture<'a, Result<LoadedBranch, StoreError>> {
(**self).load_branch(tenant_id, session_id, leaf)
}
}
impl<T: SpendStore + ?Sized> SpendStore for std::sync::Arc<T> {
fn sum_spend_since<'a>(
&'a self,
tenant_id: &'a TenantId,
since_ms: i64,
billing_class: Option<BillingClass>,
) -> BoxFuture<'a, Result<MicroUsd, StoreError>> {
(**self).sum_spend_since(tenant_id, since_ms, billing_class)
}
fn sum_run_spend<'a>(
&'a self,
tenant_id: &'a TenantId,
run_id: &'a RunId,
) -> BoxFuture<'a, Result<MicroUsd, StoreError>> {
(**self).sum_run_spend(tenant_id, run_id)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn owner_id_and_pool_name_reject_empty_whitespace_and_nul() {
assert_eq!(OwnerId::try_new(""), Err(InvalidIdError::Empty));
assert_eq!(OwnerId::try_new(" \t\n "), Err(InvalidIdError::Empty));
assert_eq!(
OwnerId::try_new("worker\0id"),
Err(InvalidIdError::ContainsNul)
);
assert_eq!(PoolName::try_new(""), Err(InvalidIdError::Empty));
assert_eq!(
PoolName::try_new("pool\0name"),
Err(InvalidIdError::ContainsNul)
);
let owner = OwnerId::try_new("worker-1").unwrap();
assert_eq!(owner.as_str(), "worker-1");
let pool = PoolName::try_new("scanner-pool").unwrap();
assert_eq!(pool.as_str(), "scanner-pool");
assert!(serde_json::from_str::<OwnerId>("\"\"").is_err());
assert!(serde_json::from_str::<PoolName>("\" \"").is_err());
}
#[test]
fn terminal_run_status_maps_only_terminal_statuses() {
assert_eq!(
TerminalRunStatus::Completed.as_run_status(),
RunStatus::Completed
);
assert_eq!(TerminalRunStatus::Failed.as_run_status(), RunStatus::Failed);
assert_eq!(
TerminalRunStatus::Cancelled.as_run_status(),
RunStatus::Cancelled
);
assert_eq!(TerminalRunStatus::Parked.as_run_status(), RunStatus::Parked);
}
}