use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use thiserror::Error;
use crate::record::{sha256_hex, Effect};
pub const EFFECT_ID_DOMAIN: &str = "rusty/effect-id/v1";
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct EffectId(String);
impl EffectId {
pub fn as_str(&self) -> &str {
&self.0
}
}
impl std::fmt::Display for EffectId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
pub fn derive_effect_id(
scope: &str,
kind: &str,
input_hash: &str,
idempotency_key: Option<&str>,
) -> EffectId {
let material = [
EFFECT_ID_DOMAIN,
scope,
kind,
input_hash,
idempotency_key.unwrap_or("-"),
]
.join("\n");
EffectId(sha256_hex(material.as_bytes()))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EffectRequest {
kind: String,
effect: Effect,
input_hash: String,
idempotency_key: Option<String>,
}
impl EffectRequest {
pub fn new(
kind: impl Into<String>,
effect: Effect,
input: &Value,
idempotency_key: Option<String>,
) -> Self {
let input_hash = crate::record::PayloadRef::inline(input.clone())
.content_hash()
.expect("a serde_json::Value always serializes");
Self {
kind: kind.into(),
effect,
input_hash,
idempotency_key,
}
}
pub fn from_typed<E: TypedEffect>(effect: &E) -> Self {
Self {
kind: effect.kind().to_owned(),
effect: E::EFFECT,
input_hash: effect.input_hash().to_owned(),
idempotency_key: effect.idempotency_key().map(str::to_owned),
}
}
pub fn kind(&self) -> &str {
&self.kind
}
pub fn effect(&self) -> Effect {
self.effect
}
pub fn input_hash(&self) -> &str {
&self.input_hash
}
pub fn idempotency_key(&self) -> Option<&str> {
self.idempotency_key.as_deref()
}
pub fn effect_id(&self, scope: &str) -> EffectId {
derive_effect_id(
scope,
self.kind(),
self.input_hash(),
self.idempotency_key(),
)
}
}
pub trait TypedEffect {
const EFFECT: Effect;
fn kind(&self) -> &str;
fn input_hash(&self) -> &str;
fn idempotency_key(&self) -> Option<&str> {
None
}
fn effect_id(&self, scope: &str) -> EffectId {
derive_effect_id(
scope,
self.kind(),
self.input_hash(),
self.idempotency_key(),
)
}
}
pub trait PureEffect: TypedEffect {}
pub trait ReadOnlyEffect: TypedEffect {}
pub trait IdempotentEffect: TypedEffect {}
pub trait CompensatableEffect: TypedEffect {}
pub trait IrreversibleEffect: TypedEffect {}
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum EffectViolation {
#[error(
"effect kind `{kind}` is marked with the {marker:?} marker trait but declares \
{declared:?}: the marker and TypedEffect::EFFECT must agree"
)]
DeclarationMismatch {
kind: String,
marker: Effect,
declared: Effect,
},
#[error(
"idempotent effect kind `{kind}` has no idempotency key: a stable key is what the \
idempotency declaration means at the wire"
)]
MissingIdempotencyKey {
kind: String,
},
#[error(
"compensatable effect kind `{kind}` has no registered rollback handler: register one \
in a CompensationRegistry before executing it"
)]
MissingCompensation {
kind: String,
},
#[error(
"irreversible effect kind `{kind}` ({effect_id}) requires an explicit approval token \
scoped to its effect id"
)]
MissingApproval {
kind: String,
effect_id: EffectId,
},
#[error(
"approval token for {presented} does not admit irreversible effect kind `{kind}` \
({required})"
)]
ApprovalScopeMismatch {
kind: String,
required: EffectId,
presented: EffectId,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ApprovalToken {
effect_id: EffectId,
approved_by: String,
}
impl ApprovalToken {
pub fn approve(effect_id: EffectId, approved_by: impl Into<String>) -> Self {
Self {
effect_id,
approved_by: approved_by.into(),
}
}
pub fn for_effect<E: IrreversibleEffect>(
effect: &E,
scope: &str,
approved_by: impl Into<String>,
) -> Self {
Self::approve(effect.effect_id(scope), approved_by)
}
pub fn effect_id(&self) -> &EffectId {
&self.effect_id
}
pub fn approved_by(&self) -> &str {
&self.approved_by
}
pub fn admits(&self, effect_id: &EffectId) -> bool {
&self.effect_id == effect_id
}
}
pub type CompensationHandler = Arc<dyn Fn(&Value) -> Result<Value, String> + Send + Sync>;
#[derive(Default, Clone)]
pub struct CompensationRegistry {
handlers: BTreeMap<String, CompensationHandler>,
}
impl std::fmt::Debug for CompensationRegistry {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_set().entries(self.handlers.keys()).finish()
}
}
impl CompensationRegistry {
pub fn new() -> Self {
Self::default()
}
pub fn register(
&mut self,
kind: impl Into<String>,
handler: CompensationHandler,
) -> Option<CompensationHandler> {
self.handlers.insert(kind.into(), handler)
}
pub fn handler_for(&self, kind: &str) -> Option<&CompensationHandler> {
self.handlers.get(kind)
}
}
#[derive(Clone)]
pub struct EffectAdmissionContext {
scope: String,
approvals: Arc<Mutex<BTreeMap<EffectId, ApprovalToken>>>,
compensations: CompensationRegistry,
}
impl std::fmt::Debug for EffectAdmissionContext {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let approvals = self.approvals.lock().unwrap_or_else(|e| e.into_inner());
f.debug_struct("EffectAdmissionContext")
.field("scope", &self.scope)
.field("approval_effect_ids", &approvals.keys())
.field("compensations", &self.compensations)
.finish()
}
}
impl EffectAdmissionContext {
pub fn new(scope: impl Into<String>) -> Self {
Self {
scope: scope.into(),
approvals: Arc::new(Mutex::new(BTreeMap::new())),
compensations: CompensationRegistry::new(),
}
}
pub fn with_approvals(mut self, approvals: impl IntoIterator<Item = ApprovalToken>) -> Self {
self.approvals = Arc::new(Mutex::new(
approvals
.into_iter()
.map(|token| (token.effect_id().clone(), token))
.collect(),
));
self
}
pub fn with_compensations(mut self, compensations: CompensationRegistry) -> Self {
self.compensations = compensations;
self
}
pub fn scope(&self) -> &str {
&self.scope
}
pub fn admit(&self, request: &EffectRequest) -> Result<EffectPermit, EffectViolation> {
let effect_id = request.effect_id(self.scope());
let (compensation, approval) = match request.effect() {
Effect::Pure | Effect::ReadOnly => (None, None),
Effect::Idempotent => {
if request.idempotency_key().is_none() {
return Err(EffectViolation::MissingIdempotencyKey {
kind: request.kind().to_owned(),
});
}
(None, None)
}
Effect::Compensatable => (
Some(
self.compensations
.handler_for(request.kind())
.cloned()
.ok_or_else(|| EffectViolation::MissingCompensation {
kind: request.kind().to_owned(),
})?,
),
None,
),
Effect::NonIdempotent => {
let approval = self
.approvals
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(&effect_id)
.ok_or_else(|| EffectViolation::MissingApproval {
kind: request.kind().to_owned(),
effect_id: effect_id.clone(),
})?;
(None, Some(approval))
}
};
Ok(EffectPermit {
effect_id,
compensation,
approval,
})
}
}
#[derive(Clone)]
pub struct EffectPermit {
effect_id: EffectId,
compensation: Option<CompensationHandler>,
approval: Option<ApprovalToken>,
}
impl std::fmt::Debug for EffectPermit {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("EffectPermit")
.field("effect_id", &self.effect_id)
.field("has_compensation", &self.compensation.is_some())
.field(
"approved_by",
&self.approval.as_ref().map(ApprovalToken::approved_by),
)
.finish()
}
}
impl EffectPermit {
pub fn effect_id(&self) -> &EffectId {
&self.effect_id
}
pub fn compensation(&self) -> Option<&CompensationHandler> {
self.compensation.as_ref()
}
pub fn approval(&self) -> Option<&ApprovalToken> {
self.approval.as_ref()
}
}
fn check_declaration<E: TypedEffect>(effect: &E, marker: Effect) -> Result<(), EffectViolation> {
if E::EFFECT != marker {
return Err(EffectViolation::DeclarationMismatch {
kind: effect.kind().to_owned(),
marker,
declared: E::EFFECT,
});
}
Ok(())
}
pub fn admit_speculation<E: PureEffect>(effect: &E) -> Result<(), EffectViolation> {
check_declaration::<E>(effect, Effect::Pure)
}
pub fn admit_retry<E: IdempotentEffect>(effect: &E) -> Result<(), EffectViolation> {
check_declaration::<E>(effect, Effect::Idempotent)?;
if effect.idempotency_key().is_none() {
return Err(EffectViolation::MissingIdempotencyKey {
kind: effect.kind().to_owned(),
});
}
Ok(())
}
pub fn admit_compensatable<E: CompensatableEffect>(
effect: &E,
registry: &CompensationRegistry,
) -> Result<CompensationHandler, EffectViolation> {
check_declaration::<E>(effect, Effect::Compensatable)?;
registry.handler_for(effect.kind()).cloned().ok_or_else(|| {
EffectViolation::MissingCompensation {
kind: effect.kind().to_owned(),
}
})
}
pub fn admit_irreversible<E: IrreversibleEffect>(
effect: &E,
scope: &str,
approval: Option<&ApprovalToken>,
) -> Result<(), EffectViolation> {
check_declaration::<E>(effect, Effect::NonIdempotent)?;
let required = effect.effect_id(scope);
let token = approval.ok_or_else(|| EffectViolation::MissingApproval {
kind: effect.kind().to_owned(),
effect_id: required.clone(),
})?;
if !token.admits(&required) {
return Err(EffectViolation::ApprovalScopeMismatch {
kind: effect.kind().to_owned(),
required,
presented: token.effect_id().clone(),
});
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn effect_id_derivation_is_deterministic_and_scoped() {
let a = derive_effect_id("run-1", "charge_card", "abc123", Some("key-7"));
let b = derive_effect_id("run-1", "charge_card", "abc123", Some("key-7"));
assert_eq!(a, b, "same inputs must derive the same id");
assert_eq!(a.as_str().len(), 64, "ids are hex SHA-256 digests");
assert_ne!(
a,
derive_effect_id("run-2", "charge_card", "abc123", Some("key-7"))
);
assert_ne!(
a,
derive_effect_id("run-1", "refund", "abc123", Some("key-7"))
);
assert_ne!(
a,
derive_effect_id("run-1", "charge_card", "def456", Some("key-7"))
);
assert_ne!(
a,
derive_effect_id("run-1", "charge_card", "abc123", Some("key-8"))
);
assert_ne!(a, derive_effect_id("run-1", "charge_card", "abc123", None));
}
#[test]
fn effect_id_is_serde_transparent() {
let id = derive_effect_id("run-1", "charge_card", "abc123", None);
let value = serde_json::to_value(&id).unwrap();
assert_eq!(value, serde_json::json!(id.as_str()));
let back: EffectId = serde_json::from_value(value).unwrap();
assert_eq!(back, id);
}
}