use crate::{
CommandReceipt, CommandStore, LeaseStore, LeaseToken, LoadedBranch, OwnerId, PoolName,
SessionStore, SpendStore, StepCommit, StepCommitResult, StoreError, TerminalRunStatus,
};
use allen_types::ids::{
CommandId, EffectId, EntryId, OwnerFence, RunId, ScopeEpochs, SessionId, SessionRevision,
TenantId,
};
use allen_types::journal::{EffectEvent, EffectRecord, EffectState, transition_effect};
use allen_types::money::{BillingClass, CostBasis, MicroUsd, SpendCategory};
use allen_types::session::{RunStatus, SessionEntry};
use futures_util::future::BoxFuture;
use std::collections::BTreeMap;
use std::fmt;
use std::sync::{Mutex, MutexGuard, PoisonError};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
fn now_ms() -> i64 {
i64::try_from(
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis(),
)
.unwrap_or(i64::MAX)
}
fn expires_at_from(now: i64, ttl: Duration) -> i64 {
let ttl_ms = i64::try_from(ttl.as_millis()).unwrap_or(i64::MAX);
now.saturating_add(ttl_ms)
}
fn advance_fence(current: Option<OwnerFence>) -> Result<OwnerFence, StoreError> {
match current {
None => Ok(OwnerFence::INITIAL),
Some(f) => f
.next()
.ok_or_else(|| StoreError::Backend("fence overflow".into())),
}
}
fn check_running_fence(run: &RunRow, lease: &LeaseToken) -> Result<(), StoreError> {
match run.fence {
Some(actual) if actual != lease.fence() => {
return Err(StoreError::StaleFence {
expected: lease.fence(),
actual,
});
}
None => {
if run.status != RunStatus::Running {
return Err(StoreError::Backend(format!(
"run {} is not running (status: {})",
lease.run_id(),
run.status
)));
}
return Err(StoreError::Backend(format!(
"run {} has no active ownership fence",
lease.run_id()
)));
}
Some(_) => {}
}
if run.status != RunStatus::Running {
return Err(StoreError::Backend(format!(
"run {} is not running (status: {})",
lease.run_id(),
run.status
)));
}
Ok(())
}
fn transition_claimed_effects_to_unknown(
effects: &mut BTreeMap<EffectId, EffectRecord>,
tenant_id: &TenantId,
run_id: &RunId,
new_fence: OwnerFence,
) -> Result<Vec<EffectRecord>, StoreError> {
let mut unknown = Vec::new();
for eff in effects.values_mut() {
if &eff.tenant_id == tenant_id && &eff.run_id == run_id && eff.state == EffectState::Claimed
{
eff.state = transition_effect(eff.state, EffectEvent::RecoverCrash)?;
eff.fence = new_fence;
unknown.push(eff.clone());
}
}
Ok(unknown)
}
#[derive(Clone)]
struct SessionRow {
tenant_id: TenantId,
_parent_session_id: Option<SessionId>,
revision: SessionRevision,
epochs: ScopeEpochs,
active_leaf: Option<EntryId>,
entries: BTreeMap<EntryId, SessionEntry>,
}
#[derive(Clone)]
struct RunRow {
tenant_id: TenantId,
session_id: SessionId,
run_id: RunId,
pool_name: Option<PoolName>,
status: RunStatus,
owner_id: Option<OwnerId>,
fence: Option<OwnerFence>,
expires_at_ms: i64,
summary_code: Option<String>,
}
#[derive(Clone)]
struct SpendRow {
tenant_id: TenantId,
_session_id: SessionId,
run_id: RunId,
billing_class: BillingClass,
_category: SpendCategory,
cost: MicroUsd,
_basis: CostBasis,
recorded_at_ms: i64,
}
#[derive(Default)]
struct State {
sessions: BTreeMap<SessionId, SessionRow>,
runs: BTreeMap<RunId, RunRow>,
effects: BTreeMap<EffectId, EffectRecord>,
effect_idempotency: BTreeMap<(TenantId, String), EffectId>,
receipts: BTreeMap<(TenantId, SessionId, CommandId), CommandReceipt>,
spend: Vec<SpendRow>,
next_run_seq: u64,
}
#[derive(Default)]
pub struct InMemoryStore {
state: Mutex<State>,
}
impl fmt::Debug for InMemoryStore {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("InMemoryStore").finish_non_exhaustive()
}
}
impl InMemoryStore {
#[must_use]
pub fn new() -> Self {
Self::default()
}
fn lock_state(&self) -> MutexGuard<'_, State> {
self.state.lock().unwrap_or_else(PoisonError::into_inner)
}
}
impl LeaseStore for InMemoryStore {
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>> {
Box::pin(async move {
let mut st = self.lock_state();
let sess = st
.sessions
.get(session_id)
.ok_or_else(|| StoreError::NotFound(format!("session {session_id} not found")))?;
if &sess.tenant_id != tenant_id {
return Err(StoreError::TenantMismatch);
}
if st.runs.contains_key(run_id) {
return Err(StoreError::DuplicateIdempotencyKey(format!(
"run {run_id} already exists"
)));
}
st.runs.insert(
run_id.clone(),
RunRow {
tenant_id: tenant_id.clone(),
session_id: session_id.clone(),
run_id: run_id.clone(),
pool_name: Some(pool_name.clone()),
status: RunStatus::Queued,
owner_id: None,
fence: None,
expires_at_ms: 0,
summary_code: None,
},
);
Ok(())
})
}
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>> {
Box::pin(async move {
let mut st = self.lock_state();
let sess = st
.sessions
.get(session_id)
.ok_or_else(|| StoreError::NotFound(format!("session {session_id} not found")))?;
if &sess.tenant_id != tenant_id {
return Err(StoreError::TenantMismatch);
}
let now = now_ms();
let expires_at_ms = expires_at_from(now, ttl);
for run in st.runs.values() {
if &run.session_id == session_id
&& run.status == RunStatus::Running
&& run.expires_at_ms > now
&& run.owner_id.as_ref() != Some(owner_id)
{
return Err(StoreError::LeaseHeldByOther {
expires_at_ms: run.expires_at_ms,
});
}
}
let existing_run_id = st
.runs
.values()
.find(|r| &r.session_id == session_id && r.status == RunStatus::Running)
.map(|r| r.run_id.clone());
let superseded = existing_run_id.is_some();
let run_id = if let Some(id) = existing_run_id {
id
} else {
st.next_run_seq += 1;
let id = RunId::try_new(format!("run:interactive:{}", st.next_run_seq))
.map_err(|e| StoreError::Backend(format!("generated invalid run id: {e}")))?;
st.runs.insert(
id.clone(),
RunRow {
tenant_id: tenant_id.clone(),
session_id: session_id.clone(),
run_id: id.clone(),
pool_name: None,
status: RunStatus::Running,
owner_id: None,
fence: None,
expires_at_ms: 0,
summary_code: None,
},
);
id
};
let (run_tenant_id, run_session_id, next_fence) = {
let run = st
.runs
.get_mut(&run_id)
.ok_or_else(|| StoreError::Backend(format!("run {run_id} disappeared")))?;
let next_fence = advance_fence(run.fence)?;
run.status = RunStatus::Running;
run.owner_id = Some(owner_id.clone());
run.fence = Some(next_fence);
run.expires_at_ms = expires_at_ms;
(run.tenant_id.clone(), run.session_id.clone(), next_fence)
};
if superseded {
let _ = transition_claimed_effects_to_unknown(
&mut st.effects,
tenant_id,
&run_id,
next_fence,
)?;
}
Ok(LeaseToken::from_backend(
run_tenant_id,
run_session_id,
run_id,
owner_id.clone(),
next_fence,
expires_at_ms,
))
})
}
fn claim_queued_run<'a>(
&'a self,
owner_id: &'a OwnerId,
pool_name: &'a PoolName,
ttl: Duration,
) -> BoxFuture<'a, Result<Option<LeaseToken>, StoreError>> {
Box::pin(async move {
let mut st = self.lock_state();
let now = now_ms();
let expires_at_ms = expires_at_from(now, ttl);
let candidate_id = st
.runs
.values()
.find(|r| r.status == RunStatus::Queued && r.pool_name.as_ref() == Some(pool_name))
.map(|r| r.run_id.clone());
let Some(run_id) = candidate_id else {
return Ok(None);
};
let run = st
.runs
.get_mut(&run_id)
.ok_or_else(|| StoreError::Backend(format!("run {run_id} disappeared")))?;
let next_fence = advance_fence(run.fence)?;
run.status = RunStatus::Running;
run.owner_id = Some(owner_id.clone());
run.fence = Some(next_fence);
run.expires_at_ms = expires_at_ms;
Ok(Some(LeaseToken::from_backend(
run.tenant_id.clone(),
run.session_id.clone(),
run.run_id.clone(),
owner_id.clone(),
next_fence,
expires_at_ms,
)))
})
}
fn reclaim_expired_run<'a>(
&'a self,
owner_id: &'a OwnerId,
pool_name: &'a PoolName,
ttl: Duration,
) -> BoxFuture<'a, Result<Option<LeaseToken>, StoreError>> {
Box::pin(async move {
let mut st = self.lock_state();
let now = now_ms();
let expires_at_ms = expires_at_from(now, ttl);
let candidate_id = st
.runs
.values()
.filter(|r| {
r.status == RunStatus::Running
&& r.pool_name.as_ref() == Some(pool_name)
&& r.expires_at_ms <= now
})
.min_by(|a, b| {
a.expires_at_ms
.cmp(&b.expires_at_ms)
.then_with(|| a.run_id.cmp(&b.run_id))
})
.map(|r| r.run_id.clone());
let Some(run_id) = candidate_id else {
return Ok(None);
};
let (tenant_id, session_id, next_fence) = {
let run = st
.runs
.get_mut(&run_id)
.ok_or_else(|| StoreError::Backend(format!("run {run_id} disappeared")))?;
let next_fence = advance_fence(run.fence)?;
run.status = RunStatus::Running;
run.owner_id = Some(owner_id.clone());
run.fence = Some(next_fence);
run.expires_at_ms = expires_at_ms;
(run.tenant_id.clone(), run.session_id.clone(), next_fence)
};
let _ = transition_claimed_effects_to_unknown(
&mut st.effects,
&tenant_id,
&run_id,
next_fence,
)?;
Ok(Some(LeaseToken::from_backend(
tenant_id,
session_id,
run_id,
owner_id.clone(),
next_fence,
expires_at_ms,
)))
})
}
fn renew_lease<'a>(
&'a self,
lease: &'a LeaseToken,
ttl: Duration,
) -> BoxFuture<'a, Result<LeaseToken, StoreError>> {
Box::pin(async move {
let mut st = self.lock_state();
let run = st
.runs
.get_mut(lease.run_id())
.ok_or_else(|| StoreError::NotFound(format!("run {} not found", lease.run_id())))?;
if &run.tenant_id != lease.tenant_id() || &run.session_id != lease.session_id() {
return Err(StoreError::TenantMismatch);
}
check_running_fence(run, lease)?;
let expires_at_ms = expires_at_from(now_ms(), ttl);
run.expires_at_ms = expires_at_ms;
Ok(LeaseToken::from_backend(
lease.tenant_id().clone(),
lease.session_id().clone(),
lease.run_id().clone(),
lease.owner_id().clone(),
lease.fence(),
expires_at_ms,
))
})
}
fn finish_run<'a>(
&'a self,
lease: &'a LeaseToken,
status: TerminalRunStatus,
summary_code: Option<&'a str>,
) -> BoxFuture<'a, Result<(), StoreError>> {
Box::pin(async move {
let mut st = self.lock_state();
let run = st
.runs
.get_mut(lease.run_id())
.ok_or_else(|| StoreError::NotFound(format!("run {} not found", lease.run_id())))?;
if &run.tenant_id != lease.tenant_id() || &run.session_id != lease.session_id() {
return Err(StoreError::TenantMismatch);
}
check_running_fence(run, lease)?;
let next_fence = advance_fence(run.fence)?;
run.fence = Some(next_fence);
run.status = status.as_run_status();
run.summary_code = summary_code.map(str::to_owned);
run.expires_at_ms = 0;
Ok(())
})
}
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>> {
Box::pin(async move {
let mut st = self.lock_state();
let now = now_ms();
let (new_fence, session_id, expires_at_ms) = {
let run = st
.runs
.get_mut(run_id)
.ok_or_else(|| StoreError::NotFound(format!("run {run_id} not found")))?;
if &run.tenant_id != tenant_id {
return Err(StoreError::TenantMismatch);
}
if run.status != RunStatus::Running {
return Err(StoreError::Backend(format!(
"cannot recover run {run_id} in status {}",
run.status
)));
}
if run.expires_at_ms > now {
return Err(StoreError::LeaseHeldByOther {
expires_at_ms: run.expires_at_ms,
});
}
let next_fence = advance_fence(run.fence)?;
let expires_at_ms = expires_at_from(now, ttl);
run.fence = Some(next_fence);
run.owner_id = Some(new_owner_id.clone());
run.status = RunStatus::Running;
run.expires_at_ms = expires_at_ms;
(next_fence, run.session_id.clone(), expires_at_ms)
};
let unknown = transition_claimed_effects_to_unknown(
&mut st.effects,
tenant_id,
run_id,
new_fence,
)?;
let token = LeaseToken::from_backend(
tenant_id.clone(),
session_id,
run_id.clone(),
new_owner_id.clone(),
new_fence,
expires_at_ms,
);
Ok((token, unknown))
})
}
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>> {
Box::pin(async move {
let mut st = self.lock_state();
let now = now_ms();
let (new_fence, session_id, expires_at_ms) = {
let run = st
.runs
.get_mut(run_id)
.ok_or_else(|| StoreError::NotFound(format!("run {run_id} not found")))?;
if &run.tenant_id != tenant_id {
return Err(StoreError::TenantMismatch);
}
if !matches!(run.status, RunStatus::Running | RunStatus::WaitingApproval) {
return Err(StoreError::Backend(format!(
"cannot force-recover run {run_id} in status {}",
run.status
)));
}
let next_fence = advance_fence(run.fence)?;
let expires_at_ms = expires_at_from(now, ttl);
run.fence = Some(next_fence);
run.owner_id = Some(new_owner_id.clone());
run.status = RunStatus::Running;
run.expires_at_ms = expires_at_ms;
(next_fence, run.session_id.clone(), expires_at_ms)
};
let _ = transition_claimed_effects_to_unknown(
&mut st.effects,
tenant_id,
run_id,
new_fence,
)?;
Ok(LeaseToken::from_backend(
tenant_id.clone(),
session_id,
run_id.clone(),
new_owner_id.clone(),
new_fence,
expires_at_ms,
))
})
}
}
impl CommandStore for InMemoryStore {
fn lookup_receipt<'a>(
&'a self,
tenant_id: &'a TenantId,
session_id: &'a SessionId,
command_id: &'a CommandId,
) -> BoxFuture<'a, Result<Option<CommandReceipt>, StoreError>> {
Box::pin(async move {
let st = self.lock_state();
if let Some(sess) = st.sessions.get(session_id)
&& &sess.tenant_id != tenant_id
{
return Err(StoreError::TenantMismatch);
}
Ok(st
.receipts
.get(&(tenant_id.clone(), session_id.clone(), command_id.clone()))
.cloned())
})
}
fn commit_step<'a>(
&'a self,
lease: &'a LeaseToken,
commit: StepCommit,
) -> BoxFuture<'a, Result<StepCommitResult, StoreError>> {
Box::pin(async move {
let mut st = self.lock_state();
let run = st
.runs
.get(lease.run_id())
.ok_or_else(|| StoreError::NotFound(format!("run {} not found", lease.run_id())))?;
if &run.tenant_id != lease.tenant_id() || &run.session_id != lease.session_id() {
return Err(StoreError::TenantMismatch);
}
check_running_fence(run, lease)?;
let sess = st.sessions.get(lease.session_id()).ok_or_else(|| {
StoreError::NotFound(format!("session {} not found", lease.session_id()))
})?;
if &sess.tenant_id != lease.tenant_id() {
return Err(StoreError::TenantMismatch);
}
if sess.revision != commit.expected_revision {
return Err(StoreError::RevisionConflict {
expected: commit.expected_revision,
actual: sess.revision,
});
}
for entry in &commit.entries {
if &entry.tenant_id != lease.tenant_id() || &entry.session_id != lease.session_id()
{
return Err(StoreError::TenantMismatch);
}
}
if let Some(ref receipt) = commit.receipt
&& st.receipts.contains_key(&(
lease.tenant_id().clone(),
lease.session_id().clone(),
receipt.command_id.clone(),
))
{
return Err(StoreError::DuplicateIdempotencyKey(format!(
"command {} already committed",
receipt.command_id
)));
}
let mut pending_effects = st.effects.clone();
let mut pending_idem = st.effect_idempotency.clone();
for eff in &commit.prepare_effects {
if pending_effects.contains_key(&eff.effect_id) {
return Err(StoreError::DuplicateIdempotencyKey(format!(
"effect {} already exists",
eff.effect_id
)));
}
let key = (lease.tenant_id().clone(), eff.idempotency_key.clone());
if pending_idem.contains_key(&key) {
return Err(StoreError::DuplicateIdempotencyKey(
eff.idempotency_key.clone(),
));
}
pending_idem.insert(key, eff.effect_id.clone());
pending_effects.insert(
eff.effect_id.clone(),
EffectRecord {
tenant_id: lease.tenant_id().clone(),
effect_id: eff.effect_id.clone(),
run_id: lease.run_id().clone(),
idempotency_key: eff.idempotency_key.clone(),
fence: lease.fence(),
state: EffectState::Prepared,
action_sha256: eff.action_sha256.clone(),
result_digest: None,
},
);
}
for tr in &commit.effect_transitions {
let eff = pending_effects.get_mut(&tr.effect_id).ok_or_else(|| {
StoreError::NotFound(format!("effect {} not found", tr.effect_id))
})?;
if &eff.tenant_id != lease.tenant_id() || &eff.run_id != lease.run_id() {
return Err(StoreError::TenantMismatch);
}
let next_state = transition_effect(eff.state, tr.event)?;
eff.state = next_state;
eff.fence = lease.fence();
if let Some(ref digest) = tr.result_digest {
eff.result_digest = Some(digest.clone());
}
}
if let Some(ref leaf_id) = commit.new_leaf {
let exists = sess.entries.contains_key(leaf_id)
|| commit.entries.iter().any(|e| &e.entry_id == leaf_id);
if !exists {
return Err(StoreError::NotFound(format!(
"leaf entry {leaf_id} not found"
)));
}
}
let new_revision = sess
.revision
.next()
.ok_or_else(|| StoreError::Backend("session revision overflow".into()))?;
let mut new_epochs = sess.epochs;
if commit.bump_branch_epoch {
new_epochs = new_epochs.bump_branch();
}
if commit.bump_activity_epoch {
new_epochs = new_epochs.bump_activity();
}
st.effects = pending_effects;
st.effect_idempotency = pending_idem;
for sp in commit.spend {
st.spend.push(SpendRow {
tenant_id: lease.tenant_id().clone(),
_session_id: lease.session_id().clone(),
run_id: lease.run_id().clone(),
billing_class: sp.billing_class,
_category: sp.category,
cost: sp.cost,
_basis: sp.basis,
recorded_at_ms: sp.recorded_at_ms,
});
}
if let Some(pending) = commit.receipt {
let receipt = CommandReceipt {
tenant_id: lease.tenant_id().clone(),
session_id: lease.session_id().clone(),
command_id: pending.command_id,
settlement: pending.settlement,
resulting_revision: new_revision,
epochs: new_epochs,
payload_json: pending.payload_json,
};
st.receipts.insert(
(
receipt.tenant_id.clone(),
receipt.session_id.clone(),
receipt.command_id.clone(),
),
receipt,
);
}
let sess_mut = st.sessions.get_mut(lease.session_id()).ok_or_else(|| {
StoreError::Backend(format!("session {} disappeared", lease.session_id()))
})?;
sess_mut.revision = new_revision;
sess_mut.epochs = new_epochs;
let mut last_appended = None;
for entry in commit.entries {
last_appended = Some(entry.entry_id.clone());
sess_mut.entries.insert(entry.entry_id.clone(), entry);
}
if let Some(leaf) = commit.new_leaf {
sess_mut.active_leaf = Some(leaf);
} else if let Some(last) = last_appended {
sess_mut.active_leaf = Some(last);
}
Ok(StepCommitResult {
new_revision,
epochs: new_epochs,
})
})
}
fn list_unknown_effects<'a>(
&'a self,
tenant_id: &'a TenantId,
run_id: &'a RunId,
) -> BoxFuture<'a, Result<Vec<EffectRecord>, StoreError>> {
Box::pin(async move {
let st = self.lock_state();
if let Some(run) = st.runs.get(run_id)
&& &run.tenant_id != tenant_id
{
return Err(StoreError::TenantMismatch);
}
Ok(st
.effects
.values()
.filter(|e| {
&e.tenant_id == tenant_id
&& &e.run_id == run_id
&& e.state == EffectState::Unknown
})
.cloned()
.collect())
})
}
fn list_claimed_effects<'a>(
&'a self,
tenant_id: &'a TenantId,
run_id: &'a RunId,
) -> BoxFuture<'a, Result<Vec<EffectRecord>, StoreError>> {
Box::pin(async move {
let st = self.lock_state();
if let Some(run) = st.runs.get(run_id)
&& &run.tenant_id != tenant_id
{
return Err(StoreError::TenantMismatch);
}
Ok(st
.effects
.values()
.filter(|e| {
&e.tenant_id == tenant_id
&& &e.run_id == run_id
&& e.state == EffectState::Claimed
})
.cloned()
.collect())
})
}
}
impl SessionStore for InMemoryStore {
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>> {
Box::pin(async move {
let mut st = self.lock_state();
if st.sessions.contains_key(session_id) {
return Err(StoreError::DuplicateIdempotencyKey(format!(
"session {session_id} already exists"
)));
}
st.sessions.insert(
session_id.clone(),
SessionRow {
tenant_id: tenant_id.clone(),
_parent_session_id: parent_session_id.cloned(),
revision: SessionRevision::INITIAL,
epochs: ScopeEpochs::default(),
active_leaf: None,
entries: BTreeMap::new(),
},
);
Ok(StepCommitResult {
new_revision: SessionRevision::INITIAL,
epochs: ScopeEpochs::default(),
})
})
}
fn load_branch<'a>(
&'a self,
tenant_id: &'a TenantId,
session_id: &'a SessionId,
leaf: Option<&'a EntryId>,
) -> BoxFuture<'a, Result<LoadedBranch, StoreError>> {
Box::pin(async move {
let st = self.lock_state();
let sess = st
.sessions
.get(session_id)
.ok_or_else(|| StoreError::NotFound(format!("session {session_id} not found")))?;
if &sess.tenant_id != tenant_id {
return Err(StoreError::TenantMismatch);
}
let target_leaf = leaf.cloned().or_else(|| sess.active_leaf.clone());
let mut chain = Vec::new();
let mut cursor = target_leaf;
let mut guard_steps = 0usize;
while let Some(id) = cursor {
guard_steps += 1;
if guard_steps > sess.entries.len() + 1 {
return Err(StoreError::Backend("cycle detected in session tree".into()));
}
let entry = sess
.entries
.get(&id)
.ok_or_else(|| StoreError::NotFound(format!("entry {id} not found")))?;
chain.push(entry.clone());
cursor = entry.parent_entry_id.clone();
}
chain.reverse();
Ok(LoadedBranch {
revision: sess.revision,
epochs: sess.epochs,
entries: chain,
})
})
}
}
impl SpendStore for InMemoryStore {
fn sum_spend_since<'a>(
&'a self,
tenant_id: &'a TenantId,
since_ms: i64,
billing_class: Option<BillingClass>,
) -> BoxFuture<'a, Result<MicroUsd, StoreError>> {
Box::pin(async move {
let st = self.lock_state();
let mut total = MicroUsd::ZERO;
for item in &st.spend {
if &item.tenant_id == tenant_id
&& item.recorded_at_ms >= since_ms
&& billing_class.is_none_or(|bc| item.billing_class == bc)
{
total = total.saturating_add(item.cost);
}
}
Ok(total)
})
}
fn sum_run_spend<'a>(
&'a self,
tenant_id: &'a TenantId,
run_id: &'a RunId,
) -> BoxFuture<'a, Result<MicroUsd, StoreError>> {
Box::pin(async move {
let st = self.lock_state();
let mut total = MicroUsd::ZERO;
for item in &st.spend {
if &item.tenant_id == tenant_id && &item.run_id == run_id {
total = total.saturating_add(item.cost);
}
}
Ok(total)
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
#[tokio::test]
async fn in_memory_store_passes_full_conformance_and_concurrency_suites() {
let store = Arc::new(InMemoryStore::new());
crate::conformance::run_all(&store).await;
crate::conformance::run_concurrency(store).await;
}
#[tokio::test]
async fn in_memory_store_recovers_from_poisoned_mutex() {
let store = Arc::new(InMemoryStore::new());
let poison_handle = Arc::clone(&store);
let _ = std::thread::spawn(move || {
let _guard = poison_handle.state.lock().unwrap();
panic!("intentional poison");
})
.join();
assert!(store.state.is_poisoned());
let tenant = TenantId::try_new("org:poison").unwrap();
let session = SessionId::try_new("sess:poison").unwrap();
let res = store.create_session(&tenant, &session, None).await.unwrap();
assert_eq!(res.new_revision, SessionRevision::INITIAL);
}
}