|
| 1 | +use std::{sync::Arc, collections::HashMap}; |
| 2 | + |
| 3 | +use anyhow::Result; |
| 4 | +use async_trait::async_trait; |
| 5 | +use serde::{Deserialize, Serialize}; |
| 6 | +use spin_trigger::{cli::NoArgs, TriggerAppEngine, TriggerExecutor, EitherInstance}; |
| 7 | + |
| 8 | +mod aws; |
| 9 | +mod utils; |
| 10 | + |
| 11 | +use utils::MessageUtils; |
| 12 | + |
| 13 | +wasmtime::component::bindgen!({ |
| 14 | + path: "sqs.wit", |
| 15 | + async: true |
| 16 | +}); |
| 17 | + |
| 18 | +use fermyon::spin_sqs::sqs_types as sqs; |
| 19 | + |
| 20 | +pub(crate) type RuntimeData = (); |
| 21 | + |
| 22 | +pub struct SqsTrigger { |
| 23 | + engine: TriggerAppEngine<Self>, |
| 24 | + queue_components: Vec<Component>, |
| 25 | +} |
| 26 | + |
| 27 | +#[derive(Clone, Debug, Default, Deserialize, Serialize)] |
| 28 | +#[serde(deny_unknown_fields)] |
| 29 | +pub struct SqsTriggerConfig { |
| 30 | + pub component: String, |
| 31 | + pub queue_url: String, |
| 32 | + pub max_messages: Option<u16>, |
| 33 | + pub idle_wait_seconds: Option<u64>, |
| 34 | + pub system_attributes: Option<Vec<String>>, |
| 35 | + pub message_attributes: Option<Vec<String>>, |
| 36 | +} |
| 37 | + |
| 38 | +#[derive(Clone, Debug)] |
| 39 | +struct Component { |
| 40 | + pub id: String, |
| 41 | + pub queue_url: String, |
| 42 | + pub max_messages: u16, |
| 43 | + pub idle_wait: tokio::time::Duration, |
| 44 | + pub system_attributes: Vec<aws::QueueAttributeName>, |
| 45 | + pub message_attributes: Vec<String>, |
| 46 | +} |
| 47 | + |
| 48 | +#[derive(Clone, Debug, Default, Deserialize, Serialize)] |
| 49 | +#[serde(deny_unknown_fields)] |
| 50 | +struct TriggerMetadata { |
| 51 | + r#type: String, |
| 52 | +} |
| 53 | + |
| 54 | +// This is a placeholder - we don't yet detect any situations that would require |
| 55 | +// graceful or ungraceful exit. It will likely require rework when we do. It |
| 56 | +// is here so that we have a skeleton for returning errors that doesn't expose |
| 57 | +// us to thoughtlessly "?"-ing away an Err case and creating a situation where a |
| 58 | +// transient failure could end the trigger. |
| 59 | +#[allow(dead_code)] |
| 60 | +#[derive(Debug)] |
| 61 | +enum TerminationReason { |
| 62 | + ExitRequested, |
| 63 | + Other(String), |
| 64 | +} |
| 65 | + |
| 66 | +#[async_trait] |
| 67 | +impl TriggerExecutor for SqsTrigger { |
| 68 | + const TRIGGER_TYPE: &'static str = "sqs"; |
| 69 | + type RuntimeData = RuntimeData; |
| 70 | + type TriggerConfig = SqsTriggerConfig; |
| 71 | + type RunConfig = NoArgs; |
| 72 | + |
| 73 | + async fn new(engine: TriggerAppEngine<Self>) -> Result<Self> { |
| 74 | + let queue_components = engine |
| 75 | + .trigger_configs() |
| 76 | + .map(|(_, config)| Component { |
| 77 | + id: config.component.clone(), |
| 78 | + queue_url: config.queue_url.clone(), |
| 79 | + max_messages: config.max_messages.unwrap_or(10).into(), |
| 80 | + idle_wait: tokio::time::Duration::from_secs(config.idle_wait_seconds.unwrap_or(2)), |
| 81 | + system_attributes: config.system_attributes.clone().unwrap_or_default().iter().map(|s| s.as_str().into()).collect(), |
| 82 | + message_attributes: config.message_attributes.clone().unwrap_or_default(), |
| 83 | + }) |
| 84 | + .collect(); |
| 85 | + |
| 86 | + Ok(Self { |
| 87 | + engine, |
| 88 | + queue_components, |
| 89 | + }) |
| 90 | + } |
| 91 | + |
| 92 | + async fn run(self, _config: Self::RunConfig) -> Result<()> { |
| 93 | + tokio::spawn(async move { |
| 94 | + tokio::signal::ctrl_c().await.unwrap(); |
| 95 | + std::process::exit(0); |
| 96 | + }); |
| 97 | + |
| 98 | + let config = aws_config::load_from_env().await; |
| 99 | + |
| 100 | + let client = aws::Client::new(&config); |
| 101 | + let engine = Arc::new(self.engine); |
| 102 | + |
| 103 | + let loops = self.queue_components.iter().map(|component| { |
| 104 | + Self::start_receive_loop(engine.clone(), &client, component) |
| 105 | + }); |
| 106 | + |
| 107 | + let (tr, _, rest) = futures::future::select_all(loops).await; |
| 108 | + drop(rest); |
| 109 | + |
| 110 | + match tr { |
| 111 | + Ok(TerminationReason::ExitRequested) => { |
| 112 | + tracing::trace!("Exiting"); |
| 113 | + Ok(()) |
| 114 | + }, |
| 115 | + _ => { |
| 116 | + tracing::trace!("Fatal: {:?}", tr); |
| 117 | + Err(anyhow::anyhow!("{tr:?}")) |
| 118 | + } |
| 119 | + } |
| 120 | + } |
| 121 | +} |
| 122 | + |
| 123 | +impl SqsTrigger { |
| 124 | + fn start_receive_loop(engine: Arc<TriggerAppEngine<Self>>, client: &aws::Client, component: &Component) -> tokio::task::JoinHandle<TerminationReason> { |
| 125 | + let future = Self::receive(engine, client.clone(), component.clone()); |
| 126 | + tokio::task::spawn(future) |
| 127 | + } |
| 128 | + |
| 129 | + // This doesn't return a Result because we don't want a thoughtless `?` to exit the loop |
| 130 | + // and terminate the entire trigger. Termination should be a conscious decision when |
| 131 | + // we are sure there is no point continuing. |
| 132 | + async fn receive(engine: Arc<TriggerAppEngine<Self>>, client: aws::Client, component: Component) -> TerminationReason { |
| 133 | + let queue_timeout_secs = aws::get_queue_timeout_secs(&client, &component.queue_url).await; |
| 134 | + |
| 135 | + loop { |
| 136 | + tracing::trace!("Queue {}: attempting to receive up to {}", component.queue_url, component.max_messages); |
| 137 | + |
| 138 | + let rmo = match client |
| 139 | + .receive_message() |
| 140 | + .queue_url(&component.queue_url) |
| 141 | + .max_number_of_messages(component.max_messages.into()) |
| 142 | + .set_attribute_names(Some(component.system_attributes.clone())) |
| 143 | + .set_message_attribute_names(Some(component.message_attributes.clone())) |
| 144 | + .send() |
| 145 | + .await |
| 146 | + { |
| 147 | + Ok(rmo) => rmo, |
| 148 | + Err(e) => { |
| 149 | + tracing::error!("Queue {}: error receiving messages: {:?}", component.queue_url, e); |
| 150 | + tokio::time::sleep(component.idle_wait).await; |
| 151 | + continue; |
| 152 | + } |
| 153 | + }; |
| 154 | + |
| 155 | + if let Some(msgs) = rmo.messages() { |
| 156 | + let msgs = msgs.to_vec(); |
| 157 | + tracing::info!("Queue {}: received {} message(s)", component.queue_url, msgs.len()); |
| 158 | + for msg in msgs { |
| 159 | + // Spin off the execution so it doesn't block the queue |
| 160 | + let processor = SqsMessageProcessor::new(&engine, &client, &component, queue_timeout_secs); |
| 161 | + tokio::spawn(async move { |
| 162 | + processor.process_message(msg).await |
| 163 | + }); |
| 164 | + } |
| 165 | + } else { |
| 166 | + tracing::trace!("Queue {}: no messages received", component.queue_url); |
| 167 | + tokio::time::sleep(component.idle_wait).await; |
| 168 | + } |
| 169 | + } |
| 170 | + } |
| 171 | +} |
| 172 | + |
| 173 | +struct SqsMessageProcessor { |
| 174 | + engine: Arc<TriggerAppEngine<SqsTrigger>>, |
| 175 | + client: aws::Client, |
| 176 | + component: Component, |
| 177 | + queue_timeout_secs: u16, |
| 178 | +} |
| 179 | + |
| 180 | +impl SqsMessageProcessor { |
| 181 | + fn new( |
| 182 | + engine: &Arc<TriggerAppEngine<SqsTrigger>>, |
| 183 | + client: &aws::Client, |
| 184 | + component: &Component, |
| 185 | + queue_timeout_secs: u16 |
| 186 | + ) -> Self { |
| 187 | + Self { |
| 188 | + engine: engine.clone(), |
| 189 | + client: client.clone(), |
| 190 | + component: component.clone(), |
| 191 | + queue_timeout_secs |
| 192 | + } |
| 193 | + } |
| 194 | + |
| 195 | + async fn process_message(&self, msg: aws::Message) { |
| 196 | + let msg_id = msg.display_id(); |
| 197 | + tracing::trace!("Message {msg_id}: spawned processing task"); |
| 198 | + |
| 199 | + // The attr lists have to be returned to this level so that they live long enough |
| 200 | + let attrs = to_wit_message_attrs(&msg); |
| 201 | + let message = sqs::Message { |
| 202 | + id: msg.message_id().map(|s| s.to_owned()), |
| 203 | + message_attributes: attrs, |
| 204 | + body: msg.body().map(|s| s.to_owned()), |
| 205 | + }; |
| 206 | + |
| 207 | + let renew_lease = aws::hold_message_lease(&self.client, self.queue_url(), &msg, self.queue_timeout_secs); |
| 208 | + |
| 209 | + let action = self.execute_wasm(message).await; |
| 210 | + |
| 211 | + if let Some(renewer) = renew_lease { |
| 212 | + renewer.abort(); |
| 213 | + } |
| 214 | + |
| 215 | + match action { |
| 216 | + Ok(sqs::MessageAction::Delete) => { |
| 217 | + tracing::trace!("Message {msg_id} processed successfully: action is Delete"); |
| 218 | + if let Some(receipt_handle) = msg.receipt_handle() { |
| 219 | + tracing::trace!("Message {msg_id}: attempting to delete via {receipt_handle}"); |
| 220 | + match self.client.delete_message().queue_url(self.queue_url()).receipt_handle(receipt_handle).send().await { |
| 221 | + Ok(_) => tracing::trace!("Message {msg_id} deleted"), |
| 222 | + Err(e) => tracing::error!("Message {msg_id}: error deleting via {receipt_handle}: {e:?}"), |
| 223 | + } |
| 224 | + } |
| 225 | + } |
| 226 | + Ok(sqs::MessageAction::Leave) => { |
| 227 | + tracing::trace!("Message {msg_id} processed successfully: action is Leave"); |
| 228 | + // TODO: change message visibility to 0? |
| 229 | + } |
| 230 | + Err(e) => { |
| 231 | + tracing::error!("Message {msg_id} processing error: {}", e.to_string()); |
| 232 | + // TODO: change message visibility to 0 I guess? |
| 233 | + } |
| 234 | + } |
| 235 | + } |
| 236 | + |
| 237 | + async fn execute_wasm(&self, message: sqs::Message) -> Result<sqs::MessageAction> { |
| 238 | + let msg_id = message.display_id(); |
| 239 | + let component_id = &self.component.id; |
| 240 | + tracing::trace!("Message {msg_id}: executing component {component_id}"); |
| 241 | + let (instance, mut store) = self.engine.prepare_instance(component_id).await?; |
| 242 | + let EitherInstance::Component(instance) = instance else { |
| 243 | + unreachable!() |
| 244 | + }; |
| 245 | + |
| 246 | + let instance = SpinSqs::new(&mut store, &instance)?; |
| 247 | + |
| 248 | + match instance.call_handle_queue_message(&mut store, &message).await { |
| 249 | + Ok(Ok(action)) => { |
| 250 | + tracing::trace!("Message {msg_id}: component {component_id} completed okay"); |
| 251 | + Ok(action) |
| 252 | + }, |
| 253 | + Ok(Err(e)) => { |
| 254 | + tracing::warn!("Message {msg_id}: component {component_id} returned error {:?}", e); |
| 255 | + Err(anyhow::anyhow!("Component {component_id} returned error processing message {msg_id}")) // TODO: more details when WIT provides them |
| 256 | + }, |
| 257 | + Err(e) => { |
| 258 | + tracing::error!("Message {msg_id}: engine error running component {component_id}: {:?}", e); |
| 259 | + Err(anyhow::anyhow!("Error executing component {component_id} while processing message {msg_id}")) |
| 260 | + }, |
| 261 | + } |
| 262 | + } |
| 263 | + |
| 264 | + fn queue_url(&self) -> &str { |
| 265 | + &self.component.queue_url |
| 266 | + } |
| 267 | +} |
| 268 | + |
| 269 | +fn to_wit_message_attrs(m: &aws::Message) -> Vec<sqs::MessageAttribute> { |
| 270 | + let msg_id = m.display_id(); |
| 271 | + |
| 272 | + let sysattrs = m.attributes() |
| 273 | + .map(system_attributes_to_wit) |
| 274 | + .unwrap_or_default(); |
| 275 | + let userattrs = m.message_attributes() |
| 276 | + .map(|a| user_attributes_to_wit(a, &msg_id)) |
| 277 | + .unwrap_or_default(); |
| 278 | + |
| 279 | + vec![sysattrs, userattrs].concat() |
| 280 | +} |
| 281 | + |
| 282 | +fn system_attributes_to_wit(src: &HashMap<aws::MessageSystemAttributeName, String>) -> Vec<sqs::MessageAttribute> { |
| 283 | + src |
| 284 | + .iter() |
| 285 | + .map(|(k, v)| sqs::MessageAttribute { |
| 286 | + name: k.as_str().to_string(), |
| 287 | + value: sqs::MessageAttributeValue::Str(v.to_string()), |
| 288 | + data_type: None |
| 289 | + }) |
| 290 | + .collect::<Vec<_>>() |
| 291 | +} |
| 292 | + |
| 293 | +fn user_attributes_to_wit(src: &HashMap<String, aws::MessageAttributeValue>, msg_id: &str) -> Vec<sqs::MessageAttribute> { |
| 294 | + src |
| 295 | + .iter() |
| 296 | + .filter_map(|(k, v)| { |
| 297 | + match wit_value(v) { |
| 298 | + Ok(wv) => Some(sqs::MessageAttribute { |
| 299 | + name: k.to_string(), |
| 300 | + value: wv, |
| 301 | + data_type: None |
| 302 | + }), |
| 303 | + Err(e) => { |
| 304 | + tracing::error!("Message {msg_id}: can't convert attribute {} to string or blob, skipped: {e:?}", k.as_str()); // TODO: this should probably fail the message |
| 305 | + None |
| 306 | + }, |
| 307 | + } |
| 308 | + }) |
| 309 | + .collect::<Vec<_>>() |
| 310 | +} |
| 311 | + |
| 312 | +fn wit_value(v: &aws::MessageAttributeValue) -> Result<sqs::MessageAttributeValue> { |
| 313 | + if let Some(s) = v.string_value() { |
| 314 | + Ok(sqs::MessageAttributeValue::Str(s.to_string())) |
| 315 | + } else if let Some(b) = v.binary_value() { |
| 316 | + Ok(sqs::MessageAttributeValue::Binary(b.as_ref().to_vec())) |
| 317 | + } else { |
| 318 | + Err(anyhow::anyhow!("Don't know what to do with message attribute value {:?} (data type {:?})", v, v.data_type())) |
| 319 | + } |
| 320 | +} |
0 commit comments