use crate::WorkflowDatabase;
use async_trait::async_trait;
use multicast::command::RequestContext;
use multicast_codemode::{
CallRecovery, Connector, ConnectorDescription, ConnectorTool, RetryPolicy, ToolContext,
};
use serde_json::Value;
use std::sync::Arc;
#[async_trait]
pub trait WorkflowAuthority: Send + Sync {
fn capture(&self, request: Option<&RequestContext>) -> Result<String, String>;
async fn resolve(&self, reference: &str) -> Result<RequestContext, String>;
}
#[derive(Clone)]
pub struct WorkflowBindings {
database: Arc<dyn WorkflowDatabase>,
authority: Arc<dyn WorkflowAuthority>,
}
impl WorkflowBindings {
pub fn new(
database: Arc<dyn WorkflowDatabase>,
authority: Arc<dyn WorkflowAuthority>,
) -> Result<Self, String> {
database.execute_batch("CREATE TABLE IF NOT EXISTS incurs_workflow_authority(id TEXT PRIMARY KEY, reference TEXT NOT NULL)")?;
Ok(Self {
database,
authority,
})
}
pub async fn admit(
&self,
id: &str,
request: Option<&RequestContext>,
) -> Result<RequestContext, String> {
let existing = self.reference(id)?;
let reference = match existing {
Some(reference) => {
if request.is_some() && self.authority.capture(request)? != reference {
return Err("WORKFLOW_AUTHORITY_MISMATCH".into());
}
reference
}
None => {
let reference = self.authority.capture(request)?;
if reference.is_empty() || reference.len() > 1024 {
return Err("WORKFLOW_AUTHORITY_REFERENCE".into());
}
self.authority.resolve(&reference).await?;
let mut write = |sql: &dyn crate::WorkflowSql| {
sql.execute("INSERT OR IGNORE INTO incurs_workflow_authority(id,reference) VALUES (?,?)",&[Value::String(id.into()),Value::String(reference.clone())])?;
let rows = sql.query(
"SELECT reference FROM incurs_workflow_authority WHERE id=?",
&[Value::String(id.into())],
)?;
if rows.first().and_then(|r| r.first()).and_then(Value::as_str)
!= Some(reference.as_str())
{
return Err("WORKFLOW_AUTHORITY_MISMATCH".into());
}
Ok(())
};
self.database.transaction(&mut write)?;
reference
}
};
self.authority.resolve(&reference).await
}
pub async fn resolve(&self, id: &str) -> Result<RequestContext, String> {
let reference = self.reference(id)?.ok_or("WORKFLOW_AUTHORITY_MISSING")?;
self.authority.resolve(&reference).await
}
pub async fn inherit(&self, parent: &str, child: &str) -> Result<(), String> {
let reference = self
.reference(parent)?
.ok_or("WORKFLOW_AUTHORITY_MISSING")?;
self.authority.resolve(&reference).await?;
let mut write = |sql: &dyn crate::WorkflowSql| {
sql.execute(
"INSERT OR IGNORE INTO incurs_workflow_authority(id,reference) VALUES (?,?)",
&[
Value::String(child.into()),
Value::String(reference.clone()),
],
)?;
let rows = sql.query(
"SELECT reference FROM incurs_workflow_authority WHERE id=?",
&[Value::String(child.into())],
)?;
if rows.first().and_then(|r| r.first()).and_then(Value::as_str)
!= Some(reference.as_str())
{
return Err("WORKFLOW_AUTHORITY_MISMATCH".into());
}
Ok(())
};
self.database.transaction(&mut write)
}
fn reference(&self, id: &str) -> Result<Option<String>, String> {
let rows = self.database.query(
"SELECT reference FROM incurs_workflow_authority WHERE id=?",
&[Value::String(id.into())],
)?;
rows.first()
.map(|row| {
row.first()
.and_then(Value::as_str)
.map(str::to_string)
.ok_or_else(|| "WORKFLOW_AUTHORITY_CORRUPT".into())
})
.transpose()
}
pub fn connector(&self, inner: Arc<dyn Connector>) -> Arc<dyn Connector> {
Arc::new(AuthorityConnector {
inner,
bindings: self.clone(),
})
}
}
struct AuthorityConnector {
inner: Arc<dyn Connector>,
bindings: WorkflowBindings,
}
impl AuthorityConnector {
async fn context(&self, context: &ToolContext) -> Result<ToolContext, String> {
let mut context = context.clone();
context.request = Some(self.bindings.resolve(&context.execution_id).await?);
Ok(context)
}
}
#[async_trait]
impl Connector for AuthorityConnector {
async fn admit_child(
&self,
parent: &str,
child: &str,
request: Option<&RequestContext>,
) -> Result<(), String> {
self.bindings.inherit(parent, child).await?;
self.inner.admit_child(parent, child, request).await
}
fn name(&self) -> &str {
self.inner.name()
}
async fn describe(&self) -> Result<ConnectorDescription, String> {
self.inner.describe().await
}
fn retry_policy(&self, method: &str) -> RetryPolicy {
self.inner.retry_policy(method)
}
async fn prepare_arguments(
&self,
seq: u64,
tool: &ConnectorTool,
arguments: Value,
context: &ToolContext,
) -> Result<Value, String> {
self.inner
.prepare_arguments(seq, tool, arguments, &self.context(context).await?)
.await
}
async fn execute(
&self,
method: &str,
arguments: Value,
context: &ToolContext,
) -> Result<Value, String> {
self.inner
.execute(method, arguments, &self.context(context).await?)
.await
}
async fn recover(
&self,
method: &str,
arguments: &Value,
context: &ToolContext,
) -> Result<CallRecovery, String> {
self.inner
.recover(method, arguments, &self.context(context).await?)
.await
}
async fn revert(
&self,
method: &str,
arguments: Value,
result: Value,
context: &ToolContext,
) -> Result<bool, String> {
self.inner
.revert(method, arguments, result, &self.context(context).await?)
.await
}
async fn pass_ended(&self, id: &str, status: &str) {
self.inner.pass_ended(id, status).await;
}
async fn execution_ended(&self, id: &str, status: &str) {
self.inner.execution_ended(id, status).await;
}
}