1use crate::WorkflowDatabase;
7use async_trait::async_trait;
8use multicast::command::RequestContext;
9use multicast_codemode::{
10 CallRecovery, Connector, ConnectorDescription, ConnectorTool, RetryPolicy, ToolContext,
11};
12use serde_json::Value;
13use std::sync::Arc;
14
15#[async_trait]
17pub trait WorkflowAuthority: Send + Sync {
18 fn capture(&self, request: Option<&RequestContext>) -> Result<String, String>;
22 async fn resolve(&self, reference: &str) -> Result<RequestContext, String>;
25}
26
27#[derive(Clone)]
29pub struct WorkflowBindings {
30 database: Arc<dyn WorkflowDatabase>,
31 authority: Arc<dyn WorkflowAuthority>,
32}
33impl WorkflowBindings {
34 pub fn new(
36 database: Arc<dyn WorkflowDatabase>,
37 authority: Arc<dyn WorkflowAuthority>,
38 ) -> Result<Self, String> {
39 database.execute_batch("CREATE TABLE IF NOT EXISTS incurs_workflow_authority(id TEXT PRIMARY KEY, reference TEXT NOT NULL)")?;
40 Ok(Self {
41 database,
42 authority,
43 })
44 }
45 pub async fn admit(
48 &self,
49 id: &str,
50 request: Option<&RequestContext>,
51 ) -> Result<RequestContext, String> {
52 let existing = self.reference(id)?;
53 let reference = match existing {
54 Some(reference) => {
55 if request.is_some() && self.authority.capture(request)? != reference {
56 return Err("WORKFLOW_AUTHORITY_MISMATCH".into());
57 }
58 reference
59 }
60 None => {
61 let reference = self.authority.capture(request)?;
62 if reference.is_empty() || reference.len() > 1024 {
63 return Err("WORKFLOW_AUTHORITY_REFERENCE".into());
64 }
65 self.authority.resolve(&reference).await?;
67 let mut write = |sql: &dyn crate::WorkflowSql| {
68 sql.execute("INSERT OR IGNORE INTO incurs_workflow_authority(id,reference) VALUES (?,?)",&[Value::String(id.into()),Value::String(reference.clone())])?;
69 let rows = sql.query(
70 "SELECT reference FROM incurs_workflow_authority WHERE id=?",
71 &[Value::String(id.into())],
72 )?;
73 if rows.first().and_then(|r| r.first()).and_then(Value::as_str)
74 != Some(reference.as_str())
75 {
76 return Err("WORKFLOW_AUTHORITY_MISMATCH".into());
77 }
78 Ok(())
79 };
80 self.database.transaction(&mut write)?;
81 reference
82 }
83 };
84 self.authority.resolve(&reference).await
85 }
86 pub async fn resolve(&self, id: &str) -> Result<RequestContext, String> {
88 let reference = self.reference(id)?.ok_or("WORKFLOW_AUTHORITY_MISSING")?;
89 self.authority.resolve(&reference).await
90 }
91 pub async fn inherit(&self, parent: &str, child: &str) -> Result<(), String> {
94 let reference = self
95 .reference(parent)?
96 .ok_or("WORKFLOW_AUTHORITY_MISSING")?;
97 self.authority.resolve(&reference).await?;
98 let mut write = |sql: &dyn crate::WorkflowSql| {
99 sql.execute(
100 "INSERT OR IGNORE INTO incurs_workflow_authority(id,reference) VALUES (?,?)",
101 &[
102 Value::String(child.into()),
103 Value::String(reference.clone()),
104 ],
105 )?;
106 let rows = sql.query(
107 "SELECT reference FROM incurs_workflow_authority WHERE id=?",
108 &[Value::String(child.into())],
109 )?;
110 if rows.first().and_then(|r| r.first()).and_then(Value::as_str)
111 != Some(reference.as_str())
112 {
113 return Err("WORKFLOW_AUTHORITY_MISMATCH".into());
114 }
115 Ok(())
116 };
117 self.database.transaction(&mut write)
118 }
119 fn reference(&self, id: &str) -> Result<Option<String>, String> {
120 let rows = self.database.query(
121 "SELECT reference FROM incurs_workflow_authority WHERE id=?",
122 &[Value::String(id.into())],
123 )?;
124 rows.first()
125 .map(|row| {
126 row.first()
127 .and_then(Value::as_str)
128 .map(str::to_string)
129 .ok_or_else(|| "WORKFLOW_AUTHORITY_CORRUPT".into())
130 })
131 .transpose()
132 }
133 pub fn connector(&self, inner: Arc<dyn Connector>) -> Arc<dyn Connector> {
135 Arc::new(AuthorityConnector {
136 inner,
137 bindings: self.clone(),
138 })
139 }
140}
141struct AuthorityConnector {
142 inner: Arc<dyn Connector>,
143 bindings: WorkflowBindings,
144}
145impl AuthorityConnector {
146 async fn context(&self, context: &ToolContext) -> Result<ToolContext, String> {
147 let mut context = context.clone();
148 context.request = Some(self.bindings.resolve(&context.execution_id).await?);
149 Ok(context)
150 }
151}
152#[async_trait]
153impl Connector for AuthorityConnector {
154 async fn admit_child(
155 &self,
156 parent: &str,
157 child: &str,
158 request: Option<&RequestContext>,
159 ) -> Result<(), String> {
160 self.bindings.inherit(parent, child).await?;
161 self.inner.admit_child(parent, child, request).await
162 }
163 fn name(&self) -> &str {
164 self.inner.name()
165 }
166 async fn describe(&self) -> Result<ConnectorDescription, String> {
167 self.inner.describe().await
168 }
169 fn retry_policy(&self, method: &str) -> RetryPolicy {
170 self.inner.retry_policy(method)
171 }
172 async fn prepare_arguments(
173 &self,
174 seq: u64,
175 tool: &ConnectorTool,
176 arguments: Value,
177 context: &ToolContext,
178 ) -> Result<Value, String> {
179 self.inner
180 .prepare_arguments(seq, tool, arguments, &self.context(context).await?)
181 .await
182 }
183 async fn execute(
184 &self,
185 method: &str,
186 arguments: Value,
187 context: &ToolContext,
188 ) -> Result<Value, String> {
189 self.inner
190 .execute(method, arguments, &self.context(context).await?)
191 .await
192 }
193 async fn recover(
194 &self,
195 method: &str,
196 arguments: &Value,
197 context: &ToolContext,
198 ) -> Result<CallRecovery, String> {
199 self.inner
200 .recover(method, arguments, &self.context(context).await?)
201 .await
202 }
203 async fn revert(
204 &self,
205 method: &str,
206 arguments: Value,
207 result: Value,
208 context: &ToolContext,
209 ) -> Result<bool, String> {
210 self.inner
211 .revert(method, arguments, result, &self.context(context).await?)
212 .await
213 }
214 async fn pass_ended(&self, id: &str, status: &str) {
215 self.inner.pass_ended(id, status).await;
216 }
217 async fn execution_ended(&self, id: &str, status: &str) {
218 self.inner.execution_ended(id, status).await;
219 }
220}