base_commit
stringlengths 40
40
| problem_statement
stringlengths 26
4.45k
| hints_text
stringlengths 0
8.52k
| created_at
stringlengths 20
20
| instance_id
stringlengths 16
18
| repo
stringclasses 1
value | version
stringclasses 13
values | patch
stringlengths 223
160k
| pull_number
int64 57
2.9k
| issue_numbers
listlengths 1
1
| test_patch
stringlengths 365
43.9k
| environment_setup_commit
stringclasses 13
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
Implement wasi-keyvalue
An exploratory PR for exploring, apropos of #2447.
|
2024-10-24T23:21:04Z
|
fermyon__spin-2895
|
fermyon/spin
|
3.2
|
diff --git a/Cargo.lock b/Cargo.lock
index 25d792db42..0e9cf73e06 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -7093,6 +7093,7 @@ dependencies = [
"spin-resource-table",
"spin-world",
"tempfile",
+ "thiserror",
"tokio",
"toml 0.8.19",
"tracing",
@@ -7355,6 +7356,7 @@ name = "spin-key-value-azure"
version = "2.8.0-pre0"
dependencies = [
"anyhow",
+ "azure_core",
"azure_data_cosmos",
"azure_identity",
"futures",
diff --git a/crates/factor-key-value/Cargo.toml b/crates/factor-key-value/Cargo.toml
index 1d103ec294..af38d9f8e5 100644
--- a/crates/factor-key-value/Cargo.toml
+++ b/crates/factor-key-value/Cargo.toml
@@ -16,6 +16,7 @@ spin-world = { path = "../world" }
tokio = { workspace = true, features = ["macros", "sync", "rt"] }
toml = { workspace = true }
tracing = { workspace = true }
+thiserror = { workspace = true }
[dev-dependencies]
spin-factors-test = { path = "../factors-test" }
diff --git a/crates/factor-key-value/src/host.rs b/crates/factor-key-value/src/host.rs
index b8dbb95968..06acd0bf40 100644
--- a/crates/factor-key-value/src/host.rs
+++ b/crates/factor-key-value/src/host.rs
@@ -1,7 +1,9 @@
+use super::{Cas, SwapError};
use anyhow::{Context, Result};
use spin_core::{async_trait, wasmtime::component::Resource};
use spin_resource_table::Table;
use spin_world::v2::key_value;
+use spin_world::wasi::keyvalue as wasi_keyvalue;
use std::{collections::HashSet, sync::Arc};
use tracing::{instrument, Level};
@@ -30,12 +32,19 @@ pub trait Store: Sync + Send {
async fn delete(&self, key: &str) -> Result<(), Error>;
async fn exists(&self, key: &str) -> Result<bool, Error>;
async fn get_keys(&self) -> Result<Vec<String>, Error>;
+ async fn get_many(&self, keys: Vec<String>) -> Result<Vec<(String, Option<Vec<u8>>)>, Error>;
+ async fn set_many(&self, key_values: Vec<(String, Vec<u8>)>) -> Result<(), Error>;
+ async fn delete_many(&self, keys: Vec<String>) -> Result<(), Error>;
+ async fn increment(&self, key: String, delta: i64) -> Result<i64, Error>;
+ async fn new_compare_and_swap(&self, bucket_rep: u32, key: &str)
+ -> Result<Arc<dyn Cas>, Error>;
}
pub struct KeyValueDispatch {
allowed_stores: HashSet<String>,
manager: Arc<dyn StoreManager>,
stores: Table<Arc<dyn Store>>,
+ compare_and_swaps: Table<Arc<dyn Cas>>,
}
impl KeyValueDispatch {
@@ -52,16 +61,43 @@ impl KeyValueDispatch {
allowed_stores,
manager,
stores: Table::new(capacity),
+ compare_and_swaps: Table::new(capacity),
}
}
- pub fn get_store(&self, store: Resource<key_value::Store>) -> anyhow::Result<&Arc<dyn Store>> {
+ pub fn get_store<T: 'static>(&self, store: Resource<T>) -> anyhow::Result<&Arc<dyn Store>> {
self.stores.get(store.rep()).context("invalid store")
}
+ pub fn get_cas<T: 'static>(&self, cas: Resource<T>) -> Result<&Arc<dyn Cas>> {
+ self.compare_and_swaps
+ .get(cas.rep())
+ .context("invalid compare and swap")
+ }
+
pub fn allowed_stores(&self) -> &HashSet<String> {
&self.allowed_stores
}
+
+ pub fn get_store_wasi<T: 'static>(
+ &self,
+ store: Resource<T>,
+ ) -> Result<&Arc<dyn Store>, wasi_keyvalue::store::Error> {
+ self.stores
+ .get(store.rep())
+ .ok_or(wasi_keyvalue::store::Error::NoSuchStore)
+ }
+
+ pub fn get_cas_wasi<T: 'static>(
+ &self,
+ cas: Resource<T>,
+ ) -> Result<&Arc<dyn Cas>, wasi_keyvalue::atomics::Error> {
+ self.compare_and_swaps
+ .get(cas.rep())
+ .ok_or(wasi_keyvalue::atomics::Error::Other(
+ "compare and swap not found".to_string(),
+ ))
+ }
}
#[async_trait]
@@ -141,12 +177,239 @@ impl key_value::HostStore for KeyValueDispatch {
}
}
+fn to_wasi_err(e: Error) -> wasi_keyvalue::store::Error {
+ match e {
+ Error::AccessDenied => wasi_keyvalue::store::Error::AccessDenied,
+ Error::NoSuchStore => wasi_keyvalue::store::Error::NoSuchStore,
+ Error::StoreTableFull => wasi_keyvalue::store::Error::Other("store table full".to_string()),
+ Error::Other(msg) => wasi_keyvalue::store::Error::Other(msg),
+ }
+}
+
+#[async_trait]
+impl wasi_keyvalue::store::Host for KeyValueDispatch {
+ async fn open(
+ &mut self,
+ identifier: String,
+ ) -> Result<Resource<wasi_keyvalue::store::Bucket>, wasi_keyvalue::store::Error> {
+ if self.allowed_stores.contains(&identifier) {
+ let store = self
+ .stores
+ .push(self.manager.get(&identifier).await.map_err(to_wasi_err)?)
+ .map_err(|()| wasi_keyvalue::store::Error::Other("store table full".to_string()))?;
+ Ok(Resource::new_own(store))
+ } else {
+ Err(wasi_keyvalue::store::Error::AccessDenied)
+ }
+ }
+
+ fn convert_error(
+ &mut self,
+ error: spin_world::wasi::keyvalue::store::Error,
+ ) -> std::result::Result<spin_world::wasi::keyvalue::store::Error, anyhow::Error> {
+ Ok(error)
+ }
+}
+
+use wasi_keyvalue::store::Bucket;
+#[async_trait]
+impl wasi_keyvalue::store::HostBucket for KeyValueDispatch {
+ async fn get(
+ &mut self,
+ self_: Resource<Bucket>,
+ key: String,
+ ) -> Result<Option<Vec<u8>>, wasi_keyvalue::store::Error> {
+ let store = self.get_store_wasi(self_)?;
+ store.get(&key).await.map_err(to_wasi_err)
+ }
+
+ async fn set(
+ &mut self,
+ self_: Resource<Bucket>,
+ key: String,
+ value: Vec<u8>,
+ ) -> Result<(), wasi_keyvalue::store::Error> {
+ let store = self.get_store_wasi(self_)?;
+ store.set(&key, &value).await.map_err(to_wasi_err)
+ }
+
+ async fn delete(
+ &mut self,
+ self_: Resource<Bucket>,
+ key: String,
+ ) -> Result<(), wasi_keyvalue::store::Error> {
+ let store = self.get_store_wasi(self_)?;
+ store.delete(&key).await.map_err(to_wasi_err)
+ }
+
+ async fn exists(
+ &mut self,
+ self_: Resource<Bucket>,
+ key: String,
+ ) -> Result<bool, wasi_keyvalue::store::Error> {
+ let store = self.get_store_wasi(self_)?;
+ store.exists(&key).await.map_err(to_wasi_err)
+ }
+
+ async fn list_keys(
+ &mut self,
+ self_: Resource<Bucket>,
+ cursor: Option<String>,
+ ) -> Result<wasi_keyvalue::store::KeyResponse, wasi_keyvalue::store::Error> {
+ match cursor {
+ Some(_) => Err(wasi_keyvalue::store::Error::Other(
+ "list_keys: cursor not supported".to_owned(),
+ )),
+ None => {
+ let store = self.get_store_wasi(self_)?;
+ let keys = store.get_keys().await.map_err(to_wasi_err)?;
+ Ok(wasi_keyvalue::store::KeyResponse { keys, cursor: None })
+ }
+ }
+ }
+
+ async fn drop(&mut self, rep: Resource<Bucket>) -> anyhow::Result<()> {
+ self.stores.remove(rep.rep());
+ Ok(())
+ }
+}
+
+#[async_trait]
+impl wasi_keyvalue::batch::Host for KeyValueDispatch {
+ #[instrument(name = "spin_key_value.get_many", skip(self, bucket, keys), err(level = Level::INFO), fields(otel.kind = "client"))]
+ async fn get_many(
+ &mut self,
+ bucket: Resource<wasi_keyvalue::batch::Bucket>,
+ keys: Vec<String>,
+ ) -> std::result::Result<Vec<(String, Option<Vec<u8>>)>, wasi_keyvalue::store::Error> {
+ let store = self.get_store_wasi(bucket)?;
+ store
+ .get_many(keys.iter().map(|k| k.to_string()).collect())
+ .await
+ .map_err(to_wasi_err)
+ }
+
+ #[instrument(name = "spin_key_value.set_many", skip(self, bucket, key_values), err(level = Level::INFO), fields(otel.kind = "client"))]
+ async fn set_many(
+ &mut self,
+ bucket: Resource<wasi_keyvalue::batch::Bucket>,
+ key_values: Vec<(String, Vec<u8>)>,
+ ) -> std::result::Result<(), wasi_keyvalue::store::Error> {
+ let store = self.get_store_wasi(bucket)?;
+ store.set_many(key_values).await.map_err(to_wasi_err)
+ }
+
+ #[instrument(name = "spin_key_value.get_many", skip(self, bucket, keys), err(level = Level::INFO), fields(otel.kind = "client"))]
+ async fn delete_many(
+ &mut self,
+ bucket: Resource<wasi_keyvalue::batch::Bucket>,
+ keys: Vec<String>,
+ ) -> std::result::Result<(), wasi_keyvalue::store::Error> {
+ let store = self.get_store_wasi(bucket)?;
+ store
+ .delete_many(keys.iter().map(|k| k.to_string()).collect())
+ .await
+ .map_err(to_wasi_err)
+ }
+}
+
+#[async_trait]
+impl wasi_keyvalue::atomics::HostCas for KeyValueDispatch {
+ async fn new(
+ &mut self,
+ bucket: Resource<wasi_keyvalue::atomics::Bucket>,
+ key: String,
+ ) -> Result<Resource<wasi_keyvalue::atomics::Cas>, wasi_keyvalue::store::Error> {
+ let bucket_rep = bucket.rep();
+ let bucket: Resource<Bucket> = Resource::new_own(bucket_rep);
+ let store = self.get_store_wasi(bucket)?;
+ let cas = store
+ .new_compare_and_swap(bucket_rep, &key)
+ .await
+ .map_err(to_wasi_err)?;
+ self.compare_and_swaps
+ .push(cas)
+ .map_err(|()| {
+ spin_world::wasi::keyvalue::store::Error::Other(
+ "too many compare_and_swaps opened".to_string(),
+ )
+ })
+ .map(Resource::new_own)
+ }
+
+ async fn current(
+ &mut self,
+ cas: Resource<wasi_keyvalue::atomics::Cas>,
+ ) -> Result<Option<Vec<u8>>, wasi_keyvalue::store::Error> {
+ let cas = self
+ .get_cas(cas)
+ .map_err(|e| wasi_keyvalue::store::Error::Other(e.to_string()))?;
+ cas.current().await.map_err(to_wasi_err)
+ }
+
+ async fn drop(&mut self, rep: Resource<wasi_keyvalue::atomics::Cas>) -> Result<()> {
+ self.compare_and_swaps.remove(rep.rep());
+ Ok(())
+ }
+}
+
+#[async_trait]
+impl wasi_keyvalue::atomics::Host for KeyValueDispatch {
+ #[instrument(name = "spin_key_value.increment", skip(self, bucket, key, delta), err(level = Level::INFO), fields(otel.kind = "client"))]
+ async fn increment(
+ &mut self,
+ bucket: Resource<wasi_keyvalue::atomics::Bucket>,
+ key: String,
+ delta: i64,
+ ) -> Result<i64, wasi_keyvalue::store::Error> {
+ let store = self.get_store_wasi(bucket)?;
+ store.increment(key, delta).await.map_err(to_wasi_err)
+ }
+
+ #[instrument(name = "spin_key_value.swap", skip(self, cas_res, value), err(level = Level::INFO), fields(otel.kind = "client"))]
+ async fn swap(
+ &mut self,
+ cas_res: Resource<atomics::Cas>,
+ value: Vec<u8>,
+ ) -> Result<std::result::Result<(), CasError>> {
+ let cas_rep = cas_res.rep();
+ let cas = self
+ .get_cas(Resource::<Bucket>::new_own(cas_rep))
+ .map_err(|e| CasError::StoreError(atomics::Error::Other(e.to_string())))?;
+
+ match cas.swap(value).await {
+ Ok(_) => Ok(Ok(())),
+ Err(err) => match err {
+ SwapError::CasFailed(_) => {
+ let bucket = Resource::new_own(cas.bucket_rep().await);
+ let new_cas = self.new(bucket, cas.key().await).await?;
+ let new_cas_rep = new_cas.rep();
+ self.current(Resource::new_own(new_cas_rep)).await?;
+ Err(anyhow::Error::new(CasError::CasFailed(Resource::new_own(
+ new_cas_rep,
+ ))))
+ }
+ SwapError::Other(msg) => Err(anyhow::Error::new(CasError::StoreError(
+ atomics::Error::Other(msg),
+ ))),
+ },
+ }
+ }
+}
+
pub fn log_error(err: impl std::fmt::Debug) -> Error {
tracing::warn!("key-value error: {err:?}");
Error::Other(format!("{err:?}"))
}
+pub fn log_cas_error(err: impl std::fmt::Debug) -> SwapError {
+ tracing::warn!("key-value error: {err:?}");
+ SwapError::Other(format!("{err:?}"))
+}
+
use spin_world::v1::key_value::Error as LegacyError;
+use spin_world::wasi::keyvalue::atomics;
+use spin_world::wasi::keyvalue::atomics::{CasError, HostCas};
fn to_legacy_error(value: key_value::Error) -> LegacyError {
match value {
diff --git a/crates/factor-key-value/src/lib.rs b/crates/factor-key-value/src/lib.rs
index 685766b51c..2d9dbb2d9d 100644
--- a/crates/factor-key-value/src/lib.rs
+++ b/crates/factor-key-value/src/lib.rs
@@ -15,8 +15,9 @@ use spin_locked_app::MetadataKey;
/// Metadata key for key-value stores.
pub const KEY_VALUE_STORES_KEY: MetadataKey<Vec<String>> = MetadataKey::new("key_value_stores");
-pub use host::{log_error, Error, KeyValueDispatch, Store, StoreManager};
+pub use host::{log_cas_error, log_error, Error, KeyValueDispatch, Store, StoreManager};
pub use runtime_config::RuntimeConfig;
+use spin_core::async_trait;
pub use util::{CachingStoreManager, DelegatingStoreManager};
/// A factor that provides key-value storage.
@@ -40,6 +41,9 @@ impl Factor for KeyValueFactor {
fn init<T: Send + 'static>(&mut self, mut ctx: InitContext<T, Self>) -> anyhow::Result<()> {
ctx.link_bindings(spin_world::v1::key_value::add_to_linker)?;
ctx.link_bindings(spin_world::v2::key_value::add_to_linker)?;
+ ctx.link_bindings(spin_world::wasi::keyvalue::store::add_to_linker)?;
+ ctx.link_bindings(spin_world::wasi::keyvalue::batch::add_to_linker)?;
+ ctx.link_bindings(spin_world::wasi::keyvalue::atomics::add_to_linker)?;
Ok(())
}
@@ -131,6 +135,37 @@ impl AppState {
}
}
+/// `SwapError` are errors that occur during compare and swap operations
+#[derive(Debug, thiserror::Error)]
+pub enum SwapError {
+ #[error("{0}")]
+ CasFailed(String),
+
+ #[error("{0}")]
+ Other(String),
+}
+
+/// `Cas` trait describes the interface a key value compare and swap implementor must fulfill.
+///
+/// `current` is expected to get the current value for the key associated with the CAS operation
+/// while also starting what is needed to ensure the value to be replaced will not have mutated
+/// between the time of calling `current` and `swap`. For example, a get from a backend store
+/// may provide the caller with an etag (a version stamp), which can be used with an if-match
+/// header to ensure the version updated is the version that was read (optimistic concurrency).
+/// Rather than an etag, one could start a transaction, if supported by the backing store, which
+/// would provide atomicity.
+///
+/// `swap` is expected to replace the old value with the new value respecting the atomicity of the
+/// operation. If there was no key / value with the given key in the store, the `swap` operation
+/// should **insert** the key and value, disallowing an update.
+#[async_trait]
+pub trait Cas: Sync + Send {
+ async fn current(&self) -> anyhow::Result<Option<Vec<u8>>, Error>;
+ async fn swap(&self, value: Vec<u8>) -> anyhow::Result<(), SwapError>;
+ async fn bucket_rep(&self) -> u32;
+ async fn key(&self) -> String;
+}
+
pub struct InstanceBuilder {
/// The store manager for the app.
///
diff --git a/crates/factor-key-value/src/util.rs b/crates/factor-key-value/src/util.rs
index 57c4968011..dcf8cb4e7e 100644
--- a/crates/factor-key-value/src/util.rs
+++ b/crates/factor-key-value/src/util.rs
@@ -1,4 +1,4 @@
-use crate::{Error, Store, StoreManager};
+use crate::{Cas, Error, Store, StoreManager, SwapError};
use lru::LruCache;
use spin_core::async_trait;
use std::{
@@ -92,10 +92,10 @@ impl<T: StoreManager> StoreManager for CachingStoreManager<T> {
async fn get(&self, name: &str) -> Result<Arc<dyn Store>, Error> {
Ok(Arc::new(CachingStore {
inner: self.inner.get(name).await?,
- state: AsyncMutex::new(CachingStoreState {
+ state: Arc::new(AsyncMutex::new(CachingStoreState {
cache: LruCache::new(self.capacity),
previous_task: None,
- }),
+ })),
}))
}
@@ -143,7 +143,7 @@ impl CachingStoreState {
struct CachingStore {
inner: Arc<dyn Store>,
- state: AsyncMutex<CachingStoreState>,
+ state: Arc<AsyncMutex<CachingStoreState>>,
}
#[async_trait]
@@ -237,4 +237,123 @@ impl Store for CachingStore {
.into_iter()
.collect())
}
+
+ async fn get_many(
+ &self,
+ keys: Vec<String>,
+ ) -> anyhow::Result<Vec<(String, Option<Vec<u8>>)>, Error> {
+ let mut state = self.state.lock().await;
+ let mut found: Vec<(String, Option<Vec<u8>>)> = Vec::new();
+ let mut not_found: Vec<String> = Vec::new();
+ for key in keys {
+ match state.cache.get(key.as_str()) {
+ Some(Some(value)) => found.push((key, Some(value.clone()))),
+ _ => not_found.push(key),
+ }
+ }
+
+ let keys_and_values = self.inner.get_many(not_found).await?;
+ for (key, value) in keys_and_values {
+ found.push((key.clone(), value.clone()));
+ state.cache.put(key, value);
+ }
+
+ Ok(found)
+ }
+
+ async fn set_many(&self, key_values: Vec<(String, Vec<u8>)>) -> anyhow::Result<(), Error> {
+ let mut state = self.state.lock().await;
+
+ for (key, value) in key_values.clone() {
+ state.cache.put(key, Some(value));
+ }
+
+ self.inner.set_many(key_values).await
+ }
+
+ async fn delete_many(&self, keys: Vec<String>) -> anyhow::Result<(), Error> {
+ let mut state = self.state.lock().await;
+
+ for key in keys.clone() {
+ state.cache.put(key, None);
+ }
+
+ self.inner.delete_many(keys).await
+ }
+
+ async fn increment(&self, key: String, delta: i64) -> anyhow::Result<i64, Error> {
+ let mut state = self.state.lock().await;
+ let counter = self.inner.increment(key.clone(), delta).await?;
+ state
+ .cache
+ .put(key, Some(i64::to_le_bytes(counter).to_vec()));
+ Ok(counter)
+ }
+
+ async fn new_compare_and_swap(
+ &self,
+ bucket_rep: u32,
+ key: &str,
+ ) -> anyhow::Result<Arc<dyn Cas>, Error> {
+ let inner = self.inner.new_compare_and_swap(bucket_rep, key).await?;
+ Ok(Arc::new(CompareAndSwap {
+ bucket_rep,
+ state: self.state.clone(),
+ key: key.to_string(),
+ inner_cas: inner,
+ }))
+ }
+}
+
+struct CompareAndSwap {
+ bucket_rep: u32,
+ key: String,
+ state: Arc<AsyncMutex<CachingStoreState>>,
+ inner_cas: Arc<dyn Cas>,
+}
+
+#[async_trait]
+impl Cas for CompareAndSwap {
+ async fn current(&self) -> anyhow::Result<Option<Vec<u8>>, Error> {
+ let mut state = self.state.lock().await;
+ state.flush().await?;
+ let res = self.inner_cas.current().await;
+ match res.clone() {
+ Ok(value) => {
+ state.cache.put(self.key.clone(), value.clone());
+ state.flush().await?;
+ Ok(value)
+ }
+ Err(err) => Err(err),
+ }?;
+ res
+ }
+
+ async fn swap(&self, value: Vec<u8>) -> anyhow::Result<(), SwapError> {
+ let mut state = self.state.lock().await;
+ state
+ .flush()
+ .await
+ .map_err(|_e| SwapError::Other("failed flushing".to_string()))?;
+ let res = self.inner_cas.swap(value.clone()).await;
+ match res {
+ Ok(()) => {
+ state.cache.put(self.key.clone(), Some(value));
+ state
+ .flush()
+ .await
+ .map_err(|_e| SwapError::Other("failed flushing".to_string()))?;
+ Ok(())
+ }
+ Err(err) => Err(err),
+ }
+ }
+
+ async fn bucket_rep(&self) -> u32 {
+ self.bucket_rep
+ }
+
+ async fn key(&self) -> String {
+ self.key.clone()
+ }
}
diff --git a/crates/key-value-azure/Cargo.toml b/crates/key-value-azure/Cargo.toml
index 4697b0f920..b612f3f4a4 100644
--- a/crates/key-value-azure/Cargo.toml
+++ b/crates/key-value-azure/Cargo.toml
@@ -12,6 +12,7 @@ rust-version.workspace = true
anyhow = { workspace = true }
azure_data_cosmos = { git = "https://github.com/azure/azure-sdk-for-rust.git", rev = "8c4caa251c3903d5eae848b41bb1d02a4d65231c" }
azure_identity = { git = "https://github.com/azure/azure-sdk-for-rust.git", rev = "8c4caa251c3903d5eae848b41bb1d02a4d65231c" }
+azure_core = { git = "https://github.com/azure/azure-sdk-for-rust.git", rev = "8c4caa251c3903d5eae848b41bb1d02a4d65231c" }
futures = { workspace = true }
serde = { workspace = true }
spin-core = { path = "../core" }
diff --git a/crates/key-value-azure/src/store.rs b/crates/key-value-azure/src/store.rs
index a6538e0747..258934e4df 100644
--- a/crates/key-value-azure/src/store.rs
+++ b/crates/key-value-azure/src/store.rs
@@ -1,6 +1,6 @@
-use std::sync::Arc;
-
use anyhow::Result;
+use azure_data_cosmos::prelude::Operation;
+use azure_data_cosmos::resources::collection::PartitionKey;
use azure_data_cosmos::{
prelude::{AuthorizationToken, CollectionClient, CosmosClient, Query},
CosmosEntity,
@@ -8,7 +8,8 @@ use azure_data_cosmos::{
use futures::StreamExt;
use serde::{Deserialize, Serialize};
use spin_core::async_trait;
-use spin_factor_key_value::{log_error, Error, Store, StoreManager};
+use spin_factor_key_value::{log_cas_error, log_error, Cas, Error, Store, StoreManager, SwapError};
+use std::sync::{Arc, Mutex};
pub struct KeyValueAzureCosmos {
client: CollectionClient,
@@ -111,11 +112,19 @@ impl StoreManager for KeyValueAzureCosmos {
}
}
+#[derive(Clone)]
struct AzureCosmosStore {
_name: String,
client: CollectionClient,
}
+struct CompareAndSwap {
+ key: String,
+ client: CollectionClient,
+ bucket_rep: u32,
+ etag: Mutex<Option<String>>,
+}
+
#[async_trait]
impl Store for AzureCosmosStore {
async fn get(&self, key: &str) -> Result<Option<Vec<u8>>, Error> {
@@ -151,6 +160,160 @@ impl Store for AzureCosmosStore {
async fn get_keys(&self) -> Result<Vec<String>, Error> {
self.get_keys().await
}
+
+ async fn get_many(&self, keys: Vec<String>) -> Result<Vec<(String, Option<Vec<u8>>)>, Error> {
+ let in_clause: String = keys
+ .into_iter()
+ .map(|k| format!("'{}'", k))
+ .collect::<Vec<String>>()
+ .join(", ");
+ let stmt = Query::new(format!("SELECT * FROM c WHERE c.id IN ({})", in_clause));
+ let query = self
+ .client
+ .query_documents(stmt)
+ .query_cross_partition(true);
+
+ let mut res = Vec::new();
+ let mut stream = query.into_stream::<Pair>();
+ while let Some(resp) = stream.next().await {
+ let resp = resp.map_err(log_error)?;
+ for (pair, _) in resp.results {
+ res.push((pair.id, Some(pair.value)));
+ }
+ }
+ Ok(res)
+ }
+
+ async fn set_many(&self, key_values: Vec<(String, Vec<u8>)>) -> Result<(), Error> {
+ for (key, value) in key_values {
+ self.set(key.as_ref(), &value).await?
+ }
+ Ok(())
+ }
+
+ async fn delete_many(&self, keys: Vec<String>) -> Result<(), Error> {
+ for key in keys {
+ self.delete(key.as_ref()).await?
+ }
+ Ok(())
+ }
+
+ async fn increment(&self, key: String, delta: i64) -> Result<i64, Error> {
+ let operations = vec![Operation::incr("/value", delta).map_err(log_error)?];
+ let _ = self
+ .client
+ .document_client(key.clone(), &key.as_str())
+ .map_err(log_error)?
+ .patch_document(operations)
+ .await
+ .map_err(log_error)?;
+ let pair = self.get_pair(key.as_ref()).await?;
+ match pair {
+ Some(p) => Ok(i64::from_le_bytes(
+ p.value.try_into().expect("incorrect length"),
+ )),
+ None => Err(Error::Other(
+ "increment returned an empty value after patching, which indicates a bug"
+ .to_string(),
+ )),
+ }
+ }
+
+ async fn new_compare_and_swap(
+ &self,
+ bucket_rep: u32,
+ key: &str,
+ ) -> Result<Arc<dyn spin_factor_key_value::Cas>, Error> {
+ Ok(Arc::new(CompareAndSwap {
+ key: key.to_string(),
+ client: self.client.clone(),
+ etag: Mutex::new(None),
+ bucket_rep,
+ }))
+ }
+}
+
+#[async_trait]
+impl Cas for CompareAndSwap {
+ /// `current` will fetch the current value for the key and store the etag for the record. The
+ /// etag will be used to perform and optimistic concurrency update using the `if-match` header.
+ async fn current(&self) -> Result<Option<Vec<u8>>, Error> {
+ let mut stream = self
+ .client
+ .query_documents(Query::new(format!(
+ "SELECT * FROM c WHERE c.id='{}'",
+ self.key
+ )))
+ .query_cross_partition(true)
+ .max_item_count(1)
+ .into_stream::<Pair>();
+
+ let current_value: Option<(Vec<u8>, Option<String>)> = match stream.next().await {
+ Some(r) => {
+ let r = r.map_err(log_error)?;
+ match r.results.first() {
+ Some((item, Some(attr))) => {
+ Some((item.clone().value, Some(attr.etag().to_string())))
+ }
+ Some((item, None)) => Some((item.clone().value, None)),
+ _ => None,
+ }
+ }
+ None => None,
+ };
+
+ match current_value {
+ Some((value, etag)) => {
+ self.etag.lock().unwrap().clone_from(&etag);
+ Ok(Some(value))
+ }
+ None => Ok(None),
+ }
+ }
+
+ /// `swap` updates the value for the key using the etag saved in the `current` function for
+ /// optimistic concurrency.
+ async fn swap(&self, value: Vec<u8>) -> Result<(), SwapError> {
+ let pk = PartitionKey::from(&self.key);
+ let pair = Pair {
+ id: self.key.clone(),
+ value,
+ };
+
+ let doc_client = self
+ .client
+ .document_client(&self.key, &pk)
+ .map_err(log_cas_error)?;
+
+ let etag_value = self.etag.lock().unwrap().clone();
+ match etag_value {
+ Some(etag) => {
+ // attempt to replace the document if the etag matches
+ doc_client
+ .replace_document(pair)
+ .if_match_condition(azure_core::request_options::IfMatchCondition::Match(etag))
+ .await
+ .map_err(|e| SwapError::CasFailed(format!("{e:?}")))
+ .map(drop)
+ }
+ None => {
+ // if we have no etag, then we assume the document does not yet exist and must insert; no upserts.
+ self.client
+ .create_document(pair)
+ .await
+ .map_err(|e| SwapError::CasFailed(format!("{e:?}")))
+ .map(drop)
+ }
+ }
+ }
+
+ async fn bucket_rep(&self) -> u32 {
+ self.bucket_rep
+ }
+
+ async fn key(&self) -> String {
+ self.key.clone()
+ }
}
impl AzureCosmosStore {
diff --git a/crates/key-value-redis/src/store.rs b/crates/key-value-redis/src/store.rs
index 8d2950305f..1fbbabc6c0 100644
--- a/crates/key-value-redis/src/store.rs
+++ b/crates/key-value-redis/src/store.rs
@@ -1,7 +1,8 @@
use anyhow::{Context, Result};
-use redis::{aio::MultiplexedConnection, parse_redis_url, AsyncCommands};
+use redis::{aio::MultiplexedConnection, parse_redis_url, AsyncCommands, Client, RedisError};
use spin_core::async_trait;
-use spin_factor_key_value::{log_error, Error, Store, StoreManager};
+use spin_factor_key_value::{log_error, Cas, Error, Store, StoreManager, SwapError};
+use std::ops::DerefMut;
use std::sync::Arc;
use tokio::sync::{Mutex, OnceCell};
use url::Url;
@@ -28,7 +29,7 @@ impl StoreManager for KeyValueRedis {
let connection = self
.connection
.get_or_try_init(|| async {
- redis::Client::open(self.database_url.clone())?
+ Client::open(self.database_url.clone())?
.get_multiplexed_async_connection()
.await
.map(Mutex::new)
@@ -39,6 +40,7 @@ impl StoreManager for KeyValueRedis {
Ok(Arc::new(RedisStore {
connection: connection.clone(),
+ database_url: self.database_url.clone(),
}))
}
@@ -54,6 +56,13 @@ impl StoreManager for KeyValueRedis {
struct RedisStore {
connection: Arc<Mutex<MultiplexedConnection>>,
+ database_url: Url,
+}
+
+struct CompareAndSwap {
+ key: String,
+ connection: Arc<Mutex<MultiplexedConnection>>,
+ bucket_rep: u32,
}
#[async_trait]
@@ -98,4 +107,113 @@ impl Store for RedisStore {
.await
.map_err(log_error)
}
+
+ async fn get_many(&self, keys: Vec<String>) -> Result<Vec<(String, Option<Vec<u8>>)>, Error> {
+ self.connection
+ .lock()
+ .await
+ .keys(keys)
+ .await
+ .map_err(log_error)
+ }
+
+ async fn set_many(&self, key_values: Vec<(String, Vec<u8>)>) -> Result<(), Error> {
+ self.connection
+ .lock()
+ .await
+ .mset(&key_values)
+ .await
+ .map_err(log_error)
+ }
+
+ async fn delete_many(&self, keys: Vec<String>) -> Result<(), Error> {
+ self.connection
+ .lock()
+ .await
+ .del(keys)
+ .await
+ .map_err(log_error)
+ }
+
+ async fn increment(&self, key: String, delta: i64) -> Result<i64, Error> {
+ self.connection
+ .lock()
+ .await
+ .incr(key, delta)
+ .await
+ .map_err(log_error)
+ }
+
+ /// `new_compare_and_swap` builds a new CAS structure giving it its own connection since Redis
+ /// transactions are scoped to a connection and any WATCH should be dropped upon the drop of
+ /// the connection.
+ async fn new_compare_and_swap(
+ &self,
+ bucket_rep: u32,
+ key: &str,
+ ) -> Result<Arc<dyn Cas>, Error> {
+ let cx = Client::open(self.database_url.clone())
+ .map_err(log_error)?
+ .get_multiplexed_async_connection()
+ .await
+ .map(Mutex::new)
+ .map(Arc::new)
+ .map_err(log_error)?;
+
+ Ok(Arc::new(CompareAndSwap {
+ key: key.to_string(),
+ connection: cx,
+ bucket_rep,
+ }))
+ }
+}
+
+#[async_trait]
+impl Cas for CompareAndSwap {
+ /// current will initiate a transaction by WATCH'ing a key in Redis, and then returning the
+ /// current value for the key.
+ async fn current(&self) -> Result<Option<Vec<u8>>, Error> {
+ redis::cmd("WATCH")
+ .arg(&self.key)
+ .exec_async(self.connection.lock().await.deref_mut())
+ .await
+ .map_err(log_error)?;
+ self.connection
+ .lock()
+ .await
+ .get(&self.key)
+ .await
+ .map_err(log_error)
+ }
+
+ /// swap will set the key to the new value only if the key has not changed. Afterward, the
+ /// transaction will be terminated with an UNWATCH
+ async fn swap(&self, value: Vec<u8>) -> Result<(), SwapError> {
+ // Create transaction pipeline
+ let mut transaction = redis::pipe();
+ let res: Result<(), RedisError> = transaction
+ .atomic()
+ .set(&self.key, value)
+ .query_async(self.connection.lock().await.deref_mut())
+ .await;
+
+ redis::cmd("UNWATCH")
+ .arg(&self.key)
+ .exec_async(self.connection.lock().await.deref_mut())
+ .await
+ .map_err(|err| SwapError::CasFailed(format!("{err:?}")))?;
+
+ match res {
+ Ok(_) => Ok(()),
+ Err(err) => Err(SwapError::CasFailed(format!("{err:?}"))),
+ }
+ }
+
+ async fn bucket_rep(&self) -> u32 {
+ self.bucket_rep
+ }
+
+ async fn key(&self) -> String {
+ self.key.clone()
+ }
}
diff --git a/crates/key-value-spin/Cargo.toml b/crates/key-value-spin/Cargo.toml
index 84a522f27c..6c431c7ad6 100644
--- a/crates/key-value-spin/Cargo.toml
+++ b/crates/key-value-spin/Cargo.toml
@@ -6,7 +6,7 @@ edition = { workspace = true }
[dependencies]
anyhow = { workspace = true }
-rusqlite = { version = "0.32", features = ["bundled"] }
+rusqlite = { version = "0.32", features = ["bundled", "array"] }
serde = { workspace = true }
spin-core = { path = "../core" }
spin-factor-key-value = { path = "../factor-key-value" }
diff --git a/crates/key-value-spin/src/store.rs b/crates/key-value-spin/src/store.rs
index e12f5e05c7..f18b60f7b7 100644
--- a/crates/key-value-spin/src/store.rs
+++ b/crates/key-value-spin/src/store.rs
@@ -1,7 +1,8 @@
use anyhow::Result;
-use rusqlite::Connection;
+use rusqlite::{named_params, Connection};
use spin_core::async_trait;
-use spin_factor_key_value::{log_error, Error, Store, StoreManager};
+use spin_factor_key_value::{log_cas_error, log_error, Cas, Error, Store, StoreManager, SwapError};
+use std::rc::Rc;
use std::{
path::PathBuf,
sync::OnceLock,
@@ -53,6 +54,9 @@ impl KeyValueSqlite {
)
.map_err(log_error)?;
+ // the array module is needed for `rarray` usage in queries.
+ rusqlite::vtab::array::load_module(&connection).map_err(log_error)?;
+
Ok(Arc::new(Mutex::new(connection)))
}
}
@@ -156,6 +160,184 @@ impl Store for SqliteStore {
.collect()
})
}
+
+ async fn get_many(&self, keys: Vec<String>) -> Result<Vec<(String, Option<Vec<u8>>)>, Error> {
+ task::block_in_place(|| {
+ let sql_value_keys: Vec<rusqlite::types::Value> =
+ keys.into_iter().map(rusqlite::types::Value::from).collect();
+ let ptr = Rc::new(sql_value_keys);
+ let row_iter: Vec<Result<(String, Option<Vec<u8>>), Error>> = self.connection
+ .lock()
+ .unwrap()
+ .prepare_cached("SELECT key, value FROM spin_key_value WHERE store=:name AND key IN rarray(:keys)")
+ .map_err(log_error)?
+ .query_map(named_params! {":name": &self.name, ":keys": ptr}, |row| {
+ <(String, Option<Vec<u8>>)>::try_from(row)
+ })
+ .map_err(log_error)?
+ .map(|r: Result<(String, Option<Vec<u8>>), rusqlite::Error>| r.map_err(log_error))
+ .collect();
+
+ let mut keys_and_values: Vec<(String, Option<Vec<u8>>)> = Vec::new();
+ for row in row_iter {
+ let res = row.map_err(log_error)?;
+ keys_and_values.push(res);
+ }
+ Ok(keys_and_values)
+ })
+ }
+
+ async fn set_many(&self, key_values: Vec<(String, Vec<u8>)>) -> Result<(), Error> {
+ task::block_in_place(|| {
+ let mut binding = self.connection.lock().unwrap();
+ let tx = binding.transaction().map_err(log_error)?;
+ for kv in key_values {
+ tx.prepare_cached(
+ "INSERT INTO spin_key_value (store, key, value) VALUES ($1, $2, $3)
+ ON CONFLICT(store, key) DO UPDATE SET value=$3",
+ )
+ .map_err(log_error)?
+ .execute(rusqlite::params![&self.name, kv.0, kv.1])
+ .map_err(log_error)
+ .map(drop)?;
+ }
+ tx.commit().map_err(log_error)
+ })
+ }
+
+ async fn delete_many(&self, keys: Vec<String>) -> Result<(), Error> {
+ task::block_in_place(|| {
+ let sql_value_keys: Vec<rusqlite::types::Value> =
+ keys.into_iter().map(rusqlite::types::Value::from).collect();
+ let ptr = Rc::new(sql_value_keys);
+ self.connection
+ .lock()
+ .unwrap()
+ .prepare_cached(
+ "DELETE FROM spin_key_value WHERE store=:name AND key IN rarray(:keys)",
+ )
+ .map_err(log_error)?
+ .execute(named_params! {":name": &self.name, ":keys": ptr})
+ .map_err(log_error)
+ .map(drop)
+ })
+ }
+
+ // The assumption with increment is that if the value for the key does not exist, it will be
+ // assumed to be zero. In the case that we are unable to unmarshal the value into an i64 an error will be returned.
+ async fn increment(&self, key: String, delta: i64) -> Result<i64, Error> {
+ task::block_in_place(|| {
+ let mut binding = self.connection.lock().unwrap();
+
+ let tx = binding.transaction().map_err(log_error)?;
+
+ let value: Option<Vec<u8>> = tx
+ .prepare_cached("SELECT value FROM spin_key_value WHERE store=$1 AND key=$2")
+ .map_err(log_error)?
+ .query_map([&self.name, &key], |row| row.get(0))
+ .map_err(log_error)?
+ .next()
+ .transpose()
+ .map_err(log_error)?;
+
+ let numeric: i64 = match value {
+ Some(v) => i64::from_le_bytes(v.try_into().expect("incorrect length")),
+ None => 0,
+ };
+
+ let new_value = numeric + delta;
+ tx.prepare_cached(
+ "INSERT INTO spin_key_value (store, key, value) VALUES ($1, $2, $3)
+ ON CONFLICT(store, key) DO UPDATE SET value=$3",
+ )
+ .map_err(log_error)?
+ .execute(rusqlite::params![&self.name, key, new_value.to_le_bytes()])
+ .map_err(log_error)
+ .map(drop)?;
+
+ tx.commit().map_err(log_error)?;
+ Ok(new_value)
+ })
+ }
+
+ async fn new_compare_and_swap(
+ &self,
+ bucket_rep: u32,
+ key: &str,
+ ) -> Result<Arc<dyn Cas>, Error> {
+ Ok(Arc::new(CompareAndSwap {
+ name: self.name.clone(),
+ key: key.to_string(),
+ connection: self.connection.clone(),
+ value: Mutex::new(None),
+ bucket_rep,
+ }))
+ }
+}
+
+struct CompareAndSwap {
+ name: String,
+ key: String,
+ value: Mutex<Option<Vec<u8>>>,
+ connection: Arc<Mutex<Connection>>,
+ bucket_rep: u32,
+}
+
+#[async_trait]
+impl Cas for CompareAndSwap {
+ async fn current(&self) -> Result<Option<Vec<u8>>, Error> {
+ task::block_in_place(|| {
+ let value: Option<Vec<u8>> = self
+ .connection
+ .lock()
+ .unwrap()
+ .prepare_cached("SELECT value FROM spin_key_value WHERE store=$1 AND key=$2")
+ .map_err(log_error)?
+ .query_map([&self.name, &self.key], |row| row.get(0))
+ .map_err(log_error)?
+ .next()
+ .transpose()
+ .map_err(log_error)?;
+
+ self.value.lock().unwrap().clone_from(&value);
+ Ok(value.clone())
+ })
+ }
+
+ async fn swap(&self, value: Vec<u8>) -> Result<(), SwapError> {
+ task::block_in_place(|| {
+ let old_value = self.value.lock().unwrap();
+ let rows_changed = self.connection
+ .lock()
+ .unwrap()
+ .prepare_cached(
+ "UPDATE spin_key_value SET value=:new_value WHERE store=:name and key=:key and value=:old_value",
+ )
+ .map_err(log_cas_error)?
+ .execute(named_params! {
+ ":name": &self.name,
+ ":key": self.key,
+ ":old_value": old_value.clone().unwrap(),
+ ":new_value": value,
+ })
+ .map_err(log_cas_error)?;
+
+ // We expect only 1 row to be updated. If 0, we know that the underlying value has changed.
+ if rows_changed == 1 {
+ Ok(())
+ } else {
+ Err(SwapError::CasFailed("failed to update 1 row".to_owned()))
+ }
+ })
+ }
+
+ async fn bucket_rep(&self) -> u32 {
+ self.bucket_rep
+ }
+
+ async fn key(&self) -> String {
+ self.key.clone()
+ }
}
#[cfg(test)]
@@ -164,6 +346,9 @@ mod test {
use spin_core::wasmtime::component::Resource;
use spin_factor_key_value::{DelegatingStoreManager, KeyValueDispatch};
use spin_world::v2::key_value::HostStore;
+ use spin_world::wasi::keyvalue::atomics::HostCas as wasi_cas_host;
+ use spin_world::wasi::keyvalue::atomics::{CasError, Host};
+ use spin_world::wasi::keyvalue::batch::Host as wasi_batch_host;
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn all() -> Result<()> {
@@ -248,8 +433,123 @@ mod test {
Ok(None)
));
- kv.drop(Resource::new_own(rep)).await?;
+ let keys_and_values: Vec<(String, Vec<u8>)> = vec![
+ ("bin".to_string(), b"baz".to_vec()),
+ ("alex".to_string(), b"pat".to_vec()),
+ ];
+ assert!(kv
+ .set_many(Resource::new_own(rep), keys_and_values.clone())
+ .await
+ .is_ok());
+
+ let res = kv
+ .get_many(
+ Resource::new_own(rep),
+ keys_and_values
+ .clone()
+ .iter()
+ .map(|key_value| key_value.0.clone())
+ .collect(),
+ )
+ .await;
+
+ assert!(res.is_ok(), "failed with {:?}", res.err());
+ assert_eq!(
+ kv.get(Resource::new_own(rep), "bin".to_owned())
+ .await??
+ .unwrap(),
+ b"baz".to_vec()
+ );
+
+ assert_eq!(kv_incr(&mut kv, rep, 1).await, 1);
+ assert_eq!(kv_incr(&mut kv, rep, 2).await, 3);
+ assert_eq!(kv_incr(&mut kv, rep, -10).await, -7);
+
+ let res = kv
+ .delete_many(
+ Resource::new_own(rep),
+ vec!["counter".to_owned(), "bin".to_owned(), "alex".to_owned()],
+ )
+ .await;
+ assert!(res.is_ok(), "failed with {:?}", res.err());
+ assert_eq!(kv.get_keys(Resource::new_own(rep)).await??.len(), 0);
+
+ // Compare and Swap tests
+ cas_failed(&mut kv, rep).await?;
+ cas_succeeds(&mut kv, rep).await?;
+
+ HostStore::drop(&mut kv, Resource::new_own(rep)).await?;
Ok(())
}
+
+ async fn cas_failed(kv: &mut KeyValueDispatch, rep: u32) -> Result<()> {
+ let cas_key = "fail".to_owned();
+ let cas_orig_value = b"baz".to_vec();
+ kv.set(
+ Resource::new_own(rep),
+ cas_key.clone(),
+ cas_orig_value.clone(),
+ )
+ .await??;
+ let cas = kv.new(Resource::new_own(rep), cas_key.clone()).await?;
+ let cas_rep = cas.rep();
+ let current_val = kv.current(Resource::new_own(cas_rep)).await?.unwrap();
+ assert_eq!(
+ String::from_utf8(cas_orig_value)?,
+ String::from_utf8(current_val)?
+ );
+
+ // change the value midway through a compare_and_set
+ kv.set(Resource::new_own(rep), cas_key.clone(), b"foo".to_vec())
+ .await??;
+ let cas_final_value = b"This should fail with a CAS error".to_vec();
+ let res = kv.swap(Resource::new_own(cas.rep()), cas_final_value).await;
+ match res {
+ Ok(_) => panic!("expected a CAS failure"),
+ Err(err) => {
+ for cause in err.chain() {
+ if let Some(cas_err) = cause.downcast_ref::<CasError>() {
+ assert!(matches!(cas_err, CasError::CasFailed(_)));
+ return Ok(());
+ }
+ }
+ panic!("expected a CAS failure")
+ }
+ }
+ }
+
+ async fn cas_succeeds(kv: &mut KeyValueDispatch, rep: u32) -> Result<()> {
+ let cas_key = "succeed".to_owned();
+ let cas_orig_value = b"baz".to_vec();
+ kv.set(
+ Resource::new_own(rep),
+ cas_key.clone(),
+ cas_orig_value.clone(),
+ )
+ .await??;
+ let cas = kv.new(Resource::new_own(rep), cas_key.clone()).await?;
+ let cas_rep = cas.rep();
+ let current_val = kv.current(Resource::new_own(cas_rep)).await?.unwrap();
+ assert_eq!(
+ String::from_utf8(cas_orig_value)?,
+ String::from_utf8(current_val)?
+ );
+ let cas_final_value = b"This should update key bar".to_vec();
+ let res = kv.swap(Resource::new_own(cas.rep()), cas_final_value).await;
+ match res {
+ Ok(_) => Ok(()),
+ Err(err) => {
+ panic!("unexpected err: {:?}", err);
+ }
+ }
+ }
+
+ async fn kv_incr(kv: &mut KeyValueDispatch, rep: u32, delta: i64) -> i64 {
+ let res = kv
+ .increment(Resource::new_own(rep), "counter".to_owned(), delta)
+ .await;
+ assert!(res.is_ok(), "failed with {:?}", res.err());
+ res.unwrap()
+ }
}
diff --git a/crates/world/src/lib.rs b/crates/world/src/lib.rs
index 4aa2ecbd0c..a3ecf810e4 100644
--- a/crates/world/src/lib.rs
+++ b/crates/world/src/lib.rs
@@ -10,6 +10,7 @@ wasmtime::component::bindgen!({
include fermyon:spin/host;
include fermyon:spin/platform@2.0.0;
include fermyon:spin/platform@3.0.0;
+ include wasi:keyvalue/imports@0.2.0-draft2;
}
"#,
path: "../../wit",
@@ -31,6 +32,7 @@ wasmtime::component::bindgen!({
"fermyon:spin/variables@2.0.0/error" => v2::variables::Error,
"spin:postgres/postgres/error" => spin::postgres::postgres::Error,
"wasi:config/store@0.2.0-draft-2024-09-27/error" => wasi::config::store::Error,
+ "wasi:keyvalue/store/error" => wasi::keyvalue::store::Error,
},
trappable_imports: true,
});
diff --git a/wit/deps/keyvalue-2024-10-17/atomic.wit b/wit/deps/keyvalue-2024-10-17/atomic.wit
new file mode 100644
index 0000000000..2c3e0d047b
--- /dev/null
+++ b/wit/deps/keyvalue-2024-10-17/atomic.wit
@@ -0,0 +1,46 @@
+/// A keyvalue interface that provides atomic operations.
+///
+/// Atomic operations are single, indivisible operations. When a fault causes an atomic operation to
+/// fail, it will appear to the invoker of the atomic operation that the action either completed
+/// successfully or did nothing at all.
+///
+/// Please note that this interface is bare functions that take a reference to a bucket. This is to
+/// get around the current lack of a way to "extend" a resource with additional methods inside of
+/// wit. Future version of the interface will instead extend these methods on the base `bucket`
+/// resource.
+interface atomics {
+ use store.{bucket, error};
+
+ /// The error returned by a CAS operation
+ variant cas-error {
+ /// A store error occurred when performing the operation
+ store-error(error),
+ /// The CAS operation failed because the value was too old. This returns a new CAS handle
+ /// for easy retries. Implementors MUST return a CAS handle that has been updated to the
+ /// latest version or transaction.
+ cas-failed(cas),
+ }
+
+ /// A handle to a CAS (compare-and-swap) operation.
+ resource cas {
+ /// Construct a new CAS operation. Implementors can map the underlying functionality
+ /// (transactions, versions, etc) as desired.
+ new: static func(bucket: borrow<bucket>, key: string) -> result<cas, error>;
+ /// Get the current value of the key (if it exists). This allows for avoiding reads if all
+ /// that is needed to ensure the atomicity of the operation
+ current: func() -> result<option<list<u8>>, error>;
+ }
+
+ /// Atomically increment the value associated with the key in the store by the given delta. It
+ /// returns the new value.
+ ///
+ /// If the key does not exist in the store, it creates a new key-value pair with the value set
+ /// to the given delta.
+ ///
+ /// If any other error occurs, it returns an `Err(error)`.
+ increment: func(bucket: borrow<bucket>, key: string, delta: s64) -> result<s64, error>;
+
+ /// Perform the swap on a CAS operation. This consumes the CAS handle and returns an error if
+ /// the CAS operation failed.
+ swap: func(cas: cas, value: list<u8>) -> result<_, cas-error>;
+}
diff --git a/wit/deps/keyvalue-2024-10-17/batch.wit b/wit/deps/keyvalue-2024-10-17/batch.wit
new file mode 100644
index 0000000000..6d6e873553
--- /dev/null
+++ b/wit/deps/keyvalue-2024-10-17/batch.wit
@@ -0,0 +1,63 @@
+/// A keyvalue interface that provides batch operations.
+///
+/// A batch operation is an operation that operates on multiple keys at once.
+///
+/// Batch operations are useful for reducing network round-trip time. For example, if you want to
+/// get the values associated with 100 keys, you can either do 100 get operations or you can do 1
+/// batch get operation. The batch operation is faster because it only needs to make 1 network call
+/// instead of 100.
+///
+/// A batch operation does not guarantee atomicity, meaning that if the batch operation fails, some
+/// of the keys may have been modified and some may not.
+///
+/// This interface does has the same consistency guarantees as the `store` interface, meaning that
+/// you should be able to "read your writes."
+///
+/// Please note that this interface is bare functions that take a reference to a bucket. This is to
+/// get around the current lack of a way to "extend" a resource with additional methods inside of
+/// wit. Future version of the interface will instead extend these methods on the base `bucket`
+/// resource.
+interface batch {
+ use store.{bucket, error};
+
+ /// Get the key-value pairs associated with the keys in the store. It returns a list of
+ /// key-value pairs.
+ ///
+ /// If any of the keys do not exist in the store, it returns a `none` value for that pair in the
+ /// list.
+ ///
+ /// MAY show an out-of-date value if there are concurrent writes to the store.
+ ///
+ /// If any other error occurs, it returns an `Err(error)`.
+ get-many: func(bucket: borrow<bucket>, keys: list<string>) -> result<list<tuple<string, option<list<u8>>>>, error>;
+
+ /// Set the values associated with the keys in the store. If the key already exists in the
+ /// store, it overwrites the value.
+ ///
+ /// Note that the key-value pairs are not guaranteed to be set in the order they are provided.
+ ///
+ /// If any of the keys do not exist in the store, it creates a new key-value pair.
+ ///
+ /// If any other error occurs, it returns an `Err(error)`. When an error occurs, it does not
+ /// rollback the key-value pairs that were already set. Thus, this batch operation does not
+ /// guarantee atomicity, implying that some key-value pairs could be set while others might
+ /// fail.
+ ///
+ /// Other concurrent operations may also be able to see the partial results.
+ set-many: func(bucket: borrow<bucket>, key-values: list<tuple<string, list<u8>>>) -> result<_, error>;
+
+ /// Delete the key-value pairs associated with the keys in the store.
+ ///
+ /// Note that the key-value pairs are not guaranteed to be deleted in the order they are
+ /// provided.
+ ///
+ /// If any of the keys do not exist in the store, it skips the key.
+ ///
+ /// If any other error occurs, it returns an `Err(error)`. When an error occurs, it does not
+ /// rollback the key-value pairs that were already deleted. Thus, this batch operation does not
+ /// guarantee atomicity, implying that some key-value pairs could be deleted while others might
+ /// fail.
+ ///
+ /// Other concurrent operations may also be able to see the partial results.
+ delete-many: func(bucket: borrow<bucket>, keys: list<string>) -> result<_, error>;
+}
diff --git a/wit/deps/keyvalue-2024-10-17/store.wit b/wit/deps/keyvalue-2024-10-17/store.wit
new file mode 100644
index 0000000000..c7fef41135
--- /dev/null
+++ b/wit/deps/keyvalue-2024-10-17/store.wit
@@ -0,0 +1,122 @@
+/// A keyvalue interface that provides eventually consistent key-value operations.
+///
+/// Each of these operations acts on a single key-value pair.
+///
+/// The value in the key-value pair is defined as a `u8` byte array and the intention is that it is
+/// the common denominator for all data types defined by different key-value stores to handle data,
+/// ensuring compatibility between different key-value stores. Note: the clients will be expecting
+/// serialization/deserialization overhead to be handled by the key-value store. The value could be
+/// a serialized object from JSON, HTML or vendor-specific data types like AWS S3 objects.
+///
+/// Data consistency in a key value store refers to the guarantee that once a write operation
+/// completes, all subsequent read operations will return the value that was written.
+///
+/// Any implementation of this interface must have enough consistency to guarantee "reading your
+/// writes." In particular, this means that the client should never get a value that is older than
+/// the one it wrote, but it MAY get a newer value if one was written around the same time. These
+/// guarantees only apply to the same client (which will likely be provided by the host or an
+/// external capability of some kind). In this context a "client" is referring to the caller or
+/// guest that is consuming this interface. Once a write request is committed by a specific client,
+/// all subsequent read requests by the same client will reflect that write or any subsequent
+/// writes. Another client running in a different context may or may not immediately see the result
+/// due to the replication lag. As an example of all of this, if a value at a given key is A, and
+/// the client writes B, then immediately reads, it should get B. If something else writes C in
+/// quick succession, then the client may get C. However, a client running in a separate context may
+/// still see A or B
+interface store {
+ /// The set of errors which may be raised by functions in this package
+ variant error {
+ /// The host does not recognize the store identifier requested.
+ no-such-store,
+
+ /// The requesting component does not have access to the specified store
+ /// (which may or may not exist).
+ access-denied,
+
+ /// Some implementation-specific error has occurred (e.g. I/O)
+ other(string)
+ }
+
+ /// A response to a `list-keys` operation.
+ record key-response {
+ /// The list of keys returned by the query.
+ keys: list<string>,
+ /// The continuation token to use to fetch the next page of keys. If this is `null`, then
+ /// there are no more keys to fetch.
+ cursor: option<string>
+ }
+
+ /// Get the bucket with the specified identifier.
+ ///
+ /// `identifier` must refer to a bucket provided by the host.
+ ///
+ /// `error::no-such-store` will be raised if the `identifier` is not recognized.
+ open: func(identifier: string) -> result<bucket, error>;
+
+ /// A bucket is a collection of key-value pairs. Each key-value pair is stored as a entry in the
+ /// bucket, and the bucket itself acts as a collection of all these entries.
+ ///
+ /// It is worth noting that the exact terminology for bucket in key-value stores can very
+ /// depending on the specific implementation. For example:
+ ///
+ /// 1. Amazon DynamoDB calls a collection of key-value pairs a table
+ /// 2. Redis has hashes, sets, and sorted sets as different types of collections
+ /// 3. Cassandra calls a collection of key-value pairs a column family
+ /// 4. MongoDB calls a collection of key-value pairs a collection
+ /// 5. Riak calls a collection of key-value pairs a bucket
+ /// 6. Memcached calls a collection of key-value pairs a slab
+ /// 7. Azure Cosmos DB calls a collection of key-value pairs a container
+ ///
+ /// In this interface, we use the term `bucket` to refer to a collection of key-value pairs
+ resource bucket {
+ /// Get the value associated with the specified `key`
+ ///
+ /// The value is returned as an option. If the key-value pair exists in the
+ /// store, it returns `Ok(value)`. If the key does not exist in the
+ /// store, it returns `Ok(none)`.
+ ///
+ /// If any other error occurs, it returns an `Err(error)`.
+ get: func(key: string) -> result<option<list<u8>>, error>;
+
+ /// Set the value associated with the key in the store. If the key already
+ /// exists in the store, it overwrites the value.
+ ///
+ /// If the key does not exist in the store, it creates a new key-value pair.
+ ///
+ /// If any other error occurs, it returns an `Err(error)`.
+ set: func(key: string, value: list<u8>) -> result<_, error>;
+
+ /// Delete the key-value pair associated with the key in the store.
+ ///
+ /// If the key does not exist in the store, it does nothing.
+ ///
+ /// If any other error occurs, it returns an `Err(error)`.
+ delete: func(key: string) -> result<_, error>;
+
+ /// Check if the key exists in the store.
+ ///
+ /// If the key exists in the store, it returns `Ok(true)`. If the key does
+ /// not exist in the store, it returns `Ok(false)`.
+ ///
+ /// If any other error occurs, it returns an `Err(error)`.
+ exists: func(key: string) -> result<bool, error>;
+
+ /// Get all the keys in the store with an optional cursor (for use in pagination). It
+ /// returns a list of keys. Please note that for most KeyValue implementations, this is a
+ /// can be a very expensive operation and so it should be used judiciously. Implementations
+ /// can return any number of keys in a single response, but they should never attempt to
+ /// send more data than is reasonable (i.e. on a small edge device, this may only be a few
+ /// KB, while on a large machine this could be several MB). Any response should also return
+ /// a cursor that can be used to fetch the next page of keys. See the `key-response` record
+ /// for more information.
+ ///
+ /// Note that the keys are not guaranteed to be returned in any particular order.
+ ///
+ /// If the store is empty, it returns an empty list.
+ ///
+ /// MAY show an out-of-date list of keys if there are concurrent writes to the store.
+ ///
+ /// If any error occurs, it returns an `Err(error)`.
+ list-keys: func(cursor: option<string>) -> result<key-response, error>;
+ }
+}
diff --git a/wit/deps/keyvalue-2024-10-17/watch.wit b/wit/deps/keyvalue-2024-10-17/watch.wit
new file mode 100644
index 0000000000..9299119624
--- /dev/null
+++ b/wit/deps/keyvalue-2024-10-17/watch.wit
@@ -0,0 +1,16 @@
+/// A keyvalue interface that provides watch operations.
+///
+/// This interface is used to provide event-driven mechanisms to handle
+/// keyvalue changes.
+interface watcher {
+ /// A keyvalue interface that provides handle-watch operations.
+ use store.{bucket};
+
+ /// Handle the `set` event for the given bucket and key. It includes a reference to the `bucket`
+ /// that can be used to interact with the store.
+ on-set: func(bucket: bucket, key: string, value: list<u8>);
+
+ /// Handle the `delete` event for the given bucket and key. It includes a reference to the
+ /// `bucket` that can be used to interact with the store.
+ on-delete: func(bucket: bucket, key: string);
+}
diff --git a/wit/deps/keyvalue-2024-10-17/world.wit b/wit/deps/keyvalue-2024-10-17/world.wit
new file mode 100644
index 0000000000..64eb4e1225
--- /dev/null
+++ b/wit/deps/keyvalue-2024-10-17/world.wit
@@ -0,0 +1,26 @@
+package wasi: keyvalue@0.2.0-draft2;
+
+/// The `wasi:keyvalue/imports` world provides common APIs for interacting with key-value stores.
+/// Components targeting this world will be able to do:
+///
+/// 1. CRUD (create, read, update, delete) operations on key-value stores.
+/// 2. Atomic `increment` and CAS (compare-and-swap) operations.
+/// 3. Batch operations that can reduce the number of round trips to the network.
+world imports {
+ /// The `store` capability allows the component to perform eventually consistent operations on
+ /// the key-value store.
+ import store;
+
+ /// The `atomic` capability allows the component to perform atomic / `increment` and CAS
+ /// (compare-and-swap) operations.
+ import atomics;
+
+ /// The `batch` capability allows the component to perform eventually consistent batch
+ /// operations that can reduce the number of round trips to the network.
+ import batch;
+}
+
+world watch-service {
+ include imports;
+ export watcher;
+}
diff --git a/wit/world.wit b/wit/world.wit
index 55a369174b..07da9cd4bf 100644
--- a/wit/world.wit
+++ b/wit/world.wit
@@ -9,6 +9,7 @@ world http-trigger {
/// The imports needed for a guest to run on a Spin host
world platform {
include fermyon:spin/platform@2.0.0;
+ include wasi:keyvalue/imports@0.2.0-draft2;
import spin:postgres/postgres@3.0.0;
import wasi:config/store@0.2.0-draft-2024-09-27;
}
| 2,895
|
[
"2486"
] |
diff --git a/crates/factor-key-value/tests/factor_test.rs b/crates/factor-key-value/tests/factor_test.rs
index 83a67700d7..afd62a03f9 100644
--- a/crates/factor-key-value/tests/factor_test.rs
+++ b/crates/factor-key-value/tests/factor_test.rs
@@ -1,6 +1,6 @@
use anyhow::bail;
use spin_core::async_trait;
-use spin_factor_key_value::{KeyValueFactor, RuntimeConfig, Store, StoreManager};
+use spin_factor_key_value::{Cas, KeyValueFactor, RuntimeConfig, Store, StoreManager};
use spin_factors::RuntimeFactors;
use spin_factors_test::{toml, TestEnvironment};
use spin_world::v2::key_value::{Error, HostStore};
@@ -140,4 +140,36 @@ impl Store for MockStore {
async fn get_keys(&self) -> Result<Vec<String>, Error> {
todo!()
}
+
+ async fn get_many(
+ &self,
+ keys: Vec<String>,
+ ) -> anyhow::Result<Vec<(String, Option<Vec<u8>>)>, Error> {
+ let _ = keys;
+ todo!()
+ }
+
+ async fn set_many(&self, key_values: Vec<(String, Vec<u8>)>) -> anyhow::Result<(), Error> {
+ let _ = key_values;
+ todo!()
+ }
+
+ async fn delete_many(&self, keys: Vec<String>) -> anyhow::Result<(), Error> {
+ let _ = keys;
+ todo!()
+ }
+
+ async fn increment(&self, key: String, delta: i64) -> anyhow::Result<i64, Error> {
+ let (_, _) = (key, delta);
+ todo!()
+ }
+
+ async fn new_compare_and_swap(
+ &self,
+ bucket_rep: u32,
+ key: &str,
+ ) -> anyhow::Result<Arc<dyn Cas>, Error> {
+ let (_, _) = (key, bucket_rep);
+ todo!()
+ }
}
diff --git a/tests/runtime-tests/tests/wasi-key-value/spin.toml b/tests/runtime-tests/tests/wasi-key-value/spin.toml
new file mode 100644
index 0000000000..53cda06cec
--- /dev/null
+++ b/tests/runtime-tests/tests/wasi-key-value/spin.toml
@@ -0,0 +1,14 @@
+spin_manifest_version = 2
+
+[application]
+name = "wasi-key-value"
+authors = ["Fermyon Engineering <engineering@fermyon.com>"]
+version = "0.1.0"
+
+[[trigger.http]]
+route = "/"
+component = "test"
+
+[component.test]
+source = "%{source=wasi-key-value}"
+key_value_stores = ["default"]
diff --git a/tests/test-components/components/Cargo.lock b/tests/test-components/components/Cargo.lock
index bec40906b2..d4f02054f9 100644
--- a/tests/test-components/components/Cargo.lock
+++ b/tests/test-components/components/Cargo.lock
@@ -939,6 +939,14 @@ dependencies = [
"wit-bindgen 0.16.0",
]
+[[package]]
+name = "wasi-key-value"
+version = "0.1.0"
+dependencies = [
+ "helper",
+ "wit-bindgen 0.16.0",
+]
+
[[package]]
name = "wasm-encoder"
version = "0.36.2"
diff --git a/tests/test-components/components/wasi-key-value/Cargo.toml b/tests/test-components/components/wasi-key-value/Cargo.toml
new file mode 100644
index 0000000000..0bd198ce14
--- /dev/null
+++ b/tests/test-components/components/wasi-key-value/Cargo.toml
@@ -0,0 +1,11 @@
+[package]
+name = "wasi-key-value"
+version = "0.1.0"
+edition = "2021"
+
+[lib]
+crate-type = ["cdylib"]
+
+[dependencies]
+helper = { path = "../../helper" }
+wit-bindgen = "0.16.0"
diff --git a/tests/test-components/components/wasi-key-value/README.md b/tests/test-components/components/wasi-key-value/README.md
new file mode 100644
index 0000000000..2cff701082
--- /dev/null
+++ b/tests/test-components/components/wasi-key-value/README.md
@@ -0,0 +1,10 @@
+# Key Value
+
+Tests the key/value interface.
+
+## Expectations
+
+This test component expects the following to be true:
+* It is given permission to open a connection to the "default" store.
+* It does not have permission to access a store named "forbidden".
+* It is empty
diff --git a/tests/test-components/components/wasi-key-value/src/lib.rs b/tests/test-components/components/wasi-key-value/src/lib.rs
new file mode 100644
index 0000000000..dd435f6133
--- /dev/null
+++ b/tests/test-components/components/wasi-key-value/src/lib.rs
@@ -0,0 +1,66 @@
+use helper::{ensure_matches, ensure_ok};
+
+use bindings::wasi::keyvalue::store::{open, Error, KeyResponse};
+use bindings::wasi::keyvalue::batch as wasi_batch;
+use bindings::wasi::keyvalue::atomics as wasi_atomics;
+
+helper::define_component!(Component);
+
+impl Component {
+ fn main() -> Result<(), String> {
+ ensure_matches!(open("forbidden"), Err(Error::AccessDenied));
+
+ let store = ensure_ok!(open("default"));
+
+ // Ensure nothing set in `bar` key
+ ensure_ok!(store.delete("bar"));
+ ensure_matches!(store.exists("bar"), Ok(false));
+ ensure_matches!(store.get("bar"), Ok(None));
+ ensure_matches!(keys(&store.list_keys(None)), Ok(&[]));
+
+ // Set `bar` key
+ ensure_ok!(store.set("bar", b"baz"));
+ ensure_matches!(store.exists("bar"), Ok(true));
+ ensure_matches!(store.get("bar"), Ok(Some(v)) if v == b"baz");
+ ensure_matches!(keys(&store.list_keys(None)), Ok([bar]) if bar == "bar");
+ ensure_matches!(keys(&store.list_keys(Some("0"))), Err(Error::Other(_))); // "list_keys: cursor not supported"
+
+ // Override `bar` key
+ ensure_ok!(store.set("bar", b"wow"));
+ ensure_matches!(store.exists("bar"), Ok(true));
+ ensure_matches!(store.get("bar"), Ok(Some(wow)) if wow == b"wow");
+ ensure_matches!(keys(&store.list_keys(None)), Ok([bar]) if bar == "bar");
+
+ // Set another key
+ ensure_ok!(store.set("qux", b"yay"));
+ ensure_matches!(keys(&store.list_keys(None)), Ok(c) if c.len() == 2 && c.contains(&"bar".into()) && c.contains(&"qux".into()));
+
+ // Delete everything
+ ensure_ok!(store.delete("bar"));
+ ensure_ok!(store.delete("bar"));
+ ensure_ok!(store.delete("qux"));
+ ensure_matches!(store.exists("bar"), Ok(false));
+ ensure_matches!(store.get("qux"), Ok(None));
+ ensure_matches!(keys(&store.list_keys(None)), Ok(&[]));
+
+ ensure_ok!(wasi_batch::set_many(&store, &[("bar".to_string(), b"bin".to_vec()), ("baz".to_string(), b"buzz".to_vec())]));
+ ensure_ok!(wasi_batch::get_many(&store, &["bar".to_string(), "baz".to_string()]));
+ ensure_ok!(wasi_batch::delete_many(&store, &["bar".to_string(), "baz".to_string()]));
+ ensure_matches!(wasi_atomics::increment(&store, "counter", 10), Ok(v) if v == 10);
+ ensure_matches!(wasi_atomics::increment(&store, "counter", 5), Ok(v) if v == 15);
+
+ // successful compare and swap
+ ensure_ok!(store.set("bar", b"wow"));
+ let cas = ensure_ok!(wasi_atomics::Cas::new(&store, "bar"));
+ ensure_matches!(cas.current(), Ok(Some(v)) if v == b"wow".to_vec());
+ ensure_ok!(wasi_atomics::swap(cas, b"swapped"));
+ ensure_matches!(store.get("bar"), Ok(Some(v)) if v == b"swapped");
+ ensure_ok!(store.delete("bar"));
+
+ Ok(())
+ }
+}
+
+fn keys<E>(res: &Result<KeyResponse, E>) -> Result<&[String], &E> {
+ res.as_ref().map(|kr| kr.keys.as_slice())
+}
|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
|
2a9bf7c57eda9aa42152f016373d3105170b164b
|
Support wasi-config
WASI is moving wasi-config to phase 3 soon. We should consider moving from the [spin variables](https://github.com/fermyon/spin/blob/main/wit/variables.wit) interface to [WASI config](https://github.com/WebAssembly/wasi-runtime-config).
The main diff is the need to add support for `get-all`
Spin 3.0 may be a good opportunity to make this switch
|
2024-09-27T03:14:37Z
|
fermyon__spin-2869
|
fermyon/spin
|
3.2
|
diff --git a/Cargo.lock b/Cargo.lock
index dcb490ed1f..7e275d9e29 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -7065,6 +7065,7 @@ version = "2.8.0-pre0"
dependencies = [
"anyhow",
"async-trait",
+ "futures",
"spin-locked-app",
"thiserror",
"tokio",
diff --git a/crates/expressions/Cargo.toml b/crates/expressions/Cargo.toml
index cc416867ed..6c9749fb4d 100644
--- a/crates/expressions/Cargo.toml
+++ b/crates/expressions/Cargo.toml
@@ -7,6 +7,7 @@ edition = { workspace = true }
[dependencies]
anyhow = { workspace = true }
async-trait = { workspace = true }
+futures = { workspace = true }
spin-locked-app = { path = "../locked-app" }
thiserror = { workspace = true }
diff --git a/crates/expressions/src/lib.rs b/crates/expressions/src/lib.rs
index 350914b558..23be70b654 100644
--- a/crates/expressions/src/lib.rs
+++ b/crates/expressions/src/lib.rs
@@ -52,6 +52,22 @@ impl ProviderResolver {
self.resolve_template(template).await
}
+ /// Resolves all variables for the given component.
+ pub async fn resolve_all(&self, component_id: &str) -> Result<Vec<(String, String)>> {
+ use futures::FutureExt;
+
+ let Some(keys2templates) = self.internal.component_configs.get(component_id) else {
+ return Ok(vec![]);
+ };
+
+ let resolve_futs = keys2templates.iter().map(|(key, template)| {
+ self.resolve_template(template)
+ .map(|r| r.map(|value| (key.to_string(), value)))
+ });
+
+ futures::future::try_join_all(resolve_futs).await
+ }
+
/// Resolves the given template.
pub async fn resolve_template(&self, template: &Template) -> Result<String> {
let mut resolved_parts: Vec<Cow<str>> = Vec::with_capacity(template.parts().len());
diff --git a/crates/factor-variables/src/host.rs b/crates/factor-variables/src/host.rs
index bc30fe0a79..5ab38b50bc 100644
--- a/crates/factor-variables/src/host.rs
+++ b/crates/factor-variables/src/host.rs
@@ -1,5 +1,5 @@
use spin_factors::anyhow;
-use spin_world::{async_trait, v1, v2::variables};
+use spin_world::{async_trait, v1, v2::variables, wasi::config as wasi_config};
use tracing::{instrument, Level};
use crate::InstanceState;
@@ -37,6 +37,41 @@ impl v1::config::Host for InstanceState {
}
}
+#[async_trait]
+impl wasi_config::store::Host for InstanceState {
+ async fn get(&mut self, key: String) -> Result<Option<String>, wasi_config::store::Error> {
+ match <Self as variables::Host>::get(self, key).await {
+ Ok(value) => Ok(Some(value)),
+ Err(variables::Error::Undefined(_)) => Ok(None),
+ Err(variables::Error::InvalidName(_)) => Ok(None), // this is the guidance from https://github.com/WebAssembly/wasi-runtime-config/pull/19)
+ Err(variables::Error::Provider(msg)) => Err(wasi_config::store::Error::Upstream(msg)),
+ Err(variables::Error::Other(msg)) => Err(wasi_config::store::Error::Io(msg)),
+ }
+ }
+
+ async fn get_all(&mut self) -> Result<Vec<(String, String)>, wasi_config::store::Error> {
+ let all = self
+ .expression_resolver
+ .resolve_all(&self.component_id)
+ .await;
+ all.map_err(|e| {
+ match expressions_to_variables_err(e) {
+ variables::Error::Undefined(msg) => wasi_config::store::Error::Io(msg), // this shouldn't happen but just in case
+ variables::Error::InvalidName(msg) => wasi_config::store::Error::Io(msg), // this shouldn't happen but just in case
+ variables::Error::Provider(msg) => wasi_config::store::Error::Upstream(msg),
+ variables::Error::Other(msg) => wasi_config::store::Error::Io(msg),
+ }
+ })
+ }
+
+ fn convert_error(
+ &mut self,
+ err: wasi_config::store::Error,
+ ) -> anyhow::Result<wasi_config::store::Error> {
+ Ok(err)
+ }
+}
+
fn expressions_to_variables_err(err: spin_expressions::Error) -> variables::Error {
use spin_expressions::Error;
match err {
diff --git a/crates/factor-variables/src/lib.rs b/crates/factor-variables/src/lib.rs
index ac5c7e626b..0983696094 100644
--- a/crates/factor-variables/src/lib.rs
+++ b/crates/factor-variables/src/lib.rs
@@ -31,6 +31,7 @@ impl Factor for VariablesFactor {
fn init<T: Send + 'static>(&mut self, mut ctx: InitContext<T, Self>) -> anyhow::Result<()> {
ctx.link_bindings(spin_world::v1::config::add_to_linker)?;
ctx.link_bindings(spin_world::v2::variables::add_to_linker)?;
+ ctx.link_bindings(spin_world::wasi::config::store::add_to_linker)?;
Ok(())
}
diff --git a/crates/world/src/lib.rs b/crates/world/src/lib.rs
index 0ecb57ee1d..676ec3e54a 100644
--- a/crates/world/src/lib.rs
+++ b/crates/world/src/lib.rs
@@ -28,6 +28,7 @@ wasmtime::component::bindgen!({
"fermyon:spin/sqlite@2.0.0/error" => v2::sqlite::Error,
"fermyon:spin/sqlite/error" => v1::sqlite::Error,
"fermyon:spin/variables@2.0.0/error" => v2::variables::Error,
+ "wasi:config/store@0.2.0-draft-2024-09-27/error" => wasi::config::store::Error,
},
trappable_imports: true,
});
diff --git a/wit/deps/spin@3.0.0/world.wit b/wit/deps/spin@3.0.0/world.wit
index e920055a9a..b38f1f4630 100644
--- a/wit/deps/spin@3.0.0/world.wit
+++ b/wit/deps/spin@3.0.0/world.wit
@@ -9,4 +9,5 @@ world http-trigger {
/// The imports needed for a guest to run on a Spin host
world platform {
include fermyon:spin/platform@2.0.0;
+ import wasi:config/store@0.2.0-draft-2024-09-27;
}
diff --git a/wit/deps/wasi-runtime-config-2024-09-27/store.wit b/wit/deps/wasi-runtime-config-2024-09-27/store.wit
new file mode 100644
index 0000000000..794379a754
--- /dev/null
+++ b/wit/deps/wasi-runtime-config-2024-09-27/store.wit
@@ -0,0 +1,30 @@
+interface store {
+ /// An error type that encapsulates the different errors that can occur fetching configuration values.
+ variant error {
+ /// This indicates an error from an "upstream" config source.
+ /// As this could be almost _anything_ (such as Vault, Kubernetes ConfigMaps, KeyValue buckets, etc),
+ /// the error message is a string.
+ upstream(string),
+ /// This indicates an error from an I/O operation.
+ /// As this could be almost _anything_ (such as a file read, network connection, etc),
+ /// the error message is a string.
+ /// Depending on how this ends up being consumed,
+ /// we may consider moving this to use the `wasi:io/error` type instead.
+ /// For simplicity right now in supporting multiple implementations, it is being left as a string.
+ io(string),
+ }
+
+ /// Gets a configuration value of type `string` associated with the `key`.
+ ///
+ /// The value is returned as an `option<string>`. If the key is not found,
+ /// `Ok(none)` is returned. If an error occurs, an `Err(error)` is returned.
+ get: func(
+ /// A string key to fetch
+ key: string
+ ) -> result<option<string>, error>;
+
+ /// Gets a list of configuration key-value pairs of type `string`.
+ ///
+ /// If an error occurs, an `Err(error)` is returned.
+ get-all: func() -> result<list<tuple<string, string>>, error>;
+}
diff --git a/wit/deps/wasi-runtime-config-2024-09-27/world.wit b/wit/deps/wasi-runtime-config-2024-09-27/world.wit
new file mode 100644
index 0000000000..e879af51b1
--- /dev/null
+++ b/wit/deps/wasi-runtime-config-2024-09-27/world.wit
@@ -0,0 +1,6 @@
+package wasi:config@0.2.0-draft-2024-09-27;
+
+world imports {
+ /// The interface for wasi:config/store
+ import store;
+}
\ No newline at end of file
| 2,869
|
[
"2868"
] |
diff --git a/tests/runtime-tests/tests/variables/spin.toml b/tests/runtime-tests/tests/variables/spin.toml
new file mode 100644
index 0000000000..b63cd61ddd
--- /dev/null
+++ b/tests/runtime-tests/tests/variables/spin.toml
@@ -0,0 +1,17 @@
+spin_manifest_version = "1"
+authors = [""]
+description = ""
+name = "variables"
+trigger = { type = "http" }
+version = "0.1.0"
+
+[variables]
+variable = { default = "value" }
+
+[[component]]
+id = "variables"
+source = "%{source=variables}"
+[component.trigger]
+route = "/..."
+[component.config]
+variable = "{{ variable }}"
diff --git a/tests/runtime-tests/tests/wasi-config/spin.toml b/tests/runtime-tests/tests/wasi-config/spin.toml
new file mode 100644
index 0000000000..2eee4f45e9
--- /dev/null
+++ b/tests/runtime-tests/tests/wasi-config/spin.toml
@@ -0,0 +1,17 @@
+spin_manifest_version = "1"
+authors = [""]
+description = ""
+name = "wasi-config"
+trigger = { type = "http" }
+version = "0.1.0"
+
+[variables]
+variable = { default = "value" }
+
+[[component]]
+id = "wasi-config"
+source = "%{source=wasi-config}"
+[component.trigger]
+route = "/..."
+[component.config]
+variable = "{{ variable }}"
diff --git a/tests/test-components/components/Cargo.lock b/tests/test-components/components/Cargo.lock
index 3c6212dd85..bec40906b2 100644
--- a/tests/test-components/components/Cargo.lock
+++ b/tests/test-components/components/Cargo.lock
@@ -906,6 +906,14 @@ version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
+[[package]]
+name = "wasi-config"
+version = "0.1.0"
+dependencies = [
+ "helper",
+ "wit-bindgen 0.16.0",
+]
+
[[package]]
name = "wasi-http-rc-2023-11-10"
version = "0.1.0"
diff --git a/tests/test-components/components/wasi-config/Cargo.toml b/tests/test-components/components/wasi-config/Cargo.toml
new file mode 100644
index 0000000000..558e708682
--- /dev/null
+++ b/tests/test-components/components/wasi-config/Cargo.toml
@@ -0,0 +1,11 @@
+[package]
+name = "wasi-config"
+version = "0.1.0"
+edition = "2021"
+
+[lib]
+crate-type = ["cdylib"]
+
+[dependencies]
+helper = { path = "../../helper" }
+wit-bindgen = "0.16.0"
diff --git a/tests/test-components/components/wasi-config/README.md b/tests/test-components/components/wasi-config/README.md
new file mode 100644
index 0000000000..7492706f45
--- /dev/null
+++ b/tests/test-components/components/wasi-config/README.md
@@ -0,0 +1,8 @@
+# Variables
+
+Tests the wasi:config interface.
+
+## Expectations
+
+This test component expects the following to be true:
+* Only the variable named "variable" is defined with value "value"
diff --git a/tests/test-components/components/wasi-config/src/lib.rs b/tests/test-components/components/wasi-config/src/lib.rs
new file mode 100644
index 0000000000..6e9b5706a7
--- /dev/null
+++ b/tests/test-components/components/wasi-config/src/lib.rs
@@ -0,0 +1,23 @@
+use helper::ensure_matches;
+
+use bindings::wasi::config::store::{get, get_all};
+
+helper::define_component!(Component);
+
+impl Component {
+ fn main() -> Result<(), String> {
+ ensure_matches!(get("variable"), Ok(Some(val)) if val == "value");
+ ensure_matches!(get("non_existent"), Ok(None));
+
+ let expected_all = vec![
+ ("variable".to_owned(), "value".to_owned()),
+ ];
+ ensure_matches!(get_all(), Ok(val) if val == expected_all);
+
+ ensure_matches!(get("invalid-name"), Ok(None));
+ ensure_matches!(get("invalid!name"), Ok(None));
+ ensure_matches!(get("4invalidname"), Ok(None));
+
+ Ok(())
+ }
+}
|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
|
6df7262df11bce1046fb838ed2e7b1126c2966c0
|
Enable spinning up only a subset of an application's components
## Summary
Say I have an app with 4 components but only want to run 2, I should be able to do the equivalent of `spin up --component "foo" --component "bar"`
## Background
Spin unifies serverless application development. Developers can define distinct functions as components and group them all together into one fully-featured Spin application. Each of these components has unique requirements, such as access to a database or LLM. Not all of these requirements are always available to the developer or in production. For these reasons, developers should be able to run a subset of components of a Spin application.
## Proposed DevX
```sh
# Run all components
spin up
# Run the `hello-rust` and `hello-go` components
spin up --component "hello-rust" --component "hello-go"
```
|
I am working on a SIP for this
|
2024-09-12T17:06:00Z
|
fermyon__spin-2826
|
fermyon/spin
|
3.2
|
diff --git a/Cargo.lock b/Cargo.lock
index 62cf5ab301..9a64364e80 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -7006,6 +7006,7 @@ dependencies = [
"futures",
"glob",
"hex",
+ "http 1.1.0",
"http-body-util",
"hyper 1.4.1",
"hyper-util",
@@ -7032,6 +7033,7 @@ dependencies = [
"spin-common",
"spin-doctor",
"spin-expressions",
+ "spin-factor-outbound-networking",
"spin-http",
"spin-loader",
"spin-locked-app",
diff --git a/Cargo.toml b/Cargo.toml
index 78a8ae3d51..3410690242 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -28,6 +28,7 @@ dialoguer = "0.10"
dirs = { workspace = true }
futures = { workspace = true }
glob = { workspace = true }
+http = { workspace = true }
indicatif = "0.17"
is-terminal = "0.4"
itertools = { workspace = true }
@@ -59,6 +60,7 @@ spin-build = { path = "crates/build" }
spin-common = { path = "crates/common" }
spin-doctor = { path = "crates/doctor" }
spin-expressions = { path = "crates/expressions" }
+spin-factor-outbound-networking = { path = "crates/factor-outbound-networking" }
spin-http = { path = "crates/http" }
spin-loader = { path = "crates/loader" }
spin-locked-app = { path = "crates/locked-app" }
diff --git a/crates/factor-outbound-networking/src/lib.rs b/crates/factor-outbound-networking/src/lib.rs
index 25d8085c13..7c83677e27 100644
--- a/crates/factor-outbound-networking/src/lib.rs
+++ b/crates/factor-outbound-networking/src/lib.rs
@@ -1,8 +1,6 @@
mod config;
pub mod runtime_config;
-use std::{collections::HashMap, sync::Arc};
-
use futures_util::{
future::{BoxFuture, Shared},
FutureExt,
@@ -14,6 +12,7 @@ use spin_factors::{
anyhow::{self, Context},
ConfigureAppContext, Error, Factor, FactorInstanceBuilder, PrepareContext, RuntimeFactors,
};
+use std::{collections::HashMap, sync::Arc};
pub use config::{
allowed_outbound_hosts, is_service_chaining_host, parse_service_chaining_target,
diff --git a/src/commands/up.rs b/src/commands/up.rs
index 87f5d61cf3..7fb5f4c56b 100644
--- a/src/commands/up.rs
+++ b/src/commands/up.rs
@@ -1,18 +1,19 @@
mod app_source;
use std::{
- collections::HashMap,
+ collections::{HashMap, HashSet},
ffi::OsString,
fmt::Debug,
path::{Path, PathBuf},
process::Stdio,
};
-use anyhow::{anyhow, bail, Context, Result};
+use anyhow::{anyhow, bail, ensure, Context, Result};
use clap::{CommandFactory, Parser};
use reqwest::Url;
use spin_app::locked::LockedApp;
use spin_common::ui::quoted_path;
+use spin_factor_outbound_networking::{allowed_outbound_hosts, parse_service_chaining_target};
use spin_loader::FilesMountStrategy;
use spin_oci::OciLoader;
use spin_trigger::cli::{LaunchMetadata, SPIN_LOCAL_APP_DIR, SPIN_LOCKED_URL, SPIN_WORKING_DIR};
@@ -113,6 +114,10 @@ pub struct UpCommand {
#[clap(long, takes_value = false, env = ALWAYS_BUILD_ENV)]
pub build: bool,
+ /// [Experimental] Component ID to run. This can be specified multiple times. The default is all components.
+ #[clap(hide = true, short = 'c', long = "component-id")]
+ pub components: Vec<String>,
+
/// All other args, to be passed through to the trigger
#[clap(hide = true)]
pub trigger_args: Vec<OsString>,
@@ -164,13 +169,12 @@ impl UpCommand {
.context("Could not canonicalize working directory")?;
let resolved_app_source = self.resolve_app_source(&app_source, &working_dir).await?;
-
- let trigger_cmds = trigger_command_for_resolved_app_source(&resolved_app_source)
- .with_context(|| format!("Couldn't find trigger executor for {app_source}"))?;
-
- let is_multi = trigger_cmds.len() > 1;
-
if self.help {
+ let trigger_cmds =
+ trigger_commands_for_trigger_types(resolved_app_source.trigger_types())
+ .with_context(|| format!("Couldn't find trigger executor for {app_source}"))?;
+
+ let is_multi = trigger_cmds.len() > 1;
if is_multi {
// For now, only common flags are allowed on multi-trigger apps.
let mut child = self
@@ -189,10 +193,25 @@ impl UpCommand {
if self.build {
app_source.build().await?;
}
-
let mut locked_app = self
.load_resolved_app_source(resolved_app_source, &working_dir)
- .await?;
+ .await
+ .context("Failed to load application")?;
+ if !self.components.is_empty() {
+ retain_components(&mut locked_app, &self.components)?;
+ }
+
+ let trigger_types: HashSet<&str> = locked_app
+ .triggers
+ .iter()
+ .map(|t| t.trigger_type.as_ref())
+ .collect();
+
+ ensure!(!trigger_types.is_empty(), "No triggers in app");
+
+ let trigger_cmds = trigger_commands_for_trigger_types(trigger_types.into_iter().collect())
+ .with_context(|| format!("Couldn't find trigger executor for {app_source}"))?;
+ let is_multi = trigger_cmds.len() > 1;
self.update_locked_app(&mut locked_app);
let locked_url = self.write_locked_app(&locked_app, &working_dir).await?;
@@ -630,11 +649,8 @@ fn trigger_command(trigger_type: &str) -> Vec<String> {
vec!["trigger".to_owned(), trigger_type.to_owned()]
}
-fn trigger_command_for_resolved_app_source(
- resolved: &ResolvedAppSource,
-) -> Result<Vec<Vec<String>>> {
- let trigger_type = resolved.trigger_types()?;
- trigger_type
+fn trigger_commands_for_trigger_types(trigger_types: Vec<&str>) -> Result<Vec<Vec<String>>> {
+ trigger_types
.iter()
.map(|&t| match t {
"http" | "redis" => Ok(trigger_command(t)),
@@ -646,6 +662,86 @@ fn trigger_command_for_resolved_app_source(
.collect()
}
+/// Scrubs the locked app to only contain the given list of components
+/// Introspects the LockedApp to find and selectively retain the triggers that correspond to those components
+fn retain_components(locked_app: &mut LockedApp, retained_components: &[String]) -> Result<()> {
+ // Create a temporary app to access parsed component and trigger information
+ let tmp_app = spin_app::App::new("tmp", locked_app.clone());
+ validate_retained_components_exist(&tmp_app, retained_components)?;
+ validate_retained_components_service_chaining(&tmp_app, retained_components)?;
+ let (component_ids, trigger_ids): (HashSet<String>, HashSet<String>) = tmp_app
+ .triggers()
+ .filter_map(|t| match t.component() {
+ Ok(comp) if retained_components.contains(&comp.id().to_string()) => {
+ Some((comp.id().to_owned(), t.id().to_owned()))
+ }
+ _ => None,
+ })
+ .collect();
+ locked_app
+ .components
+ .retain(|c| component_ids.contains(&c.id));
+ locked_app.triggers.retain(|t| trigger_ids.contains(&t.id));
+ Ok(())
+}
+
+/// Validates that all service chaining of an app will be satisfied by the
+/// retained components.
+///
+/// This does a best effort look up of components that are
+/// allowed to be accessed through service chaining and will error early if a
+/// component is configured to to chain to another component that is not
+/// retained. All wildcard service chaining is disallowed and all templated URLs
+/// are ignored.
+fn validate_retained_components_service_chaining(
+ app: &spin_app::App,
+ retained_components: &[String],
+) -> Result<()> {
+ app
+ .triggers().try_for_each(|t| {
+ let Ok(component) = t.component() else { return Ok(()) };
+ if retained_components.contains(&component.id().to_string()) {
+ let allowed_hosts = allowed_outbound_hosts(&component).context("failed to get allowed hosts")?;
+ for host in allowed_hosts {
+ // Templated URLs are not yet resolved at this point, so ignore unresolvable URIs
+ if let Ok(uri) = host.parse::<http::Uri>() {
+ if let Some(chaining_target) = parse_service_chaining_target(&uri) {
+ if !retained_components.contains(&chaining_target) {
+ if chaining_target == "*" {
+ bail!("Component selected with '--component {}' cannot use wildcard service chaining: allowed_outbound_hosts = [\"http://*.spin.internal\"]", component.id());
+ }
+ bail!(
+ "Component selected with '--component {}' cannot use service chaining to unselected component: allowed_outbound_hosts = [\"http://{}.spin.internal\"]",
+ component.id(), chaining_target
+ );
+ }
+ }
+ }
+ }
+ }
+ anyhow::Ok(())
+ })?;
+
+ Ok(())
+}
+
+/// Validates that all components specified to be retained actually exist in the app
+fn validate_retained_components_exist(
+ app: &spin_app::App,
+ retained_components: &[String],
+) -> Result<()> {
+ let app_components = app
+ .components()
+ .map(|c| c.id().to_string())
+ .collect::<HashSet<_>>();
+ for c in retained_components {
+ if !app_components.contains(c) {
+ bail!("Specified component \"{c}\" not found in application");
+ }
+ }
+ Ok(())
+}
+
#[cfg(test)]
mod test {
use crate::commands::up::app_source::AppSource;
@@ -658,6 +754,156 @@ mod test {
format!("{repo_base}/{path}")
}
+ #[tokio::test]
+ async fn test_retain_components_filtering_for_only_component_works() {
+ let manifest = toml::toml! {
+ spin_manifest_version = 2
+
+ [application]
+ name = "test-app"
+
+ [[trigger.test-trigger]]
+ component = "empty"
+
+ [component.empty]
+ source = "does-not-exist.wasm"
+ };
+ let mut locked_app = build_locked_app(&manifest).await.unwrap();
+ retain_components(&mut locked_app, &["empty".to_string()]).unwrap();
+ let components = locked_app
+ .components
+ .iter()
+ .map(|c| c.id.to_string())
+ .collect::<HashSet<_>>();
+ assert!(components.contains("empty"));
+ assert!(components.len() == 1);
+ }
+
+ #[tokio::test]
+ async fn test_retain_components_filtering_for_non_existent_component_fails() {
+ let manifest = toml::toml! {
+ spin_manifest_version = 2
+
+ [application]
+ name = "test-app"
+
+ [[trigger.test-trigger]]
+ component = "empty"
+
+ [component.empty]
+ source = "does-not-exist.wasm"
+ };
+ let mut locked_app = build_locked_app(&manifest).await.unwrap();
+ let Err(e) = retain_components(&mut locked_app, &["dne".to_string()]) else {
+ panic!("Expected component not found error");
+ };
+ assert_eq!(
+ e.to_string(),
+ "Specified component \"dne\" not found in application"
+ );
+ assert!(retain_components(&mut locked_app, &["dne".to_string()]).is_err());
+ }
+
+ #[tokio::test]
+ async fn test_retain_components_app_with_service_chaining_fails() {
+ let manifest = toml::toml! {
+ spin_manifest_version = 2
+
+ [application]
+ name = "test-app"
+
+ [[trigger.test-trigger]]
+ component = "empty"
+
+ [component.empty]
+ source = "does-not-exist.wasm"
+ allowed_outbound_hosts = ["http://another.spin.internal"]
+
+ [[trigger.another-trigger]]
+ component = "another"
+
+ [component.another]
+ source = "does-not-exist.wasm"
+
+ [[trigger.third-trigger]]
+ component = "third"
+
+ [component.third]
+ source = "does-not-exist.wasm"
+ allowed_outbound_hosts = ["http://*.spin.internal"]
+ };
+ let mut locked_app = build_locked_app(&manifest)
+ .await
+ .expect("could not build locked app");
+ let Err(e) = retain_components(&mut locked_app, &["empty".to_string()]) else {
+ panic!("Expected service chaining to non-retained component error");
+ };
+ assert_eq!(
+ e.to_string(),
+ "Component selected with '--component empty' cannot use service chaining to unselected component: allowed_outbound_hosts = [\"http://another.spin.internal\"]"
+ );
+ let Err(e) = retain_components(
+ &mut locked_app,
+ &["third".to_string(), "another".to_string()],
+ ) else {
+ panic!("Expected wildcard service chaining error");
+ };
+ assert_eq!(
+ e.to_string(),
+ "Component selected with '--component third' cannot use wildcard service chaining: allowed_outbound_hosts = [\"http://*.spin.internal\"]"
+ );
+ assert!(retain_components(&mut locked_app, &["another".to_string()]).is_ok());
+ }
+
+ #[tokio::test]
+ async fn test_retain_components_app_with_templated_host_passes() {
+ let manifest = toml::toml! {
+ spin_manifest_version = 2
+
+ [application]
+ name = "test-app"
+
+ [variables]
+ host = { default = "test" }
+
+ [[trigger.test-trigger]]
+ component = "empty"
+
+ [component.empty]
+ source = "does-not-exist.wasm"
+
+ [[trigger.another-trigger]]
+ component = "another"
+
+ [component.another]
+ source = "does-not-exist.wasm"
+
+ [[trigger.third-trigger]]
+ component = "third"
+
+ [component.third]
+ source = "does-not-exist.wasm"
+ allowed_outbound_hosts = ["http://{{ host }}.spin.internal"]
+ };
+ let mut locked_app = build_locked_app(&manifest)
+ .await
+ .expect("could not build locked app");
+ assert!(
+ retain_components(&mut locked_app, &["empty".to_string(), "third".to_string()]).is_ok()
+ );
+ }
+
+ // Duplicate from crates/factors-test/src/lib.rs
+ pub async fn build_locked_app(
+ manifest: &toml::map::Map<String, toml::Value>,
+ ) -> anyhow::Result<LockedApp> {
+ let toml_str = toml::to_string(manifest).context("failed serializing manifest")?;
+ let dir = tempfile::tempdir().context("failed creating tempdir")?;
+ let path = dir.path().join("spin.toml");
+ std::fs::write(&path, toml_str).context("failed writing manifest")?;
+ spin_loader::from_file(&path, FilesMountStrategy::Direct, None).await
+ }
+
#[test]
fn can_infer_files() {
let file = repo_path("examples/http-rust/spin.toml");
diff --git a/src/commands/up/app_source.rs b/src/commands/up/app_source.rs
index 4c7ab656f6..7969106992 100644
--- a/src/commands/up/app_source.rs
+++ b/src/commands/up/app_source.rs
@@ -3,7 +3,6 @@ use std::{
path::{Path, PathBuf},
};
-use anyhow::ensure;
use spin_common::ui::quoted_path;
use spin_locked_app::locked::LockedApp;
use spin_manifest::schema::v2::AppManifest;
@@ -99,7 +98,7 @@ pub enum ResolvedAppSource {
}
impl ResolvedAppSource {
- pub fn trigger_types(&self) -> anyhow::Result<Vec<&str>> {
+ pub fn trigger_types(&self) -> Vec<&str> {
let types = match self {
ResolvedAppSource::File { manifest, .. } => manifest
.triggers
@@ -114,7 +113,6 @@ impl ResolvedAppSource {
ResolvedAppSource::BareWasm { .. } => ["http"].into_iter().collect(),
};
- ensure!(!types.is_empty(), "no triggers in app");
- Ok(types.into_iter().collect())
+ types.into_iter().collect()
}
}
| 2,826
|
[
"2820"
] |
diff --git a/tests/integration.rs b/tests/integration.rs
index 6cbf43cfc6..4b14a1e8a9 100644
--- a/tests/integration.rs
+++ b/tests/integration.rs
@@ -348,12 +348,7 @@ mod integration_tests {
},
)?;
- let expected = r#"Error: Couldn't find trigger executor for local app "spin.toml"
-
-Caused by:
- no triggers in app
-"#;
-
+ let expected = "Error: No triggers in app\n";
assert_eq!(env.runtime_mut().stderr(), expected);
Ok(())
|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
09de9c38f6c9ca280020cd9afd5eb655651b8766
|
Swift and Grain Templates Tests Not Working
After the Factors work the Swift and Grain templates have stopped working:
## Swift
When the `http_swift_template_smoke_test` test is run, the following error appears:
```
Error: preparing wasm "/tmp/t68d4-a/main.wasm"
Caused by:
This Wasm module appears to have been compiled with wasi-sdk version <19 which contains a critical memory safety bug. For more information, see: https://github.com/fermyon/spin/issues/2552
```
The Swift toolchain uses a fairly old version of wasi-sdk. It is possible that a newer version of the Swift toolchain would work, but as of yet we've not been able to get things working.
## Grain
When the `http_grain_template_smoke_test` test is run, the following error appears:
```
Error: Expected status 200 for / but got 500
Body: 'Exactly one of 'location' or 'content-type' must be specified'
Stderr: '2024-08-27T15:11:00.204342Z ERROR spin_http::wagi: HTTP 500 error error=Exactly one of 'location' or 'content-type' must be specified
```
Most likely the wagi module is not giving any output and thus there are no headers to parse leading to the error. Why this would be happy is not clear at the moment.
For now, we will be turning off both tests while we continue to investigate.
|
The Grain issue appears to be a missing newline between the header and the body, which reproduces under `wasmtime run`.
A newer versions of Grain (0.6.6) fixes the newline issue but has an exciting new problem: it emits duplicate imports which are permitted in core wasm modules but forbidden in component model modules. Deduping imports as part of componentization may be a plausible fix here.
Edit: Deeper problems: https://github.com/grain-lang/grain/issues/2153
Duplicate imports tracked separately: https://github.com/fermyon/spin/issues/2778
I'm not sure how plausible it is to get the Swift template working again; SwiftWasm 5.10 appears to be producing [uncomponentizable modules](https://github.com/fermyon/spin/issues/2552).
Given that the current Swift template is WAGI-only and - since it doesn't use wit-bindgen - supports only very limited host functionality, I would vote for dropping the template until we have better tooling.
|
2024-08-29T21:22:47Z
|
fermyon__spin-2789
|
fermyon/spin
|
3.2
|
diff --git a/crates/templates/src/manager.rs b/crates/templates/src/manager.rs
index 4ddc7271cd..2ef5abfebb 100644
--- a/crates/templates/src/manager.rs
+++ b/crates/templates/src/manager.rs
@@ -566,7 +566,7 @@ mod tests {
}
}
- const TPLS_IN_THIS: usize = 12;
+ const TPLS_IN_THIS: usize = 11;
#[tokio::test]
async fn can_install_into_new_directory() {
diff --git a/templates/http-grain/content/main.gr b/templates/http-grain/content/main.gr
index 6f0dbc4111..b1eb30ccc2 100644
--- a/templates/http-grain/content/main.gr
+++ b/templates/http-grain/content/main.gr
@@ -1,3 +1,7 @@
-print("content-type: text/plain")
-print("")
-print("Hello, World")
+module Main
+
+provide let _start = () => {
+ print("content-type: text/plain")
+ print("")
+ print("Hello, World")
+}
diff --git a/templates/http-grain/content/spin.toml b/templates/http-grain/content/spin.toml
index 90ce23c6de..44323d5c5f 100644
--- a/templates/http-grain/content/spin.toml
+++ b/templates/http-grain/content/spin.toml
@@ -15,5 +15,5 @@ executor = { type = "wagi" }
source = "main.wasm"
allowed_outbound_hosts = []
[component.{{project-name | kebab_case}}.build]
-command = "grain compile --release -o main.wasm main.gr"
+command = "grain compile --release --use-start-section -o main.wasm main.gr"
watch = ["**/*.gr"]
diff --git a/templates/http-swift/content/.gitignore b/templates/http-swift/content/.gitignore
deleted file mode 100644
index b565010470..0000000000
--- a/templates/http-swift/content/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-main.wasm
-.spin/
diff --git a/templates/http-swift/content/main.swift b/templates/http-swift/content/main.swift
deleted file mode 100644
index b3c8f1cedd..0000000000
--- a/templates/http-swift/content/main.swift
+++ /dev/null
@@ -1,16 +0,0 @@
-import WASILibc
-
-// Until all of ProcessInfo makes its way into SwiftWasm
-func getEnvVar(key: String) -> Optional<String> {
- guard let rawValue = getenv(key) else {return Optional.none}
- return String(validatingUTF8: rawValue)
-}
-
-let server = getEnvVar(key: "SERVER_SOFTWARE") ?? "Unknown Server"
-let message = """
-content-type: text/plain
-
-Hello from \(server)!
-"""
-
-print(message)
diff --git a/templates/http-swift/content/spin.toml b/templates/http-swift/content/spin.toml
deleted file mode 100644
index 4ad08af295..0000000000
--- a/templates/http-swift/content/spin.toml
+++ /dev/null
@@ -1,19 +0,0 @@
-spin_manifest_version = 2
-
-[application]
-name = "{{project-name | kebab_case}}"
-version = "0.1.0"
-authors = ["{{authors}}"]
-description = "{{project-description}}"
-
-[[trigger.http]]
-route = "{{http-path}}"
-component = "{{project-name | kebab_case}}"
-executor = { type = "wagi" }
-
-[component.{{project-name | kebab_case}}]
-source = "main.wasm"
-allowed_outbound_hosts = []
-[component.{{project-name | kebab_case}}.build]
-command = "swiftc -target wasm32-unknown-wasi main.swift -o main.wasm"
-watch = ["**/*.swift"]
diff --git a/templates/http-swift/metadata/spin-template.toml b/templates/http-swift/metadata/spin-template.toml
deleted file mode 100644
index ce0e3df49a..0000000000
--- a/templates/http-swift/metadata/spin-template.toml
+++ /dev/null
@@ -1,8 +0,0 @@
-manifest_version = "1"
-id = "http-swift"
-description = "HTTP request handler using SwiftWasm"
-tags = ["http", "swift"]
-
-[parameters]
-project-description = { type = "string", prompt = "Description", default = "" }
-http-path = { type = "string", prompt = "HTTP path", default = "/...", pattern = "^/\\S*$" }
| 2,789
|
[
"2774"
] |
diff --git a/tests/integration.rs b/tests/integration.rs
index c09e241d3f..6cbf43cfc6 100644
--- a/tests/integration.rs
+++ b/tests/integration.rs
@@ -628,7 +628,6 @@ Caused by:
#[test]
#[cfg(target_arch = "x86_64")]
#[cfg(feature = "extern-dependencies-tests")]
- #[ignore = "https://github.com/fermyon/spin/issues/2774"]
fn http_grain_template_smoke_test() -> anyhow::Result<()> {
http_smoke_test_template(
"http-grain",
@@ -655,21 +654,6 @@ Caused by:
)
}
- #[test]
- #[cfg(feature = "extern-dependencies-tests")]
- #[ignore = "https://github.com/fermyon/spin/issues/2774"]
- fn http_swift_template_smoke_test() -> anyhow::Result<()> {
- http_smoke_test_template(
- "http-swift",
- None,
- None,
- &[],
- |_| Ok(()),
- HashMap::default(),
- "Hello from WAGI/1!\n",
- )
- }
-
#[test]
#[cfg(feature = "extern-dependencies-tests")]
fn http_php_template_smoke_test() -> anyhow::Result<()> {
|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
c02b44135364b6aab5f427a2697cfa347042c0af
|
Format toml in CI
I'd like us to add a toml formatter to CI. It'd be nice to not have to deal with formatting or alphabetical sorting in our `Cargo.toml`'s.
|
This is as standard as it gets right now afaict: https://github.com/tamasfe/taplo
cc @rylev
|
2024-08-26T21:17:10Z
|
fermyon__spin-2767
|
fermyon/spin
|
3.2
|
diff --git a/.cargo/config.toml b/.cargo/config.toml
index c390ab08e0..00b96c3e8b 100644
--- a/.cargo/config.toml
+++ b/.cargo/config.toml
@@ -1,11 +1,11 @@
[net]
- git-fetch-with-cli = true
+git-fetch-with-cli = true
[target.aarch64-unknown-linux-gnu]
- rustflags = ["-C", "target-feature=+fp16"]
+rustflags = ["-C", "target-feature=+fp16"]
[target.aarch64-unknown-linux-musl]
- rustflags = ["-C", "target-feature=+fp16", "-C", "target-feature=+crt-static", "-C", "link-self-contained=yes"]
+rustflags = ["-C", "target-feature=+fp16", "-C", "target-feature=+crt-static", "-C", "link-self-contained=yes"]
[target.x86_64-unknown-linux-musl]
- rustflags = ["-C", "target-feature=+crt-static", "-C", "link-self-contained=yes"]
+rustflags = ["-C", "target-feature=+crt-static", "-C", "link-self-contained=yes"]
diff --git a/Cargo.toml b/Cargo.toml
index c32cfc09c2..171d57d3de 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -21,8 +21,8 @@ bytes = "1.1"
chrono = "0.4"
clap = { version = "3.2.24", features = ["derive", "env"] }
clearscreen = "2.0.1"
-command-group = "2.1"
comfy-table = "5.0"
+command-group = "2.1"
ctrlc = { version = "3.2", features = ["termination"] }
dialoguer = "0.10"
dirs = "4.0"
@@ -35,8 +35,6 @@ itertools = "0.11.0"
lazy_static = "1.4.0"
levenshtein = "1.0.5"
nix = { version = "0.24", features = ["signal"] }
-spin-key-value = { path = "crates/key-value" }
-spin-key-value-sqlite = { path = "crates/key-value-sqlite" }
path-absolutize = "3.0.11"
rand = "0.8"
regex = "1.5.5"
@@ -46,13 +44,14 @@ semver = "1.0"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0.82"
sha2 = "0.10.2"
-terminal = { path = "crates/terminal" }
spin-app = { path = "crates/app" }
spin-build = { path = "crates/build" }
spin-common = { path = "crates/common" }
spin-doctor = { path = "crates/doctor" }
spin-expressions = { path = "crates/expressions" }
spin-http = { path = "crates/http" }
+spin-key-value = { path = "crates/key-value" }
+spin-key-value-sqlite = { path = "crates/key-value-sqlite" }
spin-loader = { path = "crates/loader" }
spin-locked-app = { path = "crates/locked-app" }
spin-manifest = { path = "crates/manifest" }
@@ -65,7 +64,9 @@ spin-templates = { path = "crates/templates" }
spin-trigger = { path = "crates/trigger" }
spin-trigger-http = { path = "crates/trigger-http" }
spin-trigger-redis = { path = "crates/trigger-redis" }
+terminal = { path = "crates/terminal" }
+subprocess = "0.2.9"
tempfile = "3.8.0"
tokio = { version = "1.23", features = ["full"] }
toml = "0.6"
@@ -75,7 +76,6 @@ uuid = { version = "^1.0", features = ["v4"] }
wasmtime = { workspace = true }
watchexec = { git = "https://github.com/watchexec/watchexec.git", rev = "8e91d26ef6400c1e60b32a8314cbb144fa33f288" }
watchexec-filterer-globset = { git = "https://github.com/watchexec/watchexec.git", rev = "8e91d26ef6400c1e60b32a8314cbb144fa33f288" }
-subprocess = "0.2.9"
[target.'cfg(target_os = "linux")'.dependencies]
# This needs to be an explicit dependency to enable
@@ -84,20 +84,20 @@ openssl = { version = "0.10" }
[dev-dependencies]
anyhow = { workspace = true, features = ["backtrace"] }
+conformance = { path = "tests/conformance-tests" }
+conformance-tests = { workspace = true }
hex = "0.4.3"
-hyper = { workspace = true }
-sha2 = "0.10.1"
-which = "4.2.5"
http-body-util = { workspace = true }
-testing-framework = { path = "tests/testing-framework" }
+hyper = { workspace = true }
hyper-util = { version = "0.1.2", features = ["tokio"] }
redis = "0.24"
runtime-tests = { path = "tests/runtime-tests" }
-test-components = { path = "tests/test-components" }
+sha2 = "0.10.1"
test-codegen-macro = { path = "crates/test-codegen-macro" }
+test-components = { path = "tests/test-components" }
test-environment = { workspace = true }
-conformance-tests = { workspace = true }
-conformance = { path = "tests/conformance-tests" }
+testing-framework = { path = "tests/testing-framework" }
+which = "4.2.5"
[build-dependencies]
cargo-target-dep = { git = "https://github.com/fermyon/cargo-target-dep", rev = "482f269eceb7b1a7e8fc618bf8c082dd24979cf1" }
@@ -127,12 +127,12 @@ members = [
[workspace.dependencies]
anyhow = "1.0.75"
+conformance-tests = { git = "https://github.com/fermyon/conformance-tests", rev = "387b7f375df59e6254a7c29cf4a53507a9f46d32" }
http-body-util = "0.1.0"
hyper = { version = "1.0.0", features = ["full"] }
reqwest = { version = "0.12", features = ["stream", "blocking"] }
-tracing = { version = "0.1", features = ["log"] }
-conformance-tests = { git = "https://github.com/fermyon/conformance-tests", rev = "387b7f375df59e6254a7c29cf4a53507a9f46d32" }
test-environment = { git = "https://github.com/fermyon/conformance-tests", rev = "387b7f375df59e6254a7c29cf4a53507a9f46d32" }
+tracing = { version = "0.1", features = ["log"] }
wasi-common-preview1 = { version = "22.0.0", package = "wasi-common", features = [
"tokio",
diff --git a/Cross.toml b/Cross.toml
index b8b2392ec5..84ffc5fbd6 100644
--- a/Cross.toml
+++ b/Cross.toml
@@ -1,9 +1,9 @@
[build]
- default-target = "x86_64-unknown-linux-musl"
+default-target = "x86_64-unknown-linux-musl"
[build.env]
- passthrough = [ "BUILD_SPIN_EXAMPLES", "RUSTFLAGS", ]
+passthrough = ["BUILD_SPIN_EXAMPLES", "RUSTFLAGS"]
[target.aarch64-unknown-linux-musl]
- dockerfile.file = "./cross/Dockerfile"
- dockerfile.context = "./cross/"
\ No newline at end of file
+dockerfile.file = "./cross/Dockerfile"
+dockerfile.context = "./cross/"
diff --git a/crates/build/Cargo.toml b/crates/build/Cargo.toml
index b48418ad12..5b3f00c478 100644
--- a/crates/build/Cargo.toml
+++ b/crates/build/Cargo.toml
@@ -7,11 +7,11 @@ edition = { workspace = true }
[dependencies]
anyhow = "1.0.57"
futures = "0.3.21"
-serde = { version = "1.0", features = [ "derive" ] }
+serde = { version = "1.0", features = ["derive"] }
spin-common = { path = "../common" }
spin-manifest = { path = "../manifest" }
-terminal = { path = "../terminal" }
subprocess = "0.2.8"
-tokio = { version = "1.23", features = [ "full" ] }
+terminal = { path = "../terminal" }
+tokio = { version = "1.23", features = ["full"] }
toml = "0.5"
tracing = { workspace = true }
diff --git a/crates/common/Cargo.toml b/crates/common/Cargo.toml
index fb60b1f4d4..2471b4eaef 100644
--- a/crates/common/Cargo.toml
+++ b/crates/common/Cargo.toml
@@ -10,4 +10,4 @@ dirs = "5.0.1"
sha2 = "0.10"
tempfile = "3.5"
tokio = { version = "1", features = ["rt", "time"] }
-url = "2"
\ No newline at end of file
+url = "2"
diff --git a/crates/componentize/Cargo.toml b/crates/componentize/Cargo.toml
index 1f62620f14..e9a17de0bc 100644
--- a/crates/componentize/Cargo.toml
+++ b/crates/componentize/Cargo.toml
@@ -11,23 +11,23 @@ rust-version.workspace = true
[dependencies]
anyhow = { workspace = true }
tracing = "0.1"
-wasmparser = "0.200.0"
wasm-encoder = "0.200.0"
wasm-metadata = "0.200.0"
+wasmparser = "0.200.0"
wit-component = "0.200.0"
wit-parser = "0.200.0"
[dev-dependencies]
-wasmtime = { workspace = true }
-wasmtime-wasi = { workspace = true }
-tokio = { version = "1.36.0", features = ["macros", "rt", "fs"] }
async-trait = "0.1.77"
cap-std = "2.0.1"
rand = "0.8.5"
rand_chacha = "0.3.1"
rand_core = "0.6.4"
serde = { version = "1.0.197", features = ["derive"] }
+serde_json = "1.0"
tempfile = "3.10.0"
+tokio = { version = "1.36.0", features = ["macros", "rt", "fs"] }
toml = "0.8.10"
-serde_json = "1.0"
-wat = "1.200.0"
\ No newline at end of file
+wasmtime = { workspace = true }
+wasmtime-wasi = { workspace = true }
+wat = "1.200.0"
diff --git a/crates/compose/Cargo.toml b/crates/compose/Cargo.toml
index f6d9a7b837..a10102cba4 100644
--- a/crates/compose/Cargo.toml
+++ b/crates/compose/Cargo.toml
@@ -12,10 +12,10 @@ rust-version.workspace = true
anyhow = { workspace = true }
async-trait = "0.1"
indexmap = "2.2.6"
+semver = "1"
spin-app = { path = "../app" }
-spin-serde = { path = "../serde" }
spin-componentize = { workspace = true }
-semver = "1"
+spin-serde = { path = "../serde" }
thiserror = "1"
tokio = { version = "1.23", features = ["fs"] }
wac-graph = "0.5.0"
diff --git a/crates/compose/deny-all/Cargo.toml b/crates/compose/deny-all/Cargo.toml
index 931bc4d5f0..a3199be821 100644
--- a/crates/compose/deny-all/Cargo.toml
+++ b/crates/compose/deny-all/Cargo.toml
@@ -31,4 +31,4 @@ world = "deny-all"
"wasi:cli" = { path = "wit/deps/wasi/cli.wasm" }
"wasi:io" = { path = "wit/deps/wasi/io.wasm" }
-[workspace]
\ No newline at end of file
+[workspace]
diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml
index 53ab5f3875..50fc6f1e58 100644
--- a/crates/core/Cargo.toml
+++ b/crates/core/Cargo.toml
@@ -13,9 +13,9 @@ wasmtime = { workspace = true }
[dev-dependencies]
serde_json = "1"
spin-componentize = { workspace = true }
-tokio = { version = "1", features = ["macros", "rt", "rt-multi-thread"] }
spin-factor-wasi = { path = "../factor-wasi" }
spin-factors = { path = "../factors" }
spin-factors-test = { path = "../factors-test" }
spin-locked-app = { path = "../locked-app" }
-wasmtime-wasi = { workspace = true }
\ No newline at end of file
+tokio = { version = "1", features = ["macros", "rt", "rt-multi-thread"] }
+wasmtime-wasi = { workspace = true }
diff --git a/crates/expressions/Cargo.toml b/crates/expressions/Cargo.toml
index c1129b7031..342591b179 100644
--- a/crates/expressions/Cargo.toml
+++ b/crates/expressions/Cargo.toml
@@ -9,10 +9,10 @@ anyhow = "1.0"
async-trait = "0.1"
dotenvy = "0.15"
once_cell = "1"
+serde = "1.0.188"
spin-locked-app = { path = "../locked-app" }
thiserror = "1"
-serde = "1.0.188"
[dev-dependencies]
-toml = "0.5"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
+toml = "0.5"
diff --git a/crates/factor-key-value/Cargo.toml b/crates/factor-key-value/Cargo.toml
index 64df403528..9efd51b703 100644
--- a/crates/factor-key-value/Cargo.toml
+++ b/crates/factor-key-value/Cargo.toml
@@ -14,11 +14,11 @@ spin-world = { path = "../world" }
toml = "0.8"
[dev-dependencies]
-spin-factors-test = { path = "../factors-test" }
-tokio = { version = "1", features = ["macros", "rt"] }
-spin-factor-key-value-spin = { path = "../factor-key-value-spin" }
spin-factor-key-value-redis = { path = "../factor-key-value-redis" }
+spin-factor-key-value-spin = { path = "../factor-key-value-spin" }
+spin-factors-test = { path = "../factors-test" }
tempfile = "3.12.0"
+tokio = { version = "1", features = ["macros", "rt"] }
[lints]
diff --git a/crates/factor-llm/Cargo.toml b/crates/factor-llm/Cargo.toml
index b7f0e4107a..5989e1ad6e 100644
--- a/crates/factor-llm/Cargo.toml
+++ b/crates/factor-llm/Cargo.toml
@@ -22,9 +22,9 @@ spin-llm-local = { path = "../llm-local", optional = true }
spin-llm-remote-http = { path = "../llm-remote-http" }
spin-locked-app = { path = "../locked-app" }
spin-world = { path = "../world" }
-tracing = { workspace = true }
tokio = { version = "1", features = ["sync"] }
toml = "0.8"
+tracing = { workspace = true }
url = { version = "2", features = ["serde"] }
[dev-dependencies]
diff --git a/crates/factor-outbound-mqtt/Cargo.toml b/crates/factor-outbound-mqtt/Cargo.toml
index 95d7dce534..d9dfa04f83 100644
--- a/crates/factor-outbound-mqtt/Cargo.toml
+++ b/crates/factor-outbound-mqtt/Cargo.toml
@@ -7,9 +7,9 @@ edition = { workspace = true }
[dependencies]
anyhow = "1.0"
rumqttc = { version = "0.24", features = ["url"] }
+spin-core = { path = "../core" }
spin-factor-outbound-networking = { path = "../factor-outbound-networking" }
spin-factors = { path = "../factors" }
-spin-core = { path = "../core" }
spin-world = { path = "../world" }
table = { path = "../table" }
tokio = { version = "1.0", features = ["sync"] }
diff --git a/crates/factor-outbound-mysql/Cargo.toml b/crates/factor-outbound-mysql/Cargo.toml
index da9324eabe..083807cf19 100644
--- a/crates/factor-outbound-mysql/Cargo.toml
+++ b/crates/factor-outbound-mysql/Cargo.toml
@@ -12,7 +12,7 @@ anyhow = "1.0"
flate2 = "1.0.17"
# Removing default features for mysql_async to remove flate2/zlib feature
mysql_async = { version = "0.33.0", default-features = false, features = [
- "native-tls-tls",
+ "native-tls-tls",
] }
# Removing default features for mysql_common to remove flate2/zlib feature
mysql_common = { version = "0.31.0", default-features = false }
@@ -20,7 +20,7 @@ spin-app = { path = "../app" }
spin-core = { path = "../core" }
spin-expressions = { path = "../expressions" }
spin-factor-outbound-networking = { path = "../factor-outbound-networking" }
-spin-factors = { path = "../factors"}
+spin-factors = { path = "../factors" }
spin-outbound-networking = { path = "../outbound-networking" }
spin-world = { path = "../world" }
table = { path = "../table" }
diff --git a/crates/factor-outbound-networking/Cargo.toml b/crates/factor-outbound-networking/Cargo.toml
index 03fd55e4c6..66e1d054f1 100644
--- a/crates/factor-outbound-networking/Cargo.toml
+++ b/crates/factor-outbound-networking/Cargo.toml
@@ -33,7 +33,7 @@ wasmtime-wasi = { workspace = true }
default = ["spin-cli"]
# Includes the runtime configuration handling used by the Spin CLI
spin-cli = [
- "dep:rustls-pemfile",
+ "dep:rustls-pemfile",
]
[lints]
workspace = true
diff --git a/crates/factor-outbound-redis/Cargo.toml b/crates/factor-outbound-redis/Cargo.toml
index 0dffe6ea41..b46a273bcd 100644
--- a/crates/factor-outbound-redis/Cargo.toml
+++ b/crates/factor-outbound-redis/Cargo.toml
@@ -6,19 +6,19 @@ edition = { workspace = true }
[dependencies]
anyhow = "1.0"
+redis = { version = "0.21", features = ["tokio-comp", "tokio-native-tls-comp", "aio"] }
+spin-core = { path = "../core" }
spin-factor-outbound-networking = { path = "../factor-outbound-networking" }
spin-factors = { path = "../factors" }
-spin-core = { path = "../core" }
spin-world = { path = "../world" }
-tracing = { workspace = true }
table = { path = "../table" }
-redis = { version = "0.21", features = ["tokio-comp", "tokio-native-tls-comp", "aio"] }
+tracing = { workspace = true }
[dev-dependencies]
+spin-factor-variables = { path = "../factor-variables" }
spin-factors-test = { path = "../factors-test" }
tokio = { version = "1", features = ["macros", "rt"] }
-spin-factor-variables = { path = "../factor-variables" }
# wasmtime-wasi-http = { workspace = true }
[lints]
diff --git a/crates/factor-sqlite/Cargo.toml b/crates/factor-sqlite/Cargo.toml
index 3b45dcf3ca..4919a7305c 100644
--- a/crates/factor-sqlite/Cargo.toml
+++ b/crates/factor-sqlite/Cargo.toml
@@ -13,13 +13,13 @@ async-trait = "0.1"
serde = { version = "1.0", features = ["rc"] }
spin-factors = { path = "../factors" }
spin-locked-app = { path = "../locked-app" }
+spin-sqlite = { path = "../sqlite", optional = true }
+spin-sqlite-inproc = { path = "../sqlite-inproc", optional = true }
+spin-sqlite-libsql = { path = "../sqlite-libsql", optional = true }
spin-world = { path = "../world" }
table = { path = "../table" }
tokio = "1"
toml = "0.8"
-spin-sqlite = { path = "../sqlite", optional = true }
-spin-sqlite-inproc = { path = "../sqlite-inproc", optional = true }
-spin-sqlite-libsql = { path = "../sqlite-libsql", optional = true }
[dev-dependencies]
spin-factors-test = { path = "../factors-test" }
@@ -29,9 +29,9 @@ tokio = { version = "1", features = ["macros", "rt"] }
default = ["spin-cli"]
# Includes the runtime configuration handling used by the Spin CLI
spin-cli = [
- "dep:spin-sqlite",
- "dep:spin-sqlite-inproc",
- "dep:spin-sqlite-libsql",
+ "dep:spin-sqlite",
+ "dep:spin-sqlite-inproc",
+ "dep:spin-sqlite-libsql",
]
[lints]
diff --git a/crates/factor-variables/Cargo.toml b/crates/factor-variables/Cargo.toml
index 60e0f507b7..0cf4ab089a 100644
--- a/crates/factor-variables/Cargo.toml
+++ b/crates/factor-variables/Cargo.toml
@@ -5,9 +5,9 @@ authors = { workspace = true }
edition = { workspace = true }
[dependencies]
-azure_security_keyvault = { git = "https://github.com/azure/azure-sdk-for-rust", rev = "8c4caa251c3903d5eae848b41bb1d02a4d65231c" }
azure_core = { git = "https://github.com/azure/azure-sdk-for-rust", rev = "8c4caa251c3903d5eae848b41bb1d02a4d65231c" }
azure_identity = { git = "https://github.com/azure/azure-sdk-for-rust", rev = "8c4caa251c3903d5eae848b41bb1d02a4d65231c" }
+azure_security_keyvault = { git = "https://github.com/azure/azure-sdk-for-rust", rev = "8c4caa251c3903d5eae848b41bb1d02a4d65231c" }
dotenvy = "0.15"
serde = { version = "1.0", features = ["rc"] }
spin-expressions = { path = "../expressions" }
diff --git a/crates/http/Cargo.toml b/crates/http/Cargo.toml
index 4c993a13f7..60b58f03ff 100644
--- a/crates/http/Cargo.toml
+++ b/crates/http/Cargo.toml
@@ -7,16 +7,16 @@ edition = { workspace = true }
[dependencies]
anyhow = "1.0"
http = "1.0.0"
-hyper = { workspace = true }
http-body-util = { workspace = true }
-wasmtime-wasi-http = { workspace = true, optional = true }
+hyper = { workspace = true }
indexmap = "1"
percent-encoding = "2"
routefinder = "0.5.4"
serde = { version = "1.0", features = ["derive"] }
-tracing = { workspace = true }
spin-app = { path = "../app", optional = true }
spin-locked-app = { path = "../locked-app" }
+tracing = { workspace = true }
+wasmtime-wasi-http = { workspace = true, optional = true }
[dev-dependencies]
toml = "0.8.2"
diff --git a/crates/key-value-azure/Cargo.toml b/crates/key-value-azure/Cargo.toml
index fc119f5748..13804c3b2e 100644
--- a/crates/key-value-azure/Cargo.toml
+++ b/crates/key-value-azure/Cargo.toml
@@ -10,11 +10,11 @@ azure_data_cosmos = { git = "https://github.com/azure/azure-sdk-for-rust.git", r
azure_identity = { git = "https://github.com/azure/azure-sdk-for-rust.git", rev = "8c4caa251c3903d5eae848b41bb1d02a4d65231c" }
futures = "0.3.28"
serde = { version = "1.0", features = ["derive"] }
-spin-key-value = { path = "../key-value" }
spin-core = { path = "../core" }
+spin-key-value = { path = "../key-value" }
tokio = "1"
-url = "2"
tracing = { workspace = true }
+url = "2"
[lints]
workspace = true
diff --git a/crates/key-value-redis/Cargo.toml b/crates/key-value-redis/Cargo.toml
index 119d4dd2ee..baf71731f5 100644
--- a/crates/key-value-redis/Cargo.toml
+++ b/crates/key-value-redis/Cargo.toml
@@ -7,12 +7,12 @@ edition = { workspace = true }
[dependencies]
anyhow = "1"
redis = { version = "0.21", features = ["tokio-comp", "tokio-native-tls-comp"] }
-spin-key-value = { path = "../key-value" }
spin-core = { path = "../core" }
+spin-key-value = { path = "../key-value" }
spin-world = { path = "../world" }
tokio = "1"
-url = "2"
tracing = { workspace = true }
+url = "2"
[lints]
workspace = true
diff --git a/crates/key-value-sqlite/Cargo.toml b/crates/key-value-sqlite/Cargo.toml
index eed418a9ca..63f51862d0 100644
--- a/crates/key-value-sqlite/Cargo.toml
+++ b/crates/key-value-sqlite/Cargo.toml
@@ -7,11 +7,11 @@ edition = { workspace = true }
[dependencies]
anyhow = "1"
once_cell = "1"
-rusqlite = { version = "0.29.0", features = [ "bundled" ] }
-tokio = "1"
-spin-key-value = { path = "../key-value" }
+rusqlite = { version = "0.29.0", features = ["bundled"] }
spin-core = { path = "../core" }
+spin-key-value = { path = "../key-value" }
spin-world = { path = "../world" }
+tokio = "1"
tracing = { workspace = true }
[lints]
diff --git a/crates/key-value/Cargo.toml b/crates/key-value/Cargo.toml
index e5b53aec5a..0d13e95c71 100644
--- a/crates/key-value/Cargo.toml
+++ b/crates/key-value/Cargo.toml
@@ -9,10 +9,10 @@ doctest = false
[dependencies]
anyhow = "1.0"
-tokio = { version = "1", features = ["macros", "sync", "rt"] }
+lru = "0.9.0"
spin-app = { path = "../app" }
spin-core = { path = "../core" }
spin-world = { path = "../world" }
table = { path = "../table" }
+tokio = { version = "1", features = ["macros", "sync", "rt"] }
tracing = { workspace = true }
-lru = "0.9.0"
diff --git a/crates/llm-local/Cargo.toml b/crates/llm-local/Cargo.toml
index 5b73316423..9e559d76aa 100644
--- a/crates/llm-local/Cargo.toml
+++ b/crates/llm-local/Cargo.toml
@@ -10,8 +10,8 @@ candle = { git = "https://github.com/huggingface/candle", rev = "b80348d22f8f0da
candle-nn = { git = "https://github.com/huggingface/candle", rev = "b80348d22f8f0dadb6cc4101bde031d5de69a9a5" }
chrono = "0.4.26"
llm = { git = "https://github.com/rustformers/llm", rev = "2f6ffd4435799ceaa1d1bcb5a8790e5b3e0c5663", features = [
- "tokenizers-remote",
- "llama",
+ "tokenizers-remote",
+ "llama",
], default-features = false }
lru = "0.9.0"
num_cpus = "1"
diff --git a/crates/llm-remote-http/Cargo.toml b/crates/llm-remote-http/Cargo.toml
index af05459e56..c0fa4b4789 100644
--- a/crates/llm-remote-http/Cargo.toml
+++ b/crates/llm-remote-http/Cargo.toml
@@ -7,11 +7,11 @@ edition = { workspace = true }
[dependencies]
anyhow = "1.0"
http = "0.2"
+reqwest = { version = "0.11", features = ["gzip", "json"] }
serde = { version = "1.0.150", features = ["derive"] }
serde_json = "1.0"
spin-telemetry = { path = "../telemetry" }
spin-world = { path = "../world" }
-reqwest = { version = "0.11", features = ["gzip", "json"] }
tracing = { workspace = true }
[lints]
diff --git a/crates/loader/Cargo.toml b/crates/loader/Cargo.toml
index 2b49dca9c9..c568998823 100644
--- a/crates/loader/Cargo.toml
+++ b/crates/loader/Cargo.toml
@@ -16,7 +16,6 @@ indexmap = { version = "1" }
itertools = "0.10.3"
lazy_static = "1.4.0"
mime_guess = { version = "2.0" }
-spin-outbound-networking = { path = "../outbound-networking" }
path-absolutize = { version = "3.0.11", features = ["use_unix_paths_on_wasm"] }
regex = "1.5.4"
reqwest = "0.11.9"
@@ -25,9 +24,10 @@ serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
sha2 = "0.10.8"
shellexpand = "3.1"
-spin-locked-app = { path = "../locked-app" }
spin-common = { path = "../common" }
+spin-locked-app = { path = "../locked-app" }
spin-manifest = { path = "../manifest" }
+spin-outbound-networking = { path = "../outbound-networking" }
spin-serde = { path = "../serde" }
tempfile = "3.8.0"
terminal = { path = "../terminal" }
diff --git a/crates/locked-app/Cargo.toml b/crates/locked-app/Cargo.toml
index cc4d7ae6ee..d0531c52a6 100644
--- a/crates/locked-app/Cargo.toml
+++ b/crates/locked-app/Cargo.toml
@@ -10,4 +10,4 @@ async-trait = "0.1"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
spin-serde = { path = "../serde" }
-thiserror = "1.0"
\ No newline at end of file
+thiserror = "1.0"
diff --git a/crates/manifest/Cargo.toml b/crates/manifest/Cargo.toml
index 8ae06ffedc..dc18ef8abc 100644
--- a/crates/manifest/Cargo.toml
+++ b/crates/manifest/Cargo.toml
@@ -10,8 +10,8 @@ indexmap = { version = "1", features = ["serde"] }
semver = { version = "1.0", features = ["serde"] }
serde = { version = "1.0", features = ["derive"] }
spin-serde = { path = "../serde" }
-thiserror = "1"
terminal = { path = "../terminal" }
+thiserror = "1"
toml = { version = "0.8.0", features = ["preserve_order"] }
url = "2.4.1"
wasm-pkg-common = "0.4.1"
diff --git a/crates/oci/Cargo.toml b/crates/oci/Cargo.toml
index 92ac7ae6e3..2077b3e873 100644
--- a/crates/oci/Cargo.toml
+++ b/crates/oci/Cargo.toml
@@ -13,9 +13,9 @@ base64 = "0.21"
chrono = "0.4"
# Fork with updated auth to support ACR login
# Ref https://github.com/camallo/dkregistry-rs/pull/263
+dirs = "4.0"
dkregistry = { git = "https://github.com/fermyon/dkregistry-rs", rev = "161cf2b66996ed97c7abaf046e38244484814de3" }
docker_credential = "1.0"
-dirs = "4.0"
futures-util = "0.3"
itertools = "0.12.1"
oci-distribution = { git = "https://github.com/fermyon/oci-distribution", rev = "7e4ce9be9bcd22e78a28f06204931f10c44402ba" }
diff --git a/crates/outbound-networking/Cargo.toml b/crates/outbound-networking/Cargo.toml
index 0505f5f00d..d630181eb2 100644
--- a/crates/outbound-networking/Cargo.toml
+++ b/crates/outbound-networking/Cargo.toml
@@ -8,7 +8,7 @@ edition.workspace = true
anyhow = "1.0"
http = "1.0.0"
ipnet = "2.9.0"
-spin-expressions = { path = "../expressions" }
+spin-expressions = { path = "../expressions" }
spin-locked-app = { path = "../locked-app" }
terminal = { path = "../terminal" }
url = "2.4.1"
diff --git a/crates/plugins/Cargo.toml b/crates/plugins/Cargo.toml
index 896d6590e7..165fc88eec 100644
--- a/crates/plugins/Cargo.toml
+++ b/crates/plugins/Cargo.toml
@@ -22,6 +22,6 @@ tar = "0.4.38"
tempfile = "3.3.0"
terminal = { path = "../terminal" }
thiserror = "1"
-tokio = { version = "1.23", features = [ "fs", "process", "rt", "macros" ] }
+tokio = { version = "1.23", features = ["fs", "process", "rt", "macros"] }
tracing = { workspace = true }
url = { version = "2.2.2", features = ["serde"] }
diff --git a/crates/runtime-config/Cargo.toml b/crates/runtime-config/Cargo.toml
index 267dfdec79..9ca8e5e8df 100644
--- a/crates/runtime-config/Cargo.toml
+++ b/crates/runtime-config/Cargo.toml
@@ -10,21 +10,21 @@ rust-version.workspace = true
[dependencies]
anyhow = { workspace = true }
-spin-factors = { path = "../factors" }
spin-factor-key-value = { path = "../factor-key-value" }
-spin-factor-key-value-spin = { path = "../factor-key-value-spin" }
-spin-factor-key-value-redis = { path = "../factor-key-value-redis" }
spin-factor-key-value-azure = { path = "../factor-key-value-azure" }
+spin-factor-key-value-redis = { path = "../factor-key-value-redis" }
+spin-factor-key-value-spin = { path = "../factor-key-value-spin" }
spin-factor-llm = { path = "../factor-llm" }
spin-factor-outbound-http = { path = "../factor-outbound-http" }
spin-factor-outbound-mqtt = { path = "../factor-outbound-mqtt" }
+spin-factor-outbound-mysql = { path = "../factor-outbound-mysql" }
spin-factor-outbound-networking = { path = "../factor-outbound-networking" }
spin-factor-outbound-pg = { path = "../factor-outbound-pg" }
-spin-factor-outbound-mysql = { path = "../factor-outbound-mysql" }
spin-factor-outbound-redis = { path = "../factor-outbound-redis" }
spin-factor-sqlite = { path = "../factor-sqlite" }
spin-factor-variables = { path = "../factor-variables" }
spin-factor-wasi = { path = "../factor-wasi" }
+spin-factors = { path = "../factors" }
toml = "0.8"
[lints]
diff --git a/crates/serde/Cargo.toml b/crates/serde/Cargo.toml
index cf7ad7b169..89f8a918b9 100644
--- a/crates/serde/Cargo.toml
+++ b/crates/serde/Cargo.toml
@@ -9,4 +9,4 @@ anyhow = "1.0"
base64 = "0.22.1"
semver = { version = "1.0", features = ["serde"] }
serde = "1.0.189"
-wasm-pkg-common = "0.4.1"
\ No newline at end of file
+wasm-pkg-common = "0.4.1"
diff --git a/crates/sqlite-inproc/Cargo.toml b/crates/sqlite-inproc/Cargo.toml
index 874eafd3e2..12fe8fc55f 100644
--- a/crates/sqlite-inproc/Cargo.toml
+++ b/crates/sqlite-inproc/Cargo.toml
@@ -5,13 +5,13 @@ authors = { workspace = true }
edition = { workspace = true }
[dependencies]
+anyhow = "1.0"
async-trait = "0.1.68"
+once_cell = "1"
+rand = "0.8"
+rusqlite = { version = "0.29.0", features = ["bundled"] }
spin-sqlite = { path = "../sqlite" }
spin-world = { path = "../world" }
-anyhow = "1.0"
-rusqlite = { version = "0.29.0", features = [ "bundled" ] }
-rand = "0.8"
-once_cell = "1"
tokio = "1"
tracing = { workspace = true }
diff --git a/crates/sqlite-libsql/Cargo.toml b/crates/sqlite-libsql/Cargo.toml
index d754418c93..0d2f279209 100644
--- a/crates/sqlite-libsql/Cargo.toml
+++ b/crates/sqlite-libsql/Cargo.toml
@@ -5,15 +5,15 @@ authors = { workspace = true }
edition = { workspace = true }
[dependencies]
-async-trait = "0.1.68"
anyhow = "1.0"
+async-trait = "0.1.68"
# We don't actually use rusqlite itself, but we'd like the same bundled
# libsqlite3-sys as used by spin-sqlite-inproc.
+libsql = { version = "0.3.2", features = ["remote"], default-features = false }
rusqlite = { version = "0.29.0", features = ["bundled"] }
spin-sqlite = { path = "../sqlite" }
spin-world = { path = "../world" }
sqlparser = "0.34"
-libsql = { version = "0.3.2", features = ["remote"], default-features = false }
tokio = { version = "1", features = ["full"] }
tracing = { workspace = true }
diff --git a/crates/sqlite/Cargo.toml b/crates/sqlite/Cargo.toml
index 6a5b5e8b01..0cb7b12b47 100644
--- a/crates/sqlite/Cargo.toml
+++ b/crates/sqlite/Cargo.toml
@@ -7,8 +7,8 @@ edition = { workspace = true }
[dependencies]
anyhow = "1.0"
async-trait = "0.1.68"
-spin-core = { path = "../core" }
spin-app = { path = "../app" }
+spin-core = { path = "../core" }
spin-world = { path = "../world" }
table = { path = "../table" }
tokio = "1"
diff --git a/crates/telemetry/Cargo.toml b/crates/telemetry/Cargo.toml
index 4e63a6e8f2..095936d076 100644
--- a/crates/telemetry/Cargo.toml
+++ b/crates/telemetry/Cargo.toml
@@ -8,16 +8,16 @@ edition = { workspace = true }
anyhow = { workspace = true }
http0 = { version = "0.2.9", package = "http" }
http1 = { version = "1.0.0", package = "http" }
-opentelemetry = { version = "0.22.0", features = [ "metrics", "trace", "logs"] }
-opentelemetry_sdk = { version = "0.22.1", features = ["rt-tokio", "logs_level_enabled"] }
-opentelemetry-otlp = { version = "0.15.0", default-features=false, features = ["http-proto", "trace", "http", "reqwest-client", "metrics", "grpc-tonic", "logs"] }
+opentelemetry = { version = "0.22.0", features = ["metrics", "trace", "logs"] }
+opentelemetry-otlp = { version = "0.15.0", default-features = false, features = ["http-proto", "trace", "http", "reqwest-client", "metrics", "grpc-tonic", "logs"] }
opentelemetry-semantic-conventions = "0.14.0"
+opentelemetry_sdk = { version = "0.22.1", features = ["rt-tokio", "logs_level_enabled"] }
+terminal = { path = "../terminal" }
tracing = { version = "0.1.37", features = ["log"] }
tracing-appender = "0.2.2"
-tracing-opentelemetry = { version = "0.23.0", default-features = false, features = ["metrics"] }
+tracing-opentelemetry = { version = "0.23.0", default-features = false, features = ["metrics"] }
tracing-subscriber = { version = "0.3.17", default-features = false, features = ["smallvec", "fmt", "ansi", "std", "env-filter", "json", "registry"] }
url = "2.2.2"
-terminal = { path = "../terminal" }
[features]
tracing-log-compat = ["tracing-subscriber/tracing-log", "tracing-opentelemetry/tracing-log"]
diff --git a/crates/terminal/Cargo.toml b/crates/terminal/Cargo.toml
index d40dc8f7bf..52f66dbe78 100644
--- a/crates/terminal/Cargo.toml
+++ b/crates/terminal/Cargo.toml
@@ -5,6 +5,6 @@ authors = { workspace = true }
edition = { workspace = true }
[dependencies]
-termcolor = "1.2"
-once_cell = "1.0"
atty = "0.2"
+once_cell = "1.0"
+termcolor = "1.2"
diff --git a/crates/trigger-http/Cargo.toml b/crates/trigger-http/Cargo.toml
index 65030acc6a..c273b1db22 100644
--- a/crates/trigger-http/Cargo.toml
+++ b/crates/trigger-http/Cargo.toml
@@ -19,9 +19,9 @@ clap = "3"
futures = "0.3"
futures-util = "0.3.8"
http = "1.0.0"
+http-body-util = { workspace = true }
hyper = { workspace = true }
hyper-util = { version = "0.1.2", features = ["tokio"] }
-http-body-util = { workspace = true }
indexmap = "1"
percent-encoding = "2"
rustls = { version = "0.22.4" }
@@ -42,8 +42,8 @@ terminal = { path = "../terminal" }
tls-listener = { version = "0.10.0", features = ["rustls"] }
tokio = { version = "1.23", features = ["full"] }
tokio-rustls = { version = "0.25.0" }
-url = "2.4.1"
tracing = { workspace = true }
+url = "2.4.1"
wasmtime = { workspace = true }
wasmtime-wasi = { workspace = true }
wasmtime-wasi-http = { workspace = true }
diff --git a/crates/trigger-redis/Cargo.toml b/crates/trigger-redis/Cargo.toml
index 0ace95427b..f399afeb4d 100644
--- a/crates/trigger-redis/Cargo.toml
+++ b/crates/trigger-redis/Cargo.toml
@@ -11,14 +11,14 @@ doctest = false
anyhow = "1.0"
async-trait = "0.1"
futures = "0.3"
+redis = { version = "0.26.1", features = ["tokio-comp"] }
serde = "1.0.188"
spin-factor-variables = { path = "../factor-variables" }
spin-telemetry = { path = "../telemetry" }
spin-trigger = { path = "../trigger" }
spin-world = { path = "../world" }
-redis = { version = "0.26.1", features = ["tokio-comp"] }
-tracing = { workspace = true }
tokio = { version = "1.39.3", features = ["macros", "rt"] }
+tracing = { workspace = true }
[lints]
workspace = true
diff --git a/crates/trigger/Cargo.toml b/crates/trigger/Cargo.toml
index c8f6b5c8ba..d022d1534c 100644
--- a/crates/trigger/Cargo.toml
+++ b/crates/trigger/Cargo.toml
@@ -18,31 +18,31 @@ anyhow = "1"
clap = { version = "3.1.18", features = ["derive", "env"] }
ctrlc = { version = "3.2", features = ["termination"] }
futures = "0.3"
-spin-runtime-config = { path = "../runtime-config" }
sanitize-filename = "0.5"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
spin-app = { path = "../app" }
spin-common = { path = "../common" }
-spin-compose = { path = "../compose" }
spin-componentize = { path = "../componentize" }
+spin-compose = { path = "../compose" }
spin-core = { path = "../core" }
spin-factor-key-value = { path = "../factor-key-value" }
-spin-factor-outbound-http = { path = "../factor-outbound-http" }
spin-factor-llm = { path = "../factor-llm" }
+spin-factor-outbound-http = { path = "../factor-outbound-http" }
spin-factor-outbound-mqtt = { path = "../factor-outbound-mqtt" }
+spin-factor-outbound-mysql = { path = "../factor-outbound-mysql" }
spin-factor-outbound-networking = { path = "../factor-outbound-networking" }
spin-factor-outbound-pg = { path = "../factor-outbound-pg" }
-spin-factor-outbound-mysql = { path = "../factor-outbound-mysql" }
spin-factor-outbound-redis = { path = "../factor-outbound-redis" }
spin-factor-sqlite = { path = "../factor-sqlite" }
spin-factor-variables = { path = "../factor-variables" }
spin-factor-wasi = { path = "../factor-wasi" }
spin-factors = { path = "../factors" }
spin-factors-executor = { path = "../factors-executor" }
+spin-runtime-config = { path = "../runtime-config" }
spin-telemetry = { path = "../telemetry" }
-tokio = { version = "1.23", features = ["fs"] }
terminal = { path = "../terminal" }
+tokio = { version = "1.23", features = ["fs"] }
tracing = { workspace = true }
[lints]
diff --git a/examples/spin-wagi-http/http-rust/Cargo.toml b/examples/spin-wagi-http/http-rust/Cargo.toml
index 71644ebd08..b5fb3c8d32 100644
--- a/examples/spin-wagi-http/http-rust/Cargo.toml
+++ b/examples/spin-wagi-http/http-rust/Cargo.toml
@@ -4,7 +4,7 @@ version = "0.1.0"
edition = "2021"
[lib]
-crate-type = [ "cdylib" ]
+crate-type = ["cdylib"]
[dependencies]
# Useful crate to handle errors.
diff --git a/examples/wagi-http-rust/Cargo.toml b/examples/wagi-http-rust/Cargo.toml
index 9e98c0368b..4c5da453f4 100644
--- a/examples/wagi-http-rust/Cargo.toml
+++ b/examples/wagi-http-rust/Cargo.toml
@@ -6,4 +6,4 @@ edition = "2021"
[dependencies]
miniserde = "0.1"
-[workspace]
\ No newline at end of file
+[workspace]
diff --git a/examples/wagi-http-rust/spin.toml b/examples/wagi-http-rust/spin.toml
index c5d1a7821a..bae10e49a8 100644
--- a/examples/wagi-http-rust/spin.toml
+++ b/examples/wagi-http-rust/spin.toml
@@ -9,7 +9,7 @@ version = "1.0.0"
[[trigger.http]]
route = "/env"
component = "env"
-executor = { type = "wagi" }
+executor = { type = "wagi" }
[component.env]
source = "target/wasm32-wasi/release/wagihelloworld.wasm"
diff --git a/taplo.toml b/taplo.toml
new file mode 100644
index 0000000000..1cd2a08e26
--- /dev/null
+++ b/taplo.toml
@@ -0,0 +1,15 @@
+exclude = [
+ ".git/**/*.toml",
+ "**/tests/**/*.toml",
+ "templates/**/*.toml",
+]
+
+[formatting]
+array_auto_collapse = false
+array_auto_expand = false
+
+[[rule]]
+include = ["Cargo.toml", "**/Cargo.toml"]
+keys = ["dependencies", "workspace.dependencies", "dev-dependencies"]
+[rule.formatting]
+reorder_keys = true
| 2,767
|
[
"2766"
] |
diff --git a/crates/ui-testing/Cargo.toml b/crates/ui-testing/Cargo.toml
index ad0d9021be..ad2a7316ae 100644
--- a/crates/ui-testing/Cargo.toml
+++ b/crates/ui-testing/Cargo.toml
@@ -9,4 +9,4 @@ anyhow = "1.0"
dirs = "4.0"
libtest-mimic = "0.6.1"
snapbox = "0.4.12"
-tokio = { version = "1", features = ["macros", "rt"] }
\ No newline at end of file
+tokio = { version = "1", features = ["macros", "rt"] }
diff --git a/examples/vault-variable-test/Cargo.toml b/examples/vault-variable-test/Cargo.toml
index 21c6575816..d50a940b22 100644
--- a/examples/vault-variable-test/Cargo.toml
+++ b/examples/vault-variable-test/Cargo.toml
@@ -10,7 +10,7 @@ crate-type = ["cdylib"]
[dependencies]
anyhow = "1"
-spin-sdk = "2.2.0"
constant_time_eq = "0.3.0"
+spin-sdk = "2.2.0"
[workspace]
diff --git a/examples/vault-variable-test/runtime_config.toml b/examples/vault-variable-test/runtime_config.toml
index e8cb076570..002db0d7cc 100644
--- a/examples/vault-variable-test/runtime_config.toml
+++ b/examples/vault-variable-test/runtime_config.toml
@@ -2,4 +2,4 @@
type = "vault"
url = "http://127.0.0.1:8200"
token = "root"
-mount = "secret"
\ No newline at end of file
+mount = "secret"
|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
2d709df2d87ec1efd11a7052df6135e4ea29a7be
|
Abstract pg client type in factor-outbound-pg
This is followup work to #2632
|
2024-07-15T21:05:43Z
|
fermyon__spin-2651
|
fermyon/spin
|
3.2
|
diff --git a/Cargo.lock b/Cargo.lock
index 891e4802c9..f2cae7b546 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -7615,7 +7615,6 @@ dependencies = [
"spin-core",
"spin-factor-outbound-networking",
"spin-factor-variables",
- "spin-factor-wasi",
"spin-factors",
"spin-factors-test",
"spin-world",
diff --git a/crates/factor-outbound-pg/Cargo.toml b/crates/factor-outbound-pg/Cargo.toml
index ca18e93a18..cd8681a4a2 100644
--- a/crates/factor-outbound-pg/Cargo.toml
+++ b/crates/factor-outbound-pg/Cargo.toml
@@ -19,7 +19,6 @@ tracing = { workspace = true }
[dev-dependencies]
spin-factor-variables = { path = "../factor-variables" }
-spin-factor-wasi = { path = "../factor-wasi" }
spin-factors-test = { path = "../factors-test" }
tokio = { version = "1", features = ["macros", "rt"] }
diff --git a/crates/factor-outbound-pg/src/client.rs b/crates/factor-outbound-pg/src/client.rs
new file mode 100644
index 0000000000..06a93a6311
--- /dev/null
+++ b/crates/factor-outbound-pg/src/client.rs
@@ -0,0 +1,284 @@
+use anyhow::{anyhow, Result};
+use native_tls::TlsConnector;
+use postgres_native_tls::MakeTlsConnector;
+use spin_world::async_trait;
+use spin_world::v2::postgres::{self as v2};
+use spin_world::v2::rdbms_types::{Column, DbDataType, DbValue, ParameterValue, RowSet};
+use tokio_postgres::types::Type;
+use tokio_postgres::{config::SslMode, types::ToSql, Row};
+use tokio_postgres::{Client as TokioClient, NoTls, Socket};
+
+#[async_trait]
+pub trait Client {
+ async fn build_client(address: &str) -> Result<Self>
+ where
+ Self: Sized;
+
+ async fn execute(
+ &self,
+ statement: String,
+ params: Vec<ParameterValue>,
+ ) -> Result<u64, v2::Error>;
+
+ async fn query(
+ &self,
+ statement: String,
+ params: Vec<ParameterValue>,
+ ) -> Result<RowSet, v2::Error>;
+}
+
+#[async_trait]
+impl Client for TokioClient {
+ async fn build_client(address: &str) -> Result<Self>
+ where
+ Self: Sized,
+ {
+ let config = address.parse::<tokio_postgres::Config>()?;
+
+ tracing::debug!("Build new connection: {}", address);
+
+ if config.get_ssl_mode() == SslMode::Disable {
+ let (client, connection) = config.connect(NoTls).await?;
+ spawn_connection(connection);
+ Ok(client)
+ } else {
+ let builder = TlsConnector::builder();
+ let connector = MakeTlsConnector::new(builder.build()?);
+ let (client, connection) = config.connect(connector).await?;
+ spawn_connection(connection);
+ Ok(client)
+ }
+ }
+
+ async fn execute(
+ &self,
+ statement: String,
+ params: Vec<ParameterValue>,
+ ) -> Result<u64, v2::Error> {
+ let params: Vec<&(dyn ToSql + Sync)> = params
+ .iter()
+ .map(to_sql_parameter)
+ .collect::<Result<Vec<_>>>()
+ .map_err(|e| v2::Error::ValueConversionFailed(format!("{:?}", e)))?;
+
+ self.execute(&statement, params.as_slice())
+ .await
+ .map_err(|e| v2::Error::QueryFailed(format!("{:?}", e)))
+ }
+
+ async fn query(
+ &self,
+ statement: String,
+ params: Vec<ParameterValue>,
+ ) -> Result<RowSet, v2::Error> {
+ let params: Vec<&(dyn ToSql + Sync)> = params
+ .iter()
+ .map(to_sql_parameter)
+ .collect::<Result<Vec<_>>>()
+ .map_err(|e| v2::Error::BadParameter(format!("{:?}", e)))?;
+
+ let results = self
+ .query(&statement, params.as_slice())
+ .await
+ .map_err(|e| v2::Error::QueryFailed(format!("{:?}", e)))?;
+
+ if results.is_empty() {
+ return Ok(RowSet {
+ columns: vec![],
+ rows: vec![],
+ });
+ }
+
+ let columns = infer_columns(&results[0]);
+ let rows = results
+ .iter()
+ .map(convert_row)
+ .collect::<Result<Vec<_>, _>>()
+ .map_err(|e| v2::Error::QueryFailed(format!("{:?}", e)))?;
+
+ Ok(RowSet { columns, rows })
+ }
+}
+
+fn spawn_connection<T>(connection: tokio_postgres::Connection<Socket, T>)
+where
+ T: tokio_postgres::tls::TlsStream + std::marker::Unpin + std::marker::Send + 'static,
+{
+ tokio::spawn(async move {
+ if let Err(e) = connection.await {
+ tracing::error!("Postgres connection error: {}", e);
+ }
+ });
+}
+
+fn to_sql_parameter(value: &ParameterValue) -> Result<&(dyn ToSql + Sync)> {
+ match value {
+ ParameterValue::Boolean(v) => Ok(v),
+ ParameterValue::Int32(v) => Ok(v),
+ ParameterValue::Int64(v) => Ok(v),
+ ParameterValue::Int8(v) => Ok(v),
+ ParameterValue::Int16(v) => Ok(v),
+ ParameterValue::Floating32(v) => Ok(v),
+ ParameterValue::Floating64(v) => Ok(v),
+ ParameterValue::Uint8(_)
+ | ParameterValue::Uint16(_)
+ | ParameterValue::Uint32(_)
+ | ParameterValue::Uint64(_) => Err(anyhow!("Postgres does not support unsigned integers")),
+ ParameterValue::Str(v) => Ok(v),
+ ParameterValue::Binary(v) => Ok(v),
+ ParameterValue::DbNull => Ok(&PgNull),
+ }
+}
+
+fn infer_columns(row: &Row) -> Vec<Column> {
+ let mut result = Vec::with_capacity(row.len());
+ for index in 0..row.len() {
+ result.push(infer_column(row, index));
+ }
+ result
+}
+
+fn infer_column(row: &Row, index: usize) -> Column {
+ let column = &row.columns()[index];
+ let name = column.name().to_owned();
+ let data_type = convert_data_type(column.type_());
+ Column { name, data_type }
+}
+
+fn convert_data_type(pg_type: &Type) -> DbDataType {
+ match *pg_type {
+ Type::BOOL => DbDataType::Boolean,
+ Type::BYTEA => DbDataType::Binary,
+ Type::FLOAT4 => DbDataType::Floating32,
+ Type::FLOAT8 => DbDataType::Floating64,
+ Type::INT2 => DbDataType::Int16,
+ Type::INT4 => DbDataType::Int32,
+ Type::INT8 => DbDataType::Int64,
+ Type::TEXT | Type::VARCHAR | Type::BPCHAR => DbDataType::Str,
+ _ => {
+ tracing::debug!("Couldn't convert Postgres type {} to WIT", pg_type.name(),);
+ DbDataType::Other
+ }
+ }
+}
+
+fn convert_row(row: &Row) -> Result<Vec<DbValue>, tokio_postgres::Error> {
+ let mut result = Vec::with_capacity(row.len());
+ for index in 0..row.len() {
+ result.push(convert_entry(row, index)?);
+ }
+ Ok(result)
+}
+
+fn convert_entry(row: &Row, index: usize) -> Result<DbValue, tokio_postgres::Error> {
+ let column = &row.columns()[index];
+ let value = match column.type_() {
+ &Type::BOOL => {
+ let value: Option<bool> = row.try_get(index)?;
+ match value {
+ Some(v) => DbValue::Boolean(v),
+ None => DbValue::DbNull,
+ }
+ }
+ &Type::BYTEA => {
+ let value: Option<Vec<u8>> = row.try_get(index)?;
+ match value {
+ Some(v) => DbValue::Binary(v),
+ None => DbValue::DbNull,
+ }
+ }
+ &Type::FLOAT4 => {
+ let value: Option<f32> = row.try_get(index)?;
+ match value {
+ Some(v) => DbValue::Floating32(v),
+ None => DbValue::DbNull,
+ }
+ }
+ &Type::FLOAT8 => {
+ let value: Option<f64> = row.try_get(index)?;
+ match value {
+ Some(v) => DbValue::Floating64(v),
+ None => DbValue::DbNull,
+ }
+ }
+ &Type::INT2 => {
+ let value: Option<i16> = row.try_get(index)?;
+ match value {
+ Some(v) => DbValue::Int16(v),
+ None => DbValue::DbNull,
+ }
+ }
+ &Type::INT4 => {
+ let value: Option<i32> = row.try_get(index)?;
+ match value {
+ Some(v) => DbValue::Int32(v),
+ None => DbValue::DbNull,
+ }
+ }
+ &Type::INT8 => {
+ let value: Option<i64> = row.try_get(index)?;
+ match value {
+ Some(v) => DbValue::Int64(v),
+ None => DbValue::DbNull,
+ }
+ }
+ &Type::TEXT | &Type::VARCHAR | &Type::BPCHAR => {
+ let value: Option<String> = row.try_get(index)?;
+ match value {
+ Some(v) => DbValue::Str(v),
+ None => DbValue::DbNull,
+ }
+ }
+ t => {
+ tracing::debug!(
+ "Couldn't convert Postgres type {} in column {}",
+ t.name(),
+ column.name()
+ );
+ DbValue::Unsupported
+ }
+ };
+ Ok(value)
+}
+
+/// Although the Postgres crate converts Rust Option::None to Postgres NULL,
+/// it enforces the type of the Option as it does so. (For example, trying to
+/// pass an Option::<i32>::None to a VARCHAR column fails conversion.) As we
+/// do not know expected column types, we instead use a "neutral" custom type
+/// which allows conversion to any type but always tells the Postgres crate to
+/// treat it as a SQL NULL.
+struct PgNull;
+
+impl ToSql for PgNull {
+ fn to_sql(
+ &self,
+ _ty: &Type,
+ _out: &mut tokio_postgres::types::private::BytesMut,
+ ) -> Result<tokio_postgres::types::IsNull, Box<dyn std::error::Error + Sync + Send>>
+ where
+ Self: Sized,
+ {
+ Ok(tokio_postgres::types::IsNull::Yes)
+ }
+
+ fn accepts(_ty: &Type) -> bool
+ where
+ Self: Sized,
+ {
+ true
+ }
+
+ fn to_sql_checked(
+ &self,
+ _ty: &Type,
+ _out: &mut tokio_postgres::types::private::BytesMut,
+ ) -> Result<tokio_postgres::types::IsNull, Box<dyn std::error::Error + Sync + Send>> {
+ Ok(tokio_postgres::types::IsNull::Yes)
+ }
+}
+
+impl std::fmt::Debug for PgNull {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("NULL").finish()
+ }
+}
diff --git a/crates/factor-outbound-pg/src/host.rs b/crates/factor-outbound-pg/src/host.rs
index 63bc9ac91b..1f7be3570b 100644
--- a/crates/factor-outbound-pg/src/host.rs
+++ b/crates/factor-outbound-pg/src/host.rs
@@ -1,27 +1,21 @@
-use anyhow::{anyhow, Result};
-use native_tls::TlsConnector;
-use postgres_native_tls::MakeTlsConnector;
+use anyhow::Result;
use spin_core::{async_trait, wasmtime::component::Resource};
use spin_world::v1::postgres as v1;
use spin_world::v1::rdbms_types as v1_types;
use spin_world::v2::postgres::{self as v2, Connection};
use spin_world::v2::rdbms_types;
-use spin_world::v2::rdbms_types::{Column, DbDataType, DbValue, ParameterValue, RowSet};
-use tokio_postgres::{
- config::SslMode,
- types::{ToSql, Type},
- Client, NoTls, Row, Socket,
-};
+use spin_world::v2::rdbms_types::{ParameterValue, RowSet};
use tracing::instrument;
use tracing::Level;
+use crate::client::Client;
use crate::InstanceState;
-impl InstanceState {
+impl<C: Client> InstanceState<C> {
async fn open_connection(&mut self, address: &str) -> Result<Resource<Connection>, v2::Error> {
self.connections
.push(
- build_client(address)
+ C::build_client(address)
.await
.map_err(|e| v2::Error::ConnectionFailed(format!("{e:?}")))?,
)
@@ -29,7 +23,7 @@ impl InstanceState {
.map(Resource::new_own)
}
- async fn get_client(&mut self, connection: Resource<Connection>) -> Result<&Client, v2::Error> {
+ async fn get_client(&mut self, connection: Resource<Connection>) -> Result<&C, v2::Error> {
self.connections
.get(connection.rep())
.ok_or_else(|| v2::Error::ConnectionFailed("no connection found".into()))
@@ -52,7 +46,6 @@ impl InstanceState {
.or_else(|| if ports.len() == 1 { ports.get(1) } else { None });
let port_str = port.map(|p| format!(":{}", p)).unwrap_or_default();
let url = format!("{address}{port_str}");
- // TODO: Should I be unwrapping this?
if !self.allowed_hosts.check_url(&url, "postgres").await? {
return Ok(false);
}
@@ -66,10 +59,10 @@ impl InstanceState {
}
#[async_trait]
-impl v2::Host for InstanceState {}
+impl<C: Send + Sync + Client> v2::Host for InstanceState<C> {}
#[async_trait]
-impl v2::HostConnection for InstanceState {
+impl<C: Send + Sync + Client> v2::HostConnection for InstanceState<C> {
#[instrument(name = "spin_outbound_pg.open_connection", skip(self), err(level = Level::INFO), fields(otel.kind = "client", db.system = "postgresql"))]
async fn open(&mut self, address: String) -> Result<Resource<Connection>, v2::Error> {
if !self
@@ -91,20 +84,11 @@ impl v2::HostConnection for InstanceState {
statement: String,
params: Vec<ParameterValue>,
) -> Result<u64, v2::Error> {
- let params: Vec<&(dyn ToSql + Sync)> = params
- .iter()
- .map(to_sql_parameter)
- .collect::<anyhow::Result<Vec<_>>>()
- .map_err(|e| v2::Error::ValueConversionFailed(format!("{:?}", e)))?;
-
- let nrow = self
+ Ok(self
.get_client(connection)
.await?
- .execute(&statement, params.as_slice())
- .await
- .map_err(|e| v2::Error::QueryFailed(format!("{:?}", e)))?;
-
- Ok(nrow)
+ .execute(statement, params)
+ .await?)
}
#[instrument(name = "spin_outbound_pg.query", skip(self, connection), err(level = Level::INFO), fields(otel.kind = "client", db.system = "postgresql", otel.name = statement))]
@@ -114,34 +98,11 @@ impl v2::HostConnection for InstanceState {
statement: String,
params: Vec<ParameterValue>,
) -> Result<RowSet, v2::Error> {
- let params: Vec<&(dyn ToSql + Sync)> = params
- .iter()
- .map(to_sql_parameter)
- .collect::<anyhow::Result<Vec<_>>>()
- .map_err(|e| v2::Error::BadParameter(format!("{:?}", e)))?;
-
- let results = self
+ Ok(self
.get_client(connection)
.await?
- .query(&statement, params.as_slice())
- .await
- .map_err(|e| v2::Error::QueryFailed(format!("{:?}", e)))?;
-
- if results.is_empty() {
- return Ok(RowSet {
- columns: vec![],
- rows: vec![],
- });
- }
-
- let columns = infer_columns(&results[0]);
- let rows = results
- .iter()
- .map(convert_row)
- .collect::<Result<Vec<_>, _>>()
- .map_err(|e| v2::Error::QueryFailed(format!("{:?}", e)))?;
-
- Ok(RowSet { columns, rows })
+ .query(statement, params)
+ .await?)
}
fn drop(&mut self, connection: Resource<Connection>) -> anyhow::Result<()> {
@@ -150,225 +111,12 @@ impl v2::HostConnection for InstanceState {
}
}
-impl rdbms_types::Host for InstanceState {
+impl<C: Send> rdbms_types::Host for InstanceState<C> {
fn convert_error(&mut self, error: v2::Error) -> Result<v2::Error> {
Ok(error)
}
}
-fn to_sql_parameter(value: &ParameterValue) -> anyhow::Result<&(dyn ToSql + Sync)> {
- match value {
- ParameterValue::Boolean(v) => Ok(v),
- ParameterValue::Int32(v) => Ok(v),
- ParameterValue::Int64(v) => Ok(v),
- ParameterValue::Int8(v) => Ok(v),
- ParameterValue::Int16(v) => Ok(v),
- ParameterValue::Floating32(v) => Ok(v),
- ParameterValue::Floating64(v) => Ok(v),
- ParameterValue::Uint8(_)
- | ParameterValue::Uint16(_)
- | ParameterValue::Uint32(_)
- | ParameterValue::Uint64(_) => Err(anyhow!("Postgres does not support unsigned integers")),
- ParameterValue::Str(v) => Ok(v),
- ParameterValue::Binary(v) => Ok(v),
- ParameterValue::DbNull => Ok(&PgNull),
- }
-}
-
-fn infer_columns(row: &Row) -> Vec<Column> {
- let mut result = Vec::with_capacity(row.len());
- for index in 0..row.len() {
- result.push(infer_column(row, index));
- }
- result
-}
-
-fn infer_column(row: &Row, index: usize) -> Column {
- let column = &row.columns()[index];
- let name = column.name().to_owned();
- let data_type = convert_data_type(column.type_());
- Column { name, data_type }
-}
-
-fn convert_data_type(pg_type: &Type) -> DbDataType {
- match *pg_type {
- Type::BOOL => DbDataType::Boolean,
- Type::BYTEA => DbDataType::Binary,
- Type::FLOAT4 => DbDataType::Floating32,
- Type::FLOAT8 => DbDataType::Floating64,
- Type::INT2 => DbDataType::Int16,
- Type::INT4 => DbDataType::Int32,
- Type::INT8 => DbDataType::Int64,
- Type::TEXT | Type::VARCHAR | Type::BPCHAR => DbDataType::Str,
- _ => {
- tracing::debug!("Couldn't convert Postgres type {} to WIT", pg_type.name(),);
- DbDataType::Other
- }
- }
-}
-
-fn convert_row(row: &Row) -> Result<Vec<DbValue>, tokio_postgres::Error> {
- let mut result = Vec::with_capacity(row.len());
- for index in 0..row.len() {
- result.push(convert_entry(row, index)?);
- }
- Ok(result)
-}
-
-fn convert_entry(row: &Row, index: usize) -> Result<DbValue, tokio_postgres::Error> {
- let column = &row.columns()[index];
- let value = match column.type_() {
- &Type::BOOL => {
- let value: Option<bool> = row.try_get(index)?;
- match value {
- Some(v) => DbValue::Boolean(v),
- None => DbValue::DbNull,
- }
- }
- &Type::BYTEA => {
- let value: Option<Vec<u8>> = row.try_get(index)?;
- match value {
- Some(v) => DbValue::Binary(v),
- None => DbValue::DbNull,
- }
- }
- &Type::FLOAT4 => {
- let value: Option<f32> = row.try_get(index)?;
- match value {
- Some(v) => DbValue::Floating32(v),
- None => DbValue::DbNull,
- }
- }
- &Type::FLOAT8 => {
- let value: Option<f64> = row.try_get(index)?;
- match value {
- Some(v) => DbValue::Floating64(v),
- None => DbValue::DbNull,
- }
- }
- &Type::INT2 => {
- let value: Option<i16> = row.try_get(index)?;
- match value {
- Some(v) => DbValue::Int16(v),
- None => DbValue::DbNull,
- }
- }
- &Type::INT4 => {
- let value: Option<i32> = row.try_get(index)?;
- match value {
- Some(v) => DbValue::Int32(v),
- None => DbValue::DbNull,
- }
- }
- &Type::INT8 => {
- let value: Option<i64> = row.try_get(index)?;
- match value {
- Some(v) => DbValue::Int64(v),
- None => DbValue::DbNull,
- }
- }
- &Type::TEXT | &Type::VARCHAR | &Type::BPCHAR => {
- let value: Option<String> = row.try_get(index)?;
- match value {
- Some(v) => DbValue::Str(v),
- None => DbValue::DbNull,
- }
- }
- t => {
- tracing::debug!(
- "Couldn't convert Postgres type {} in column {}",
- t.name(),
- column.name()
- );
- DbValue::Unsupported
- }
- };
- Ok(value)
-}
-
-async fn build_client(address: &str) -> anyhow::Result<Client> {
- let config = address.parse::<tokio_postgres::Config>()?;
-
- tracing::debug!("Build new connection: {}", address);
-
- if config.get_ssl_mode() == SslMode::Disable {
- connect(config).await
- } else {
- connect_tls(config).await
- }
-}
-
-async fn connect(config: tokio_postgres::Config) -> anyhow::Result<Client> {
- let (client, connection) = config.connect(NoTls).await?;
-
- spawn(connection);
-
- Ok(client)
-}
-
-async fn connect_tls(config: tokio_postgres::Config) -> anyhow::Result<Client> {
- let builder = TlsConnector::builder();
- let connector = MakeTlsConnector::new(builder.build()?);
- let (client, connection) = config.connect(connector).await?;
-
- spawn(connection);
-
- Ok(client)
-}
-
-fn spawn<T>(connection: tokio_postgres::Connection<Socket, T>)
-where
- T: tokio_postgres::tls::TlsStream + std::marker::Unpin + std::marker::Send + 'static,
-{
- tokio::spawn(async move {
- if let Err(e) = connection.await {
- tracing::error!("Postgres connection error: {}", e);
- }
- });
-}
-
-/// Although the Postgres crate converts Rust Option::None to Postgres NULL,
-/// it enforces the type of the Option as it does so. (For example, trying to
-/// pass an Option::<i32>::None to a VARCHAR column fails conversion.) As we
-/// do not know expected column types, we instead use a "neutral" custom type
-/// which allows conversion to any type but always tells the Postgres crate to
-/// treat it as a SQL NULL.
-struct PgNull;
-
-impl ToSql for PgNull {
- fn to_sql(
- &self,
- _ty: &Type,
- _out: &mut tokio_postgres::types::private::BytesMut,
- ) -> Result<tokio_postgres::types::IsNull, Box<dyn std::error::Error + Sync + Send>>
- where
- Self: Sized,
- {
- Ok(tokio_postgres::types::IsNull::Yes)
- }
-
- fn accepts(_ty: &Type) -> bool
- where
- Self: Sized,
- {
- true
- }
-
- fn to_sql_checked(
- &self,
- _ty: &Type,
- _out: &mut tokio_postgres::types::private::BytesMut,
- ) -> Result<tokio_postgres::types::IsNull, Box<dyn std::error::Error + Sync + Send>> {
- Ok(tokio_postgres::types::IsNull::Yes)
- }
-}
-
-impl std::fmt::Debug for PgNull {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- f.debug_struct("NULL").finish()
- }
-}
-
/// Delegate a function call to the v2::HostConnection implementation
macro_rules! delegate {
($self:ident.$name:ident($address:expr, $($arg:expr),*)) => {{
@@ -388,7 +136,7 @@ macro_rules! delegate {
}
#[async_trait]
-impl v1::Host for InstanceState {
+impl<C: Send + Sync + Client> v1::Host for InstanceState<C> {
async fn execute(
&mut self,
address: String,
diff --git a/crates/factor-outbound-pg/src/lib.rs b/crates/factor-outbound-pg/src/lib.rs
index 1436669321..484cc68c3a 100644
--- a/crates/factor-outbound-pg/src/lib.rs
+++ b/crates/factor-outbound-pg/src/lib.rs
@@ -1,18 +1,22 @@
+pub mod client;
mod host;
+use client::Client;
use spin_factor_outbound_networking::{OutboundAllowedHosts, OutboundNetworkingFactor};
use spin_factors::{
anyhow, ConfigureAppContext, Factor, InstanceBuilders, PrepareContext, RuntimeFactors,
SelfInstanceBuilder,
};
-use tokio_postgres::Client;
+use tokio_postgres::Client as PgClient;
-pub struct OutboundPgFactor;
+pub struct OutboundPgFactor<C = PgClient> {
+ _phantom: std::marker::PhantomData<C>,
+}
-impl Factor for OutboundPgFactor {
+impl<C: Send + Sync + Client + 'static> Factor for OutboundPgFactor<C> {
type RuntimeConfig = ();
type AppState = ();
- type InstanceBuilder = InstanceState;
+ type InstanceBuilder = InstanceState<C>;
fn init<T: RuntimeFactors>(
&mut self,
@@ -45,9 +49,23 @@ impl Factor for OutboundPgFactor {
}
}
-pub struct InstanceState {
+impl<C> Default for OutboundPgFactor<C> {
+ fn default() -> Self {
+ Self {
+ _phantom: Default::default(),
+ }
+ }
+}
+
+impl<C> OutboundPgFactor<C> {
+ pub fn new() -> Self {
+ Self::default()
+ }
+}
+
+pub struct InstanceState<C> {
allowed_hosts: OutboundAllowedHosts,
- connections: table::Table<Client>,
+ connections: table::Table<C>,
}
-impl SelfInstanceBuilder for InstanceState {}
+impl<C: Send + 'static> SelfInstanceBuilder for InstanceState<C> {}
| 2,651
|
[
"2649"
] |
diff --git a/crates/factor-outbound-pg/tests/factor_test.rs b/crates/factor-outbound-pg/tests/factor_test.rs
index 4f2f788521..07f47cc0c0 100644
--- a/crates/factor-outbound-pg/tests/factor_test.rs
+++ b/crates/factor-outbound-pg/tests/factor_test.rs
@@ -1,39 +1,48 @@
-use anyhow::bail;
+use anyhow::{bail, Result};
use spin_factor_outbound_networking::OutboundNetworkingFactor;
+use spin_factor_outbound_pg::client::Client;
use spin_factor_outbound_pg::OutboundPgFactor;
use spin_factor_variables::{StaticVariables, VariablesFactor};
-use spin_factor_wasi::{DummyFilesMounter, WasiFactor};
use spin_factors::{anyhow, RuntimeFactors};
use spin_factors_test::{toml, TestEnvironment};
+use spin_world::async_trait;
use spin_world::v2::postgres::HostConnection;
+use spin_world::v2::postgres::{self as v2};
use spin_world::v2::rdbms_types::Error as PgError;
+use spin_world::v2::rdbms_types::{ParameterValue, RowSet};
#[derive(RuntimeFactors)]
struct TestFactors {
- wasi: WasiFactor,
variables: VariablesFactor,
networking: OutboundNetworkingFactor,
- pg: OutboundPgFactor,
+ pg: OutboundPgFactor<MockClient>,
+}
+
+fn factors() -> Result<TestFactors> {
+ let mut f = TestFactors {
+ variables: VariablesFactor::default(),
+ networking: OutboundNetworkingFactor,
+ pg: OutboundPgFactor::<MockClient>::new(),
+ };
+ f.variables.add_provider_type(StaticVariables)?;
+ Ok(f)
}
fn test_env() -> TestEnvironment {
TestEnvironment::default_manifest_extend(toml! {
[component.test-component]
source = "does-not-exist.wasm"
+ allowed_outbound_hosts = ["postgres://*:*"]
})
}
#[tokio::test]
async fn disallowed_host_fails() -> anyhow::Result<()> {
- let mut factors = TestFactors {
- wasi: WasiFactor::new(DummyFilesMounter),
- variables: VariablesFactor::default(),
- networking: OutboundNetworkingFactor,
- pg: OutboundPgFactor,
- };
- factors.variables.add_provider_type(StaticVariables)?;
-
- let env = test_env();
+ let factors = factors()?;
+ let env = TestEnvironment::default_manifest_extend(toml! {
+ [component.test-component]
+ source = "does-not-exist.wasm"
+ });
let mut state = env.build_instance_state(factors).await?;
let res = state
@@ -43,8 +52,94 @@ async fn disallowed_host_fails() -> anyhow::Result<()> {
let Err(err) = res else {
bail!("expected Err, got Ok");
};
- println!("err: {:?}", err);
assert!(matches!(err, PgError::ConnectionFailed(_)));
Ok(())
}
+
+#[tokio::test]
+async fn allowed_host_succeeds() -> anyhow::Result<()> {
+ let factors = factors()?;
+ let env = test_env();
+ let mut state = env.build_instance_state(factors).await?;
+
+ let res = state
+ .pg
+ .open("postgres://localhost:5432/test".to_string())
+ .await;
+ let Ok(_) = res else {
+ bail!("expected Ok, got Err");
+ };
+
+ Ok(())
+}
+
+#[tokio::test]
+async fn exercise_execute() -> anyhow::Result<()> {
+ let factors = factors()?;
+ let env = test_env();
+ let mut state = env.build_instance_state(factors).await?;
+
+ let connection = state
+ .pg
+ .open("postgres://localhost:5432/test".to_string())
+ .await?;
+
+ state
+ .pg
+ .execute(connection, "SELECT * FROM test".to_string(), vec![])
+ .await?;
+
+ Ok(())
+}
+
+#[tokio::test]
+async fn exercise_query() -> anyhow::Result<()> {
+ let factors = factors()?;
+ let env = test_env();
+ let mut state = env.build_instance_state(factors).await?;
+
+ let connection = state
+ .pg
+ .open("postgres://localhost:5432/test".to_string())
+ .await?;
+
+ state
+ .pg
+ .query(connection, "SELECT * FROM test".to_string(), vec![])
+ .await?;
+
+ Ok(())
+}
+
+// TODO: We can expand this mock to track calls and simulate return values
+pub struct MockClient {}
+
+#[async_trait]
+impl Client for MockClient {
+ async fn build_client(_address: &str) -> anyhow::Result<Self>
+ where
+ Self: Sized,
+ {
+ Ok(MockClient {})
+ }
+
+ async fn execute(
+ &self,
+ _statement: String,
+ _params: Vec<ParameterValue>,
+ ) -> Result<u64, v2::Error> {
+ Ok(0)
+ }
+
+ async fn query(
+ &self,
+ _statement: String,
+ _params: Vec<ParameterValue>,
+ ) -> Result<RowSet, v2::Error> {
+ Ok(RowSet {
+ columns: vec![],
+ rows: vec![],
+ })
+ }
+}
|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
|
aedc2b8ccc65f41615fa7beb3e427843dd782114
|
Support overriding the "Spin data dir" via env var
The Spin "data dir" (e.g. `~/.local/share`) is used as the root for plugin and template state. We have a request (part of #2555) to make this customizable to aid integration with other development tooling.
The data dir is constructed here: https://github.com/fermyon/spin/blob/aedc2b8ccc65f41615fa7beb3e427843dd782114/crates/common/src/data_dir.rs#L7
As suggested in the linked discussion, we could add support for an environment variable to override this algorithm. Bike-shedding on the name of that variable, I suggest `SPIN_DATA_DIR`.
In addition to adding this support, a bit of related clean-up would be nice:
- Replace [`TEST_PLUGINS_DIRECTORY`](https://github.com/fermyon/spin/blob/8534cbec177b881d1f9ae4e4008a1f8e1c712cb3/crates/plugins/src/store.rs#L28) with this new env var
- Maybe rename `default_data_dir` to...`spin_data_dir` (?); there isn't anything really "default" about it, especially with the removal of `TEST_PLUGINS_DIRECTORY`
Separately, should we do the same for "cache" (used by badger, OCI) and "config" (OCI registry auth) dirs?
cc @jandubois, @itowlson
|
2024-06-17T03:01:45Z
|
fermyon__spin-2568
|
fermyon/spin
|
3.2
|
diff --git a/crates/common/src/data_dir.rs b/crates/common/src/data_dir.rs
index 1d6fc8a496..e5f1a05349 100644
--- a/crates/common/src/data_dir.rs
+++ b/crates/common/src/data_dir.rs
@@ -4,7 +4,10 @@ use anyhow::{anyhow, Result};
use std::path::{Path, PathBuf};
/// Return the default data directory for Spin
-pub fn default_data_dir() -> Result<PathBuf> {
+pub fn data_dir() -> Result<PathBuf> {
+ if let Ok(data_dir) = std::env::var("SPIN_DATA_DIR") {
+ return Ok(PathBuf::from(data_dir));
+ }
if let Some(pkg_mgr_dir) = package_manager_data_dir() {
return Ok(pkg_mgr_dir);
}
diff --git a/crates/plugins/src/store.rs b/crates/plugins/src/store.rs
index fb924c2382..0e84aeb2dd 100644
--- a/crates/plugins/src/store.rs
+++ b/crates/plugins/src/store.rs
@@ -1,6 +1,6 @@
use anyhow::{Context, Result};
use flate2::read::GzDecoder;
-use spin_common::data_dir::default_data_dir;
+use spin_common::data_dir::data_dir;
use std::{
ffi::OsStr,
fs::{self, File},
@@ -25,12 +25,7 @@ impl PluginStore {
}
pub fn try_default() -> Result<Self> {
- let data_dir = if let Ok(test_dir) = std::env::var("TEST_PLUGINS_DIRECTORY") {
- PathBuf::from(test_dir).join("spin")
- } else {
- default_data_dir()?
- };
- Ok(Self::new(data_dir.join("plugins")))
+ Ok(Self::new(data_dir()?.join("plugins")))
}
/// Gets the path to where Spin plugin are installed.
diff --git a/crates/templates/src/store.rs b/crates/templates/src/store.rs
index b484af30b2..0a70aa9673 100644
--- a/crates/templates/src/store.rs
+++ b/crates/templates/src/store.rs
@@ -1,5 +1,5 @@
use anyhow::Context;
-use spin_common::data_dir::default_data_dir;
+use spin_common::data_dir::data_dir;
use std::path::{Path, PathBuf};
use crate::directory::subdirectories;
@@ -20,7 +20,7 @@ impl TemplateStore {
}
pub(crate) fn try_default() -> anyhow::Result<Self> {
- Ok(Self::new(default_data_dir()?.join("templates")))
+ Ok(Self::new(data_dir()?.join("templates")))
}
pub(crate) fn get_directory(&self, id: impl AsRef<str>) -> PathBuf {
| 2,568
|
[
"2563"
] |
diff --git a/tests/integration.rs b/tests/integration.rs
index f0841cab35..210a8440ae 100644
--- a/tests/integration.rs
+++ b/tests/integration.rs
@@ -903,7 +903,7 @@ route = "/..."
"--yes",
])
// Ensure that spin installs the plugins into the temporary directory
- .env("TEST_PLUGINS_DIRECTORY", "./plugins");
+ .env("SPIN_DATA_DIR", "./plugins");
env.run_in(&mut install)?;
/// Make sure that the plugin is uninstalled after the test
@@ -927,13 +927,11 @@ route = "/..."
"--yes",
])
// Ensure that spin installs the plugins into the temporary directory
- .env("TEST_PLUGINS_DIRECTORY", "./plugins");
+ .env("SPIN_DATA_DIR", "./plugins");
env.run_in(&mut install)?;
let mut execute = std::process::Command::new(spin_binary());
- execute
- .args(["example"])
- .env("TEST_PLUGINS_DIRECTORY", "./plugins");
+ execute.args(["example"]).env("SPIN_DATA_DIR", "./plugins");
let output = env.run_in(&mut execute)?;
// Verify plugin successfully wrote to output file
@@ -957,12 +955,11 @@ route = "/..."
"example-plugin-manifest.json",
"--yes",
])
- .env("TEST_PLUGINS_DIRECTORY", "./plugins");
+ .env("SPIN_DATA_DIR", "./plugins");
env.run_in(&mut upgrade)?;
// Check plugin version
let installed_manifest = std::path::PathBuf::from("plugins")
- .join("spin")
.join("plugins")
.join("manifests")
.join("example.json");
@@ -984,7 +981,7 @@ route = "/..."
login
.args(["login", "--help"])
// Ensure that spin installs the plugins into the temporary directory
- .env("TEST_PLUGINS_DIRECTORY", "./plugins");
+ .env("SPIN_DATA_DIR", "./plugins");
let output = env.run_in(&mut login)?;
// Verify plugin successfully wrote to output file
@@ -1361,7 +1358,7 @@ route = "/..."
// Create a test plugin store so we don't modify the user's real one.
let plugin_store_dir = Path::new(concat!(env!("OUT_DIR"), "/plugin-store"));
- let plugins_dir = plugin_store_dir.join("spin/plugins");
+ let plugins_dir = plugin_store_dir.join("plugins");
let plugin_dir = plugins_dir.join("trigger-timer");
fs::create_dir_all(&plugin_dir)?;
@@ -1388,7 +1385,7 @@ route = "/..."
&format!("{TIMER_TRIGGER_INTEGRATION_TEST}/spin.toml"),
"--test",
])
- .env("TEST_PLUGINS_DIRECTORY", plugin_store_dir)
+ .env("SPIN_DATA_DIR", plugin_store_dir)
.output()?;
assert!(
out.status.success(),
|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
|
4f63686c1ce2432306279b11deb28bb183e2eb50
|
"Unknown lint: `clippy::blocks_in_conditions`" warning when clippying Spin source
The `clippy::blocks_in_conditions` lint causes an "unknown lint" warning on Rust 1.75. Looking at the linked issue it was maybe introduced in 1.76? The MSRV of Spin is 1.74. Are we happy to rev that to 1.76, or are we okay to ignore the warnings (since the only reason we mention the lint is a bug that will hopefully get fixed soon)?
|
> since the only reason we mention the lint is a bug that will hopefully get fixed soon
@itowlson can you link to the bug? Or not yet tracked? At first take, I'd be inclined to keep Spin at 1.74 and fix the bug.
@vdice https://github.com/rust-lang/rust-clippy/issues/12281 (ref: https://github.com/fermyon/spin/blob/ae1d3e6193d1c54ed55fbd9cb0c0da6a1399599e/Cargo.toml#L138)
I think ignoring the warning is appropriate. I have updated this issue's title to be slightly more discoverable if someone else is annoyed by the warning.
|
2024-05-06T22:38:55Z
|
fermyon__spin-2491
|
fermyon/spin
|
3.2
|
diff --git a/.cargo/config b/.cargo/config.toml
similarity index 100%
rename from .cargo/config
rename to .cargo/config.toml
diff --git a/crates/http/src/wagi/mod.rs b/crates/http/src/wagi/mod.rs
index bbb021dc93..6f93971767 100644
--- a/crates/http/src/wagi/mod.rs
+++ b/crates/http/src/wagi/mod.rs
@@ -184,13 +184,13 @@ fn parse_host_header_uri(
let mut parse_host = |hdr: String| {
let mut parts = hdr.splitn(2, ':');
match parts.next() {
- Some(h) if !h.is_empty() => host = h.to_owned(),
+ Some(h) if !h.is_empty() => h.clone_into(&mut host),
_ => {}
}
match parts.next() {
Some(p) if !p.is_empty() => {
tracing::debug!(port = p, "Overriding port");
- port = p.to_owned()
+ p.clone_into(&mut port);
}
_ => {}
}
diff --git a/crates/manifest/src/normalize.rs b/crates/manifest/src/normalize.rs
index 6955db15c7..2182c95515 100644
--- a/crates/manifest/src/normalize.rs
+++ b/crates/manifest/src/normalize.rs
@@ -86,7 +86,7 @@ fn normalize_trigger_ids(manifest: &mut AppManifest) {
if let Some(ComponentSpec::Reference(component_id)) = &trigger.component {
let candidate_id = format!("{component_id}-{trigger_type}-trigger");
if !trigger_ids.contains(&candidate_id) {
- trigger.id = candidate_id.clone();
+ trigger.id.clone_from(&candidate_id);
trigger_ids.insert(candidate_id);
continue;
}
diff --git a/crates/oci/src/auth.rs b/crates/oci/src/auth.rs
index 6a1a782eb9..82b28525a1 100644
--- a/crates/oci/src/auth.rs
+++ b/crates/oci/src/auth.rs
@@ -60,7 +60,7 @@ impl AuthConfig {
/// Get the registry authentication for a given registry from the default location.
pub async fn get_auth_from_default(server: impl AsRef<str>) -> Result<RegistryAuth> {
let auths = Self::load_default().await?;
- let encoded = match auths.auths.get(&server.as_ref().to_string()) {
+ let encoded = match auths.auths.get(server.as_ref()) {
Some(e) => e,
None => bail!(format!("no credentials stored for {}", server.as_ref())),
};
diff --git a/crates/trigger-http/src/handler.rs b/crates/trigger-http/src/handler.rs
index bd72e0e451..6287c05ac2 100644
--- a/crates/trigger-http/src/handler.rs
+++ b/crates/trigger-http/src/handler.rs
@@ -378,7 +378,7 @@ fn set_http_origin_from_request(
.host_components_data()
.get_or_insert(outbound_http_handle);
- outbound_http_data.origin = origin.clone();
+ outbound_http_data.origin.clone_from(&origin);
store.as_mut().data_mut().as_mut().allowed_hosts =
outbound_http_data.allowed_hosts.clone();
}
diff --git a/crates/trigger-http/src/lib.rs b/crates/trigger-http/src/lib.rs
index 743866887e..8a8bf90d72 100644
--- a/crates/trigger-http/src/lib.rs
+++ b/crates/trigger-http/src/lib.rs
@@ -662,7 +662,10 @@ impl OutboundWasiHttpHandler for HttpRuntimeData {
.map(|s| s == &Scheme::HTTPS)
.unwrap_or_default();
// We know that `uri` has an authority because we set it above
- request.authority = uri.authority().unwrap().as_str().to_owned();
+ uri.authority()
+ .unwrap()
+ .as_str()
+ .clone_into(&mut request.authority);
*request.request.uri_mut() = uri;
}
diff --git a/crates/trigger/src/runtime_config/llm.rs b/crates/trigger/src/runtime_config/llm.rs
index af5f2a3629..d9cf8dc159 100644
--- a/crates/trigger/src/runtime_config/llm.rs
+++ b/crates/trigger/src/runtime_config/llm.rs
@@ -1,7 +1,4 @@
-use async_trait::async_trait;
-use spin_llm::LlmEngine;
use spin_llm_remote_http::RemoteHttpLlmEngine;
-use spin_world::v2::llm as wasi_llm;
use url::Url;
#[derive(Default)]
@@ -26,7 +23,7 @@ pub(crate) async fn build_component(
#[cfg(not(feature = "llm"))]
LlmComputeOpts::Spin => {
let _ = use_gpu;
- spin_llm::LlmComponent::new(move || Box::new(NoopLlmEngine.clone()))
+ spin_llm::LlmComponent::new(move || Box::new(noop::NoopLlmEngine.clone()))
}
LlmComputeOpts::RemoteHttp(config) => {
tracing::log::info!("Using remote compute for LLMs");
@@ -50,29 +47,36 @@ pub struct RemoteHttpComputeOpts {
auth_token: String,
}
-#[derive(Clone)]
-struct NoopLlmEngine;
+#[cfg(not(feature = "llm"))]
+mod noop {
+ use async_trait::async_trait;
+ use spin_llm::LlmEngine;
+ use spin_world::v2::llm as wasi_llm;
-#[async_trait]
-impl LlmEngine for NoopLlmEngine {
- async fn infer(
- &mut self,
- _model: wasi_llm::InferencingModel,
- _prompt: String,
- _params: wasi_llm::InferencingParams,
- ) -> Result<wasi_llm::InferencingResult, wasi_llm::Error> {
- Err(wasi_llm::Error::RuntimeError(
- "Local LLM operations are not supported in this version of Spin.".into(),
- ))
- }
+ #[derive(Clone)]
+ pub(super) struct NoopLlmEngine;
+
+ #[async_trait]
+ impl LlmEngine for NoopLlmEngine {
+ async fn infer(
+ &mut self,
+ _model: wasi_llm::InferencingModel,
+ _prompt: String,
+ _params: wasi_llm::InferencingParams,
+ ) -> Result<wasi_llm::InferencingResult, wasi_llm::Error> {
+ Err(wasi_llm::Error::RuntimeError(
+ "Local LLM operations are not supported in this version of Spin.".into(),
+ ))
+ }
- async fn generate_embeddings(
- &mut self,
- _model: wasi_llm::EmbeddingModel,
- _data: Vec<String>,
- ) -> Result<wasi_llm::EmbeddingsResult, wasi_llm::Error> {
- Err(wasi_llm::Error::RuntimeError(
- "Local LLM operations are not supported in this version of Spin.".into(),
- ))
+ async fn generate_embeddings(
+ &mut self,
+ _model: wasi_llm::EmbeddingModel,
+ _data: Vec<String>,
+ ) -> Result<wasi_llm::EmbeddingsResult, wasi_llm::Error> {
+ Err(wasi_llm::Error::RuntimeError(
+ "Local LLM operations are not supported in this version of Spin.".into(),
+ ))
+ }
}
}
| 2,491
|
[
"2424"
] |
diff --git a/tests/testcases/mod.rs b/tests/testcases/mod.rs
index 4ebd2338bb..12eae3c469 100644
--- a/tests/testcases/mod.rs
+++ b/tests/testcases/mod.rs
@@ -345,11 +345,11 @@ pub fn bootstrap_smoke_test(
let mut custom_path = value.to_owned();
if value.starts_with('.') {
let current_dir = env.path();
- custom_path = current_dir
+ current_dir
.join(value)
.to_str()
.unwrap_or_default()
- .to_owned();
+ .clone_into(&mut custom_path);
}
build.env(key, format!("{}:{}", custom_path, path));
} else {
|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
72cc02514e3506ddda357d03d2d060d8ad08f2b1
|
Allow for more granular route matching in Spin
Currently, the route matching in spin can be of two forms
```toml
# match a single route
route = "/{path}"
# match any route with the prefix
route = "/{path-prefix}/..."
```
It would be helpful in certain cases if the route matching allowed more granularity. For an example consider the case of a Bartholomew app with a proxy component.
```toml
[[component]]
id = "bartholomew"
[component.trigger]
route = "/..."
[[component]]
id = "proxy"
[component.trigger]
route = "/spin/*"
```
With such a configuration, the `proxy` component would match the route `/spin/index` but not `/spin/v1/index`. Thus allowing the `proxy` to handle one specific subset of the routes while `bartholomew` handles the rest.
There is potential for another level of granularity where we could define something like
```toml
route = "/spin/*/test"
```
Which would only match `/spin/index/test` but not `/spin/index/something-else`
Thoughts?
|
I'm not necessarily opposed to this but just want to note that V2 manifests help with a workaround in some (not all!) situations:
```toml
[[trigger.http]]
route = "/..."
component = "bartholomew"
[[trigger.http]]
route = "/spin/..."
component = "proxy"
[[trigger.http]]
route = "/spin/v1/..."
component = "bartholomew"
```
@lann that works in that specific case but if someone adds a `/spin/v2` as well, then we would need to add another definition in the manifest. So I would imagine it would not scale very well.
@lann one other practical issue is that it increases the memory usage since the extra component mounts end up creating their own copy of the static files
With v2 manifests that shouldn't happen if you point two triggers at one component. If mounts are duplicated in that case it's a bug.
Oh ok - I was testing with just `v1` and spin `v1.5.1`. I was creating multiple components, so that makes sense.
@karthik2804 did Spin v2 and the v2 manifest help here? I'm assuming we'd still like this issue to track nested wildcard route support (eg `route = "/spin/*/test"` mentioned above)?
Do we have a good sense of what we want from this feature? It seems like the ask is specifically for a kind of "single level" wildcard, i.e. like `/...` except only up to the next `/` (if there is one). Is that the full extent of it?
Some challenges I see here are:
* Do we need to surface the "matched" segment(s) in the same way we surface `/...` tails via `spin-path-info`?
* How does the "longest match" rule translate e.g. if I have `/a/b/*/d` and `/a/*/c/d` then which one should handle `/a/b/c/d`?
Any other design considerations?
The use case I have had requires only a single level of wildcard but based on @lann's workaround above, it could be done by adding multiple triggers.
- I would expect the `spin-path-info` to be exposed as it is today. I am not sure I follow the question about "matched" segments.
- I do not have a solid answer for the longest match rule translation.
@karthik2804 Sorry I maybe confused the question by giving the `spin-path-info` analogy - it was intended only as analogy. Let me rephrase:
Suppose I have a trigger `/a/*/b`. Suppose a request matches that trigger, and my component runs. My component wants to know what the `*` was. (For example, if the user visited `/a/gorilla/b`, I want the `gorilla` part.) How does it get it?
(Potentially nastier is the multiple case of `/user/*/note/*`. Now from `/user/itowlson/note/4067` my component wants to know that the wildcards were `itowlson` _and_ `4067`.)
@karthik2804 Is your comment about the multiple trigger workaround suggesting that this is no longer important (at least to you) and could be dropped from the 2.1 list? I am not sure if we have any other users asking after this yet.
@itowlson, it was in reference to the following
> It seems like the ask is specifically for a kind of "single level" wildcard, i.e. like /... except only up to the next / (if there is one). Is that the full extent of it?
The workaround above solves the issue I ran into (I have yet to test).
On the sharing multiple matched segments, ~~could add a new header `spin-matched-segments: "itowlson,4067"` where the segments are separated by commas.~~ URL paths can contains commas.
I chatted with Karthik offline and some alternative ideas for capturing `*` values could be:
* A CSV / multi-instance header, with commas in values encoded if present (which should be rare).
* Allow/require names for wildcards e.g. `/user/*username/note/*noteid` giving rise to separate `spin-something-username` and `spin-something-noteid` headers.
> * Allow/require names for wildcards e.g. `/user/*username/note/*noteid` giving rise to separate `spin-something-username` and `spin-something-noteid` headers.
FYI: From a customer perspective, this would be a really useful feature to have - personally, I would vote for named wildcards, but I'd be happy with any workable solution for enabling more powerful wildcard paths 😁
Regular Expressions are The Swiss Army Knife of Text Processing.
Flexible routing structure can give me more flexible / micro-sized modularization which I can split my app into more smaller wasms. Isn't that the recommended direction for wasm architecturing?
Given that https://github.com/fermyon/spin/pull/2305 is nearing completion, one thing I'd like to explore is using that service chaining feature to enable advanced routing scenarios via a routing component, especially for something like regular expressions which may not be appropriate for all users.
I started exploring this and I am getting very hung up on potential ambiguities. For example, if the app has routes `/a/*/c` and `/a/b/...`, which one does `/a/b/c` match? I started going with a "longest initial exact segment takes precedence" rule, which runs into tiebreaking problems, but those are fixable. But then I started thinking "exact trailing segment should trump wildcard trailing segment".
And then I started thinking "what if we just reject applications with this kind of ambiguous overlap", requiring any pair of routes to be either disjoint or in a subset relationship. Because if you have `/a/*/c` and `/a/b/...` then you probably have problems that you need to address _before_ the ambiguous request comes in. And this seems like a reaonable rule if it's easy to implement, but I bet it will turn out to be equivalent to the halting problem because everything always does. And it leaves people who really want to express `a / anything-but-b / c` stuffed unless we extend the pattern language further (hello regular expressions, hello unbounded evaluation times).
Another possibility, which lines up with some programmatic routers, is to make it order-dependent: first (or last) match wins. Pre-1.0 Spin had that rule, and we replaced it with longest match because it provides more reliability as manifests change (e.g. triggers getting tacked on the end via `spin add`). We _could_ bring that back for the specific case of "best match is not well defined" but I'm really reluctant to do that because who knows what well-defined means in this case.
Finally, the original issue asked for single-segment match only in a trailing position, e.g. a `*` suffix to go alongside the `...` one. That avoids any ambiguity, but falls short of what others in the thread have been talking about.
I feel like I'm overthinking this because lots of routers _just do this stuff_, so, save me from myself folks: how should this behave?
Could we lean into routefinder here? If we introduce named parameters (e.g. `:planet`) it seems like we could establish a mapping to the syntax supported by routefinder (e.g. `/...` => `/*`). This would appear to cover the usecases above.
Also, I'm not a big fan of supporting `...` and `*`; historically I've seen them both used to mean "wildcard" and dread the confusion to inevitably plague our route dx.
The question then is how do we surface named captures to a guest? Immediately I'm not opposed to propagating captures as `spin-route-param` headers (or something of the sort) as mentioned earlier.
The major benefit of creating an isomorphism to routerfinder (or similar syntax) is that we can take advantage of the ranking and ordering of routes to handle all the ambiguities mentioned.
I like `routefinder`'s precedence rules and am similarly wary of using `*` since its meaning varies so much (any single segment vs any number of segments vs any number of _trailing_ segments).
I'd be fine with e.g. `/:param/...` (disallowing `*` as an input) as the next step here. Given that we already have a bunch of magic `spin-*` headers I suppose something like `spin-param-<param>` is probably _fine_.
Yeah sorry `*` was not a syntax proposal it was a way of expressing the ambiguity. The ambiguity, not the syntax, is the problem.
I will look at routefinder precedence: thanks.
|
2024-04-22T03:53:13Z
|
fermyon__spin-2464
|
fermyon/spin
|
3.2
|
diff --git a/Cargo.lock b/Cargo.lock
index 3242c114aa..d8b01f0cf2 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2901,7 +2901,7 @@ dependencies = [
"httpdate",
"itoa",
"pin-project-lite",
- "socket2 0.4.10",
+ "socket2 0.5.6",
"tokio",
"tower-service",
"tracing",
@@ -5434,6 +5434,16 @@ version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3582f63211428f83597b51b2ddb88e2a91a9d52d12831f9d08f5e624e8977422"
+[[package]]
+name = "routefinder"
+version = "0.5.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0971d3c8943a6267d6bd0d782fdc4afa7593e7381a92a3df950ff58897e066b5"
+dependencies = [
+ "smartcow",
+ "smartstring",
+]
+
[[package]]
name = "rpassword"
version = "7.3.1"
@@ -6028,6 +6038,26 @@ version = "1.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67"
+[[package]]
+name = "smartcow"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "656fcb1c1fca8c4655372134ce87d8afdf5ec5949ebabe8d314be0141d8b5da2"
+dependencies = [
+ "smartstring",
+]
+
+[[package]]
+name = "smartstring"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3fb72c633efbaa2dd666986505016c32c3044395ceaf881518399d2f4127ee29"
+dependencies = [
+ "autocfg",
+ "static_assertions",
+ "version_check",
+]
+
[[package]]
name = "snapbox"
version = "0.4.17"
@@ -6314,6 +6344,7 @@ dependencies = [
"hyper 1.2.0",
"indexmap 1.9.3",
"percent-encoding",
+ "routefinder",
"serde",
"spin-app",
"spin-locked-app",
diff --git a/crates/http/Cargo.toml b/crates/http/Cargo.toml
index 1a32565617..fc30406e59 100644
--- a/crates/http/Cargo.toml
+++ b/crates/http/Cargo.toml
@@ -12,6 +12,7 @@ http-body-util = { workspace = true }
wasmtime-wasi-http = { workspace = true, optional = true }
indexmap = "1"
percent-encoding = "2"
+routefinder = "0.5.4"
serde = { version = "1.0", features = ["derive"] }
tracing = { workspace = true }
spin-app = { path = "../app", optional = true }
diff --git a/crates/http/src/routes.rs b/crates/http/src/routes.rs
index 52eb5f0c1e..e7d43e4127 100644
--- a/crates/http/src/routes.rs
+++ b/crates/http/src/routes.rs
@@ -3,24 +3,38 @@
#![deny(missing_docs)]
use anyhow::{anyhow, Result};
-use http::Uri;
use indexmap::IndexMap;
-use std::{borrow::Cow, fmt};
+use std::{collections::HashMap, fmt};
use crate::config::HttpTriggerRouteConfig;
/// Router for the HTTP trigger.
#[derive(Clone, Debug)]
pub struct Router {
- /// Ordered map between a path and the component ID that should handle it.
- pub(crate) routes: IndexMap<RoutePattern, String>,
+ /// Resolves paths to routing information - specifically component IDs
+ /// but also recording about the original route.
+ router: std::sync::Arc<routefinder::Router<RouteHandler>>,
+}
+
+/// What a route maps to
+#[derive(Clone, Debug)]
+struct RouteHandler {
+ /// The component ID that the route maps to.
+ component_id: String,
+ /// The route, including any application base.
+ based_route: String,
+ /// The route, not including any application base.
+ raw_route: String,
+ /// The route, including any application base and capturing information about whether it has a trailing wildcard.
+ /// (This avoids re-parsing the route string.)
+ parsed_based_route: ParsedRoute,
}
/// A detected duplicate route.
#[derive(Debug)] // Needed to call `expect_err` on `Router::build`
pub struct DuplicateRoute {
/// The duplicated route pattern.
- pub route: RoutePattern,
+ route: String,
/// The raw route that was duplicated.
pub replaced_id: String,
/// The component ID corresponding to the duplicated route.
@@ -33,15 +47,24 @@ impl Router {
base: &str,
component_routes: impl IntoIterator<Item = (&'a str, &'a HttpTriggerRouteConfig)>,
) -> Result<(Self, Vec<DuplicateRoute>)> {
+ // Some information we need to carry between stages of the builder.
+ struct RoutingEntry<'a> {
+ based_route: String,
+ raw_route: &'a str,
+ component_id: &'a str,
+ }
+
let mut routes = IndexMap::new();
let mut duplicates = vec![];
+ // Filter out private endpoints and capture the routes.
let routes_iter = component_routes
.into_iter()
.filter_map(|(component_id, route)| {
match route {
- HttpTriggerRouteConfig::Route(r) => {
- Some(Ok((RoutePattern::from(base, r), component_id.to_string())))
+ HttpTriggerRouteConfig::Route(raw_route) => {
+ let based_route = sanitize_with_base(base, raw_route);
+ Some(Ok(RoutingEntry { based_route, raw_route, component_id }))
}
HttpTriggerRouteConfig::Private(endpoint) => if endpoint.private {
None
@@ -52,50 +75,70 @@ impl Router {
})
.collect::<Result<Vec<_>>>()?;
- for (route, component_id) in routes_iter {
- let replaced = routes.insert(route.clone(), component_id.clone());
+ // Remove duplicates.
+ for re in routes_iter {
+ let effective_id = re.component_id.to_string();
+ let replaced = routes.insert(re.raw_route, re);
if let Some(replaced) = replaced {
duplicates.push(DuplicateRoute {
- route: route.clone(),
- replaced_id: replaced,
- effective_id: component_id.clone(),
+ route: replaced.based_route,
+ replaced_id: replaced.component_id.to_string(),
+ effective_id,
});
}
}
- Ok((Self { routes }, duplicates))
- }
+ // Build a `routefinder` from the remaining routes.
- /// Returns the constructed routes.
- pub fn routes(&self) -> impl Iterator<Item = (&RoutePattern, &String)> {
- self.routes.iter()
- }
+ let mut rf = routefinder::Router::new();
- /// This returns the component id and route pattern for a matched route.
- pub fn route_full(&self, p: &str) -> Result<(&str, &RoutePattern)> {
- let matches = self.routes.iter().filter(|(rp, _)| rp.matches(p));
+ for re in routes.into_values() {
+ let (rfroute, parsed) = Self::parse_route(&re.based_route).map_err(|e| {
+ anyhow!(
+ "Error parsing route {} associated with component {}: {e}",
+ re.based_route,
+ re.component_id
+ )
+ })?;
- let mut best_match: (Option<&str>, Option<&RoutePattern>, usize) = (None, None, 0); // matched id, pattern and length
+ let handler = RouteHandler {
+ component_id: re.component_id.to_string(),
+ based_route: re.based_route,
+ raw_route: re.raw_route.to_string(),
+ parsed_based_route: parsed,
+ };
- for (rp, id) in matches {
- match rp {
- RoutePattern::Exact(_m) => {
- // Exact matching routes take precedence over wildcard matches.
- return Ok((id, rp));
- }
- RoutePattern::Wildcard(m) => {
- // Check and find longest matching prefix of wildcard pattern.
- let (_id_opt, _rp_opt, len) = best_match;
- if m.len() >= len {
- best_match = (Some(id), Some(rp), m.len());
- }
- }
- }
+ rf.add(rfroute, handler).map_err(|e| anyhow!("{e}"))?;
+ }
+
+ let router = Self {
+ router: std::sync::Arc::new(rf),
+ };
+
+ Ok((router, duplicates))
+ }
+
+ fn parse_route(based_route: &str) -> Result<(routefinder::RouteSpec, ParsedRoute), String> {
+ if let Some(wild_suffixed) = based_route.strip_suffix("/...") {
+ let rs = format!("{wild_suffixed}/*").try_into()?;
+ let parsed = ParsedRoute::trailing_wildcard(wild_suffixed);
+ Ok((rs, parsed))
+ } else if let Some(wild_suffixed) = based_route.strip_suffix("/*") {
+ let rs = based_route.try_into()?;
+ let parsed = ParsedRoute::trailing_wildcard(wild_suffixed);
+ Ok((rs, parsed))
+ } else {
+ let rs = based_route.try_into()?;
+ let parsed = ParsedRoute::exact(based_route);
+ Ok((rs, parsed))
}
+ }
- let (id, rp, _) = best_match;
- id.zip(rp)
- .ok_or_else(|| anyhow!("Cannot match route for path {p}"))
+ /// Returns the constructed routes.
+ pub fn routes(&self) -> impl Iterator<Item = (&(impl fmt::Display + fmt::Debug), &String)> {
+ self.router
+ .iter()
+ .map(|(_spec, handler)| (&handler.parsed_based_route, &handler.component_id))
}
/// This returns the component ID that should handle the given path, or an error
@@ -104,327 +147,267 @@ impl Router {
/// If multiple components could potentially handle the same request based on their
/// defined routes, components with matching exact routes take precedence followed
/// by matching wildcard patterns with the longest matching prefix.
- pub fn route(&self, p: &str) -> Result<&str> {
- self.route_full(p).map(|(r, _)| r)
+ pub fn route(&self, p: &str) -> Result<RouteMatch> {
+ let best_match = self
+ .router
+ .best_match(p)
+ .ok_or_else(|| anyhow!("Cannot match route for path {p}"))?;
+
+ let route_handler = best_match.handler().clone();
+ let named_wildcards = best_match
+ .captures()
+ .iter()
+ .map(|(k, v)| (k.to_owned(), v.to_owned()))
+ .collect();
+ let trailing_wildcard = best_match.captures().wildcard().map(|s|
+ // Backward compatibility considerations - Spin has traditionally
+ // captured trailing slashes, but routefinder does not.
+ match (s.is_empty(), p.ends_with('/')) {
+ // route: /foo/..., path: /foo
+ (true, false) => s.to_owned(),
+ // route: /foo/..., path: /foo/
+ (true, true) => "/".to_owned(),
+ // route: /foo/..., path: /foo/bar
+ (false, false) => format!("/{s}"),
+ // route: /foo/..., path: /foo/bar/
+ (false, true) => format!("/{s}/"),
+ }
+ );
+
+ Ok(RouteMatch {
+ route_handler,
+ named_wildcards,
+ trailing_wildcard,
+ })
+ }
+}
+
+impl DuplicateRoute {
+ /// The duplicated route pattern.
+ pub fn route(&self) -> &str {
+ if self.route.is_empty() {
+ "/"
+ } else {
+ &self.route
+ }
}
}
-/// Route patterns for HTTP components.
-#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
-pub enum RoutePattern {
- /// A route pattern that only matches the exact path given.
+#[derive(Clone, Debug)]
+enum ParsedRoute {
Exact(String),
- /// A route pattern that matches any path starting with the given string.
- Wildcard(String),
+ TrailingWildcard(String),
}
-impl RoutePattern {
- /// Returns a RoutePattern given a path fragment.
- pub fn from<S: Into<String>>(base: S, path: S) -> Self {
- let path = Self::sanitize_with_base(base, path);
- match path.strip_suffix("/...") {
- Some(p) => Self::Wildcard(p.to_owned()),
- None => Self::Exact(path),
- }
+impl ParsedRoute {
+ fn exact(route: impl Into<String>) -> Self {
+ Self::Exact(route.into())
}
- /// Returns true if the given path fragment can be handled
- /// by the route pattern.
- pub fn matches<S: Into<String>>(&self, p: S) -> bool {
- let p = Self::sanitize(p);
- match self {
- RoutePattern::Exact(path) => &p == path,
- RoutePattern::Wildcard(pattern) => {
- &p == pattern || p.starts_with(&format!("{}/", pattern))
- }
- }
+ fn trailing_wildcard(route: impl Into<String>) -> Self {
+ Self::TrailingWildcard(route.into())
}
+}
- /// Resolves a relative path from the end of the matched path to the end of the string.
- pub fn relative(&self, uri: &str) -> Result<String> {
- let base = match self {
- Self::Exact(path) => path,
- Self::Wildcard(prefix) => prefix,
- };
- Ok(uri
- .parse::<Uri>()?
- .path()
- .strip_prefix(base)
- .unwrap_or_default()
- .to_owned())
- }
-
- /// The full path (for Exact) or prefix (for Wildcard).
- pub fn path_or_prefix(&self) -> &str {
- match self {
- RoutePattern::Exact(s) => s,
- RoutePattern::Wildcard(s) => s,
+impl fmt::Display for ParsedRoute {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match &self {
+ ParsedRoute::Exact(path) => write!(f, "{}", path),
+ ParsedRoute::TrailingWildcard(pattern) => write!(f, "{} (wildcard)", pattern),
}
}
+}
- /// The full pattern, with trailing "/..." for Wildcard.
- pub fn full_pattern(&self) -> Cow<str> {
- match self {
- Self::Exact(path) => path.into(),
- Self::Wildcard(prefix) => format!("{}/...", prefix).into(),
+/// A routing match for a URL.
+pub struct RouteMatch {
+ route_handler: RouteHandler,
+ named_wildcards: HashMap<String, String>,
+ trailing_wildcard: Option<String>,
+}
+
+impl RouteMatch {
+ /// A synthetic match as if the given path was matched against the wildcard route.
+ /// Used in service chaining.
+ pub fn synthetic(component_id: &str, path: &str) -> Self {
+ Self {
+ route_handler: RouteHandler {
+ component_id: component_id.to_string(),
+ based_route: "/...".to_string(),
+ raw_route: "/...".to_string(),
+ parsed_based_route: ParsedRoute::TrailingWildcard(String::new()),
+ },
+ named_wildcards: Default::default(),
+ trailing_wildcard: Some(path.to_string()),
}
}
- /// The full pattern, with trailing "/..." for Wildcard and "/" for root.
- pub fn full_pattern_non_empty(&self) -> Cow<str> {
- match self {
- Self::Exact(path) if path.is_empty() => "/".into(),
- _ => self.full_pattern(),
- }
+ /// The matched component.
+ pub fn component_id(&self) -> &str {
+ &self.route_handler.component_id
}
- /// Sanitizes the base and path and return a formed path.
- pub fn sanitize_with_base<S: Into<String>>(base: S, path: S) -> String {
- let path = Self::absolutize(path);
+ /// The matched route, as originally written in the manifest, combined with the base.
+ pub fn based_route(&self) -> &str {
+ &self.route_handler.based_route
+ }
- format!("{}{}", Self::sanitize(base.into()), Self::sanitize(path))
+ /// The matched route, excluding any trailing wildcard, combined with the base.
+ pub fn based_route_or_prefix(&self) -> String {
+ self.route_handler
+ .based_route
+ .strip_suffix("/...")
+ .unwrap_or(&self.route_handler.based_route)
+ .to_string()
}
- fn absolutize<S: Into<String>>(s: S) -> String {
- let s = s.into();
- if s.starts_with('/') {
- s
- } else {
- format!("/{s}")
- }
+ /// The matched route, as originally written in the manifest.
+ pub fn raw_route(&self) -> &str {
+ &self.route_handler.raw_route
}
- /// Strips the trailing slash from a string.
- fn sanitize<S: Into<String>>(s: S) -> String {
- let s = s.into();
- // TODO
- // This only strips a single trailing slash.
- // Should we attempt to strip all trailing slashes?
- match s.strip_suffix('/') {
- Some(s) => s.into(),
- None => s,
- }
+ /// The matched route, excluding any trailing wildcard.
+ pub fn raw_route_or_prefix(&self) -> String {
+ self.route_handler
+ .raw_route
+ .strip_suffix("/...")
+ .unwrap_or(&self.route_handler.raw_route)
+ .to_string()
+ }
+
+ /// The named wildcards captured from the path, if any
+ pub fn named_wildcards(&self) -> &HashMap<String, String> {
+ &self.named_wildcards
+ }
+
+ /// The trailing wildcard part of the path, if any
+ pub fn trailing_wildcard(&self) -> String {
+ self.trailing_wildcard.clone().unwrap_or_default()
}
}
-impl fmt::Display for RoutePattern {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- match &self {
- RoutePattern::Exact(path) => write!(f, "{}", path),
- RoutePattern::Wildcard(pattern) => write!(f, "{} (wildcard)", pattern),
- }
+/// Sanitizes the base and path and return a formed path.
+fn sanitize_with_base<S: Into<String>>(base: S, path: S) -> String {
+ let path = absolutize(path);
+
+ format!("{}{}", sanitize(base.into()), sanitize(path))
+}
+
+fn absolutize<S: Into<String>>(s: S) -> String {
+ let s = s.into();
+ if s.starts_with('/') {
+ s
+ } else {
+ format!("/{s}")
+ }
+}
+
+/// Strips the trailing slash from a string.
+fn sanitize<S: Into<String>>(s: S) -> String {
+ let s = s.into();
+ // TODO
+ // This only strips a single trailing slash.
+ // Should we attempt to strip all trailing slashes?
+ match s.strip_suffix('/') {
+ Some(s) => s.into(),
+ None => s,
}
}
#[cfg(test)]
mod route_tests {
- use spin_testing::init_tracing;
-
use crate::config::HttpPrivateEndpoint;
use super::*;
#[test]
- fn test_exact_route() {
- init_tracing();
-
- let rp = RoutePattern::from("/", "/foo/bar");
- assert!(rp.matches("/foo/bar"));
- assert!(rp.matches("/foo/bar/"));
- assert!(!rp.matches("/foo"));
- assert!(!rp.matches("/foo/bar/thisshouldbefalse"));
- assert!(!rp.matches("/abc"));
-
- let rp = RoutePattern::from("/base", "/foo");
- assert!(rp.matches("/base/foo"));
- assert!(rp.matches("/base/foo/"));
- assert!(!rp.matches("/base/foo/bar"));
- assert!(!rp.matches("/thishouldbefalse"));
-
- let rp = RoutePattern::from("/base/", "/foo");
- assert!(rp.matches("/base/foo"));
- assert!(rp.matches("/base/foo/"));
- assert!(!rp.matches("/base/foo/bar"));
- assert!(!rp.matches("/thishouldbefalse"));
-
- let rp = RoutePattern::from("/base/", "/foo/");
- assert!(rp.matches("/base/foo"));
- assert!(rp.matches("/base/foo/"));
- assert!(!rp.matches("/base/foo/bar"));
- assert!(!rp.matches("/thishouldbefalse"));
- }
+ fn test_router_exact() -> Result<()> {
+ let (r, _dups) = Router::build(
+ "/",
+ [("foo", &"/foo".into()), ("foobar", &"/foo/bar".into())],
+ )?;
- #[test]
- fn test_pattern_route() {
- let rp = RoutePattern::from("/", "/...");
- assert!(rp.matches("/foo/bar/"));
- assert!(rp.matches("/foo"));
- assert!(rp.matches("/foo/bar/baz"));
- assert!(rp.matches("/this/should/really/match/everything/"));
- assert!(rp.matches("/"));
-
- let rp = RoutePattern::from("/", "/foo/...");
- assert!(rp.matches("/foo/bar/"));
- assert!(rp.matches("/foo"));
- assert!(rp.matches("/foo/bar/baz"));
- assert!(!rp.matches("/this/should/really/not/match/everything/"));
- assert!(!rp.matches("/"));
-
- let rp = RoutePattern::from("/base", "/...");
- assert!(rp.matches("/base/foo/bar/"));
- assert!(rp.matches("/base/foo"));
- assert!(rp.matches("/base/foo/bar/baz"));
- assert!(rp.matches("/base/this/should/really/match/everything/"));
- assert!(rp.matches("/base"));
+ assert_eq!(r.route("/foo")?.component_id(), "foo");
+ assert_eq!(r.route("/foo/bar")?.component_id(), "foobar");
+ Ok(())
}
#[test]
- fn handles_missing_leading_slash() {
- let rp = RoutePattern::from("/", "foo/bar");
- assert!(rp.matches("/foo/bar"));
- assert!(rp.matches("/foo/bar/"));
- assert!(!rp.matches("/foo"));
- assert!(!rp.matches("/foo/bar/thisshouldbefalse"));
- assert!(!rp.matches("/abc"));
-
- let rp = RoutePattern::from("/base", "foo");
- assert!(rp.matches("/base/foo"));
- assert!(rp.matches("/base/foo/"));
- assert!(!rp.matches("/base/foo/bar"));
- assert!(!rp.matches("/thishouldbefalse"));
+ fn test_router_respects_base() -> Result<()> {
+ let (r, _dups) = Router::build(
+ "/base",
+ [("foo", &"/foo".into()), ("foobar", &"/foo/bar".into())],
+ )?;
+
+ assert_eq!(r.route("/base/foo")?.component_id(), "foo");
+ assert_eq!(r.route("/base/foo/bar")?.component_id(), "foobar");
+ Ok(())
}
#[test]
- fn test_relative() -> Result<()> {
- assert_eq!(
- RoutePattern::from("/", "/foo").relative("/foo/bar")?,
- "/bar".to_string()
- );
- assert_eq!(
- RoutePattern::from("/base", "/foo").relative("/base/foo/bar")?,
- "/bar".to_string()
- );
+ fn test_router_wildcard() -> Result<()> {
+ let (r, _dups) = Router::build("/", [("all", &"/...".into())])?;
+ assert_eq!(r.route("/foo/bar")?.component_id(), "all");
+ assert_eq!(r.route("/abc/")?.component_id(), "all");
+ assert_eq!(r.route("/")?.component_id(), "all");
assert_eq!(
- RoutePattern::from("/", "/foo").relative("/foo")?,
- "".to_string()
+ r.route("/this/should/be/captured?abc=def")?.component_id(),
+ "all"
);
- assert_eq!(
- RoutePattern::from("/base", "/foo").relative("/base/foo")?,
- "".to_string()
- );
-
- assert_eq!(
- RoutePattern::from("/", "/static/...").relative("/static/images/abc.png")?,
- "/images/abc.png".to_string()
- );
- assert_eq!(
- RoutePattern::from("/base", "/static/...").relative("/base/static/images/abc.png")?,
- "/images/abc.png".to_string()
- );
-
- assert_eq!(
- RoutePattern::from("/base", "/static/...")
- .relative("/base/static/images/abc.png?abc=def&foo=bar")?,
- "/images/abc.png".to_string()
- );
-
Ok(())
}
#[test]
- fn test_router() -> Result<()> {
- let mut routes = IndexMap::new();
-
- routes.insert(RoutePattern::from("/", "/foo"), "foo".to_string());
- routes.insert(RoutePattern::from("/", "/foo/bar"), "foobar".to_string());
-
- let r = Router { routes };
-
- assert_eq!(r.route("/foo")?, "foo".to_string());
- assert_eq!(r.route("/foo/bar")?, "foobar".to_string());
-
- let mut routes = IndexMap::new();
-
- routes.insert(RoutePattern::from("/base", "/foo"), "foo".to_string());
- routes.insert(
- RoutePattern::from("/base", "/foo/bar"),
- "foobar".to_string(),
- );
+ fn wildcard_routes_use_custom_display() {
+ let (routes, _dups) = Router::build("/", vec![("comp", &"/whee/...".into())]).unwrap();
- let r = Router { routes };
-
- assert_eq!(r.route("/base/foo")?, "foo".to_string());
- assert_eq!(r.route("/base/foo/bar")?, "foobar".to_string());
-
- let mut routes = IndexMap::new();
-
- routes.insert(RoutePattern::from("/", "/..."), "all".to_string());
-
- let r = Router { routes };
-
- assert_eq!(r.route("/foo/bar")?, "all".to_string());
- assert_eq!(r.route("/abc/")?, "all".to_string());
- assert_eq!(r.route("/")?, "all".to_string());
- assert_eq!(
- r.route("/this/should/be/captured?abc=def")?,
- "all".to_string()
- );
-
- let mut routes = IndexMap::new();
+ let (route, component_id) = routes.routes().next().unwrap();
- routes.insert(
- RoutePattern::from("/", "/one/..."),
- "one_wildcard".to_string(),
- );
- routes.insert(
- RoutePattern::from("/", "/one/two/..."),
- "onetwo_wildcard".to_string(),
- );
- routes.insert(
- RoutePattern::from("/", "/one/two/three/..."),
- "onetwothree_wildcard".to_string(),
- );
+ assert_eq!("comp", component_id);
+ assert_eq!("/whee (wildcard)", format!("{route}"));
+ }
- let r = Router { routes };
+ #[test]
+ fn test_router_respects_longest_match() -> Result<()> {
+ let (r, _dups) = Router::build(
+ "/",
+ [
+ ("one_wildcard", &"/one/...".into()),
+ ("onetwo_wildcard", &"/one/two/...".into()),
+ ("onetwothree_wildcard", &"/one/two/three/...".into()),
+ ],
+ )?;
assert_eq!(
- r.route("/one/two/three/four")?,
- "onetwothree_wildcard".to_string()
+ r.route("/one/two/three/four")?.component_id(),
+ "onetwothree_wildcard"
);
- let mut routes = IndexMap::new();
-
- routes.insert(
- RoutePattern::from("/", "/one/two/three/..."),
- "onetwothree_wildcard".to_string(),
- );
- routes.insert(
- RoutePattern::from("/", "/one/two/..."),
- "onetwo_wildcard".to_string(),
- );
- routes.insert(
- RoutePattern::from("/", "/one/..."),
- "one_wildcard".to_string(),
- );
-
- let r = Router { routes };
+ // ...regardless of order
+ let (r, _dups) = Router::build(
+ "/",
+ [
+ ("onetwothree_wildcard", &"/one/two/three/...".into()),
+ ("onetwo_wildcard", &"/one/two/...".into()),
+ ("one_wildcard", &"/one/...".into()),
+ ],
+ )?;
assert_eq!(
- r.route("/one/two/three/four")?,
- "onetwothree_wildcard".to_string()
+ r.route("/one/two/three/four")?.component_id(),
+ "onetwothree_wildcard"
);
+ Ok(())
+ }
- // Test routing rule "exact beats wildcard" ...
- let mut routes = IndexMap::new();
-
- routes.insert(RoutePattern::from("/", "/one"), "one_exact".to_string());
-
- routes.insert(RoutePattern::from("/", "/..."), "wildcard".to_string());
-
- let r = Router { routes };
+ #[test]
+ fn test_router_exact_beats_wildcard() -> Result<()> {
+ let (r, _dups) = Router::build(
+ "/",
+ [("one_exact", &"/one".into()), ("wildcard", &"/...".into())],
+ )?;
- assert_eq!(r.route("/one")?, "one_exact".to_string(),);
+ assert_eq!(r.route("/one")?.component_id(), "one_exact");
Ok(())
}
@@ -442,7 +425,7 @@ mod route_tests {
)
.unwrap();
- assert_eq!(4, routes.routes.len());
+ assert_eq!(4, routes.routes().count());
assert_eq!(0, duplicates.len());
}
@@ -451,18 +434,18 @@ mod route_tests {
let (routes, _) = Router::build(
"/",
vec![
- ("/", &"/".into()),
- ("/foo", &"/foo".into()),
- ("/bar", &"/bar".into()),
- ("/whee/...", &"/whee/...".into()),
+ ("comp-/", &"/".into()),
+ ("comp-/foo", &"/foo".into()),
+ ("comp-/bar", &"/bar".into()),
+ ("comp-/whee/...", &"/whee/...".into()),
],
)
.unwrap();
- assert_eq!("/", routes.routes[0]);
- assert_eq!("/foo", routes.routes[1]);
- assert_eq!("/bar", routes.routes[2]);
- assert_eq!("/whee/...", routes.routes[3]);
+ assert_eq!("comp-/", routes.routes().next().unwrap().1);
+ assert_eq!("comp-/foo", routes.routes().nth(1).unwrap().1);
+ assert_eq!("comp-/bar", routes.routes().nth(2).unwrap().1);
+ assert_eq!("comp-/whee/...", routes.routes().nth(3).unwrap().1);
}
#[test]
@@ -470,15 +453,15 @@ mod route_tests {
let (routes, duplicates) = Router::build(
"/",
vec![
- ("/", &"/".into()),
- ("first /foo", &"/foo".into()),
- ("second /foo", &"/foo".into()),
- ("/whee/...", &"/whee/...".into()),
+ ("comp-/", &"/".into()),
+ ("comp-first /foo", &"/foo".into()),
+ ("comp-second /foo", &"/foo".into()),
+ ("comp-/whee/...", &"/whee/...".into()),
],
)
.unwrap();
- assert_eq!(3, routes.routes.len());
+ assert_eq!(3, routes.routes().count());
assert_eq!(1, duplicates.len());
}
@@ -487,17 +470,47 @@ mod route_tests {
let (routes, duplicates) = Router::build(
"/",
vec![
- ("/", &"/".into()),
- ("first /foo", &"/foo".into()),
- ("second /foo", &"/foo".into()),
- ("/whee/...", &"/whee/...".into()),
+ ("comp-/", &"/".into()),
+ ("comp-first /foo", &"/foo".into()),
+ ("comp-second /foo", &"/foo".into()),
+ ("comp-/whee/...", &"/whee/...".into()),
],
)
.unwrap();
- assert_eq!("second /foo", routes.routes[1]);
- assert_eq!("first /foo", duplicates[0].replaced_id);
- assert_eq!("second /foo", duplicates[0].effective_id);
+ assert_eq!("comp-second /foo", routes.routes().nth(1).unwrap().1);
+ assert_eq!("comp-first /foo", duplicates[0].replaced_id);
+ assert_eq!("comp-second /foo", duplicates[0].effective_id);
+ }
+
+ #[test]
+ fn duplicate_routes_reporting_is_faithful() {
+ let (_, duplicates) = Router::build(
+ "/",
+ vec![
+ ("comp-first /", &"/".into()),
+ ("comp-second /", &"/".into()),
+ ("comp-first /foo", &"/foo".into()),
+ ("comp-second /foo", &"/foo".into()),
+ ("comp-first /...", &"/...".into()),
+ ("comp-second /...", &"/...".into()),
+ ("comp-first /whee/...", &"/whee/...".into()),
+ ("comp-second /whee/...", &"/whee/...".into()),
+ ],
+ )
+ .unwrap();
+
+ assert_eq!("comp-first /", duplicates[0].replaced_id);
+ assert_eq!("/", duplicates[0].route());
+
+ assert_eq!("comp-first /foo", duplicates[1].replaced_id);
+ assert_eq!("/foo", duplicates[1].route());
+
+ assert_eq!("comp-first /...", duplicates[2].replaced_id);
+ assert_eq!("/...", duplicates[2].route());
+
+ assert_eq!("comp-first /whee/...", duplicates[3].replaced_id);
+ assert_eq!("/whee/...", duplicates[3].route());
}
#[test]
@@ -505,19 +518,19 @@ mod route_tests {
let (routes, _) = Router::build(
"/",
vec![
- ("/", &"/".into()),
- ("/foo", &"/foo".into()),
+ ("comp-/", &"/".into()),
+ ("comp-/foo", &"/foo".into()),
(
- "private",
+ "comp-private",
&HttpTriggerRouteConfig::Private(HttpPrivateEndpoint { private: true }),
),
- ("/whee/...", &"/whee/...".into()),
+ ("comp-/whee/...", &"/whee/...".into()),
],
)
.unwrap();
- assert_eq!(3, routes.routes.len());
- assert!(!routes.routes.values().any(|c| c == "private"));
+ assert_eq!(3, routes.routes().count());
+ assert!(!routes.routes().any(|(_r, c)| c == "comp-private"));
}
#[test]
@@ -525,17 +538,59 @@ mod route_tests {
let e = Router::build(
"/",
vec![
- ("/", &"/".into()),
- ("/foo", &"/foo".into()),
+ ("comp-/", &"/".into()),
+ ("comp-/foo", &"/foo".into()),
(
- "bad component",
+ "comp-bad component",
&HttpTriggerRouteConfig::Private(HttpPrivateEndpoint { private: false }),
),
- ("/whee/...", &"/whee/...".into()),
+ ("comp-/whee/...", &"/whee/...".into()),
],
)
.expect_err("should not have accepted a 'route = true'");
- assert!(e.to_string().contains("bad component"));
+ assert!(e.to_string().contains("comp-bad component"));
+ }
+
+ #[test]
+ fn trailing_wildcard_is_captured() {
+ let (routes, _dups) = Router::build("/", vec![("comp", &"/...".into())]).unwrap();
+ let m = routes.route("/1/2/3").expect("/1/2/3 should have matched");
+ assert_eq!("/1/2/3", m.trailing_wildcard());
+
+ let (routes, _dups) = Router::build("/", vec![("comp", &"/1/...".into())]).unwrap();
+ let m = routes.route("/1/2/3").expect("/1/2/3 should have matched");
+ assert_eq!("/2/3", m.trailing_wildcard());
+ }
+
+ #[test]
+ fn trailing_wildcard_respects_trailing_slash() {
+ // We test this because it is the existing Spin behaviour but is *not*
+ // how routefinder behaves by default (routefinder prefers to ignore trailing
+ // slashes).
+ let (routes, _dups) = Router::build("/", vec![("comp", &"/test/...".into())]).unwrap();
+ let m = routes.route("/test").expect("/test should have matched");
+ assert_eq!("", m.trailing_wildcard());
+ let m = routes.route("/test/").expect("/test/ should have matched");
+ assert_eq!("/", m.trailing_wildcard());
+ let m = routes
+ .route("/test/hello")
+ .expect("/test/hello should have matched");
+ assert_eq!("/hello", m.trailing_wildcard());
+ let m = routes
+ .route("/test/hello/")
+ .expect("/test/hello/ should have matched");
+ assert_eq!("/hello/", m.trailing_wildcard());
+ }
+
+ #[test]
+ fn named_wildcard_is_captured() {
+ let (routes, _dups) = Router::build("/", vec![("comp", &"/1/:two/3".into())]).unwrap();
+ let m = routes.route("/1/2/3").expect("/1/2/3 should have matched");
+ assert_eq!("2", m.named_wildcards()["two"]);
+
+ let (routes, _dups) = Router::build("/", vec![("comp", &"/1/:two/...".into())]).unwrap();
+ let m = routes.route("/1/2/3").expect("/1/2/3 should have matched");
+ assert_eq!("2", m.named_wildcards()["two"]);
}
}
diff --git a/crates/http/src/wagi/mod.rs b/crates/http/src/wagi/mod.rs
index db9dff0fb0..bbb021dc93 100644
--- a/crates/http/src/wagi/mod.rs
+++ b/crates/http/src/wagi/mod.rs
@@ -10,7 +10,7 @@ use http::{
HeaderMap, HeaderValue, Response, StatusCode,
};
-use crate::{body, routes::RoutePattern, Body};
+use crate::{body, routes::RouteMatch, Body};
/// This sets the version of CGI that WAGI adheres to.
///
@@ -22,7 +22,7 @@ pub const WAGI_VERSION: &str = "CGI/1.1";
pub const SERVER_SOFTWARE_VERSION: &str = "WAGI/1";
pub fn build_headers(
- route: &RoutePattern,
+ route_match: &RouteMatch,
req: &Parts,
content_length: usize,
client_addr: SocketAddr,
@@ -30,12 +30,7 @@ pub fn build_headers(
use_tls: bool,
) -> HashMap<String, String> {
let (host, port) = parse_host_header_uri(&req.headers, &req.uri, default_host);
- let path_info = req
- .uri
- .path()
- .strip_prefix(route.path_or_prefix())
- .unwrap_or_default()
- .to_owned();
+ let path_info = route_match.trailing_wildcard();
let mut headers = HashMap::new();
@@ -92,7 +87,7 @@ pub fn build_headers(
// have a trailing '/...'
headers.insert(
"X_MATCHED_ROUTE".to_owned(),
- route.full_pattern().into_owned(),
+ route_match.based_route().to_string(),
);
headers.insert(
@@ -108,7 +103,10 @@ pub fn build_headers(
// The Path component is /$SCRIPT_NAME/$PATH_INFO
// SCRIPT_NAME is the route that matched.
// https://datatracker.ietf.org/doc/html/rfc3875#section-4.1.13
- headers.insert("SCRIPT_NAME".to_owned(), route.path_or_prefix().to_owned());
+ headers.insert(
+ "SCRIPT_NAME".to_owned(),
+ route_match.based_route_or_prefix(),
+ );
// PATH_INFO is any path information after SCRIPT_NAME
//
// I am intentionally ignoring the PATH_INFO rule that says that a PATH_INFO
diff --git a/crates/trigger-http/src/handler.rs b/crates/trigger-http/src/handler.rs
index 6220acb8f4..bd72e0e451 100644
--- a/crates/trigger-http/src/handler.rs
+++ b/crates/trigger-http/src/handler.rs
@@ -13,6 +13,7 @@ use spin_core::wasi_2023_10_18::exports::wasi::http::incoming_handler::Guest as
use spin_core::wasi_2023_11_10::exports::wasi::http::incoming_handler::Guest as IncomingHandler2023_11_10;
use spin_core::Instance;
use spin_http::body;
+use spin_http::routes::RouteMatch;
use spin_trigger::TriggerAppEngine;
use spin_world::v1::http_types;
use std::sync::Arc;
@@ -25,16 +26,17 @@ pub struct HttpHandlerExecutor;
#[async_trait]
impl HttpExecutor for HttpHandlerExecutor {
- #[instrument(name = "spin_trigger_http.execute_wasm", skip_all, err(level = Level::INFO), fields(otel.name = format!("execute_wasm_component {}", component_id)))]
+ #[instrument(name = "spin_trigger_http.execute_wasm", skip_all, err(level = Level::INFO), fields(otel.name = format!("execute_wasm_component {}", route_match.component_id())))]
async fn execute(
&self,
engine: Arc<TriggerAppEngine<HttpTrigger>>,
- component_id: &str,
base: &str,
- raw_route: &str,
+ route_match: &RouteMatch,
req: Request<Body>,
client_addr: SocketAddr,
) -> Result<Response<Body>> {
+ let component_id = route_match.component_id();
+
tracing::trace!(
"Executing request using the Spin executor for component {}",
component_id
@@ -49,10 +51,10 @@ impl HttpExecutor for HttpHandlerExecutor {
let resp = match HandlerType::from_exports(instance.exports(&mut store)) {
Some(HandlerType::Wasi) => {
- Self::execute_wasi(store, instance, base, raw_route, req, client_addr).await?
+ Self::execute_wasi(store, instance, base, route_match, req, client_addr).await?
}
Some(HandlerType::Spin) => {
- Self::execute_spin(store, instance, base, raw_route, req, client_addr)
+ Self::execute_spin(store, instance, base, route_match, req, client_addr)
.await
.map_err(contextualise_err)?
}
@@ -76,11 +78,11 @@ impl HttpHandlerExecutor {
mut store: Store,
instance: Instance,
base: &str,
- raw_route: &str,
+ route_match: &RouteMatch,
req: Request<Body>,
client_addr: SocketAddr,
) -> Result<Response<Body>> {
- let headers = Self::headers(&req, raw_route, base, client_addr)?;
+ let headers = Self::headers(&req, base, route_match, client_addr)?;
let func = instance
.exports(&mut store)
.instance("fermyon:spin/inbound-http")
@@ -156,11 +158,11 @@ impl HttpHandlerExecutor {
mut store: Store,
instance: Instance,
base: &str,
- raw_route: &str,
+ route_match: &RouteMatch,
mut req: Request<Body>,
client_addr: SocketAddr,
) -> anyhow::Result<Response<Body>> {
- let headers = Self::headers(&req, raw_route, base, client_addr)?;
+ let headers = Self::headers(&req, base, route_match, client_addr)?;
req.headers_mut().clear();
req.headers_mut()
.extend(headers.into_iter().filter_map(|(n, v)| {
@@ -281,8 +283,8 @@ impl HttpHandlerExecutor {
fn headers(
req: &Request<Body>,
- raw: &str,
base: &str,
+ route_match: &RouteMatch,
client_addr: SocketAddr,
) -> Result<Vec<(String, String)>> {
let mut res = Vec::new();
@@ -306,9 +308,10 @@ impl HttpHandlerExecutor {
// Set the environment information (path info, base path, etc) as headers.
// In the future, we might want to have this information in a context
// object as opposed to headers.
- for (keys, val) in crate::compute_default_headers(req.uri(), raw, base, host, client_addr)?
+ for (keys, val) in
+ crate::compute_default_headers(req.uri(), base, host, route_match, client_addr)?
{
- res.push((Self::prepare_header_key(keys[0]), val));
+ res.push((Self::prepare_header_key(&keys[0]), val));
}
Ok(res)
diff --git a/crates/trigger-http/src/lib.rs b/crates/trigger-http/src/lib.rs
index 7720a8d231..743866887e 100644
--- a/crates/trigger-http/src/lib.rs
+++ b/crates/trigger-http/src/lib.rs
@@ -32,8 +32,8 @@ use spin_core::{Engine, OutboundWasiHttpHandler};
use spin_http::{
app_info::AppInfo,
body,
- config::{HttpExecutorType, HttpTriggerConfig, HttpTriggerRouteConfig},
- routes::{RoutePattern, Router},
+ config::{HttpExecutorType, HttpTriggerConfig},
+ routes::{RouteMatch, Router},
};
use spin_outbound_networking::{
is_service_chaining_host, parse_service_chaining_target, AllowedHostsConfig, OutboundUrl,
@@ -140,7 +140,7 @@ impl TriggerExecutor for HttpTrigger {
log::error!(
" {}: {} (duplicate of {})",
dup.replaced_id,
- dup.route.full_pattern_non_empty(),
+ dup.route(),
dup.effective_id,
);
}
@@ -256,34 +256,24 @@ impl HttpTrigger {
// Route to app component
match self.router.route(&path) {
- Ok(component_id) => {
+ Ok(route_match) => {
spin_telemetry::metrics::monotonic_counter!(
spin.request_count = 1,
trigger_type = "http",
app_id = &self.engine.app_name,
- component_id = component_id
+ component_id = route_match.component_id()
);
+ let component_id = route_match.component_id();
+
let trigger = self.component_trigger_configs.get(component_id).unwrap();
let executor = trigger.executor.as_ref().unwrap_or(&HttpExecutorType::Http);
- let raw_route = match &trigger.route {
- HttpTriggerRouteConfig::Route(r) => r.as_str(),
- HttpTriggerRouteConfig::Private(_) => "/...",
- };
-
let res = match executor {
HttpExecutorType::Http => {
HttpHandlerExecutor
- .execute(
- self.engine.clone(),
- component_id,
- &self.base,
- raw_route,
- req,
- addr,
- )
+ .execute(self.engine.clone(), &self.base, &route_match, req, addr)
.await
}
HttpExecutorType::Wagi(wagi_config) => {
@@ -291,26 +281,19 @@ impl HttpTrigger {
wagi_config: wagi_config.clone(),
};
executor
- .execute(
- self.engine.clone(),
- component_id,
- &self.base,
- raw_route,
- req,
- addr,
- )
+ .execute(self.engine.clone(), &self.base, &route_match, req, addr)
.await
}
};
match res {
Ok(res) => Ok(MatchedRoute::with_response_extension(
res,
- raw_route.to_string(),
+ route_match.raw_route(),
)),
Err(e) => {
log::error!("Error processing request: {:?}", e);
instrument_error(&e);
- Self::internal_error(None, raw_route.to_string())
+ Self::internal_error(None, route_match.raw_route())
}
}
}
@@ -331,7 +314,7 @@ impl HttpTrigger {
}
/// Creates an HTTP 500 response.
- fn internal_error(body: Option<&str>, route: String) -> Result<Response<Body>> {
+ fn internal_error(body: Option<&str>, route: impl Into<String>) -> Result<Response<Body>> {
let body = match body {
Some(body) => body::full(Bytes::copy_from_slice(body.as_bytes())),
None => body::empty(),
@@ -492,48 +475,62 @@ fn strip_forbidden_headers(req: &mut Request<Body>) {
// modules is going to be different, so each executor must must use the info
// in its standardized way (environment variables for the Wagi executor, and custom headers
// for the Spin HTTP executor).
-const FULL_URL: &[&str] = &["SPIN_FULL_URL", "X_FULL_URL"];
-const PATH_INFO: &[&str] = &["SPIN_PATH_INFO", "PATH_INFO"];
-const MATCHED_ROUTE: &[&str] = &["SPIN_MATCHED_ROUTE", "X_MATCHED_ROUTE"];
-const COMPONENT_ROUTE: &[&str] = &["SPIN_COMPONENT_ROUTE", "X_COMPONENT_ROUTE"];
-const RAW_COMPONENT_ROUTE: &[&str] = &["SPIN_RAW_COMPONENT_ROUTE", "X_RAW_COMPONENT_ROUTE"];
-const BASE_PATH: &[&str] = &["SPIN_BASE_PATH", "X_BASE_PATH"];
-const CLIENT_ADDR: &[&str] = &["SPIN_CLIENT_ADDR", "X_CLIENT_ADDR"];
-
-pub(crate) fn compute_default_headers<'a>(
+const FULL_URL: [&str; 2] = ["SPIN_FULL_URL", "X_FULL_URL"];
+const PATH_INFO: [&str; 2] = ["SPIN_PATH_INFO", "PATH_INFO"];
+const MATCHED_ROUTE: [&str; 2] = ["SPIN_MATCHED_ROUTE", "X_MATCHED_ROUTE"];
+const COMPONENT_ROUTE: [&str; 2] = ["SPIN_COMPONENT_ROUTE", "X_COMPONENT_ROUTE"];
+const RAW_COMPONENT_ROUTE: [&str; 2] = ["SPIN_RAW_COMPONENT_ROUTE", "X_RAW_COMPONENT_ROUTE"];
+const BASE_PATH: [&str; 2] = ["SPIN_BASE_PATH", "X_BASE_PATH"];
+const CLIENT_ADDR: [&str; 2] = ["SPIN_CLIENT_ADDR", "X_CLIENT_ADDR"];
+
+pub(crate) fn compute_default_headers(
uri: &Uri,
- raw: &str,
base: &str,
host: &str,
+ route_match: &RouteMatch,
client_addr: SocketAddr,
-) -> Result<Vec<(&'a [&'a str], String)>> {
+) -> Result<Vec<([String; 2], String)>> {
+ fn owned(strs: &[&'static str; 2]) -> [String; 2] {
+ [strs[0].to_owned(), strs[1].to_owned()]
+ }
+
+ let owned_full_url: [String; 2] = owned(&FULL_URL);
+ let owned_path_info: [String; 2] = owned(&PATH_INFO);
+ let owned_matched_route: [String; 2] = owned(&MATCHED_ROUTE);
+ let owned_component_route: [String; 2] = owned(&COMPONENT_ROUTE);
+ let owned_raw_component_route: [String; 2] = owned(&RAW_COMPONENT_ROUTE);
+ let owned_base_path: [String; 2] = owned(&BASE_PATH);
+ let owned_client_addr: [String; 2] = owned(&CLIENT_ADDR);
+
let mut res = vec![];
let abs_path = uri
.path_and_query()
.expect("cannot get path and query")
.as_str();
- let path_info = RoutePattern::from(base, raw).relative(abs_path)?;
+ let path_info = route_match.trailing_wildcard();
let scheme = uri.scheme_str().unwrap_or("http");
let full_url = format!("{}://{}{}", scheme, host, abs_path);
- let matched_route = RoutePattern::sanitize_with_base(base, raw);
- res.push((PATH_INFO, path_info));
- res.push((FULL_URL, full_url));
- res.push((MATCHED_ROUTE, matched_route));
+ res.push((owned_path_info, path_info));
+ res.push((owned_full_url, full_url));
+ res.push((owned_matched_route, route_match.based_route().to_string()));
- res.push((BASE_PATH, base.to_string()));
- res.push((RAW_COMPONENT_ROUTE, raw.to_string()));
+ res.push((owned_base_path, base.to_string()));
res.push((
- COMPONENT_ROUTE,
- raw.to_string()
- .strip_suffix("/...")
- .unwrap_or(raw)
- .to_string(),
+ owned_raw_component_route,
+ route_match.raw_route().to_string(),
));
- res.push((CLIENT_ADDR, client_addr.to_string()));
+ res.push((owned_component_route, route_match.raw_route_or_prefix()));
+ res.push((owned_client_addr, client_addr.to_string()));
+
+ for (wild_name, wild_value) in route_match.named_wildcards() {
+ let wild_header = format!("SPIN_PATH_MATCH_{}", wild_name.to_ascii_uppercase()); // TODO: safer
+ let wild_wagi_header = format!("X_PATH_MATCH_{}", wild_name.to_ascii_uppercase()); // TODO: safer
+ res.push(([wild_header, wild_wagi_header], wild_value.clone()));
+ }
Ok(res)
}
@@ -545,9 +542,8 @@ pub(crate) trait HttpExecutor: Clone + Send + Sync + 'static {
async fn execute(
&self,
engine: Arc<TriggerAppEngine<HttpTrigger>>,
- component_id: &str,
base: &str,
- raw_route: &str,
+ route_match: &RouteMatch,
req: Request<Body>,
client_addr: SocketAddr,
) -> Result<Response<Body>>;
@@ -586,8 +582,7 @@ impl HttpRuntimeData {
let engine = chained_handler.engine;
let handler = chained_handler.executor;
- let base = "/";
- let raw_route = "/...";
+ let route_match = RouteMatch::synthetic(&component_id, request.request.uri().path());
let client_addr = std::net::SocketAddr::from_str("0.0.0.0:0")?;
@@ -603,8 +598,7 @@ impl HttpRuntimeData {
.execute(
engine.clone(),
&component_id,
- base,
- raw_route,
+ &route_match,
req,
client_addr,
)
@@ -784,35 +778,38 @@ mod tests {
.uri(req_uri)
.body("")?;
+ let (router, _) = Router::build(base, [("DUMMY", &trigger_route.into())])?;
+ let route_match = router.route("/base/foo/bar")?;
+
let default_headers =
- crate::compute_default_headers(req.uri(), trigger_route, base, host, client_addr)?;
+ crate::compute_default_headers(req.uri(), base, host, &route_match, client_addr)?;
assert_eq!(
- search(FULL_URL, &default_headers).unwrap(),
+ search(&FULL_URL, &default_headers).unwrap(),
"https://fermyon.dev/base/foo/bar?key1=value1&key2=value2".to_string()
);
assert_eq!(
- search(PATH_INFO, &default_headers).unwrap(),
+ search(&PATH_INFO, &default_headers).unwrap(),
"/bar".to_string()
);
assert_eq!(
- search(MATCHED_ROUTE, &default_headers).unwrap(),
+ search(&MATCHED_ROUTE, &default_headers).unwrap(),
"/base/foo/...".to_string()
);
assert_eq!(
- search(BASE_PATH, &default_headers).unwrap(),
+ search(&BASE_PATH, &default_headers).unwrap(),
"/base".to_string()
);
assert_eq!(
- search(RAW_COMPONENT_ROUTE, &default_headers).unwrap(),
+ search(&RAW_COMPONENT_ROUTE, &default_headers).unwrap(),
"/foo/...".to_string()
);
assert_eq!(
- search(COMPONENT_ROUTE, &default_headers).unwrap(),
+ search(&COMPONENT_ROUTE, &default_headers).unwrap(),
"/foo".to_string()
);
assert_eq!(
- search(CLIENT_ADDR, &default_headers).unwrap(),
+ search(&CLIENT_ADDR, &default_headers).unwrap(),
"127.0.0.1:8777".to_string()
);
@@ -839,43 +836,114 @@ mod tests {
.uri(req_uri)
.body("")?;
+ let (router, _) = Router::build(base, [("DUMMY", &trigger_route.into())])?;
+ let route_match = router.route("/foo/bar")?;
+
let default_headers =
- crate::compute_default_headers(req.uri(), trigger_route, base, host, client_addr)?;
+ crate::compute_default_headers(req.uri(), base, host, &route_match, client_addr)?;
// TODO: we currently replace the scheme with HTTP. When TLS is supported, this should be fixed.
assert_eq!(
- search(FULL_URL, &default_headers).unwrap(),
+ search(&FULL_URL, &default_headers).unwrap(),
"https://fermyon.dev/foo/bar?key1=value1&key2=value2".to_string()
);
assert_eq!(
- search(PATH_INFO, &default_headers).unwrap(),
+ search(&PATH_INFO, &default_headers).unwrap(),
"/bar".to_string()
);
assert_eq!(
- search(MATCHED_ROUTE, &default_headers).unwrap(),
+ search(&MATCHED_ROUTE, &default_headers).unwrap(),
"/foo/...".to_string()
);
assert_eq!(
- search(BASE_PATH, &default_headers).unwrap(),
+ search(&BASE_PATH, &default_headers).unwrap(),
"/".to_string()
);
assert_eq!(
- search(RAW_COMPONENT_ROUTE, &default_headers).unwrap(),
+ search(&RAW_COMPONENT_ROUTE, &default_headers).unwrap(),
"/foo/...".to_string()
);
assert_eq!(
- search(COMPONENT_ROUTE, &default_headers).unwrap(),
+ search(&COMPONENT_ROUTE, &default_headers).unwrap(),
"/foo".to_string()
);
assert_eq!(
- search(CLIENT_ADDR, &default_headers).unwrap(),
+ search(&CLIENT_ADDR, &default_headers).unwrap(),
+ "127.0.0.1:8777".to_string()
+ );
+
+ Ok(())
+ }
+
+ #[test]
+ fn test_default_headers_with_named_wildcards() -> Result<()> {
+ let scheme = "https";
+ let host = "fermyon.dev";
+ let base = "/";
+ let trigger_route = "/foo/:userid/...";
+ let component_path = "/foo";
+ let path_info = "/bar";
+ let client_addr: SocketAddr = "127.0.0.1:8777".parse().unwrap();
+
+ let req_uri = format!(
+ "{}://{}{}/42{}?key1=value1&key2=value2",
+ scheme, host, component_path, path_info
+ );
+
+ let req = http::Request::builder()
+ .method("POST")
+ .uri(req_uri)
+ .body("")?;
+
+ let (router, _) = Router::build(base, [("DUMMY", &trigger_route.into())])?;
+ let route_match = router.route("/foo/42/bar")?;
+
+ let default_headers =
+ crate::compute_default_headers(req.uri(), base, host, &route_match, client_addr)?;
+
+ // TODO: we currently replace the scheme with HTTP. When TLS is supported, this should be fixed.
+ assert_eq!(
+ search(&FULL_URL, &default_headers).unwrap(),
+ "https://fermyon.dev/foo/42/bar?key1=value1&key2=value2".to_string()
+ );
+ assert_eq!(
+ search(&PATH_INFO, &default_headers).unwrap(),
+ "/bar".to_string()
+ );
+ assert_eq!(
+ search(&MATCHED_ROUTE, &default_headers).unwrap(),
+ "/foo/:userid/...".to_string()
+ );
+ assert_eq!(
+ search(&BASE_PATH, &default_headers).unwrap(),
+ "/".to_string()
+ );
+ assert_eq!(
+ search(&RAW_COMPONENT_ROUTE, &default_headers).unwrap(),
+ "/foo/:userid/...".to_string()
+ );
+ assert_eq!(
+ search(&COMPONENT_ROUTE, &default_headers).unwrap(),
+ "/foo/:userid".to_string()
+ );
+ assert_eq!(
+ search(&CLIENT_ADDR, &default_headers).unwrap(),
"127.0.0.1:8777".to_string()
);
+ assert_eq!(
+ search(
+ &["SPIN_PATH_MATCH_USERID", "X_PATH_MATCH_USERID"],
+ &default_headers
+ )
+ .unwrap(),
+ "42".to_string()
+ );
+
Ok(())
}
- fn search<'a>(keys: &'a [&'a str], headers: &[(&[&str], String)]) -> Option<String> {
+ fn search(keys: &[&str; 2], headers: &[([String; 2], String)]) -> Option<String> {
let mut res: Option<String> = None;
for (k, v) in headers {
if k[0] == keys[0] && k[1] == keys[1] {
diff --git a/crates/trigger-http/src/wagi.rs b/crates/trigger-http/src/wagi.rs
index 755968f8d6..0cb0202006 100644
--- a/crates/trigger-http/src/wagi.rs
+++ b/crates/trigger-http/src/wagi.rs
@@ -6,7 +6,7 @@ use async_trait::async_trait;
use http_body_util::BodyExt;
use hyper::{Request, Response};
use spin_core::WasiVersion;
-use spin_http::{config::WagiTriggerConfig, routes::RoutePattern, wagi};
+use spin_http::{config::WagiTriggerConfig, routes::RouteMatch, wagi};
use spin_trigger::TriggerAppEngine;
use tracing::{instrument, Level};
use wasi_common_preview1::{pipe::WritePipe, I32Exit};
@@ -20,16 +20,17 @@ pub struct WagiHttpExecutor {
#[async_trait]
impl HttpExecutor for WagiHttpExecutor {
- #[instrument(name = "spin_trigger_http.execute_wagi", skip_all, err(level = Level::INFO), fields(otel.name = format!("execute_wagi_component {}", component)))]
+ #[instrument(name = "spin_trigger_http.execute_wagi", skip_all, err(level = Level::INFO), fields(otel.name = format!("execute_wagi_component {}", route_match.component_id())))]
async fn execute(
&self,
engine: Arc<TriggerAppEngine<HttpTrigger>>,
- component: &str,
base: &str,
- raw_route: &str,
+ route_match: &RouteMatch,
req: Request<Body>,
client_addr: SocketAddr,
) -> Result<Response<Body>> {
+ let component = route_match.component_id();
+
tracing::trace!(
"Executing request using the Wagi executor for component {}",
component
@@ -55,14 +56,8 @@ impl HttpExecutor for WagiHttpExecutor {
// TODO
// The default host and TLS fields are currently hard-coded.
- let mut headers = wagi::build_headers(
- &RoutePattern::from(base, raw_route),
- &parts,
- len,
- client_addr,
- "default_host",
- false,
- );
+ let mut headers =
+ wagi::build_headers(route_match, &parts, len, client_addr, "default_host", false);
let default_host = http::HeaderValue::from_str("localhost")?;
let host = std::str::from_utf8(
@@ -78,7 +73,7 @@ impl HttpExecutor for WagiHttpExecutor {
// `PATH_INFO`, or `X_FULL_URL`).
// Note that this overrides any existing headers previously set by Wagi.
for (keys, val) in
- crate::compute_default_headers(&parts.uri, raw_route, base, host, client_addr)?
+ crate::compute_default_headers(&parts.uri, base, host, route_match, client_addr)?
{
headers.insert(keys[1].to_string(), val);
}
| 2,464
|
[
"1923"
] |
diff --git a/tests/integration.rs b/tests/integration.rs
index 9e30952a35..1a4fe2acbe 100644
--- a/tests/integration.rs
+++ b/tests/integration.rs
@@ -1273,6 +1273,41 @@ route = "/..."
Ok(())
}
+ #[test]
+ fn test_http_routing() -> anyhow::Result<()> {
+ run_test(
+ "http-routing",
+ SpinAppType::Http,
+ [],
+ testing_framework::ServicesConfig::none(),
+ move |env| {
+ let spin = env.runtime_mut();
+ assert_spin_request(
+ spin,
+ Request::full(Method::GET, "/users/42", &[], Some("")),
+ Response::new_with_body(200, "42:"),
+ )?;
+ assert_spin_request(
+ spin,
+ Request::full(Method::GET, "/users/42/", &[], Some("")),
+ Response::new_with_body(200, "42:/"),
+ )?;
+ assert_spin_request(
+ spin,
+ Request::full(Method::GET, "/users/42/hello", &[], Some("")),
+ Response::new_with_body(200, "42:/hello"),
+ )?;
+ assert_spin_request(
+ spin,
+ Request::full(Method::GET, "/users/42/hello/", &[], Some("")),
+ Response::new_with_body(200, "42:/hello/"),
+ )?;
+ Ok(())
+ },
+ )?;
+ Ok(())
+ }
+
#[test]
fn test_outbound_post() -> anyhow::Result<()> {
run_test(
diff --git a/tests/test-components/components/Cargo.lock b/tests/test-components/components/Cargo.lock
index c181f6bea0..928df83f2d 100644
--- a/tests/test-components/components/Cargo.lock
+++ b/tests/test-components/components/Cargo.lock
@@ -287,6 +287,15 @@ dependencies = [
"itoa",
]
+[[package]]
+name = "http-routing"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "helper",
+ "spin-sdk 2.2.0",
+]
+
[[package]]
name = "id-arena"
version = "2.2.1"
diff --git a/tests/test-components/components/http-routing/Cargo.toml b/tests/test-components/components/http-routing/Cargo.toml
new file mode 100644
index 0000000000..e59ff4f225
--- /dev/null
+++ b/tests/test-components/components/http-routing/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+name = "http-routing"
+version = "0.1.0"
+edition = "2021"
+
+[lib]
+crate-type = ["cdylib"]
+
+[dependencies]
+anyhow = "1"
+helper = { path = "../../helper", default-features = false }
+spin-sdk = "2.2.0"
diff --git a/tests/test-components/components/http-routing/src/lib.rs b/tests/test-components/components/http-routing/src/lib.rs
new file mode 100644
index 0000000000..59591bee94
--- /dev/null
+++ b/tests/test-components/components/http-routing/src/lib.rs
@@ -0,0 +1,27 @@
+use anyhow::{anyhow, Result};
+use helper::ensure_some;
+use spin_sdk::{http_component, http::{Request, Response}};
+
+#[http_component]
+fn test_routing_headers(req: Request) -> Result<Response> {
+ test_routing_headers_impl(req).map_err(|e| anyhow!("{e}"))
+}
+
+fn test_routing_headers_impl(req: Request) -> Result<Response, String> {
+ let header_userid = req
+ .header("spin-path-match-userid")
+ .and_then(|v| v.as_str());
+ let header_userid = ensure_some!(header_userid);
+
+ let trailing = req
+ .header("spin-path-info")
+ .and_then(|v| v.as_str());
+ let trailing = ensure_some!(trailing);
+
+ let response = format!("{header_userid}:{trailing}");
+
+ Ok(Response::builder()
+ .status(200)
+ .body(response)
+ .build())
+}
diff --git a/tests/testcases/http-routing/spin.toml b/tests/testcases/http-routing/spin.toml
new file mode 100644
index 0000000000..547269fd6a
--- /dev/null
+++ b/tests/testcases/http-routing/spin.toml
@@ -0,0 +1,13 @@
+spin_manifest_version = 2
+
+[application]
+name = "http-routing"
+authors = ["Fermyon Engineering <engineering@fermyon.com>"]
+version = "0.1.0"
+
+[[trigger.http]]
+route = "/users/:userid/..."
+component = "http-routing"
+
+[component.http-routing]
+source = "%{source=http-routing}"
|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
d6b9713c311208a250185f326987f3dcf651517c
|
In `component.files`, mapping a single file to `/` gives an unhelpful error
The `component.files` section allows a directory or file to be mounted in the guest at a specific location, e.g. `{ source = "cat.jpg", destination = "/dog.jpg" }`.
If the destination is an illegal name for a file, such as `/`, an error occurs, but does not clearly point to the problem:
```
Error: Failed to load manifest from "spin.toml"
Caused by:
0: Failed to load Spin app from "spin.toml"
1: Failed to load component `favicon`
2: Failed to copy "/Users/vdice/code/github.com/benwis/benwis_spin/target/site/favicon.ico" to "/private/var/folders/nc/yfj0pylx4vzdr3s_66r129s00000gn/T/spinup-vQC7kb/assets/favicon/"
3: No such file or directory (os error 2)
```
It should say something like "`/` is not a valid destination file name."
|
2024-04-17T02:05:18Z
|
fermyon__spin-2460
|
fermyon/spin
|
3.2
|
diff --git a/crates/loader/src/local.rs b/crates/loader/src/local.rs
index f9d019c737..c6e122ab94 100644
--- a/crates/loader/src/local.rs
+++ b/crates/loader/src/local.rs
@@ -269,7 +269,8 @@ impl LocalLoader {
} => {
let src = Path::new(source);
let dest = dest_root.join(destination.trim_start_matches('/'));
- self.copy_file_or_directory(src, &dest, exclude_files).await
+ self.copy_file_or_directory(src, &dest, destination, exclude_files)
+ .await
}
}
}
@@ -291,7 +292,7 @@ impl LocalLoader {
.await?;
} else {
// "single/file.txt"
- self.copy_single_file(&path, &dest).await?;
+ self.copy_single_file(&path, &dest, glob_or_path).await?;
}
} else if looks_like_glob_pattern(glob_or_path) {
// "glob/pattern/*"
@@ -308,6 +309,7 @@ impl LocalLoader {
&self,
src: &Path,
dest: &Path,
+ guest_dest: &str,
exclude_files: &[String],
) -> Result<()> {
let src_path = self.app_root.join(src);
@@ -321,7 +323,7 @@ impl LocalLoader {
.await?;
} else {
// { source = "host/file.txt", destination = "guest/file.txt" }
- self.copy_single_file(&src_path, dest).await?;
+ self.copy_single_file(&src_path, dest, guest_dest).await?;
}
Ok(())
}
@@ -368,13 +370,14 @@ impl LocalLoader {
let relative_path = src.strip_prefix(src_prefix)?;
let dest = dest_root.join(relative_path);
- self.copy_single_file(&src, &dest).await?;
+ self.copy_single_file(&src, &dest, &relative_path.to_string_lossy())
+ .await?;
}
Ok(())
}
// Copy a single file from `src` to `dest`, creating parent directories.
- async fn copy_single_file(&self, src: &Path, dest: &Path) -> Result<()> {
+ async fn copy_single_file(&self, src: &Path, dest: &Path, guest_dest: &str) -> Result<()> {
// Sanity checks: src is in app_root...
src.strip_prefix(&self.app_root)?;
// ...and dest is in the Copy root.
@@ -394,17 +397,43 @@ impl LocalLoader {
quoted_path(&dest_parent)
)
})?;
- crate::fs::copy(src, dest).await.with_context(|| {
- format!(
- "Failed to copy {} to {}",
- quoted_path(src),
- quoted_path(dest)
- )
- })?;
+ crate::fs::copy(src, dest)
+ .await
+ .or_else(|e| Self::failed_to_copy_single_file_error(src, dest, guest_dest, e))?;
tracing::debug!("Copied {src:?} to {dest:?}");
Ok(())
}
+ fn failed_to_copy_single_file_error<T>(
+ src: &Path,
+ dest: &Path,
+ guest_dest: &str,
+ e: anyhow::Error,
+ ) -> anyhow::Result<T> {
+ let src_text = quoted_path(src);
+ let dest_text = quoted_path(dest);
+ let base_msg = format!("Failed to copy {src_text} to working path {dest_text}");
+
+ if let Some(io_error) = e.downcast_ref::<std::io::Error>() {
+ if Self::is_directory_like(guest_dest)
+ || io_error.kind() == std::io::ErrorKind::NotFound
+ {
+ return Err(anyhow::anyhow!(
+ r#""{guest_dest}" is not a valid destination file name"#
+ ))
+ .context(base_msg);
+ }
+ }
+
+ Err(e).with_context(|| format!("{base_msg} (for destination path \"{guest_dest}\")"))
+ }
+
+ /// Does a guest path appear to be a directory name, e.g. "/" or ".."? This is for guest
+ /// paths *only* and does not consider Windows separators.
+ fn is_directory_like(guest_path: &str) -> bool {
+ guest_path.ends_with('/') || guest_path.ends_with('.') || guest_path.ends_with("..")
+ }
+
// Resolve the given direct mount directory, checking that it is valid for
// direct mounting and returning its canonicalized source path.
async fn resolve_direct_mount(&self, mount: &WasiFilesMount) -> Result<ContentPath> {
@@ -584,3 +613,33 @@ fn warn_if_component_load_slothful() -> sloth::SlothGuard {
let message = "Loading Wasm components is taking a few seconds...";
sloth::warn_if_slothful(SLOTH_WARNING_DELAY_MILLIS, format!("{message}\n"))
}
+
+#[cfg(test)]
+mod test {
+ use super::*;
+
+ #[tokio::test]
+ async fn bad_destination_filename_is_explained() -> anyhow::Result<()> {
+ let app_root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+ .join("tests")
+ .join("file-errors");
+ let wd = tempfile::tempdir()?;
+ let loader = LocalLoader::new(
+ &app_root,
+ FilesMountStrategy::Copy(wd.path().to_owned()),
+ None,
+ )
+ .await?;
+ let err = loader
+ .load_file(app_root.join("bad.toml"))
+ .await
+ .expect_err("loader should not have succeeded");
+ let err_ctx = format!("{err:#}");
+ assert!(
+ err_ctx.contains(r#""/" is not a valid destination file name"#),
+ "expected error to show destination file name but got {}",
+ err_ctx
+ );
+ Ok(())
+ }
+}
| 2,460
|
[
"2361"
] |
diff --git a/crates/loader/tests/file-errors/bad.toml b/crates/loader/tests/file-errors/bad.toml
new file mode 100644
index 0000000000..3da28e46fc
--- /dev/null
+++ b/crates/loader/tests/file-errors/bad.toml
@@ -0,0 +1,12 @@
+spin_manifest_version = 2
+
+[application]
+name = "file-errors"
+
+[[trigger.http]]
+route = "/..."
+component = "bad"
+
+[component.bad]
+source = "dummy.wasm.txt"
+files = [{ source = "host.txt", destination = "/" }]
diff --git a/crates/loader/tests/file-errors/dummy.wasm.txt b/crates/loader/tests/file-errors/dummy.wasm.txt
new file mode 100644
index 0000000000..00af6f9155
--- /dev/null
+++ b/crates/loader/tests/file-errors/dummy.wasm.txt
@@ -0,0 +1,1 @@
+This file needs to exist for manifests to validate, but is never used.
\ No newline at end of file
diff --git a/crates/loader/tests/file-errors/host.txt b/crates/loader/tests/file-errors/host.txt
new file mode 100644
index 0000000000..71e1133715
--- /dev/null
+++ b/crates/loader/tests/file-errors/host.txt
@@ -0,0 +1,1 @@
+Super excited for being copied from the host to the working directory!
|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
|
769d71efb1768f3f972ac47b5f05d41365b9a458
|
Create directory for `static-fileserver` template
When a user runs the `static-fileserver` template, it asks for the directory from which to serve files.
If that directory doesn't exist, it would be a nice touch to create it.
|
Implication is that `spin up` fails if the directory does not exist.
```
> spin up
Error: Failed to prepare configuration
Caused by:
0: Failed to collect file mounts for assets
1: Cannot place /Users/mikkel/code/temp/new_fileserver/assets: source must be a directory
```
We should improve that error message too!
I came here to add a similar issue. It seems you also get a confusing error even if you create a folder afterwords (ie: ./assets) but you don't put anything in it. Starting with a blank fileserver template, if I add the assets directory, but don't add anything into it, I get the following errors when trying to `spin up`
```shell
Error: Failed to load manifest from "spin.toml"
Caused by:
0: Failed to load Spin app from "spin.toml"
1: Failed to load component `test-fileserver`
2: Couldn't resolve `/private/var/folders/2v/tdl9yh_55ls951rm1f8mpf040000gn/T/spinup-cfMZ4R/assets/test-fileserver`
3: No such file or directory (os error 2)
```
however, if I `touch assets/index.html` and run it again, everything is fine. If I remove the index.html file, the error returns.
|
2024-03-21T20:08:16Z
|
fermyon__spin-2387
|
fermyon/spin
|
3.2
|
diff --git a/crates/templates/src/reader.rs b/crates/templates/src/reader.rs
index 9006c8a065..5e64739442 100644
--- a/crates/templates/src/reader.rs
+++ b/crates/templates/src/reader.rs
@@ -23,6 +23,7 @@ pub(crate) struct RawTemplateManifestV1 {
pub add_component: Option<RawTemplateVariant>,
pub parameters: Option<IndexMap<String, RawParameter>>,
pub custom_filters: Option<serde::de::IgnoredAny>, // kept for error messaging
+ pub outputs: Option<IndexMap<String, RawExtraOutput>>,
}
#[derive(Debug, Deserialize)]
@@ -45,6 +46,18 @@ pub(crate) struct RawParameter {
pub pattern: Option<String>,
}
+#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields, rename_all = "snake_case", tag = "action")]
+pub(crate) enum RawExtraOutput {
+ CreateDir(RawCreateDir),
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields, rename_all = "snake_case")]
+pub(crate) struct RawCreateDir {
+ pub path: String,
+}
+
pub(crate) fn parse_manifest_toml(text: impl AsRef<str>) -> anyhow::Result<RawTemplateManifest> {
toml::from_str(text.as_ref()).context("Failed to parse template manifest TOML")
}
diff --git a/crates/templates/src/renderer.rs b/crates/templates/src/renderer.rs
index 3aca99e408..faf0233ca3 100644
--- a/crates/templates/src/renderer.rs
+++ b/crates/templates/src/renderer.rs
@@ -20,6 +20,7 @@ pub(crate) enum RenderOperation {
AppendToml(PathBuf, TemplateContent),
MergeToml(PathBuf, MergeTarget, TemplateContent), // file to merge into, table to merge into, content to merge
WriteFile(PathBuf, TemplateContent),
+ CreateDirectory(PathBuf, std::sync::Arc<liquid::Template>),
}
pub(crate) enum MergeTarget {
@@ -75,6 +76,11 @@ impl RenderOperation {
let MergeTarget::Application(target_table) = target;
Ok(TemplateOutput::MergeToml(path, target_table, rendered_text))
}
+ Self::CreateDirectory(path, template) => {
+ let rendered = template.render(globals)?;
+ let path = path.join(rendered); // TODO: should we validate that `rendered` was relative?`
+ Ok(TemplateOutput::CreateDirectory(path))
+ }
}
}
}
diff --git a/crates/templates/src/run.rs b/crates/templates/src/run.rs
index 928de175c2..cbde4dda6d 100644
--- a/crates/templates/src/run.rs
+++ b/crates/templates/src/run.rs
@@ -12,7 +12,7 @@ use crate::{
cancellable::Cancellable,
interaction::{InteractionStrategy, Interactive, Silent},
renderer::MergeTarget,
- template::TemplateVariantInfo,
+ template::{ExtraOutputAction, TemplateVariantInfo},
};
use crate::{
renderer::{RenderOperation, TemplateContent, TemplateRenderer},
@@ -118,7 +118,14 @@ impl Run {
.map(|(id, path)| self.snippet_operation(id, path))
.collect::<anyhow::Result<Vec<_>>>()?;
- let render_operations = files.into_iter().chain(snippets).collect();
+ let extras = self
+ .template
+ .extra_outputs()
+ .iter()
+ .map(|extra| self.extra_operation(extra))
+ .collect::<anyhow::Result<Vec<_>>>()?;
+
+ let render_operations = files.into_iter().chain(snippets).chain(extras).collect();
match interaction.populate_parameters(self) {
Cancellable::Ok(parameter_values) => {
@@ -292,6 +299,17 @@ impl Run {
}
}
+ fn extra_operation(&self, extra: &ExtraOutputAction) -> anyhow::Result<RenderOperation> {
+ match extra {
+ ExtraOutputAction::CreateDirectory(_, template) => {
+ Ok(RenderOperation::CreateDirectory(
+ self.options.output_path.clone(),
+ template.clone(),
+ ))
+ }
+ }
+ }
+
fn list_content_files(from: &Path) -> anyhow::Result<Vec<PathBuf>> {
let walker = WalkDir::new(from);
let files = walker
diff --git a/crates/templates/src/template.rs b/crates/templates/src/template.rs
index 6b6f227fbe..0de9c5ab2f 100644
--- a/crates/templates/src/template.rs
+++ b/crates/templates/src/template.rs
@@ -9,7 +9,10 @@ use regex::Regex;
use crate::{
constraints::StringConstraints,
- reader::{RawParameter, RawTemplateManifest, RawTemplateManifestV1, RawTemplateVariant},
+ reader::{
+ RawExtraOutput, RawParameter, RawTemplateManifest, RawTemplateManifestV1,
+ RawTemplateVariant,
+ },
run::{Run, RunOptions},
store::TemplateLayout,
};
@@ -24,6 +27,7 @@ pub struct Template {
trigger: TemplateTriggerCompatibility,
variants: HashMap<TemplateVariantKind, TemplateVariant>,
parameters: Vec<TemplateParameter>,
+ extra_outputs: Vec<ExtraOutputAction>,
snippets_dir: Option<PathBuf>,
content_dir: Option<PathBuf>, // TODO: maybe always need a spin.toml file in there?
}
@@ -113,6 +117,18 @@ pub(crate) struct TemplateParameter {
default_value: Option<String>,
}
+pub(crate) enum ExtraOutputAction {
+ CreateDirectory(String, std::sync::Arc<liquid::Template>),
+}
+
+impl std::fmt::Debug for ExtraOutputAction {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::CreateDirectory(orig, _) => f.debug_tuple("CreateDirectory").field(orig).finish(),
+ }
+ }
+}
+
impl Template {
pub(crate) fn load_from(layout: &TemplateLayout) -> anyhow::Result<Self> {
let manifest_path = layout.manifest_path();
@@ -155,6 +171,7 @@ impl Template {
trigger: Self::parse_trigger_type(raw.trigger_type, layout),
variants: Self::parse_template_variants(raw.new_application, raw.add_component),
parameters: Self::parse_parameters(&raw.parameters)?,
+ extra_outputs: Self::parse_extra_outputs(&raw.outputs)?,
snippets_dir,
content_dir,
},
@@ -237,6 +254,10 @@ impl Template {
self.parameters.iter().find(|p| p.id == name.as_ref())
}
+ pub(crate) fn extra_outputs(&self) -> &[ExtraOutputAction] {
+ &self.extra_outputs
+ }
+
pub(crate) fn content_dir(&self) -> &Option<PathBuf> {
&self.content_dir
}
@@ -343,6 +364,18 @@ impl Template {
}
}
+ fn parse_extra_outputs(
+ raw: &Option<IndexMap<String, RawExtraOutput>>,
+ ) -> anyhow::Result<Vec<ExtraOutputAction>> {
+ match raw {
+ None => Ok(vec![]),
+ Some(parameters) => parameters
+ .iter()
+ .map(|(k, v)| ExtraOutputAction::from_raw(k, v))
+ .collect(),
+ }
+ }
+
pub(crate) fn included_files(
&self,
base: &std::path::Path,
@@ -460,6 +493,20 @@ impl TemplateParameterDataType {
}
}
+impl ExtraOutputAction {
+ fn from_raw(id: &str, raw: &RawExtraOutput) -> anyhow::Result<Self> {
+ Ok(match raw {
+ RawExtraOutput::CreateDir(create) => {
+ let path_template =
+ liquid::Parser::new().parse(&create.path).with_context(|| {
+ format!("Template error: output {id} is not a valid template")
+ })?;
+ Self::CreateDirectory(create.path.clone(), std::sync::Arc::new(path_template))
+ }
+ })
+ }
+}
+
impl TemplateVariant {
pub(crate) fn skip_file(&self, base: &std::path::Path, path: &std::path::Path) -> bool {
self.skip_files
diff --git a/crates/templates/src/writer.rs b/crates/templates/src/writer.rs
index d896fcfc70..2b35c45373 100644
--- a/crates/templates/src/writer.rs
+++ b/crates/templates/src/writer.rs
@@ -10,6 +10,7 @@ pub(crate) enum TemplateOutput {
WriteFile(PathBuf, Vec<u8>),
AppendToml(PathBuf, String),
MergeToml(PathBuf, &'static str, String), // only have to worry about merging into root table for now
+ CreateDirectory(PathBuf),
}
impl TemplateOutputs {
@@ -57,6 +58,11 @@ impl TemplateOutput {
.await
.with_context(|| format!("Can't save changes to {}", path.display()))?;
}
+ TemplateOutput::CreateDirectory(dir) => {
+ tokio::fs::create_dir_all(dir)
+ .await
+ .with_context(|| format!("Failed to create directory {}", dir.display()))?;
+ }
}
Ok(())
}
diff --git a/templates/static-fileserver/metadata/spin-template.toml b/templates/static-fileserver/metadata/spin-template.toml
index 00ae333541..a700ad135f 100644
--- a/templates/static-fileserver/metadata/spin-template.toml
+++ b/templates/static-fileserver/metadata/spin-template.toml
@@ -14,3 +14,6 @@ component = "component.txt"
project-description = { type = "string", prompt = "Description", default = "" }
http-path = { type = "string", prompt = "HTTP path", default = "/static/...", pattern = "^/\\S*$" }
files-path = { type = "string", prompt = "Directory containing the files to serve", default = "assets", pattern = "^\\S+$" }
+
+[outputs]
+create_asset_directory = { action = "create_dir", path = "{{ files-path }}" }
| 2,387
|
[
"1022"
] |
diff --git a/crates/templates/src/test_built_ins/mod.rs b/crates/templates/src/test_built_ins/mod.rs
index ef32188fdb..aa018a984b 100644
--- a/crates/templates/src/test_built_ins/mod.rs
+++ b/crates/templates/src/test_built_ins/mod.rs
@@ -15,7 +15,53 @@ impl ProgressReporter for DiscardingReporter {
}
#[tokio::test]
-async fn add_fileserver_does_not_create_dir() -> anyhow::Result<()> {
+async fn new_fileserver_creates_assets_dir() -> anyhow::Result<()> {
+ let built_ins_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..");
+ let built_ins_src = TemplateSource::File(built_ins_dir);
+
+ let store_dir = tempfile::tempdir()?;
+ let store = store::TemplateStore::new(store_dir.path());
+ let manager = TemplateManager::new(store);
+
+ manager
+ .install(
+ &built_ins_src,
+ &InstallOptions::default(),
+ &DiscardingReporter,
+ )
+ .await?;
+
+ let app_dir = tempfile::tempdir()?;
+
+ // Create an app to add the fileserver into
+ let new_fs_options = RunOptions {
+ variant: TemplateVariantInfo::NewApplication,
+ name: "fs".to_owned(),
+ output_path: app_dir.path().join("fs"),
+ values: HashMap::new(),
+ accept_defaults: true,
+ no_vcs: false,
+ };
+ manager
+ .get("static-fileserver")?
+ .expect("static-fileserver template should exist")
+ .run(new_fs_options)
+ .silent()
+ .await?;
+
+ assert!(
+ app_dir.path().join("fs").exists(),
+ "fs dir should have been created"
+ );
+ assert!(
+ app_dir.path().join("fs").join("assets").exists(),
+ "fs/assets dir should have been created"
+ );
+ Ok(())
+}
+
+#[tokio::test]
+async fn add_fileserver_creates_assets_dir() -> anyhow::Result<()> {
let built_ins_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..");
let built_ins_src = TemplateSource::File(built_ins_dir);
@@ -49,13 +95,15 @@ async fn add_fileserver_does_not_create_dir() -> anyhow::Result<()> {
.silent()
.await?;
+ let fs_settings = HashMap::from_iter([("files-path".to_owned(), "moarassets".to_owned())]);
+
// Add the fileserver to that app
let manifest_path = app_dir.path().join("spin.toml");
let add_fs_options = RunOptions {
variant: TemplateVariantInfo::AddComponent { manifest_path },
name: "fs".to_owned(),
output_path: app_dir.path().join("fs"),
- values: HashMap::new(),
+ values: fs_settings,
accept_defaults: true,
no_vcs: false,
};
@@ -68,8 +116,12 @@ async fn add_fileserver_does_not_create_dir() -> anyhow::Result<()> {
// Finally!
assert!(
- !app_dir.path().join("fs").exists(),
- "<app_dir>/fs should not have been created"
+ app_dir.path().join("fs").exists(),
+ "<app_dir>/fs should have been created"
+ );
+ assert!(
+ app_dir.path().join("fs").join("moarassets").exists(),
+ "<app_dir>/fs/moarassets should have been created"
);
Ok(())
}
|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
0df6fe6f3866b3eea7f4b3470e1b874a3d0a72d6
|
Cyclic dependency (sometimes) may break Rust Analyzer
This is the error I am seeing when opening the Spin workspace:
```
[ERROR project_model::workspace] cyclic deps:
spin_trigger_http(Idx::<CrateData>(562)) ->
spin_testing(Idx::<CrateData>(560)), alternative path: spin_testing(Idx::<CrateData>(560)) ->
spin_trigger_http(Idx::<CrateData>(562))\n"
```
Rust Analyzer sometimes recovers and is able to work, but not sure if the cyclic dependency is something we should address.
|
2024-03-18T23:37:23Z
|
fermyon__spin-2375
|
fermyon/spin
|
3.2
|
diff --git a/Cargo.lock b/Cargo.lock
index 2b857cbac1..13bd06bd6b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6377,7 +6377,6 @@ dependencies = [
"spin-core",
"spin-http",
"spin-trigger",
- "spin-trigger-http",
"tokio",
"tracing-subscriber",
]
| 2,375
|
[
"2253"
] |
diff --git a/crates/testing/Cargo.toml b/crates/testing/Cargo.toml
index e6ba33bac7..45204df15d 100644
--- a/crates/testing/Cargo.toml
+++ b/crates/testing/Cargo.toml
@@ -13,7 +13,6 @@ serde_json = "1"
spin-app = { path = "../app" }
spin-core = { path = "../core" }
spin-http = { path = "../http" }
-spin-trigger-http = { path = "../trigger-http" }
spin-trigger = { path = "../trigger" }
tokio = { version = "1", features = ["macros", "rt"] }
tracing-subscriber = "0.3"
|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
|
6178b24de08252072352e5c6ac9d77827f2a155a
|
`spin up --build --help` incorrectly builds the application
When passing both `--build` and `--help` to spin up, the application builds _while also showing help output_ - you can see this in the details block below. One would expect the application to not build, but instead only show the help output 😅 (although admittedly this is an amusing issue to write).
<details>
<summary>
$ spin up --build --help
</summary>
```console
$ spin up --build --help
spin-up
Start the Spin application
USAGE:
spin up [OPTIONS]
OPTIONS:
--build For local apps, specifies to perform `spin build` before running the
application [env: SPIN_ALWAYS_BUILD=]
--direct-mounts For local apps with directory mounts and no excluded files, mount
them directly instead of using a temporary directory
-e, --env <ENV> Pass an environment variable (key=value) to all components of the
application
-f, --from <APPLICATION> The application to run. This may be a manifest (spin.toml) file, a
directory containing a spin.toml file, or a remote registry
reference. If omitted, it defaults to "spin.toml"
-h, --help
-k, --insecure Ignore server certificate errors from a registry
--temp <TMP> Temporary directory for the static assets of the components
Building component hello-starling with `npm run build`
> starling-js-app@1.0.0 build
> npx webpack --mode=production && npx mkdirp target && ./tools/componentize.sh ./dist/spin.js ./target/hello-starling.wasm
asset spin.js 3.53 KiB [compared for emit] (name: main)
./src/index.ts 3 KiB [built] [code generated]
webpack 5.90.3 compiled successfully in 628 ms
Finished building all Spin components
HTTP TRIGGER OPTIONS:
--allow-transient-write
Set the static assets of the components in the temporary directory as writable
--cache <WASMTIME_CACHE_FILE>
Wasmtime cache configuration file
[env: WASMTIME_CACHE_FILE=]
--disable-cache
Disable Wasmtime cache
[env: DISABLE_WASMTIME_CACHE=]
--disable-pooling
Disable Wasmtime's pooling instance allocator
--follow <FOLLOW_ID>
Print output to stdout/stderr only for given component(s)
--key-value <KEY_VALUES>
Set a key/value pair (key=value) in the application's default store. Any existing value
will be overwritten. Can be used multiple times
-L, --log-dir <APP_LOG_DIR>
Log directory for the stdout and stderr of components. Setting to the empty string
disables logging to disk
[env: SPIN_LOG_DIR=]
--listen <ADDRESS>
IP address and port to listen on
[default: 127.0.0.1:3000]
-q, --quiet
Silence all component output to stdout/stderr
--runtime-config-file <RUNTIME_CONFIG_FILE>
Configuration file for config providers and wasmtime config
[env: RUNTIME_CONFIG_FILE=]
--sqlite <SQLITE_STATEMENTS>
Run a SQLite statement such as a migration against the default database. To run from a
file, prefix the filename with @ e.g. spin up --sqlite @migration.sql
--state-dir <STATE_DIR>
Set the application state directory path. This is used in the default locations for
logs, key value stores, etc.
For local apps, this defaults to `.spin/` relative to the `spin.toml` file. For remote
apps, this has no default (unset). Passing an empty value forces the value to be unset.
--tls-cert <TLS_CERT>
The path to the certificate to use for https, if this is not set, normal http will be
used. The cert should be in PEM format
[env: SPIN_TLS_CERT=]
--tls-key <TLS_KEY>
The path to the certificate key to use for https, if this is not set, normal http will
be used. The key should be in PKCS#8 format
[env: SPIN_TLS_KEY=]
```
</details>
|
2024-03-05T17:09:39Z
|
fermyon__spin-2324
|
fermyon/spin
|
3.2
|
diff --git a/src/commands/up.rs b/src/commands/up.rs
index ee6fbe30c1..d66d7930ba 100644
--- a/src/commands/up.rs
+++ b/src/commands/up.rs
@@ -151,10 +151,6 @@ impl UpCommand {
}
}
- if self.build {
- app_source.build().await?;
- }
-
// Get working dir holder and hold on to it for the rest of the function.
// If the working dir is a temporary dir it will be deleted on drop.
let working_dir_holder = self.get_canonical_working_dir()?;
@@ -186,6 +182,10 @@ impl UpCommand {
return Ok(());
}
+ if self.build {
+ app_source.build().await?;
+ }
+
let mut locked_app = self
.load_resolved_app_source(resolved_app_source, &working_dir)
.await?;
| 2,324
|
[
"2323"
] |
diff --git a/tests/integration.rs b/tests/integration.rs
index eb4e3db16c..330c3161d3 100644
--- a/tests/integration.rs
+++ b/tests/integration.rs
@@ -662,6 +662,47 @@ route = "/..."
Ok(())
}
+ #[test]
+ fn spin_up_help_build_does_not_build() -> anyhow::Result<()> {
+ let env = testing_framework::TestEnvironment::<()>::boot(
+ &testing_framework::ServicesConfig::none(),
+ )?;
+
+ // We still don't see full help if there are no components.
+ let toml_text = r#"spin_version = "1"
+name = "unbuilt"
+trigger = { type = "http" }
+version = "0.1.0"
+[[component]]
+id = "unbuilt"
+source = "fake.wasm"
+[component.build]
+command = "echo should_not_print"
+[component.trigger]
+route = "/..."
+"#;
+ env.write_file("spin.toml", toml_text)?;
+ env.write_file("fake.wasm", [])?;
+
+ testing_framework::runtimes::spin_cli::SpinCli::start(
+ &spin_binary(),
+ &env,
+ Vec::<String>::new(),
+ SpinAppType::None,
+ )?;
+
+ let mut up = std::process::Command::new(spin_binary());
+ up.args(["up", "--build", "--help"]);
+ let output = env.run_in(&mut up)?;
+
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(stdout.contains("--quiet"));
+ assert!(stdout.contains("--listen"));
+ assert!(!stdout.contains("should_not_print"));
+
+ Ok(())
+ }
+
// TODO: Test on Windows
#[cfg(not(target_os = "windows"))]
#[test]
|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
|
b3cfbba3ea576a4094122e04bc287458e5dbe920
|
Configurable allowed outbound hosts based on application variables
I have the following setup: the host I need my application to send outbound connections to is an application variable that is set at runtime through an application variable.
Is there a way to use a (or more) variable(s) to configure an allowed outbound host?
```toml
[variables]
my_host = { default = "http://localhost" }
my_port = { default = "5003" }
[[trigger.http]]
route = "/checkout/..."
component = "checkout"
[component.checkout]
source = "checkout/target/checkout.wasm"
allowed_outbound_hosts = [
"{{ my_host }}:{{ my_port }}",
]
```
|
I tried tackling this for #653 a while ago but realized that this would require some major design changes to the variables subsystem. One question is whether these settings should update if the interpolated values from a dynamic variables provider update. On top of that the current implementation just makes it hard to get the values where you need them.
Then I need to ship(even git-commit!!) my redis credentials with spin.toml. Sad :crying_cat_face:
https://discord.com/channels/926888690310053918/950022897160839248/1210028950185574410
After add my redis credential into spin.toml, now i need to add my libsql's password into spin.toml.
Eventually my spin.toml is full of my api keys and passwords.
Is there anyway I can avoid writing all my credentials in spin.toml?
Correction. My libsql credentials goes to "runtime-config.toml" not spin.toml.
This is certainly an issue. Thinking out loud here: I wonder if a good next feature would be to allow environment variable interpolation when we resolve these configuration options. My worry with that is whether there are some config options where `$` or `${}` already have meaning.
@rylev That would require adding environment variables to Cloud too (which is no bad thing of course, just noting it).
|
2024-02-27T05:35:10Z
|
fermyon__spin-2299
|
fermyon/spin
|
3.2
|
diff --git a/Cargo.lock b/Cargo.lock
index 6448dcb92f..2b8e78ec5d 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4257,6 +4257,7 @@ dependencies = [
"reqwest",
"spin-app",
"spin-core",
+ "spin-expressions",
"spin-locked-app",
"spin-outbound-networking",
"spin-world",
@@ -4273,6 +4274,7 @@ dependencies = [
"rumqttc",
"spin-app",
"spin-core",
+ "spin-expressions",
"spin-outbound-networking",
"spin-world",
"table",
@@ -4290,6 +4292,7 @@ dependencies = [
"mysql_common",
"spin-app",
"spin-core",
+ "spin-expressions",
"spin-outbound-networking",
"spin-world",
"table",
@@ -4307,6 +4310,7 @@ dependencies = [
"postgres-native-tls",
"spin-app",
"spin-core",
+ "spin-expressions",
"spin-outbound-networking",
"spin-world",
"table",
@@ -4323,6 +4327,7 @@ dependencies = [
"redis 0.21.7",
"spin-app",
"spin-core",
+ "spin-expressions",
"spin-outbound-networking",
"spin-world",
"table",
@@ -5885,6 +5890,7 @@ dependencies = [
"spin-build",
"spin-common",
"spin-doctor",
+ "spin-expressions",
"spin-http",
"spin-key-value",
"spin-key-value-sqlite",
@@ -5998,6 +6004,22 @@ dependencies = [
"ui-testing",
]
+[[package]]
+name = "spin-expressions"
+version = "2.4.0-pre0"
+dependencies = [
+ "anyhow",
+ "async-trait",
+ "dotenvy",
+ "once_cell",
+ "serde",
+ "spin-app",
+ "thiserror",
+ "tokio",
+ "toml 0.5.11",
+ "vaultrs",
+]
+
[[package]]
name = "spin-http"
version = "2.4.0-pre0"
@@ -6225,6 +6247,7 @@ version = "2.4.0-pre0"
dependencies = [
"anyhow",
"ipnet",
+ "spin-expressions",
"spin-locked-app",
"terminal",
"url",
@@ -6383,6 +6406,7 @@ dependencies = [
"spin-common",
"spin-componentize",
"spin-core",
+ "spin-expressions",
"spin-key-value",
"spin-key-value-azure",
"spin-key-value-redis",
@@ -6460,6 +6484,7 @@ dependencies = [
"serde",
"spin-app",
"spin-core",
+ "spin-expressions",
"spin-testing",
"spin-trigger",
"spin-world",
@@ -6477,6 +6502,7 @@ dependencies = [
"serde",
"spin-app",
"spin-core",
+ "spin-expressions",
"spin-world",
"thiserror",
"tokio",
diff --git a/Cargo.toml b/Cargo.toml
index 56dc91228a..4a3806513e 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -54,6 +54,7 @@ spin-app = { path = "crates/app" }
spin-build = { path = "crates/build" }
spin-common = { path = "crates/common" }
spin-doctor = { path = "crates/doctor" }
+spin-expressions = { path = "crates/expressions" }
spin-http = { path = "crates/http" }
spin-loader = { path = "crates/loader" }
spin-locked-app = { path = "crates/locked-app" }
diff --git a/crates/expressions/Cargo.toml b/crates/expressions/Cargo.toml
new file mode 100644
index 0000000000..852b7ec561
--- /dev/null
+++ b/crates/expressions/Cargo.toml
@@ -0,0 +1,19 @@
+[package]
+name = "spin-expressions"
+version = { workspace = true }
+authors = { workspace = true }
+edition = { workspace = true }
+
+[dependencies]
+anyhow = "1.0"
+async-trait = "0.1"
+dotenvy = "0.15"
+once_cell = "1"
+spin-app = { path = "../app" }
+thiserror = "1"
+tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
+vaultrs = "0.6.2"
+serde = "1.0.188"
+
+[dev-dependencies]
+toml = "0.5"
diff --git a/crates/expressions/src/lib.rs b/crates/expressions/src/lib.rs
new file mode 100644
index 0000000000..89bf3715d7
--- /dev/null
+++ b/crates/expressions/src/lib.rs
@@ -0,0 +1,312 @@
+pub mod provider;
+mod template;
+
+use std::{borrow::Cow, collections::HashMap, fmt::Debug};
+
+use spin_app::Variable;
+
+pub use provider::Provider;
+use template::Part;
+pub use template::Template;
+
+/// A variable resolver.
+#[derive(Debug, Default)]
+pub struct Resolver {
+ // variable key -> variable
+ variables: HashMap<String, Variable>,
+ // component ID -> variable key -> variable value template
+ component_configs: HashMap<String, HashMap<String, Template>>,
+ providers: Vec<Box<dyn Provider>>,
+}
+
+#[derive(Default)]
+pub struct PreparedResolver {
+ variables: HashMap<String, String>,
+}
+
+pub type SharedPreparedResolver =
+ std::sync::Arc<std::sync::OnceLock<std::sync::Arc<PreparedResolver>>>;
+
+impl Resolver {
+ /// Creates a Resolver for the given Tree.
+ pub fn new(variables: impl IntoIterator<Item = (String, Variable)>) -> Result<Self> {
+ let variables: HashMap<_, _> = variables.into_iter().collect();
+ // Validate keys so that we can rely on them during resolution
+ variables.keys().try_for_each(|key| Key::validate(key))?;
+ Ok(Self {
+ variables,
+ component_configs: Default::default(),
+ providers: Default::default(),
+ })
+ }
+
+ /// Adds component variable values to the Resolver.
+ pub fn add_component_variables(
+ &mut self,
+ component_id: impl Into<String>,
+ variables: impl IntoIterator<Item = (String, String)>,
+ ) -> Result<()> {
+ let component_id = component_id.into();
+ let templates = variables
+ .into_iter()
+ .map(|(key, val)| {
+ // Validate variable keys so that we can rely on them during resolution
+ Key::validate(&key)?;
+ let template = self.validate_template(val)?;
+ Ok((key, template))
+ })
+ .collect::<Result<_>>()?;
+
+ self.component_configs.insert(component_id, templates);
+
+ Ok(())
+ }
+
+ /// Adds a variable Provider to the Resolver.
+ pub fn add_provider(&mut self, provider: Box<dyn Provider>) {
+ self.providers.push(provider);
+ }
+
+ /// Resolves a variable value for the given path.
+ pub async fn resolve(&self, component_id: &str, key: Key<'_>) -> Result<String> {
+ let configs = self.component_configs.get(component_id).ok_or_else(|| {
+ Error::Undefined(format!("no variable for component {component_id:?}"))
+ })?;
+
+ let key = key.as_ref();
+ let template = configs
+ .get(key)
+ .ok_or_else(|| Error::Undefined(format!("no variable for {component_id:?}.{key:?}")))?;
+
+ self.resolve_template(template).await
+ }
+
+ pub async fn resolve_template(&self, template: &Template) -> Result<String> {
+ let mut resolved_parts: Vec<Cow<str>> = Vec::with_capacity(template.parts().len());
+ for part in template.parts() {
+ resolved_parts.push(match part {
+ Part::Lit(lit) => lit.as_ref().into(),
+ Part::Expr(var) => self.resolve_variable(var).await?.into(),
+ });
+ }
+ Ok(resolved_parts.concat())
+ }
+
+ pub async fn prepare(&self) -> Result<PreparedResolver> {
+ let mut variables = HashMap::new();
+ for name in self.variables.keys() {
+ let value = self.resolve_variable(name).await?;
+ variables.insert(name.clone(), value);
+ }
+ Ok(PreparedResolver { variables })
+ }
+
+ async fn resolve_variable(&self, key: &str) -> Result<String> {
+ let var = self
+ .variables
+ .get(key)
+ // This should have been caught by validate_template
+ .ok_or_else(|| Error::InvalidName(key.to_string()))?;
+
+ for provider in &self.providers {
+ if let Some(value) = provider.get(&Key(key)).await.map_err(Error::Provider)? {
+ return Ok(value);
+ }
+ }
+
+ var.default.clone().ok_or_else(|| {
+ Error::Provider(anyhow::anyhow!(
+ "no provider resolved required variable {key:?}"
+ ))
+ })
+ }
+
+ fn validate_template(&self, template: String) -> Result<Template> {
+ let template = Template::new(template)?;
+ // Validate template variables are valid
+ template.parts().try_for_each(|part| match part {
+ Part::Expr(var) if !self.variables.contains_key(var.as_ref()) => {
+ Err(Error::InvalidTemplate(format!("unknown variable {var:?}")))
+ }
+ _ => Ok(()),
+ })?;
+ Ok(template)
+ }
+}
+
+impl PreparedResolver {
+ fn resolve_variable(&self, key: &str) -> Result<String> {
+ self.variables
+ .get(key)
+ .cloned()
+ .ok_or(Error::InvalidName(key.to_string()))
+ }
+
+ pub fn resolve_template(&self, template: &Template) -> Result<String> {
+ let mut resolved_parts: Vec<Cow<str>> = Vec::with_capacity(template.parts().len());
+ for part in template.parts() {
+ resolved_parts.push(match part {
+ Part::Lit(lit) => lit.as_ref().into(),
+ Part::Expr(var) => self.resolve_variable(var)?.into(),
+ });
+ }
+ Ok(resolved_parts.concat())
+ }
+}
+
+/// A variable key
+#[derive(Debug, PartialEq, Eq)]
+pub struct Key<'a>(&'a str);
+
+impl<'a> Key<'a> {
+ /// Creates a new Key.
+ pub fn new(key: &'a str) -> Result<Self> {
+ Self::validate(key)?;
+ Ok(Self(key))
+ }
+
+ pub fn as_str(&self) -> &str {
+ self.0
+ }
+
+ // To allow various (env var, file path) transformations:
+ // - must start with an ASCII letter
+ // - underscores are allowed; one at a time between other characters
+ // - all other characters must be ASCII alphanumeric
+ fn validate(key: &str) -> Result<()> {
+ {
+ if key.is_empty() {
+ Err("must not be empty".to_string())
+ } else if let Some(invalid) = key
+ .chars()
+ .find(|c| !(c.is_ascii_lowercase() || c.is_ascii_digit() || c == &'_'))
+ {
+ Err(format!("invalid character {:?}. Variable names may contain only lower-case letters, numbers, and underscores.", invalid))
+ } else if !key.bytes().next().unwrap().is_ascii_lowercase() {
+ Err("must start with a lowercase ASCII letter".to_string())
+ } else if !key.bytes().last().unwrap().is_ascii_alphanumeric() {
+ Err("must end with a lowercase ASCII letter or digit".to_string())
+ } else if key.contains("__") {
+ Err("must not contain multiple consecutive underscores".to_string())
+ } else {
+ Ok(())
+ }
+ }
+ .map_err(|reason| Error::InvalidName(format!("{key:?}: {reason}")))
+ }
+}
+
+impl<'a> AsRef<str> for Key<'a> {
+ fn as_ref(&self) -> &str {
+ self.0
+ }
+}
+
+type Result<T> = std::result::Result<T, Error>;
+
+/// A variable resolution error.
+#[derive(Debug, thiserror::Error)]
+pub enum Error {
+ /// Invalid variable name.
+ #[error("invalid variable name: {0}")]
+ InvalidName(String),
+
+ /// Invalid variable template.
+ #[error("invalid variable template: {0}")]
+ InvalidTemplate(String),
+
+ /// Variable provider error.
+ #[error("provider error: {0:?}")]
+ Provider(#[source] anyhow::Error),
+
+ /// Undefined variable.
+ #[error("undefined variable: {0}")]
+ Undefined(String),
+}
+
+#[cfg(test)]
+mod tests {
+ use async_trait::async_trait;
+
+ use super::*;
+
+ #[derive(Debug)]
+ struct TestProvider;
+
+ #[async_trait]
+ impl Provider for TestProvider {
+ async fn get(&self, key: &Key) -> anyhow::Result<Option<String>> {
+ match key.as_ref() {
+ "required" => Ok(Some("provider-value".to_string())),
+ "broken" => anyhow::bail!("broken"),
+ _ => Ok(None),
+ }
+ }
+ }
+
+ async fn test_resolve(template: &str) -> Result<String> {
+ let mut resolver = Resolver::new([
+ (
+ "required".into(),
+ Variable {
+ default: None,
+ secret: false,
+ },
+ ),
+ (
+ "default".into(),
+ Variable {
+ default: Some("default-value".into()),
+ secret: false,
+ },
+ ),
+ ])
+ .unwrap();
+ resolver
+ .add_component_variables("test-component", [("test_key".into(), template.into())])
+ .unwrap();
+ resolver.add_provider(Box::new(TestProvider));
+ resolver.resolve("test-component", Key("test_key")).await
+ }
+
+ #[tokio::test]
+ async fn resolve_static() {
+ assert_eq!(test_resolve("static-value").await.unwrap(), "static-value");
+ }
+
+ #[tokio::test]
+ async fn resolve_variable_default() {
+ assert_eq!(
+ test_resolve("prefix-{{ default }}-suffix").await.unwrap(),
+ "prefix-default-value-suffix"
+ );
+ }
+
+ #[tokio::test]
+ async fn resolve_variable_provider() {
+ assert_eq!(
+ test_resolve("prefix-{{ required }}-suffix").await.unwrap(),
+ "prefix-provider-value-suffix"
+ );
+ }
+
+ #[test]
+ fn keys_good() {
+ for key in ["a", "abc", "a1b2c3", "a_1", "a_1_b_3"] {
+ Key::new(key).expect(key);
+ }
+ }
+
+ #[test]
+ fn keys_bad() {
+ for key in ["", "aX", "1bc", "_x", "x.y", "x_", "a__b", "x-y"] {
+ Key::new(key).expect_err(key);
+ }
+ }
+
+ #[test]
+ fn template_literal() {
+ assert!(Template::new("hello").unwrap().is_literal());
+ assert!(!Template::new("hello {{ world }}").unwrap().is_literal());
+ }
+}
diff --git a/crates/expressions/src/provider.rs b/crates/expressions/src/provider.rs
new file mode 100644
index 0000000000..f0eec76ab6
--- /dev/null
+++ b/crates/expressions/src/provider.rs
@@ -0,0 +1,12 @@
+use std::fmt::Debug;
+
+use async_trait::async_trait;
+
+use crate::Key;
+
+/// A config provider.
+#[async_trait]
+pub trait Provider: Debug + Send + Sync {
+ /// Returns the value at the given config path, if it exists.
+ async fn get(&self, key: &Key) -> anyhow::Result<Option<String>>;
+}
diff --git a/crates/variables/src/template.rs b/crates/expressions/src/template.rs
similarity index 91%
rename from crates/variables/src/template.rs
rename to crates/expressions/src/template.rs
index 783834bf2d..694ee01f8a 100644
--- a/crates/variables/src/template.rs
+++ b/crates/expressions/src/template.rs
@@ -5,10 +5,12 @@ use crate::{Error, Result};
/// Template represents a simple string template that allows expressions in
/// double curly braces, similar to Mustache or Liquid.
#[derive(Clone, Debug, PartialEq)]
-pub(crate) struct Template(Vec<Part>);
+pub struct Template {
+ parts: Vec<Part>,
+}
impl Template {
- pub(crate) fn new(template: impl Into<Box<str>>) -> Result<Self> {
+ pub fn new(template: impl Into<Box<str>>) -> Result<Self> {
let mut parts = vec![];
let mut remainder: Box<str> = template.into();
while !remainder.is_empty() {
@@ -37,11 +39,15 @@ impl Template {
parts.push(part);
remainder = rest.into();
}
- Ok(Template(parts))
+ Ok(Template { parts })
+ }
+
+ pub fn is_literal(&self) -> bool {
+ self.parts.iter().all(|p| matches!(p, Part::Lit(_)))
}
pub(crate) fn parts(&self) -> std::slice::Iter<Part> {
- self.0.iter()
+ self.parts.iter()
}
}
diff --git a/crates/loader/src/local.rs b/crates/loader/src/local.rs
index 26dcf8bf6b..d8f1b3a9d4 100644
--- a/crates/loader/src/local.rs
+++ b/crates/loader/src/local.rs
@@ -124,7 +124,7 @@ impl LocalLoader {
let allowed_outbound_hosts = component
.normalized_allowed_outbound_hosts()
.context("`allowed_http_hosts` is malformed")?;
- let _ = spin_outbound_networking::AllowedHostsConfig::parse(&allowed_outbound_hosts)
+ spin_outbound_networking::AllowedHostsConfig::validate(&allowed_outbound_hosts)
.context("`allowed_outbound_hosts` is malformed")?;
let metadata = ValuesMapBuilder::new()
diff --git a/crates/outbound-http/Cargo.toml b/crates/outbound-http/Cargo.toml
index 81f8f86aea..cc3dee9f47 100644
--- a/crates/outbound-http/Cargo.toml
+++ b/crates/outbound-http/Cargo.toml
@@ -13,6 +13,7 @@ http = "0.2"
reqwest = { version = "0.11", features = ["gzip"] }
spin-app = { path = "../app", optional = true }
spin-core = { path = "../core", optional = true }
+spin-expressions = { path = "../expressions", optional = true }
spin-locked-app = { path = "../locked-app" }
spin-outbound-networking = { path = "../outbound-networking" }
spin-world = { path = "../world", optional = true }
@@ -22,4 +23,4 @@ url = "2.2.1"
[features]
default = ["runtime"]
-runtime = ["dep:spin-app", "dep:spin-core", "dep:spin-world"]
+runtime = ["dep:spin-app", "dep:spin-core", "dep:spin-expressions", "dep:spin-world"]
diff --git a/crates/outbound-http/src/host_component.rs b/crates/outbound-http/src/host_component.rs
index 1b489340d6..0fd60a05d9 100644
--- a/crates/outbound-http/src/host_component.rs
+++ b/crates/outbound-http/src/host_component.rs
@@ -7,7 +7,9 @@ use spin_world::v1::http;
use crate::host_impl::OutboundHttp;
-pub struct OutboundHttpComponent;
+pub struct OutboundHttpComponent {
+ pub resolver: spin_expressions::SharedPreparedResolver,
+}
impl HostComponent for OutboundHttpComponent {
type Data = OutboundHttp;
@@ -33,7 +35,7 @@ impl DynamicHostComponent for OutboundHttpComponent {
let hosts = component
.get_metadata(ALLOWED_HOSTS_KEY)?
.unwrap_or_default();
- data.allowed_hosts = AllowedHostsConfig::parse(&hosts)?;
+ data.allowed_hosts = AllowedHostsConfig::parse(&hosts, self.resolver.get().unwrap())?;
Ok(())
}
}
diff --git a/crates/outbound-mqtt/Cargo.toml b/crates/outbound-mqtt/Cargo.toml
index 82817b60af..ae6918b2ec 100644
--- a/crates/outbound-mqtt/Cargo.toml
+++ b/crates/outbound-mqtt/Cargo.toml
@@ -12,6 +12,7 @@ anyhow = "1.0"
rumqttc = { version = "0.24", features = ["url"] }
spin-app = { path = "../app" }
spin-core = { path = "../core" }
+spin-expressions = { path = "../expressions" }
spin-world = { path = "../world" }
spin-outbound-networking = { path = "../outbound-networking" }
table = { path = "../table" }
diff --git a/crates/outbound-mqtt/src/host_component.rs b/crates/outbound-mqtt/src/host_component.rs
index 52531b9d17..df242a54ba 100644
--- a/crates/outbound-mqtt/src/host_component.rs
+++ b/crates/outbound-mqtt/src/host_component.rs
@@ -4,7 +4,9 @@ use spin_core::HostComponent;
use crate::OutboundMqtt;
-pub struct OutboundMqttComponent;
+pub struct OutboundMqttComponent {
+ pub resolver: spin_expressions::SharedPreparedResolver,
+}
impl HostComponent for OutboundMqttComponent {
type Data = OutboundMqtt;
@@ -29,8 +31,11 @@ impl DynamicHostComponent for OutboundMqttComponent {
let hosts = component
.get_metadata(spin_outbound_networking::ALLOWED_HOSTS_KEY)?
.unwrap_or_default();
- data.allowed_hosts = spin_outbound_networking::AllowedHostsConfig::parse(&hosts)
- .context("`allowed_outbound_hosts` contained an invalid url")?;
+ data.allowed_hosts = spin_outbound_networking::AllowedHostsConfig::parse(
+ &hosts,
+ self.resolver.get().unwrap(),
+ )
+ .context("`allowed_outbound_hosts` contained an invalid url")?;
Ok(())
}
}
diff --git a/crates/outbound-mysql/Cargo.toml b/crates/outbound-mysql/Cargo.toml
index 607a6528b7..14a7de3464 100644
--- a/crates/outbound-mysql/Cargo.toml
+++ b/crates/outbound-mysql/Cargo.toml
@@ -18,6 +18,7 @@ mysql_async = { version = "0.33.0", default-features = false, features = [
mysql_common = { version = "0.31.0", default-features = false }
spin-app = { path = "../app" }
spin-core = { path = "../core" }
+spin-expressions = { path = "../expressions" }
spin-outbound-networking = { path = "../outbound-networking" }
spin-world = { path = "../world" }
table = { path = "../table" }
diff --git a/crates/outbound-mysql/src/lib.rs b/crates/outbound-mysql/src/lib.rs
index f44ac88a90..4d2a206a31 100644
--- a/crates/outbound-mysql/src/lib.rs
+++ b/crates/outbound-mysql/src/lib.rs
@@ -11,6 +11,10 @@ use std::sync::Arc;
use url::Url;
/// A simple implementation to support outbound mysql connection
+pub struct OutboundMysqlComponent {
+ pub resolver: spin_expressions::SharedPreparedResolver,
+}
+
#[derive(Default)]
pub struct OutboundMysql {
allowed_hosts: spin_outbound_networking::AllowedHostsConfig,
@@ -43,8 +47,8 @@ impl OutboundMysql {
}
}
-impl HostComponent for OutboundMysql {
- type Data = Self;
+impl HostComponent for OutboundMysqlComponent {
+ type Data = OutboundMysql;
fn add_to_linker<T: Send>(
linker: &mut spin_core::Linker<T>,
@@ -59,7 +63,7 @@ impl HostComponent for OutboundMysql {
}
}
-impl DynamicHostComponent for OutboundMysql {
+impl DynamicHostComponent for OutboundMysqlComponent {
fn update_data(
&self,
data: &mut Self::Data,
@@ -68,8 +72,11 @@ impl DynamicHostComponent for OutboundMysql {
let hosts = component
.get_metadata(spin_outbound_networking::ALLOWED_HOSTS_KEY)?
.unwrap_or_default();
- data.allowed_hosts = spin_outbound_networking::AllowedHostsConfig::parse(&hosts)
- .context("`allowed_outbound_hosts` contained an invalid url")?;
+ data.allowed_hosts = spin_outbound_networking::AllowedHostsConfig::parse(
+ &hosts,
+ self.resolver.get().unwrap(),
+ )
+ .context("`allowed_outbound_hosts` contained an invalid url")?;
Ok(())
}
}
diff --git a/crates/outbound-networking/Cargo.toml b/crates/outbound-networking/Cargo.toml
index 127a353711..9c36e30354 100644
--- a/crates/outbound-networking/Cargo.toml
+++ b/crates/outbound-networking/Cargo.toml
@@ -7,6 +7,7 @@ edition.workspace = true
[dependencies]
anyhow = "1.0"
ipnet = "2.9.0"
+spin-expressions = { path = "../expressions" }
spin-locked-app = { path = "../locked-app" }
terminal = { path = "../terminal" }
url = "2.4.1"
diff --git a/crates/outbound-networking/src/lib.rs b/crates/outbound-networking/src/lib.rs
index 019c85100a..f7445920fd 100644
--- a/crates/outbound-networking/src/lib.rs
+++ b/crates/outbound-networking/src/lib.rs
@@ -1,4 +1,4 @@
-use std::ops::Range;
+use std::{ops::Range, sync::Arc};
use anyhow::{bail, ensure, Context};
use spin_locked_app::MetadataKey;
@@ -296,16 +296,59 @@ pub enum AllowedHostsConfig {
SpecificHosts(Vec<AllowedHostConfig>),
}
+enum PartialAllowedHostConfig {
+ Exact(AllowedHostConfig),
+ Unresolved(spin_expressions::Template),
+}
+
+impl PartialAllowedHostConfig {
+ fn resolve(
+ self,
+ resolver: &Arc<spin_expressions::PreparedResolver>,
+ ) -> anyhow::Result<AllowedHostConfig> {
+ match self {
+ Self::Exact(h) => Ok(h),
+ Self::Unresolved(t) => AllowedHostConfig::parse(resolver.resolve_template(&t)?),
+ }
+ }
+}
+
impl AllowedHostsConfig {
- pub fn parse<S: AsRef<str>>(hosts: &[S]) -> anyhow::Result<AllowedHostsConfig> {
+ pub fn parse<S: AsRef<str>>(
+ hosts: &[S],
+ resolver: &Arc<spin_expressions::PreparedResolver>,
+ ) -> anyhow::Result<AllowedHostsConfig> {
+ let partial = Self::parse_partial(hosts)?;
+ let allowed = partial
+ .into_iter()
+ .map(|p| p.resolve(resolver))
+ .collect::<anyhow::Result<Vec<_>>>()?;
+ Ok(Self::SpecificHosts(allowed))
+ }
+
+ pub fn validate<S: AsRef<str>>(hosts: &[S]) -> anyhow::Result<()> {
+ _ = Self::parse_partial(hosts)?;
+ Ok(())
+ }
+
+ // Parses literals but defers templates. This is pulled out so that `validate`
+ // doesn't have to deal with resolving templates.
+ fn parse_partial<S: AsRef<str>>(hosts: &[S]) -> anyhow::Result<Vec<PartialAllowedHostConfig>> {
if hosts.len() == 1 && hosts[0].as_ref() == "insecure:allow-all" {
bail!("'insecure:allow-all' is not allowed - use '*://*:*' instead if you really want to allow all outbound traffic'")
}
let mut allowed = Vec::with_capacity(hosts.len());
for host in hosts {
- allowed.push(AllowedHostConfig::parse(host.as_ref().to_owned())?)
+ let template = spin_expressions::Template::new(host.as_ref())?;
+ if template.is_literal() {
+ allowed.push(PartialAllowedHostConfig::Exact(AllowedHostConfig::parse(
+ host.as_ref(),
+ )?));
+ } else {
+ allowed.push(PartialAllowedHostConfig::Unresolved(template));
+ }
}
- Ok(Self::SpecificHosts(allowed))
+ Ok(allowed)
}
/// Determine if the supplied url is allowed
@@ -428,6 +471,10 @@ mod test {
}
}
+ fn dummy_resolver() -> Arc<spin_expressions::PreparedResolver> {
+ Arc::new(spin_expressions::PreparedResolver::default())
+ }
+
use super::*;
use std::net::{Ipv4Addr, Ipv6Addr};
@@ -603,8 +650,12 @@ mod test {
#[test]
fn test_allowed_hosts_respects_allow_all() {
- assert!(AllowedHostsConfig::parse(&["insecure:allow-all"]).is_err());
- assert!(AllowedHostsConfig::parse(&["spin.fermyon.dev", "insecure:allow-all"]).is_err());
+ assert!(AllowedHostsConfig::parse(&["insecure:allow-all"], &dummy_resolver()).is_err());
+ assert!(AllowedHostsConfig::parse(
+ &["spin.fermyon.dev", "insecure:allow-all"],
+ &dummy_resolver()
+ )
+ .is_err());
}
#[test]
@@ -617,9 +668,11 @@ mod test {
#[test]
fn test_allowed_hosts_can_be_specific() {
- let allowed =
- AllowedHostsConfig::parse(&["*://spin.fermyon.dev:443", "http://example.com:8383"])
- .unwrap();
+ let allowed = AllowedHostsConfig::parse(
+ &["*://spin.fermyon.dev:443", "http://example.com:8383"],
+ &dummy_resolver(),
+ )
+ .unwrap();
assert!(
allowed.allows(&OutboundUrl::parse("http://example.com:8383/foo/bar", "http").unwrap())
);
@@ -632,9 +685,11 @@ mod test {
#[test]
fn test_allowed_hosts_can_be_subdomain_wildcards() {
- let allowed =
- AllowedHostsConfig::parse(&["http://*.example.com", "http://*.example2.com:8383"])
- .unwrap();
+ let allowed = AllowedHostsConfig::parse(
+ &["http://*.example.com", "http://*.example2.com:8383"],
+ &dummy_resolver(),
+ )
+ .unwrap();
assert!(
allowed.allows(&OutboundUrl::parse("http://a.example.com/foo/bar", "http").unwrap())
);
@@ -655,7 +710,7 @@ mod test {
#[test]
fn test_hash_char_in_db_password() {
- let allowed = AllowedHostsConfig::parse(&["mysql://xyz.com"]).unwrap();
+ let allowed = AllowedHostsConfig::parse(&["mysql://xyz.com"], &dummy_resolver()).unwrap();
assert!(
allowed.allows(&OutboundUrl::parse("mysql://user:pass#word@xyz.com", "mysql").unwrap())
);
diff --git a/crates/outbound-pg/Cargo.toml b/crates/outbound-pg/Cargo.toml
index a78cdd70f2..568eac834f 100644
--- a/crates/outbound-pg/Cargo.toml
+++ b/crates/outbound-pg/Cargo.toml
@@ -13,6 +13,7 @@ native-tls = "0.2.11"
postgres-native-tls = "0.5.0"
spin-app = { path = "../app" }
spin-core = { path = "../core" }
+spin-expressions = { path = "../expressions" }
spin-outbound-networking = { path = "../outbound-networking" }
spin-world = { path = "../world" }
table = { path = "../table" }
diff --git a/crates/outbound-pg/src/lib.rs b/crates/outbound-pg/src/lib.rs
index e7a82bb915..20335211af 100644
--- a/crates/outbound-pg/src/lib.rs
+++ b/crates/outbound-pg/src/lib.rs
@@ -13,6 +13,10 @@ use tokio_postgres::{
Client, NoTls, Row, Socket,
};
+pub struct OutboundPgComponent {
+ pub resolver: spin_expressions::SharedPreparedResolver,
+}
+
/// A simple implementation to support outbound pg connection
#[derive(Default)]
pub struct OutboundPg {
@@ -67,8 +71,8 @@ impl OutboundPg {
}
}
-impl HostComponent for OutboundPg {
- type Data = Self;
+impl HostComponent for OutboundPgComponent {
+ type Data = OutboundPg;
fn add_to_linker<T: Send>(
linker: &mut spin_core::Linker<T>,
@@ -83,7 +87,7 @@ impl HostComponent for OutboundPg {
}
}
-impl DynamicHostComponent for OutboundPg {
+impl DynamicHostComponent for OutboundPgComponent {
fn update_data(
&self,
data: &mut Self::Data,
@@ -92,8 +96,11 @@ impl DynamicHostComponent for OutboundPg {
let hosts = component
.get_metadata(spin_outbound_networking::ALLOWED_HOSTS_KEY)?
.unwrap_or_default();
- data.allowed_hosts = spin_outbound_networking::AllowedHostsConfig::parse(&hosts)
- .context("`allowed_outbound_hosts` contained an invalid url")?;
+ data.allowed_hosts = spin_outbound_networking::AllowedHostsConfig::parse(
+ &hosts,
+ self.resolver.get().unwrap(),
+ )
+ .context("`allowed_outbound_hosts` contained an invalid url")?;
Ok(())
}
}
diff --git a/crates/outbound-redis/Cargo.toml b/crates/outbound-redis/Cargo.toml
index 2d893c624f..e321a8d17c 100644
--- a/crates/outbound-redis/Cargo.toml
+++ b/crates/outbound-redis/Cargo.toml
@@ -12,6 +12,7 @@ anyhow = "1.0"
redis = { version = "0.21", features = ["tokio-comp", "tokio-native-tls-comp"] }
spin-app = { path = "../app" }
spin-core = { path = "../core" }
+spin-expressions = { path = "../expressions" }
spin-world = { path = "../world" }
spin-outbound-networking = { path = "../outbound-networking" }
table = { path = "../table" }
diff --git a/crates/outbound-redis/src/host_component.rs b/crates/outbound-redis/src/host_component.rs
index f09bdaf0a4..464e1712d2 100644
--- a/crates/outbound-redis/src/host_component.rs
+++ b/crates/outbound-redis/src/host_component.rs
@@ -4,7 +4,9 @@ use spin_core::HostComponent;
use crate::OutboundRedis;
-pub struct OutboundRedisComponent;
+pub struct OutboundRedisComponent {
+ pub resolver: spin_expressions::SharedPreparedResolver,
+}
impl HostComponent for OutboundRedisComponent {
type Data = OutboundRedis;
@@ -30,8 +32,11 @@ impl DynamicHostComponent for OutboundRedisComponent {
let hosts = component
.get_metadata(spin_outbound_networking::ALLOWED_HOSTS_KEY)?
.unwrap_or_default();
- data.allowed_hosts = spin_outbound_networking::AllowedHostsConfig::parse(&hosts)
- .context("`allowed_outbound_hosts` contained an invalid url")?;
+ data.allowed_hosts = spin_outbound_networking::AllowedHostsConfig::parse(
+ &hosts,
+ self.resolver.get().unwrap(),
+ )
+ .context("`allowed_outbound_hosts` contained an invalid url")?;
Ok(())
}
}
diff --git a/crates/trigger-redis/Cargo.toml b/crates/trigger-redis/Cargo.toml
index b56268d1c9..efebfe6fe1 100644
--- a/crates/trigger-redis/Cargo.toml
+++ b/crates/trigger-redis/Cargo.toml
@@ -14,6 +14,7 @@ futures = "0.3"
serde = "1.0.188"
spin-app = { path = "../app" }
spin-core = { path = "../core" }
+spin-expressions = { path = "../expressions" }
spin-trigger = { path = "../trigger" }
spin-world = { path = "../world" }
redis = { version = "0.21", features = ["tokio-comp"] }
diff --git a/crates/trigger-redis/src/lib.rs b/crates/trigger-redis/src/lib.rs
index 10d032b908..73459ceefd 100644
--- a/crates/trigger-redis/src/lib.rs
+++ b/crates/trigger-redis/src/lib.rs
@@ -56,6 +56,8 @@ impl TriggerExecutor for RedisTrigger {
.trigger_metadata::<TriggerMetadata>()?
.unwrap_or_default()
.address;
+ let address_expr = spin_expressions::Template::new(address)?;
+ let address = engine.resolve_template(&address_expr)?;
let mut channel_components: HashMap<String, Vec<String>> = HashMap::new();
diff --git a/crates/trigger/Cargo.toml b/crates/trigger/Cargo.toml
index 7860ea4508..47b2a708e6 100644
--- a/crates/trigger/Cargo.toml
+++ b/crates/trigger/Cargo.toml
@@ -28,6 +28,7 @@ outbound-mqtt = { path = "../outbound-mqtt" }
outbound-pg = { path = "../outbound-pg" }
outbound-mysql = { path = "../outbound-mysql" }
spin-common = { path = "../common" }
+spin-expressions = { path = "../expressions" }
spin-key-value = { path = "../key-value" }
spin-key-value-azure = { path = "../key-value-azure" }
spin-key-value-redis = { path = "../key-value-redis" }
diff --git a/crates/trigger/src/cli.rs b/crates/trigger/src/cli.rs
index 008d87b39b..499e9542ad 100644
--- a/crates/trigger/src/cli.rs
+++ b/crates/trigger/src/cli.rs
@@ -207,7 +207,7 @@ where
self.update_config(builder.config_mut())?;
builder.hooks(StdioLoggingTriggerHooks::new(self.follow_components()));
- builder.hooks(Network);
+ builder.hooks(Network::default());
builder.hooks(KeyValuePersistenceMessageHook);
builder.hooks(SqlitePersistenceMessageHook);
diff --git a/crates/trigger/src/lib.rs b/crates/trigger/src/lib.rs
index 1d79f8a4de..604fdd6a51 100644
--- a/crates/trigger/src/lib.rs
+++ b/crates/trigger/src/lib.rs
@@ -107,6 +107,8 @@ impl<Executor: TriggerExecutor> TriggerExecutorBuilder<Executor> {
where
Executor::TriggerConfig: DeserializeOwned,
{
+ let resolver_cell = std::sync::Arc::new(std::sync::OnceLock::new());
+
let engine = {
let mut builder = Engine::builder(&self.config)?;
@@ -125,18 +127,28 @@ impl<Executor: TriggerExecutor> TriggerExecutorBuilder<Executor> {
self.loader.add_dynamic_host_component(
&mut builder,
- outbound_redis::OutboundRedisComponent,
+ outbound_redis::OutboundRedisComponent {
+ resolver: resolver_cell.clone(),
+ },
)?;
self.loader.add_dynamic_host_component(
&mut builder,
- outbound_mqtt::OutboundMqttComponent,
+ outbound_mqtt::OutboundMqttComponent {
+ resolver: resolver_cell.clone(),
+ },
)?;
self.loader.add_dynamic_host_component(
&mut builder,
- outbound_mysql::OutboundMysql::default(),
+ outbound_mysql::OutboundMysqlComponent {
+ resolver: resolver_cell.clone(),
+ },
+ )?;
+ self.loader.add_dynamic_host_component(
+ &mut builder,
+ outbound_pg::OutboundPgComponent {
+ resolver: resolver_cell.clone(),
+ },
)?;
- self.loader
- .add_dynamic_host_component(&mut builder, outbound_pg::OutboundPg::default())?;
self.loader.add_dynamic_host_component(
&mut builder,
runtime_config::llm::build_component(&runtime_config, init_data.llm.use_gpu)
@@ -157,7 +169,9 @@ impl<Executor: TriggerExecutor> TriggerExecutorBuilder<Executor> {
)?;
self.loader.add_dynamic_host_component(
&mut builder,
- outbound_http::OutboundHttpComponent,
+ outbound_http::OutboundHttpComponent {
+ resolver: resolver_cell.clone(),
+ },
)?;
self.loader.add_dynamic_host_component(
&mut builder,
@@ -175,12 +189,22 @@ impl<Executor: TriggerExecutor> TriggerExecutorBuilder<Executor> {
let app_name = app.borrowed().require_metadata(APP_NAME_KEY)?;
+ let resolver =
+ spin_variables::make_resolver(app.borrowed(), runtime_config.variables_providers())?;
+ let prepared_resolver = std::sync::Arc::new(resolver.prepare().await?);
+ resolver_cell
+ .set(prepared_resolver.clone())
+ .map_err(|_| anyhow::anyhow!("resolver cell was already set!"))?;
+
self.hooks
.iter_mut()
- .try_for_each(|h| h.app_loaded(app.borrowed(), &runtime_config))?;
+ .try_for_each(|h| h.app_loaded(app.borrowed(), &runtime_config, &prepared_resolver))?;
// Run trigger executor
- Executor::new(TriggerAppEngine::new(engine, app_name, app, self.hooks).await?).await
+ Executor::new(
+ TriggerAppEngine::new(engine, app_name, app, self.hooks, &prepared_resolver).await?,
+ )
+ .await
}
}
@@ -223,6 +247,8 @@ pub struct TriggerAppEngine<Executor: TriggerExecutor> {
trigger_configs: Vec<Executor::TriggerConfig>,
// Map of {Component ID -> InstancePre} for each component.
component_instance_pres: HashMap<String, EitherInstancePre<Executor::RuntimeData>>,
+ // Resolver for value template expressions
+ resolver: std::sync::Arc<spin_expressions::PreparedResolver>,
}
impl<Executor: TriggerExecutor> TriggerAppEngine<Executor> {
@@ -233,6 +259,7 @@ impl<Executor: TriggerExecutor> TriggerAppEngine<Executor> {
app_name: String,
app: OwnedApp,
hooks: Vec<Box<dyn TriggerHooks>>,
+ resolver: &std::sync::Arc<spin_expressions::PreparedResolver>,
) -> Result<Self>
where
<Executor as TriggerExecutor>::TriggerConfig: DeserializeOwned,
@@ -283,6 +310,7 @@ impl<Executor: TriggerExecutor> TriggerAppEngine<Executor> {
hooks,
trigger_configs: trigger_configs.into_iter().map(|(_, v)| v).collect(),
component_instance_pres,
+ resolver: resolver.clone(),
})
}
@@ -373,6 +401,13 @@ impl<Executor: TriggerExecutor> TriggerAppEngine<Executor> {
)
})
}
+
+ pub fn resolve_template(
+ &self,
+ template: &spin_expressions::Template,
+ ) -> Result<String, spin_expressions::Error> {
+ self.resolver.resolve_template(template)
+ }
}
/// TriggerHooks allows a Spin environment to hook into a TriggerAppEngine's
@@ -381,7 +416,12 @@ pub trait TriggerHooks: Send + Sync {
#![allow(unused_variables)]
/// Called once, immediately after an App is loaded.
- fn app_loaded(&mut self, app: &App, runtime_config: &RuntimeConfig) -> Result<()> {
+ fn app_loaded(
+ &mut self,
+ app: &App,
+ runtime_config: &RuntimeConfig,
+ resolver: &std::sync::Arc<spin_expressions::PreparedResolver>,
+ ) -> Result<()> {
Ok(())
}
diff --git a/crates/trigger/src/network.rs b/crates/trigger/src/network.rs
index 4f7065c629..72efba272c 100644
--- a/crates/trigger/src/network.rs
+++ b/crates/trigger/src/network.rs
@@ -1,8 +1,23 @@
+use std::sync::Arc;
+
use crate::TriggerHooks;
-pub struct Network;
+#[derive(Default)]
+pub struct Network {
+ resolver: Arc<spin_expressions::PreparedResolver>,
+}
impl TriggerHooks for Network {
+ fn app_loaded(
+ &mut self,
+ _app: &spin_app::App,
+ _runtime_config: &crate::RuntimeConfig,
+ resolver: &Arc<spin_expressions::PreparedResolver>,
+ ) -> anyhow::Result<()> {
+ self.resolver = resolver.clone();
+ Ok(())
+ }
+
fn component_store_builder(
&self,
component: &spin_app::AppComponent,
@@ -11,7 +26,8 @@ impl TriggerHooks for Network {
let hosts = component
.get_metadata(spin_outbound_networking::ALLOWED_HOSTS_KEY)?
.unwrap_or_default();
- let allowed_hosts = spin_outbound_networking::AllowedHostsConfig::parse(&hosts)?;
+ let allowed_hosts =
+ spin_outbound_networking::AllowedHostsConfig::parse(&hosts, &self.resolver)?;
match allowed_hosts {
spin_outbound_networking::AllowedHostsConfig::All => {
store_builder.inherit_limited_network()
diff --git a/crates/trigger/src/runtime_config/key_value.rs b/crates/trigger/src/runtime_config/key_value.rs
index 1b0dcc1a1b..b186c48191 100644
--- a/crates/trigger/src/runtime_config/key_value.rs
+++ b/crates/trigger/src/runtime_config/key_value.rs
@@ -144,7 +144,12 @@ impl AzureCosmosConfig {
pub struct KeyValuePersistenceMessageHook;
impl TriggerHooks for KeyValuePersistenceMessageHook {
- fn app_loaded(&mut self, app: &spin_app::App, runtime_config: &RuntimeConfig) -> Result<()> {
+ fn app_loaded(
+ &mut self,
+ app: &spin_app::App,
+ runtime_config: &RuntimeConfig,
+ _resolver: &Arc<spin_expressions::PreparedResolver>,
+ ) -> Result<()> {
// Only print if the app actually uses KV
if app.components().all(|c| {
c.get_metadata(KEY_VALUE_STORES_KEY)
diff --git a/crates/trigger/src/runtime_config/sqlite.rs b/crates/trigger/src/runtime_config/sqlite.rs
index 8ae8974f7f..c8dd2e869d 100644
--- a/crates/trigger/src/runtime_config/sqlite.rs
+++ b/crates/trigger/src/runtime_config/sqlite.rs
@@ -166,6 +166,7 @@ impl TriggerHooks for SqlitePersistenceMessageHook {
&mut self,
app: &spin_app::App,
runtime_config: &RuntimeConfig,
+ _resolver: &Arc<spin_expressions::PreparedResolver>,
) -> anyhow::Result<()> {
if app.components().all(|c| {
c.get_metadata(DATABASES_KEY)
diff --git a/crates/trigger/src/runtime_config/variables_provider.rs b/crates/trigger/src/runtime_config/variables_provider.rs
index ffaeee35de..db0008b403 100644
--- a/crates/trigger/src/runtime_config/variables_provider.rs
+++ b/crates/trigger/src/runtime_config/variables_provider.rs
@@ -5,7 +5,7 @@ use spin_variables::provider::{env::EnvProvider, vault::VaultProvider};
use super::RuntimeConfig;
-pub type VariablesProvider = Box<dyn spin_variables::Provider>;
+pub type VariablesProvider = Box<dyn spin_expressions::Provider>;
// Holds deserialized options from a `[[config_provider]]` runtime config section.
#[derive(Debug, Deserialize)]
diff --git a/crates/trigger/src/stdio.rs b/crates/trigger/src/stdio.rs
index b578149986..75a7b5be9e 100644
--- a/crates/trigger/src/stdio.rs
+++ b/crates/trigger/src/stdio.rs
@@ -90,6 +90,7 @@ impl TriggerHooks for StdioLoggingTriggerHooks {
&mut self,
app: &spin_app::App,
runtime_config: &RuntimeConfig,
+ _resolver: &std::sync::Arc<spin_expressions::PreparedResolver>,
) -> anyhow::Result<()> {
self.log_dir = runtime_config.log_dir();
diff --git a/crates/variables/Cargo.toml b/crates/variables/Cargo.toml
index 0ad6012560..904cbd2325 100644
--- a/crates/variables/Cargo.toml
+++ b/crates/variables/Cargo.toml
@@ -11,6 +11,7 @@ dotenvy = "0.15"
once_cell = "1"
spin-app = { path = "../app" }
spin-core = { path = "../core" }
+spin-expressions = { path = "../expressions" }
spin-world = { path = "../world" }
thiserror = "1"
tokio = { version = "1", features = ["rt-multi-thread"] }
diff --git a/crates/variables/src/host_component.rs b/crates/variables/src/host_component.rs
index dd88d4c03b..e343220dfc 100644
--- a/crates/variables/src/host_component.rs
+++ b/crates/variables/src/host_component.rs
@@ -6,7 +6,7 @@ use spin_app::{AppComponent, DynamicHostComponent};
use spin_core::{async_trait, HostComponent};
use spin_world::v2::variables;
-use crate::{Error, Key, Provider, Resolver};
+use spin_expressions::{Error, Key, Provider, Resolver};
pub struct VariablesHostComponent {
providers: Mutex<Vec<Box<dyn Provider>>>,
@@ -44,28 +44,30 @@ impl HostComponent for VariablesHostComponent {
impl DynamicHostComponent for VariablesHostComponent {
fn update_data(&self, data: &mut Self::Data, component: &AppComponent) -> anyhow::Result<()> {
self.resolver.get_or_try_init(|| {
- let mut resolver = Resolver::new(
- component
- .app
- .variables()
- .map(|(key, var)| (key.clone(), var.clone())),
- )?;
- for component in component.app.components() {
- resolver.add_component_variables(
- component.id(),
- component.config().map(|(k, v)| (k.into(), v.into())),
- )?;
- }
- for provider in self.providers.lock().unwrap().drain(..) {
- resolver.add_provider(provider);
- }
- Ok::<_, anyhow::Error>(resolver)
+ make_resolver(component.app, self.providers.lock().unwrap().drain(..))
})?;
data.component_id = Some(component.id().to_string());
Ok(())
}
}
+pub fn make_resolver(
+ app: &spin_app::App,
+ providers: impl IntoIterator<Item = Box<dyn Provider>>,
+) -> anyhow::Result<Resolver> {
+ let mut resolver = Resolver::new(app.variables().map(|(key, var)| (key.clone(), var.clone())))?;
+ for component in app.components() {
+ resolver.add_component_variables(
+ component.id(),
+ component.config().map(|(k, v)| (k.into(), v.into())),
+ )?;
+ }
+ for provider in providers {
+ resolver.add_provider(provider);
+ }
+ Ok(resolver)
+}
+
/// A component variables interface implementation.
pub struct ComponentVariables {
resolver: Arc<OnceCell<Resolver>>,
@@ -78,13 +80,13 @@ impl variables::Host for ComponentVariables {
Ok(async {
// Set by DynamicHostComponent::update_data
let component_id = self.component_id.as_deref().unwrap();
- let key = Key::new(&key)?;
- Ok(self
- .resolver
+ let key = Key::new(&key).map_err(as_wit)?;
+ self.resolver
.get()
.unwrap()
.resolve(component_id, key)
- .await?)
+ .await
+ .map_err(as_wit)
}
.await)
}
@@ -107,13 +109,11 @@ impl spin_world::v1::config::Host for ComponentVariables {
}
}
-impl From<Error> for variables::Error {
- fn from(err: Error) -> Self {
- match err {
- Error::InvalidName(msg) => Self::InvalidName(msg),
- Error::Undefined(msg) => Self::Undefined(msg),
- Error::Provider(err) => Self::Provider(err.to_string()),
- other => Self::Other(format!("{other}")),
- }
+fn as_wit(err: Error) -> variables::Error {
+ match err {
+ Error::InvalidName(msg) => variables::Error::InvalidName(msg),
+ Error::Undefined(msg) => variables::Error::Undefined(msg),
+ Error::Provider(err) => variables::Error::Provider(err.to_string()),
+ other => variables::Error::Other(format!("{other}")),
}
}
diff --git a/crates/variables/src/lib.rs b/crates/variables/src/lib.rs
index cfb814fb96..620e6171c9 100644
--- a/crates/variables/src/lib.rs
+++ b/crates/variables/src/lib.rs
@@ -1,265 +1,4 @@
mod host_component;
pub mod provider;
-mod template;
-use std::{borrow::Cow, collections::HashMap, fmt::Debug};
-
-use spin_app::Variable;
-
-pub use crate::{host_component::VariablesHostComponent, provider::Provider};
-use template::{Part, Template};
-
-/// A variable resolver.
-#[derive(Debug, Default)]
-pub struct Resolver {
- // variable key -> variable
- variables: HashMap<String, Variable>,
- // component ID -> variable key -> variable value template
- component_configs: HashMap<String, HashMap<String, Template>>,
- providers: Vec<Box<dyn Provider>>,
-}
-
-impl Resolver {
- /// Creates a Resolver for the given Tree.
- pub fn new(variables: impl IntoIterator<Item = (String, Variable)>) -> Result<Self> {
- let variables: HashMap<_, _> = variables.into_iter().collect();
- // Validate keys so that we can rely on them during resolution
- variables.keys().try_for_each(|key| Key::validate(key))?;
- Ok(Self {
- variables,
- component_configs: Default::default(),
- providers: Default::default(),
- })
- }
-
- /// Adds component variable values to the Resolver.
- pub fn add_component_variables(
- &mut self,
- component_id: impl Into<String>,
- variables: impl IntoIterator<Item = (String, String)>,
- ) -> Result<()> {
- let component_id = component_id.into();
- let templates = variables
- .into_iter()
- .map(|(key, val)| {
- // Validate variable keys so that we can rely on them during resolution
- Key::validate(&key)?;
- let template = self.validate_template(val)?;
- Ok((key, template))
- })
- .collect::<Result<_>>()?;
-
- self.component_configs.insert(component_id, templates);
-
- Ok(())
- }
-
- /// Adds a variable Provider to the Resolver.
- pub fn add_provider(&mut self, provider: Box<dyn Provider>) {
- self.providers.push(provider);
- }
-
- /// Resolves a variable value for the given path.
- pub async fn resolve(&self, component_id: &str, key: Key<'_>) -> Result<String> {
- let configs = self.component_configs.get(component_id).ok_or_else(|| {
- Error::Undefined(format!("no variable for component {component_id:?}"))
- })?;
-
- let key = key.as_ref();
- let template = configs
- .get(key)
- .ok_or_else(|| Error::Undefined(format!("no variable for {component_id:?}.{key:?}")))?;
-
- self.resolve_template(template).await
- }
-
- async fn resolve_template(&self, template: &Template) -> Result<String> {
- let mut resolved_parts: Vec<Cow<str>> = Vec::with_capacity(template.parts().len());
- for part in template.parts() {
- resolved_parts.push(match part {
- Part::Lit(lit) => lit.as_ref().into(),
- Part::Expr(var) => self.resolve_variable(var).await?.into(),
- });
- }
- Ok(resolved_parts.concat())
- }
-
- async fn resolve_variable(&self, key: &str) -> Result<String> {
- let var = self
- .variables
- .get(key)
- // This should have been caught by validate_template
- .ok_or_else(|| Error::InvalidName(key.to_string()))?;
-
- for provider in &self.providers {
- if let Some(value) = provider.get(&Key(key)).await.map_err(Error::Provider)? {
- return Ok(value);
- }
- }
-
- var.default.clone().ok_or_else(|| {
- Error::Provider(anyhow::anyhow!(
- "no provider resolved required variable {key:?}"
- ))
- })
- }
-
- fn validate_template(&self, template: String) -> Result<Template> {
- let template = Template::new(template)?;
- // Validate template variables are valid
- template.parts().try_for_each(|part| match part {
- Part::Expr(var) if !self.variables.contains_key(var.as_ref()) => {
- Err(Error::InvalidTemplate(format!("unknown variable {var:?}")))
- }
- _ => Ok(()),
- })?;
- Ok(template)
- }
-}
-
-/// A variable key
-#[derive(Debug, PartialEq, Eq)]
-pub struct Key<'a>(&'a str);
-
-impl<'a> Key<'a> {
- /// Creates a new Key.
- pub fn new(key: &'a str) -> Result<Self> {
- Self::validate(key)?;
- Ok(Self(key))
- }
-
- // To allow various (env var, file path) transformations:
- // - must start with an ASCII letter
- // - underscores are allowed; one at a time between other characters
- // - all other characters must be ASCII alphanumeric
- fn validate(key: &str) -> Result<()> {
- {
- if key.is_empty() {
- Err("must not be empty".to_string())
- } else if let Some(invalid) = key
- .chars()
- .find(|c| !(c.is_ascii_lowercase() || c.is_ascii_digit() || c == &'_'))
- {
- Err(format!("invalid character {:?}. Variable names may contain only lower-case letters, numbers, and underscores.", invalid))
- } else if !key.bytes().next().unwrap().is_ascii_lowercase() {
- Err("must start with a lowercase ASCII letter".to_string())
- } else if !key.bytes().last().unwrap().is_ascii_alphanumeric() {
- Err("must end with a lowercase ASCII letter or digit".to_string())
- } else if key.contains("__") {
- Err("must not contain multiple consecutive underscores".to_string())
- } else {
- Ok(())
- }
- }
- .map_err(|reason| Error::InvalidName(format!("{key:?}: {reason}")))
- }
-}
-
-impl<'a> AsRef<str> for Key<'a> {
- fn as_ref(&self) -> &str {
- self.0
- }
-}
-
-type Result<T> = std::result::Result<T, Error>;
-
-/// A variable resolution error.
-#[derive(Debug, thiserror::Error)]
-pub enum Error {
- /// Invalid variable name.
- #[error("invalid variable name: {0}")]
- InvalidName(String),
-
- /// Invalid variable template.
- #[error("invalid variable template: {0}")]
- InvalidTemplate(String),
-
- /// Variable provider error.
- #[error("provider error: {0:?}")]
- Provider(#[source] anyhow::Error),
-
- /// Undefined variable.
- #[error("undefined variable: {0}")]
- Undefined(String),
-}
-
-#[cfg(test)]
-mod tests {
- use async_trait::async_trait;
-
- use super::*;
-
- #[derive(Debug)]
- struct TestProvider;
-
- #[async_trait]
- impl Provider for TestProvider {
- async fn get(&self, key: &Key) -> anyhow::Result<Option<String>> {
- match key.as_ref() {
- "required" => Ok(Some("provider-value".to_string())),
- "broken" => anyhow::bail!("broken"),
- _ => Ok(None),
- }
- }
- }
-
- async fn test_resolve(template: &str) -> Result<String> {
- let mut resolver = Resolver::new([
- (
- "required".into(),
- Variable {
- default: None,
- secret: false,
- },
- ),
- (
- "default".into(),
- Variable {
- default: Some("default-value".into()),
- secret: false,
- },
- ),
- ])
- .unwrap();
- resolver
- .add_component_variables("test-component", [("test_key".into(), template.into())])
- .unwrap();
- resolver.add_provider(Box::new(TestProvider));
- resolver.resolve("test-component", Key("test_key")).await
- }
-
- #[tokio::test]
- async fn resolve_static() {
- assert_eq!(test_resolve("static-value").await.unwrap(), "static-value");
- }
-
- #[tokio::test]
- async fn resolve_variable_default() {
- assert_eq!(
- test_resolve("prefix-{{ default }}-suffix").await.unwrap(),
- "prefix-default-value-suffix"
- );
- }
-
- #[tokio::test]
- async fn resolve_variable_provider() {
- assert_eq!(
- test_resolve("prefix-{{ required }}-suffix").await.unwrap(),
- "prefix-provider-value-suffix"
- );
- }
-
- #[test]
- fn keys_good() {
- for key in ["a", "abc", "a1b2c3", "a_1", "a_1_b_3"] {
- Key::new(key).expect(key);
- }
- }
-
- #[test]
- fn keys_bad() {
- for key in ["", "aX", "1bc", "_x", "x.y", "x_", "a__b", "x-y"] {
- Key::new(key).expect_err(key);
- }
- }
-}
+pub use host_component::{make_resolver, VariablesHostComponent};
diff --git a/crates/variables/src/provider.rs b/crates/variables/src/provider.rs
index e6dbeaadc5..ea223c6e87 100644
--- a/crates/variables/src/provider.rs
+++ b/crates/variables/src/provider.rs
@@ -1,16 +1,2 @@
-use std::fmt::Debug;
-
-use async_trait::async_trait;
-
-use crate::Key;
-
-/// Environment variable based provider.
pub mod env;
pub mod vault;
-
-/// A config provider.
-#[async_trait]
-pub trait Provider: Debug + Send + Sync {
- /// Returns the value at the given config path, if it exists.
- async fn get(&self, key: &Key) -> anyhow::Result<Option<String>>;
-}
diff --git a/crates/variables/src/provider/env.rs b/crates/variables/src/provider/env.rs
index d57261c180..439f4e64a4 100644
--- a/crates/variables/src/provider/env.rs
+++ b/crates/variables/src/provider/env.rs
@@ -3,7 +3,7 @@ use std::{collections::HashMap, path::PathBuf, sync::Mutex};
use anyhow::{Context, Result};
use async_trait::async_trait;
-use crate::{Key, Provider};
+use spin_expressions::{Key, Provider};
const DEFAULT_ENV_PREFIX: &str = "SPIN_VARIABLE";
const LEGACY_ENV_PREFIX: &str = "SPIN_CONFIG";
diff --git a/crates/variables/src/provider/vault.rs b/crates/variables/src/provider/vault.rs
index a0f901bde8..9d5911816c 100644
--- a/crates/variables/src/provider/vault.rs
+++ b/crates/variables/src/provider/vault.rs
@@ -7,7 +7,7 @@ use vaultrs::{
kv2,
};
-use crate::{Key, Provider};
+use spin_expressions::{Key, Provider};
/// A config Provider that uses HashiCorp Vault.
#[derive(Debug)]
@@ -49,8 +49,8 @@ impl Provider for VaultProvider {
.build()?,
)?;
let path = match &self.prefix {
- Some(prefix) => format!("{}/{}", prefix, key.0),
- None => key.0.to_string(),
+ Some(prefix) => format!("{}/{}", prefix, key.as_str()),
+ None => key.as_str().to_string(),
};
match kv2::read::<Secret>(&client, &self.mount, &path).await {
Ok(secret) => Ok(Some(secret.value)),
diff --git a/examples/spin-timer/Cargo.lock b/examples/spin-timer/Cargo.lock
index 69c3af4890..f65887effc 100644
--- a/examples/spin-timer/Cargo.lock
+++ b/examples/spin-timer/Cargo.lock
@@ -2571,6 +2571,7 @@ dependencies = [
"reqwest",
"spin-app",
"spin-core",
+ "spin-expressions",
"spin-locked-app",
"spin-outbound-networking",
"spin-world",
@@ -2587,6 +2588,7 @@ dependencies = [
"rumqttc",
"spin-app",
"spin-core",
+ "spin-expressions",
"spin-outbound-networking",
"spin-world",
"table",
@@ -2604,6 +2606,7 @@ dependencies = [
"mysql_common",
"spin-app",
"spin-core",
+ "spin-expressions",
"spin-outbound-networking",
"spin-world",
"table",
@@ -2621,6 +2624,7 @@ dependencies = [
"postgres-native-tls",
"spin-app",
"spin-core",
+ "spin-expressions",
"spin-outbound-networking",
"spin-world",
"table",
@@ -2637,6 +2641,7 @@ dependencies = [
"redis",
"spin-app",
"spin-core",
+ "spin-expressions",
"spin-outbound-networking",
"spin-world",
"table",
@@ -3745,6 +3750,21 @@ dependencies = [
"wasmtime-wasi-http",
]
+[[package]]
+name = "spin-expressions"
+version = "2.4.0-pre0"
+dependencies = [
+ "anyhow",
+ "async-trait",
+ "dotenvy",
+ "once_cell",
+ "serde",
+ "spin-app",
+ "thiserror",
+ "tokio",
+ "vaultrs",
+]
+
[[package]]
name = "spin-key-value"
version = "2.4.0-pre0"
@@ -3897,6 +3917,7 @@ version = "2.4.0-pre0"
dependencies = [
"anyhow",
"ipnet",
+ "spin-expressions",
"spin-locked-app",
"terminal",
"url",
@@ -3976,6 +3997,7 @@ dependencies = [
"spin-common",
"spin-componentize",
"spin-core",
+ "spin-expressions",
"spin-key-value",
"spin-key-value-azure",
"spin-key-value-redis",
@@ -4011,6 +4033,7 @@ dependencies = [
"serde",
"spin-app",
"spin-core",
+ "spin-expressions",
"spin-world",
"thiserror",
"tokio",
| 2,299
|
[
"2153"
] |
diff --git a/tests/integration.rs b/tests/integration.rs
index 330c3161d3..ea6177ff31 100644
--- a/tests/integration.rs
+++ b/tests/integration.rs
@@ -245,6 +245,7 @@ mod integration_tests {
[],
testing_framework::ServicesConfig::none(),
SpinAppType::None,
+ |_| Ok(()),
)?;
let expected = r#"Error: Couldn't find trigger executor for local app "spin.toml"
@@ -353,13 +354,17 @@ Caused by:
#[cfg(feature = "extern-dependencies-tests")]
fn test_vault_config_provider() -> anyhow::Result<()> {
use std::collections::HashMap;
+
+ use crate::testcases::run_test_inited;
const VAULT_ROOT_TOKEN: &str = "root";
- run_test(
+ run_test_inited(
"vault-variables-test",
SpinAppType::Http,
vec!["--runtime-config-file".into(), "runtime_config.toml".into()],
testing_framework::ServicesConfig::new(vec!["vault".into()])?,
|env| {
+ // Vault can take a few moments to be ready
+ std::thread::sleep(std::time::Duration::from_secs(2));
let http_client = reqwest::blocking::Client::new();
let body: HashMap<String, HashMap<String, String>> =
serde_json::from_value(serde_json::json!(
@@ -382,6 +387,9 @@ Caused by:
.context("failed to send request to Vault")?
.status();
assert_eq!(status, 200);
+ Ok(())
+ },
+ |env| {
let spin = env.runtime_mut();
let request = Request::new(Method::GET, "/");
assert_spin_request(
diff --git a/tests/runtime-tests/src/lib.rs b/tests/runtime-tests/src/lib.rs
index d0e1b95b49..5442ed0ff5 100644
--- a/tests/runtime-tests/src/lib.rs
+++ b/tests/runtime-tests/src/lib.rs
@@ -63,7 +63,7 @@ impl RuntimeTest<SpinCli> {
services_config,
testing_framework::runtimes::SpinAppType::Http,
);
- let env = TestEnvironment::up(env_config)?;
+ let env = TestEnvironment::up(env_config, |_| Ok(()))?;
Ok(Self {
test_path: config.test_path,
on_error: config.on_error,
@@ -125,7 +125,7 @@ impl RuntimeTest<InProcessSpin> {
};
let services_config = services_config(&config)?;
let env_config = TestEnvironmentConfig::in_process(services_config, preboot);
- let env = TestEnvironment::up(env_config)?;
+ let env = TestEnvironment::up(env_config, |_| Ok(()))?;
Ok(Self {
test_path: config.test_path,
on_error: config.on_error,
diff --git a/tests/runtime-tests/tests/outbound-mqtt-variable-permission/services b/tests/runtime-tests/tests/outbound-mqtt-variable-permission/services
new file mode 100644
index 0000000000..1d00b34f3a
--- /dev/null
+++ b/tests/runtime-tests/tests/outbound-mqtt-variable-permission/services
@@ -0,0 +1,1 @@
+mqtt
\ No newline at end of file
diff --git a/tests/runtime-tests/tests/outbound-mqtt-variable-permission/spin.toml b/tests/runtime-tests/tests/outbound-mqtt-variable-permission/spin.toml
new file mode 100644
index 0000000000..ffff0180d3
--- /dev/null
+++ b/tests/runtime-tests/tests/outbound-mqtt-variable-permission/spin.toml
@@ -0,0 +1,19 @@
+spin_manifest_version = 2
+
+[application]
+name = "outbound-mqtt"
+authors = ["Suneet Nangia <suneetnangia@gmail.com>"]
+version = "0.1.0"
+
+[variables]
+mqtt_server = { default = "localhost" }
+
+[[trigger.http]]
+route = "/"
+component = "test"
+
+[component.test]
+source = "%{source=outbound-mqtt}"
+allowed_outbound_hosts = ["mqtt://{{ mqtt_server }}:%{port=1883}"]
+# To test anonymous MQTT authentication, remove the values from MQTT_USERNAME and MQTT_PASSWORD env variables.
+environment = { MQTT_ADDRESS = "mqtt://localhost:%{port=1883}?client_id=spintest", MQTT_USERNAME = "user", MQTT_PASSWORD = "password", MQTT_KEEP_ALIVE_INTERVAL = "30" }
diff --git a/tests/runtime-tests/tests/outbound-mysql-variable-permission/services b/tests/runtime-tests/tests/outbound-mysql-variable-permission/services
new file mode 100644
index 0000000000..0d46ca3214
--- /dev/null
+++ b/tests/runtime-tests/tests/outbound-mysql-variable-permission/services
@@ -0,0 +1,1 @@
+mysql
\ No newline at end of file
diff --git a/tests/runtime-tests/tests/outbound-mysql-variable-permission/spin.toml b/tests/runtime-tests/tests/outbound-mysql-variable-permission/spin.toml
new file mode 100644
index 0000000000..e649f9ed5d
--- /dev/null
+++ b/tests/runtime-tests/tests/outbound-mysql-variable-permission/spin.toml
@@ -0,0 +1,18 @@
+spin_manifest_version = 2
+
+[application]
+name = "outbound-mysql"
+authors = ["Fermyon Engineering <engineering@fermyon.com>"]
+version = "0.1.0"
+
+[variables]
+mysql_host = { default = "localhost" }
+
+[[trigger.http]]
+route = "/"
+component = "test"
+
+[component.test]
+source = "%{source=outbound-mysql}"
+allowed_outbound_hosts = ["mysql://{{ mysql_host }}:%{port=3306}"]
+environment = { DB_URL = "mysql://spin:spin@localhost:%{port=3306}/spin_dev" }
diff --git a/tests/runtime-tests/tests/outbound-postgres-variable-permission/services b/tests/runtime-tests/tests/outbound-postgres-variable-permission/services
new file mode 100644
index 0000000000..7d72bd7826
--- /dev/null
+++ b/tests/runtime-tests/tests/outbound-postgres-variable-permission/services
@@ -0,0 +1,1 @@
+postgres
\ No newline at end of file
diff --git a/tests/runtime-tests/tests/outbound-postgres-variable-permission/spin.toml b/tests/runtime-tests/tests/outbound-postgres-variable-permission/spin.toml
new file mode 100644
index 0000000000..3a34bb572f
--- /dev/null
+++ b/tests/runtime-tests/tests/outbound-postgres-variable-permission/spin.toml
@@ -0,0 +1,18 @@
+spin_manifest_version = 2
+
+[application]
+name = "outbound-postgres"
+authors = ["Fermyon Engineering <engineering@fermyon.com>"]
+version = "0.1.0"
+
+[variables]
+pg_host = { default = "localhost" }
+
+[[trigger.http]]
+route = "/"
+component = "test"
+
+[component.test]
+source = "%{source=outbound-postgres}"
+allowed_outbound_hosts = ["postgres://{{ pg_host }}:%{port=5432}"]
+environment = { DB_URL = "postgres://postgres:postgres@localhost:%{port=5432}/spin_dev" }
diff --git a/tests/runtime-tests/tests/outbound-redis-variable-permission/services b/tests/runtime-tests/tests/outbound-redis-variable-permission/services
new file mode 100644
index 0000000000..74b362f93c
--- /dev/null
+++ b/tests/runtime-tests/tests/outbound-redis-variable-permission/services
@@ -0,0 +1,1 @@
+redis
\ No newline at end of file
diff --git a/tests/runtime-tests/tests/outbound-redis-variable-permission/spin.toml b/tests/runtime-tests/tests/outbound-redis-variable-permission/spin.toml
new file mode 100644
index 0000000000..176e5b14ab
--- /dev/null
+++ b/tests/runtime-tests/tests/outbound-redis-variable-permission/spin.toml
@@ -0,0 +1,18 @@
+spin_manifest_version = 2
+
+[application]
+name = "outbound-redis"
+authors = ["Fermyon Engineering <engineering@fermyon.com>"]
+version = "0.1.0"
+
+[variables]
+redis_host = { default = "localhost" }
+
+[[trigger.http]]
+route = "/"
+component = "test"
+
+[component.test]
+source = "%{source=outbound-redis}"
+environment = { REDIS_ADDRESS = "redis://localhost:%{port=6379}" }
+allowed_outbound_hosts = ["redis://{{ redis_host }}:%{port=6379}"]
diff --git a/tests/runtime-tests/tests/tcp-sockets-ip-range-variable-permission/services b/tests/runtime-tests/tests/tcp-sockets-ip-range-variable-permission/services
new file mode 100644
index 0000000000..272b7c0636
--- /dev/null
+++ b/tests/runtime-tests/tests/tcp-sockets-ip-range-variable-permission/services
@@ -0,0 +1,1 @@
+tcp-echo
\ No newline at end of file
diff --git a/tests/runtime-tests/tests/tcp-sockets-ip-range-variable-permission/spin.toml b/tests/runtime-tests/tests/tcp-sockets-ip-range-variable-permission/spin.toml
new file mode 100644
index 0000000000..dc67fc0e7c
--- /dev/null
+++ b/tests/runtime-tests/tests/tcp-sockets-ip-range-variable-permission/spin.toml
@@ -0,0 +1,19 @@
+spin_manifest_version = 2
+
+[application]
+name = "tcp-sockets"
+authors = ["Fermyon Engineering <engineering@fermyon.com>"]
+version = "0.1.0"
+
+[variables]
+addr_prefix = { default = "127.0.0.0"}
+prefix_len = { default = "24"}
+
+[[trigger.http]]
+route = "/"
+component = "test"
+
+[component.test]
+source = "%{source=tcp-sockets}"
+environment = { ADDRESS = "127.0.0.1:%{port=5000}" }
+allowed_outbound_hosts = ["*://{{ addr_prefix }}/{{ prefix_len }}:%{port=5000}"]
diff --git a/tests/runtime.rs b/tests/runtime.rs
index 6b3ac27ded..d541313e74 100644
--- a/tests/runtime.rs
+++ b/tests/runtime.rs
@@ -10,7 +10,8 @@ mod runtime_tests {
ignore: [
// This test is flaky. Often gets "Connection reset by peer" errors.
// https://github.com/fermyon/spin/issues/2265
- "outbound-postgres"
+ "outbound-postgres",
+ "outbound-postgres-variable-permission"
]
);
diff --git a/tests/testcases/mod.rs b/tests/testcases/mod.rs
index b7913b85d7..b136d1938e 100644
--- a/tests/testcases/mod.rs
+++ b/tests/testcases/mod.rs
@@ -12,7 +12,32 @@ pub fn run_test(
) -> testing_framework::TestResult<anyhow::Error>
+ 'static,
) -> testing_framework::TestResult<anyhow::Error> {
- let mut env = bootstap_env(test_name, spin_up_args, services_config, app_type)
+ run_test_inited(
+ test_name,
+ app_type,
+ spin_up_args,
+ services_config,
+ |_| Ok(()),
+ test,
+ )
+}
+
+/// Run an integration test, initialising the environment before running Spin
+pub fn run_test_inited(
+ test_name: impl Into<String>,
+ app_type: testing_framework::runtimes::SpinAppType,
+ spin_up_args: impl IntoIterator<Item = String>,
+ services_config: testing_framework::ServicesConfig,
+ init_env: impl FnOnce(
+ &mut testing_framework::TestEnvironment<testing_framework::runtimes::spin_cli::SpinCli>,
+ ) -> testing_framework::TestResult<anyhow::Error>
+ + 'static,
+ test: impl FnOnce(
+ &mut testing_framework::TestEnvironment<testing_framework::runtimes::spin_cli::SpinCli>,
+ ) -> testing_framework::TestResult<anyhow::Error>
+ + 'static,
+) -> testing_framework::TestResult<anyhow::Error> {
+ let mut env = bootstap_env(test_name, spin_up_args, services_config, app_type, init_env)
.context("failed to boot test environment")?;
test(&mut env)?;
Ok(())
@@ -24,6 +49,10 @@ pub fn bootstap_env(
spin_up_args: impl IntoIterator<Item = String>,
services_config: testing_framework::ServicesConfig,
app_type: testing_framework::runtimes::SpinAppType,
+ init_env: impl FnOnce(
+ &mut testing_framework::TestEnvironment<testing_framework::runtimes::spin_cli::SpinCli>,
+ ) -> testing_framework::TestResult<anyhow::Error>
+ + 'static,
) -> anyhow::Result<
testing_framework::TestEnvironment<testing_framework::runtimes::spin_cli::SpinCli>,
> {
@@ -35,7 +64,7 @@ pub fn bootstap_env(
services_config,
app_type,
);
- testing_framework::TestEnvironment::up(config)
+ testing_framework::TestEnvironment::up(config, init_env)
}
/// Assert that a request to the spin server returns the expected status and body
diff --git a/tests/testing-framework/src/test_environment.rs b/tests/testing-framework/src/test_environment.rs
index c934ae790a..cc39754018 100644
--- a/tests/testing-framework/src/test_environment.rs
+++ b/tests/testing-framework/src/test_environment.rs
@@ -19,8 +19,12 @@ pub struct TestEnvironment<R> {
impl<R: Runtime> TestEnvironment<R> {
/// Spin up a test environment with a runtime
- pub fn up(config: TestEnvironmentConfig<R>) -> anyhow::Result<Self> {
+ pub fn up(
+ config: TestEnvironmentConfig<R>,
+ init_env: impl FnOnce(&mut Self) -> crate::TestResult<anyhow::Error> + 'static,
+ ) -> anyhow::Result<Self> {
let mut env = Self::boot(&config.services_config)?;
+ init_env(&mut env)?;
let runtime = (config.create_runtime)(&mut env)?;
env.start_runtime(runtime)
}
@@ -221,7 +225,7 @@ impl TestEnvironmentConfig<InProcessSpin> {
let loader = TriggerLoader::new(env.path().join(".working_dir"), false);
let mut builder = TriggerExecutorBuilder::<HttpTrigger>::new(loader);
// TODO(rylev): see if we can reuse the builder from spin_trigger instead of duplicating it here
- builder.hooks(spin_trigger::network::Network);
+ builder.hooks(spin_trigger::network::Network::default());
let trigger = builder
.build(
format!("file:{}", env.path().join("locked.json").display()),
|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
bf3be1b271bf0efa7c3bffde071d512ef646fe81
|
Mounting the same component on multiple triggers does not work
When trying to use the same component for multiple triggers, only the final trigger works when running a `spin up`
An example of a manifest is
```toml
spin_manifest_version = 2
[application]
name = "test"
version = "0.1.0"
authors = ["karthik2804 <karthik.ganeshram@fermyon.com>"]
description = ""
[[trigger.http]]
route = "/..."
component = "test"
[[trigger.http]]
route = "/v1/..."
component = "test"
[component.test]
source = "target/wasm32-wasi/release/test.wasm"
allowed_outbound_hosts = []
[component.test.build]
command = "cargo build --target wasm32-wasi --release"
watch = ["src/**/*.rs", "Cargo.toml"]
```
results in
```bash
$ spin up
Logging component stdio to ".spin/logs/"
Serving http://127.0.0.1:3000
Available Routes:
test: http://127.0.0.1:3000/v1 (wildcard)
```
|
2023-12-06T00:49:11Z
|
fermyon__spin-2145
|
fermyon/spin
|
3.2
|
diff --git a/crates/trigger/src/lib.rs b/crates/trigger/src/lib.rs
index 961ad8947f..5b8c10559c 100644
--- a/crates/trigger/src/lib.rs
+++ b/crates/trigger/src/lib.rs
@@ -7,7 +7,6 @@ use std::{collections::HashMap, marker::PhantomData};
use anyhow::{Context, Result};
pub use async_trait::async_trait;
-use indexmap::IndexMap;
use runtime_config::llm::LLmOptions;
use serde::de::DeserializeOwned;
@@ -238,12 +237,19 @@ impl<Executor: TriggerExecutor> TriggerAppEngine<Executor> {
})?,
))
})
- .collect::<Result<IndexMap<_, _>>>()?;
+ .collect::<Result<Vec<_>>>()?;
let mut component_instance_pres = HashMap::default();
for component in app.borrowed().components() {
let id = component.id();
- if let Some(config) = trigger_configs.get(id) {
+ // There is an issue here for triggers that consider the trigger config during
+ // preinstantiation. We defer this for now because the only case is the HTTP
+ // `executor` field and that should not differ from trigger to trigger.
+ let trigger_config = trigger_configs
+ .iter()
+ .find(|(c, _)| c == id)
+ .map(|(_, cfg)| cfg);
+ if let Some(config) = trigger_config {
component_instance_pres.insert(
id.to_owned(),
Executor::instantiate_pre(&engine, &component, config)
@@ -264,7 +270,7 @@ impl<Executor: TriggerExecutor> TriggerAppEngine<Executor> {
app_name,
app,
hooks,
- trigger_configs: trigger_configs.into_values().collect(),
+ trigger_configs: trigger_configs.into_iter().map(|(_, v)| v).collect(),
component_instance_pres,
})
}
| 2,145
|
[
"2143"
] |
diff --git a/tests/http/simple-spin-rust/double-trouble.toml b/tests/http/simple-spin-rust/double-trouble.toml
new file mode 100644
index 0000000000..b42f8181c5
--- /dev/null
+++ b/tests/http/simple-spin-rust/double-trouble.toml
@@ -0,0 +1,22 @@
+spin_manifest_version = 2
+
+[application]
+name = "spin-hello-world"
+version = "1.0.0"
+
+[[trigger.http]]
+route = "/route1"
+component = "hello"
+
+[[trigger.http]]
+route = "/route2"
+component = "hello" # intentionally pointing to same component
+
+[variables]
+object = { default = "teapot" }
+
+[component.hello]
+source = "target/wasm32-wasi/release/simple_spin_rust.wasm"
+files = [{ source = "assets", destination = "/" }]
+[component.hello.variables]
+message = "I'm a {{object}}"
diff --git a/tests/integration.rs b/tests/integration.rs
index 1e0ea6ea7b..91d5130c68 100644
--- a/tests/integration.rs
+++ b/tests/integration.rs
@@ -63,6 +63,22 @@ mod integration_tests {
Ok(())
}
+ #[tokio::test]
+ async fn test_duplicate_rust_local() -> Result<()> {
+ let s = SpinTestController::with_manifest(
+ &format!("{}/{}", RUST_HTTP_INTEGRATION_TEST, "double-trouble.toml"),
+ &[],
+ &[],
+ )
+ .await?;
+
+ assert_status(&s, "/route1", 200).await?;
+ assert_status(&s, "/route2", 200).await?;
+ assert_status(&s, "/thisshouldfail", 404).await?;
+
+ Ok(())
+ }
+
#[tokio::test]
async fn test_timer_trigger() -> Result<()> {
use std::fs;
|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
|
8337a35c57d0540caf7a48d70e839a1e41608011
|
Allow plugin settings in the manifest
A user is working on a `spin clean` plugin. The files to delete on a clean may be language and application specific (e.g. in Rust the `target` directory, in JS the `dist` directory, etc.). Noted troublemaker @mikkelhegn suggested the info could be stored in `spin.toml` as e.g. `component.clean`. But this would make the Spin loader reject the file because we deny unknown fields when deserialising.
We could simply allow unknown fields. This would be a simple change. However it would create the risk that a plugin author uses a field called `foo` and later we, all unawares, use `foo` for an "official" field. It would also impact our ability to provide validation / intellisense / a schema because if someone wrote `biuld` then we could not be sure it was a typo.
A safer change would be to allow unknown fields in dedicated sections (e.g. `[component.build.extra_info]`) or in a distinctive format (`x:clean`), though this makes the native/plugin distinction in-your-face.
Options:
1. Stick with denying unknown fields. Plugin authors must use parallel config files, and if users have to maintain two files then so be it.
2. Allow unknown fields because the risk of a clash is relatively small and schema validation is never going to be perfect anyway.
3. Allow unknown fields subject to some limitation or restriction. What might that look like? Would it be friendly to users who have to author the `spin.toml` file?
4. Something else?
|
I'm definitely weary of option 2. I think this is the most risky choice fraught with the evilest of demons.
I'm not strongly opposed to the idea of a `component.tool.clean` where `tool` is effectively like `package.metadata` in `Cargo.toml`. Generically we reserve `tool` (or whatever) and allow per compoment customizations under this section.
So I guess some combination of 1 & 3 where the value of `tool` is a simple untyped toml value consumable by plugins.
@fibonacci1729 And similarly at the top level I guess, in case a plugin wants to associate app-level info, e.g.
```
spin_manifest_version = "1"
# etc.
[tool.frobnicate]
reticulate_splines = false
[[component]]
id = "foo"
[tool.clean]
files = [...]
```
I like this. We'd need to define at what levels the extra section would be allowed (e.g. could you have a `component.build.tool.clean`) but it feels like we should be able to make it not too obtrusive - depending on TOML syntax restrictions anyway.
Yeah that makes sense to me @itowlson . I would guess it would make the most sense to restrict the `tool` section to top-level (as you suggest) and each component section. I don't see any immediate value to allowing it to be specified on nested sections within a component but I haven't crawled too deep into the thought hole yet.
Another question about this: suppose we do as proposed and have a `tool` map at various levels. Should this be propagated into the `LockedApp`? My first guess was not but:
1. if a plugin uses the loader rather than the schema then it will get a `LockedApp` not a "manifest"
2. it's possible people will write plugins that work on OCI images
Thoughts?
I would also assume that tool-specific settings would not make it into the `LockedApp` however i share your concerns about plugins that operate on OCI images. Is there a precedence for plugins that can only operate on the `LockedApp`?
I don't know of any today (apart from custom triggers, which use the standard trigger sections for their settings). I can imagine plugins that want to work with registry apps, but I'm struggling for scenarios where those would require settings that travel _with_ the app rather than being selected when the plugin runs.
To me, these `tool` settings seem to be the developer side of things like what `runtime-config` is to runtimes. It seems counter-intuitive that these would end up in a distributed artefact given that they are really settings per developer. But am definitely in the same boat as you thinking-wise, i don't feel great about entirely eliminating that possibility without great justification. Maybe we can make the assumption that these don't get propagated to the LockedApp for now and revisit when there is a compelling use-case? What do you think?
I think that's okay. Adding them to the LockedApp in a future release would be a non-breaking change. I'll go ahead on this basis. Thanks!
|
2023-11-16T21:46:17Z
|
fermyon__spin-2104
|
fermyon/spin
|
3.2
|
diff --git a/crates/manifest/src/compat.rs b/crates/manifest/src/compat.rs
index fd453fa5ee..4cb12d698d 100644
--- a/crates/manifest/src/compat.rs
+++ b/crates/manifest/src/compat.rs
@@ -21,6 +21,7 @@ pub fn v1_to_v2_app(manifest: v1::AppManifestV1) -> Result<v2::AppManifest, Erro
description: manifest.description,
authors: manifest.authors,
trigger_global_configs,
+ tool: Default::default(),
};
let app_variables = manifest
@@ -82,6 +83,7 @@ pub fn v1_to_v2_app(manifest: v1::AppManifestV1) -> Result<v2::AppManifest, Erro
sqlite_databases,
ai_models,
build: component.build,
+ tool: Default::default(),
allowed_outbound_hosts,
allowed_http_hosts: Vec::new(),
},
diff --git a/crates/manifest/src/schema/v2.rs b/crates/manifest/src/schema/v2.rs
index c51c9da24f..29b73e2355 100644
--- a/crates/manifest/src/schema/v2.rs
+++ b/crates/manifest/src/schema/v2.rs
@@ -44,6 +44,9 @@ pub struct AppDetails {
/// `[application.triggers.<type>]`
#[serde(rename = "trigger", default, skip_serializing_if = "Map::is_empty")]
pub trigger_global_configs: Map<String, toml::Table>,
+ /// Settings for custom tools or plugins. Spin ignores this field.
+ #[serde(default, skip_serializing_if = "Map::is_empty")]
+ pub tool: Map<String, toml::Table>,
}
/// Trigger configuration
@@ -131,6 +134,9 @@ pub struct Component {
/// Build configuration
#[serde(default, skip_serializing_if = "Option::is_none")]
pub build: Option<ComponentBuildConfig>,
+ /// Settings for custom tools or plugins. Spin ignores this field.
+ #[serde(default, skip_serializing_if = "Map::is_empty")]
+ pub tool: Map<String, toml::Table>,
}
impl Component {
@@ -224,6 +230,41 @@ mod tests {
FakeTriggerConfig::deserialize(manifest.triggers["fake"][0].config.clone()).unwrap();
}
+ #[derive(Deserialize)]
+ #[allow(dead_code)]
+ struct FakeGlobalToolConfig {
+ lint_level: String,
+ }
+
+ #[derive(Deserialize)]
+ #[allow(dead_code)]
+ struct FakeComponentToolConfig {
+ command: String,
+ }
+
+ #[test]
+ fn deserialising_custom_tool_settings() {
+ let manifest = AppManifest::deserialize(toml! {
+ spin_manifest_version = 2
+ [application]
+ name = "trigger-configs"
+ [application.tool.lint]
+ lint_level = "savage"
+ [[trigger.fake]]
+ something = "something else"
+ [component.fake]
+ source = "dummy"
+ [component.fake.tool.clean]
+ command = "cargo clean"
+ })
+ .unwrap();
+
+ FakeGlobalToolConfig::deserialize(manifest.application.tool["lint"].clone()).unwrap();
+ let fake_id: KebabId = "fake".to_owned().try_into().unwrap();
+ FakeComponentToolConfig::deserialize(manifest.components[&fake_id].tool["clean"].clone())
+ .unwrap();
+ }
+
#[test]
fn test_valid_snake_ids() {
for valid in ["default", "mixed_CASE_words", "letters1_then2_numbers345"] {
| 2,104
|
[
"1768"
] |
diff --git a/crates/manifest/tests/ui/maximal.json b/crates/manifest/tests/ui/maximal.json
index 4780f693b1..1968f2d32f 100644
--- a/crates/manifest/tests/ui/maximal.json
+++ b/crates/manifest/tests/ui/maximal.json
@@ -12,6 +12,11 @@
"fake": {
"global_option": true
}
+ },
+ "tool": {
+ "lint": {
+ "lint_level": "savage"
+ }
}
},
"variables": {
@@ -77,6 +82,11 @@
"watch": [
"src/**/*.rs"
]
+ },
+ "tool": {
+ "clean": {
+ "command": "cargo clean"
+ }
}
}
}
diff --git a/crates/manifest/tests/ui/maximal.toml b/crates/manifest/tests/ui/maximal.toml
index dba5abb55c..0fd7c96b06 100644
--- a/crates/manifest/tests/ui/maximal.toml
+++ b/crates/manifest/tests/ui/maximal.toml
@@ -9,6 +9,9 @@ authors = ["alice@example.com", "bob@example.com"]
[application.trigger.fake]
global_option = true
+[application.tool.lint]
+lint_level = "savage"
+
[variables]
var_one = { default = "Default" }
var_TWO = { required = true, secret = true }
@@ -38,3 +41,6 @@ ai_models = ["llama2-chat"]
command = "cargo build"
workdir = "my-component"
watch = ["src/**/*.rs"]
+
+[component.maximal-component.tool.clean]
+command = "cargo clean"
|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
273c684627837e48c141050ad10ec23f94244b45
|
Relax the .cache requirement for `spin_loader::from_file`
Hi there,
I was upgrading the spin shim from spin 1.x to 2.0.0 and found that the `spin_loader::from_file` function requires the work directory to either have `$HOME/.cache` or `XDG_CACHE_HOME` for Linux environment due to the usage of `dirs::cache_dir()`. I want to relex this requirement or at least provide a configuration to specify the cache directory in the API.
See this discussion: https://github.com/deislabs/containerd-wasm-shims/pull/177#discussion_r1385691274
Thanks!
|
Replied inline: https://github.com/deislabs/containerd-wasm-shims/pull/177#discussion_r1388210225
|
2023-11-14T20:25:31Z
|
fermyon__spin-2095
|
fermyon/spin
|
3.2
|
diff --git a/crates/loader/src/lib.rs b/crates/loader/src/lib.rs
index 86e625d79f..9b5d5f72b1 100644
--- a/crates/loader/src/lib.rs
+++ b/crates/loader/src/lib.rs
@@ -30,10 +30,11 @@ pub(crate) const MAX_FILE_LOADING_CONCURRENCY: usize = 16;
pub async fn from_file(
manifest_path: impl AsRef<Path>,
files_mount_strategy: FilesMountStrategy,
+ cache_root: Option<PathBuf>,
) -> Result<LockedApp> {
let path = manifest_path.as_ref();
let app_root = parent_dir(path)?;
- let loader = LocalLoader::new(&app_root, files_mount_strategy).await?;
+ let loader = LocalLoader::new(&app_root, files_mount_strategy, cache_root).await?;
loader.load_file(path).await
}
diff --git a/crates/loader/src/local.rs b/crates/loader/src/local.rs
index e0114c166f..ddea5ab7ab 100644
--- a/crates/loader/src/local.rs
+++ b/crates/loader/src/local.rs
@@ -25,14 +25,18 @@ pub struct LocalLoader {
}
impl LocalLoader {
- pub async fn new(app_root: &Path, files_mount_strategy: FilesMountStrategy) -> Result<Self> {
+ pub async fn new(
+ app_root: &Path,
+ files_mount_strategy: FilesMountStrategy,
+ cache_root: Option<PathBuf>,
+ ) -> Result<Self> {
let app_root = app_root
.canonicalize()
.with_context(|| format!("Invalid manifest dir `{}`", app_root.display()))?;
Ok(Self {
app_root,
files_mount_strategy,
- cache: Cache::new(None).await?,
+ cache: Cache::new(cache_root).await?,
// Limit concurrency to avoid hitting system resource limits
file_loading_permits: Semaphore::new(crate::MAX_FILE_LOADING_CONCURRENCY),
})
diff --git a/crates/oci/src/client.rs b/crates/oci/src/client.rs
index ffa1ce86c3..8bdb58a432 100644
--- a/crates/oci/src/client.rs
+++ b/crates/oci/src/client.rs
@@ -81,6 +81,7 @@ impl Client {
let locked = spin_loader::from_file(
manifest_path,
FilesMountStrategy::Copy(working_dir.path().into()),
+ None,
)
.await?;
diff --git a/src/commands/up.rs b/src/commands/up.rs
index 05bfe88c9d..a36e10d5a1 100644
--- a/src/commands/up.rs
+++ b/src/commands/up.rs
@@ -334,7 +334,7 @@ impl UpCommand {
} else {
FilesMountStrategy::Copy(working_dir.join("assets"))
};
- spin_loader::from_file(&manifest_path, files_mount_strategy)
+ spin_loader::from_file(&manifest_path, files_mount_strategy, None)
.await
.with_context(|| format!("Failed to load manifest from {manifest_path:?}"))
}
| 2,095
|
[
"2072"
] |
diff --git a/crates/loader/tests/ui.rs b/crates/loader/tests/ui.rs
index 8dc80d2858..2debf28203 100644
--- a/crates/loader/tests/ui.rs
+++ b/crates/loader/tests/ui.rs
@@ -49,6 +49,7 @@ fn run_test(input: &Path, normalizer: &mut Normalizer) -> Result<String, Failed>
let locked = spin_loader::from_file(
input,
spin_loader::FilesMountStrategy::Copy(files_mount_root),
+ None,
)
.await
.map_err(|err| format!("{err:?}"))?;
|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
40bbead627ef6c8f61706516e5f11f1122a33f21
|
Manifest(v2): improved error when component id not kebab-case
For v2 manifests (`spin_manifest_version = 2`), the [component ID must be kebab-case](https://github.com/fermyon/spin/blob/main/crates/manifest/src/schema/v2.rs) if employing separators. When not in this form, the `spin up` error should mention this. As of current writing, the following error is seen:
```
Error: Failed to load manifest from "spin.toml"
Caused by:
0: Failed to read Spin app manifest from "spin.toml"
1: TOML parse error at line 14, column 13
|
14 | component = "spin_config_tinygo"
| ^^^^^^^^^^^^^^^^^^^^
data did not match any variant of untagged enum ComponentSpec
```
|
2023-11-13T14:14:18Z
|
fermyon__spin-2092
|
fermyon/spin
|
3.2
|
diff --git a/crates/manifest/src/schema/v2.rs b/crates/manifest/src/schema/v2.rs
index 18c5233ee5..c51c9da24f 100644
--- a/crates/manifest/src/schema/v2.rs
+++ b/crates/manifest/src/schema/v2.rs
@@ -70,7 +70,7 @@ pub struct OneOrManyComponentSpecs(#[serde(with = "one_or_many")] pub Vec<Compon
/// Component reference or inline definition
#[derive(Clone, Debug, Serialize, Deserialize)]
-#[serde(deny_unknown_fields, untagged)]
+#[serde(deny_unknown_fields, untagged, try_from = "toml::Value")]
pub enum ComponentSpec {
/// `"component-id"`
Reference(KebabId),
@@ -78,6 +78,20 @@ pub enum ComponentSpec {
Inline(Box<Component>),
}
+impl TryFrom<toml::Value> for ComponentSpec {
+ type Error = toml::de::Error;
+
+ fn try_from(value: toml::Value) -> Result<Self, Self::Error> {
+ if value.is_str() {
+ Ok(ComponentSpec::Reference(KebabId::deserialize(value)?))
+ } else {
+ Ok(ComponentSpec::Inline(Box::new(Component::deserialize(
+ value,
+ )?)))
+ }
+ }
+}
+
/// Component definition
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
| 2,092
|
[
"1950"
] |
diff --git a/crates/manifest/tests/ui/invalid/bad_kebab_component_ref.err b/crates/manifest/tests/ui/invalid/bad_kebab_component_ref.err
new file mode 100644
index 0000000000..59fdcfcc82
--- /dev/null
+++ b/crates/manifest/tests/ui/invalid/bad_kebab_component_ref.err
@@ -0,0 +1,6 @@
+TOML parse error at line 7, column 13
+ |
+7 | component = "1-2-3"
+ | ^^^^^^^
+'-'-separated words must start with an ASCII letter; got '1'
+
diff --git a/crates/manifest/tests/ui/invalid/bad_kebab_component_ref.toml b/crates/manifest/tests/ui/invalid/bad_kebab_component_ref.toml
new file mode 100644
index 0000000000..a3960eec7b
--- /dev/null
+++ b/crates/manifest/tests/ui/invalid/bad_kebab_component_ref.toml
@@ -0,0 +1,7 @@
+spin_manifest_version = 2
+
+[application]
+name = "minimal-v2"
+
+[[trigger.fake]]
+component = "1-2-3"
\ No newline at end of file
|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
|
fb03aadaefbde4e4d3a26169782f5efa44847940
|
Outgoing post requests send(Request::post(...)) do not work
spin 2.0.0 (e4bb235 2023-11-03)
cloud 0.5.1 [installed]
js2wasm 0.6.1 [installed]
py2wasm 0.3.2 [installed]
I am trying to send an outgoing post request with some payload but the http::send() does not finish.
```rust
#[http_component]
async fn handle_notion_ical_fermyon(req: Request) -> Result<impl IntoResponse> {
let body = "{data: [1]}";
let request = RequestBuilder::new(Method::Post, "")
.uri(&format!("http://localhost:3001",))
.method(Method::Post)
.body(body)
.build();
let response: IncomingResponse = send(request).await?;
// unreachable
let status = response.status();
tracing::info!(?status);
Ok(Response::builder()
.status(200)
.header("content-type", "text/plain")
.body("Hello, Fermyon")?)
}
```
Inside send() it's stuck here
```rust
let response = executor::outgoing_request_send(request)
.await
.map_err(SendError::Http)?;
```
|
I wrote a dummy server that outputs incoming requests:
INFO dummy_server: req: Request { method: POST, uri: http://localhost:3001/, version: HTTP/1.1, headers: {"host": "localhost:3001", "transfer-encoding": "chunked"}, body: Body(Streaming) }
at src/main.rs:9
INFO dummy_server: Body(Streaming)
at src/main.rs:12
And it seems the body is never streamed.
Hello, thanks for the report. I have confirmed this problem; we're looking into it.
Also, please note that streaming support is experimental. We have been expecting hiccups. :slightly_smiling_face:
I think the issue here is that the `http_component` macro is a bit too flexible and is allowing function signatures which we didn't necessarily mean to support. The intention was that `async` handlers would use a `wasi-http` style handler function, e.g. `async fn handle_request(request: IncomingRequest, response_out: ResponseOutparam)`, which is well-tested. Combining the non-streaming `Request` and `Response` types with `async` is not something we thought to try or support.
I'll dig into this to understand exactly where it's breaking, but the solution may be to simply disallow that combination in the macro. Meanwhile, the workaround is to use the `wasi-http` types instead -- see the `wasi-http-rust-streaming-outgoing-body` example in this repository for reference.
Ok, nevermind what I said above -- looks like this scenario _is_ intended to work after all and I accidentally broke it. Sorry about that! I'll have a PR up to fix it shortly.
|
2023-11-10T16:34:48Z
|
fermyon__spin-2086
|
fermyon/spin
|
2.0
|
diff --git a/Cargo.lock b/Cargo.lock
index 1191cd0198..c50558a2ba 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5637,6 +5637,7 @@ dependencies = [
"futures",
"glob",
"hex",
+ "http-body-util",
"hyper 1.0.0-rc.3",
"indicatif 0.17.6",
"is-terminal",
diff --git a/Cargo.toml b/Cargo.toml
index 2acf7c4205..66b792c7fd 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -86,6 +86,7 @@ hyper = { workspace = true }
sha2 = "0.10.1"
which = "4.2.5"
e2e-testing = { path = "crates/e2e-testing" }
+http-body-util = { workspace = true }
[build-dependencies]
cargo-target-dep = { git = "https://github.com/fermyon/cargo-target-dep", rev = "b7b1989fe0984c0f7c4966398304c6538e52fe49" }
diff --git a/build.rs b/build.rs
index 48c5ca8a27..ec5ebbec6b 100644
--- a/build.rs
+++ b/build.rs
@@ -13,6 +13,7 @@ const RUST_HTTP_VAULT_VARIABLES_TEST: &str = "tests/http/vault-variables-test";
const RUST_OUTBOUND_REDIS_INTEGRATION_TEST: &str = "tests/outbound-redis/http-rust-outbound-redis";
const TIMER_TRIGGER_INTEGRATION_TEST: &str = "examples/spin-timer/app-example";
const WASI_HTTP_INTEGRATION_TEST: &str = "examples/wasi-http-rust-streaming-outgoing-body";
+const OUTBOUND_HTTP_POST_INTEGRATION_TEST: &str = "examples/http-rust-outbound-post";
fn main() {
// Extract environment information to be passed to plugins.
@@ -92,6 +93,7 @@ error: the `wasm32-wasi` target is not installed
cargo_build(RUST_OUTBOUND_REDIS_INTEGRATION_TEST);
cargo_build(TIMER_TRIGGER_INTEGRATION_TEST);
cargo_build(WASI_HTTP_INTEGRATION_TEST);
+ cargo_build(OUTBOUND_HTTP_POST_INTEGRATION_TEST);
}
fn build_wasm_test_program(name: &'static str, root: &'static str) {
diff --git a/examples/http-rust-outbound-post/.cargo/config.toml b/examples/http-rust-outbound-post/.cargo/config.toml
new file mode 100644
index 0000000000..6b77899cb3
--- /dev/null
+++ b/examples/http-rust-outbound-post/.cargo/config.toml
@@ -0,0 +1,2 @@
+[build]
+target = "wasm32-wasi"
diff --git a/examples/http-rust-outbound-post/Cargo.lock b/examples/http-rust-outbound-post/Cargo.lock
new file mode 100644
index 0000000000..65034ef19a
--- /dev/null
+++ b/examples/http-rust-outbound-post/Cargo.lock
@@ -0,0 +1,723 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 3
+
+[[package]]
+name = "anyhow"
+version = "1.0.75"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
+
+[[package]]
+name = "async-trait"
+version = "0.1.74"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.39",
+]
+
+[[package]]
+name = "autocfg"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
+
+[[package]]
+name = "bitflags"
+version = "2.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "327762f6e5a765692301e5bb513e0d9fef63be86bbc14528052b1cd3e6f03e07"
+
+[[package]]
+name = "block-buffer"
+version = "0.10.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
+dependencies = [
+ "generic-array",
+]
+
+[[package]]
+name = "bytes"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2bd12c1caf447e69cd4528f47f94d203fd2582878ecb9e9465484c4148a8223"
+
+[[package]]
+name = "cfg-if"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
+
+[[package]]
+name = "cpufeatures"
+version = "0.2.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce420fe07aecd3e67c5f910618fe65e94158f6dcc0adf44e00d69ce2bdfe0fd0"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "crypto-common"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3"
+dependencies = [
+ "generic-array",
+ "typenum",
+]
+
+[[package]]
+name = "digest"
+version = "0.10.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
+dependencies = [
+ "block-buffer",
+ "crypto-common",
+]
+
+[[package]]
+name = "equivalent"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5"
+
+[[package]]
+name = "fnv"
+version = "1.0.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
+
+[[package]]
+name = "form_urlencoded"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a62bc1cf6f830c2ec14a513a9fb124d0a213a629668a4186f329db21fe045652"
+dependencies = [
+ "percent-encoding",
+]
+
+[[package]]
+name = "futures"
+version = "0.3.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "da0290714b38af9b4a7b094b8a37086d1b4e61f2df9122c3cad2577669145335"
+dependencies = [
+ "futures-channel",
+ "futures-core",
+ "futures-executor",
+ "futures-io",
+ "futures-sink",
+ "futures-task",
+ "futures-util",
+]
+
+[[package]]
+name = "futures-channel"
+version = "0.3.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff4dd66668b557604244583e3e1e1eada8c5c2e96a6d0d6653ede395b78bbacb"
+dependencies = [
+ "futures-core",
+ "futures-sink",
+]
+
+[[package]]
+name = "futures-core"
+version = "0.3.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eb1d22c66e66d9d72e1758f0bd7d4fd0bee04cad842ee34587d68c07e45d088c"
+
+[[package]]
+name = "futures-executor"
+version = "0.3.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0f4fb8693db0cf099eadcca0efe2a5a22e4550f98ed16aba6c48700da29597bc"
+dependencies = [
+ "futures-core",
+ "futures-task",
+ "futures-util",
+]
+
+[[package]]
+name = "futures-io"
+version = "0.3.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8bf34a163b5c4c52d0478a4d757da8fb65cabef42ba90515efee0f6f9fa45aaa"
+
+[[package]]
+name = "futures-macro"
+version = "0.3.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "53b153fd91e4b0147f4aced87be237c98248656bb01050b96bf3ee89220a8ddb"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.39",
+]
+
+[[package]]
+name = "futures-sink"
+version = "0.3.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e36d3378ee38c2a36ad710c5d30c2911d752cb941c00c72dbabfb786a7970817"
+
+[[package]]
+name = "futures-task"
+version = "0.3.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "efd193069b0ddadc69c46389b740bbccdd97203899b48d09c5f7969591d6bae2"
+
+[[package]]
+name = "futures-util"
+version = "0.3.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a19526d624e703a3179b3d322efec918b6246ea0fa51d41124525f00f1cc8104"
+dependencies = [
+ "futures-channel",
+ "futures-core",
+ "futures-io",
+ "futures-macro",
+ "futures-sink",
+ "futures-task",
+ "memchr",
+ "pin-project-lite",
+ "pin-utils",
+ "slab",
+]
+
+[[package]]
+name = "generic-array"
+version = "0.14.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
+dependencies = [
+ "typenum",
+ "version_check",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.14.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f93e7192158dbcda357bdec5fb5788eebf8bbac027f3f33e719d29135ae84156"
+
+[[package]]
+name = "heck"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
+dependencies = [
+ "unicode-segmentation",
+]
+
+[[package]]
+name = "hex"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
+
+[[package]]
+name = "http"
+version = "0.2.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f95b9abcae896730d42b78e09c155ed4ddf82c07b4de772c64aee5b2d8b7c150"
+dependencies = [
+ "bytes",
+ "fnv",
+ "itoa",
+]
+
+[[package]]
+name = "id-arena"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "25a2bc672d1148e28034f176e01fffebb08b35768468cc954630da77a1449005"
+
+[[package]]
+name = "idna"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7d20d6b07bfbc108882d88ed8e37d39636dcc260e15e30c45e6ba089610b917c"
+dependencies = [
+ "unicode-bidi",
+ "unicode-normalization",
+]
+
+[[package]]
+name = "indexmap"
+version = "2.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d530e1a18b1cb4c484e6e34556a0d948706958449fca0cab753d649f2bce3d1f"
+dependencies = [
+ "equivalent",
+ "hashbrown",
+ "serde",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38"
+
+[[package]]
+name = "leb128"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "884e2677b40cc8c339eaefcb701c32ef1fd2493d71118dc0ca4b6a736c93bd67"
+
+[[package]]
+name = "libc"
+version = "0.2.150"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "89d92a4743f9a61002fae18374ed11e7973f530cb3a3255fb354818118b2203c"
+
+[[package]]
+name = "log"
+version = "0.4.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f"
+
+[[package]]
+name = "memchr"
+version = "2.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f665ee40bc4a3c5590afb1e9677db74a508659dfd71e126420da8274909a0167"
+
+[[package]]
+name = "once_cell"
+version = "1.18.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d"
+
+[[package]]
+name = "percent-encoding"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b2a4787296e9989611394c33f193f676704af1686e70b8f8033ab5ba9a35a94"
+
+[[package]]
+name = "pin-project-lite"
+version = "0.2.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8afb450f006bf6385ca15ef45d71d2288452bc3683ce2e2cacc0d18e4be60b58"
+
+[[package]]
+name = "pin-utils"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.69"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "134c189feb4956b20f6f547d2cf727d4c0fe06722b20a0eec87ed445a97f92da"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.33"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "routefinder"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "94f8f99b10dedd317514253dda1fa7c14e344aac96e1f78149a64879ce282aca"
+dependencies = [
+ "smartcow",
+ "smartstring",
+]
+
+[[package]]
+name = "ryu"
+version = "1.0.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741"
+
+[[package]]
+name = "semver"
+version = "1.0.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "836fa6a3e1e547f9a2c4040802ec865b5d85f4014efe00555d7090a3dcaa1090"
+
+[[package]]
+name = "serde"
+version = "1.0.192"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bca2a08484b285dcb282d0f67b26cadc0df8b19f8c12502c13d966bf9482f001"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.192"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d6c7207fbec9faa48073f3e3074cbe553af6ea512d7c21ba46e434e70ea9fbc1"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.39",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.108"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d1c7e3eac408d115102c4c24ad393e0821bb3a5df4d506a80f85f7a742a526b"
+dependencies = [
+ "itoa",
+ "ryu",
+ "serde",
+]
+
+[[package]]
+name = "sha2"
+version = "0.10.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "793db75ad2bcafc3ffa7c68b215fee268f537982cd901d132f89c6343f3a3dc8"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "digest",
+]
+
+[[package]]
+name = "slab"
+version = "0.4.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "smallvec"
+version = "1.11.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4dccd0940a2dcdf68d092b8cbab7dc0ad8fa938bf95787e1b916b0e3d0e8e970"
+
+[[package]]
+name = "smartcow"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "656fcb1c1fca8c4655372134ce87d8afdf5ec5949ebabe8d314be0141d8b5da2"
+dependencies = [
+ "smartstring",
+]
+
+[[package]]
+name = "smartstring"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3fb72c633efbaa2dd666986505016c32c3044395ceaf881518399d2f4127ee29"
+dependencies = [
+ "autocfg",
+ "static_assertions",
+ "version_check",
+]
+
+[[package]]
+name = "spdx"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b19b32ed6d899ab23174302ff105c1577e45a06b08d4fe0a9dd13ce804bbbf71"
+dependencies = [
+ "smallvec",
+]
+
+[[package]]
+name = "spin-macro"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "bytes",
+ "http",
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+]
+
+[[package]]
+name = "spin-outbound-post"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "futures",
+ "hex",
+ "sha2",
+ "spin-sdk",
+ "url",
+]
+
+[[package]]
+name = "spin-sdk"
+version = "2.0.0"
+dependencies = [
+ "anyhow",
+ "async-trait",
+ "bytes",
+ "form_urlencoded",
+ "futures",
+ "http",
+ "once_cell",
+ "routefinder",
+ "serde",
+ "serde_json",
+ "spin-macro",
+ "thiserror",
+ "wit-bindgen",
+]
+
+[[package]]
+name = "static_assertions"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
+
+[[package]]
+name = "syn"
+version = "1.0.109"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "syn"
+version = "2.0.39"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23e78b90f2fcf45d3e842032ce32e3f2d1545ba6636271dcbf24fa306d87be7a"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "thiserror"
+version = "1.0.50"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f9a7210f5c9a7156bb50aa36aed4c95afb51df0df00713949448cf9e97d382d2"
+dependencies = [
+ "thiserror-impl",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "1.0.50"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "266b2e40bc00e5a6c09c3584011e08b06f123c00362c92b975ba9843aaaa14b8"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.39",
+]
+
+[[package]]
+name = "tinyvec"
+version = "1.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50"
+dependencies = [
+ "tinyvec_macros",
+]
+
+[[package]]
+name = "tinyvec_macros"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
+
+[[package]]
+name = "typenum"
+version = "1.17.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825"
+
+[[package]]
+name = "unicode-bidi"
+version = "0.3.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92888ba5573ff080736b3648696b70cafad7d250551175acbaa4e0385b3e1460"
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
+
+[[package]]
+name = "unicode-normalization"
+version = "0.1.22"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c5713f0fc4b5db668a2ac63cdb7bb4469d8c9fed047b1d0292cc7b0ce2ba921"
+dependencies = [
+ "tinyvec",
+]
+
+[[package]]
+name = "unicode-segmentation"
+version = "1.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1dd624098567895118886609431a7c3b8f516e41d30e0643f03d94592a147e36"
+
+[[package]]
+name = "unicode-xid"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f962df74c8c05a667b5ee8bcf162993134c104e96440b663c8daa176dc772d8c"
+
+[[package]]
+name = "url"
+version = "2.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "143b538f18257fac9cad154828a57c6bf5157e1aa604d4816b5995bf6de87ae5"
+dependencies = [
+ "form_urlencoded",
+ "idna",
+ "percent-encoding",
+]
+
+[[package]]
+name = "version_check"
+version = "0.9.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
+
+[[package]]
+name = "wasm-encoder"
+version = "0.36.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "822b645bf4f2446b949776ffca47e2af60b167209ffb70814ef8779d299cd421"
+dependencies = [
+ "leb128",
+]
+
+[[package]]
+name = "wasm-metadata"
+version = "0.10.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2167ce53b2faa16a92c6cafd4942cff16c9a4fa0c5a5a0a41131ee4e49fc055f"
+dependencies = [
+ "anyhow",
+ "indexmap",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "spdx",
+ "wasm-encoder",
+ "wasmparser",
+]
+
+[[package]]
+name = "wasmparser"
+version = "0.116.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a58e28b80dd8340cb07b8242ae654756161f6fc8d0038123d679b7b99964fa50"
+dependencies = [
+ "indexmap",
+ "semver",
+]
+
+[[package]]
+name = "wit-bindgen"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "38726c54a5d7c03cac28a2a8de1006cfe40397ddf6def3f836189033a413bc08"
+dependencies = [
+ "bitflags",
+ "wit-bindgen-rust-macro",
+]
+
+[[package]]
+name = "wit-bindgen-core"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c8bf1fddccaff31a1ad57432d8bfb7027a7e552969b6c68d6d8820dcf5c2371f"
+dependencies = [
+ "anyhow",
+ "wit-component",
+ "wit-parser",
+]
+
+[[package]]
+name = "wit-bindgen-rust"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0e7200e565124801e01b7b5ddafc559e1da1b2e1bed5364d669cd1d96fb88722"
+dependencies = [
+ "anyhow",
+ "heck",
+ "wasm-metadata",
+ "wit-bindgen-core",
+ "wit-component",
+]
+
+[[package]]
+name = "wit-bindgen-rust-macro"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ae33920ad8119fe72cf59eb00f127c0b256a236b9de029a1a10397b1f38bdbd"
+dependencies = [
+ "anyhow",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.39",
+ "wit-bindgen-core",
+ "wit-bindgen-rust",
+ "wit-component",
+]
+
+[[package]]
+name = "wit-component"
+version = "0.17.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "480cc1a078b305c1b8510f7c455c76cbd008ee49935f3a6c5fd5e937d8d95b1e"
+dependencies = [
+ "anyhow",
+ "bitflags",
+ "indexmap",
+ "log",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "wasm-encoder",
+ "wasm-metadata",
+ "wasmparser",
+ "wit-parser",
+]
+
+[[package]]
+name = "wit-parser"
+version = "0.12.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "43771ee863a16ec4ecf9da0fc65c3bbd4a1235c8e3da5f094b562894843dfa76"
+dependencies = [
+ "anyhow",
+ "id-arena",
+ "indexmap",
+ "log",
+ "semver",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "unicode-xid",
+]
diff --git a/examples/http-rust-outbound-post/Cargo.toml b/examples/http-rust-outbound-post/Cargo.toml
new file mode 100644
index 0000000000..412fc15578
--- /dev/null
+++ b/examples/http-rust-outbound-post/Cargo.toml
@@ -0,0 +1,17 @@
+[package]
+name = "spin-outbound-post"
+version = "0.1.0"
+edition = "2021"
+
+[lib]
+crate-type = ["cdylib"]
+
+[dependencies]
+anyhow = "1.0.71"
+futures = "0.3.28"
+hex = "0.4.3"
+sha2 = "0.10.6"
+url = "2.4.0"
+spin-sdk = { path = "../../sdk/rust" }
+
+[workspace]
diff --git a/examples/http-rust-outbound-post/spin.toml b/examples/http-rust-outbound-post/spin.toml
new file mode 100644
index 0000000000..7ca703f5dc
--- /dev/null
+++ b/examples/http-rust-outbound-post/spin.toml
@@ -0,0 +1,18 @@
+spin_manifest_version = 2
+
+[application]
+authors = ["Fermyon Engineering <engineering@fermyon.com>"]
+description = "Demonstrates outbound HTTP calls"
+name = "spin-outbound-post"
+version = "1.0.0"
+
+[[trigger.http]]
+route = "/..."
+component = "spin-outbound-post"
+
+[component.spin-outbound-post]
+source = "target/wasm32-wasi/release/spin_outbound_post.wasm"
+allowed_outbound_hosts = ["http://*:*", "https://*:*"]
+[component.spin-outbound-post.build]
+command = "cargo build --target wasm32-wasi --release"
+watch = ["src/**/*.rs", "Cargo.toml"]
diff --git a/examples/http-rust-outbound-post/src/lib.rs b/examples/http-rust-outbound-post/src/lib.rs
new file mode 100644
index 0000000000..d5f93bafe3
--- /dev/null
+++ b/examples/http-rust-outbound-post/src/lib.rs
@@ -0,0 +1,30 @@
+use {
+ anyhow::{anyhow, Result},
+ spin_sdk::{
+ http::{self, IncomingResponse, IntoResponse, Method, Request, RequestBuilder, Response},
+ http_component,
+ },
+};
+
+#[http_component]
+async fn handle(req: Request) -> Result<impl IntoResponse> {
+ let request = RequestBuilder::new(Method::Post, "/")
+ .uri(
+ req.header("url")
+ .ok_or_else(|| anyhow!("missing url header"))?
+ .as_str()
+ .ok_or_else(|| anyhow!("invalid utf-8 in url header value"))?,
+ )
+ .method(Method::Post)
+ .body("Hello, world!")
+ .build();
+
+ let response: IncomingResponse = http::send(request).await?;
+ let status = response.status();
+
+ Ok(Response::builder()
+ .status(200)
+ .header("content-type", "text/plain")
+ .body(format!("response status: {status}"))
+ .build())
+}
diff --git a/sdk/rust/src/http.rs b/sdk/rust/src/http.rs
index dd6c6f9f9d..5705480400 100644
--- a/sdk/rust/src/http.rs
+++ b/sdk/rust/src/http.rs
@@ -363,7 +363,7 @@ impl HeaderValue {
pub fn as_str(&self) -> Option<&str> {
match &self.inner {
HeaderValueRep::String(s) => Some(s),
- HeaderValueRep::Bytes(_) => None,
+ HeaderValueRep::Bytes(b) => std::str::from_utf8(b).ok(),
}
}
@@ -587,14 +587,13 @@ where
// It is part of the contract of the trait that implementors of `TryIntoOutgoingRequest`
// do not call `OutgoingRequest::write`` if they return a buffered body.
let mut body_sink = request.take_body();
- let response = executor::outgoing_request_send(request)
- .await
- .map_err(SendError::Http)?;
+ let response = executor::outgoing_request_send(request);
body_sink
.send(body_buffer)
.await
.map_err(|e| SendError::Http(Error::UnexpectedError(e.to_string())))?;
- response
+ drop(body_sink);
+ response.await.map_err(SendError::Http)?
} else {
executor::outgoing_request_send(request)
.await
diff --git a/sdk/rust/src/http/executor.rs b/sdk/rust/src/http/executor.rs
index aedc7182d5..5852681a90 100644
--- a/sdk/rust/src/http/executor.rs
+++ b/sdk/rust/src/http/executor.rs
@@ -91,7 +91,6 @@ pub(crate) fn outgoing_body(body: OutgoingBody) -> impl Sink<Vec<u8>, Error = ty
move |context| {
let pair = pair.borrow();
let (stream, _) = &pair.0.as_ref().unwrap();
-
loop {
match stream.check_write() {
Ok(0) => {
| 2,086
|
[
"2080"
] |
diff --git a/tests/http/headers-env-routes-test/Cargo.lock b/tests/http/headers-env-routes-test/Cargo.lock
index d57a7d2a78..490730043f 100644
--- a/tests/http/headers-env-routes-test/Cargo.lock
+++ b/tests/http/headers-env-routes-test/Cargo.lock
@@ -377,7 +377,7 @@ dependencies = [
[[package]]
name = "spin-sdk"
-version = "2.0.0-rc.1"
+version = "2.0.0"
dependencies = [
"anyhow",
"async-trait",
diff --git a/tests/http/simple-spin-rust/Cargo.lock b/tests/http/simple-spin-rust/Cargo.lock
index 058f48c78d..a25ae3c9a9 100644
--- a/tests/http/simple-spin-rust/Cargo.lock
+++ b/tests/http/simple-spin-rust/Cargo.lock
@@ -376,7 +376,7 @@ dependencies = [
[[package]]
name = "spin-sdk"
-version = "2.0.0-rc.1"
+version = "2.0.0"
dependencies = [
"anyhow",
"async-trait",
diff --git a/tests/http/vault-variables-test/Cargo.lock b/tests/http/vault-variables-test/Cargo.lock
index f56259bcd4..c705762b5f 100644
--- a/tests/http/vault-variables-test/Cargo.lock
+++ b/tests/http/vault-variables-test/Cargo.lock
@@ -367,7 +367,7 @@ dependencies = [
[[package]]
name = "spin-sdk"
-version = "2.0.0-rc.1"
+version = "2.0.0"
dependencies = [
"anyhow",
"async-trait",
diff --git a/tests/integration.rs b/tests/integration.rs
index 45315517fc..14f09eafc3 100644
--- a/tests/integration.rs
+++ b/tests/integration.rs
@@ -2,6 +2,7 @@
mod integration_tests {
use anyhow::{anyhow, Context, Error, Result};
use futures::{channel::oneshot, future, stream, FutureExt};
+ use http_body_util::BodyExt;
use hyper::{body::Bytes, server::conn::http1, service::service_fn, Method, StatusCode};
use reqwest::{Client, Response};
use sha2::{Digest, Sha256};
@@ -14,7 +15,7 @@ mod integration_tests {
net::{Ipv4Addr, SocketAddrV4, TcpListener},
path::Path,
process::{self, Child, Command, Output},
- sync::Arc,
+ sync::{Arc, Mutex},
time::Duration,
};
use tempfile::tempdir;
@@ -674,6 +675,88 @@ route = "/..."
do_test_build_command("tests/build/simple").await
}
+ #[tokio::test]
+ async fn test_outbound_post() -> Result<()> {
+ let listener = tokio::net::TcpListener::bind((Ipv4Addr::new(127, 0, 0, 1), 0)).await?;
+
+ let prefix = format!("http://{}", listener.local_addr()?);
+
+ let body = Arc::new(Mutex::new(Vec::new()));
+
+ let server = {
+ let body = body.clone();
+ async move {
+ loop {
+ let (stream, _) = listener.accept().await?;
+ let body = body.clone();
+ task::spawn(async move {
+ if let Err(e) = http1::Builder::new()
+ .keep_alive(true)
+ .serve_connection(
+ stream,
+ service_fn(
+ move |request: hyper::Request<hyper::body::Incoming>| {
+ let body = body.clone();
+ async move {
+ if let &Method::POST = request.method() {
+ let req_body = request.into_body();
+ let bytes =
+ req_body.collect().await?.to_bytes().to_vec();
+ *body.lock().unwrap() = bytes;
+ Ok::<_, Error>(hyper::Response::new(body::empty()))
+ } else {
+ Ok(hyper::Response::builder()
+ .status(StatusCode::METHOD_NOT_ALLOWED)
+ .body(body::empty())?)
+ }
+ }
+ },
+ ),
+ )
+ .await
+ {
+ log::warn!("{e:?}");
+ }
+ });
+
+ // Help rustc with type inference:
+ if false {
+ return Ok::<_, Error>(());
+ }
+ }
+ }
+ }
+ .then(|result| {
+ if let Err(e) = result {
+ log::warn!("{e:?}");
+ }
+ future::ready(())
+ })
+ .boxed();
+
+ let (_tx, rx) = oneshot::channel::<()>();
+
+ task::spawn(async move {
+ drop(future::select(server, rx).await);
+ });
+ let controller = SpinTestController::with_manifest(
+ "examples/http-rust-outbound-post/spin.toml",
+ &[],
+ &[],
+ )
+ .await?;
+
+ let response = Client::new()
+ .get(format!("http://{}/", controller.url))
+ .header("url", format!("{prefix}/"))
+ .send()
+ .await?;
+ assert_eq!(200, response.status());
+ assert_eq!(b"Hello, world!", body.lock().unwrap().as_slice());
+
+ Ok(())
+ }
+
#[tokio::test]
async fn test_wasi_http_hash_all() -> Result<()> {
let bodies = Arc::new(
diff --git a/tests/outbound-redis/http-rust-outbound-redis/Cargo.lock b/tests/outbound-redis/http-rust-outbound-redis/Cargo.lock
index c967fa6eee..73eeb114cf 100644
--- a/tests/outbound-redis/http-rust-outbound-redis/Cargo.lock
+++ b/tests/outbound-redis/http-rust-outbound-redis/Cargo.lock
@@ -377,7 +377,7 @@ dependencies = [
[[package]]
name = "spin-sdk"
-version = "2.0.0-rc.1"
+version = "2.0.0"
dependencies = [
"anyhow",
"async-trait",
|
fb03aadaefbde4e4d3a26169782f5efa44847940
|
3fbff440a53fb45a8d8df25d763f9141c65af614
|
Outgoing post requests send(Request::post(...)) do not work
spin 2.0.0 (e4bb235 2023-11-03)
cloud 0.5.1 [installed]
js2wasm 0.6.1 [installed]
py2wasm 0.3.2 [installed]
I am trying to send an outgoing post request with some payload but the http::send() does not finish.
```rust
#[http_component]
async fn handle_notion_ical_fermyon(req: Request) -> Result<impl IntoResponse> {
let body = "{data: [1]}";
let request = RequestBuilder::new(Method::Post, "")
.uri(&format!("http://localhost:3001",))
.method(Method::Post)
.body(body)
.build();
let response: IncomingResponse = send(request).await?;
// unreachable
let status = response.status();
tracing::info!(?status);
Ok(Response::builder()
.status(200)
.header("content-type", "text/plain")
.body("Hello, Fermyon")?)
}
```
Inside send() it's stuck here
```rust
let response = executor::outgoing_request_send(request)
.await
.map_err(SendError::Http)?;
```
|
I wrote a dummy server that outputs incoming requests:
INFO dummy_server: req: Request { method: POST, uri: http://localhost:3001/, version: HTTP/1.1, headers: {"host": "localhost:3001", "transfer-encoding": "chunked"}, body: Body(Streaming) }
at src/main.rs:9
INFO dummy_server: Body(Streaming)
at src/main.rs:12
And it seems the body is never streamed.
Hello, thanks for the report. I have confirmed this problem; we're looking into it.
Also, please note that streaming support is experimental. We have been expecting hiccups. :slightly_smiling_face:
I think the issue here is that the `http_component` macro is a bit too flexible and is allowing function signatures which we didn't necessarily mean to support. The intention was that `async` handlers would use a `wasi-http` style handler function, e.g. `async fn handle_request(request: IncomingRequest, response_out: ResponseOutparam)`, which is well-tested. Combining the non-streaming `Request` and `Response` types with `async` is not something we thought to try or support.
I'll dig into this to understand exactly where it's breaking, but the solution may be to simply disallow that combination in the macro. Meanwhile, the workaround is to use the `wasi-http` types instead -- see the `wasi-http-rust-streaming-outgoing-body` example in this repository for reference.
Ok, nevermind what I said above -- looks like this scenario _is_ intended to work after all and I accidentally broke it. Sorry about that! I'll have a PR up to fix it shortly.
|
2023-11-10T16:13:07Z
|
fermyon__spin-2083
|
fermyon/spin
|
3.2
|
diff --git a/Cargo.lock b/Cargo.lock
index 4c03d62ec7..5d16ce9406 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5647,6 +5647,7 @@ dependencies = [
"futures",
"glob",
"hex",
+ "http-body-util",
"hyper 1.0.0-rc.3",
"indicatif 0.17.6",
"is-terminal",
diff --git a/Cargo.toml b/Cargo.toml
index e304790437..1c94ce6f99 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -86,6 +86,7 @@ hyper = { workspace = true }
sha2 = "0.10.1"
which = "4.2.5"
e2e-testing = { path = "crates/e2e-testing" }
+http-body-util = { workspace = true }
[build-dependencies]
cargo-target-dep = { git = "https://github.com/fermyon/cargo-target-dep", rev = "b7b1989fe0984c0f7c4966398304c6538e52fe49" }
diff --git a/build.rs b/build.rs
index 48c5ca8a27..ec5ebbec6b 100644
--- a/build.rs
+++ b/build.rs
@@ -13,6 +13,7 @@ const RUST_HTTP_VAULT_VARIABLES_TEST: &str = "tests/http/vault-variables-test";
const RUST_OUTBOUND_REDIS_INTEGRATION_TEST: &str = "tests/outbound-redis/http-rust-outbound-redis";
const TIMER_TRIGGER_INTEGRATION_TEST: &str = "examples/spin-timer/app-example";
const WASI_HTTP_INTEGRATION_TEST: &str = "examples/wasi-http-rust-streaming-outgoing-body";
+const OUTBOUND_HTTP_POST_INTEGRATION_TEST: &str = "examples/http-rust-outbound-post";
fn main() {
// Extract environment information to be passed to plugins.
@@ -92,6 +93,7 @@ error: the `wasm32-wasi` target is not installed
cargo_build(RUST_OUTBOUND_REDIS_INTEGRATION_TEST);
cargo_build(TIMER_TRIGGER_INTEGRATION_TEST);
cargo_build(WASI_HTTP_INTEGRATION_TEST);
+ cargo_build(OUTBOUND_HTTP_POST_INTEGRATION_TEST);
}
fn build_wasm_test_program(name: &'static str, root: &'static str) {
diff --git a/examples/http-rust-outbound-post/.cargo/config.toml b/examples/http-rust-outbound-post/.cargo/config.toml
new file mode 100644
index 0000000000..6b77899cb3
--- /dev/null
+++ b/examples/http-rust-outbound-post/.cargo/config.toml
@@ -0,0 +1,2 @@
+[build]
+target = "wasm32-wasi"
diff --git a/examples/http-rust-outbound-post/Cargo.lock b/examples/http-rust-outbound-post/Cargo.lock
new file mode 100644
index 0000000000..2f28dd1117
--- /dev/null
+++ b/examples/http-rust-outbound-post/Cargo.lock
@@ -0,0 +1,723 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 3
+
+[[package]]
+name = "anyhow"
+version = "1.0.75"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
+
+[[package]]
+name = "async-trait"
+version = "0.1.74"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.39",
+]
+
+[[package]]
+name = "autocfg"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
+
+[[package]]
+name = "bitflags"
+version = "2.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "327762f6e5a765692301e5bb513e0d9fef63be86bbc14528052b1cd3e6f03e07"
+
+[[package]]
+name = "block-buffer"
+version = "0.10.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
+dependencies = [
+ "generic-array",
+]
+
+[[package]]
+name = "bytes"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2bd12c1caf447e69cd4528f47f94d203fd2582878ecb9e9465484c4148a8223"
+
+[[package]]
+name = "cfg-if"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
+
+[[package]]
+name = "cpufeatures"
+version = "0.2.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce420fe07aecd3e67c5f910618fe65e94158f6dcc0adf44e00d69ce2bdfe0fd0"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "crypto-common"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3"
+dependencies = [
+ "generic-array",
+ "typenum",
+]
+
+[[package]]
+name = "digest"
+version = "0.10.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
+dependencies = [
+ "block-buffer",
+ "crypto-common",
+]
+
+[[package]]
+name = "equivalent"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5"
+
+[[package]]
+name = "fnv"
+version = "1.0.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
+
+[[package]]
+name = "form_urlencoded"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a62bc1cf6f830c2ec14a513a9fb124d0a213a629668a4186f329db21fe045652"
+dependencies = [
+ "percent-encoding",
+]
+
+[[package]]
+name = "futures"
+version = "0.3.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "da0290714b38af9b4a7b094b8a37086d1b4e61f2df9122c3cad2577669145335"
+dependencies = [
+ "futures-channel",
+ "futures-core",
+ "futures-executor",
+ "futures-io",
+ "futures-sink",
+ "futures-task",
+ "futures-util",
+]
+
+[[package]]
+name = "futures-channel"
+version = "0.3.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff4dd66668b557604244583e3e1e1eada8c5c2e96a6d0d6653ede395b78bbacb"
+dependencies = [
+ "futures-core",
+ "futures-sink",
+]
+
+[[package]]
+name = "futures-core"
+version = "0.3.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eb1d22c66e66d9d72e1758f0bd7d4fd0bee04cad842ee34587d68c07e45d088c"
+
+[[package]]
+name = "futures-executor"
+version = "0.3.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0f4fb8693db0cf099eadcca0efe2a5a22e4550f98ed16aba6c48700da29597bc"
+dependencies = [
+ "futures-core",
+ "futures-task",
+ "futures-util",
+]
+
+[[package]]
+name = "futures-io"
+version = "0.3.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8bf34a163b5c4c52d0478a4d757da8fb65cabef42ba90515efee0f6f9fa45aaa"
+
+[[package]]
+name = "futures-macro"
+version = "0.3.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "53b153fd91e4b0147f4aced87be237c98248656bb01050b96bf3ee89220a8ddb"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.39",
+]
+
+[[package]]
+name = "futures-sink"
+version = "0.3.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e36d3378ee38c2a36ad710c5d30c2911d752cb941c00c72dbabfb786a7970817"
+
+[[package]]
+name = "futures-task"
+version = "0.3.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "efd193069b0ddadc69c46389b740bbccdd97203899b48d09c5f7969591d6bae2"
+
+[[package]]
+name = "futures-util"
+version = "0.3.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a19526d624e703a3179b3d322efec918b6246ea0fa51d41124525f00f1cc8104"
+dependencies = [
+ "futures-channel",
+ "futures-core",
+ "futures-io",
+ "futures-macro",
+ "futures-sink",
+ "futures-task",
+ "memchr",
+ "pin-project-lite",
+ "pin-utils",
+ "slab",
+]
+
+[[package]]
+name = "generic-array"
+version = "0.14.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
+dependencies = [
+ "typenum",
+ "version_check",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.14.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f93e7192158dbcda357bdec5fb5788eebf8bbac027f3f33e719d29135ae84156"
+
+[[package]]
+name = "heck"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
+dependencies = [
+ "unicode-segmentation",
+]
+
+[[package]]
+name = "hex"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
+
+[[package]]
+name = "http"
+version = "0.2.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f95b9abcae896730d42b78e09c155ed4ddf82c07b4de772c64aee5b2d8b7c150"
+dependencies = [
+ "bytes",
+ "fnv",
+ "itoa",
+]
+
+[[package]]
+name = "id-arena"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "25a2bc672d1148e28034f176e01fffebb08b35768468cc954630da77a1449005"
+
+[[package]]
+name = "idna"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7d20d6b07bfbc108882d88ed8e37d39636dcc260e15e30c45e6ba089610b917c"
+dependencies = [
+ "unicode-bidi",
+ "unicode-normalization",
+]
+
+[[package]]
+name = "indexmap"
+version = "2.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d530e1a18b1cb4c484e6e34556a0d948706958449fca0cab753d649f2bce3d1f"
+dependencies = [
+ "equivalent",
+ "hashbrown",
+ "serde",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38"
+
+[[package]]
+name = "leb128"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "884e2677b40cc8c339eaefcb701c32ef1fd2493d71118dc0ca4b6a736c93bd67"
+
+[[package]]
+name = "libc"
+version = "0.2.150"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "89d92a4743f9a61002fae18374ed11e7973f530cb3a3255fb354818118b2203c"
+
+[[package]]
+name = "log"
+version = "0.4.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f"
+
+[[package]]
+name = "memchr"
+version = "2.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f665ee40bc4a3c5590afb1e9677db74a508659dfd71e126420da8274909a0167"
+
+[[package]]
+name = "once_cell"
+version = "1.18.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d"
+
+[[package]]
+name = "percent-encoding"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b2a4787296e9989611394c33f193f676704af1686e70b8f8033ab5ba9a35a94"
+
+[[package]]
+name = "pin-project-lite"
+version = "0.2.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8afb450f006bf6385ca15ef45d71d2288452bc3683ce2e2cacc0d18e4be60b58"
+
+[[package]]
+name = "pin-utils"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.69"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "134c189feb4956b20f6f547d2cf727d4c0fe06722b20a0eec87ed445a97f92da"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.33"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "routefinder"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "94f8f99b10dedd317514253dda1fa7c14e344aac96e1f78149a64879ce282aca"
+dependencies = [
+ "smartcow",
+ "smartstring",
+]
+
+[[package]]
+name = "ryu"
+version = "1.0.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741"
+
+[[package]]
+name = "semver"
+version = "1.0.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "836fa6a3e1e547f9a2c4040802ec865b5d85f4014efe00555d7090a3dcaa1090"
+
+[[package]]
+name = "serde"
+version = "1.0.192"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bca2a08484b285dcb282d0f67b26cadc0df8b19f8c12502c13d966bf9482f001"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.192"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d6c7207fbec9faa48073f3e3074cbe553af6ea512d7c21ba46e434e70ea9fbc1"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.39",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.108"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d1c7e3eac408d115102c4c24ad393e0821bb3a5df4d506a80f85f7a742a526b"
+dependencies = [
+ "itoa",
+ "ryu",
+ "serde",
+]
+
+[[package]]
+name = "sha2"
+version = "0.10.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "793db75ad2bcafc3ffa7c68b215fee268f537982cd901d132f89c6343f3a3dc8"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "digest",
+]
+
+[[package]]
+name = "slab"
+version = "0.4.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "smallvec"
+version = "1.11.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4dccd0940a2dcdf68d092b8cbab7dc0ad8fa938bf95787e1b916b0e3d0e8e970"
+
+[[package]]
+name = "smartcow"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "656fcb1c1fca8c4655372134ce87d8afdf5ec5949ebabe8d314be0141d8b5da2"
+dependencies = [
+ "smartstring",
+]
+
+[[package]]
+name = "smartstring"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3fb72c633efbaa2dd666986505016c32c3044395ceaf881518399d2f4127ee29"
+dependencies = [
+ "autocfg",
+ "static_assertions",
+ "version_check",
+]
+
+[[package]]
+name = "spdx"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b19b32ed6d899ab23174302ff105c1577e45a06b08d4fe0a9dd13ce804bbbf71"
+dependencies = [
+ "smallvec",
+]
+
+[[package]]
+name = "spin-macro"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "bytes",
+ "http",
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+]
+
+[[package]]
+name = "spin-outbound-post"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "futures",
+ "hex",
+ "sha2",
+ "spin-sdk",
+ "url",
+]
+
+[[package]]
+name = "spin-sdk"
+version = "2.1.0-pre0"
+dependencies = [
+ "anyhow",
+ "async-trait",
+ "bytes",
+ "form_urlencoded",
+ "futures",
+ "http",
+ "once_cell",
+ "routefinder",
+ "serde",
+ "serde_json",
+ "spin-macro",
+ "thiserror",
+ "wit-bindgen",
+]
+
+[[package]]
+name = "static_assertions"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
+
+[[package]]
+name = "syn"
+version = "1.0.109"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "syn"
+version = "2.0.39"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23e78b90f2fcf45d3e842032ce32e3f2d1545ba6636271dcbf24fa306d87be7a"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "thiserror"
+version = "1.0.50"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f9a7210f5c9a7156bb50aa36aed4c95afb51df0df00713949448cf9e97d382d2"
+dependencies = [
+ "thiserror-impl",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "1.0.50"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "266b2e40bc00e5a6c09c3584011e08b06f123c00362c92b975ba9843aaaa14b8"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.39",
+]
+
+[[package]]
+name = "tinyvec"
+version = "1.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50"
+dependencies = [
+ "tinyvec_macros",
+]
+
+[[package]]
+name = "tinyvec_macros"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
+
+[[package]]
+name = "typenum"
+version = "1.17.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825"
+
+[[package]]
+name = "unicode-bidi"
+version = "0.3.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92888ba5573ff080736b3648696b70cafad7d250551175acbaa4e0385b3e1460"
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
+
+[[package]]
+name = "unicode-normalization"
+version = "0.1.22"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c5713f0fc4b5db668a2ac63cdb7bb4469d8c9fed047b1d0292cc7b0ce2ba921"
+dependencies = [
+ "tinyvec",
+]
+
+[[package]]
+name = "unicode-segmentation"
+version = "1.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1dd624098567895118886609431a7c3b8f516e41d30e0643f03d94592a147e36"
+
+[[package]]
+name = "unicode-xid"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f962df74c8c05a667b5ee8bcf162993134c104e96440b663c8daa176dc772d8c"
+
+[[package]]
+name = "url"
+version = "2.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "143b538f18257fac9cad154828a57c6bf5157e1aa604d4816b5995bf6de87ae5"
+dependencies = [
+ "form_urlencoded",
+ "idna",
+ "percent-encoding",
+]
+
+[[package]]
+name = "version_check"
+version = "0.9.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
+
+[[package]]
+name = "wasm-encoder"
+version = "0.36.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "822b645bf4f2446b949776ffca47e2af60b167209ffb70814ef8779d299cd421"
+dependencies = [
+ "leb128",
+]
+
+[[package]]
+name = "wasm-metadata"
+version = "0.10.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2167ce53b2faa16a92c6cafd4942cff16c9a4fa0c5a5a0a41131ee4e49fc055f"
+dependencies = [
+ "anyhow",
+ "indexmap",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "spdx",
+ "wasm-encoder",
+ "wasmparser",
+]
+
+[[package]]
+name = "wasmparser"
+version = "0.116.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a58e28b80dd8340cb07b8242ae654756161f6fc8d0038123d679b7b99964fa50"
+dependencies = [
+ "indexmap",
+ "semver",
+]
+
+[[package]]
+name = "wit-bindgen"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "38726c54a5d7c03cac28a2a8de1006cfe40397ddf6def3f836189033a413bc08"
+dependencies = [
+ "bitflags",
+ "wit-bindgen-rust-macro",
+]
+
+[[package]]
+name = "wit-bindgen-core"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c8bf1fddccaff31a1ad57432d8bfb7027a7e552969b6c68d6d8820dcf5c2371f"
+dependencies = [
+ "anyhow",
+ "wit-component",
+ "wit-parser",
+]
+
+[[package]]
+name = "wit-bindgen-rust"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0e7200e565124801e01b7b5ddafc559e1da1b2e1bed5364d669cd1d96fb88722"
+dependencies = [
+ "anyhow",
+ "heck",
+ "wasm-metadata",
+ "wit-bindgen-core",
+ "wit-component",
+]
+
+[[package]]
+name = "wit-bindgen-rust-macro"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ae33920ad8119fe72cf59eb00f127c0b256a236b9de029a1a10397b1f38bdbd"
+dependencies = [
+ "anyhow",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.39",
+ "wit-bindgen-core",
+ "wit-bindgen-rust",
+ "wit-component",
+]
+
+[[package]]
+name = "wit-component"
+version = "0.17.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "480cc1a078b305c1b8510f7c455c76cbd008ee49935f3a6c5fd5e937d8d95b1e"
+dependencies = [
+ "anyhow",
+ "bitflags",
+ "indexmap",
+ "log",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "wasm-encoder",
+ "wasm-metadata",
+ "wasmparser",
+ "wit-parser",
+]
+
+[[package]]
+name = "wit-parser"
+version = "0.12.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "43771ee863a16ec4ecf9da0fc65c3bbd4a1235c8e3da5f094b562894843dfa76"
+dependencies = [
+ "anyhow",
+ "id-arena",
+ "indexmap",
+ "log",
+ "semver",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "unicode-xid",
+]
diff --git a/examples/http-rust-outbound-post/Cargo.toml b/examples/http-rust-outbound-post/Cargo.toml
new file mode 100644
index 0000000000..412fc15578
--- /dev/null
+++ b/examples/http-rust-outbound-post/Cargo.toml
@@ -0,0 +1,17 @@
+[package]
+name = "spin-outbound-post"
+version = "0.1.0"
+edition = "2021"
+
+[lib]
+crate-type = ["cdylib"]
+
+[dependencies]
+anyhow = "1.0.71"
+futures = "0.3.28"
+hex = "0.4.3"
+sha2 = "0.10.6"
+url = "2.4.0"
+spin-sdk = { path = "../../sdk/rust" }
+
+[workspace]
diff --git a/examples/http-rust-outbound-post/spin.toml b/examples/http-rust-outbound-post/spin.toml
new file mode 100644
index 0000000000..7ca703f5dc
--- /dev/null
+++ b/examples/http-rust-outbound-post/spin.toml
@@ -0,0 +1,18 @@
+spin_manifest_version = 2
+
+[application]
+authors = ["Fermyon Engineering <engineering@fermyon.com>"]
+description = "Demonstrates outbound HTTP calls"
+name = "spin-outbound-post"
+version = "1.0.0"
+
+[[trigger.http]]
+route = "/..."
+component = "spin-outbound-post"
+
+[component.spin-outbound-post]
+source = "target/wasm32-wasi/release/spin_outbound_post.wasm"
+allowed_outbound_hosts = ["http://*:*", "https://*:*"]
+[component.spin-outbound-post.build]
+command = "cargo build --target wasm32-wasi --release"
+watch = ["src/**/*.rs", "Cargo.toml"]
diff --git a/examples/http-rust-outbound-post/src/lib.rs b/examples/http-rust-outbound-post/src/lib.rs
new file mode 100644
index 0000000000..d5f93bafe3
--- /dev/null
+++ b/examples/http-rust-outbound-post/src/lib.rs
@@ -0,0 +1,30 @@
+use {
+ anyhow::{anyhow, Result},
+ spin_sdk::{
+ http::{self, IncomingResponse, IntoResponse, Method, Request, RequestBuilder, Response},
+ http_component,
+ },
+};
+
+#[http_component]
+async fn handle(req: Request) -> Result<impl IntoResponse> {
+ let request = RequestBuilder::new(Method::Post, "/")
+ .uri(
+ req.header("url")
+ .ok_or_else(|| anyhow!("missing url header"))?
+ .as_str()
+ .ok_or_else(|| anyhow!("invalid utf-8 in url header value"))?,
+ )
+ .method(Method::Post)
+ .body("Hello, world!")
+ .build();
+
+ let response: IncomingResponse = http::send(request).await?;
+ let status = response.status();
+
+ Ok(Response::builder()
+ .status(200)
+ .header("content-type", "text/plain")
+ .body(format!("response status: {status}"))
+ .build())
+}
diff --git a/sdk/rust/src/http.rs b/sdk/rust/src/http.rs
index bf52612b39..173ff62d70 100644
--- a/sdk/rust/src/http.rs
+++ b/sdk/rust/src/http.rs
@@ -373,7 +373,7 @@ impl HeaderValue {
pub fn as_str(&self) -> Option<&str> {
match &self.inner {
HeaderValueRep::String(s) => Some(s),
- HeaderValueRep::Bytes(_) => None,
+ HeaderValueRep::Bytes(b) => std::str::from_utf8(b).ok(),
}
}
@@ -597,14 +597,13 @@ where
// It is part of the contract of the trait that implementors of `TryIntoOutgoingRequest`
// do not call `OutgoingRequest::write`` if they return a buffered body.
let mut body_sink = request.take_body();
- let response = executor::outgoing_request_send(request)
- .await
- .map_err(SendError::Http)?;
+ let response = executor::outgoing_request_send(request);
body_sink
.send(body_buffer)
.await
.map_err(|e| SendError::Http(Error::UnexpectedError(e.to_string())))?;
- response
+ drop(body_sink);
+ response.await.map_err(SendError::Http)?
} else {
executor::outgoing_request_send(request)
.await
diff --git a/sdk/rust/src/http/executor.rs b/sdk/rust/src/http/executor.rs
index 45ac1aca97..d5727bb4b5 100644
--- a/sdk/rust/src/http/executor.rs
+++ b/sdk/rust/src/http/executor.rs
@@ -91,7 +91,6 @@ pub(crate) fn outgoing_body(body: OutgoingBody) -> impl Sink<Vec<u8>, Error = ty
move |context| {
let pair = pair.borrow();
let (stream, _) = &pair.0.as_ref().unwrap();
-
loop {
match stream.check_write() {
Ok(0) => {
| 2,083
|
[
"2080"
] |
diff --git a/tests/integration.rs b/tests/integration.rs
index 36ab055056..d7c07bb729 100644
--- a/tests/integration.rs
+++ b/tests/integration.rs
@@ -2,6 +2,7 @@
mod integration_tests {
use anyhow::{anyhow, Context, Error, Result};
use futures::{channel::oneshot, future, stream, FutureExt};
+ use http_body_util::BodyExt;
use hyper::{body::Bytes, server::conn::http1, service::service_fn, Method, StatusCode};
use reqwest::{Client, Response};
use sha2::{Digest, Sha256};
@@ -14,7 +15,7 @@ mod integration_tests {
net::{Ipv4Addr, SocketAddrV4, TcpListener},
path::Path,
process::{self, Child, Command, Output},
- sync::Arc,
+ sync::{Arc, Mutex},
time::Duration,
};
use tempfile::tempdir;
@@ -673,6 +674,88 @@ route = "/..."
do_test_build_command("tests/build/simple").await
}
+ #[tokio::test]
+ async fn test_outbound_post() -> Result<()> {
+ let listener = tokio::net::TcpListener::bind((Ipv4Addr::new(127, 0, 0, 1), 0)).await?;
+
+ let prefix = format!("http://{}", listener.local_addr()?);
+
+ let body = Arc::new(Mutex::new(Vec::new()));
+
+ let server = {
+ let body = body.clone();
+ async move {
+ loop {
+ let (stream, _) = listener.accept().await?;
+ let body = body.clone();
+ task::spawn(async move {
+ if let Err(e) = http1::Builder::new()
+ .keep_alive(true)
+ .serve_connection(
+ stream,
+ service_fn(
+ move |request: hyper::Request<hyper::body::Incoming>| {
+ let body = body.clone();
+ async move {
+ if let &Method::POST = request.method() {
+ let req_body = request.into_body();
+ let bytes =
+ req_body.collect().await?.to_bytes().to_vec();
+ *body.lock().unwrap() = bytes;
+ Ok::<_, Error>(hyper::Response::new(body::empty()))
+ } else {
+ Ok(hyper::Response::builder()
+ .status(StatusCode::METHOD_NOT_ALLOWED)
+ .body(body::empty())?)
+ }
+ }
+ },
+ ),
+ )
+ .await
+ {
+ log::warn!("{e:?}");
+ }
+ });
+
+ // Help rustc with type inference:
+ if false {
+ return Ok::<_, Error>(());
+ }
+ }
+ }
+ }
+ .then(|result| {
+ if let Err(e) = result {
+ log::warn!("{e:?}");
+ }
+ future::ready(())
+ })
+ .boxed();
+
+ let (_tx, rx) = oneshot::channel::<()>();
+
+ task::spawn(async move {
+ drop(future::select(server, rx).await);
+ });
+ let controller = SpinTestController::with_manifest(
+ "examples/http-rust-outbound-post/spin.toml",
+ &[],
+ &[],
+ )
+ .await?;
+
+ let response = Client::new()
+ .get(format!("http://{}/", controller.url))
+ .header("url", format!("{prefix}/"))
+ .send()
+ .await?;
+ assert_eq!(200, response.status());
+ assert_eq!(b"Hello, world!", body.lock().unwrap().as_slice());
+
+ Ok(())
+ }
+
#[tokio::test]
async fn test_wasi_http_hash_all() -> Result<()> {
let bodies = Arc::new(
|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
a7c0f6a7f23f74742654d0f69ae888ebf18f6407
|
`spin add` doesn't check for manifest version mis-match
When using the `spin add` command with a template using the manifest v1 format, with an application, which already has the manifest in v2, the command completes, and you end up with a non-working manifest.
It would be great to have something checking if there's a match between the manifest used in the app, and the manifest version being brought by the template.
|
Yes, we should also check for same trigger type.
The slight challenge here is that fragment TOML in `spin add` doesn't carry a version number. We can either apply some heuristics or add some metadata to the trigger (which is what we did for the trigger type check I think).
|
2023-11-01T21:01:39Z
|
fermyon__spin-2025
|
fermyon/spin
|
3.2
|
diff --git a/crates/templates/src/app_info.rs b/crates/templates/src/app_info.rs
index 4326c3a7e3..fef0e8fb8a 100644
--- a/crates/templates/src/app_info.rs
+++ b/crates/templates/src/app_info.rs
@@ -11,6 +11,7 @@ use spin_manifest::schema::v1;
use crate::store::TemplateLayout;
pub(crate) struct AppInfo {
+ manifest_format: u32,
trigger_type: String,
}
@@ -39,7 +40,12 @@ impl AppInfo {
fn from_existent_file(manifest_path: &Path) -> anyhow::Result<Self> {
let manifest_str = std::fs::read_to_string(manifest_path)?;
- let trigger_type = match spin_manifest::ManifestVersion::detect(&manifest_str)? {
+ let manifest_version = spin_manifest::ManifestVersion::detect(&manifest_str)?;
+ let manifest_format = match manifest_version {
+ spin_manifest::ManifestVersion::V1 => 1,
+ spin_manifest::ManifestVersion::V2 => 2,
+ };
+ let trigger_type = match manifest_version {
spin_manifest::ManifestVersion::V1 => {
toml::from_str::<ManifestV1TriggerProbe>(&manifest_str)?
.trigger
@@ -55,7 +61,14 @@ impl AppInfo {
triggers.into_iter().next().unwrap().0
}
};
- Ok(Self { trigger_type })
+ Ok(Self {
+ manifest_format,
+ trigger_type,
+ })
+ }
+
+ pub fn manifest_format(&self) -> u32 {
+ self.manifest_format
}
pub fn trigger_type(&self) -> &str {
diff --git a/crates/templates/src/manager.rs b/crates/templates/src/manager.rs
index 9c26f6e5bd..66e33d99bd 100644
--- a/crates/templates/src/manager.rs
+++ b/crates/templates/src/manager.rs
@@ -1119,6 +1119,8 @@ mod tests {
assert!(!spin_toml.contains("service.example.com"));
}
+ // TODO: The challenge here is that figuring out the trigger from a template manifest is now hard
+ // because template manifests are not valid TOML (because the component table header is templatised).
#[tokio::test]
#[ignore] // This will need rework when more templates are ported to the v2 manifest - the failure is benign, a missing safety rail not an error
async fn cannot_add_component_that_does_not_match_trigger() {
@@ -1195,6 +1197,64 @@ mod tests {
}
}
+ #[tokio::test]
+ async fn cannot_add_component_that_does_not_match_manifest() {
+ let temp_dir = tempdir().unwrap();
+ let store = TemplateStore::new(temp_dir.path());
+ let manager = TemplateManager { store };
+ let source = TemplateSource::File(project_root());
+
+ manager
+ .install(&source, &InstallOptions::default(), &DiscardingReporter)
+ .await
+ .unwrap();
+
+ let dest_temp_dir = tempdir().unwrap();
+ let application_dir = dest_temp_dir.path().join("multi");
+
+ // Set up the containing app
+ {
+ let fake_v1_src = test_data_root().join("v1manifest.toml");
+ let fake_v1_dest = application_dir.join("spin.toml");
+ tokio::fs::create_dir_all(&application_dir).await.unwrap();
+ tokio::fs::copy(fake_v1_src, fake_v1_dest).await.unwrap();
+ }
+
+ let spin_toml_path = application_dir.join("spin.toml");
+ assert!(
+ spin_toml_path.exists(),
+ "expected v1 spin.toml to be created"
+ );
+
+ // Now add a component
+ {
+ let template = manager.get("http-rust").unwrap().unwrap();
+
+ let output_dir = "hello";
+ let values = [
+ ("project-description".to_owned(), "hello".to_owned()),
+ ("http-path".to_owned(), "/hello".to_owned()),
+ ]
+ .into_iter()
+ .collect();
+ let options = RunOptions {
+ variant: crate::template::TemplateVariantInfo::AddComponent {
+ manifest_path: spin_toml_path.clone(),
+ },
+ output_path: PathBuf::from(output_dir),
+ name: "hello".to_owned(),
+ values,
+ accept_defaults: false,
+ };
+
+ template
+ .run(options)
+ .silent()
+ .await
+ .expect_err("Expected to fail to add component, but it succeeded");
+ }
+ }
+
#[tokio::test]
async fn cannot_new_a_component_only_template() {
let temp_dir = tempdir().unwrap();
diff --git a/crates/templates/src/run.rs b/crates/templates/src/run.rs
index 4093d8c20e..e2f7ffbe37 100644
--- a/crates/templates/src/run.rs
+++ b/crates/templates/src/run.rs
@@ -85,7 +85,8 @@ impl Run {
&self,
interaction: impl InteractionStrategy,
) -> anyhow::Result<Option<TemplateRenderer>> {
- self.validate_trigger().await?;
+ self.validate_trigger()?;
+ self.validate_version()?;
// TODO: rationalise `path` and `dir`
let to = self.generation_target_dir();
@@ -211,7 +212,7 @@ impl Run {
}
}
- async fn validate_trigger(&self) -> anyhow::Result<()> {
+ fn validate_trigger(&self) -> anyhow::Result<()> {
match &self.options.variant {
TemplateVariantInfo::NewApplication => Ok(()),
TemplateVariantInfo::AddComponent { manifest_path } => {
@@ -225,6 +226,20 @@ impl Run {
}
}
+ fn validate_version(&self) -> anyhow::Result<()> {
+ match &self.options.variant {
+ TemplateVariantInfo::NewApplication => Ok(()),
+ TemplateVariantInfo::AddComponent { manifest_path } => {
+ match crate::app_info::AppInfo::from_file(manifest_path) {
+ Some(Ok(app_info)) => self
+ .template
+ .check_compatible_manifest_format(app_info.manifest_format()),
+ _ => Ok(()), // Fail forgiving - don't block the user if things are under construction
+ }
+ }
+ }
+ }
+
fn snippet_operation(&self, id: &str, snippet_file: &str) -> anyhow::Result<RenderOperation> {
let snippets_dir = self
.template
diff --git a/crates/templates/src/template.rs b/crates/templates/src/template.rs
index 5c78a2858d..d540a5c1e1 100644
--- a/crates/templates/src/template.rs
+++ b/crates/templates/src/template.rs
@@ -358,6 +358,43 @@ impl Template {
}
}
}
+
+ pub(crate) fn check_compatible_manifest_format(
+ &self,
+ manifest_format: u32,
+ ) -> anyhow::Result<()> {
+ let Some(content_dir) = &self.content_dir else {
+ return Ok(());
+ };
+ let manifest_tpl = content_dir.join("spin.toml");
+ if !manifest_tpl.is_file() {
+ return Ok(());
+ }
+
+ // We can't load the manifest template because it's not valid TOML until
+ // substituted, so GO BIG or at least GO CRUDE.
+ let Ok(manifest_tpl_str) = std::fs::read_to_string(&manifest_tpl) else {
+ return Ok(());
+ };
+ let is_v1_tpl = manifest_tpl_str.contains("spin_manifest_version = \"1\"");
+ let is_v2_tpl = manifest_tpl_str.contains("spin_manifest_version = 2");
+
+ // If we have not positively identified a format, err on the side of forgiveness
+ let positively_identified = is_v1_tpl ^ is_v2_tpl; // exactly one should be true
+ if !positively_identified {
+ return Ok(());
+ }
+
+ let compatible = (is_v1_tpl && manifest_format == 1) || (is_v2_tpl && manifest_format == 2);
+
+ if compatible {
+ Ok(())
+ } else {
+ Err(anyhow!(
+ "This template is for a different version of the Spin manifest"
+ ))
+ }
+ }
}
impl TemplateParameter {
| 2,025
|
[
"2016"
] |
diff --git a/crates/templates/tests/v1manifest.toml b/crates/templates/tests/v1manifest.toml
new file mode 100644
index 0000000000..c98aab9aff
--- /dev/null
+++ b/crates/templates/tests/v1manifest.toml
@@ -0,0 +1,8 @@
+spin_manifest_version = "1"
+name = "v1"
+version = "0.1.0"
+trigger = { type = "http", base = "/" }
+
+[[component]]
+id = "v1"
+source = "does-not-exist.wasm"
|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
3167e6ee78e739367762fb41ccc2098f9620c40e
|
unable to use docker compose file to run e2e tests on newer macs
While trying to run the docker compose file for the e2e tests, I ran into the following error:
```
$ docker build -t spin-e2e-tests -f e2e-tests-aarch64.Dockerfile
$ docker compose -f e2e-tests-docker-compose.yml run e2e-tests
[+] Running 0/1
⠧ mysql Pulling 0.6s
no matching manifest for linux/arm64/v8 in the manifest list entries
```
The mysql image being referenced does not support arm64. We might be able to use the `arm64v8/mysql` image or the `mysql/mysql-server` image maintained by the Oracle team in the docker compose file to resolve this issue.
|
I used the `mysql/mysql-server` image locally to run the docker compose file and got past the previous issue but wasn't able to get past compiling the spin-cli:
```
error: linking with `cc` failed: exit status: 1 [... lots of other output here]
= note: collect2: fatal error: ld terminated with signal 9 [Killed]
compilation terminated.
error: could not compile `spin-cli` due to previous error
Hi Michelle
I will check this and get back to you. Thank you for trying this out
it takes us somewhere, but still not completely ironed out (currently failing to run `spin` binary I downloaded from `Github` releases)
Change in `e2e-tests-aarch64.Dockerfile`:
(added --target aarch64-unknown-linux-gnu)
```
diff --git a/e2e-tests-aarch64.Dockerfile b/e2e-tests-aarch64.Dockerfile
index 023f83e..9bb3997 100644
--- a/e2e-tests-aarch64.Dockerfile
+++ b/e2e-tests-aarch64.Dockerfile
@@ -59,4 +59,4 @@ RUN node --version
WORKDIR /e2e-tests
COPY . .
-CMD cargo test spinup_tests --features new-e2e-tests --no-fail-fast -- --nocapture
+CMD cargo test spinup_tests --features new-e2e-tests --no-fail-fast --target aarch64-unknown-linux-gnu -- --nocapture
```
Building and running tests
```
docker build --platform arm64 -f e2e-tests-aarch64.Dockerfile . -t spin-e2e-tests
DOCKER_DEFAULT_PLATFORM=linux/arm64 docker compose -f e2e-tests-docker-compose.yml run e2e-tests
docker run --rm -it --platform linux/arm64 spin-e2e-tests bash
```
Hi @michelleN can you give this a shot. I was able to atleast start running the tests on my laptop with above changes (using `docker container`. I still need to verify the steps with `docker-compose`).
(they are taking forever to build/run, took ~2h for spin compilation inside the docker container)
Process info from inside the container
```
root@7f00d47b9e1a:/e2e-tests# ps -ef | grep spin
root 25 1 0 06:52 pts/0 00:00:51 /usr/bin/qemu-aarch64 /usr/local/rustup/toolchains/1.66-aarch64-unknown-linux-gnu/bin/cargo test spinup_tests --features new-e2e-tests --no-fail-fast --target aarch64-unknown-linux-gnu -- --nocapture
root 32140 25 2 08:32 pts/0 00:00:13 /usr/bin/qemu-aarch64 /e2e-tests/target/aarch64-unknown-linux-gnu/debug/deps/spinup_tests-305200408185c61a spinup_tests --nocapture
root 32160 32140 0 08:32 pts/0 00:00:00 /usr/bin/qemu-aarch64 /usr/local/bin/spin build
root 32162 32140 0 08:32 pts/0 00:00:00 /usr/bin/qemu-aarch64 /usr/local/bin/spin build
root 32165 32140 0 08:32 pts/0 00:00:00 /usr/bin/qemu-aarch64 /usr/local/bin/spin build
root 32242 32140 0 08:32 pts/0 00:00:01 /usr/bin/qemu-aarch64 /usr/local/bin/spin up --listen 127.0.0.1:45913
root 32390 32242 9 08:32 pts/0 00:00:44 /usr/bin/qemu-aarch64 /usr/local/bin/spin trigger http --listen 127.0.0.1:45913
root 32461 32140 0 08:32 pts/0 00:00:00 /usr/bin/qemu-aarch64 /usr/local/bin/spin build
root 32782 32140 0 08:32 pts/0 00:00:00 /usr/bin/qemu-aarch64 /usr/local/bin/spin build
root 33355 32140 0 08:33 pts/0 00:00:00 /usr/bin/qemu-aarch64 /usr/local/bin/spin build
```
Logs from `cargo test` command
```
test spinup_tests::assets_routing_works has been running for over 60 seconds
test spinup_tests::header_dynamic_env_works has been running for over 60 seconds
test spinup_tests::header_env_routes_works has been running for over 60 seconds
test spinup_tests::http_c_works has been running for over 60 seconds
test spinup_tests::http_go_works has been running for over 60 seconds
test spinup_tests::http_js_works has been running for over 60 seconds
test spinup_tests::http_rust_outbound_mysql_works has been running for over 60 seconds
test spinup_tests::http_rust_works has been running for over 60 seconds
http://127.0.0.1:45913/static/donotmount/a
http://127.0.0.1:45913/static/thisshouldbemounted/thisshouldbeexcluded/4
test spinup_tests::assets_routing_works ... ok
test spinup_tests::http_ts_works has been running for over 60 seconds
```
@rajatjindal
The first command works just fine (docker build) but I am still having trouble running the docker compose file.
```
src/spin [main] $ DOCKER_DEFAULT_PLATFORM=linux/arm64 docker compose -f e2e-tests-docker-compose.yml run e2e-tests
[+] Running 0/1
⠧ mysql Pulling 0.7s
no matching manifest for linux/arm64/v8 in the manifest list entries
```
When I update the image to mysql/mysql-server:8.0.22, I get the following error:
```
= note: collect2: fatal error: ld terminated with signal 9 [Killed]
compilation terminated.
error: could not compile `spin-cli` due to previous error
```
|
2023-02-17T05:52:15Z
|
fermyon__spin-1174
|
fermyon/spin
|
0.9
|
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 0b89821db3..6ce192740b 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -170,4 +170,4 @@ jobs:
- name: Run e2e tests
run: |
chmod +x `pwd`/target/release/spin
- docker compose -f e2e-tests-docker-compose.yml run e2e-tests
+ docker compose -f e2e-tests-docker-compose.yml run -v `pwd`/target/release/spin:/usr/local/bin/spin e2e-tests
| 1,174
|
[
"1105"
] |
diff --git a/e2e-tests-aarch64.Dockerfile b/e2e-tests-aarch64.Dockerfile
index 282bd5610c..042f5fe536 100644
--- a/e2e-tests-aarch64.Dockerfile
+++ b/e2e-tests-aarch64.Dockerfile
@@ -1,5 +1,8 @@
FROM ubuntu:22.04
+ARG BUILD_SPIN=false
+ARG SPIN_VERSION=canary
+
WORKDIR /root
RUN apt-get update && apt-get install -y wget sudo xz-utils gcc git pkg-config
@@ -21,42 +24,48 @@ RUN wget https://ziglang.org/download/0.10.0/zig-linux-aarch64-0.10.0.tar.xz &&
tar -xf zig-linux-aarch64-0.10.0.tar.xz
ENV PATH="$PATH:/root/zig-linux-aarch64-0.10.0"
-# # grain
+# # grain - disabled as no arm build
# RUN wget https://github.com/grain-lang/grain/releases/download/grain-v0.5.4/grain-linux-x64 && \
# mv grain-linux-x64 /usr/local/bin/grain && chmod +x /usr/local/bin/grain
-# spin
-RUN wget https://github.com/fermyon/spin/releases/download/canary/spin-canary-linux-aarch64.tar.gz && \
- tar -xvf spin-canary-linux-aarch64.tar.gz && \
- ls -ltr && \
- mv spin /usr/local/bin/spin
-
# # rust
ENV RUSTUP_HOME=/usr/local/rustup \
CARGO_HOME=/usr/local/cargo \
PATH=/usr/local/cargo/bin:$PATH
-RUN url="https://static.rust-lang.org/rustup/dist/aarch64-unknown-linux-gnu/rustup-init"; \
- wget "$url"; \
- chmod +x rustup-init; \
- ./rustup-init -y --no-modify-path --default-toolchain 1.66 --default-host aarch64-unknown-linux-gnu; \
- rm rustup-init; \
- chmod -R a+w $RUSTUP_HOME $CARGO_HOME; \
- rustup --version; \
- cargo --version; \
- rustc --version; \
+RUN url="https://static.rust-lang.org/rustup/dist/aarch64-unknown-linux-gnu/rustup-init"; \
+ wget "$url"; \
+ chmod +x rustup-init; \
+ ./rustup-init -y --no-modify-path --default-toolchain 1.66 --default-host aarch64-unknown-linux-gnu; \
+ rm rustup-init; \
+ chmod -R a+w $RUSTUP_HOME $CARGO_HOME; \
+ rustup --version; \
+ cargo --version; \
+ rustc --version; \
rustup target add wasm32-wasi;
## check versions
-RUN tinygo version
-RUN go version
-# RUN grain --version
-RUN spin --version
-RUN zig version
-RUN rustc --version
-RUN node --version
+RUN tinygo version; \
+ go version; \
+ zig version; \
+ rustc --version; \
+ node --version;
WORKDIR /e2e-tests
COPY . .
+# spin
+RUN if [ "${BUILD_SPIN}" != "true" ]; then \
+ wget https://github.com/fermyon/spin/releases/download/${SPIN_VERSION}/spin-${SPIN_VERSION}-linux-aarch64.tar.gz && \
+ tar -xvf spin-${SPIN_VERSION}-linux-aarch64.tar.gz && \
+ ls -ltr && \
+ mv spin /usr/local/bin/spin; \
+ else \
+ cargo build --release && \
+ cp target/release/spin /usr/local/bin/spin; \
+ fi
+
+RUN spin --version
+
+
CMD cargo test spinup_tests --features new-e2e-tests --no-fail-fast -- --nocapture
diff --git a/e2e-tests-docker-compose.yml b/e2e-tests-docker-compose.yml
index 4990065240..c3145c5456 100644
--- a/e2e-tests-docker-compose.yml
+++ b/e2e-tests-docker-compose.yml
@@ -2,7 +2,7 @@ version: "3.9"
services:
mysql:
- image: mysql:8.0.22
+ image: ${MYSQL_IMAGE:-mysql:8.0.22}
ports:
- "3306:3306"
volumes:
@@ -19,8 +19,6 @@ services:
- mysql
image: spin-e2e-tests
entrypoint: cargo test spinup_tests --features new-e2e-tests --no-fail-fast -- --nocapture
- volumes:
- - ./target/release/spin:/usr/local/bin/spin
volumes:
db_data: {}
diff --git a/tests/README.md b/tests/README.md
index 5603ae1e26..e483678660 100644
--- a/tests/README.md
+++ b/tests/README.md
@@ -20,6 +20,26 @@ docker build -t spin-e2e-tests -f e2e-tests.Dockerfile .
docker compose -f e2e-tests-docker-compose.yml run e2e-tests
```
+## How to run e2e tests on aarch64
+```
+## go to root dir of the project, e2e-tests-aarch64.Dockerfile is located there
+docker build -t spin-e2e-tests -f e2e-tests-aarch64.Dockerfile .
+MYSQL_IMAGE=arm64v8/mysql:8.0.32 docker compose \
+ -f e2e-tests-docker-compose.yml run \
+ e2e-tests
+```
+
+## How to use `spin` binary with your local changes
+
+By default tests use the canary build of `spin` downloaded at docker image creation time. If you want to test it with your changes, you can use `--build-arg BUILD_SPIN=true`
+
+```
+docker build --build-arg BUILD_SPIN=true -t spin-e2e-tests -f e2e-tests.Dockerfile .
+docker compose \
+ -f e2e-tests-docker-compose.yml run \
+ e2e-tests
+```
+
## Important files and their function
`crates/e2e-testing` - All the test framework/utilities that are required for `e2e-tests`
|
3da388c68704a21fd6292987b4e9ddb1079d2984
|
e2f4fac924bcd2e222faad7eb49bb7dcfcec62ad
|
Rename `spin_version` to `spin_manifest_version` in Spin application manifest
## Issue
Spin application manifests (`spin.toml`) must specify what application manifest version it is using. This is set by setting the [`spin_version` in a `spin.toml`](https://github.com/fermyon/spin/blob/7cad829d6c87d6956a049bb6fa7e8d3711b6d70c/examples/http-rust/spin.toml#L1). This field suggests that it is declaring the version of Spin that it runs on when it is really declaring the version of the manifest TOML that it is. We should rename this field to `spin_manifest_version` to make this clear.
## Proposed solution
1) non-breaking: Ideally, we could add an alias to the `spin_version` field of the manifest so that the name change would not be breaking. This may not be possible with `serde` defaults. Instead, we may need to write a custom deserializer that deserializes that field appropriately and calls to the default deserializer for the remaining fields.
2) Alternatively, we could make it a breaking change with a major release.
|
I'm weary of the custom deserializer approach for *1*. My concern is that for tools not written in rust that might consume a `spin.toml` can now no longer just deserialize the manifest however they have to implement this custom deserializing. Thinking about some theoretical plugin implemented in `go` that consumes a `spin.toml`.
I fear that any rename to `spin_version` may come with subtle drawbacks (which i am fine with) as long as we are cognizant of what we are giving up.
I'm in favor of *2* but recognize the cost of not being able to do this until `1.0`
Morbid curiosity came over me and i'm not confident that using `alias` or `rename` is a viable option either:
This does not compile:
```rust
#[derive(Deserialize)]
#[serde(tag = "spin_version", alias = "spin_manifest_version")]
enum Manifest {
#[serde(rename = "1")]
V1,
}
```
This is a runtime error ...
```rust
#[derive(Deserialize)]
#[serde(tag = "spin_version", rename = "spin_manifest_version")]
enum Manifest {
#[serde(rename = "1")]
V1,
}
```
... when deserializing this input:
```toml
spin_manifest_version = "1"
```
I think you can do this using an untagged enum of two tagged enums. Similar to what I did in https://github.com/fermyon/spin/blob/813a3f4b8ff5e899b3720a7f746252d5d0d087f4/crates/manifest/src/lib.rs#L139
_This post is provided AS IS and comes with no warranties express or implied_
@fibonacci1729 re other languages... this would hopefully only be an issue for a brief transitional period, and given that we are not aware of other tools depending on spin.toml it would hopefully not be a big deal... I bet we have hairier things that other languages would need to grapple with too! But definitely something we should keep in mind longer term!
@kate-goldenring There are a couple of places at the moment where we look at subsets of the manifest (to avoid going through full `spin_loader` processing) - just noting them so we capture them too:
https://github.com/fermyon/spin/blob/main/crates/build/src/manifest.rs
https://github.com/fermyon/spin/blob/main/crates/templates/src/app_info.rs
@itowlson I am curious about using the `untagged` enum approach, i haven't considered that.
Thinking out loud again, If that doesn't work we could alternatively deserialize the toml into a `HashMap<String, toml::Value>` and dispatch to the approriate deserializer given the presence of `spin_version` or `spin_manifest_version` but this feels janky and circumventing the entire point of versioning the manifest format in the first place. This is effectively the custom deserializing approach.
> this would hopefully only be an issue for a brief transitional period
@itowlson can you clarify what the transition period here is? Essentially several months of backwards compat and then we'd switch to only supporting `spin_manifest_version`?
Yeah, if someone were starting a plugin once this goes in, I'd assume they'd likely target only the new syntax. But you're right, there could be apps with the old syntax lurking around for a while!
@fibonacci1729 It's wordy and involved a bunch of dreary helpers but:
```
// The thing we actually want to work with
#[derive(Debug, Deserialize)]
#[serde(from = "AppSer")] // LET THE CHEATING BEGIN
enum App {
V1(AppV1),
}
#[derive(Debug, Deserialize)]
struct AppV1 {
foo: String
}
#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum AppSer {
OldSkool(AppOldSkool),
NewSkool(AppNewSkool),
}
#[derive(Debug, Deserialize)]
#[serde(tag = "version")]
enum AppOldSkool {
#[serde(rename = "1")]
V1(AppV1),
}
#[derive(Debug, Deserialize)]
#[serde(tag = "megaversion")]
enum AppNewSkool {
#[serde(rename = "1")]
V1(AppV1),
}
impl From<AppSer> for App {
fn from(value: AppSer) -> Self {
match value {
AppSer::OldSkool(AppOldSkool::V1(m)) => Self::V1(m),
AppSer::NewSkool(AppNewSkool::V1(m)) => Self::V1(m),
}
}
}
fn main() {{
let text1 = r#"version = "1"
foo = "bar""#;
let text2 = r#"megaversion = "1"
foo = "bar""#;
for text in &[text1, text2] {
let app: App = toml::from_str(text).unwrap();
println!("--> {app:?}");
}
}
// output
--> V1(AppV1 { foo: "bar" })
--> V1(AppV1 { foo: "bar" })
```
Ahh clever! _skepticism melts away_.
So then to transition to a `v2` manifest format, we'd simply extend `AppNewSkool` with a `V2` variant?
Yes - the presence of `megaversion` would cause the untagged enum to plump for the new variant, and from that point on the tag on the new "nested" enum would take effect.
@itowlson thanks for sharing the cheat! I patched it together into a working POC here: https://github.com/fermyon/spin/compare/main...kate-goldenring:spin:spin-manifest-version?
I have a few concerns, though:
1. It seems like the couple months of back compat may not be worth the duplicate (`manifest.rs` and `config.rs`) and cheatty code.
2. We still need to change internal field references of `spin_version` to `spin_manifest_version` (but this nested enum would help hide that change from people still using `spin_version`
Re 1, yeah, the duplication is regrettable. We could rework the loader pipeline to allow interested consumers to hook in at an earlier point, so that build and templates don't need their subsets, but that feels out of scope for this work (I considered it at the time I was doing that duplication but couldn't face it). And yeah, I agree it incurs quite a few paragraphs of ugliness over the transition period... It's a pity there's no generic `serde` solution for this and I'm definitely not saying we have to do it my way, just sharing what I learned in earlier battles with serde.
What I propose is that we stroke our chins and muse loudly, "Hmm, I bet this could be solved by a Rust macr--" and before we finished the sentence Brian would have done all the hard work for us... 🤔 🤞
This seems to work:
```rust
#[derive(Deserialize)]
#[serde(untagged)]
enum VersionedManifest {
V1Old {
spin_version: spin_app::locked::FixedVersion<1>,
#[serde(flatten)]
manifest: ManifestV1,
},
V1New {
spin_manifest_version: spin_app::locked::FixedVersion<1>,
#[serde(flatten)]
manifest: ManifestV1,
},
}
#[derive(Deserialize)]
struct ManifestV1 {
name: String,
}
```
[`FixedVersion`](https://github.com/fermyon/spin/blob/main/crates/app/src/locked.rs#L120-L123) would need to be adapted to accept strings instead of numbers but that should be straightforward.
Ooooooooooooooooh! Much nicer!
|
2023-02-16T21:18:21Z
|
fermyon__spin-1169
|
fermyon/spin
|
0.9
|
diff --git a/crates/bindle/src/expander.rs b/crates/bindle/src/expander.rs
index ef6d89999e..5001384bdc 100644
--- a/crates/bindle/src/expander.rs
+++ b/crates/bindle/src/expander.rs
@@ -20,7 +20,7 @@ pub async fn expand_manifest(
let app_file = absolutize(app_file)?;
let manifest = spin_loader::local::raw_manifest_from_file(&app_file).await?;
validate_raw_app_manifest(&manifest)?;
- let local_schema::RawAppManifestAnyVersion::V1(manifest) = manifest;
+ let manifest = manifest.into_v1();
let app_dir = parent_dir(&app_file)?;
// * create a new spin.toml-like document where
diff --git a/crates/build/src/lib.rs b/crates/build/src/lib.rs
index 16ffb1c504..6f97793b86 100644
--- a/crates/build/src/lib.rs
+++ b/crates/build/src/lib.rs
@@ -16,7 +16,7 @@ pub async fn build(manifest_file: &Path) -> Result<()> {
let manifest_text = tokio::fs::read_to_string(manifest_file)
.await
.with_context(|| format!("Cannot read manifest file from {}", manifest_file.display()))?;
- let BuildAppInfoAnyVersion::V1(app) = toml::from_str(&manifest_text)?;
+ let app = toml::from_str(&manifest_text).map(BuildAppInfoAnyVersion::into_v1)?;
let app_dir = parent_dir(manifest_file)?;
if app.components.iter().all(|c| c.build.is_none()) {
diff --git a/crates/build/src/manifest.rs b/crates/build/src/manifest.rs
index 2eea6dc5f6..ae04ea1a7e 100644
--- a/crates/build/src/manifest.rs
+++ b/crates/build/src/manifest.rs
@@ -1,12 +1,30 @@
-use std::path::PathBuf;
-
use serde::{Deserialize, Serialize};
+use spin_loader::local::config::FixedStringVersion;
+use std::path::PathBuf;
-#[derive(Clone, Debug, Deserialize, Serialize)]
-#[serde(tag = "spin_version")]
+#[derive(Clone, Debug, Deserialize)]
+#[serde(untagged)]
pub(crate) enum BuildAppInfoAnyVersion {
- #[serde(rename = "1")]
- V1(BuildAppInfoV1),
+ V1Old {
+ #[allow(dead_code)]
+ spin_version: FixedStringVersion<1>,
+ #[serde(flatten)]
+ manifest: BuildAppInfoV1,
+ },
+ V1New {
+ #[allow(dead_code)]
+ spin_manifest_version: FixedStringVersion<1>,
+ #[serde(flatten)]
+ manifest: BuildAppInfoV1,
+ },
+}
+impl BuildAppInfoAnyVersion {
+ pub fn into_v1(self) -> BuildAppInfoV1 {
+ match self {
+ BuildAppInfoAnyVersion::V1New { manifest, .. } => manifest,
+ BuildAppInfoAnyVersion::V1Old { manifest, .. } => manifest,
+ }
+ }
}
#[derive(Clone, Debug, Deserialize, Serialize)]
diff --git a/crates/loader/src/local/config.rs b/crates/loader/src/local/config.rs
index b7f0e0ac6e..fa1fc72ca1 100644
--- a/crates/loader/src/local/config.rs
+++ b/crates/loader/src/local/config.rs
@@ -22,12 +22,43 @@ pub(crate) type RawAppManifestAnyVersionPartial = RawAppManifestAnyVersionImpl<t
pub(crate) type RawComponentManifestPartial = RawComponentManifestImpl<toml::Value>;
/// Container for any version of the manifest.
-#[derive(Clone, Debug, Deserialize, Serialize)]
-#[serde(tag = "spin_version")]
+#[derive(Clone, Debug, Deserialize)]
+#[serde(untagged)]
pub enum RawAppManifestAnyVersionImpl<C> {
- /// A manifest with API version 1.
- #[serde(rename = "1")]
- V1(RawAppManifestImpl<C>),
+ /// Old Spin manifest versioned with `spin_version` key
+ V1Old {
+ /// Version key name
+ spin_version: FixedStringVersion<1>,
+ /// Manifest
+ #[serde(flatten)]
+ manifest: RawAppManifestImpl<C>,
+ },
+ /// New Spin manifest versioned with `spin_manifest_version` key
+ V1New {
+ /// Version key name
+ spin_manifest_version: FixedStringVersion<1>,
+ /// Manifest
+ #[serde(flatten)]
+ manifest: RawAppManifestImpl<C>,
+ },
+}
+
+impl<C> RawAppManifestAnyVersionImpl<C> {
+ /// Converts `RawAppManifestAnyVersionImpl` into underlying V1 manifest
+ pub fn into_v1(self) -> RawAppManifestImpl<C> {
+ match self {
+ RawAppManifestAnyVersionImpl::V1New { manifest, .. } => manifest,
+ RawAppManifestAnyVersionImpl::V1Old { manifest, .. } => manifest,
+ }
+ }
+
+ /// Returns a reference to the underlying V1 manifest
+ pub fn as_v1(&self) -> &RawAppManifestImpl<C> {
+ match self {
+ RawAppManifestAnyVersionImpl::V1New { manifest, .. } => manifest,
+ RawAppManifestAnyVersionImpl::V1Old { manifest, .. } => manifest,
+ }
+ }
}
/// Application configuration local file format.
@@ -176,3 +207,27 @@ pub struct FileComponentUrlSource {
/// SHA256 digest, in the form `sha256:...`
pub digest: String,
}
+
+/// FixedStringVersion represents a schema version field with a const value.
+#[derive(Clone, Debug, Default, Serialize, Deserialize)]
+#[serde(into = "String", try_from = "String")]
+pub struct FixedStringVersion<const V: usize>;
+
+impl<const V: usize> From<FixedStringVersion<V>> for String {
+ fn from(_: FixedStringVersion<V>) -> String {
+ V.to_string()
+ }
+}
+
+impl<const V: usize> TryFrom<String> for FixedStringVersion<V> {
+ type Error = String;
+ fn try_from(value: String) -> Result<Self, Self::Error> {
+ let value: usize = value
+ .parse()
+ .map_err(|err| format!("invalid version: {}", err))?;
+ if value != V {
+ return Err(format!("invalid version {} != {}", value, V));
+ }
+ Ok(Self)
+ }
+}
diff --git a/crates/loader/src/local/mod.rs b/crates/loader/src/local/mod.rs
index a7b132fda3..016a74e5e7 100644
--- a/crates/loader/src/local/mod.rs
+++ b/crates/loader/src/local/mod.rs
@@ -101,9 +101,8 @@ async fn prepare_any_version(
base_dst: Option<impl AsRef<Path>>,
bindle_connection: &Option<BindleConnectionInfo>,
) -> Result<Application> {
- match raw {
- RawAppManifestAnyVersion::V1(raw) => prepare(raw, src, base_dst, bindle_connection).await,
- }
+ let manifest = raw.into_v1();
+ prepare(manifest, src, base_dst, bindle_connection).await
}
/// Iterates over a vector of RawComponentManifest structs and throws an error if any component ids are duplicated
@@ -122,13 +121,11 @@ fn error_on_duplicate_ids(components: Vec<RawComponentManifest>) -> Result<()> {
/// Validate fields in raw app manifest
pub fn validate_raw_app_manifest(raw: &RawAppManifestAnyVersion) -> Result<()> {
- match raw {
- RawAppManifestAnyVersion::V1(raw) => {
- raw.components
- .iter()
- .try_for_each(|c| validate_allowed_http_hosts(&c.wasm.allowed_http_hosts))?;
- }
- }
+ let manifest = raw.as_v1();
+ manifest
+ .components
+ .iter()
+ .try_for_each(|c| validate_allowed_http_hosts(&c.wasm.allowed_http_hosts))?;
Ok(())
}
@@ -405,7 +402,7 @@ impl ComponentDigest {
fn resolve_partials(
partially_parsed: RawAppManifestAnyVersionPartial,
) -> Result<RawAppManifestAnyVersion> {
- let RawAppManifestAnyVersionPartial::V1(manifest) = partially_parsed;
+ let manifest = partially_parsed.into_v1();
let app_trigger = &manifest.info.trigger;
let components = manifest
@@ -414,11 +411,15 @@ fn resolve_partials(
.map(|c| resolve_partial_component(app_trigger, c))
.collect::<Result<_>>()?;
- Ok(RawAppManifestAnyVersion::V1(RawAppManifest {
- info: manifest.info,
- components,
- variables: manifest.variables,
- }))
+ // Only concerned with preserving manifest.
+ Ok(RawAppManifestAnyVersion::V1New {
+ manifest: RawAppManifest {
+ info: manifest.info,
+ components,
+ variables: manifest.variables,
+ },
+ spin_manifest_version: config::FixedStringVersion::default(),
+ })
}
fn resolve_partial_component(
@@ -494,8 +495,7 @@ source = "nonexistent.wasm"
#[test]
fn can_parse_http_trigger() {
let m = load_test_manifest(r#"{ type = "http", base = "/" }"#, r#"route = "/...""#);
-
- let RawAppManifestAnyVersion::V1(m1) = m;
+ let m1 = m.into_v1();
let t = &m1.info.trigger;
let ct = &m1.components[0].trigger;
assert!(matches!(t, ApplicationTrigger::Http(_)));
@@ -509,7 +509,7 @@ source = "nonexistent.wasm"
r#"channel = "chan""#,
);
- let RawAppManifestAnyVersion::V1(m1) = m;
+ let m1 = m.into_v1();
let t = m1.info.trigger;
let ct = &m1.components[0].trigger;
assert!(matches!(t, ApplicationTrigger::Redis(_)));
@@ -520,7 +520,7 @@ source = "nonexistent.wasm"
fn can_parse_unknown_trigger() {
let m = load_test_manifest(r#"{ type = "pounce" }"#, r#"on = "MY KNEES""#);
- let RawAppManifestAnyVersion::V1(m1) = m;
+ let m1 = m.into_v1();
let t = m1.info.trigger;
let ct = &m1.components[0].trigger;
assert!(matches!(t, ApplicationTrigger::External(_)));
@@ -534,7 +534,7 @@ source = "nonexistent.wasm"
r#"route = "over the cat tree and out of the sun""#,
);
- let RawAppManifestAnyVersion::V1(m1) = m;
+ let m1 = m.into_v1();
let t = m1.info.trigger;
let ct = &m1.components[0].trigger;
assert!(matches!(t, ApplicationTrigger::External(_)));
diff --git a/examples/http-rust/Cargo.lock b/examples/http-rust/Cargo.lock
index d3593d5b7e..d5c528837b 100644
--- a/examples/http-rust/Cargo.lock
+++ b/examples/http-rust/Cargo.lock
@@ -154,7 +154,7 @@ dependencies = [
[[package]]
name = "spin-sdk"
-version = "0.7.1"
+version = "0.8.0"
dependencies = [
"anyhow",
"bytes",
diff --git a/src/commands/deploy.rs b/src/commands/deploy.rs
index 47d4b0c35e..927a2c38bb 100644
--- a/src/commands/deploy.rs
+++ b/src/commands/deploy.rs
@@ -15,7 +15,7 @@ use spin_http::routes::RoutePattern;
use spin_http::AppInfo;
use spin_http::WELL_KNOWN_PREFIX;
use spin_loader::bindle::BindleConnectionInfo;
-use spin_loader::local::config::{RawAppManifest, RawAppManifestAnyVersion};
+use spin_loader::local::config::RawAppManifest;
use spin_loader::local::{assets, config, parent_dir};
use spin_manifest::ApplicationTrigger;
use spin_manifest::{HttpTriggerConfiguration, TriggerConfig};
@@ -188,7 +188,7 @@ impl DeployCommand {
async fn deploy_hippo(self, login_connection: LoginConnection) -> Result<()> {
let cfg_any = spin_loader::local::raw_manifest_from_file(&self.app).await?;
- let RawAppManifestAnyVersion::V1(cfg) = cfg_any;
+ let cfg = cfg_any.into_v1();
ensure!(!cfg.components.is_empty(), "No components in spin.toml!");
@@ -318,7 +318,7 @@ impl DeployCommand {
let client = CloudClient::new(connection_config.clone());
let cfg_any = spin_loader::local::raw_manifest_from_file(&self.app).await?;
- let RawAppManifestAnyVersion::V1(cfg) = cfg_any;
+ let cfg = cfg_any.into_v1();
ensure!(!cfg.components.is_empty(), "No components in spin.toml!");
| 1,169
|
[
"1069"
] |
diff --git a/crates/loader/src/local/tests.rs b/crates/loader/src/local/tests.rs
index 06a2e0704c..e9b17cfb62 100644
--- a/crates/loader/src/local/tests.rs
+++ b/crates/loader/src/local/tests.rs
@@ -47,12 +47,34 @@ async fn test_from_local_source() -> Result<()> {
Ok(())
}
+#[test]
+fn test_manifest_v1_signatures() -> Result<()> {
+ const MANIFEST: &str = include_str!("../../tests/valid-manifest.toml");
+ let ageless = MANIFEST
+ .replace("spin_version", "temp")
+ .replace("spin_manifest_version", "temp");
+ let v1_old = ageless.replace("temp", "spin_version");
+ let v1_new = ageless.replace("temp", "spin_manifest_version");
+ into_v1_manifest(&v1_old, "chain-of-command")?;
+ into_v1_manifest(&v1_new, "chain-of-command")?;
+ Ok(())
+}
+
+fn into_v1_manifest(spin_versioned_manifest: &str, app_name: &str) -> Result<()> {
+ use config::RawAppManifestAnyVersionImpl;
+ let raw: RawAppManifestAnyVersionImpl<toml::Value> =
+ toml::from_slice(spin_versioned_manifest.as_bytes())?;
+ let manifest = raw.into_v1();
+ assert_eq!(manifest.info.name, app_name);
+ Ok(())
+}
+
#[test]
fn test_manifest() -> Result<()> {
const MANIFEST: &str = include_str!("../../tests/valid-manifest.toml");
let cfg_any: RawAppManifestAnyVersion = raw_manifest_from_str(MANIFEST)?;
- let RawAppManifestAnyVersion::V1(cfg) = cfg_any;
+ let cfg = cfg_any.into_v1();
assert_eq!(cfg.info.name, "chain-of-command");
assert_eq!(cfg.info.version, "6.11.2");
@@ -184,8 +206,8 @@ fn test_unknown_version_is_rejected() {
let e = cfg.unwrap_err().to_string();
assert!(
- e.contains("spin_version"),
- "Expected error to mention `spin_version`"
+ e.contains("RawAppManifestAnyVersionImpl"),
+ "Expected error to mention `RawAppManifestAnyVersionImpl`"
);
}
@@ -197,7 +219,7 @@ fn test_wagi_executor_with_custom_entrypoint() -> Result<()> {
const EXPECTED_DEFAULT_ARGV: &str = "${SCRIPT_NAME} ${ARGS}";
let cfg_any: RawAppManifestAnyVersion = raw_manifest_from_str(MANIFEST)?;
- let RawAppManifestAnyVersion::V1(cfg) = cfg_any;
+ let cfg = cfg_any.into_v1();
let http_config: HttpConfig = cfg.components[0].trigger.clone().try_into()?;
diff --git a/tests/integration.rs b/tests/integration.rs
index 963ee4e75a..a41cafc8f3 100644
--- a/tests/integration.rs
+++ b/tests/integration.rs
@@ -2,10 +2,7 @@
mod integration_tests {
use anyhow::{Context, Result};
use hyper::{Body, Client, Response};
- use spin_loader::local::{
- config::{RawAppManifestAnyVersion, RawModuleSource},
- raw_manifest_from_file,
- };
+ use spin_loader::local::{config::RawModuleSource, raw_manifest_from_file};
use std::{
collections::HashMap,
ffi::OsStr,
@@ -994,7 +991,7 @@ mod integration_tests {
/// in `spin.toml` inside `dir`.
async fn do_test_build_command(dir: impl AsRef<Path>) -> Result<()> {
let manifest_file = dir.as_ref().join("spin.toml");
- let RawAppManifestAnyVersion::V1(manifest) = raw_manifest_from_file(&manifest_file).await?;
+ let manifest = raw_manifest_from_file(&manifest_file).await?.into_v1();
let mut sources = vec![];
for component_manifest in manifest.components.iter() {
|
3da388c68704a21fd6292987b4e9ddb1079d2984
|
25d35a8bbafb447cacc4357a79f8c50ac81007c8
|
Make log output to stdout default
When running Spin locally in a development loop, I always use `--follow-all` to have my logs written out to the console.
From conversations I've heard others not discovering this option, e.g.:
> Debugging in spin was an initial pain point until finding the log directory. Did not find about follow-all until pretty late
I'd like to propose that writing logs to stdout becomes the default behavior, and that a new option to only output to log files gets introduced, e.g. `--silent` or `--no-stdout`.
|
Is that "make writing to standard output default and _not_ write to a log directory", or do we want both?
My preference would be default to both, meaning only changing the current default behavior to also write to stdout. If completeness is important, having switches being `--logging file-only` `--logging stdout-only` could be the way to go.
### TLDR
I would like to propose the following:
- Default: to write into `stdout`/`stderr` (only). `The Twelve Factor App` [justifies this behavior](https://12factor.net/logs).
- If `-L`/`--log-dir` is provided without value: write to the default directory.
- If `-L`/`--log-dir` is provided with value: write into the specified directory.
Nice to have:
- To provide the default directory in the help output:
```
-L, --log-dir <APP_LOG_DIR>
Log directory for the stdout and stderr of components
```
```
-L, --log-dir <APP_LOG_DIR>
Log directory for the stdout and stderr of components [default: $HOME/.spin/<app-name>/logs]
```
- Expose global trigger args (those that make sense across all trigger types) in the `up`/`build --up` help output (please see rationale below)
### Rationale
The problem with `--follow-all` might be the UX issue because there it's hidden in the `--help`.
My expectation when I run `build --up -h` is to see `up` args included in the help output.
```sh
$ spin build --up -h
spin-build
Build the Spin application
USAGE:
spin build [OPTIONS] [UP_ARGS]...
ARGS:
<UP_ARGS>...
OPTIONS:
-f, --file <APP_CONFIG_FILE> Path to spin.toml
-h, --help Print help information
-u, --up Run the application after building
```
Then `spin up` is missing `trigger` args:
```sh
$ ./target/release/spin up -h
spin-up
Start the Spin application
USAGE:
spin up [OPTIONS]
OPTIONS:
-b, --bindle <BINDLE_ID>
ID of application bindle
--bindle-password <BINDLE_PASSWORD>
Basic http auth password for the bindle server [env: BINDLE_PASSWORD=]
--bindle-server <BINDLE_SERVER_URL>
URL of bindle server [env: BINDLE_URL=]
--bindle-username <BINDLE_USERNAME>
Basic http auth username for the bindle server [env: BINDLE_USERNAME=]
-e, --env <ENV>
Pass an environment variable (key=value) to all components of the application
-f, --file <APP_CONFIG_FILE>
Path to spin.toml
-h, --help
-k, --insecure
Ignore server certificate errors from bindle server
--temp <TMP>
Temporary directory for the static assets of the components
```
But the trigger command is hidden from the subcommands list:
```sh
./target/release/spin --help
spin 0.6.0 (db3a68d 2022-11-30)
The Spin CLI
USAGE:
spin <SUBCOMMAND>
OPTIONS:
-h, --help Print help information
-V, --version Print version information
SUBCOMMANDS:
add Scaffold a new component into an existing application
bindle Commands for publishing applications as bindles
build Build the Spin application
deploy Deploy a Spin application
help Print this message or the help of the given subcommand(s)
login Log into the server
new Scaffold a new application based on a template
plugin Install/uninstall Spin plugins
templates Commands for working with WebAssembly component templates
up Start the Spin application
```
The only way to figure out about trigger args (besides the developer docs) is to notice it when spin is started with `RUST_LOG=spin=trace`:
```sh
RUST_LOG=spin=trace ../../target/release/spin build --up
Executing the build command for component hello: cargo build --target wasm32-wasi --release
Finished release [optimized] target(s) in 0.01s
Successfully ran the build command for the Spin components.
2022-12-01T12:03:12.920883Z TRACE spin_cli::commands::up: Running trigger executor: "/spin/target/release/spin" "trigger" "http"
2022-12-01T12:03:12.927711Z TRACE spin_http: Constructed router for application spin-hello-world: {Exact("/hello"): "hello"}
Serving http://127.0.0.1:3000
2022-12-01T12:03:12.927763Z INFO spin_http: Serving http://127.0.0.1:3000
Available Routes:
hello: http://127.0.0.1:3000/hello
A simple component that returns hello.
^C2022-12-01T12:03:14.428816Z INFO spin_trigger::cli: User requested shutdown: exiting
```
So `--follow-all` is available in the `spin trigger <trigger-type> -h` output, but it's hard to figure out the existence of `spin trigger -h` at all.
@etehtsea this seems like a bug in `up`. There are some trigger-specific arguments like `--listen` that are only shown if a `spin.toml` with that trigger is present. But `--follow-all` is generic and should always be shown.
We should also maybe add a message to `spin up --help` _without_ a `spin.toml` to say "additional options may be available in the presence of a manifest" (yes with less terrible wording).
...oh, and also `spin build` at the very least should mention that "if `--up` is present then `up` options are also available - see `spin up --help` for details" (again with better wording)
If it's nothing urgent, I can take a look into it
~Well, it looks like trigger options _used_ to be surfaced if there was a `spin.toml` present (https://github.com/fermyon/spin/issues/815) but have fallen off again. I'll raise a separate issue for that.~ Ah, no, they usually appear but not always. Raised https://github.com/fermyon/spin/issues/932.
|
2023-02-07T00:08:14Z
|
fermyon__spin-1115
|
fermyon/spin
|
0.8
|
diff --git a/crates/trigger/src/cli.rs b/crates/trigger/src/cli.rs
index 082b6f407f..f115cbc56b 100644
--- a/crates/trigger/src/cli.rs
+++ b/crates/trigger/src/cli.rs
@@ -65,11 +65,18 @@ where
pub follow_components: Vec<String>,
/// Print all component output to stdout/stderr
+ /// Deprecated
+ #[clap(long = "follow-all")]
+ pub follow_all_components: bool,
+
+ /// Silence all component output to stdout/stderr
#[clap(
- long = "follow-all",
+ long = "quiet",
+ short = 'q',
+ aliases = &["sh", "shush"],
conflicts_with = FOLLOW_LOG_OPT,
- )]
- pub follow_all_components: bool,
+ )]
+ pub silence_component_logs: bool,
/// Set the static assets of the components in the temporary directory as writable.
#[clap(long = "allow-transient-write")]
@@ -179,9 +186,12 @@ where
pub fn follow_components(&self) -> FollowComponents {
if self.follow_all_components {
- FollowComponents::All
- } else if self.follow_components.is_empty() {
+ eprintln!("NOTE: --follow-all has been deprecated. All component ouput is now printed to stdout by default.")
+ }
+ if self.silence_component_logs {
FollowComponents::None
+ } else if self.follow_components.is_empty() {
+ FollowComponents::All
} else {
let followed = self.follow_components.clone().into_iter().collect();
FollowComponents::Named(followed)
diff --git a/examples/spin-timer/readme.md b/examples/spin-timer/readme.md
index 5df2a0f7e9..1e65b56a23 100644
--- a/examples/spin-timer/readme.md
+++ b/examples/spin-timer/readme.md
@@ -10,4 +10,4 @@ To test:
* Update the URL too, to reflect the directory where the tar file is
* `spin plugin install --file ./trigger-timer.json --yes`
-Then you should be able to `spin build --up --follow-all` the guest.
+Then you should be able to `spin build --up` the guest.
diff --git a/src/commands/registry.rs b/src/commands/registry.rs
index 5ed9c86d74..f5045a8474 100644
--- a/src/commands/registry.rs
+++ b/src/commands/registry.rs
@@ -121,7 +121,7 @@ pub struct Run {
pub reference: String,
/// All other args, to be passed through to the trigger
- /// TODO: The arguments have to be passed like `-- --follow-all` for now.
+ /// TODO: The arguments have to be passed like `-- --quiet` for now.
#[clap(hide = true)]
pub trigger_args: Vec<OsString>,
}
@@ -156,8 +156,8 @@ impl Run {
.arg(trigger_type)
// TODO: This should be inferred from the lockfile.
.arg("--oci")
- // TODO: Once we figure out how to handle the flags for triggers, i.e. `-- --follow-all`, remove this.
- .arg("--follow-all")
+ // TODO: Once we figure out how to handle the flags for triggers, i.e. `-- --quiet`, remove this.
+ .arg("--quiet")
.args(&self.trigger_args)
.env(SPIN_WORKING_DIR, working_dir.path());
| 1,115
|
[
"928"
] |
diff --git a/tests/integration.rs b/tests/integration.rs
index 793f47153d..1fc926676f 100644
--- a/tests/integration.rs
+++ b/tests/integration.rs
@@ -1076,7 +1076,7 @@ route = "/..."
let output = run(up_help_args, None, None)?;
let stdout = String::from_utf8_lossy(&output.stdout);
- assert!(stdout.contains("--follow-all"));
+ assert!(stdout.contains("--quiet"));
assert!(stdout.contains("--listen"));
Ok(())
|
25d35a8bbafb447cacc4357a79f8c50ac81007c8
|
1abf1c0b396e574e7ce0ebdd76939e6efcaaafc0
|
spin plugin -> spin plugins
Super minor nit. Currently the top level command is `plugin` and is aliased to `plugins`. Should the top level command be `plugins` instead to match the plurality of `spin templates`? Still aliased to plugin for convenience. Thoughts welcome.
|
@itowlson and I were discussing this on the aliasing PR: https://github.com/fermyon/spin/pull/994#issuecomment-1358408185. +1 for changing `Plugin` to `Plugins`. I am happy to take this on
|
2023-01-23T22:58:54Z
|
fermyon__spin-1043
|
fermyon/spin
|
0.7
|
diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs
index 03c73bf13b..8e01580cd8 100644
--- a/crates/plugins/src/manifest.rs
+++ b/crates/plugins/src/manifest.rs
@@ -141,7 +141,7 @@ fn inner_check_supported_version(
eprintln!("Plugin is not compatible with this version of Spin (supported: {supported_on}, actual: {spin_version}). Check overridden ... continuing to install or execute plugin.");
} else {
return Err(anyhow!(
- "Plugin is not compatible with this version of Spin (supported: {supported_on}, actual: {spin_version}). Try running `spin plugin update && spin plugin upgrade --all` to install latest or override with `--override-compatibility-check`."
+ "Plugin is not compatible with this version of Spin (supported: {supported_on}, actual: {spin_version}). Try running `spin plugins update && spin plugins upgrade --all` to install latest or override with `--override-compatibility-check`."
));
}
}
diff --git a/src/bin/spin.rs b/src/bin/spin.rs
index b25af89e63..4149fc1e1d 100644
--- a/src/bin/spin.rs
+++ b/src/bin/spin.rs
@@ -53,8 +53,8 @@ enum SpinApp {
Deploy(DeployCommand),
Build(BuildCommand),
Login(LoginCommand),
- #[clap(subcommand, alias = "plugins")]
- Plugin(PluginCommands),
+ #[clap(subcommand, alias = "plugin")]
+ Plugins(PluginCommands),
#[clap(subcommand, hide = true)]
Trigger(TriggerCommands),
#[clap(external_subcommand)]
@@ -81,7 +81,7 @@ impl SpinApp {
Self::Trigger(TriggerCommands::Http(cmd)) => cmd.run().await,
Self::Trigger(TriggerCommands::Redis(cmd)) => cmd.run().await,
Self::Login(cmd) => cmd.run().await,
- Self::Plugin(cmd) => cmd.run().await,
+ Self::Plugins(cmd) => cmd.run().await,
Self::External(cmd) => execute_external_subcommand(cmd, SpinApp::command()).await,
}
}
| 1,043
|
[
"1042"
] |
diff --git a/tests/integration.rs b/tests/integration.rs
index e1e5cd30ff..944bebe317 100644
--- a/tests/integration.rs
+++ b/tests/integration.rs
@@ -1201,7 +1201,7 @@ route = "/..."
// Install plugin
let install_args = vec![
SPIN_BINARY,
- "plugin",
+ "plugins",
"install",
"--file",
manifest_file_path.to_str().unwrap(),
@@ -1227,7 +1227,7 @@ route = "/..."
)?;
let upgrade_args = vec![
SPIN_BINARY,
- "plugin",
+ "plugins",
"upgrade",
"example",
"--file",
@@ -1248,7 +1248,7 @@ route = "/..."
assert!(manifest.contains("0.2.1"));
// Uninstall plugin
- let uninstall_args = vec![SPIN_BINARY, "plugin", "uninstall", "example"];
+ let uninstall_args = vec![SPIN_BINARY, "plugins", "uninstall", "example"];
run(uninstall_args, None, None)?;
Ok(())
}
diff --git a/tests/plugin/README.md b/tests/plugin/README.md
index 1a643e7aec..3b286d1548 100644
--- a/tests/plugin/README.md
+++ b/tests/plugin/README.md
@@ -1,7 +1,7 @@
# Example Plugin
This `example.sh` script acts as an example Spin plugin for testing Spin plugin functionality.
-It is referenced in the `spin plugin` [integration tests](../integration.rs)
+It is referenced in the `spin plugins` [integration tests](../integration.rs)
To recreate:
|
1abf1c0b396e574e7ce0ebdd76939e6efcaaafc0
|
7c00e8a59cb0436ecc017f16371db3929185b2af
|
Variable default value ignored and error thrown when Vault Config Provider is used
In my Spin app I've configured three variables (**it's important to have at least one variable configured which is not stored in Vault as secret**)
```toml
[variables]
a = { default = "foo" }
b = { required = true }
c = { required = true }
```
Variable `b` exists as secret in Vault
```bash
vault kv get secret/b
======== Secret Path ========
secret/data/b
======= Metadata =======
Key Value
--- -----
created_time 2022-12-15T22:11:11.791431757Z
custom_metadata <nil>
deletion_time n/a
destroyed false
version 1
==== Data ====
Key Value
--- -----
value Baz
```
Component configuration is just forwarding the variables:
```toml
[[component]]
id = "some"
source = "some.wasm"
[component.config]
a = "{{ a }}"
b = "{{ b }}"
c = "{{ c }}"
```
When trying to access the configuration data in my component as shown here:
```rust
let a = config::get("a")?;
let b = config::get("b")?;
let c = config::get("c")?;
```
Before starting the Spin app, variable `c` is set as env var.
```bash
export SPIN_APP_C="Baz"
spin build --up --follow-all --runtime-config-file runtime_config.toml
```
When triggering the component, the following error is thrown:
```bash
The Vault server returned an error (status code 404)
2022-12-15T22:25:09.024940Z ERROR rustify::client: error=Server returned error
2022-12-15T22:25:09.024972Z ERROR rustify::endpoint: error=Server returned error
2022-12-15T22:25:09.024982Z ERROR vaultrs::api: Detected errors in API response: []
2022-12-15T22:25:09.024988Z ERROR vaultrs::kv2: error=The Vault server returned an error (status code 404)
```
Although `a` has a default value, I have to provide `a` explicitly by either providing `SPIN_APP_A` as environment variable or by storing `a` in Vault.
The app works as expected **only** if all variables are provided by a **config data provider**.
IMO the `config::get` should not throw when the underlying variable has a default value.
|
Just to be clear, if you're _not_ using Vault (so `b` and `c` are provided via environment variables), it works correctly, right? This is only when the Vault config provider is in the mix?
Just checked it. Yes, when I do not link Vault, it works as expected.
Thanks, I can reproduce this and will take a look.
Whenever Spin needs a config value, it first asks Vault, and if Vault returns an error, then Spin propagates that.
The correct behaviour if the error is "not found" should be to return `Ok(None)` so that Spin keeps searching the provider chain, eventually arriving at the default value.
|
2022-12-16T00:00:19Z
|
fermyon__spin-984
|
fermyon/spin
|
0.7
|
diff --git a/crates/config/src/provider/vault.rs b/crates/config/src/provider/vault.rs
index 58fd653dad..afc8c08b2d 100644
--- a/crates/config/src/provider/vault.rs
+++ b/crates/config/src/provider/vault.rs
@@ -1,8 +1,9 @@
-use anyhow::Result;
+use anyhow::{Context, Result};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use vaultrs::{
client::{VaultClient, VaultClientSettingsBuilder},
+ error::ClientError,
kv2,
};
@@ -51,7 +52,12 @@ impl Provider for VaultProvider {
Some(prefix) => format!("{}/{}", prefix, key.0),
None => key.0.to_string(),
};
- let secret: Secret = kv2::read(&client, &self.mount, &path).await?;
- Ok(Some(secret.value))
+ match kv2::read::<Secret>(&client, &self.mount, &path).await {
+ Ok(secret) => Ok(Some(secret.value)),
+ // Vault doesn't have this entry so pass along the chain
+ Err(ClientError::APIError { code: 404, .. }) => Ok(None),
+ // Other Vault error so bail rather than looking elsewhere
+ Err(e) => Err(e).context("Failed to check Vault for config"),
+ }
}
}
| 984
|
[
"983"
] |
diff --git a/tests/http/vault-config-test/spin.toml b/tests/http/vault-config-test/spin.toml
index c61db840f7..422a6f3b3e 100644
--- a/tests/http/vault-config-test/spin.toml
+++ b/tests/http/vault-config-test/spin.toml
@@ -7,13 +7,15 @@ version = "0.1.0"
[variables]
password = { required = true }
+greeting = { default = "Hello!" }
[[component]]
id = "config-test"
-source = "target/wasm32-wasi/release/config_test.wasm"
+source = "target/wasm32-wasi/release/vault_config_test.wasm"
[component.trigger]
route = "/..."
[component.build]
command = "cargo build --target wasm32-wasi --release"
[component.config]
password = "{{ password }}"
+greeting = "{{ greeting }}"
diff --git a/tests/http/vault-config-test/src/lib.rs b/tests/http/vault-config-test/src/lib.rs
index 849d9c3f01..cf130e43b1 100644
--- a/tests/http/vault-config-test/src/lib.rs
+++ b/tests/http/vault-config-test/src/lib.rs
@@ -8,8 +8,11 @@ use spin_sdk::{
/// A simple Spin HTTP component.
#[http_component]
fn config_test(_req: Request) -> Result<Response> {
+ // Ensure we can get a value from Vault
let password = config::get("password").expect("Failed to acquire password from vault");
+ // Ensure we can get a defaulted value
+ let greeting = config::get("greeting").expect("Failed to acquire greeting from default");
Ok(http::Response::builder()
.status(200)
- .body(Some(format!("Got password {}", password).into()))?)
+ .body(Some(format!("{} Got password {}", greeting, password).into()))?)
}
|
1abf1c0b396e574e7ce0ebdd76939e6efcaaafc0
|
268ae0a0015ac5b971ddd11a4c336fc24b76e754
|
request to add `spin plugin list` command
it will be nice to list the `plugins` available to install (or already installed?)
|
listing available plugins (in the plugins repo) vs installed ones in fairly different on the implementation side. Do we want to support both? We could do the following:
`spin plugin list`: lists installed plugins
`spin plugin search`: displays all plugins available in plugins registry
Or maybe `spin plugin install` (without plugin name) can look like `spin new` where it outputs the plugins available in the spin plugins repo.
Some tools use `list` and `list --available` (or, conversely, `list --installed` and `list`). I don't have a strong view though I do feel that `search` implies something different to `list` - it implies searching for a target rather than browsing what's out there.
`apt list` lists the catalog and `apt list --installed` lists installed so we may want to model after that since we have been consistent with apt so far
|
2022-12-14T01:02:48Z
|
fermyon__spin-972
|
fermyon/spin
|
0.6
|
diff --git a/crates/plugins/src/lookup.rs b/crates/plugins/src/lookup.rs
index 194e0ae28d..08e4847aa4 100644
--- a/crates/plugins/src/lookup.rs
+++ b/crates/plugins/src/lookup.rs
@@ -100,9 +100,13 @@ fn spin_plugins_repo_manifest_path(
plugin_version: &Option<Version>,
plugins_dir: &Path,
) -> PathBuf {
+ spin_plugins_repo_manifest_dir(plugins_dir)
+ .join(plugin_name)
+ .join(manifest_file_name_version(plugin_name, plugin_version))
+}
+
+pub fn spin_plugins_repo_manifest_dir(plugins_dir: &Path) -> PathBuf {
plugins_dir
.join(PLUGINS_REPO_LOCAL_DIRECTORY)
.join(PLUGINS_REPO_MANIFESTS_DIRECTORY)
- .join(plugin_name)
- .join(manifest_file_name_version(plugin_name, plugin_version))
}
diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs
index f2c9cab791..03c73bf13b 100644
--- a/crates/plugins/src/manifest.rs
+++ b/crates/plugins/src/manifest.rs
@@ -2,6 +2,8 @@ use anyhow::{anyhow, Context, Result};
use semver::{Version, VersionReq};
use serde::{Deserialize, Serialize};
+use crate::PluginStore;
+
/// Expected schema of a plugin manifest. Should match the latest Spin plugin
/// manifest JSON schema:
/// https://github.com/fermyon/spin-plugins/tree/main/json-schema
@@ -30,9 +32,24 @@ impl PluginManifest {
pub fn name(&self) -> String {
self.name.to_lowercase()
}
+ pub fn version(&self) -> &str {
+ &self.version
+ }
pub fn license(&self) -> &str {
self.license.as_ref()
}
+ pub fn has_compatible_package(&self) -> bool {
+ self.packages.iter().any(|p| p.matches_current_os_arch())
+ }
+ pub fn is_compatible_spin_version(&self, spin_version: &str) -> bool {
+ check_supported_version(self, spin_version, false).is_ok()
+ }
+ pub fn is_installed_in(&self, store: &PluginStore) -> bool {
+ match store.read_plugin_manifest(&self.name) {
+ Ok(m) => m.version == self.version,
+ Err(_) => false,
+ }
+ }
}
/// Describes compatibility and location of a plugin source.
@@ -52,6 +69,10 @@ impl PluginPackage {
pub fn url(&self) -> String {
self.url.clone()
}
+ pub fn matches_current_os_arch(&self) -> bool {
+ self.os.rust_name() == std::env::consts::OS
+ && self.arch.rust_name() == std::env::consts::ARCH
+ }
}
/// Describes the compatible OS of a plugin
diff --git a/crates/plugins/src/store.rs b/crates/plugins/src/store.rs
index f84f7455f0..83910b90d9 100644
--- a/crates/plugins/src/store.rs
+++ b/crates/plugins/src/store.rs
@@ -1,6 +1,7 @@
use anyhow::{anyhow, Result};
use flate2::read::GzDecoder;
use std::{
+ ffi::OsStr,
fs::{self, File},
path::{Path, PathBuf},
};
@@ -62,6 +63,57 @@ impl PluginStore {
binary
}
+ pub fn installed_manifests(&self) -> Result<Vec<PluginManifest>> {
+ let manifests_dir = self.installed_manifests_directory();
+ let manifest_paths = Self::json_files_in(&manifests_dir);
+ let manifests = manifest_paths
+ .iter()
+ .filter_map(|path| Self::try_read_manifest_from(path))
+ .collect();
+ Ok(manifests)
+ }
+
+ // TODO: report errors on individuals
+ pub fn catalogue_manifests(&self) -> Result<Vec<PluginManifest>> {
+ // Structure:
+ // CATALOGUE_DIR (spin/plugins/.spin-plugins/manifests)
+ // |- foo
+ // | |- foo@0.1.2.json
+ // | |- foo@1.2.3.json
+ // | |- foo.json
+ // |- bar
+ // |- bar.json
+ let catalogue_dir =
+ crate::lookup::spin_plugins_repo_manifest_dir(self.get_plugins_directory());
+ let plugin_dirs = catalogue_dir
+ .read_dir()?
+ .filter_map(|d| d.ok())
+ .map(|d| d.path())
+ .filter(|p| p.is_dir());
+ let manifest_paths = plugin_dirs.flat_map(|path| Self::json_files_in(&path));
+ let manifests: Vec<_> = manifest_paths
+ .filter_map(|path| Self::try_read_manifest_from(&path))
+ .collect();
+ Ok(manifests)
+ }
+
+ fn try_read_manifest_from(manifest_path: &Path) -> Option<PluginManifest> {
+ let manifest_file = File::open(manifest_path).ok()?;
+ serde_json::from_reader(manifest_file).ok()
+ }
+
+ fn json_files_in(dir: &Path) -> Vec<PathBuf> {
+ let json_ext = Some(OsStr::new("json"));
+ match dir.read_dir() {
+ Err(_) => vec![],
+ Ok(rd) => rd
+ .filter_map(|de| de.ok())
+ .map(|de| de.path())
+ .filter(|p| p.is_file() && p.extension() == json_ext)
+ .collect(),
+ }
+ }
+
/// Returns the PluginManifest for an installed plugin with a given name.
/// Looks up and parses the JSON plugin manifest file into object form.
pub fn read_plugin_manifest(&self, plugin_name: &str) -> PluginLookupResult<PluginManifest> {
diff --git a/src/commands/plugins.rs b/src/commands/plugins.rs
index b66ff6cf4d..ea6abc22dd 100644
--- a/src/commands/plugins.rs
+++ b/src/commands/plugins.rs
@@ -22,6 +22,9 @@ pub enum PluginCommands {
/// plugins directory.
Install(Install),
+ /// List available or installed plugins.
+ List(List),
+
/// Remove a plugin from your installation.
Uninstall(Uninstall),
@@ -36,6 +39,7 @@ impl PluginCommands {
pub async fn run(self) -> Result<()> {
match self {
PluginCommands::Install(cmd) => cmd.run().await,
+ PluginCommands::List(cmd) => cmd.run().await,
PluginCommands::Uninstall(cmd) => cmd.run().await,
PluginCommands::Upgrade(cmd) => cmd.run().await,
PluginCommands::Update => update().await,
@@ -285,6 +289,121 @@ impl Upgrade {
}
}
+/// Install plugins from remote source
+#[derive(Parser, Debug)]
+pub struct List {
+ /// List only installed plugins.
+ #[clap(long = "installed", takes_value = false)]
+ pub installed: bool,
+}
+
+impl List {
+ pub async fn run(self) -> Result<()> {
+ let mut plugins = if self.installed {
+ Self::list_installed_plugins()
+ } else {
+ Self::list_catalogue_plugins()
+ }?;
+
+ plugins.sort_by(|p, q| p.cmp(q));
+
+ Self::print(&plugins);
+ Ok(())
+ }
+
+ fn list_installed_plugins() -> Result<Vec<PluginDescriptor>> {
+ let manager = PluginManager::try_default()?;
+ let store = manager.store();
+ let manifests = store.installed_manifests()?;
+ let descriptors = manifests
+ .iter()
+ .map(|m| PluginDescriptor {
+ name: m.name(),
+ version: m.version().to_owned(),
+ installed: true,
+ compatibility: PluginCompatibility::for_current(m),
+ })
+ .collect();
+ Ok(descriptors)
+ }
+
+ fn list_catalogue_plugins() -> Result<Vec<PluginDescriptor>> {
+ let manager = PluginManager::try_default()?;
+ let store = manager.store();
+ let manifests = store.catalogue_manifests();
+ let descriptors = manifests?
+ .iter()
+ .map(|m| PluginDescriptor {
+ name: m.name(),
+ version: m.version().to_owned(),
+ installed: m.is_installed_in(store),
+ compatibility: PluginCompatibility::for_current(m),
+ })
+ .collect();
+ Ok(descriptors)
+ }
+
+ fn print(plugins: &[PluginDescriptor]) {
+ if plugins.is_empty() {
+ println!("No plugins found");
+ } else {
+ for p in plugins {
+ let installed = if p.installed { " [installed]" } else { "" };
+ let compat = match p.compatibility {
+ PluginCompatibility::Compatible => "",
+ PluginCompatibility::IncompatibleSpin => " [requires other Spin version]",
+ PluginCompatibility::Incompatible => " [incompatible]",
+ };
+ println!("{} {}{}{}", p.name, p.version, installed, compat);
+ }
+ }
+ }
+}
+
+#[derive(Debug)]
+enum PluginCompatibility {
+ Compatible,
+ IncompatibleSpin,
+ Incompatible,
+}
+
+impl PluginCompatibility {
+ fn for_current(manifest: &PluginManifest) -> Self {
+ if manifest.has_compatible_package() {
+ let spin_version = env!("VERGEN_BUILD_SEMVER");
+ if manifest.is_compatible_spin_version(spin_version) {
+ Self::Compatible
+ } else {
+ Self::IncompatibleSpin
+ }
+ } else {
+ Self::Incompatible
+ }
+ }
+}
+
+#[derive(Debug)]
+struct PluginDescriptor {
+ name: String,
+ version: String,
+ compatibility: PluginCompatibility,
+ installed: bool,
+}
+
+impl PluginDescriptor {
+ fn cmp(&self, other: &Self) -> std::cmp::Ordering {
+ let version_cmp = match (
+ semver::Version::parse(&self.version),
+ semver::Version::parse(&other.version),
+ ) {
+ (Ok(v1), Ok(v2)) => v1.cmp(&v2),
+ _ => self.version.cmp(&other.version),
+ };
+
+ self.name.cmp(&other.name).then(version_cmp)
+ }
+}
+
/// Updates the locally cached spin-plugins repository, fetching the latest plugins.
async fn update() -> Result<()> {
let manager = PluginManager::try_default()?;
| 972
|
[
"937"
] |
diff --git a/crates/plugins/tests/README.md b/crates/plugins/tests/README.md
new file mode 100644
index 0000000000..8462f4b10a
--- /dev/null
+++ b/crates/plugins/tests/README.md
@@ -0,0 +1,8 @@
+## Fake plugin manifests
+
+These plugin manifests are fake - they exist to help exercise compatibility
+failure paths. They are in a compatible layout for you to xcopy to your
+catalogue snapshot directory (`~/.local/share/spin/plugins/.spin-plugins/manifests/`).
+
+The actual package pointers are what we engineers call "hot garbage"; they
+cannot be installed as actual plugins.
diff --git a/crates/plugins/tests/arm-only/arm-only.json b/crates/plugins/tests/arm-only/arm-only.json
new file mode 100644
index 0000000000..f17219d6f4
--- /dev/null
+++ b/crates/plugins/tests/arm-only/arm-only.json
@@ -0,0 +1,15 @@
+{
+ "name": "arm-only",
+ "description": "A plugin which only works on ARM Linux.",
+ "version": "0.1.0",
+ "spinCompatibility": ">=0.4",
+ "license": "Apache-2.0",
+ "packages": [
+ {
+ "os": "linux",
+ "arch": "arm",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ }
+ ]
+}
diff --git a/crates/plugins/tests/not-spin-ver/not-spin-ver.json b/crates/plugins/tests/not-spin-ver/not-spin-ver.json
new file mode 100644
index 0000000000..fce6254bde
--- /dev/null
+++ b/crates/plugins/tests/not-spin-ver/not-spin-ver.json
@@ -0,0 +1,21 @@
+{
+ "name": "not-spin-ver",
+ "description": "A plugin which doesn't work with your current version of Spin.",
+ "version": "10.2.0",
+ "spinCompatibility": "=999.999.999",
+ "license": "Apache-2.0",
+ "packages": [
+ {
+ "os": "linux",
+ "arch": "amd64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ },
+ {
+ "os": "macos",
+ "arch": "aarch64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ }
+ ]
+}
diff --git a/crates/plugins/tests/not-spin-ver/not-spin-ver@9.1.0.json b/crates/plugins/tests/not-spin-ver/not-spin-ver@9.1.0.json
new file mode 100644
index 0000000000..cf51603b46
--- /dev/null
+++ b/crates/plugins/tests/not-spin-ver/not-spin-ver@9.1.0.json
@@ -0,0 +1,15 @@
+{
+ "name": "not-spin-ver",
+ "description": "A plugin which doesn't work with your current version of Spin - Mac only build.",
+ "version": "9.1.0",
+ "spinCompatibility": "=999.999.999",
+ "license": "Apache-2.0",
+ "packages": [
+ {
+ "os": "macos",
+ "arch": "aarch64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ }
+ ]
+}
diff --git a/crates/plugins/tests/windows-only/windows-only.json b/crates/plugins/tests/windows-only/windows-only.json
new file mode 100644
index 0000000000..ec61020804
--- /dev/null
+++ b/crates/plugins/tests/windows-only/windows-only.json
@@ -0,0 +1,15 @@
+{
+ "name": "windows-only",
+ "description": "A plugin which only works on Windows.",
+ "version": "0.1.0",
+ "spinCompatibility": ">=0.4",
+ "license": "Apache-2.0",
+ "packages": [
+ {
+ "os": "windows",
+ "arch": "amd64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ }
+ ]
+}
|
268ae0a0015ac5b971ddd11a4c336fc24b76e754
|
8dfc4d6fbb31d624eb034f78640cb207bec1f682
|
Add `spin up` option to mount static asset directory directly
Currently, `spin up` always copies static assets into a temporary directory and mounts that into the host. This creates friction when iteratively developing static assets (e.g. SPAs) since `spin up` must be restarted each time any asset changes in order for the updated asset to be served.
I'm proposing that we add an option, e.g. `--direct-mount` to mount the asset directory directly instead of using a temporary directory, so that changes on the host filesystem are immediately visible to subsequent app invocations, with no restart required.
|
It would be good to ponder the behaviour on patterns/individual files. Many users will read a `--direct-mount` flag as implying that _all_ files, including loose ones, are also directly mounted, but as far as I know that would require mounting the entire containing directory, which is what the copy sought to avoid.
I wonder if this could instead by tackled by Radu's much-requested "hot reload" flag, which would provide for hot reload of loose files plus allow it to reflect changes in component Wasm as well as in assets. I'm not sure if that's prohibitively more complex though!
I was thinking the (documented) behavior would be that `--direct-mount` only works for locally-loaded apps using only directory mounts with no excluded files, and anything else causes an error.
I agree that a general hot reload option that works for everything, including loose files and Wasms, but I'm guessing that would be significantly more work. This proposal just solves a useful subset of that problem, which I _think_ should require a lot less effort. I'm in the middle of prototyping this now, so we should soon know whether that's true.
Yeah, if it errors on patterns then at least it's failing safe! Sounds good - thanks!
|
2022-12-12T22:01:37Z
|
fermyon__spin-967
|
fermyon/spin
|
0.6
|
diff --git a/crates/loader/src/local/assets.rs b/crates/loader/src/local/assets.rs
index a38f0f0de6..174c95bec3 100644
--- a/crates/loader/src/local/assets.rs
+++ b/crates/loader/src/local/assets.rs
@@ -18,6 +18,26 @@ use super::config::{RawDirectoryPlacement, RawFileMount};
/// Prepare all local assets given a component ID and its file patterns.
/// This file will copy all assets into a temporary directory as read-only.
pub(crate) async fn prepare_component(
+ raw_mounts: &[RawFileMount],
+ src: impl AsRef<Path>,
+ base_dst: Option<impl AsRef<Path>>,
+ id: &str,
+ exclude_files: &[String],
+) -> Result<Vec<DirectoryMount>> {
+ if let Some(base_dst) = base_dst {
+ prepare_component_with_temp_dir(raw_mounts, src, base_dst, id, exclude_files).await
+ } else {
+ tracing::info!("directly mounting local asset directories into guest");
+
+ if !exclude_files.is_empty() {
+ bail!("this component cannot be run with `--direct-mount` because some files are excluded from mounting")
+ }
+
+ prepare_component_with_direct_mounts(raw_mounts)
+ }
+}
+
+async fn prepare_component_with_temp_dir(
raw_mounts: &[RawFileMount],
src: impl AsRef<Path>,
base_dst: impl AsRef<Path>,
@@ -38,6 +58,29 @@ pub(crate) async fn prepare_component(
Ok(vec![DirectoryMount { guest, host }])
}
+fn prepare_component_with_direct_mounts(
+ raw_mounts: &[RawFileMount],
+) -> Result<Vec<DirectoryMount>> {
+ tracing::info!("directly mounting local asset directories into guest");
+
+ raw_mounts
+ .iter()
+ .map(|mount| match mount {
+ RawFileMount::Placement(placement) => Ok(DirectoryMount {
+ guest: placement
+ .destination
+ .to_str()
+ .context("unable to parse mount destination as UTF-8")?
+ .to_owned(),
+ host: placement.source.clone(),
+ }),
+ RawFileMount::Pattern(_) => Err(anyhow!(
+ "this component cannot be run with `--direct-mount` because it uses file patterns"
+ )),
+ })
+ .collect()
+}
+
/// A file that a component requires to be present at runtime.
#[derive(Debug, Clone)]
pub struct FileMount {
diff --git a/crates/loader/src/local/mod.rs b/crates/loader/src/local/mod.rs
index 0732464235..433f660f96 100644
--- a/crates/loader/src/local/mod.rs
+++ b/crates/loader/src/local/mod.rs
@@ -38,7 +38,7 @@ use self::config::FileComponentUrlSource;
/// otherwise create a new temporary directory.
pub async fn from_file(
app: impl AsRef<Path>,
- base_dst: impl AsRef<Path>,
+ base_dst: Option<impl AsRef<Path>>,
bindle_connection: &Option<BindleConnectionInfo>,
) -> Result<Application> {
let app = absolutize(app)?;
@@ -91,7 +91,7 @@ pub fn absolutize(path: impl AsRef<Path>) -> Result<PathBuf> {
async fn prepare_any_version(
raw: RawAppManifestAnyVersion,
src: impl AsRef<Path>,
- base_dst: impl AsRef<Path>,
+ base_dst: Option<impl AsRef<Path>>,
bindle_connection: &Option<BindleConnectionInfo>,
) -> Result<Application> {
match raw {
@@ -129,7 +129,7 @@ pub fn validate_raw_app_manifest(raw: &RawAppManifestAnyVersion) -> Result<()> {
async fn prepare(
raw: RawAppManifest,
src: impl AsRef<Path>,
- base_dst: impl AsRef<Path>,
+ base_dst: Option<impl AsRef<Path>>,
bindle_connection: &Option<BindleConnectionInfo>,
) -> Result<Application> {
let info = info(raw.info, &src);
@@ -145,7 +145,7 @@ async fn prepare(
let components = future::join_all(
raw.components
.into_iter()
- .map(|c| async { core(c, &src, &base_dst, bindle_connection).await })
+ .map(|c| async { core(c, &src, base_dst.as_ref(), bindle_connection).await })
.collect::<Vec<_>>(),
)
.await
@@ -171,7 +171,7 @@ async fn prepare(
async fn core(
raw: RawComponentManifest,
src: impl AsRef<Path>,
- base_dst: impl AsRef<Path>,
+ base_dst: Option<impl AsRef<Path>>,
bindle_connection: &Option<BindleConnectionInfo>,
) -> Result<CoreComponent> {
let id = raw.id;
@@ -227,7 +227,7 @@ async fn core(
let mounts = match raw.wasm.files {
Some(f) => {
let exclude_files = raw.wasm.exclude_files.unwrap_or_default();
- assets::prepare_component(&f, src, &base_dst, &id, &exclude_files).await?
+ assets::prepare_component(&f, src, base_dst, &id, &exclude_files).await?
}
None => vec![],
};
diff --git a/crates/trigger/src/locked.rs b/crates/trigger/src/locked.rs
index 67de11e3ba..e485531cf7 100644
--- a/crates/trigger/src/locked.rs
+++ b/crates/trigger/src/locked.rs
@@ -235,7 +235,7 @@ mod tests {
std::fs::write("spin.toml", TEST_MANIFEST).expect("write manifest");
std::fs::write("test-source.wasm", "not actual wasm").expect("write source");
std::fs::write("static.txt", "content").expect("write static");
- let app = spin_loader::local::from_file("spin.toml", &tempdir, &None)
+ let app = spin_loader::local::from_file("spin.toml", Some(&tempdir), &None)
.await
.expect("load app");
(app, tempdir)
diff --git a/src/commands/up.rs b/src/commands/up.rs
index 0a83078c82..a9c4f8550f 100644
--- a/src/commands/up.rs
+++ b/src/commands/up.rs
@@ -87,6 +87,14 @@ pub struct UpCommand {
#[clap(long = "temp")]
pub tmp: Option<PathBuf>,
+ /// For local apps with directory mounts and no excluded files, mount them directly instead of using a temporary
+ /// directory.
+ ///
+ /// This allows you to update the assets on the host filesystem such that the updates are visible to the guest
+ /// without a restart. This cannot be used with bindle apps or apps which use file patterns and/or exclusions.
+ #[clap(long, takes_value = false, conflicts_with = BINDLE_ID_OPT)]
+ pub direct_mounts: bool,
+
/// All other args, to be passed through to the trigger
#[clap(hide = true)]
pub trigger_args: Vec<OsString>,
@@ -127,10 +135,19 @@ impl UpCommand {
.as_deref()
.unwrap_or_else(|| DEFAULT_MANIFEST_FILE.as_ref());
let bindle_connection = self.bindle_connection();
- spin_loader::from_file(manifest_file, &working_dir, &bindle_connection).await?
+ let asset_dst = if self.direct_mounts {
+ None
+ } else {
+ Some(&working_dir)
+ };
+ spin_loader::from_file(manifest_file, asset_dst, &bindle_connection).await?
}
(None, Some(bindle)) => match &self.server {
- Some(server) => spin_loader::from_bindle(bindle, server, &working_dir).await?,
+ Some(server) => {
+ assert!(!self.direct_mounts);
+
+ spin_loader::from_bindle(bindle, server, &working_dir).await?
+ }
_ => bail!("Loading from a bindle requires a Bindle server URL"),
},
(Some(_), Some(_)) => bail!("Specify only one of app file or bindle ID"),
| 967
|
[
"964"
] |
diff --git a/crates/loader/src/local/tests.rs b/crates/loader/src/local/tests.rs
index ceaff588af..3aae011dc4 100644
--- a/crates/loader/src/local/tests.rs
+++ b/crates/loader/src/local/tests.rs
@@ -11,7 +11,7 @@ async fn test_from_local_source() -> Result<()> {
let temp_dir = tempfile::tempdir()?;
let dir = temp_dir.path();
- let app = from_file(MANIFEST, dir, &None).await?;
+ let app = from_file(MANIFEST, Some(dir), &None).await?;
assert_eq!(app.info.name, "spin-local-source-test");
assert_eq!(app.info.version, "1.0.0");
@@ -157,7 +157,7 @@ async fn test_invalid_manifest() -> Result<()> {
let temp_dir = tempfile::tempdir()?;
let dir = temp_dir.path();
- let app = from_file(MANIFEST, dir, &None).await;
+ let app = from_file(MANIFEST, Some(dir), &None).await;
let e = app.unwrap_err().to_string();
assert!(
@@ -214,7 +214,7 @@ async fn test_duplicate_component_id_is_rejected() -> Result<()> {
let temp_dir = tempfile::tempdir()?;
let dir = temp_dir.path();
- let app = from_file(MANIFEST, dir, &None).await;
+ let app = from_file(MANIFEST, Some(dir), &None).await;
assert!(
app.is_err(),
@@ -236,7 +236,7 @@ async fn test_insecure_allow_all_with_invalid_url() -> Result<()> {
let temp_dir = tempfile::tempdir()?;
let dir = temp_dir.path();
- let app = from_file(MANIFEST, dir, &None).await;
+ let app = from_file(MANIFEST, Some(dir), &None).await;
assert!(
app.is_ok(),
@@ -252,7 +252,7 @@ async fn test_invalid_url_in_allowed_http_hosts_is_rejected() -> Result<()> {
let temp_dir = tempfile::tempdir()?;
let dir = temp_dir.path();
- let app = from_file(MANIFEST, dir, &None).await;
+ let app = from_file(MANIFEST, Some(dir), &None).await;
assert!(app.is_err(), "Expected allowed_http_hosts parsing error");
|
268ae0a0015ac5b971ddd11a4c336fc24b76e754
|
c368fce72261339b6de908e22b81cf21217a8181
|
`spin up --help` doesn't display all options unless application is fully ready to load
If I do a `spin up --help` in a directory with a `spin.toml`, I normally get a full set of options including those that (internally) happen to be implemented through the trigger such as `--log-dir` and `--follow`.
However, if I `spin new` a directory and do `spin up --help`, I get only the subset that (internally) happen to be implemented diirectly on the `Up` command type itself.
But if I do a `spin build` then it starts working again. It was the inability to load the component Wasm source that was causing the options to disappear.
So it looks like `spin up --help` is trying to load the application to the point where it is ready for the relevant `spin trigger foo` command to execute, even though all we actually need to be able to extract is the trigger type.
|
2022-12-05T00:14:22Z
|
fermyon__spin-934
|
fermyon/spin
|
0.6
|
diff --git a/src/commands/up.rs b/src/commands/up.rs
index 958a59ccd2..0a83078c82 100644
--- a/src/commands/up.rs
+++ b/src/commands/up.rs
@@ -148,32 +148,20 @@ impl UpCommand {
ApplicationTrigger::Redis(_) => "redis",
};
- // Build and write app lock file
- let locked_app = spin_trigger::locked::build_locked_app(app, &working_dir)?;
- let locked_path = working_dir.join("spin.lock");
- let locked_app_contents =
- serde_json::to_vec_pretty(&locked_app).context("failed to serialize locked app")?;
- std::fs::write(&locked_path, locked_app_contents)
- .with_context(|| format!("failed to write {:?}", locked_path))?;
- let locked_url = Url::from_file_path(&locked_path)
- .map_err(|_| anyhow!("cannot convert to file URL: {locked_path:?}"))?
- .to_string();
-
- // For `spin up --help`, we just want the executor to dump its own argument usage info
- let trigger_args = if self.help {
- vec![OsString::from("--help-args-only")]
- } else {
- self.trigger_args
- };
-
// The docs for `current_exe` warn that this may be insecure because it could be executed
// via hard-link. I think it should be fine as long as we aren't `setuid`ing this binary.
let mut cmd = std::process::Command::new(std::env::current_exe().unwrap());
cmd.arg("trigger")
- .env(SPIN_WORKING_DIR, working_dir)
- .env(SPIN_LOCKED_URL, locked_url)
.arg(trigger_type)
- .args(trigger_args);
+ .env(SPIN_WORKING_DIR, &working_dir);
+
+ if self.help {
+ cmd.arg("--help-args-only");
+ } else {
+ let locked_url = self.write_locked_app(app, &working_dir)?;
+ cmd.env(SPIN_LOCKED_URL, locked_url)
+ .args(&self.trigger_args);
+ };
tracing::trace!("Running trigger executor: {:?}", cmd);
@@ -199,6 +187,25 @@ impl UpCommand {
}
}
+ fn write_locked_app(
+ &self,
+ app: spin_manifest::Application,
+ working_dir: &Path,
+ ) -> Result<String, anyhow::Error> {
+ // Build and write app lock file
+ let locked_app = spin_trigger::locked::build_locked_app(app, working_dir)?;
+ let locked_path = working_dir.join("spin.lock");
+ let locked_app_contents =
+ serde_json::to_vec_pretty(&locked_app).context("failed to serialize locked app")?;
+ std::fs::write(&locked_path, locked_app_contents)
+ .with_context(|| format!("failed to write {:?}", locked_path))?;
+ let locked_url = Url::from_file_path(&locked_path)
+ .map_err(|_| anyhow!("cannot convert to file URL: {locked_path:?}"))?
+ .to_string();
+
+ Ok(locked_url)
+ }
+
fn bindle_connection(&self) -> Option<BindleConnectionInfo> {
self.server.as_ref().map(|url| {
BindleConnectionInfo::new(
| 934
|
[
"932"
] |
diff --git a/tests/integration.rs b/tests/integration.rs
index e0c5373e65..d191e60fcc 100644
--- a/tests/integration.rs
+++ b/tests/integration.rs
@@ -1078,6 +1078,43 @@ mod integration_tests {
Ok(())
}
+ #[test]
+ fn spin_up_gives_help_on_new_app() -> Result<()> {
+ let temp_dir = tempdir()?;
+ let dir = temp_dir.path();
+ let manifest_file = dir.join("spin.toml");
+
+ // We still don't see full help if there are no components.
+ let toml_text = r#"spin_version = "1"
+name = "unbuilt"
+trigger = { type = "http", base = "/" }
+version = "0.1.0"
+[[component]]
+id = "unbuilt"
+source = "DOES-NOT-EXIST.wasm"
+[component.trigger]
+route = "/..."
+"#;
+
+ std::fs::write(&manifest_file, toml_text)?;
+
+ let up_help_args = vec![
+ SPIN_BINARY,
+ "up",
+ "--file",
+ manifest_file.to_str().unwrap(),
+ "--help",
+ ];
+
+ let output = run(up_help_args, None, None)?;
+
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(stdout.contains("--follow-all"));
+ assert!(stdout.contains("--listen"));
+
+ Ok(())
+ }
+
// TODO: Test on Windows
#[cfg(not(target_os = "windows"))]
#[test]
|
268ae0a0015ac5b971ddd11a4c336fc24b76e754
|
|
cfc203e63a4a0e36a4ee94d66362c04f07d52841
|
`spin build` trigger validation messages are not explained
I fouled up the Redis template so that `trigger` had a `base` field instead of `address`.
When I ran `spin build`, it said `Error: missing field `address``.
As my brain was in the "I am compiling" mindset, I assumed there was something wrong in the code, though I was puzzled by the lack of compiler context. It didn't occur to me for a while that Spin was actually validating the trigger configuration.
Could we either ignore irrelevant fields during build, or provide a contextful message such as "Invalid trigger configuration" or "Invalid manifest file", ideally saying more about where the error occurred than just the name of what in this case was a nested field? Even calling it `trigger.address` would have helped.
|
I think this could be a "good first issue" if we flesh it out a bit more, e.g. explaining where in the code to add context.
|
2022-11-22T00:57:31Z
|
fermyon__spin-913
|
fermyon/spin
|
0.6
|
diff --git a/Cargo.lock b/Cargo.lock
index 849055c632..f3a5ac0b31 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4006,8 +4006,11 @@ version = "0.6.0"
dependencies = [
"anyhow",
"futures",
+ "serde",
"spin-loader",
"subprocess",
+ "tokio",
+ "toml",
"tracing",
]
diff --git a/crates/build/Cargo.toml b/crates/build/Cargo.toml
index 7b7027dad6..6b5f1ecbf3 100644
--- a/crates/build/Cargo.toml
+++ b/crates/build/Cargo.toml
@@ -7,6 +7,9 @@ edition = { workspace = true }
[dependencies]
anyhow = "1.0.57"
futures = "0.3.21"
+serde = { version = "1.0", features = [ "derive" ] }
spin-loader = { path = "../loader" }
subprocess = "0.2.8"
+tokio = { version = "1.11", features = [ "full" ] }
+toml = "0.5"
tracing = { version = "0.1", features = [ "log" ] }
diff --git a/crates/build/src/lib.rs b/crates/build/src/lib.rs
index 76a6df71b8..dc6dd6bae2 100644
--- a/crates/build/src/lib.rs
+++ b/crates/build/src/lib.rs
@@ -2,18 +2,22 @@
//! A library for building Spin components.
+mod manifest;
+
use anyhow::{bail, Context, Result};
-use spin_loader::local::{
- config::{RawAppManifestAnyVersion, RawComponentManifest},
- parent_dir, raw_manifest_from_file,
-};
+use spin_loader::local::parent_dir;
use std::path::{Path, PathBuf};
use subprocess::{Exec, Redirection};
use tracing::log;
+use crate::manifest::{BuildAppInfoAnyVersion, RawComponentManifest};
+
/// If present, run the build command of each component.
pub async fn build(manifest_file: &Path) -> Result<()> {
- let RawAppManifestAnyVersion::V1(app) = raw_manifest_from_file(&manifest_file).await?;
+ let manifest_text = tokio::fs::read_to_string(manifest_file)
+ .await
+ .with_context(|| format!("Cannot read manifest file from {}", manifest_file.display()))?;
+ let BuildAppInfoAnyVersion::V1(app) = toml::from_str(&manifest_text)?;
let app_dir = parent_dir(manifest_file)?;
if app.components.iter().all(|c| c.build.is_none()) {
@@ -98,3 +102,19 @@ fn construct_workdir(app_dir: &Path, workdir: Option<impl AsRef<Path>>) -> Resul
Ok(cwd)
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn test_data_root() -> PathBuf {
+ let crate_dir = env!("CARGO_MANIFEST_DIR");
+ PathBuf::from(crate_dir).join("tests")
+ }
+
+ #[tokio::test]
+ async fn can_load_even_if_trigger_invalid() {
+ let bad_trigger_file = test_data_root().join("bad_trigger.toml");
+ build(&bad_trigger_file).await.unwrap();
+ }
+}
diff --git a/crates/build/src/manifest.rs b/crates/build/src/manifest.rs
new file mode 100644
index 0000000000..2eea6dc5f6
--- /dev/null
+++ b/crates/build/src/manifest.rs
@@ -0,0 +1,31 @@
+use std::path::PathBuf;
+
+use serde::{Deserialize, Serialize};
+
+#[derive(Clone, Debug, Deserialize, Serialize)]
+#[serde(tag = "spin_version")]
+pub(crate) enum BuildAppInfoAnyVersion {
+ #[serde(rename = "1")]
+ V1(BuildAppInfoV1),
+}
+
+#[derive(Clone, Debug, Deserialize, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub(crate) struct BuildAppInfoV1 {
+ #[serde(rename = "component")]
+ pub components: Vec<RawComponentManifest>,
+}
+
+#[derive(Clone, Debug, Deserialize, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub(crate) struct RawComponentManifest {
+ pub id: String,
+ pub build: Option<RawBuildConfig>,
+}
+
+#[derive(Clone, Debug, Deserialize, Serialize)]
+#[serde(deny_unknown_fields, rename_all = "snake_case")]
+pub(crate) struct RawBuildConfig {
+ pub command: String,
+ pub workdir: Option<PathBuf>,
+}
| 913
|
[
"473"
] |
diff --git a/crates/build/tests/bad_trigger.toml b/crates/build/tests/bad_trigger.toml
new file mode 100644
index 0000000000..8af11b6e71
--- /dev/null
+++ b/crates/build/tests/bad_trigger.toml
@@ -0,0 +1,13 @@
+spin_version = "1"
+name = "bad_trigger"
+# The trigger is missing the `base` field
+trigger = { type = "http" }
+version = "0.1.0"
+
+[[component]]
+id = "test"
+source = "does-not-exist"
+[component.trigger]
+route = "/test"
+[component.build]
+command = "echo done"
|
268ae0a0015ac5b971ddd11a4c336fc24b76e754
|
79d16153927850496cb84c1f50a8bfd3ae3e7821
|
Grab `.wasm` binaries from the web
I want to be able to share modules with others but not require them to download/compile them themselves
## Spin.toml
My intuition says this URL would be written in the `spin.toml` like so:
```
[[component]]
id = "key-value"
source = "https://github.com/ecumene/components/.../hello-world.wasm"
```
But how would we get the modules? I think there are generally two ways to achieve this
1. Build a tool that saves them to a cache based on the `spin.toml` and change nothing here
1. Have Spin download these at runtime
We could also do both! Maybe we could include a mapping of these modules to their place on the drive, and that would leave it up to something built into Spin or some manager to resolve them.
|
We could combine the two ways: having spin download these wasm files at runtime and cache them to a `spin.lock` file, which includes the checksums. In this way when the next time spin is running, if the checksum of the `spin.toml` is not changed, then can use the cached wasm files. And of course if the lock file is deleted, then spin will always fetch the newest remote wasm modules.
Would the lockfile map the downloaded modules to their place on disk too?
I would decouple the two conversations as two distinct ones:
1. using HTTP URLs as module sources in `spin.toml` files
1. caching pulled modules (and assets), which also includes when running from Bindle, and I think it makes sense to have a common caching implementation for various sources.
For 1, do we need to consider any authentication mechanisms when performing HTTP requests, or are we ok with public sources for now?
(I think for the first iteration on this, public sources like GitHub releases are totally fine).
> For 1, do we need to consider any authentication mechanisms when performing HTTP requests, or are we ok with public sources for now?
Like HTTP basic auth? Or something else like a cookie?
For my purposes public sources are fine
Yep I agree that this is two tasks. I'm happy to work on the caching implementaiton.
I think we should default to verifying the integrity of remote-sourced binaries to encourage good security practices. That might look something like:
```toml
[component.source]
url = "https://raw.githubusercontent.com/..."
integrity = "sha256:abc123..."
```
_If necessary_, we could allow explicit integrity opt-out, e.g.: `integrity = "insecure"`
This could also (later) be expanded nicely to code signing, e.g. `integrity = "ed25519:<pubkey>"`.
I'm not opposed to this (provided we address the software supply chain risks) but would like to get a sense for where it fits in with bindle publishing and the registry. Presumably the situation here is that a developer would like to reuse a handler, such as Bartholomew, but within their own application context; whereas bindles are more about providing full applications.
Should we instead provide a convenient way for users to publish and reference module-only bindles, with all the guarantees that provides consumers around provenance and immutability? Or would the "plain HTTP" solution still be necessary because there aren't enough well known bindle servers around?
Longer term this speaks to questions such as the component registry, and the composing of applications from public, published components. So let's get a sense of where we envisage this being used, whether it is about convenient short-term sharing within a close collaboration, or long-term publishing of components designed for reuse.
I guess I am worried that we risk doing the unreliable, physically coupled publishing strategy first, and risk ending up with a spaghetti ecosystem with high vulnerability to supply chain attacks, which becomes entrenched before we have a structured alternative. On the other hand, I do see the value of convenient sharing and don't want to hold it up while we labour on a 'perfect' solution!
_As long as the remote item is integrity-checked_, it should be no less secure than `wget`ing the module and referencing that local file.
Most of the value of bindle (or a future registry) is what it can (could) add on top: component discovery, code signing key management, update management, dependency resolution, etc.
|
2022-11-09T04:41:25Z
|
fermyon__spin-890
|
fermyon/spin
|
0.6
|
diff --git a/crates/loader/src/local/config.rs b/crates/loader/src/local/config.rs
index 3773d7697c..5cde747cbd 100644
--- a/crates/loader/src/local/config.rs
+++ b/crates/loader/src/local/config.rs
@@ -137,6 +137,8 @@ pub enum RawModuleSource {
FileReference(PathBuf),
/// Reference to a remote bindle
Bindle(FileComponentBindleSource),
+ /// Reference to a Wasm file at a URL
+ Url(FileComponentUrlSource),
}
/// A component source from Bindle.
@@ -151,3 +153,13 @@ pub struct FileComponentBindleSource {
/// Parcel to use from the bindle.
pub parcel: String,
}
+/// A component source from a URL.
+#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
+#[serde(deny_unknown_fields, rename_all = "snake_case")]
+pub struct FileComponentUrlSource {
+ /// The URL of the Wasm binary.
+ pub url: String,
+ /// The digest of the Wasm binary, used for integrity checking. This must be a
+ /// SHA256 digest, in the form `sha256:...`
+ pub digest: String,
+}
diff --git a/crates/loader/src/local/mod.rs b/crates/loader/src/local/mod.rs
index ad240acf64..3c4ff90512 100644
--- a/crates/loader/src/local/mod.rs
+++ b/crates/loader/src/local/mod.rs
@@ -10,21 +10,28 @@ pub mod config;
#[cfg(test)]
mod tests;
-use std::{path::Path, str::FromStr};
+use std::{
+ path::{Path, PathBuf},
+ str::FromStr,
+};
use anyhow::{anyhow, bail, Context, Result};
use futures::future;
+use itertools::Itertools;
use outbound_http::allowed_http_hosts::validate_allowed_http_hosts;
use path_absolutize::Absolutize;
+use reqwest::Url;
use spin_manifest::{
Application, ApplicationInformation, ApplicationOrigin, CoreComponent, ModuleSource,
SpinVersion, WasmConfig,
};
use tokio::{fs::File, io::AsyncReadExt};
-use crate::bindle::BindleConnectionInfo;
+use crate::{bindle::BindleConnectionInfo, digest::bytes_sha256_string};
use config::{RawAppInformation, RawAppManifest, RawAppManifestAnyVersion, RawComponentManifest};
+use self::config::FileComponentUrlSource;
+
/// Given the path to a spin.toml manifest file, prepare its assets locally and
/// get a prepared application configuration consumable by a Spin execution context.
/// If a directory is provided, use it as the base directory to expand the assets,
@@ -188,6 +195,17 @@ async fn core(
let name = format!("{}@{}", bindle_id, parcel_sha);
ModuleSource::Buffer(bytes, name)
}
+ config::RawModuleSource::Url(us) => {
+ let source = UrlSource::new(&us)
+ .with_context(|| format!("Can't use Web source in component {}", id))?;
+
+ let bytes = source
+ .get()
+ .await
+ .with_context(|| format!("Can't use source {} for component {}", us.url, id))?;
+
+ ModuleSource::Buffer(bytes, us.url)
+ }
};
let description = raw.description;
@@ -215,6 +233,119 @@ async fn core(
})
}
+/// A parsed URL source for a component module.
+#[derive(Debug)]
+pub struct UrlSource {
+ url: Url,
+ digest: ComponentDigest,
+}
+
+impl UrlSource {
+ /// Parses a URL source from a raw component manifest.
+ pub fn new(us: &FileComponentUrlSource) -> anyhow::Result<UrlSource> {
+ let url = reqwest::Url::parse(&us.url)
+ .with_context(|| format!("Invalid source URL {}", us.url))?;
+ if url.scheme() != "https" {
+ anyhow::bail!("Invalid URL scheme {}: must be HTTPS", url.scheme(),);
+ }
+
+ let digest = ComponentDigest::try_from(&us.digest)?;
+
+ Ok(Self { url, digest })
+ }
+
+ /// The URL of the source.
+ pub fn url(&self) -> &Url {
+ &self.url
+ }
+
+ /// A relative path URL derived from the URL.
+ pub fn url_relative_path(&self) -> PathBuf {
+ let path = self.url.path();
+ let rel_path = path.trim_start_matches('/');
+ PathBuf::from(rel_path)
+ }
+
+ /// The digest string (omitting the format).
+ pub fn digest_str(&self) -> &str {
+ match &self.digest {
+ ComponentDigest::Sha256(s) => s,
+ }
+ }
+
+ /// Gets the data from the source as a byte buffer.
+ pub async fn get(&self) -> anyhow::Result<Vec<u8>> {
+ let response = reqwest::get(self.url.clone())
+ .await
+ .with_context(|| format!("Error fetching source URL {}", self.url))?;
+ // TODO: handle redirects
+ let status = response.status();
+ if status != reqwest::StatusCode::OK {
+ let reason = status.canonical_reason().unwrap_or("(no reason provided)");
+ anyhow::bail!(
+ "Error fetching source URL {}: {} {}",
+ self.url,
+ status.as_u16(),
+ reason
+ );
+ }
+ let body = response
+ .bytes()
+ .await
+ .with_context(|| format!("Error loading source URL {}", self.url))?;
+ let bytes = body.into_iter().collect_vec();
+
+ self.digest.verify(&bytes).context("Incorrect digest")?;
+
+ Ok(bytes)
+ }
+}
+
+#[derive(Debug)]
+enum ComponentDigest {
+ Sha256(String),
+}
+
+impl TryFrom<&String> for ComponentDigest {
+ type Error = anyhow::Error;
+
+ fn try_from(value: &String) -> Result<Self, Self::Error> {
+ if let Some((format, text)) = value.split_once(':') {
+ match format {
+ "sha256" => {
+ if text.is_empty() {
+ Err(anyhow!("Invalid digest string '{value}': no digest"))
+ } else {
+ Ok(Self::Sha256(text.to_owned()))
+ }
+ }
+ _ => Err(anyhow!(
+ "Invalid digest string '{value}': format must be sha256"
+ )),
+ }
+ } else {
+ Err(anyhow!(
+ "Invalid digest string '{value}': format must be 'sha256:...'"
+ ))
+ }
+ }
+}
+
+impl ComponentDigest {
+ fn verify(&self, bytes: &[u8]) -> anyhow::Result<()> {
+ match self {
+ Self::Sha256(expected) => {
+ let actual = &bytes_sha256_string(bytes);
+ if expected == actual {
+ Ok(())
+ } else {
+ Err(anyhow!("Downloaded file does not match specified digest: expected {expected}, actual {actual}"))
+ }
+ }
+ }
+ }
+}
+
/// Converts the raw application information from the spin.toml manifest to the standard configuration.
fn info(raw: RawAppInformation, src: impl AsRef<Path>) -> ApplicationInformation {
ApplicationInformation {
diff --git a/crates/publish/src/expander.rs b/crates/publish/src/expander.rs
index 936ca2545b..df667c2607 100644
--- a/crates/publish/src/expander.rs
+++ b/crates/publish/src/expander.rs
@@ -8,7 +8,7 @@ use semver::BuildMetadata;
use spin_loader::{
bindle::config as bindle_schema,
digest::{bytes_sha256_string, file_sha256_string},
- local::{config as local_schema, validate_raw_app_manifest},
+ local::{config as local_schema, validate_raw_app_manifest, UrlSource},
};
use std::path::{Path, PathBuf};
@@ -42,7 +42,7 @@ pub async fn expand_manifest(
// - there is a parcel for the spin.toml-a-like and it has the magic media type
// - n parcels for the Wasm modules at their locations
- let wasm_parcels = wasm_parcels(&manifest, &app_dir)
+ let wasm_parcels = wasm_parcels(&manifest, &app_dir, &scratch_dir)
.await
.context("Failed to collect Wasm modules")?;
let wasm_parcels = consolidate_wasm_parcels(wasm_parcels);
@@ -113,6 +113,11 @@ fn bindle_component_manifest(
"This version of Spin can't publish components whose sources are already bindles"
)
}
+ local_schema::RawModuleSource::Url(us) => {
+ let source = UrlSource::new(us)
+ .with_context(|| format!("Can't use Web source in component {}", local.id))?;
+ source.digest_str().to_owned()
+ }
};
let asset_group = local.wasm.files.as_ref().map(|_| group_name_for(&local.id));
Ok(bindle_schema::RawComponentManifest {
@@ -132,8 +137,12 @@ fn bindle_component_manifest(
async fn wasm_parcels(
manifest: &local_schema::RawAppManifest,
base_dir: &Path,
+ scratch_dir: impl AsRef<Path>,
) -> Result<Vec<SourcedParcel>> {
- let parcel_futures = manifest.components.iter().map(|c| wasm_parcel(c, base_dir));
+ let parcel_futures = manifest
+ .components
+ .iter()
+ .map(|c| wasm_parcel(c, base_dir, scratch_dir.as_ref()));
let parcels = futures::future::join_all(parcel_futures).await;
parcels.into_iter().collect()
}
@@ -141,16 +150,45 @@ async fn wasm_parcels(
async fn wasm_parcel(
component: &local_schema::RawComponentManifest,
base_dir: &Path,
+ scratch_dir: impl AsRef<Path>,
) -> Result<SourcedParcel> {
- let wasm_file = match &component.source {
- local_schema::RawModuleSource::FileReference(path) => path,
+ let (wasm_file, absolute_wasm_file) = match &component.source {
+ local_schema::RawModuleSource::FileReference(path) => {
+ (path.to_owned(), base_dir.join(path))
+ }
local_schema::RawModuleSource::Bindle(_) => {
anyhow::bail!(
"This version of Spin can't publish components whose sources are already bindles"
)
}
+ local_schema::RawModuleSource::Url(us) => {
+ let id = &component.id;
+
+ let source = UrlSource::new(us)
+ .with_context(|| format!("Can't use Web source in component {}", id))?;
+
+ let bytes = source
+ .get()
+ .await
+ .with_context(|| format!("Can't use source {} for component {}", us.url, id))?;
+
+ let temp_dir = scratch_dir.as_ref().join("downloads");
+ let temp_file = temp_dir.join(us.digest.replace(':', "_"));
+
+ tokio::fs::create_dir_all(temp_dir)
+ .await
+ .context("Failed to save download to temporary file")?;
+ tokio::fs::write(&temp_file, &bytes)
+ .await
+ .context("Failed to save download to temporary file")?;
+
+ let absolute_path = dunce::canonicalize(&temp_file)
+ .context("Failed to acquire full path for app downloaded temporary file")?;
+ let dest_relative_path = source.url_relative_path();
+
+ (dest_relative_path, absolute_path)
+ }
};
- let absolute_wasm_file = base_dir.join(wasm_file);
file_parcel(&absolute_wasm_file, wasm_file, None, "application/wasm").await
}
diff --git a/src/commands/deploy.rs b/src/commands/deploy.rs
index 7c05c97589..4abbbd8970 100644
--- a/src/commands/deploy.rs
+++ b/src/commands/deploy.rs
@@ -441,6 +441,7 @@ impl DeployCommand {
copy(&mut r, &mut sha256)?;
}
config::RawModuleSource::Bindle(_b) => {}
+ config::RawModuleSource::Url(us) => sha256.update(us.digest.as_bytes()),
}
if let Some(files) = &x.wasm.files {
let source_dir = crate::app_dir(&self.app)?;
| 890
|
[
"393"
] |
diff --git a/crates/loader/src/local/tests.rs b/crates/loader/src/local/tests.rs
index f355fc7958..ceaff588af 100644
--- a/crates/loader/src/local/tests.rs
+++ b/crates/loader/src/local/tests.rs
@@ -91,11 +91,63 @@ fn test_manifest() -> Result<()> {
let b = match cfg.components[1].source.clone() {
RawModuleSource::Bindle(b) => b,
RawModuleSource::FileReference(_) => panic!("expected bindle source"),
+ RawModuleSource::Url(_) => panic!("expected bindle source"),
};
assert_eq!(b.reference, "bindle reference".to_string());
assert_eq!(b.parcel, "parcel".to_string());
+ let u = match cfg.components[2].source.clone() {
+ RawModuleSource::Url(u) => u,
+ RawModuleSource::FileReference(_) => panic!("expected URL source"),
+ RawModuleSource::Bindle(_) => panic!("expected URL source"),
+ };
+
+ assert_eq!(u.url, "https://example.com/wasm.wasm.wasm".to_string());
+ assert_eq!(u.digest, "sha256:12345".to_string());
+
+ Ok(())
+}
+
+#[tokio::test]
+async fn can_parse_url_sources() -> Result<()> {
+ let fcs = FileComponentUrlSource {
+ url: "https://example.com/wasm.wasm.wasm".to_owned(),
+ digest: "sha256:12345".to_owned(),
+ };
+ let us = UrlSource::new(&fcs)?;
+ assert_eq!("https", us.url().scheme());
+ assert_eq!("/wasm.wasm.wasm", us.url().path());
+ assert_eq!(PathBuf::from("wasm.wasm.wasm"), us.url_relative_path());
+ Ok(())
+}
+
+#[tokio::test]
+async fn url_sources_are_validated() -> Result<()> {
+ let fcs1 = FileComponentUrlSource {
+ url: "ftp://example.com/wasm.wasm.wasm".to_owned(),
+ digest: "sha256:12345".to_owned(),
+ };
+ UrlSource::new(&fcs1).expect_err("fcs1 should fail on scheme");
+
+ let fcs2 = FileComponentUrlSource {
+ url: "SNORKBONGLY".to_owned(),
+ digest: "sha256:12345".to_owned(),
+ };
+ UrlSource::new(&fcs2).expect_err("fcs2 should fail because not a URL");
+
+ let fcs3 = FileComponentUrlSource {
+ url: "https://example.com/wasm.wasm.wasm".to_owned(),
+ digest: "sha123:12345".to_owned(),
+ };
+ UrlSource::new(&fcs3).expect_err("fcs3 should fail on digest fmt");
+
+ let fcs4 = FileComponentUrlSource {
+ url: "https://example.com/wasm.wasm.wasm".to_owned(),
+ digest: "sha256:".to_owned(),
+ };
+ UrlSource::new(&fcs4).expect_err("fcs4 should fail on empty digest");
+
Ok(())
}
diff --git a/crates/loader/tests/valid-manifest.toml b/crates/loader/tests/valid-manifest.toml
index d6cf5cac6e..fb26c55073 100644
--- a/crates/loader/tests/valid-manifest.toml
+++ b/crates/loader/tests/valid-manifest.toml
@@ -23,3 +23,11 @@ parcel = "parcel"
reference = "bindle reference"
[component.trigger]
route = "/test"
+
+[[component]]
+id = "web"
+[component.source]
+url = "https://example.com/wasm.wasm.wasm"
+digest = "sha256:12345"
+[component.trigger]
+route = "/dont/test"
diff --git a/tests/http/assets-test/config/site.toml b/tests/http/assets-test/config/site.toml
new file mode 100644
index 0000000000..bd5a924951
--- /dev/null
+++ b/tests/http/assets-test/config/site.toml
@@ -0,0 +1,9 @@
+title = "Test"
+base_url = "http://localhost:3000"
+about = "This site is generated with Bartholomew, the Spin micro-CMS. And this message is in site.toml."
+theme = "fermyon"
+index_site_pages = ["main"]
+enable_shortcodes = false
+
+[extra]
+copyright = "The Site Authors"
diff --git a/tests/http/assets-test/content/index.md b/tests/http/assets-test/content/index.md
new file mode 100644
index 0000000000..d0b45e36d3
--- /dev/null
+++ b/tests/http/assets-test/content/index.md
@@ -0,0 +1,4 @@
+title = "Test"
+template = "home"
+date = "2022-10-15T00:22:56Z"
+---
diff --git a/tests/http/assets-test/spin.toml b/tests/http/assets-test/spin.toml
index 4d4437f7ec..b948172495 100644
--- a/tests/http/assets-test/spin.toml
+++ b/tests/http/assets-test/spin.toml
@@ -4,6 +4,13 @@ name = "spin-assets-test"
trigger = {type = "http", base = "/"}
version = "1.0.0"
+[[component]]
+source = { url = "https://github.com/fermyon/bartholomew/releases/download/v0.6.0/bartholomew.wasm", digest = "sha256:b64bc17da4484ff7fee619ba543f077be69b3a1f037506e0eeee1fb020d42786" }
+id = "bartholomew"
+files = [ "content/**/*" , "templates/*", "config/*"]
+[component.trigger]
+route = "/..."
+
[[component]]
id = "fs"
# should we just use git submodules to avoid having binary test files here?
diff --git a/tests/http/assets-test/templates/home.hbs b/tests/http/assets-test/templates/home.hbs
new file mode 100644
index 0000000000..5fd31b34df
--- /dev/null
+++ b/tests/http/assets-test/templates/home.hbs
@@ -0,0 +1,7 @@
+<html>
+ <body>
+ <div>
+ <h1>Hello</h1>
+ </div>
+ </body>
+</html>
diff --git a/tests/integration.rs b/tests/integration.rs
index 8b410f228c..71c7d8b1ad 100644
--- a/tests/integration.rs
+++ b/tests/integration.rs
@@ -175,6 +175,9 @@ mod integration_tests {
let s = SpinTestController::with_bindle(RUST_HTTP_STATIC_ASSETS_REST_REF, &b.url, &[])
.await?;
+ assert_status(&s, "/", 200).await?;
+ assert_response_contains(&s, "/", "<h1>Hello</h1>").await?;
+
assert_status(&s, "/static/thisshouldbemounted/1", 200).await?;
assert_status(&s, "/static/thisshouldbemounted/2", 200).await?;
assert_status(&s, "/static/thisshouldbemounted/3", 200).await?;
@@ -662,6 +665,9 @@ mod integration_tests {
)
.await?;
+ assert_status(&s, "/", 200).await?;
+ assert_response_contains(&s, "/", "<h1>Hello</h1>").await?;
+
assert_status(&s, "/static/thisshouldbemounted/1", 200).await?;
assert_status(&s, "/static/thisshouldbemounted/2", 200).await?;
assert_status(&s, "/static/thisshouldbemounted/3", 200).await?;
@@ -806,6 +812,27 @@ mod integration_tests {
Ok(())
}
+ async fn assert_response_contains(
+ s: &SpinTestController,
+ absolute_uri: &str,
+ expected: &str,
+ ) -> Result<()> {
+ let res = req(s, absolute_uri).await?;
+ let body = hyper::body::to_bytes(res.into_body())
+ .await
+ .expect("read body");
+ let body_text =
+ String::from_utf8(body.into_iter().collect()).expect("convert body to string");
+ assert!(
+ body_text.contains(expected),
+ "expected to contain {}, got {}",
+ expected,
+ body_text
+ );
+
+ Ok(())
+ }
+
async fn req(s: &SpinTestController, absolute_uri: &str) -> Result<Response<Body>> {
let c = Client::new();
let url = format!("http://{}{}", s.url, absolute_uri)
|
268ae0a0015ac5b971ddd11a4c336fc24b76e754
|
f94e397a7c5f83a753e3333ec3d9eed2a440261a
|
Spurious warning "skipping duplicate package `spinhelloworld`" when using Rust SDK
When you build Rust application that references the Rust SDK, you get a spurious warning:
```
warning: skipping duplicate package `spinhelloworld` found at `/home/ivan/.cargo/git/checkouts/spin-91500438ac5656d2/b316f47/examples/http-rust`
```
Looking at the directory, it seems Cargo checks out out the _entire_ Spin repo into the Cargo cache. So I _think_ the issue is that the repo contains several projects called `spinhelloworld`, and Cargo is looking at all of them as well as the SDK crate itself?
I don't think we used to see this, and I now see it on SDK revs going right back to 0.1.0, so I wonder if this is a new warning added to a recent version of Rust?
|
Warning doesn't happen in Rust 1.62.1 but does in 1.63.0.
Also affects programs that import Spin crates, it seems.
https://github.com/rust-lang/cargo/issues/10752
|
2022-10-26T18:12:56Z
|
fermyon__spin-862
|
fermyon/spin
|
0.6
|
diff --git a/examples/http-rust/Cargo.toml b/examples/http-rust/Cargo.toml
index 6a639603ea..5fe0d9383f 100644
--- a/examples/http-rust/Cargo.toml
+++ b/examples/http-rust/Cargo.toml
@@ -1,5 +1,5 @@
[package]
-name = "spinhelloworld"
+name = "http-rust"
version = "0.1.0"
edition = "2021"
@@ -18,4 +18,4 @@ spin-sdk = { path = "../../sdk/rust" }
# Crate that generates Rust Wasm bindings from a WebAssembly interface.
wit-bindgen-rust = { git = "https://github.com/bytecodealliance/wit-bindgen", rev = "cb871cfa1ee460b51eb1d144b175b9aab9c50aba" }
-[workspace]
\ No newline at end of file
+[workspace]
diff --git a/examples/http-rust/spin.toml b/examples/http-rust/spin.toml
index 222d41f1aa..2950d7db9a 100644
--- a/examples/http-rust/spin.toml
+++ b/examples/http-rust/spin.toml
@@ -7,7 +7,7 @@ version = "1.0.0"
[[component]]
id = "hello"
-source = "target/wasm32-wasi/release/spinhelloworld.wasm"
+source = "target/wasm32-wasi/release/http_rust.wasm"
description = "A simple component that returns hello."
[component.trigger]
route = "/hello"
| 862
|
[
"793"
] |
diff --git a/tests/http/simple-spin-rust/Cargo.lock b/tests/http/simple-spin-rust/Cargo.lock
index 84414d3142..e842ec65e4 100644
--- a/tests/http/simple-spin-rust/Cargo.lock
+++ b/tests/http/simple-spin-rust/Cargo.lock
@@ -126,6 +126,17 @@ dependencies = [
"proc-macro2",
]
+[[package]]
+name = "simple-spin-rust"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "bytes",
+ "http",
+ "spin-sdk",
+ "wit-bindgen-rust",
+]
+
[[package]]
name = "spin-macro"
version = "0.1.0"
@@ -153,17 +164,6 @@ dependencies = [
"wit-bindgen-rust",
]
-[[package]]
-name = "spinhelloworld"
-version = "0.1.0"
-dependencies = [
- "anyhow",
- "bytes",
- "http",
- "spin-sdk",
- "wit-bindgen-rust",
-]
-
[[package]]
name = "syn"
version = "1.0.85"
diff --git a/tests/http/simple-spin-rust/Cargo.toml b/tests/http/simple-spin-rust/Cargo.toml
index 4716bcba53..c5c200c129 100644
--- a/tests/http/simple-spin-rust/Cargo.toml
+++ b/tests/http/simple-spin-rust/Cargo.toml
@@ -1,5 +1,5 @@
[package]
-name = "spinhelloworld"
+name = "simple-spin-rust"
version = "0.1.0"
edition = "2021"
diff --git a/tests/http/simple-spin-rust/spin.toml b/tests/http/simple-spin-rust/spin.toml
index a807a2c443..160e7fd29f 100644
--- a/tests/http/simple-spin-rust/spin.toml
+++ b/tests/http/simple-spin-rust/spin.toml
@@ -10,7 +10,7 @@ object = { default = "teapot" }
[[component]]
id = "hello"
-source = "target/wasm32-wasi/release/spinhelloworld.wasm"
+source = "target/wasm32-wasi/release/simple_spin_rust.wasm"
files = [ { source = "assets", destination = "/" } ]
[component.trigger]
route = "/hello/..."
diff --git a/tests/integration.rs b/tests/integration.rs
index a7690d02b4..410d8179c5 100644
--- a/tests/integration.rs
+++ b/tests/integration.rs
@@ -244,7 +244,7 @@ mod integration_tests {
.join("target")
.join("wasm32-wasi")
.join("release")
- .join("spinhelloworld.wasm");
+ .join("simple_spin_rust.wasm");
let parcel_sha = file_digest_string(&wasm_path).expect("failed to get sha for parcel");
// start the Bindle registry.
|
268ae0a0015ac5b971ddd11a4c336fc24b76e754
|
eb50b54c51cb6290a592bdbfc4aa4882fdfe7191
|
Add redis command DEL to redis sdk rust
Add redis command DEL to redis sdk rust, this is a common used command in nearly all cases.
|
2022-10-18T15:22:30Z
|
fermyon__spin-828
|
fermyon/spin
|
0.5
|
diff --git a/Cargo.toml b/Cargo.toml
index ec8a8e960d..dcc1d9b6bc 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -75,6 +75,7 @@ vergen = { version = "7", default-features = false, features = [ "build", "git"
[features]
default = []
e2e-tests = []
+outbound-redis-tests = []
[workspace]
members = [
diff --git a/Makefile b/Makefile
index 32010a11c8..ea2d3a9257 100644
--- a/Makefile
+++ b/Makefile
@@ -9,7 +9,7 @@ build:
.PHONY: test
test: lint test-unit test-integration
-.PHONY: lint
+.PHONY: lint
lint:
cargo clippy --all-targets --all-features -- -D warnings
cargo fmt --all -- --check
@@ -30,9 +30,13 @@ test-integration:
.PHONY: test-e2e
test-e2e:
- RUST_LOG=$(LOG_LEVEL) cargo test --test integration --features e2e-tests --no-fail-fast -- integration_tests::test_dependencies --nocapture
+ RUST_LOG=$(LOG_LEVEL) cargo test --test integration --features e2e-tests --no-fail-fast -- integration_tests::test_dependencies --nocapture
RUST_LOG=$(LOG_LEVEL) cargo test --test integration --features e2e-tests --no-fail-fast -- --skip integration_tests::test_dependencies --nocapture
+.PHONY: test-outbound-redis
+test-outbound-redis:
+ RUST_LOG=$(LOG_LEVEL) cargo test --test integration --features outbound-redis-tests --no-fail-fast -- --nocapture
+
.PHONY: test-sdk-go
test-sdk-go:
$(MAKE) -C sdk/go test
diff --git a/build.rs b/build.rs
index 58f52f5f35..d719c382d3 100644
--- a/build.rs
+++ b/build.rs
@@ -8,6 +8,7 @@ use cargo_target_dep::build_target_dep;
const RUST_HTTP_INTEGRATION_TEST: &str = "tests/http/simple-spin-rust";
const RUST_HTTP_INTEGRATION_ENV_TEST: &str = "tests/http/headers-env-routes-test";
+const RUST_OUTBOUND_REDIS_INTEGRATION_TEST: &str = "tests/outbound-redis/http-rust-outbound-redis";
fn main() {
println!("cargo:rerun-if-changed=build.rs");
@@ -53,6 +54,7 @@ error: the `wasm32-wasi` target is not installed
cargo_build(RUST_HTTP_INTEGRATION_TEST);
cargo_build(RUST_HTTP_INTEGRATION_ENV_TEST);
+ cargo_build(RUST_OUTBOUND_REDIS_INTEGRATION_TEST);
let mut config = vergen::Config::default();
*config.git_mut().sha_kind_mut() = vergen::ShaKind::Short;
diff --git a/crates/abi-conformance/src/outbound_redis.rs b/crates/abi-conformance/src/outbound_redis.rs
index 4aa117f268..331eae388e 100644
--- a/crates/abi-conformance/src/outbound_redis.rs
+++ b/crates/abi-conformance/src/outbound_redis.rs
@@ -41,6 +41,14 @@ pub struct RedisReport {
/// function with the arguments \["127.0.0.1", "foo"\] and expect `ok(42)` as the result. The host will assert
/// that said function is called exactly once with the specified arguments.
pub incr: Result<(), String>,
+
+ /// Result of the Redis `DEL` test
+ ///
+ /// The guest module should expect a call according to [`super::InvocationStyle`] with \["outbound-redis-del",
+ /// "127.0.0.1", "foo"\] as arguments. The module should call the host-implemented `outbound-redis::del`
+ /// function with the arguments \["127.0.0.1", \["foo"\]\] and expect `ok(0)` as the result. The host will assert
+ /// that said function is called exactly once with the specified arguments.
+ pub del: Result<(), String>,
}
wit_bindgen_wasmtime::export!("../../wit/ephemeral/outbound-redis.wit");
@@ -51,6 +59,7 @@ pub(super) struct OutboundRedis {
set_set: HashSet<(String, String, Vec<u8>)>,
get_map: HashMap<(String, String), Vec<u8>>,
incr_map: HashMap<(String, String), i64>,
+ del_map: HashMap<(String, String), i64>,
}
impl outbound_redis::OutboundRedis for OutboundRedis {
@@ -93,6 +102,12 @@ impl outbound_redis::OutboundRedis for OutboundRedis {
.map(|value| value + 1)
.ok_or(outbound_redis::Error::Error)
}
+
+ fn del(&mut self, address: &str, keys: Vec<&str>) -> Result<i64, outbound_redis::Error> {
+ self.del_map
+ .remove(&(address.into(), format!("{keys:?}")))
+ .ok_or(outbound_redis::Error::Error)
+ }
}
pub(super) fn test(store: &mut Store<Context>, pre: &InstancePre<Context>) -> Result<RedisReport> {
@@ -183,5 +198,26 @@ pub(super) fn test(store: &mut Store<Context>, pre: &InstancePre<Context>) -> Re
},
)
},
+
+ del: {
+ store.data_mut().outbound_redis.del_map.insert(
+ ("127.0.0.1".into(), format!("{:?}", vec!["foo".to_owned()])),
+ 0,
+ );
+
+ super::run_command(
+ store,
+ pre,
+ &["outbound-redis-del", "127.0.0.1", "foo"],
+ |store| {
+ ensure!(
+ store.data().outbound_redis.del_map.is_empty(),
+ "expected module to call `outbound-redis::del` exactly once"
+ );
+
+ Ok(())
+ },
+ )
+ },
})
}
diff --git a/crates/outbound-redis/src/lib.rs b/crates/outbound-redis/src/lib.rs
index 4677a4188a..265df148ad 100644
--- a/crates/outbound-redis/src/lib.rs
+++ b/crates/outbound-redis/src/lib.rs
@@ -41,6 +41,12 @@ impl outbound_redis::OutboundRedis for OutboundRedis {
let value = conn.incr(key, 1).await.map_err(log_error)?;
Ok(value)
}
+
+ async fn del(&mut self, address: &str, keys: Vec<&str>) -> Result<i64, Error> {
+ let conn = self.get_conn(address).await.map_err(log_error)?;
+ let value = conn.del(keys).await.map_err(log_error)?;
+ Ok(value)
+ }
}
impl OutboundRedis {
diff --git a/examples/tinygo-outbound-redis/main.go b/examples/tinygo-outbound-redis/main.go
index e88180c9cf..315bfcf755 100644
--- a/examples/tinygo-outbound-redis/main.go
+++ b/examples/tinygo-outbound-redis/main.go
@@ -3,6 +3,7 @@ package main
import (
"net/http"
"os"
+ "strconv"
spin_http "github.com/fermyon/spin/sdk/go/http"
"github.com/fermyon/spin/sdk/go/redis"
@@ -41,6 +42,25 @@ func init() {
} else {
w.Write([]byte("mykey value was: "))
w.Write(payload)
+ w.Write([]byte("\n"))
+ }
+
+ // incr `spin-go-incr` by 1
+ if payload, err := redis.Incr(addr, "spin-go-incr"); err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ } else {
+ w.Write([]byte("spin-go-incr value: "))
+ w.Write([]byte(strconv.FormatInt(payload, 10)))
+ w.Write([]byte("\n"))
+ }
+
+ // delete `spin-go-incr` and `mykey`
+ if payload, err := redis.Del(addr, []string{"spin-go-incr", "mykey", "non-existing-key"}); err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ } else {
+ w.Write([]byte("deleted keys num: "))
+ w.Write([]byte(strconv.FormatInt(payload, 10)))
+ w.Write([]byte("\n"))
}
})
}
diff --git a/sdk/go/redis/internals.go b/sdk/go/redis/internals.go
index 13fd2d07b1..45e104453f 100644
--- a/sdk/go/redis/internals.go
+++ b/sdk/go/redis/internals.go
@@ -66,6 +66,45 @@ func set(addr, key string, payload []byte) error {
return toErr(err)
}
+func incr(addr, key string) (int64, error) {
+ caddr := redisStr(addr)
+ ckey := redisStr(key)
+
+ var cpayload C.int64_t
+
+ defer func() {
+ C.outbound_redis_string_free(&caddr)
+ C.outbound_redis_string_free(&ckey)
+ }()
+
+ err := C.outbound_redis_incr(&caddr, &ckey, &cpayload)
+ return int64(cpayload), toErr(err)
+}
+
+func del(addr string, keys []string) (int64, error) {
+ caddr := redisStr(addr)
+ ckeys := redisListStr(keys)
+
+ var cpayload C.int64_t
+
+ defer func() {
+ C.outbound_redis_string_free(&caddr)
+ C.outbound_redis_list_string_free(&ckeys)
+ }()
+
+ err := C.outbound_redis_del(&caddr, &ckeys, &cpayload)
+ return int64(cpayload), toErr(err)
+}
+
+func redisListStr(xs []string) C.outbound_redis_list_string_t {
+ var cxs []C.outbound_redis_string_t
+
+ for i := 0; i < len(xs); i++ {
+ cxs = append(cxs, redisStr(xs[i]))
+ }
+ return C.outbound_redis_list_string_t{ptr: &cxs[0], len: C.size_t(len(cxs))}
+}
+
func redisStr(x string) C.outbound_redis_string_t {
return C.outbound_redis_string_t{ptr: C.CString(x), len: C.size_t(len(x))}
}
diff --git a/sdk/go/redis/outbound-redis.c b/sdk/go/redis/outbound-redis.c
index 35617ba245..5496750072 100644
--- a/sdk/go/redis/outbound-redis.c
+++ b/sdk/go/redis/outbound-redis.c
@@ -56,9 +56,22 @@ typedef struct {
outbound_redis_error_t err;
} val;
} outbound_redis_expected_payload_error_t;
+typedef struct {
+ bool is_err;
+ union {
+ int64_t ok;
+ outbound_redis_error_t err;
+ } val;
+} outbound_redis_expected_s64_error_t;
+void outbound_redis_list_string_free(outbound_redis_list_string_t *ptr) {
+ for (size_t i = 0; i < ptr->len; i++) {
+ outbound_redis_string_free(&ptr->ptr[i]);
+ }
+ canonical_abi_free(ptr->ptr, ptr->len * 8, 4);
+}
-__attribute__((aligned(4)))
-static uint8_t RET_AREA[12];
+__attribute__((aligned(8)))
+static uint8_t RET_AREA[16];
__attribute__((import_module("outbound-redis"), import_name("publish")))
void __wasm_import_outbound_redis_publish(int32_t, int32_t, int32_t, int32_t, int32_t, int32_t, int32_t);
outbound_redis_error_t outbound_redis_publish(outbound_redis_string_t *address, outbound_redis_string_t *channel, outbound_redis_payload_t *payload) {
@@ -123,3 +136,47 @@ outbound_redis_error_t outbound_redis_set(outbound_redis_string_t *address, outb
}
}return expected.is_err ? expected.val.err : -1;
}
+__attribute__((import_module("outbound-redis"), import_name("incr")))
+void __wasm_import_outbound_redis_incr(int32_t, int32_t, int32_t, int32_t, int32_t);
+outbound_redis_error_t outbound_redis_incr(outbound_redis_string_t *address, outbound_redis_string_t *key, int64_t *ret0) {
+ int32_t ptr = (int32_t) &RET_AREA;
+ __wasm_import_outbound_redis_incr((int32_t) (*address).ptr, (int32_t) (*address).len, (int32_t) (*key).ptr, (int32_t) (*key).len, ptr);
+ outbound_redis_expected_s64_error_t expected;
+ switch ((int32_t) (*((uint8_t*) (ptr + 0)))) {
+ case 0: {
+ expected.is_err = false;
+
+ expected.val.ok = *((int64_t*) (ptr + 8));
+ break;
+ }
+ case 1: {
+ expected.is_err = true;
+
+ expected.val.err = (int32_t) (*((uint8_t*) (ptr + 8)));
+ break;
+ }
+ }*ret0 = expected.val.ok;
+ return expected.is_err ? expected.val.err : -1;
+}
+__attribute__((import_module("outbound-redis"), import_name("del")))
+void __wasm_import_outbound_redis_del(int32_t, int32_t, int32_t, int32_t, int32_t);
+outbound_redis_error_t outbound_redis_del(outbound_redis_string_t *address, outbound_redis_list_string_t *keys, int64_t *ret0) {
+ int32_t ptr = (int32_t) &RET_AREA;
+ __wasm_import_outbound_redis_del((int32_t) (*address).ptr, (int32_t) (*address).len, (int32_t) (*keys).ptr, (int32_t) (*keys).len, ptr);
+ outbound_redis_expected_s64_error_t expected;
+ switch ((int32_t) (*((uint8_t*) (ptr + 0)))) {
+ case 0: {
+ expected.is_err = false;
+
+ expected.val.ok = *((int64_t*) (ptr + 8));
+ break;
+ }
+ case 1: {
+ expected.is_err = true;
+
+ expected.val.err = (int32_t) (*((uint8_t*) (ptr + 8)));
+ break;
+ }
+ }*ret0 = expected.val.ok;
+ return expected.is_err ? expected.val.err : -1;
+}
diff --git a/sdk/go/redis/outbound-redis.h b/sdk/go/redis/outbound-redis.h
index 9c86140db5..44a0542bc1 100644
--- a/sdk/go/redis/outbound-redis.h
+++ b/sdk/go/redis/outbound-redis.h
@@ -24,9 +24,16 @@ extern "C"
size_t len;
} outbound_redis_payload_t;
void outbound_redis_payload_free(outbound_redis_payload_t *ptr);
+ typedef struct {
+ outbound_redis_string_t *ptr;
+ size_t len;
+ } outbound_redis_list_string_t;
+ void outbound_redis_list_string_free(outbound_redis_list_string_t *ptr);
outbound_redis_error_t outbound_redis_publish(outbound_redis_string_t *address, outbound_redis_string_t *channel, outbound_redis_payload_t *payload);
outbound_redis_error_t outbound_redis_get(outbound_redis_string_t *address, outbound_redis_string_t *key, outbound_redis_payload_t *ret0);
outbound_redis_error_t outbound_redis_set(outbound_redis_string_t *address, outbound_redis_string_t *key, outbound_redis_payload_t *value);
+ outbound_redis_error_t outbound_redis_incr(outbound_redis_string_t *address, outbound_redis_string_t *key, int64_t *ret0);
+ outbound_redis_error_t outbound_redis_del(outbound_redis_string_t *address, outbound_redis_list_string_t *keys, int64_t *ret0);
#ifdef __cplusplus
}
#endif
diff --git a/sdk/go/redis/redis.go b/sdk/go/redis/redis.go
index c6e9a67364..cf26fa15be 100644
--- a/sdk/go/redis/redis.go
+++ b/sdk/go/redis/redis.go
@@ -36,3 +36,16 @@ func Get(addr, key string) ([]byte, error) {
func Set(addr, key string, payload []byte) error {
return set(addr, key, payload)
}
+
+// Increments the number stored at key by one. If the key does not exist,
+// it is set to 0 before performing the operation. An error is returned if
+// the key contains a value of the wrong type or contains a string that can not
+// be represented as integer.
+func Incr(addr, key string) (int64, error) {
+ return incr(addr, key)
+}
+
+// Removes the specified keys. A key is ignored if it does not exist.
+func Del(addr string, keys []string) (int64, error) {
+ return del(addr, keys)
+}
diff --git a/wit/ephemeral/outbound-redis.wit b/wit/ephemeral/outbound-redis.wit
index d13afa0313..a11792f1fc 100644
--- a/wit/ephemeral/outbound-redis.wit
+++ b/wit/ephemeral/outbound-redis.wit
@@ -12,3 +12,6 @@ set: func(address: string, key: string, value: payload) -> expected<unit, error>
// Increments the number stored at key by one. If the key does not exist, it is set to 0 before performing the operation.
// An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer.
incr: func(address: string, key: string) -> expected<s64, error>
+
+// Removes the specified keys. A key is ignored if it does not exist.
+del: func(address: string, keys: list<string>) -> expected<s64, error>
| 828
|
[
"801"
] |
diff --git a/tests/integration.rs b/tests/integration.rs
index 55b2d2bb0d..a7690d02b4 100644
--- a/tests/integration.rs
+++ b/tests/integration.rs
@@ -602,6 +602,30 @@ mod integration_tests {
}
}
+ #[cfg(feature = "outbound-redis-tests")]
+ mod outbound_pg_tests {
+ use super::*;
+
+ const RUST_OUTBOUND_REDIS_INTEGRATION_TEST: &str =
+ "tests/outbound-redis/http-rust-outbound-redis";
+
+ #[tokio::test]
+ async fn test_outbound_redis_rust_local() -> Result<()> {
+ let s = SpinTestController::with_manifest(
+ &format!(
+ "{}/{}",
+ RUST_OUTBOUND_REDIS_INTEGRATION_TEST, DEFAULT_MANIFEST_LOCATION
+ ),
+ &[],
+ None,
+ )
+ .await?;
+
+ assert_status(&s, "/test", 204).await?;
+ Ok(())
+ }
+ }
+
#[tokio::test]
async fn test_simple_rust_local() -> Result<()> {
let s = SpinTestController::with_manifest(
diff --git a/tests/outbound-redis/http-rust-outbound-redis/.cargo/config.toml b/tests/outbound-redis/http-rust-outbound-redis/.cargo/config.toml
new file mode 100644
index 0000000000..6b77899cb3
--- /dev/null
+++ b/tests/outbound-redis/http-rust-outbound-redis/.cargo/config.toml
@@ -0,0 +1,2 @@
+[build]
+target = "wasm32-wasi"
diff --git a/tests/outbound-redis/http-rust-outbound-redis/Cargo.toml b/tests/outbound-redis/http-rust-outbound-redis/Cargo.toml
new file mode 100644
index 0000000000..cd720e12c7
--- /dev/null
+++ b/tests/outbound-redis/http-rust-outbound-redis/Cargo.toml
@@ -0,0 +1,21 @@
+[package]
+name = "http-rust-outbound-redis"
+version = "0.1.0"
+edition = "2021"
+
+[lib]
+crate-type = [ "cdylib" ]
+
+[dependencies]
+# Useful crate to handle errors.
+anyhow = "1"
+# Crate to simplify working with bytes.
+bytes = "1"
+# General-purpose crate with common HTTP types.
+http = "0.2"
+# The Spin SDK.
+spin-sdk = { path = "../../../sdk/rust" }
+# Crate that generates Rust Wasm bindings from a WebAssembly interface.
+wit-bindgen-rust = { git = "https://github.com/bytecodealliance/wit-bindgen", rev = "cb871cfa1ee460b51eb1d144b175b9aab9c50aba" }
+
+[workspace]
diff --git a/tests/outbound-redis/http-rust-outbound-redis/spin.toml b/tests/outbound-redis/http-rust-outbound-redis/spin.toml
new file mode 100644
index 0000000000..3f48e01b39
--- /dev/null
+++ b/tests/outbound-redis/http-rust-outbound-redis/spin.toml
@@ -0,0 +1,15 @@
+spin_version = "1"
+authors = ["Fermyon Engineering <engineering@fermyon.com>"]
+name = "rust-outbound-redis-example"
+trigger = { type = "http", base = "/" }
+version = "0.1.0"
+
+[[component]]
+environment = { REDIS_ADDRESS = "redis://127.0.0.1:6379" }
+id = "outbound-redis"
+source = "target/wasm32-wasi/release/http_rust_outbound_redis.wasm"
+[component.trigger]
+route = "/test"
+[component.build]
+command = "cargo build --target wasm32-wasi --release"
+
diff --git a/tests/outbound-redis/http-rust-outbound-redis/src/lib.rs b/tests/outbound-redis/http-rust-outbound-redis/src/lib.rs
new file mode 100644
index 0000000000..44b61b7792
--- /dev/null
+++ b/tests/outbound-redis/http-rust-outbound-redis/src/lib.rs
@@ -0,0 +1,37 @@
+use anyhow::{anyhow, Result};
+use spin_sdk::{
+ http::{Request, Response},
+ http_component, redis,
+};
+
+const REDIS_ADDRESS_ENV: &str = "REDIS_ADDRESS";
+
+#[http_component]
+fn test(_req: Request) -> Result<Response> {
+ let address = std::env::var(REDIS_ADDRESS_ENV)?;
+
+ redis::set(&address, "spin-example-get-set", b"Eureka!")
+ .map_err(|_| anyhow!("Error executing Redis set command"))?;
+
+ let payload = redis::get(&address, "spin-example-get-set")
+ .map_err(|_| anyhow!("Error querying Redis"))?;
+
+ assert_eq!(std::str::from_utf8(&payload).unwrap(), "Eureka!");
+
+ redis::set(&address, "spin-example-incr", b"0")
+ .map_err(|_| anyhow!("Error querying Redis set command"))?;
+
+ let int_value = redis::incr(&address, "spin-example-incr")
+ .map_err(|_| anyhow!("Error executing Redis incr command"))?;
+
+ assert_eq!(int_value, 1);
+
+ let keys = vec!["spin-example-get-set", "spin-example-incr"];
+
+ let del_keys = redis::del(&address, &keys)
+ .map_err(|_| anyhow!("Error executing Redis incr command"))?;
+
+ assert_eq!(del_keys, 2);
+
+ Ok(http::Response::builder().status(204).body(None)?)
+}
|
eb50b54c51cb6290a592bdbfc4aa4882fdfe7191
|
|
646ff10807ea049a4630ad56c84ea3faddaf3b22
|
Better error messaging for trigger execution failures
I was running a Spin application without an available Redis instance on the configured endpoint for the trigger:
`trigger = { type = "redis", address = "redis://localhost:6379" }`
The error message produced on a macOS was:
```
2022-08-21T09:37:21.146153Z ERROR spin_trigger::cli: Trigger executor failed: Connection refused (os error 61)
Error: Connection refused (os error 61)
Error: exit status: 1
```
It would be great to add a bit more context to the error, e.g. what trigger and endpoint etc.
|
2022-10-02T17:59:40Z
|
fermyon__spin-800
|
fermyon/spin
|
0.5
|
diff --git a/crates/http/benches/baseline.rs b/crates/http/benches/baseline.rs
index 00f6250743..f7ae27b639 100644
--- a/crates/http/benches/baseline.rs
+++ b/crates/http/benches/baseline.rs
@@ -7,7 +7,7 @@ use futures::future::join_all;
use http::uri::Scheme;
use http::Request;
use spin_http::HttpTrigger;
-use spin_testing::{assert_http_response_success, TestConfig};
+use spin_testing::{assert_http_response_success, HttpTestConfig};
use tokio::runtime::Runtime;
use tokio::task;
@@ -26,20 +26,20 @@ fn bench_startup(c: &mut Criterion) {
let mut group = c.benchmark_group("startup");
group.bench_function("spin-executor", |b| {
b.to_async(&async_runtime).iter(|| async {
- let trigger = TestConfig::default()
+ let trigger = HttpTestConfig::default()
.test_program("spin-http-benchmark.wasm")
.http_spin_trigger("/")
- .build_http_trigger()
+ .build_trigger()
.await;
run_concurrent_requests(Arc::new(trigger), 0, 1).await;
});
});
group.bench_function("spin-wagi-executor", |b| {
b.to_async(&async_runtime).iter(|| async {
- let trigger = TestConfig::default()
+ let trigger = HttpTestConfig::default()
.test_program("wagi-benchmark.wasm")
.http_wagi_trigger("/", Default::default())
- .build_http_trigger()
+ .build_trigger()
.await;
run_concurrent_requests(Arc::new(trigger), 0, 1).await;
});
@@ -50,12 +50,12 @@ fn bench_startup(c: &mut Criterion) {
fn bench_spin_concurrency_minimal(c: &mut Criterion) {
let async_runtime = Runtime::new().unwrap();
- let spin_trigger = Arc::new(
+ let spin_trigger: Arc<HttpTrigger> = Arc::new(
async_runtime.block_on(
- TestConfig::default()
+ HttpTestConfig::default()
.test_program("spin-http-benchmark.wasm")
.http_spin_trigger("/")
- .build_http_trigger(),
+ .build_trigger(),
),
);
@@ -86,12 +86,12 @@ fn bench_spin_concurrency_minimal(c: &mut Criterion) {
fn bench_wagi_concurrency_minimal(c: &mut Criterion) {
let async_runtime = Runtime::new().unwrap();
- let wagi_trigger = Arc::new(
+ let wagi_trigger: Arc<HttpTrigger> = Arc::new(
async_runtime.block_on(
- TestConfig::default()
+ HttpTestConfig::default()
.test_program("wagi-benchmark.wasm")
.http_wagi_trigger("/", Default::default())
- .build_http_trigger(),
+ .build_trigger(),
),
);
diff --git a/crates/http/src/lib.rs b/crates/http/src/lib.rs
index dd1111ea6a..8200394fe4 100644
--- a/crates/http/src/lib.rs
+++ b/crates/http/src/lib.rs
@@ -38,9 +38,6 @@ wit_bindgen_wasmtime::import!({paths: ["../../wit/ephemeral/spin-http.wit"], asy
pub(crate) type RuntimeData = spin_http::SpinHttpData;
pub(crate) type Store = spin_core::Store<RuntimeData>;
-/// App metadata key for storing HTTP trigger "base" value
-pub const HTTP_BASE_METADATA_KEY: &str = "http_base";
-
/// The Spin HTTP trigger.
pub struct HttpTrigger {
engine: TriggerAppEngine<Self>,
@@ -107,6 +104,13 @@ pub enum HttpExecutorType {
Wagi(WagiTriggerConfig),
}
+#[derive(Clone, Debug, Default, Deserialize, Serialize)]
+#[serde(deny_unknown_fields)]
+struct TriggerMetadata {
+ r#type: String,
+ base: String,
+}
+
#[async_trait]
impl TriggerExecutor for HttpTrigger {
const TRIGGER_TYPE: &'static str = "http";
@@ -117,9 +121,8 @@ impl TriggerExecutor for HttpTrigger {
fn new(engine: TriggerAppEngine<Self>) -> Result<Self> {
let base = engine
.app()
- .get_metadata(HTTP_BASE_METADATA_KEY)?
- .unwrap_or("/")
- .to_string();
+ .require_metadata::<TriggerMetadata>("trigger")?
+ .base;
let component_routes = engine
.trigger_configs()
@@ -533,10 +536,10 @@ mod tests {
#[tokio::test]
async fn test_spin_http() -> Result<()> {
- let trigger = spin_testing::TestConfig::default()
+ let trigger: HttpTrigger = spin_testing::HttpTestConfig::default()
.test_program("rust-http-test.wasm")
.http_spin_trigger("/test")
- .build_http_trigger()
+ .build_trigger()
.await;
let body = Body::from("Fermyon".as_bytes().to_vec());
@@ -558,10 +561,10 @@ mod tests {
#[tokio::test]
async fn test_wagi_http() -> Result<()> {
- let trigger = spin_testing::TestConfig::default()
+ let trigger: HttpTrigger = spin_testing::HttpTestConfig::default()
.test_program("wagi-test.wasm")
.http_wagi_trigger("/test", Default::default())
- .build_http_trigger()
+ .build_trigger()
.await;
let body = Body::from("Fermyon".as_bytes().to_vec());
diff --git a/crates/redis/src/lib.rs b/crates/redis/src/lib.rs
index 23f58a3bf4..d735450cbc 100644
--- a/crates/redis/src/lib.rs
+++ b/crates/redis/src/lib.rs
@@ -4,7 +4,7 @@ mod spin;
use std::collections::HashMap;
-use anyhow::{Context, Result};
+use anyhow::{anyhow, Context, Result};
use async_trait::async_trait;
use futures::StreamExt;
use redis::{Client, ConnectionLike};
@@ -40,6 +40,13 @@ pub struct RedisTriggerConfig {
pub executor: IgnoredAny,
}
+#[derive(Clone, Debug, Default, Deserialize, Serialize)]
+#[serde(deny_unknown_fields)]
+struct TriggerMetadata {
+ r#type: String,
+ address: String,
+}
+
#[async_trait]
impl TriggerExecutor for RedisTrigger {
const TRIGGER_TYPE: &'static str = "redis";
@@ -50,8 +57,8 @@ impl TriggerExecutor for RedisTrigger {
fn new(engine: TriggerAppEngine<Self>) -> Result<Self> {
let address = engine
.app()
- .require_metadata("redis_address")
- .context("Failed to configure Redis trigger")?;
+ .require_metadata::<TriggerMetadata>("trigger")?
+ .address;
let channel_components = engine
.trigger_configs()
@@ -71,7 +78,11 @@ impl TriggerExecutor for RedisTrigger {
tracing::info!("Connecting to Redis server at {}", address);
let mut client = Client::open(address.to_string())?;
- let mut pubsub = client.get_async_connection().await?.into_pubsub();
+ let mut pubsub = client
+ .get_async_connection()
+ .await
+ .with_context(|| anyhow!("Redis trigger failed to connect to {}", address))?
+ .into_pubsub();
// Subscribe to channels
for (channel, component) in self.channel_components.iter() {
diff --git a/crates/trigger-new/src/lib.rs b/crates/trigger-new/src/lib.rs
deleted file mode 100644
index 979fc66bbc..0000000000
--- a/crates/trigger-new/src/lib.rs
+++ /dev/null
@@ -1,282 +0,0 @@
-pub mod cli;
-mod loader;
-pub mod locked;
-mod stdio;
-
-use std::{
- collections::HashMap,
- marker::PhantomData,
- path::{Path, PathBuf},
-};
-
-use anyhow::{Context, Result};
-pub use async_trait::async_trait;
-use serde::de::DeserializeOwned;
-
-use spin_app::{App, AppLoader, AppTrigger, Loader, OwnedApp};
-use spin_config::{provider::env::EnvProvider, Provider};
-use spin_core::{Config, Engine, EngineBuilder, Instance, InstancePre, Store, StoreBuilder};
-
-use stdio::{ComponentStdioWriter, FollowComponents};
-
-const SPIN_HOME: &str = ".spin";
-const SPIN_CONFIG_ENV_PREFIX: &str = "SPIN_APP";
-
-#[async_trait]
-pub trait TriggerExecutor: Sized {
- const TRIGGER_TYPE: &'static str;
- type RuntimeData: Default + Send + Sync + 'static;
- type TriggerConfig;
- type RunConfig;
-
- /// Create a new trigger executor.
- fn new(engine: TriggerAppEngine<Self>) -> Result<Self>;
-
- /// Run the trigger executor.
- async fn run(self, config: Self::RunConfig) -> Result<()>;
-
- /// Make changes to the ExecutionContext using the given Builder.
- fn configure_engine(_builder: &mut EngineBuilder<Self::RuntimeData>) -> Result<()> {
- Ok(())
- }
-}
-
-pub struct TriggerExecutorBuilder<Executor: TriggerExecutor> {
- loader: AppLoader,
- config: Config,
- log_dir: Option<PathBuf>,
- follow_components: FollowComponents,
- disable_default_host_components: bool,
- _phantom: PhantomData<Executor>,
-}
-
-impl<Executor: TriggerExecutor> TriggerExecutorBuilder<Executor> {
- /// Create a new TriggerExecutorBuilder with the given Application.
- pub fn new(loader: impl Loader + Send + Sync + 'static) -> Self {
- Self {
- loader: AppLoader::new(loader),
- config: Default::default(),
- log_dir: None,
- follow_components: Default::default(),
- disable_default_host_components: false,
- _phantom: PhantomData,
- }
- }
-
- /// !!!Warning!!! Using a custom Wasmtime Config is entirely unsupported;
- /// many configurations are likely to cause errors or unexpected behavior.
- #[doc(hidden)]
- pub fn wasmtime_config_mut(&mut self) -> &mut spin_core::wasmtime::Config {
- self.config.wasmtime_config()
- }
-
- pub fn log_dir(&mut self, log_dir: PathBuf) -> &mut Self {
- self.log_dir = Some(log_dir);
- self
- }
-
- pub fn follow_components(&mut self, follow_components: FollowComponents) -> &mut Self {
- self.follow_components = follow_components;
- self
- }
-
- pub fn disable_default_host_components(&mut self) -> &mut Self {
- self.disable_default_host_components = true;
- self
- }
-
- pub async fn build(mut self, app_uri: String) -> Result<Executor>
- where
- Executor::TriggerConfig: DeserializeOwned,
- {
- let engine = {
- let mut builder = Engine::builder(&self.config)?;
-
- if !self.disable_default_host_components {
- builder.add_host_component(outbound_redis::OutboundRedis::default())?;
- builder.add_host_component(outbound_pg::OutboundPg::default())?;
- self.loader.add_dynamic_host_component(
- &mut builder,
- outbound_http::OutboundHttpComponent,
- )?;
- self.loader.add_dynamic_host_component(
- &mut builder,
- spin_config::ConfigHostComponent::new(self.default_config_providers(&app_uri)),
- )?;
- }
-
- Executor::configure_engine(&mut builder)?;
- builder.build()
- };
-
- let app = self.loader.load_owned_app(app_uri).await?;
- let app_name = app.require_metadata("name")?;
-
- let log_dir = {
- let sanitized_app = sanitize_filename::sanitize(&app_name);
- let parent_dir = match dirs::home_dir() {
- Some(home) => home.join(SPIN_HOME),
- None => PathBuf::new(), // "./"
- };
- parent_dir.join(sanitized_app).join("logs")
- };
- std::fs::create_dir_all(&log_dir)?;
-
- // Run trigger executor
- Executor::new(
- TriggerAppEngine::new(engine, app_name, app, log_dir, self.follow_components).await?,
- )
- }
-
- pub fn default_config_providers(&self, app_uri: &str) -> Vec<Box<dyn Provider>> {
- // EnvProvider
- let dotenv_path = app_uri
- .strip_prefix("file://")
- .and_then(|path| Path::new(path).parent())
- .unwrap_or_else(|| Path::new("."))
- .join(".env");
- vec![Box::new(EnvProvider::new(
- SPIN_CONFIG_ENV_PREFIX,
- Some(dotenv_path),
- ))]
- }
-}
-
-/// Execution context for a TriggerExecutor executing a particular App.
-pub struct TriggerAppEngine<Executor: TriggerExecutor> {
- /// Engine to be used with this executor.
- pub engine: Engine<Executor::RuntimeData>,
- /// Name of the app for e.g. logging.
- pub app_name: String,
- // An owned wrapper of the App.
- app: OwnedApp,
- // Log directory
- log_dir: PathBuf,
- // Component stdio follow config
- follow_components: FollowComponents,
- // Trigger configs for this trigger type, with order matching `app.triggers_with_type(Executor::TRIGGER_TYPE)`
- trigger_configs: Vec<Executor::TriggerConfig>,
- // Map of {Component ID -> InstancePre} for each component.
- component_instance_pres: HashMap<String, InstancePre<Executor::RuntimeData>>,
-}
-
-impl<Executor: TriggerExecutor> TriggerAppEngine<Executor> {
- /// Returns a new TriggerAppEngine. May return an error if trigger config validation or
- /// component pre-instantiation fails.
- pub async fn new(
- engine: Engine<Executor::RuntimeData>,
- app_name: String,
- app: OwnedApp,
- log_dir: PathBuf,
- follow_components: FollowComponents,
- ) -> Result<Self>
- where
- <Executor as TriggerExecutor>::TriggerConfig: DeserializeOwned,
- {
- let trigger_configs = app
- .triggers_with_type(Executor::TRIGGER_TYPE)
- .map(|trigger| {
- trigger.typed_config().with_context(|| {
- format!("invalid trigger configuration for {:?}", trigger.id())
- })
- })
- .collect::<Result<_>>()?;
-
- let mut component_instance_pres = HashMap::default();
- for component in app.components() {
- let module = component.load_module(&engine).await?;
- let instance_pre = engine.instantiate_pre(&module)?;
- component_instance_pres.insert(component.id().to_string(), instance_pre);
- }
-
- Ok(Self {
- engine,
- app_name,
- app,
- log_dir,
- follow_components,
- trigger_configs,
- component_instance_pres,
- })
- }
-
- /// Returns a reference to the App.
- pub fn app(&self) -> &App {
- &self.app
- }
-
- /// Returns AppTriggers and typed TriggerConfigs for this executor type.
- pub fn trigger_configs(&self) -> impl Iterator<Item = (AppTrigger, &Executor::TriggerConfig)> {
- self.app
- .triggers_with_type(Executor::TRIGGER_TYPE)
- .zip(&self.trigger_configs)
- }
-
- /// Returns a new StoreBuilder for the given component ID.
- pub fn store_builder(&self, component_id: &str) -> Result<StoreBuilder> {
- let mut builder = self.engine.store_builder();
-
- // Set up stdio logging
- builder.stdout_pipe(self.component_stdio_writer(component_id, "stdout")?);
- builder.stderr_pipe(self.component_stdio_writer(component_id, "stderr")?);
-
- Ok(builder)
- }
-
- fn component_stdio_writer(
- &self,
- component_id: &str,
- log_suffix: &str,
- ) -> Result<ComponentStdioWriter> {
- let sanitized_component_id = sanitize_filename::sanitize(component_id);
- // e.g.
- let log_path = self
- .log_dir
- .join(format!("{sanitized_component_id}_{log_suffix}.txt"));
- let follow = self.follow_components.should_follow(component_id);
- ComponentStdioWriter::new(&log_path, follow)
- .with_context(|| format!("Failed to open log file {log_path:?}"))
- }
-
- /// Returns a new Store and Instance for the given component ID.
- pub async fn prepare_instance(
- &self,
- component_id: &str,
- ) -> Result<(Instance, Store<Executor::RuntimeData>)> {
- let store_builder = self.store_builder(component_id)?;
- self.prepare_instance_with_store(component_id, store_builder)
- .await
- }
-
- /// Returns a new Store and Instance for the given component ID and StoreBuilder.
- pub async fn prepare_instance_with_store(
- &self,
- component_id: &str,
- mut store_builder: StoreBuilder,
- ) -> Result<(Instance, Store<Executor::RuntimeData>)> {
- // Look up AppComponent
- let component = self.app.get_component(component_id).with_context(|| {
- format!(
- "app {:?} has no component {:?}",
- self.app_name, component_id
- )
- })?;
-
- // Build Store
- component.apply_store_config(&mut store_builder).await?;
- let mut store = store_builder.build()?;
-
- // Instantiate
- let instance = self.component_instance_pres[component_id]
- .instantiate_async(&mut store)
- .await
- .with_context(|| {
- format!(
- "app {:?} component {:?} instantiation failed",
- self.app_name, component_id
- )
- })?;
-
- Ok((instance, store))
- }
-}
diff --git a/crates/trigger/src/cli.rs b/crates/trigger/src/cli.rs
index 51db7aad17..9baf062c9f 100644
--- a/crates/trigger/src/cli.rs
+++ b/crates/trigger/src/cli.rs
@@ -122,7 +122,7 @@ where
Ok(())
}
Ok(Err(err)) => {
- tracing::error!("Trigger executor failed: {:?}", err);
+ tracing::error!("Trigger executor failed");
Err(err)
}
Err(_aborted) => {
diff --git a/crates/trigger/src/locked.rs b/crates/trigger/src/locked.rs
index d57b709da0..dc875aaccf 100644
--- a/crates/trigger/src/locked.rs
+++ b/crates/trigger/src/locked.rs
@@ -92,9 +92,8 @@ impl LockedAppBuilder {
let trigger_type;
match (app_trigger, config) {
- (ApplicationTrigger::Http(HttpTriggerConfiguration{base}), TriggerConfig::Http(HttpConfig{ route, executor })) => {
+ (ApplicationTrigger::Http(HttpTriggerConfiguration{base: _}), TriggerConfig::Http(HttpConfig{ route, executor })) => {
trigger_type = "http";
- let route = base.trim_end_matches('/').to_string() + &route;
builder.string("route", route);
builder.serializable("executor", executor)?;
},
| 800
|
[
"704"
] |
diff --git a/crates/redis/src/tests.rs b/crates/redis/src/tests.rs
index 951ae655d3..29620f7cf4 100644
--- a/crates/redis/src/tests.rs
+++ b/crates/redis/src/tests.rs
@@ -1,7 +1,7 @@
use super::*;
use anyhow::Result;
use redis::{Msg, Value};
-use spin_testing::{tokio, TestConfig};
+use spin_testing::{tokio, RedisTestConfig};
fn create_trigger_event(channel: &str, payload: &str) -> redis::Msg {
Msg::from_value(&redis::Value::Bulk(vec![
@@ -14,10 +14,9 @@ fn create_trigger_event(channel: &str, payload: &str) -> redis::Msg {
#[tokio::test]
async fn test_pubsub() -> Result<()> {
- let trigger: RedisTrigger = TestConfig::default()
+ let trigger: RedisTrigger = RedisTestConfig::default()
.test_program("redis-rust.wasm")
- .redis_trigger("messages")
- .build_trigger()
+ .build_trigger("messages")
.await;
let msg = create_trigger_event("messages", "hello");
diff --git a/crates/testing/src/lib.rs b/crates/testing/src/lib.rs
index a040c34456..91fd951f18 100644
--- a/crates/testing/src/lib.rs
+++ b/crates/testing/src/lib.rs
@@ -16,7 +16,7 @@ use spin_app::{
AppComponent, Loader,
};
use spin_core::{Module, StoreBuilder};
-use spin_http::{HttpExecutorType, HttpTrigger, HttpTriggerConfig, WagiTriggerConfig};
+use spin_http::{HttpExecutorType, HttpTriggerConfig, WagiTriggerConfig};
use spin_trigger::{TriggerExecutor, TriggerExecutorBuilder};
pub use tokio;
@@ -37,13 +37,18 @@ macro_rules! from_json {
}
#[derive(Default)]
-pub struct TestConfig {
+pub struct HttpTestConfig {
module_path: Option<PathBuf>,
http_trigger_config: HttpTriggerConfig,
+}
+
+#[derive(Default)]
+pub struct RedisTestConfig {
+ module_path: Option<PathBuf>,
redis_channel: String,
}
-impl TestConfig {
+impl HttpTestConfig {
pub fn module_path(&mut self, path: impl Into<PathBuf>) -> &mut Self {
init_tracing();
self.module_path = Some(path.into());
@@ -80,9 +85,22 @@ impl TestConfig {
self
}
- pub fn redis_trigger(&mut self, channel: impl Into<String>) -> &mut Self {
- self.redis_channel = channel.into();
- self
+ pub fn build_loader(&self) -> impl Loader {
+ init_tracing();
+ TestLoader {
+ app: self.build_locked_app(),
+ module_path: self.module_path.clone().expect("module path to be set"),
+ }
+ }
+
+ pub async fn build_trigger<Executor: TriggerExecutor>(&self) -> Executor
+ where
+ Executor::TriggerConfig: DeserializeOwned,
+ {
+ TriggerExecutorBuilder::new(self.build_loader())
+ .build(TEST_APP_URI.to_string())
+ .await
+ .unwrap()
}
pub fn build_locked_app(&self) -> LockedApp {
@@ -100,7 +118,7 @@ impl TestConfig {
"trigger_config": self.http_trigger_config,
},
]);
- let metadata = from_json!({"name": "test-app", "redis_address": "test-redis-host"});
+ let metadata = from_json!({"name": "test-app", "trigger": {"type": "http", "base": "/"}});
let variables = Default::default();
LockedApp {
spin_lock_version: spin_app::locked::FixedVersion,
@@ -110,6 +128,22 @@ impl TestConfig {
variables,
}
}
+}
+
+impl RedisTestConfig {
+ pub fn module_path(&mut self, path: impl Into<PathBuf>) -> &mut Self {
+ init_tracing();
+ self.module_path = Some(path.into());
+ self
+ }
+
+ pub fn test_program(&mut self, name: impl AsRef<Path>) -> &mut Self {
+ self.module_path(
+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+ .join("../../target/test-programs")
+ .join(name),
+ )
+ }
pub fn build_loader(&self) -> impl Loader {
init_tracing();
@@ -119,18 +153,42 @@ impl TestConfig {
}
}
- pub async fn build_trigger<Executor: TriggerExecutor>(&self) -> Executor
+ pub async fn build_trigger<Executor: TriggerExecutor>(&mut self, channel: &str) -> Executor
where
Executor::TriggerConfig: DeserializeOwned,
{
+ self.redis_channel = channel.into();
+
TriggerExecutorBuilder::new(self.build_loader())
.build(TEST_APP_URI.to_string())
.await
.unwrap()
}
- pub async fn build_http_trigger(&self) -> HttpTrigger {
- self.build_trigger().await
+ pub fn build_locked_app(&self) -> LockedApp {
+ let components = from_json!([{
+ "id": "test-component",
+ "source": {
+ "content_type": "application/wasm",
+ "digest": "test-source",
+ },
+ }]);
+ let triggers = from_json!([
+ {
+ "id": "trigger--test-app",
+ "trigger_type": "redis",
+ "trigger_config": {"channel": self.redis_channel, "component": "test-component"},
+ },
+ ]);
+ let metadata = from_json!({"name": "test-app", "trigger": {"address": "test-redis-host", "type": "redis"}});
+ let variables = Default::default();
+ LockedApp {
+ spin_lock_version: spin_app::locked::FixedVersion,
+ components,
+ triggers,
+ metadata,
+ variables,
+ }
}
}
|
eb50b54c51cb6290a592bdbfc4aa4882fdfe7191
|
|
0e3b3d43659f1c881f07b0aca54678ed66a7aa79
|
Don't allow variables containing the '.' character
This is firmly in the "machiavellian user could shoot self in foot" category - I only encountered it because I was exploring the config code and wanted to understand the tree traversal stuff. Priority is "wash your dog first."
If you create a variable with a "." character in it, it passes validation, but is never passed to the provider to resolve, so can't be overridden.
Keys in the `[component.config]` section _do_ undergo validation for the "." character; it's only variables which don't.
|
2022-09-08T17:42:55Z
|
fermyon__spin-750
|
fermyon/spin
|
0.5
|
diff --git a/Cargo.lock b/Cargo.lock
index 7f1463987c..acb3aea92e 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3351,7 +3351,10 @@ name = "spin-config"
version = "0.2.0"
dependencies = [
"anyhow",
+ "async-trait",
"serde",
+ "spin-engine",
+ "spin-manifest",
"thiserror",
"tokio",
"toml",
@@ -3367,7 +3370,6 @@ dependencies = [
"cap-std 0.24.4",
"dirs 4.0.0",
"sanitize-filename",
- "spin-config",
"spin-manifest",
"tempfile",
"tokio",
@@ -3474,7 +3476,6 @@ dependencies = [
"anyhow",
"indexmap",
"serde",
- "spin-config",
"thiserror",
"url",
]
diff --git a/crates/config/Cargo.toml b/crates/config/Cargo.toml
index a5f8405d64..a5e6211fa7 100644
--- a/crates/config/Cargo.toml
+++ b/crates/config/Cargo.toml
@@ -6,7 +6,10 @@ authors = [ "Fermyon Engineering <engineering@fermyon.com>" ]
[dependencies]
anyhow = "1.0"
+async-trait = "0.1"
serde = { version = "1.0", features = [ "derive" ] }
+spin-engine = { path = "../engine" }
+spin-manifest = { path = "../manifest" }
thiserror = "1"
tokio = { version = "1", features = [ "rt-multi-thread" ] }
diff --git a/crates/config/src/host_component.rs b/crates/config/src/host_component.rs
index 9d7f234211..1ac0a94e72 100644
--- a/crates/config/src/host_component.rs
+++ b/crates/config/src/host_component.rs
@@ -1,39 +1,56 @@
use std::sync::Arc;
-use crate::{Error, Key, Resolver, TreePath};
+use spin_engine::host_component::HostComponent;
+use spin_manifest::CoreComponent;
+use wit_bindgen_wasmtime::async_trait;
+
+use crate::{Error, Key, Resolver};
mod wit {
wit_bindgen_wasmtime::export!({paths: ["../../wit/ephemeral/spin-config.wit"], async: *});
}
-pub use wit::spin_config::add_to_linker;
-use wit_bindgen_wasmtime::async_trait;
-/// A component configuration interface implementation.
-pub struct ComponentConfig {
- component_root: TreePath,
+pub struct ConfigHostComponent {
resolver: Arc<Resolver>,
}
-impl ComponentConfig {
- pub fn new(component_id: impl Into<String>, resolver: Arc<Resolver>) -> crate::Result<Self> {
- let component_root = TreePath::new(component_id).or_else(|_| {
- // Temporary mitigation for https://github.com/fermyon/spin/issues/337
- TreePath::new("invalid.path.issue_337")
- })?;
- Ok(Self {
- component_root,
- resolver,
+impl ConfigHostComponent {
+ pub fn new(resolver: Resolver) -> Self {
+ Self {
+ resolver: Arc::new(resolver),
+ }
+ }
+}
+
+impl HostComponent for ConfigHostComponent {
+ type State = ComponentConfig;
+
+ fn add_to_linker<T: Send>(
+ linker: &mut wit_bindgen_wasmtime::wasmtime::Linker<spin_engine::RuntimeContext<T>>,
+ state_handle: spin_engine::host_component::HostComponentsStateHandle<Self::State>,
+ ) -> anyhow::Result<()> {
+ wit::spin_config::add_to_linker(linker, move |ctx| state_handle.get_mut(ctx))
+ }
+
+ fn build_state(&self, component: &CoreComponent) -> anyhow::Result<Self::State> {
+ Ok(ComponentConfig {
+ component_id: component.id.clone(),
+ resolver: self.resolver.clone(),
})
}
}
+/// A component configuration interface implementation.
+pub struct ComponentConfig {
+ component_id: String,
+ resolver: Arc<Resolver>,
+}
+
#[async_trait]
impl wit::spin_config::SpinConfig for ComponentConfig {
async fn get_config(&mut self, key: &str) -> Result<String, wit::spin_config::Error> {
let key = Key::new(key)?;
- let path = &self.component_root + key;
- // TODO(lann): Make resolve async
- tokio::task::block_in_place(|| Ok(self.resolver.resolve(&path)?))
+ Ok(self.resolver.resolve(&self.component_id, key).await?)
}
}
diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs
index 3df750684a..16a4faa541 100644
--- a/crates/config/src/lib.rs
+++ b/crates/config/src/lib.rs
@@ -2,127 +2,126 @@ pub mod host_component;
pub mod provider;
mod template;
-mod tree;
-use std::fmt::Debug;
+use std::{borrow::Cow, collections::HashMap, fmt::Debug};
-pub use provider::Provider;
-pub use tree::{Tree, TreePath};
+pub use async_trait::async_trait;
+pub use provider::Provider;
+use spin_manifest::Variable;
use template::{Part, Template};
-/// A config resolution error.
-#[derive(Debug, thiserror::Error)]
-pub enum Error {
- /// Invalid config key.
- #[error("invalid config key: {0}")]
- InvalidKey(String),
-
- /// Invalid config path.
- #[error("invalid config path: {0}")]
- InvalidPath(String),
-
- /// Invalid config schema.
- #[error("invalid config schema: {0}")]
- InvalidSchema(String),
-
- /// Invalid config template.
- #[error("invalid config template: {0}")]
- InvalidTemplate(String),
-
- /// Config provider error.
- #[error("provider error: {0:?}")]
- Provider(anyhow::Error),
-
- /// Unknown config path.
- #[error("unknown config path: {0}")]
- UnknownPath(String),
-}
-
type Result<T> = std::result::Result<T, Error>;
/// A configuration resolver.
#[derive(Debug, Default)]
pub struct Resolver {
- tree: Tree,
+ // variable key -> variable
+ variables: HashMap<String, Variable>,
+ // component ID -> config key -> config value template
+ components_configs: HashMap<String, HashMap<String, Template>>,
providers: Vec<Box<dyn Provider>>,
}
impl Resolver {
/// Creates a Resolver for the given Tree.
- pub fn new(tree: Tree) -> Result<Self> {
+ pub fn new(variables: impl IntoIterator<Item = (String, Variable)>) -> Result<Self> {
+ let variables: HashMap<_, _> = variables.into_iter().collect();
+ // Validate keys so that we can rely on them during resolution
+ variables.keys().try_for_each(|key| Key::validate(key))?;
Ok(Self {
- tree,
- providers: vec![],
+ variables,
+ components_configs: Default::default(),
+ providers: Default::default(),
})
}
+ /// Adds component configuration values to the Resolver.
+ pub fn add_component_config(
+ &mut self,
+ component_id: impl Into<String>,
+ config: impl IntoIterator<Item = (String, String)>,
+ ) -> Result<()> {
+ let component_id = component_id.into();
+ let templates = config
+ .into_iter()
+ .map(|(key, val)| {
+ // Validate config keys so that we can rely on them during resolution
+ Key::validate(&key)?;
+ let template = self.validate_template(val)?;
+ Ok((key, template))
+ })
+ .collect::<Result<_>>()?;
+
+ self.components_configs.insert(component_id, templates);
+
+ Ok(())
+ }
+
/// Adds a config Provider to the Resolver.
pub fn add_provider(&mut self, provider: impl Provider + 'static) {
self.providers.push(Box::new(provider));
}
/// Resolves a config value for the given path.
- pub fn resolve(&self, path: &TreePath) -> Result<String> {
- self.resolve_path(path, 0)
+ pub async fn resolve(&self, component_id: &str, key: Key<'_>) -> Result<String> {
+ let configs = self.components_configs.get(component_id).ok_or_else(|| {
+ Error::UnknownPath(format!("no config for component {component_id:?}"))
+ })?;
+
+ let key = key.as_ref();
+ let template = configs
+ .get(key)
+ .ok_or_else(|| Error::UnknownPath(format!("no config for {component_id:?}.{key:?}")))?;
+
+ self.resolve_template(template).await
}
- // Simple protection against infinite recursion
- const RECURSION_LIMIT: usize = 100;
-
- // TODO(lann): make this non-recursive and/or "flatten" templates
- fn resolve_path(&self, path: &TreePath, depth: usize) -> Result<String> {
- let depth = depth + 1;
- if depth > Self::RECURSION_LIMIT {
- return Err(Error::InvalidTemplate(format!(
- "hit recursion limit at path: {}",
- path
- )));
+ async fn resolve_template(&self, template: &Template) -> Result<String> {
+ let mut resolved_parts: Vec<Cow<str>> = Vec::with_capacity(template.parts().len());
+ for part in template.parts() {
+ resolved_parts.push(match part {
+ Part::Lit(lit) => lit.as_ref().into(),
+ Part::Expr(var) => self.resolve_variable(var).await?.into(),
+ });
}
- let slot = self.tree.get(path)?;
- // If we're resolving top-level config we are ready to query provider(s).
- if path.size() == 1 {
- let key = path.keys().next().unwrap();
- for provider in &self.providers {
- if let Some(value) = provider.get(&key).map_err(Error::Provider)? {
- return Ok(value);
- }
+ Ok(resolved_parts.concat())
+ }
+
+ async fn resolve_variable(&self, key: &str) -> Result<String> {
+ let var = self
+ .variables
+ .get(key)
+ // This should have been caught by validate_template
+ .ok_or_else(|| Error::InvalidKey(key.to_string()))?;
+
+ for provider in &self.providers {
+ if let Some(value) = provider.get(&Key(key)).await.map_err(Error::Provider)? {
+ return Ok(value);
}
}
- // Resolve default template
- if let Some(template) = &slot.default {
- self.resolve_template(path, template, depth)
- } else {
- Err(Error::InvalidPath(format!(
- "missing value at required path: {}",
- path
- )))
- }
- }
- fn resolve_template(
- &self,
- path: &TreePath,
- template: &Template,
- depth: usize,
- ) -> Result<String> {
- template.parts().try_fold(String::new(), |value, part| {
- Ok(match part {
- Part::Lit(lit) => value + lit,
- Part::Expr(expr) => {
- let expr_path = if expr.starts_with('.') {
- path.resolve_relative(expr)?
- } else {
- TreePath::new(expr.to_string())?
- };
- value + &self.resolve_path(&expr_path, depth)?
- }
- })
+ var.default.clone().ok_or_else(|| {
+ Error::Provider(anyhow::anyhow!(
+ "no provider resolved required variable {key:?}"
+ ))
})
}
+
+ fn validate_template(&self, template: String) -> Result<Template> {
+ let template = Template::new(template)?;
+ // Validate template variables are valid
+ template.parts().try_for_each(|part| match part {
+ Part::Expr(var) if !self.variables.contains_key(var.as_ref()) => {
+ Err(Error::InvalidTemplate(format!("unknown variable {var:?}")))
+ }
+ _ => Ok(()),
+ })?;
+ Ok(template)
+ }
}
-/// A config key.
+/// A config key
#[derive(Debug, PartialEq, Eq)]
pub struct Key<'a>(&'a str);
@@ -156,7 +155,7 @@ impl<'a> Key<'a> {
Ok(())
}
}
- .map_err(Error::InvalidKey)
+ .map_err(|reason| Error::InvalidKey(format!("{key:?} {reason}")))
}
}
@@ -166,81 +165,99 @@ impl<'a> AsRef<str> for Key<'a> {
}
}
-#[cfg(test)]
-mod tests {
- use std::collections::HashMap;
+/// A config resolution error.
+#[derive(Debug, thiserror::Error)]
+pub enum Error {
+ /// Invalid config key.
+ #[error("invalid config key: {0}")]
+ InvalidKey(String),
+
+ /// Invalid config path.
+ #[error("invalid config path: {0}")]
+ InvalidPath(String),
+
+ /// Invalid config schema.
+ #[error("invalid config schema: {0}")]
+ InvalidSchema(String),
+
+ /// Invalid config template.
+ #[error("invalid config template: {0}")]
+ InvalidTemplate(String),
+
+ /// Config provider error.
+ #[error("provider error: {0:?}")]
+ Provider(anyhow::Error),
- use toml::toml;
+ /// Unknown config path.
+ #[error("unknown config path: {0}")]
+ UnknownPath(String),
+}
+#[cfg(test)]
+mod tests {
use super::*;
- #[test]
- fn resolver_resolve_defaults() {
- let mut tree: Tree = toml! {
- top_level = { default = "top" }
- top_ref = { default = "{{ top_level }}+{{ top_level }}" }
- top_required = { required = true }
- }
- .try_into()
- .unwrap();
- tree.merge_defaults(
- &TreePath::new("child").unwrap(),
- toml! {
- subtree_key = "sub"
- top_ref = "{{ top_level }}"
- recurse_ref = "{{ top_ref }}"
- own_ref = "{{ .subtree_key }}"
- }
- .try_into::<HashMap<String, String>>()
- .unwrap(),
- )
- .unwrap();
- tree.merge_defaults(
- &TreePath::new("child.grandchild").unwrap(),
- toml! {
- top_ref = "{{ top_level }}"
- parent_ref = "{{ ..subtree_key }}"
- mixed_ref = "{{ top_level }}/{{ ..recurse_ref }}"
- }
- .try_into::<HashMap<String, String>>()
- .unwrap(),
- )
- .unwrap();
+ #[derive(Debug)]
+ struct TestProvider;
- let resolver = Resolver::new(tree).unwrap();
- for (path, expected) in [
- ("top_level", "top"),
- ("top_ref", "top+top"),
- ("child.subtree_key", "sub"),
- ("child.top_ref", "top"),
- ("child.recurse_ref", "top+top"),
- ("child.own_ref", "sub"),
- ("child.grandchild.top_ref", "top"),
- ("child.grandchild.parent_ref", "sub"),
- ("child.grandchild.mixed_ref", "top/top+top"),
- ] {
- let path = TreePath::new(path).unwrap();
- let value = resolver.resolve(&path).unwrap();
- assert_eq!(value, expected, "mismatch at {:?}", path);
+ #[async_trait]
+ impl Provider for TestProvider {
+ async fn get(&self, key: &Key) -> anyhow::Result<Option<String>> {
+ match key.as_ref() {
+ "required" => Ok(Some("provider-value".to_string())),
+ "broken" => anyhow::bail!("broken"),
+ _ => Ok(None),
+ }
}
}
- #[test]
- fn resolver_recursion_limit() {
- let resolver = Resolver::new(
- toml! {
- x = { default = "{{y}}" }
- y = { default = "{{x}}" }
- }
- .try_into()
- .unwrap(),
- )
+ async fn test_resolve(config_template: &str) -> Result<String> {
+ let mut resolver = Resolver::new([
+ (
+ "required".into(),
+ Variable {
+ default: None,
+ secret: false,
+ },
+ ),
+ (
+ "default".into(),
+ Variable {
+ default: Some("default-value".into()),
+ secret: false,
+ },
+ ),
+ ])
.unwrap();
- let path = "x".to_string().try_into().unwrap();
- assert!(matches!(
- resolver.resolve(&path),
- Err(Error::InvalidTemplate(_))
- ));
+ resolver
+ .add_component_config(
+ "test-component",
+ [("test_key".into(), config_template.into())],
+ )
+ .unwrap();
+ resolver.add_provider(TestProvider);
+ resolver.resolve("test-component", Key("test_key")).await
+ }
+
+ #[tokio::test]
+ async fn resolve_static() {
+ assert_eq!(test_resolve("static-value").await.unwrap(), "static-value");
+ }
+
+ #[tokio::test]
+ async fn resolve_variable_default() {
+ assert_eq!(
+ test_resolve("prefix-{{ default }}-suffix").await.unwrap(),
+ "prefix-default-value-suffix"
+ );
+ }
+
+ #[tokio::test]
+ async fn resolve_variable_provider() {
+ assert_eq!(
+ test_resolve("prefix-{{ required }}-suffix").await.unwrap(),
+ "prefix-provider-value-suffix"
+ );
}
#[test]
@@ -252,7 +269,7 @@ mod tests {
#[test]
fn keys_bad() {
- for key in ["", "aX", "1bc", "_x", "x_", "a__b", "x-y"] {
+ for key in ["", "aX", "1bc", "_x", "x.y", "x_", "a__b", "x-y"] {
Key::new(key).expect_err(key);
}
}
diff --git a/crates/config/src/provider.rs b/crates/config/src/provider.rs
index b4a0c50777..9f3799937a 100644
--- a/crates/config/src/provider.rs
+++ b/crates/config/src/provider.rs
@@ -1,12 +1,15 @@
use std::fmt::Debug;
+use async_trait::async_trait;
+
use crate::Key;
/// Environment variable based provider.
pub mod env;
/// A config provider.
+#[async_trait]
pub trait Provider: Debug + Send + Sync {
/// Returns the value at the given config path, if it exists.
- fn get(&self, key: &Key) -> anyhow::Result<Option<String>>;
+ async fn get(&self, key: &Key) -> anyhow::Result<Option<String>>;
}
diff --git a/crates/config/src/provider/env.rs b/crates/config/src/provider/env.rs
index b4dff88b13..ed2dbfc2f2 100644
--- a/crates/config/src/provider/env.rs
+++ b/crates/config/src/provider/env.rs
@@ -1,6 +1,7 @@
use std::collections::HashMap;
use anyhow::Context;
+use async_trait::async_trait;
use crate::{Key, Provider};
@@ -21,6 +22,18 @@ impl EnvProvider {
envs,
}
}
+
+ fn get_sync(&self, key: &Key) -> anyhow::Result<Option<String>> {
+ let env_key = format!("{}_{}", &self.prefix, key.as_ref().to_ascii_uppercase());
+ match std::env::var(&env_key) {
+ Err(std::env::VarError::NotPresent) => {
+ Ok(self.envs.get(&env_key).map(|value| value.to_string()))
+ }
+ other => other
+ .map(Some)
+ .with_context(|| format!("failed to resolve env var {}", &env_key)),
+ }
+ }
}
impl Default for EnvProvider {
@@ -32,21 +45,10 @@ impl Default for EnvProvider {
}
}
+#[async_trait]
impl Provider for EnvProvider {
- fn get(&self, key: &Key) -> anyhow::Result<Option<String>> {
- let env_key = format!("{}_{}", &self.prefix, key.as_ref().to_ascii_uppercase());
- match std::env::var(&env_key) {
- Err(std::env::VarError::NotPresent) => {
- if let Some(value) = self.envs.get(&env_key) {
- return Ok(Some(value.to_string()));
- }
-
- Ok(None)
- }
- other => other
- .map(Some)
- .with_context(|| format!("failed to resolve env var {}", &env_key)),
- }
+ async fn get(&self, key: &Key) -> anyhow::Result<Option<String>> {
+ self.get_sync(key)
}
}
@@ -65,7 +67,7 @@ mod test {
);
assert_eq!(
EnvProvider::new("TESTING_SPIN", envs.clone())
- .get(&key1)
+ .get_sync(&key1)
.unwrap(),
Some("val".to_string())
);
@@ -77,7 +79,7 @@ mod test {
);
assert_eq!(
EnvProvider::new("TESTING_SPIN", envs.clone())
- .get(&key2)
+ .get_sync(&key2)
.unwrap(),
Some("dotenv_val".to_string())
);
@@ -86,6 +88,6 @@ mod test {
#[test]
fn provider_get_missing() {
let key = Key::new("please_do_not_ever_set_this_during_tests").unwrap();
- assert_eq!(EnvProvider::default().get(&key).unwrap(), None);
+ assert_eq!(EnvProvider::default().get_sync(&key).unwrap(), None);
}
}
diff --git a/crates/config/src/template.rs b/crates/config/src/template.rs
index bc9e9ef0ea..783834bf2d 100644
--- a/crates/config/src/template.rs
+++ b/crates/config/src/template.rs
@@ -40,7 +40,7 @@ impl Template {
Ok(Template(parts))
}
- pub(crate) fn parts(&self) -> impl Iterator<Item = &Part> {
+ pub(crate) fn parts(&self) -> std::slice::Iter<Part> {
self.0.iter()
}
}
diff --git a/crates/config/src/tree.rs b/crates/config/src/tree.rs
deleted file mode 100644
index d39019f25b..0000000000
--- a/crates/config/src/tree.rs
+++ /dev/null
@@ -1,312 +0,0 @@
-use std::collections::BTreeMap;
-use std::collections::HashMap;
-
-use serde::Deserialize;
-use serde::Serialize;
-
-use crate::template::Template;
-use crate::{Error, Key, Result};
-
-/// A configuration tree.
-#[derive(Clone, Debug, Default, Deserialize, Serialize)]
-pub struct Tree(BTreeMap<TreePath, Slot>);
-
-impl Tree {
- pub(crate) fn get(&self, path: &TreePath) -> Result<&Slot> {
- self.0
- .get(path)
- .ok_or_else(|| Error::InvalidPath(format!("no slot at path: {}", path)))
- }
-
- pub fn merge(&mut self, base: &TreePath, other: Tree) -> Result<()> {
- for (subpath, slot) in other.0.into_iter() {
- self.merge_slot(base + &subpath, slot)?;
- }
- Ok(())
- }
-
- pub fn merge_defaults(
- &mut self,
- base: &TreePath,
- defaults: impl IntoIterator<Item = (String, String)>,
- ) -> Result<()> {
- for (ref key, default) in defaults {
- let path = base + Key::new(key)?;
- let slot = Slot::from_default(default)?;
- self.merge_slot(path, slot)?;
- }
- Ok(())
- }
-
- fn merge_slot(&mut self, path: TreePath, slot: Slot) -> Result<()> {
- if self.0.contains_key(&path) {
- return Err(Error::InvalidPath(format!(
- "duplicate key at path: {}",
- path
- )));
- }
- self.0.insert(path, slot);
- Ok(())
- }
-}
-
-/// A path into a config tree.
-#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Deserialize, Serialize)]
-#[serde(try_from = "String")]
-pub struct TreePath(String);
-
-impl TreePath {
- /// Creates a ConfigPath from a String.
- pub fn new(path: impl Into<String>) -> Result<Self> {
- let path = path.into();
- if path.is_empty() {
- return Err(Error::InvalidPath("empty".to_string()));
- }
- path.split('.').try_for_each(Key::validate)?;
- Ok(TreePath(path))
- }
-
- /// Returns the number of keys in this Path.
- pub fn size(&self) -> usize {
- self.0.matches('.').count() + 1
- }
-
- /// Resolves the given relative path (starting with at least one '.').
- pub fn resolve_relative(&self, rel: &str) -> Result<Self> {
- if rel.is_empty() {
- return Err(Error::InvalidPath("rel may not be empty".to_string()));
- }
- let key = rel.trim_start_matches('.');
- let dots = rel.len() - key.len();
- if dots == 0 {
- return Err(Error::InvalidPath("rel must start with a '.'".to_string()));
- }
- // Remove last `dots` components from path.
- let path = match self.0.rmatch_indices('.').chain([(0, "")]).nth(dots - 1) {
- Some((0, _)) => key.to_string(),
- Some((idx, _)) => format!("{}.{}", &self.0[..idx], key),
- None => {
- return Err(Error::InvalidPath(format!(
- "rel has too many dots relative to base path {}",
- self
- )))
- }
- };
- Ok(Self(path))
- }
-
- /// Produces an iterator over the keys of the path.
- pub fn keys(&self) -> impl Iterator<Item = Key<'_>> {
- self.0.split('.').map(Key)
- }
-}
-
-impl AsRef<str> for TreePath {
- fn as_ref(&self) -> &str {
- self.0.as_ref()
- }
-}
-
-impl std::fmt::Display for TreePath {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(f, "{}", self.as_ref())
- }
-}
-
-impl std::ops::Add for &TreePath {
- type Output = TreePath;
- fn add(self, rhs: &TreePath) -> Self::Output {
- TreePath(format!("{}.{}", self.0, rhs.0))
- }
-}
-
-impl std::ops::Add<Key<'_>> for &TreePath {
- type Output = TreePath;
- fn add(self, key: Key) -> Self::Output {
- TreePath(format!("{}.{}", self.0, key.0))
- }
-}
-
-impl TryFrom<String> for TreePath {
- type Error = Error;
- fn try_from(value: String) -> Result<Self> {
- Self::new(value)
- }
-}
-
-#[derive(Clone, Default, PartialEq, Deserialize, Serialize)]
-#[serde(into = "RawSlot", try_from = "RawSlot")]
-pub(crate) struct Slot {
- pub secret: bool,
- pub default: Option<Template>,
-}
-
-impl Slot {
- fn from_default(default: impl Into<Box<str>>) -> Result<Self> {
- Ok(Self {
- default: Some(Template::new(default)?),
- ..Default::default()
- })
- }
-}
-
-impl TryFrom<RawSlot> for Slot {
- type Error = Error;
-
- fn try_from(raw: RawSlot) -> Result<Self> {
- let default = match raw.default {
- Some(default) => Some(Template::new(default)?),
- None if !raw.required => {
- return Err(Error::InvalidSchema(
- "slot must have a default if not required".to_string(),
- ));
- }
- None => None,
- };
- Ok(Self {
- default,
- secret: raw.secret,
- })
- }
-}
-
-impl From<Slot> for RawSlot {
- fn from(slot: Slot) -> Self {
- RawSlot {
- default: slot.default.as_ref().map(|tmpl| tmpl.to_string()),
- required: slot.default.is_none(),
- secret: slot.secret,
- }
- }
-}
-
-impl std::fmt::Debug for Slot {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- let default = match self.default.as_ref() {
- Some(_) if self.secret => Some("<SECRET>".to_string()),
- not_secret => Some(format!("{:?}", not_secret)),
- };
- f.debug_struct("Slot")
- .field("secret", &self.secret)
- .field("default", &default)
- .finish()
- }
-}
-
-#[derive(Debug, Deserialize, PartialEq, Eq)]
-pub struct RawSection(pub HashMap<String, RawSlot>);
-
-#[derive(Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
-#[serde(default)]
-pub struct RawSlot {
- pub default: Option<String>,
- pub required: bool,
- pub secret: bool,
-}
-
-#[cfg(test)]
-mod tests {
- use toml::toml;
-
- use super::*;
-
- #[test]
- fn paths_good() {
- for path in ["x", "x.y", "a.b_c.d", "f.a1.x_1"] {
- TreePath::new(path).expect(path);
- }
- }
-
- #[test]
- fn paths_bad() {
- for path in ["", "_x", "a._x", "a..b"] {
- TreePath::new(path).expect_err(path);
- }
- }
-
- #[test]
- fn path_keys() {
- assert_eq!(
- TreePath::new("a").unwrap().keys().collect::<Vec<_>>(),
- &[Key("a")]
- );
- assert_eq!(
- TreePath::new("a.b_c.d").unwrap().keys().collect::<Vec<_>>(),
- &[Key("a"), Key("b_c"), Key("d")]
- );
- }
-
- #[test]
- fn path_resolve_relative() {
- let path = TreePath::new("a.b.c").unwrap();
- for (rel, expected) in [(".x", "a.b.x"), ("..x", "a.x"), ("...x", "x")] {
- assert_eq!(path.resolve_relative(rel).unwrap().as_ref(), expected);
- }
- }
-
- #[test]
- fn path_resolve_relative_bad() {
- let path = TreePath::new("a.b.c").unwrap();
- for rel in ["", "x", "....x"] {
- path.resolve_relative(rel).expect_err(rel);
- }
- }
-
- #[test]
- fn path_display() {
- let path = TreePath::new("a.b.c").unwrap();
- assert_eq!(format!("{}", path), "a.b.c");
- }
-
- #[test]
- fn slot_debug_secret() {
- let mut slot = Slot {
- default: Some(Template::new("sesame").unwrap()),
- ..Default::default()
- };
- assert!(format!("{:?}", slot).contains("sesame"));
-
- slot.secret = true;
- assert!(!format!("{:?}", slot).contains("sesame"));
- assert!(format!("{:?}", slot).contains("<SECRET>"));
- }
-
- #[test]
- fn tree_from_toml() {
- let tree: Tree = toml! {
- required_key = { required = true }
- secret_default = { default = "TOP-SECRET", secret = true }
- }
- .try_into()
- .unwrap();
-
- for (key, expected_slot) in [
- (
- "required_key",
- Slot {
- default: None,
- ..Default::default()
- },
- ),
- (
- "secret_default",
- Slot {
- default: Some(Template::new("TOP-SECRET").unwrap()),
- secret: true,
- },
- ),
- ] {
- let path = TreePath::new(key).expect(key);
- assert_eq!(tree.get(&path).expect(key), &expected_slot);
- }
- }
-
- #[test]
- fn invalid_slot() {
- toml! {
- not_required_or_default = { secret = true }
- }
- .try_into::<Tree>()
- .expect_err("should fail");
- }
-}
diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml
index 2353f1c77c..362c2b95a2 100644
--- a/crates/engine/Cargo.toml
+++ b/crates/engine/Cargo.toml
@@ -9,10 +9,9 @@ anyhow = "1.0.44"
bytes = "1.1.0"
dirs = "4.0"
sanitize-filename = "0.3.0"
-spin-config = { path = "../config" }
spin-manifest = { path = "../manifest" }
tempfile = "3.3.0"
-tokio = { version = "1.10.0", features = [ "fs" ] }
+tokio = { version = "1.10.0", features = [ "full" ] }
tracing = { version = "0.1", features = [ "log" ] }
tracing-futures = "0.2"
wasi-cap-std-sync = "0.39.1"
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 4f9b31b320..ffbd803a10 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -12,7 +12,6 @@ use std::{collections::HashMap, io::Write, path::PathBuf, sync::Arc};
use anyhow::{bail, Context, Result};
use host_component::{HostComponent, HostComponents, HostComponentsState};
use io::{FollowComponents, OutputBuffers, RedirectPipes};
-use spin_config::{host_component::ComponentConfig, Resolver};
use spin_manifest::{CoreComponent, DirectoryMount, ModuleSource};
use tokio::{
task::JoinHandle,
@@ -36,8 +35,6 @@ pub struct ExecutionContextConfiguration {
pub log_dir: Option<PathBuf>,
/// Component log following configuration.
pub follow_components: FollowComponents,
- /// Application configuration resolver.
- pub config_resolver: Option<Arc<Resolver>>,
}
/// Top-level runtime context data to be passed to a component.
@@ -45,8 +42,6 @@ pub struct ExecutionContextConfiguration {
pub struct RuntimeContext<T> {
/// WASI context data.
pub wasi: Option<WasiCtx>,
- /// Component configuration.
- pub component_config: Option<spin_config::host_component::ComponentConfig>,
/// Host components state.
pub host_components_state: HostComponentsState,
/// Generic runtime data that can be configured by specialized engines.
@@ -106,20 +101,17 @@ impl<T: Default + Send + 'static> Builder<T> {
})
}
+ /// Returns the current ExecutionContextConfiguration.
+ pub fn config(&self) -> &ExecutionContextConfiguration {
+ &self.config
+ }
+
/// Configures the WASI linker imports for the current execution context.
pub fn link_wasi(&mut self) -> Result<&mut Self> {
wasmtime_wasi::add_to_linker(&mut self.linker, |ctx| ctx.wasi.as_mut().unwrap())?;
Ok(self)
}
- /// Configures the application configuration interface.
- pub fn link_config(&mut self) -> Result<&mut Self> {
- spin_config::host_component::add_to_linker(&mut self.linker, |ctx| {
- ctx.component_config.as_mut().unwrap()
- })?;
- Ok(self)
- }
-
/// Adds a HostComponent to the execution context.
pub fn add_host_component(
&mut self,
@@ -182,7 +174,7 @@ impl<T: Default + Send + 'static> Builder<T> {
/// Configures default host interface implementations.
pub fn link_defaults(&mut self) -> Result<&mut Self> {
- self.link_wasi()?.link_config()
+ self.link_wasi()
}
/// Builds a new default instance of the execution context.
@@ -324,11 +316,6 @@ impl<T: Default + Send> ExecutionContext<T> {
wasi_ctx.preopened_dir(Dir::open_ambient_dir(host, ambient_authority())?, guest)?;
}
- if let Some(resolver) = &self.config.config_resolver {
- ctx.component_config =
- Some(ComponentConfig::new(&component.core.id, resolver.clone())?);
- }
-
ctx.host_components_state = self.host_components.build_state(&component.core)?;
ctx.wasi = Some(wasi_ctx.build());
diff --git a/crates/loader/src/bindle/config.rs b/crates/loader/src/bindle/config.rs
index 0d86c1ae77..baff95f998 100644
--- a/crates/loader/src/bindle/config.rs
+++ b/crates/loader/src/bindle/config.rs
@@ -1,6 +1,8 @@
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
+use crate::common::RawVariable;
+
/// Application configuration file format.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
@@ -9,8 +11,8 @@ pub struct RawAppManifest {
pub trigger: spin_manifest::ApplicationTrigger,
/// Application-specific configuration schema.
- #[serde(rename = "variables")]
- pub config: Option<spin_config::Tree>,
+ #[serde(default, skip_serializing_if = "HashMap::is_empty")]
+ pub variables: HashMap<String, RawVariable>,
/// Configuration for the application components.
#[serde(rename = "component")]
diff --git a/crates/loader/src/bindle/mod.rs b/crates/loader/src/bindle/mod.rs
index 74e8a5fdc6..39842a8a53 100644
--- a/crates/loader/src/bindle/mod.rs
+++ b/crates/loader/src/bindle/mod.rs
@@ -25,7 +25,7 @@ use spin_manifest::{
Application, ApplicationInformation, ApplicationOrigin, CoreComponent, ModuleSource,
SpinVersion, WasmConfig,
};
-use std::{path::Path, sync::Arc};
+use std::path::Path;
use tracing::log;
pub(crate) use utils::BindleReader;
pub use utils::SPIN_MANIFEST_MEDIA_TYPE;
@@ -64,23 +64,12 @@ async fn prepare(
.with_context(|| anyhow!("Failed to load invoice '{}' from '{}'", id, url))?;
// Then, reconstruct the application manifest from the parcels.
- let mut raw: RawAppManifest =
+ let raw: RawAppManifest =
toml::from_slice(&reader.get_parcel(&find_manifest(&invoice)?).await?)?;
log::trace!("Recreated manifest from bindle: {:?}", raw);
validate_raw_app_manifest(&raw)?;
- let mut config_root = raw.config.take().unwrap_or_default();
- for component in &mut raw.components {
- if let Some(config) = component.config.take() {
- let path = component.id.clone().try_into().with_context(|| {
- format!("component ID {:?} not a valid config path", component.id)
- })?;
- config_root.merge_defaults(&path, config)?;
- }
- }
- let config_resolver = Some(Arc::new(spin_config::Resolver::new(config_root)?));
-
let info = info(&raw, &invoice, url);
log::trace!("Application information from bindle: {:?}", info);
let component_triggers = raw
@@ -99,11 +88,17 @@ async fn prepare(
.map(|x| x.expect("Cannot prepare component"))
.collect::<Vec<_>>();
+ let variables = raw
+ .variables
+ .into_iter()
+ .map(|(key, var)| Ok((key, var.try_into()?)))
+ .collect::<Result<_>>()?;
+
Ok(Application {
info,
+ variables,
components,
component_triggers,
- config_resolver,
})
}
@@ -153,11 +148,13 @@ async fn core(
mounts,
allowed_http_hosts,
};
+ let config = raw.config.unwrap_or_default();
Ok(CoreComponent {
source,
id,
description,
wasm,
+ config,
})
}
diff --git a/crates/loader/src/common.rs b/crates/loader/src/common.rs
new file mode 100644
index 0000000000..ef33717b31
--- /dev/null
+++ b/crates/loader/src/common.rs
@@ -0,0 +1,33 @@
+use anyhow::ensure;
+use serde::{Deserialize, Serialize};
+use spin_manifest::Variable;
+
+/// Variable configuration.
+#[derive(Clone, Debug, Default, Deserialize, Serialize)]
+#[serde(deny_unknown_fields, rename_all = "camelCase")]
+pub struct RawVariable {
+ /// If set, this variable is required; may not be set with `default`.
+ #[serde(default)]
+ pub required: bool,
+ /// If set, the default value for this variable; may not be set with `required`.
+ #[serde(default)]
+ pub default: Option<String>,
+ /// If set, this variable should be treated as sensitive.
+ #[serde(default)]
+ pub secret: bool,
+}
+
+impl TryFrom<RawVariable> for Variable {
+ type Error = anyhow::Error;
+
+ fn try_from(var: RawVariable) -> Result<Self, Self::Error> {
+ ensure!(
+ var.required ^ var.default.is_some(),
+ "variable has both `required` and `default` set"
+ );
+ Ok(Variable {
+ default: var.default,
+ secret: var.secret,
+ })
+ }
+}
diff --git a/crates/loader/src/lib.rs b/crates/loader/src/lib.rs
index 92dca06511..34f4e82636 100644
--- a/crates/loader/src/lib.rs
+++ b/crates/loader/src/lib.rs
@@ -12,6 +12,7 @@
mod assets;
pub mod bindle;
+mod common;
pub mod local;
mod validation;
diff --git a/crates/loader/src/local/config.rs b/crates/loader/src/local/config.rs
index c08a774577..6cf180a6f5 100644
--- a/crates/loader/src/local/config.rs
+++ b/crates/loader/src/local/config.rs
@@ -8,6 +8,8 @@ use serde::{Deserialize, Serialize};
use spin_manifest::{ApplicationTrigger, TriggerConfig};
use std::{collections::HashMap, path::PathBuf};
+use crate::common::RawVariable;
+
/// Container for any version of the manifest.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(tag = "spin_version")]
@@ -27,8 +29,8 @@ pub struct RawAppManifest {
pub info: RawAppInformation,
/// Application-specific configuration schema.
- #[serde(rename = "variables")]
- pub config: Option<spin_config::Tree>,
+ #[serde(default, skip_serializing_if = "HashMap::is_empty")]
+ pub variables: HashMap<String, RawVariable>,
/// Configuration for the application components.
#[serde(rename = "component")]
diff --git a/crates/loader/src/local/mod.rs b/crates/loader/src/local/mod.rs
index cc7ffb5ba7..8c0bed3b43 100644
--- a/crates/loader/src/local/mod.rs
+++ b/crates/loader/src/local/mod.rs
@@ -18,7 +18,7 @@ use spin_manifest::{
Application, ApplicationInformation, ApplicationOrigin, CoreComponent, ModuleSource,
SpinVersion, WasmConfig,
};
-use std::{path::Path, str::FromStr, sync::Arc};
+use std::{path::Path, str::FromStr};
use tokio::{fs::File, io::AsyncReadExt};
use crate::{
@@ -113,7 +113,7 @@ pub fn validate_raw_app_manifest(raw: &RawAppManifestAnyVersion) -> Result<()> {
/// Converts a raw application manifest into Spin configuration.
async fn prepare(
- mut raw: RawAppManifest,
+ raw: RawAppManifest,
src: impl AsRef<Path>,
base_dst: impl AsRef<Path>,
bindle_connection: &Option<BindleConnectionInfo>,
@@ -123,17 +123,6 @@ async fn prepare(
error_on_duplicate_ids(raw.components.clone())?;
- let mut config_root = raw.config.unwrap_or_default();
- for component in &mut raw.components {
- if let Some(config) = component.config.take() {
- let path = component.id.clone().try_into().with_context(|| {
- format!("component ID {:?} not a valid config path", component.id)
- })?;
- config_root.merge_defaults(&path, config)?;
- }
- }
- let config_resolver = Some(Arc::new(spin_config::Resolver::new(config_root)?));
-
let component_triggers = raw
.components
.iter()
@@ -153,11 +142,17 @@ async fn prepare(
.collect::<Result<Vec<_>>>()
.context("Failed to prepare configuration")?;
+ let variables = raw
+ .variables
+ .into_iter()
+ .map(|(key, var)| Ok((key, var.try_into()?)))
+ .collect::<Result<_>>()?;
+
Ok(Application {
info,
+ variables,
components,
component_triggers,
- config_resolver,
})
}
@@ -234,11 +229,13 @@ async fn core(
mounts,
allowed_http_hosts,
};
+ let config = raw.config.unwrap_or_default();
Ok(CoreComponent {
source,
id,
description,
wasm,
+ config,
})
}
diff --git a/crates/manifest/Cargo.toml b/crates/manifest/Cargo.toml
index cf6bcfd9ef..de86bba892 100644
--- a/crates/manifest/Cargo.toml
+++ b/crates/manifest/Cargo.toml
@@ -8,6 +8,5 @@ authors = [ "Fermyon Engineering <engineering@fermyon.com>" ]
anyhow = "1.0"
indexmap = "1"
serde = { version = "1.0", features = [ "derive" ] }
-spin-config = { path = "../config" }
thiserror = "1"
url = "2.2"
diff --git a/crates/manifest/src/lib.rs b/crates/manifest/src/lib.rs
index 2018c88742..000c7974a1 100644
--- a/crates/manifest/src/lib.rs
+++ b/crates/manifest/src/lib.rs
@@ -4,12 +4,10 @@
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
-use spin_config::Resolver;
use std::{
collections::HashMap,
fmt::{Debug, Formatter},
path::PathBuf,
- sync::Arc,
};
/// A trigger error.
@@ -28,12 +26,12 @@ pub type ComponentMap<T> = IndexMap<String, T>;
pub struct Application {
/// General application information.
pub info: ApplicationInformation,
+ /// Application-specific configuration variables.
+ pub variables: HashMap<String, Variable>,
/// Configuration for the application components.
pub components: Vec<CoreComponent>,
/// Configuration for the components' triggers.
pub component_triggers: ComponentMap<TriggerConfig>,
- /// Application-specific configuration resolver.
- pub config_resolver: Option<Arc<Resolver>>,
}
/// Spin API version.
@@ -81,6 +79,17 @@ pub struct CoreComponent {
pub description: Option<String>,
/// Per-component WebAssembly configuration.
pub wasm: WasmConfig,
+ /// Per-component configuration values.
+ pub config: HashMap<String, String>,
+}
+
+/// A custom config variable.
+#[derive(Clone, Debug)]
+pub struct Variable {
+ /// If set, the default value of this variable. If unset, this variable is required.
+ pub default: Option<String>,
+ /// If set, this variable's value should be treated as sensitive (e.g. not logged).
+ pub secret: bool,
}
/// The location from which an application was loaded.
diff --git a/crates/publish/src/expander.rs b/crates/publish/src/expander.rs
index 7dc58dccb6..ce76d2f04b 100644
--- a/crates/publish/src/expander.rs
+++ b/crates/publish/src/expander.rs
@@ -89,12 +89,12 @@ fn bindle_manifest(
.collect::<Result<Vec<_>>>()
.context("Failed to convert components to Bindle format")?;
let trigger = local.info.trigger.clone();
- let config = local.config.clone();
+ let variables = local.variables.clone();
Ok(bindle_schema::RawAppManifest {
trigger,
components,
- config,
+ variables,
})
}
diff --git a/crates/trigger/src/cli.rs b/crates/trigger/src/cli.rs
index ca2ff2cc3a..32beccef05 100644
--- a/crates/trigger/src/cli.rs
+++ b/crates/trigger/src/cli.rs
@@ -1,9 +1,4 @@
-use std::{
- collections::HashMap,
- error::Error,
- path::{Path, PathBuf},
- sync::Arc,
-};
+use std::{error::Error, path::PathBuf};
use anyhow::{bail, Context, Result};
use clap::{Args, IntoApp, Parser};
@@ -146,9 +141,7 @@ where
.context("SPIN_ALLOW_TRANSIENT_WRITE")?;
// TODO(lann): Find a better home for this; spin_loader?
- let dotenv_path;
let mut app = if let Some(manifest_file) = manifest_url.strip_prefix("file://") {
- dotenv_path = Path::new(manifest_file).parent().unwrap().join(".env");
let bindle_connection = std::env::var("BINDLE_URL")
.ok()
.map(|url| BindleConnectionInfo::new(url, false, None, None));
@@ -160,7 +153,6 @@ where
)
.await?
} else if let Some(bindle_url) = manifest_url.strip_prefix("bindle+") {
- dotenv_path = Path::new("./.env").to_path_buf();
let (bindle_server, bindle_id) = bindle_url
.rsplit_once("?id=")
.context("invalid bindle URL")?;
@@ -177,19 +169,6 @@ where
}
}
- let envs = read_dotenv(dotenv_path)?;
-
- // Add default config provider(s).
- // TODO(lann): Make config provider(s) configurable.
- if let Some(ref mut resolver) = app.config_resolver {
- let resolver = Arc::get_mut(resolver)
- .context("Internal error: app.config_resolver unexpectedly shared")?;
- resolver.add_provider(spin_config::provider::env::EnvProvider::new(
- spin_config::provider::env::DEFAULT_PREFIX,
- envs,
- ));
- }
-
Ok(app)
}
@@ -224,18 +203,3 @@ fn parse_env_var(s: &str) -> Result<(String, String)> {
}
Ok((parts[0].to_owned(), parts[1].to_owned()))
}
-
-// Return environment key value mapping in ".env" file.
-fn read_dotenv(dotenv_path: impl AsRef<Path>) -> Result<HashMap<String, String>> {
- let mut envs = HashMap::new();
- if !dotenv_path.as_ref().exists() {
- return Ok(envs);
- }
-
- let env_iter = dotenvy::from_path_iter(dotenv_path)?;
- for env_item in env_iter {
- let (key, value) = env_item?;
- envs.insert(key, value);
- }
- Ok(envs)
-}
diff --git a/crates/trigger/src/lib.rs b/crates/trigger/src/lib.rs
index d5901e7449..e388c1160c 100644
--- a/crates/trigger/src/lib.rs
+++ b/crates/trigger/src/lib.rs
@@ -2,16 +2,17 @@ use std::{
collections::HashMap,
error::Error,
marker::PhantomData,
- path::PathBuf,
+ path::{Path, PathBuf},
sync::{Arc, RwLock},
};
use anyhow::Result;
use async_trait::async_trait;
+use spin_config::{host_component::ConfigHostComponent, Resolver};
use spin_engine::{
io::FollowComponents, Builder, Engine, ExecutionContext, ExecutionContextConfiguration,
};
-use spin_manifest::{Application, ApplicationTrigger, TriggerConfig};
+use spin_manifest::{Application, ApplicationOrigin, ApplicationTrigger, TriggerConfig, Variable};
pub mod cli;
#[async_trait]
@@ -92,20 +93,27 @@ impl<Executor: TriggerExecutor> TriggerExecutorBuilder<Executor> {
{
let app = self.application;
+ // The .env file is either a sibling to the manifest file or (for bindles) in the current dir.
+ let dotenv_root = match &app.info.origin {
+ ApplicationOrigin::File(path) => path.parent().unwrap(),
+ ApplicationOrigin::Bindle { .. } => Path::new("."),
+ };
+
// Build ExecutionContext
let ctx_config = ExecutionContextConfiguration {
components: app.components,
label: app.info.name,
log_dir: self.log_dir,
follow_components: self.follow_components,
- config_resolver: app.config_resolver,
};
let engine = Engine::new(self.wasmtime_config)?;
let mut ctx_builder = Builder::with_engine(ctx_config, engine)?;
ctx_builder.link_defaults()?;
if !self.disable_default_host_components {
add_default_host_components(&mut ctx_builder)?;
+ add_config_host_component(&mut ctx_builder, app.variables, dotenv_root)?;
}
+
Executor::configure_execution_context(&mut ctx_builder)?;
let execution_context = ctx_builder.build().await?;
@@ -133,3 +141,42 @@ pub fn add_default_host_components<T: Default + Send + 'static>(
builder.add_host_component(outbound_pg::OutboundPg)?;
Ok(())
}
+
+pub fn add_config_host_component<T: Default + Send + 'static>(
+ ctx_builder: &mut Builder<T>,
+ variables: HashMap<String, Variable>,
+ dotenv_path: &Path,
+) -> Result<()> {
+ let mut resolver = Resolver::new(variables)?;
+
+ // Add all component configs to the Resolver.
+ for component in &ctx_builder.config().components {
+ resolver.add_component_config(
+ &component.id,
+ component.config.iter().map(|(k, v)| (k.clone(), v.clone())),
+ )?;
+ }
+
+ let envs = read_dotenv(dotenv_path)?;
+
+ // Add default config provider(s).
+ // TODO(lann): Make config provider(s) configurable.
+ resolver.add_provider(spin_config::provider::env::EnvProvider::new(
+ spin_config::provider::env::DEFAULT_PREFIX,
+ envs,
+ ));
+
+ ctx_builder.add_host_component(ConfigHostComponent::new(resolver))?;
+ Ok(())
+}
+
+// Return environment key value mapping in ".env" file.
+fn read_dotenv(dotenv_root: &Path) -> Result<HashMap<String, String>> {
+ let dotenv_path = dotenv_root.join(".env");
+ if !dotenv_path.is_file() {
+ return Ok(Default::default());
+ }
+ dotenvy::from_path_iter(dotenv_path)?
+ .map(|item| Ok(item?))
+ .collect()
+}
diff --git a/docs/content/configuration.md b/docs/content/configuration.md
index e49dc5a0fe..fec4892365 100644
--- a/docs/content/configuration.md
+++ b/docs/content/configuration.md
@@ -54,7 +54,7 @@ configuration has the following fields:
- `type` (REQUIRED): The application trigger type with the value `"redis"`.
- `address` (REQUIRED): The address of the Redis instance the components
are using for message subscriptions.
-- `variables` (OPTIONAL): [Custom configuration](#custom-configuration) "slots".
+- `variables` (OPTIONAL): [Custom configuration](#custom-configuration) variables.
- A list of `component` objects (REQUIRED) defining the application components.
### Component configuration
@@ -120,9 +120,9 @@ is published, the component will be invoked.
Spin applications may define custom configuration which can be looked up by
component code via the [spin-config interface](https://github.com/fermyon/spin/blob/main/wit/ephemeral/spin-config.wit).
-### Custom Config Slots
+### Custom Config Variables
-Application-global custom config "slots" are defined in the top-level `[variables]`
+Application-global custom config variables are defined in the top-level `[variables]`
section. These entries aren't accessed directly by components, but are referenced
by [component config](#component-custom-config) value templates. Each entry must
either have a `default` value or be marked as `required = true`. "Required" entries
@@ -140,7 +140,7 @@ api_key = { required = true }
The configuration entries available to a component are listed in its
`[component.config]` section. Configuration values may reference
-[config slots](#custom-config-slots) with simple
+[config variables](#custom-config-variables) with simple
[mustache](https://mustache.github.io/)-inspired string templates.
```toml
@@ -153,7 +153,7 @@ api_key = "{{ api_key }}"
### Custom Config Providers
-[Custom config slot](#custom-config-slots) values may be set at runtime by
+[Custom config variables](#custom-config-variables) values may be set at runtime by
config "providers". Currently there is only one provider: the environment
variable provider, which gets config values from the `spin` process's
environment (_not_ the component `environment`). Config keys are translated
diff --git a/examples/spin-timer/src/main.rs b/examples/spin-timer/src/main.rs
index a2c222c704..087439bae4 100644
--- a/examples/spin-timer/src/main.rs
+++ b/examples/spin-timer/src/main.rs
@@ -77,5 +77,6 @@ pub fn component() -> CoreComponent {
id: "test".to_string(),
description: None,
wasm: WasmConfig::default(),
+ config: Default::default(),
}
}
| 750
|
[
"718"
] |
diff --git a/crates/testing/src/lib.rs b/crates/testing/src/lib.rs
index 51744b34b4..eaf5c4504b 100644
--- a/crates/testing/src/lib.rs
+++ b/crates/testing/src/lib.rs
@@ -79,6 +79,7 @@ impl TestConfig {
id: "test-component".to_string(),
description: None,
wasm: Default::default(),
+ config: Default::default(),
}
}
@@ -94,7 +95,7 @@ impl TestConfig {
)]
.into_iter()
.collect(),
- config_resolver: None,
+ variables: Default::default(),
}
}
@@ -105,7 +106,6 @@ impl TestConfig {
let config = ExecutionContextConfiguration {
components: app.components,
label: app.info.name,
- config_resolver: app.config_resolver,
..Default::default()
};
let mut builder = Builder::new(config).expect("Builder::new failed");
|
eb50b54c51cb6290a592bdbfc4aa4882fdfe7191
|
|
e8b6667af92152971faf96e53669531c45b55c1d
|
`allowed_http_hosts` requires protocol but ignores it
If I write `allowed_http_hosts = ["https://localhost:3001"]` I can still make a request to `http://localhost:3001/` and it works.
If we are to require a protocol, shouldn't that be enforced? I assumed this was why we required a protocol rather than just a hostname.
|
Also, any port the operator specifies is ignored, e.g. if I write `allowed_http_hosts = ["https://localhost:4444"]` then make a request to `http://localhost:3001/`, it is allowed.
This is certainly in line with the name "hosts" but maybe we should validate that no port is given, or an operator might be led into a wrong assumption about what permissions they are granting.
Proposal for this and #722:
* `allowed_http_hosts` contains a list of host names (domain names).
* For now, we will also accept schemes for backward compatibility; as today, they will be ignored, but they are no longer required or desired.
* A port may optionally be specified with a host
* A host may be listed multiple times with different ports.
* If a host is listed with *no* port, then we will accept URLs without ports (so implicitly port 80 or 443 according to URL scheme).
* If a host is listed with a *specific* port, then we will accept URLs with that specific port.
* We will maintain a deny-list of ports that may *never* be specified. If one of these ports appears in `allowed_http_hosts`, it will fail validation.
* Initially the deny list will contain ports 25, 587 and 2525 (SMTP).
Feedback welcome!
`587` and `2525` are other common smtp ports
|
2022-08-31T05:19:04Z
|
fermyon__spin-727
|
fermyon/spin
|
0.4
|
diff --git a/Cargo.lock b/Cargo.lock
index 0e0abf2562..a64c3e68bb 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3538,6 +3538,7 @@ dependencies = [
"serde",
"spin-config",
"thiserror",
+ "url",
]
[[package]]
diff --git a/crates/loader/src/bindle/mod.rs b/crates/loader/src/bindle/mod.rs
index c89f45541b..74e8a5fdc6 100644
--- a/crates/loader/src/bindle/mod.rs
+++ b/crates/loader/src/bindle/mod.rs
@@ -15,7 +15,7 @@ use crate::{
config::{RawAppManifest, RawComponentManifest},
utils::{find_manifest, parcels_in_group},
},
- validation::validate_allowed_http_hosts,
+ validation::{parse_allowed_http_hosts, validate_allowed_http_hosts},
};
use anyhow::{anyhow, Context, Result};
use bindle::Invoice;
@@ -68,9 +68,10 @@ async fn prepare(
toml::from_slice(&reader.get_parcel(&find_manifest(&invoice)?).await?)?;
log::trace!("Recreated manifest from bindle: {:?}", raw);
+ validate_raw_app_manifest(&raw)?;
+
let mut config_root = raw.config.take().unwrap_or_default();
for component in &mut raw.components {
- validate_allowed_http_hosts(&component.wasm.allowed_http_hosts)?;
if let Some(config) = component.config.take() {
let path = component.id.clone().try_into().with_context(|| {
format!("component ID {:?} not a valid config path", component.id)
@@ -106,6 +107,12 @@ async fn prepare(
})
}
+fn validate_raw_app_manifest(raw: &RawAppManifest) -> Result<()> {
+ raw.components
+ .iter()
+ .try_for_each(|c| validate_allowed_http_hosts(&c.wasm.allowed_http_hosts))
+}
+
/// Given a raw component manifest, prepare its assets and return a fully formed core component.
async fn core(
raw: RawComponentManifest,
@@ -140,7 +147,7 @@ async fn core(
None => vec![],
};
let environment = raw.wasm.environment.unwrap_or_default();
- let allowed_http_hosts = raw.wasm.allowed_http_hosts.unwrap_or_default();
+ let allowed_http_hosts = parse_allowed_http_hosts(&raw.wasm.allowed_http_hosts)?;
let wasm = WasmConfig {
environment,
mounts,
diff --git a/crates/loader/src/local/mod.rs b/crates/loader/src/local/mod.rs
index bc5940fa27..cc7ffb5ba7 100644
--- a/crates/loader/src/local/mod.rs
+++ b/crates/loader/src/local/mod.rs
@@ -21,7 +21,10 @@ use spin_manifest::{
use std::{path::Path, str::FromStr, sync::Arc};
use tokio::{fs::File, io::AsyncReadExt};
-use crate::{bindle::BindleConnectionInfo, validation::validate_allowed_http_hosts};
+use crate::{
+ bindle::BindleConnectionInfo,
+ validation::{parse_allowed_http_hosts, validate_allowed_http_hosts},
+};
/// Given the path to a spin.toml manifest file, prepare its assets locally and
/// get a prepared application configuration consumable by a Spin execution context.
@@ -225,7 +228,7 @@ async fn core(
None => vec![],
};
let environment = raw.wasm.environment.unwrap_or_default();
- let allowed_http_hosts = raw.wasm.allowed_http_hosts.unwrap_or_default();
+ let allowed_http_hosts = parse_allowed_http_hosts(&raw.wasm.allowed_http_hosts)?;
let wasm = WasmConfig {
environment,
mounts,
diff --git a/crates/loader/src/validation.rs b/crates/loader/src/validation.rs
index 0cf29903c2..5ddf4c1fb3 100644
--- a/crates/loader/src/validation.rs
+++ b/crates/loader/src/validation.rs
@@ -1,23 +1,246 @@
#![deny(missing_docs)]
-use anyhow::{Context, Result};
+use anyhow::{anyhow, Result};
use reqwest::Url;
+use spin_manifest::{AllowedHttpHost, AllowedHttpHosts};
-// Check whether http host can be parsed by Url
+// Checks a list of allowed HTTP hosts is valid
pub fn validate_allowed_http_hosts(http_hosts: &Option<Vec<String>>) -> Result<()> {
- if let Some(domains) = http_hosts.as_deref() {
- if domains
- .iter()
- .any(|domain| domain == wasi_outbound_http::ALLOW_ALL_HOSTS)
- {
- return Ok(());
+ parse_allowed_http_hosts(http_hosts).map(|_| ())
+}
+
+// Parses a list of allowed HTTP hosts
+pub fn parse_allowed_http_hosts(raw: &Option<Vec<String>>) -> Result<AllowedHttpHosts> {
+ match raw {
+ None => Ok(AllowedHttpHosts::AllowSpecific(vec![])),
+ Some(list) => {
+ if list
+ .iter()
+ .any(|domain| domain == wasi_outbound_http::ALLOW_ALL_HOSTS)
+ {
+ Ok(AllowedHttpHosts::AllowAll)
+ } else {
+ let parse_results = list
+ .iter()
+ .map(|h| parse_allowed_http_host(h))
+ .collect::<Vec<_>>();
+ let (hosts, errors) = partition_results(parse_results);
+
+ if errors.is_empty() {
+ Ok(AllowedHttpHosts::AllowSpecific(hosts))
+ } else {
+ Err(anyhow!(
+ "One or more allowed_http_hosts entries was invalid:\n{}",
+ errors.join("\n")
+ ))
+ }
+ }
}
- let _ = domains
- .iter()
- .map(|d| {
- Url::parse(d).with_context(|| format!("Can't parse {} in allowed_http_hosts", d))
- })
- .collect::<Result<Vec<_>, _>>()?;
- }
- Ok(())
+ }
+}
+
+fn parse_allowed_http_host(text: &str) -> Result<AllowedHttpHost, String> {
+ // If you call Url::parse, it accepts things like `localhost:3001`, inferring
+ // `localhost` as a scheme. That's unhelpful for us, so we do a crude check
+ // before trying to treat the string as a URL.
+ if text.contains("//") {
+ parse_allowed_http_host_from_schemed(text)
+ } else {
+ parse_allowed_http_host_from_unschemed(text)
+ }
+}
+
+fn parse_allowed_http_host_from_unschemed(text: &str) -> Result<AllowedHttpHost, String> {
+ // Host name parsing is quite hairy (thanks, IPv6), so punt it off to the
+ // Url type which gets paid big bucks to do it properly. (But preserve the
+ // original un-URL-ified string for use in error messages.)
+ let urlised = format!("http://{}", text);
+ let fake_url = Url::parse(&urlised)
+ .map_err(|_| format!("{} isn't a valid host or host:port string", text))?;
+ parse_allowed_http_host_from_http_url(&fake_url, text)
+}
+
+fn parse_allowed_http_host_from_schemed(text: &str) -> Result<AllowedHttpHost, String> {
+ let url =
+ Url::parse(text).map_err(|e| format!("{} isn't a valid HTTP host URL: {}", text, e))?;
+
+ if !matches!(url.scheme(), "http" | "https") {
+ return Err(format!("{} isn't a valid host or host:port string", text));
+ }
+
+ parse_allowed_http_host_from_http_url(&url, text)
+}
+
+fn parse_allowed_http_host_from_http_url(url: &Url, text: &str) -> Result<AllowedHttpHost, String> {
+ let host = url
+ .host_str()
+ .ok_or_else(|| format!("{} doesn't contain a host name", text))?;
+
+ let has_path = url.path().len() > 1; // allow "/"
+ if has_path {
+ return Err(format!(
+ "{} contains a path, should be host and optional port only",
+ text
+ ));
+ }
+
+ Ok(AllowedHttpHost::new(host, url.port()))
+}
+
+fn partition_results<T, E>(results: Vec<Result<T, E>>) -> (Vec<T>, Vec<E>) {
+ // We are going to to be OPTIMISTIC do you hear me
+ let mut oks = Vec::with_capacity(results.len());
+ let mut errs = vec![];
+
+ for result in results {
+ match result {
+ Ok(t) => oks.push(t),
+ Err(e) => errs.push(e),
+ }
+ }
+
+ (oks, errs)
+}
+
+#[cfg(test)]
+mod test {
+ use super::*;
+
+ #[test]
+ fn test_allowed_hosts_accepts_http_url() {
+ assert_eq!(
+ AllowedHttpHost::host("spin.fermyon.dev"),
+ parse_allowed_http_host("http://spin.fermyon.dev").unwrap()
+ );
+ assert_eq!(
+ AllowedHttpHost::host("spin.fermyon.dev"),
+ parse_allowed_http_host("http://spin.fermyon.dev/").unwrap()
+ );
+ assert_eq!(
+ AllowedHttpHost::host("spin.fermyon.dev"),
+ parse_allowed_http_host("https://spin.fermyon.dev").unwrap()
+ );
+ }
+
+ #[test]
+ fn test_allowed_hosts_accepts_http_url_with_port() {
+ assert_eq!(
+ AllowedHttpHost::host_and_port("spin.fermyon.dev", 4444),
+ parse_allowed_http_host("http://spin.fermyon.dev:4444").unwrap()
+ );
+ assert_eq!(
+ AllowedHttpHost::host_and_port("spin.fermyon.dev", 4444),
+ parse_allowed_http_host("http://spin.fermyon.dev:4444/").unwrap()
+ );
+ assert_eq!(
+ AllowedHttpHost::host_and_port("spin.fermyon.dev", 5555),
+ parse_allowed_http_host("https://spin.fermyon.dev:5555").unwrap()
+ );
+ }
+
+ #[test]
+ fn test_allowed_hosts_accepts_plain_host() {
+ assert_eq!(
+ AllowedHttpHost::host("spin.fermyon.dev"),
+ parse_allowed_http_host("spin.fermyon.dev").unwrap()
+ );
+ }
+
+ #[test]
+ fn test_allowed_hosts_accepts_plain_host_with_port() {
+ assert_eq!(
+ AllowedHttpHost::host_and_port("spin.fermyon.dev", 7777),
+ parse_allowed_http_host("spin.fermyon.dev:7777").unwrap()
+ );
+ }
+
+ #[test]
+ fn test_allowed_hosts_accepts_localhost_addresses() {
+ assert_eq!(
+ AllowedHttpHost::host("localhost"),
+ parse_allowed_http_host("localhost").unwrap()
+ );
+ assert_eq!(
+ AllowedHttpHost::host("localhost"),
+ parse_allowed_http_host("http://localhost").unwrap()
+ );
+ assert_eq!(
+ AllowedHttpHost::host_and_port("localhost", 3001),
+ parse_allowed_http_host("localhost:3001").unwrap()
+ );
+ assert_eq!(
+ AllowedHttpHost::host_and_port("localhost", 3001),
+ parse_allowed_http_host("http://localhost:3001").unwrap()
+ );
+ }
+
+ #[test]
+ fn test_allowed_hosts_accepts_ip_addresses() {
+ assert_eq!(
+ AllowedHttpHost::host("192.168.1.1"),
+ parse_allowed_http_host("192.168.1.1").unwrap()
+ );
+ assert_eq!(
+ AllowedHttpHost::host("192.168.1.1"),
+ parse_allowed_http_host("http://192.168.1.1").unwrap()
+ );
+ assert_eq!(
+ AllowedHttpHost::host_and_port("192.168.1.1", 3002),
+ parse_allowed_http_host("192.168.1.1:3002").unwrap()
+ );
+ assert_eq!(
+ AllowedHttpHost::host_and_port("192.168.1.1", 3002),
+ parse_allowed_http_host("http://192.168.1.1:3002").unwrap()
+ );
+ assert_eq!(
+ AllowedHttpHost::host("[::1]"),
+ parse_allowed_http_host("[::1]").unwrap()
+ );
+ assert_eq!(
+ AllowedHttpHost::host_and_port("[::1]", 8001),
+ parse_allowed_http_host("http://[::1]:8001").unwrap()
+ );
+ }
+
+ #[test]
+ fn test_allowed_hosts_rejects_path() {
+ assert!(parse_allowed_http_host("http://spin.fermyon.dev/a").is_err());
+ assert!(parse_allowed_http_host("http://spin.fermyon.dev:6666/a/b").is_err());
+ }
+
+ #[test]
+ fn test_allowed_hosts_rejects_ftp_url() {
+ assert!(parse_allowed_http_host("ftp://spin.fermyon.dev").is_err());
+ assert!(parse_allowed_http_host("ftp://spin.fermyon.dev:6666").is_err());
+ }
+
+ fn to_vec_owned(source: &[&str]) -> Option<Vec<String>> {
+ Some(source.iter().map(|s| s.to_owned().to_owned()).collect())
+ }
+
+ #[test]
+ fn test_allowed_hosts_respects_allow_all() {
+ assert_eq!(
+ AllowedHttpHosts::AllowAll,
+ parse_allowed_http_hosts(&to_vec_owned(&["insecure:allow-all"])).unwrap()
+ );
+ assert_eq!(
+ AllowedHttpHosts::AllowAll,
+ parse_allowed_http_hosts(&to_vec_owned(&["spin.fermyon.dev", "insecure:allow-all"]))
+ .unwrap()
+ );
+ }
+
+ #[test]
+ fn test_allowed_hosts_can_be_specific() {
+ let allowed = parse_allowed_http_hosts(&to_vec_owned(&[
+ "spin.fermyon.dev",
+ "http://example.com:8383",
+ ]))
+ .unwrap();
+ assert!(allowed.allow(&Url::parse("http://example.com:8383/foo/bar").unwrap()));
+ assert!(allowed.allow(&Url::parse("https://spin.fermyon.dev/").unwrap()));
+ assert!(!allowed.allow(&Url::parse("http://example.com/").unwrap()));
+ assert!(!allowed.allow(&Url::parse("http://google.com/").unwrap()));
+ }
}
diff --git a/crates/manifest/Cargo.toml b/crates/manifest/Cargo.toml
index 4da19de033..cf6bcfd9ef 100644
--- a/crates/manifest/Cargo.toml
+++ b/crates/manifest/Cargo.toml
@@ -10,3 +10,4 @@ indexmap = "1"
serde = { version = "1.0", features = [ "derive" ] }
spin-config = { path = "../config" }
thiserror = "1"
+url = "2.2"
diff --git a/crates/manifest/src/lib.rs b/crates/manifest/src/lib.rs
index 0049b98c91..2018c88742 100644
--- a/crates/manifest/src/lib.rs
+++ b/crates/manifest/src/lib.rs
@@ -149,6 +149,70 @@ impl TryFrom<ApplicationTrigger> for RedisTriggerConfiguration {
}
}
+/// An HTTP host allow-list.
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub enum AllowedHttpHosts {
+ /// All HTTP hosts are allowed (the "insecure:allow-all" value was present in the list)
+ AllowAll,
+ /// Only the specified hosts are allowed.
+ AllowSpecific(Vec<AllowedHttpHost>),
+}
+
+impl Default for AllowedHttpHosts {
+ fn default() -> Self {
+ Self::AllowSpecific(vec![])
+ }
+}
+
+impl AllowedHttpHosts {
+ /// Tests whether the given URL is allowed according to the allow-list.
+ pub fn allow(&self, url: &url::Url) -> bool {
+ match self {
+ Self::AllowAll => true,
+ Self::AllowSpecific(hosts) => hosts.iter().any(|h| h.allow(url)),
+ }
+ }
+}
+
+/// An HTTP host allow-list entry.
+#[derive(Clone, Debug, Default, Eq, PartialEq)]
+pub struct AllowedHttpHost {
+ domain: String,
+ port: Option<u16>,
+}
+
+impl AllowedHttpHost {
+ /// Creates a new allow-list entry.
+ pub fn new(name: impl Into<String>, port: Option<u16>) -> Self {
+ Self {
+ domain: name.into(),
+ port,
+ }
+ }
+
+ /// An allow-list entry that specifies a host and allows the default port.
+ pub fn host(name: impl Into<String>) -> Self {
+ Self {
+ domain: name.into(),
+ port: None,
+ }
+ }
+
+ /// An allow-list entry that specifies a host and port.
+ pub fn host_and_port(name: impl Into<String>, port: u16) -> Self {
+ Self {
+ domain: name.into(),
+ port: Some(port),
+ }
+ }
+
+ fn allow(&self, url: &url::Url) -> bool {
+ (url.scheme() == "http" || url.scheme() == "https")
+ && self.domain == url.host_str().unwrap_or_default()
+ && self.port == url.port()
+ }
+}
+
/// WebAssembly configuration.
#[derive(Clone, Debug, Default)]
pub struct WasmConfig {
@@ -157,7 +221,7 @@ pub struct WasmConfig {
/// List of directory mounts that need to be mapped inside the WebAssembly module.
pub mounts: Vec<DirectoryMount>,
/// Optional list of HTTP hosts the component is allowed to connect.
- pub allowed_http_hosts: Vec<String>,
+ pub allowed_http_hosts: AllowedHttpHosts,
}
/// Directory mount for the assets of a component.
diff --git a/crates/outbound-http/src/host_component.rs b/crates/outbound-http/src/host_component.rs
index 9b3f100c8e..c3aa252a91 100644
--- a/crates/outbound-http/src/host_component.rs
+++ b/crates/outbound-http/src/host_component.rs
@@ -24,7 +24,7 @@ impl HostComponent for OutboundHttpComponent {
fn build_state(&self, component: &CoreComponent) -> Result<Self::State> {
Ok(OutboundHttp {
- allowed_hosts: Some(component.wasm.allowed_http_hosts.clone()),
+ allowed_hosts: component.wasm.allowed_http_hosts.clone(),
})
}
}
diff --git a/crates/outbound-http/src/lib.rs b/crates/outbound-http/src/lib.rs
index 2a3afea685..6c070679c8 100644
--- a/crates/outbound-http/src/lib.rs
+++ b/crates/outbound-http/src/lib.rs
@@ -3,6 +3,7 @@ mod host_component;
use futures::executor::block_on;
use http::HeaderMap;
use reqwest::{Client, Url};
+use spin_manifest::AllowedHttpHosts;
use std::str::FromStr;
use tokio::runtime::Handle;
use wasi_outbound_http::*;
@@ -18,11 +19,11 @@ pub const ALLOW_ALL_HOSTS: &str = "insecure:allow-all";
#[derive(Default, Clone)]
pub struct OutboundHttp {
/// List of hosts guest modules are allowed to make requests to.
- pub allowed_hosts: Option<Vec<String>>,
+ pub allowed_hosts: AllowedHttpHosts,
}
impl OutboundHttp {
- pub fn new(allowed_hosts: Option<Vec<String>>) -> Self {
+ pub fn new(allowed_hosts: AllowedHttpHosts) -> Self {
Self { allowed_hosts }
}
@@ -30,37 +31,15 @@ impl OutboundHttp {
/// allowed hosts defined by the runtime. If the list of allowed hosts contains
/// `insecure:allow-all`, then all hosts are allowed.
/// If `None` is passed, the guest module is not allowed to send the request.
- fn is_allowed(url: &str, allowed_hosts: Option<Vec<String>>) -> Result<bool, HttpError> {
- let url_host = Url::parse(url)
- .map_err(|_| HttpError::InvalidUrl)?
- .host_str()
- .ok_or(HttpError::InvalidUrl)?
- .to_owned();
- match allowed_hosts.as_deref() {
- Some(domains) => {
- tracing::info!("Allowed hosts: {:?}", domains);
- // check domains has any "insecure:allow-all" wildcard
- if domains.iter().any(|domain| domain == ALLOW_ALL_HOSTS) {
- Ok(true)
- } else {
- let allowed: Result<Vec<_>, _> =
- domains.iter().map(|d| Url::parse(d)).collect();
- let allowed = allowed.map_err(|_| HttpError::InvalidUrl)?;
-
- Ok(allowed
- .iter()
- .map(|u| u.host_str().unwrap())
- .any(|x| x == url_host.as_str()))
- }
- }
- None => Ok(false),
- }
+ fn is_allowed(&self, url: &str) -> Result<bool, HttpError> {
+ let url = Url::parse(url).map_err(|_| HttpError::InvalidUrl)?;
+ Ok(self.allowed_hosts.allow(&url))
}
}
impl wasi_outbound_http::WasiOutboundHttp for OutboundHttp {
fn request(&mut self, req: Request) -> Result<Response, HttpError> {
- if !Self::is_allowed(req.uri, self.allowed_hosts.clone())? {
+ if !self.is_allowed(req.uri)? {
tracing::log::info!("Destination not allowed: {}", req.uri);
return Err(HttpError::DestinationNotAllowed);
}
diff --git a/docs/content/go-components.md b/docs/content/go-components.md
index d1e365b408..d858c2f3e8 100644
--- a/docs/content/go-components.md
+++ b/docs/content/go-components.md
@@ -113,7 +113,7 @@ $ tinygo build -wasm-abi=generic -target=wasi -no-debug -o main.wasm main.go
```
Before we can execute this component, we need to add the
-`https://some-random-api.ml` domain to the application manifest `allowed_http_hosts`
+`some-random-api.ml` domain to the application manifest `allowed_http_hosts`
list containing the list of domains the component is allowed to make HTTP
requests to:
@@ -127,7 +127,7 @@ version = "1.0.0"
[[component]]
id = "tinygo-hello"
source = "main.wasm"
-allowed_http_hosts = [ "https://some-random-api.ml" ]
+allowed_http_hosts = [ "some-random-api.ml" ]
[component.trigger]
route = "/hello"
```
diff --git a/docs/content/rust-components.md b/docs/content/rust-components.md
index 1bdf0b62be..ed3dfb175f 100644
--- a/docs/content/rust-components.md
+++ b/docs/content/rust-components.md
@@ -88,7 +88,7 @@ fn hello_world(_req: Request) -> Result<Response> {
}
```
-Before we can execute this component, we need to add the `https://some-random-api.ml`
+Before we can execute this component, we need to add the `some-random-api.ml`
domain to the application manifest `allowed_http_hosts` list containing the list of
domains the component is allowed to make HTTP requests to:
@@ -102,7 +102,7 @@ version = "1.0.0"
[[component]]
id = "hello"
source = "target/wasm32-wasi/release/spinhelloworld.wasm"
-allowed_http_hosts = [ "https://some-random-api.ml" ]
+allowed_http_hosts = [ "some-random-api.ml" ]
[component.trigger]
route = "/hello"
```
| 727
|
[
"720"
] |
diff --git a/crates/loader/src/local/tests.rs b/crates/loader/src/local/tests.rs
index a52c012063..3ffe3a2abe 100644
--- a/crates/loader/src/local/tests.rs
+++ b/crates/loader/src/local/tests.rs
@@ -185,15 +185,16 @@ async fn test_invalid_url_in_allowed_http_hosts_is_rejected() -> Result<()> {
let dir = temp_dir.path();
let app = from_file(MANIFEST, dir, &None, false).await;
- assert!(
- app.is_err(),
- "Expected url can be parsed by reqwest Url, but there was invalid url"
- );
+ assert!(app.is_err(), "Expected allowed_http_hosts parsing error");
let e = app.unwrap_err().to_string();
assert!(
- e.contains("some-random-api.ml"),
- "Expected error to contain invalid url `some-random-api.ml`"
+ e.contains("ftp://some-random-api.ml"),
+ "Expected allowed_http_hosts parse error to contain `ftp://some-random-api.ml`"
+ );
+ assert!(
+ e.contains("example.com/wib/wob"),
+ "Expected allowed_http_hosts parse error to contain `example.com/wib/wob`"
);
Ok(())
diff --git a/crates/loader/tests/invalid-url-in-allowed-http-hosts.toml b/crates/loader/tests/invalid-url-in-allowed-http-hosts.toml
index a2de6fd7f8..6d8554c58c 100644
--- a/crates/loader/tests/invalid-url-in-allowed-http-hosts.toml
+++ b/crates/loader/tests/invalid-url-in-allowed-http-hosts.toml
@@ -6,6 +6,6 @@ trigger = { type = "http", base = "/" }
[[component]]
id = "hello"
source = "path/to/wasm/file.wasm"
-allowed_http_hosts = [ "some-random-api.ml" ]
+allowed_http_hosts = [ "ftp://some-random-api.ml", "example.com/wib/wob" ]
[component.trigger]
route = "/hello"
|
e8b6667af92152971faf96e53669531c45b55c1d
|
d4678db4948a8ef8a87f0005ae7e12321085415d
|
Test: Feature gate the e2e tests
(Where e2e tests refer to all of the currently-named integration tests that rely on dependencies such as the `bindle-server`, `nomad` and `Hippo.Web` binaries.)
Can we feature gate the newly added tests? Something like,
```rust
#[cfg(feature = "e2e-tests")]
mod e2e {
... all new test code goes here ...
}
```
Then adding the feature to Cargo.toml:
```toml
...
[features]
e2e-tests = []
```
Add a make target for `test-e2e` that invokes the test with the e2e-tests feature enabled.
Why? This way the original integration tests can be run locally until we figure how to
ensure the installation of e2e prerequisites.
_Originally posted by @fibonacci1729 in https://github.com/fermyon/spin/issues/607#issuecomment-1179282331_
|
Hey @vdice and @fibonacci1729. I am happy to take this one on.
|
2022-08-10T22:25:15Z
|
fermyon__spin-681
|
fermyon/spin
|
0.4
|
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 3d6ce3d90f..a0a6692d84 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -124,7 +124,7 @@ jobs:
- name: Cargo Test
run: |
make test-unit
- make test-integration
+ make test-e2e
env:
RUST_LOG: spin=trace
diff --git a/Cargo.toml b/Cargo.toml
index 1e977c3b2e..67fed7e347 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -63,6 +63,10 @@ which = "4.2.5"
cargo-target-dep = { git = "https://github.com/fermyon/cargo-target-dep", rev = "b7b1989fe0984c0f7c4966398304c6538e52fe49" }
vergen = { version = "7", default-features = false, features = [ "build", "git" ] }
+[features]
+default = []
+e2e-tests = []
+
[workspace]
members = [
"crates/build",
diff --git a/Makefile b/Makefile
index 22ea4308ef..9f90e8f4b6 100644
--- a/Makefile
+++ b/Makefile
@@ -20,8 +20,12 @@ test-unit:
.PHONY: test-integration
test-integration:
- RUST_LOG=$(LOG_LEVEL) cargo test --test integration --no-fail-fast -- integration_tests::test_dependencies --nocapture
- RUST_LOG=$(LOG_LEVEL) cargo test --test integration --no-fail-fast -- --skip integration_tests::test_dependencies --nocapture --include-ignored
+ RUST_LOG=$(LOG_LEVEL) cargo test --test integration --no-fail-fast -- --nocapture --include-ignored
+
+.PHONY: test-e2e
+test-e2e:
+ RUST_LOG=$(LOG_LEVEL) cargo test --test integration --features e2e-tests --no-fail-fast -- integration_tests::test_dependencies --nocapture
+ RUST_LOG=$(LOG_LEVEL) cargo test --test integration --features e2e-tests --no-fail-fast -- --skip integration_tests::test_dependencies --nocapture --include-ignored
.PHONY: test-sdk-go
test-sdk-go:
| 681
|
[
"626"
] |
diff --git a/tests/integration.rs b/tests/integration.rs
index a0031e9f18..89f8047189 100644
--- a/tests/integration.rs
+++ b/tests/integration.rs
@@ -1,7 +1,7 @@
#[cfg(test)]
mod integration_tests {
use anyhow::{Context, Result};
- use hyper::{header::HeaderName, Body, Client, Response};
+ use hyper::{Body, Client, Response};
use spin_loader::local::{
config::{RawAppManifestAnyVersion, RawModuleSource},
raw_manifest_from_file,
@@ -9,306 +9,594 @@ mod integration_tests {
use std::{
ffi::OsStr,
net::{Ipv4Addr, SocketAddrV4, TcpListener},
- path::{Path, PathBuf},
+ path::Path,
process::{self, Child, Command},
time::Duration,
};
- use tempfile::TempDir;
use tokio::{net::TcpStream, time::sleep};
- use which::which;
const RUST_HTTP_INTEGRATION_TEST: &str = "tests/http/simple-spin-rust";
- const RUST_HTTP_INTEGRATION_TEST_REF: &str = "spin-hello-world/1.0.0";
-
const RUST_HTTP_STATIC_ASSETS_TEST: &str = "tests/http/assets-test";
- const RUST_HTTP_STATIC_ASSETS_REST_REF: &str = "spin-assets-test/1.0.0";
-
- const RUST_HTTP_HEADERS_ENV_ROUTES_TEST: &str = "tests/http/headers-env-routes-test";
- const RUST_HTTP_HEADERS_ENV_ROUTES_TEST_REF: &str = "spin-headers-env-routes-test/1.0.0";
const DEFAULT_MANIFEST_LOCATION: &str = "spin.toml";
const SPIN_BINARY: &str = "./target/debug/spin";
- const BINDLE_SERVER_BINARY: &str = "bindle-server";
- const NOMAD_BINARY: &str = "nomad";
- const HIPPO_BINARY: &str = "Hippo.Web";
- const BINDLE_SERVER_PATH_ENV: &str = "SPIN_TEST_BINDLE_SERVER_PATH";
- const BINDLE_SERVER_BASIC_AUTH_HTPASSWD_FILE: &str = "tests/http/htpasswd";
- const BINDLE_SERVER_BASIC_AUTH_USER: &str = "bindle-user";
- const BINDLE_SERVER_BASIC_AUTH_PASSWORD: &str = "topsecret";
+ // This module consist of all integration tests that require dependencies such as bindle-server, nomad, and Hippo.Web to be installed.
+ #[cfg(feature = "e2e-tests")]
+ mod e2e_tests {
+ use super::*;
+ use hyper::header::HeaderName;
+ use std::path::PathBuf;
+ use tempfile::TempDir;
+ use which::which;
- const HIPPO_BASIC_AUTH_USER: &str = "hippo-user";
- const HIPPO_BASIC_AUTH_PASSWORD: &str = "topsecret";
+ const RUST_HTTP_INTEGRATION_TEST_REF: &str = "spin-hello-world/1.0.0";
- // This assumes all tests have been previously compiled by the top-level build script.
+ const RUST_HTTP_STATIC_ASSETS_REST_REF: &str = "spin-assets-test/1.0.0";
- #[tokio::test]
- async fn test_dependencies() -> Result<()> {
- which(get_process(BINDLE_SERVER_BINARY))
- .with_context(|| format!("Can't find {}", get_process(BINDLE_SERVER_BINARY)))?;
- which(get_process(NOMAD_BINARY))
- .with_context(|| format!("Can't find {}", get_process(NOMAD_BINARY)))?;
- which(get_process(HIPPO_BINARY))
- .with_context(|| format!("Can't find {}", get_process(HIPPO_BINARY)))?;
+ const RUST_HTTP_HEADERS_ENV_ROUTES_TEST: &str = "tests/http/headers-env-routes-test";
+ const RUST_HTTP_HEADERS_ENV_ROUTES_TEST_REF: &str = "spin-headers-env-routes-test/1.0.0";
- Ok(())
- }
+ const BINDLE_SERVER_BINARY: &str = "bindle-server";
+ const NOMAD_BINARY: &str = "nomad";
+ const HIPPO_BINARY: &str = "Hippo.Web";
- #[tokio::test]
- async fn test_simple_rust_local() -> Result<()> {
- let s = SpinTestController::with_manifest(
- &format!(
- "{}/{}",
- RUST_HTTP_INTEGRATION_TEST, DEFAULT_MANIFEST_LOCATION
- ),
- &[],
- None,
- )
- .await?;
+ const BINDLE_SERVER_PATH_ENV: &str = "SPIN_TEST_BINDLE_SERVER_PATH";
+ const BINDLE_SERVER_BASIC_AUTH_HTPASSWD_FILE: &str = "tests/http/htpasswd";
+ const BINDLE_SERVER_BASIC_AUTH_USER: &str = "bindle-user";
+ const BINDLE_SERVER_BASIC_AUTH_PASSWORD: &str = "topsecret";
- assert_status(&s, "/test/hello", 200).await?;
- assert_status(&s, "/test/hello/wildcards/should/be/handled", 200).await?;
- assert_status(&s, "/thisshouldfail", 404).await?;
- assert_status(&s, "/test/hello/test-placement", 200).await?;
+ const HIPPO_BASIC_AUTH_USER: &str = "hippo-user";
+ const HIPPO_BASIC_AUTH_PASSWORD: &str = "topsecret";
- Ok(())
- }
+ // This assumes all tests have been previously compiled by the top-level build script.
- #[tokio::test]
- async fn test_bindle_roundtrip_no_auth() -> Result<()> {
- // start the Bindle registry.
- let config = BindleTestControllerConfig {
- basic_auth_enabled: false,
- };
- let b = BindleTestController::new(config).await?;
+ #[tokio::test]
+ async fn test_dependencies() -> Result<()> {
+ which(get_process(BINDLE_SERVER_BINARY))
+ .with_context(|| format!("Can't find {}", get_process(BINDLE_SERVER_BINARY)))?;
+ which(get_process(NOMAD_BINARY))
+ .with_context(|| format!("Can't find {}", get_process(NOMAD_BINARY)))?;
+ which(get_process(HIPPO_BINARY))
+ .with_context(|| format!("Can't find {}", get_process(HIPPO_BINARY)))?;
- // push the application to the registry using the Spin CLI.
- run(
- vec![
- SPIN_BINARY,
- "bindle",
- "push",
- "--file",
- &format!(
- "{}/{}",
- RUST_HTTP_INTEGRATION_TEST, DEFAULT_MANIFEST_LOCATION
- ),
- "--bindle-server",
- &b.url,
- ],
- None,
- )?;
+ Ok(())
+ }
- // start Spin using the bindle reference of the application that was just pushed.
- let s =
- SpinTestController::with_bindle(RUST_HTTP_INTEGRATION_TEST_REF, &b.url, &[]).await?;
+ #[tokio::test]
+ async fn test_bindle_roundtrip_no_auth() -> Result<()> {
+ // start the Bindle registry.
+ let config = BindleTestControllerConfig {
+ basic_auth_enabled: false,
+ };
+ let b = BindleTestController::new(config).await?;
+
+ // push the application to the registry using the Spin CLI.
+ run(
+ vec![
+ SPIN_BINARY,
+ "bindle",
+ "push",
+ "--file",
+ &format!(
+ "{}/{}",
+ RUST_HTTP_INTEGRATION_TEST, DEFAULT_MANIFEST_LOCATION
+ ),
+ "--bindle-server",
+ &b.url,
+ ],
+ None,
+ )?;
+
+ // start Spin using the bindle reference of the application that was just pushed.
+ let s = SpinTestController::with_bindle(RUST_HTTP_INTEGRATION_TEST_REF, &b.url, &[])
+ .await?;
- assert_status(&s, "/test/hello", 200).await?;
- assert_status(&s, "/test/hello/wildcards/should/be/handled", 200).await?;
- assert_status(&s, "/thisshouldfail", 404).await?;
+ assert_status(&s, "/test/hello", 200).await?;
+ assert_status(&s, "/test/hello/wildcards/should/be/handled", 200).await?;
+ assert_status(&s, "/thisshouldfail", 404).await?;
- Ok(())
- }
+ Ok(())
+ }
- #[tokio::test]
- async fn test_bindle_roundtrip_basic_auth() -> Result<()> {
- // start the Bindle registry.
- let config = BindleTestControllerConfig {
- basic_auth_enabled: true,
- };
- let b = BindleTestController::new(config).await?;
+ #[tokio::test]
+ async fn test_bindle_roundtrip_basic_auth() -> Result<()> {
+ // start the Bindle registry.
+ let config = BindleTestControllerConfig {
+ basic_auth_enabled: true,
+ };
+ let b = BindleTestController::new(config).await?;
+
+ // push the application to the registry using the Spin CLI.
+ run(
+ vec![
+ SPIN_BINARY,
+ "bindle",
+ "push",
+ "--file",
+ &format!(
+ "{}/{}",
+ RUST_HTTP_INTEGRATION_TEST, DEFAULT_MANIFEST_LOCATION
+ ),
+ "--bindle-server",
+ &b.url,
+ "--bindle-username",
+ BINDLE_SERVER_BASIC_AUTH_USER,
+ "--bindle-password",
+ BINDLE_SERVER_BASIC_AUTH_PASSWORD,
+ ],
+ None,
+ )?;
+
+ // start Spin using the bindle reference of the application that was just pushed.
+ let s = SpinTestController::with_bindle(RUST_HTTP_INTEGRATION_TEST_REF, &b.url, &[])
+ .await?;
- // push the application to the registry using the Spin CLI.
- run(
- vec![
- SPIN_BINARY,
- "bindle",
- "push",
- "--file",
- &format!(
- "{}/{}",
- RUST_HTTP_INTEGRATION_TEST, DEFAULT_MANIFEST_LOCATION
- ),
- "--bindle-server",
- &b.url,
- "--bindle-username",
- BINDLE_SERVER_BASIC_AUTH_USER,
- "--bindle-password",
- BINDLE_SERVER_BASIC_AUTH_PASSWORD,
- ],
- None,
- )?;
+ assert_status(&s, "/test/hello", 200).await?;
+ assert_status(&s, "/test/hello/wildcards/should/be/handled", 200).await?;
+ assert_status(&s, "/thisshouldfail", 404).await?;
- // start Spin using the bindle reference of the application that was just pushed.
- let s =
- SpinTestController::with_bindle(RUST_HTTP_INTEGRATION_TEST_REF, &b.url, &[]).await?;
+ Ok(())
+ }
- assert_status(&s, "/test/hello", 200).await?;
- assert_status(&s, "/test/hello/wildcards/should/be/handled", 200).await?;
- assert_status(&s, "/thisshouldfail", 404).await?;
+ #[tokio::test]
+ async fn test_bindle_static_assets() -> Result<()> {
+ // start the Bindle registry.
+ let config = BindleTestControllerConfig {
+ basic_auth_enabled: false,
+ };
+ let b = BindleTestController::new(config).await?;
+
+ // push the application to the registry using the Spin CLI.
+ run(
+ vec![
+ SPIN_BINARY,
+ "bindle",
+ "push",
+ "--file",
+ &format!(
+ "{}/{}",
+ RUST_HTTP_STATIC_ASSETS_TEST, DEFAULT_MANIFEST_LOCATION
+ ),
+ "--bindle-server",
+ &b.url,
+ ],
+ None,
+ )?;
+
+ // start Spin using the bindle reference of the application that was just pushed.
+ let s = SpinTestController::with_bindle(RUST_HTTP_STATIC_ASSETS_REST_REF, &b.url, &[])
+ .await?;
- Ok(())
- }
+ assert_status(&s, "/static/thisshouldbemounted/1", 200).await?;
+ assert_status(&s, "/static/thisshouldbemounted/2", 200).await?;
+ assert_status(&s, "/static/thisshouldbemounted/3", 200).await?;
- #[tokio::test]
- async fn test_bindle_static_assets() -> Result<()> {
- // start the Bindle registry.
- let config = BindleTestControllerConfig {
- basic_auth_enabled: false,
- };
- let b = BindleTestController::new(config).await?;
+ assert_status(&s, "/static/donotmount/a", 404).await?;
+ assert_status(
+ &s,
+ "/static/thisshouldbemounted/thisshouldbeexcluded/4",
+ 404,
+ )
+ .await?;
- // push the application to the registry using the Spin CLI.
- run(
- vec![
- SPIN_BINARY,
- "bindle",
- "push",
- "--file",
- &format!(
- "{}/{}",
- RUST_HTTP_STATIC_ASSETS_TEST, DEFAULT_MANIFEST_LOCATION
- ),
- "--bindle-server",
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn test_headers_env_routes() -> Result<()> {
+ // start the Bindle registry.
+ let config = BindleTestControllerConfig {
+ basic_auth_enabled: false,
+ };
+ let b = BindleTestController::new(config).await?;
+
+ // push the application to the registry using the Spin CLI.
+ run(
+ vec![
+ SPIN_BINARY,
+ "bindle",
+ "push",
+ "--file",
+ &format!(
+ "{}/{}",
+ RUST_HTTP_HEADERS_ENV_ROUTES_TEST, DEFAULT_MANIFEST_LOCATION
+ ),
+ "--bindle-server",
+ &b.url,
+ ],
+ None,
+ )?;
+
+ // start Spin using the bindle reference of the application that was just pushed.
+ let s = SpinTestController::with_bindle(
+ RUST_HTTP_HEADERS_ENV_ROUTES_TEST_REF,
&b.url,
- ],
- None,
- )?;
+ &["foo=bar"],
+ )
+ .await?;
+
+ assert_status(&s, "/env", 200).await?;
+
+ verify_headers(
+ &s,
+ "/env/foo",
+ 200,
+ &[("env_foo", "bar"), ("env_some_key", "some_value")],
+ "/foo",
+ )
+ .await?;
+
+ Ok(())
+ }
- // start Spin using the bindle reference of the application that was just pushed.
- let s =
- SpinTestController::with_bindle(RUST_HTTP_STATIC_ASSETS_REST_REF, &b.url, &[]).await?;
+ #[tokio::test]
+ async fn test_using_parcel_as_module_source() -> Result<()> {
+ let wasm_path = PathBuf::from(RUST_HTTP_INTEGRATION_TEST)
+ .join("target")
+ .join("wasm32-wasi")
+ .join("release")
+ .join("spinhelloworld.wasm");
+ let parcel_sha = file_digest_string(&wasm_path).expect("failed to get sha for parcel");
+
+ // start the Bindle registry.
+ let config = BindleTestControllerConfig {
+ basic_auth_enabled: false,
+ };
+ let b = BindleTestController::new(config).await?;
+
+ // push the application to the registry using the Spin CLI.
+ run(
+ vec![
+ SPIN_BINARY,
+ "bindle",
+ "push",
+ "--file",
+ &format!(
+ "{}/{}",
+ RUST_HTTP_INTEGRATION_TEST, DEFAULT_MANIFEST_LOCATION
+ ),
+ "--bindle-server",
+ &b.url,
+ ],
+ None,
+ )?;
+
+ let manifest_template =
+ format!("{}/{}", RUST_HTTP_INTEGRATION_TEST, "spin-from-parcel.toml");
+ let manifest = replace_text(&manifest_template, "AWAITING_PARCEL_SHA", &parcel_sha);
+
+ let s = SpinTestController::with_manifest(
+ &format!("{}", manifest.path.display()),
+ &[],
+ Some(&b.url),
+ )
+ .await?;
+
+ assert_status(&s, "/test/hello", 200).await?;
+ assert_status(&s, "/test/hello/wildcards/should/be/handled", 200).await?;
+ assert_status(&s, "/thisshouldfail", 404).await?;
+ assert_status(&s, "/test/hello/test-placement", 200).await?;
+
+ Ok(())
+ }
- assert_status(&s, "/static/thisshouldbemounted/1", 200).await?;
- assert_status(&s, "/static/thisshouldbemounted/2", 200).await?;
- assert_status(&s, "/static/thisshouldbemounted/3", 200).await?;
+ #[tokio::test]
+ async fn test_spin_deploy() -> Result<()> {
+ println!("Testng spin deploy");
+ // start the Bindle registry.
+ let config = BindleTestControllerConfig {
+ basic_auth_enabled: false,
+ };
+ let _nomad = NomadTestController::new().await?;
+ let bindle = BindleTestController::new(config).await?;
+ let hippo = HippoTestController::new(&bindle.url).await?;
+
+ // push the application to the registry using the Spin CLI.
+ run(
+ vec![
+ SPIN_BINARY,
+ "deploy",
+ "--file",
+ &format!(
+ "{}/{}",
+ RUST_HTTP_HEADERS_ENV_ROUTES_TEST, DEFAULT_MANIFEST_LOCATION
+ ),
+ "--bindle-server",
+ &bindle.url,
+ "--hippo-server",
+ &hippo.url,
+ "--hippo-username",
+ HIPPO_BASIC_AUTH_USER,
+ "--hippo-password",
+ HIPPO_BASIC_AUTH_PASSWORD,
+ ],
+ None,
+ )?;
+
+ let apps_vm = hippo.client.list_apps().await?;
+ assert_eq!(apps_vm.apps.len(), 1, "hippo apps: {apps_vm:?}");
+
+ Ok(())
+ }
- assert_status(&s, "/static/donotmount/a", 404).await?;
- assert_status(
- &s,
- "/static/thisshouldbemounted/thisshouldbeexcluded/4",
- 404,
- )
- .await?;
+ async fn verify_headers(
+ s: &SpinTestController,
+ absolute_uri: &str,
+ expected: u16,
+ expected_env_as_headers: &[(&str, &str)],
+ expected_path_info: &str,
+ ) -> Result<()> {
+ let res = req(s, absolute_uri).await?;
+ assert_eq!(res.status(), expected);
+
+ // check the environment variables sent back as headers:
+ for (k, v) in expected_env_as_headers {
+ assert_eq!(
+ &res.headers()
+ .get(HeaderName::from_bytes(k.as_bytes())?)
+ .unwrap_or_else(|| panic!("cannot find header {}", k))
+ .to_str()?,
+ v
+ );
+ }
- Ok(())
- }
+ assert_eq!(
+ res.headers()
+ .get(HeaderName::from_bytes("spin-path-info".as_bytes())?)
+ .unwrap_or_else(|| panic!("cannot find spin-path-info header"))
+ .to_str()?,
+ expected_path_info
+ );
- #[tokio::test]
- async fn test_static_assets_without_bindle() -> Result<()> {
- let s = SpinTestController::with_manifest(
- &format!(
- "{}/{}",
- RUST_HTTP_STATIC_ASSETS_TEST, DEFAULT_MANIFEST_LOCATION
- ),
- &[],
- None,
- )
- .await?;
+ Ok(())
+ }
- assert_status(&s, "/static/thisshouldbemounted/1", 200).await?;
- assert_status(&s, "/static/thisshouldbemounted/2", 200).await?;
- assert_status(&s, "/static/thisshouldbemounted/3", 200).await?;
+ /// Controller for running a Bindle server.
+ /// This assumes `bindle-server` is present in the path.
+ pub struct BindleTestController {
+ pub url: String,
+ pub server_cache: TempDir,
+ server_handle: Child,
+ }
- assert_status(&s, "/static/donotmount/a", 404).await?;
- assert_status(
- &s,
- "/static/thisshouldbemounted/thisshouldbeexcluded/4",
- 404,
- )
- .await?;
+ /// Config for the BindleTestController
+ pub struct BindleTestControllerConfig {
+ pub basic_auth_enabled: bool,
+ }
- Ok(())
- }
+ impl BindleTestController {
+ pub async fn new(config: BindleTestControllerConfig) -> Result<BindleTestController> {
+ let server_cache = tempfile::tempdir()?;
+
+ let address = format!("127.0.0.1:{}", get_random_port()?);
+ let url = format!("http://{}/v1/", address);
+
+ let bindle_server_binary = std::env::var(BINDLE_SERVER_PATH_ENV)
+ .unwrap_or_else(|_| BINDLE_SERVER_BINARY.to_owned());
+
+ let auth_args = match config.basic_auth_enabled {
+ true => vec!["--htpasswd-file", BINDLE_SERVER_BASIC_AUTH_HTPASSWD_FILE],
+ false => vec!["--unauthenticated"],
+ };
+
+ let server_handle_result = Command::new(&bindle_server_binary)
+ .args(
+ [
+ &[
+ "-d",
+ server_cache.path().to_string_lossy().to_string().as_str(),
+ "-i",
+ address.as_str(),
+ ],
+ auth_args.as_slice(),
+ ]
+ .concat(),
+ )
+ .spawn();
+
+ let mut server_handle = match server_handle_result {
+ Ok(h) => Ok(h),
+ Err(e) => {
+ let is_path_explicit = std::env::var(BINDLE_SERVER_PATH_ENV).is_ok();
+ let context = match e.kind() {
+ std::io::ErrorKind::NotFound => {
+ if is_path_explicit {
+ format!(
+ "executing {}: is the path/filename correct?",
+ bindle_server_binary
+ )
+ } else {
+ format!(
+ "executing {}: is binary on PATH?",
+ bindle_server_binary
+ )
+ }
+ }
+ _ => format!("executing {}", bindle_server_binary),
+ };
+ Err(e).context(context)
+ }
+ }?;
- #[tokio::test]
- async fn test_headers_env_routes() -> Result<()> {
- // start the Bindle registry.
- let config = BindleTestControllerConfig {
- basic_auth_enabled: false,
- };
- let b = BindleTestController::new(config).await?;
+ wait_tcp(&address, &mut server_handle, BINDLE_SERVER_BINARY).await?;
- // push the application to the registry using the Spin CLI.
- run(
- vec![
- SPIN_BINARY,
- "bindle",
- "push",
- "--file",
- &format!(
- "{}/{}",
- RUST_HTTP_HEADERS_ENV_ROUTES_TEST, DEFAULT_MANIFEST_LOCATION
- ),
- "--bindle-server",
- &b.url,
- ],
- None,
- )?;
+ Ok(Self {
+ url,
+ server_handle,
+ server_cache,
+ })
+ }
+ }
- // start Spin using the bindle reference of the application that was just pushed.
- let s = SpinTestController::with_bindle(
- RUST_HTTP_HEADERS_ENV_ROUTES_TEST_REF,
- &b.url,
- &["foo=bar"],
- )
- .await?;
+ impl Drop for BindleTestController {
+ fn drop(&mut self) {
+ let _ = self.server_handle.kill();
+ }
+ }
- assert_status(&s, "/env", 200).await?;
+ /// Controller for running Nomad.
+ pub struct NomadTestController {
+ pub url: String,
+ nomad_handle: Child,
+ }
- verify_headers(
- &s,
- "/env/foo",
- 200,
- &[("env_foo", "bar"), ("env_some_key", "some_value")],
- "/foo",
- )
- .await?;
+ impl NomadTestController {
+ pub async fn new() -> Result<NomadTestController> {
+ let url = "127.0.0.1:4646".to_string();
- Ok(())
- }
+ let mut nomad_handle = Command::new(get_process(NOMAD_BINARY))
+ .args(["agent", "-dev"])
+ .spawn()
+ .with_context(|| "executing nomad")?;
- #[tokio::test]
- async fn test_using_parcel_as_module_source() -> Result<()> {
- let wasm_path = PathBuf::from(RUST_HTTP_INTEGRATION_TEST)
- .join("target")
- .join("wasm32-wasi")
- .join("release")
- .join("spinhelloworld.wasm");
- let parcel_sha = file_digest_string(&wasm_path).expect("failed to get sha for parcel");
-
- // start the Bindle registry.
- let config = BindleTestControllerConfig {
- basic_auth_enabled: false,
- };
- let b = BindleTestController::new(config).await?;
+ wait_tcp(&url, &mut nomad_handle, NOMAD_BINARY).await?;
- // push the application to the registry using the Spin CLI.
- run(
- vec![
- SPIN_BINARY,
- "bindle",
- "push",
- "--file",
- &format!(
- "{}/{}",
- RUST_HTTP_INTEGRATION_TEST, DEFAULT_MANIFEST_LOCATION
- ),
- "--bindle-server",
- &b.url,
- ],
- None,
- )?;
+ Ok(Self { url, nomad_handle })
+ }
+ }
- let manifest_template =
- format!("{}/{}", RUST_HTTP_INTEGRATION_TEST, "spin-from-parcel.toml");
- let manifest = replace_text(&manifest_template, "AWAITING_PARCEL_SHA", &parcel_sha);
+ impl Drop for NomadTestController {
+ fn drop(&mut self) {
+ let _ = self.nomad_handle.kill();
+ }
+ }
+ /// Controller for running Hippo.
+ pub struct HippoTestController {
+ pub url: String,
+ pub client: hippo::Client,
+ hippo_handle: Child,
+ }
+
+ impl HippoTestController {
+ pub async fn new(bindle_url: &str) -> Result<HippoTestController> {
+ let url = format!("http://127.0.0.1:{}", get_random_port()?);
+
+ let mut hippo_handle = Command::new(get_process(HIPPO_BINARY))
+ .env("ASPNETCORE_URLS", &url)
+ .env("Nomad__Driver", "raw_exec")
+ .env("Nomad__Datacenters__0", "dc1")
+ .env("Database__Driver", "inmemory")
+ .env("ConnectionStrings__Bindle", format!("Address={bindle_url}"))
+ .env("Jwt__Key", "ceci n'est pas une jeton")
+ .env("Jwt__Issuer", "localhost")
+ .env("Jwt__Audience", "localhost")
+ .spawn()
+ .with_context(|| "executing hippo")?;
+
+ wait_hippo(&url, &mut hippo_handle, HIPPO_BINARY).await?;
+
+ let client = hippo::Client::new(hippo::ConnectionInfo {
+ url: url.clone(),
+ danger_accept_invalid_certs: true,
+ api_key: None,
+ });
+ client
+ .register(
+ HIPPO_BASIC_AUTH_USER.into(),
+ HIPPO_BASIC_AUTH_PASSWORD.into(),
+ )
+ .await?;
+ let token_info = client
+ .login(
+ HIPPO_BASIC_AUTH_USER.into(),
+ HIPPO_BASIC_AUTH_PASSWORD.into(),
+ )
+ .await?;
+ let client = hippo::Client::new(hippo::ConnectionInfo {
+ url: url.clone(),
+ danger_accept_invalid_certs: true,
+ api_key: token_info.token,
+ });
+
+ Ok(Self {
+ url,
+ client,
+ hippo_handle,
+ })
+ }
+ }
+
+ impl Drop for HippoTestController {
+ fn drop(&mut self) {
+ let _ = self.hippo_handle.kill();
+ }
+ }
+
+ async fn wait_hippo(url: &str, process: &mut Child, target: &str) -> Result<()> {
+ println!("hippo url is {} and process is {:?}", url, process);
+ let mut wait_count = 0;
+ loop {
+ if wait_count >= 120 {
+ panic!(
+ "Ran out of retries waiting for {} to start on URL {}",
+ target, url
+ );
+ }
+
+ if let Ok(Some(_)) = process.try_wait() {
+ panic!(
+ "Process exited before starting to serve {} to start on URL {}",
+ target, url
+ );
+ }
+
+ if let Ok(rsp) = reqwest::get(format!("{url}/healthz")).await {
+ if let Ok(result) = rsp.text().await {
+ if result == "Healthy" {
+ break;
+ }
+ }
+ }
+
+ wait_count += 1;
+ sleep(Duration::from_secs(1)).await;
+ }
+
+ Ok(())
+ }
+
+ fn file_digest_string(path: impl AsRef<Path>) -> Result<String> {
+ use sha2::{Digest, Sha256};
+ let mut file = std::fs::File::open(&path)?;
+ let mut sha = Sha256::new();
+ std::io::copy(&mut file, &mut sha)?;
+ let digest_value = sha.finalize();
+ let digest_string = format!("{:x}", digest_value);
+ Ok(digest_string)
+ }
+
+ struct AutoDeleteFile {
+ pub path: PathBuf,
+ }
+
+ fn replace_text(template_path: impl AsRef<Path>, from: &str, to: &str) -> AutoDeleteFile {
+ let dest = template_path.as_ref().with_extension("temp");
+ let source_text =
+ std::fs::read_to_string(template_path).expect("failed to read manifest template");
+ let result_text = source_text.replace(from, to);
+ std::fs::write(&dest, result_text).expect("failed to write temp manifest");
+ AutoDeleteFile { path: dest }
+ }
+
+ impl Drop for AutoDeleteFile {
+ fn drop(&mut self) {
+ std::fs::remove_file(&self.path).unwrap();
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn test_simple_rust_local() -> Result<()> {
let s = SpinTestController::with_manifest(
- &format!("{}", manifest.path.display()),
+ &format!(
+ "{}/{}",
+ RUST_HTTP_INTEGRATION_TEST, DEFAULT_MANIFEST_LOCATION
+ ),
&[],
- Some(&b.url),
+ None,
)
.await?;
@@ -321,71 +609,28 @@ mod integration_tests {
}
#[tokio::test]
- async fn test_spin_deploy() -> Result<()> {
- // start the Bindle registry.
- let config = BindleTestControllerConfig {
- basic_auth_enabled: false,
- };
- let _nomad = NomadTestController::new().await?;
- let bindle = BindleTestController::new(config).await?;
- let hippo = HippoTestController::new(&bindle.url).await?;
-
- // push the application to the registry using the Spin CLI.
- run(
- vec![
- SPIN_BINARY,
- "deploy",
- "--file",
- &format!(
- "{}/{}",
- RUST_HTTP_HEADERS_ENV_ROUTES_TEST, DEFAULT_MANIFEST_LOCATION
- ),
- "--bindle-server",
- &bindle.url,
- "--hippo-server",
- &hippo.url,
- "--hippo-username",
- HIPPO_BASIC_AUTH_USER,
- "--hippo-password",
- HIPPO_BASIC_AUTH_PASSWORD,
- ],
+ async fn test_static_assets_without_bindle() -> Result<()> {
+ let s = SpinTestController::with_manifest(
+ &format!(
+ "{}/{}",
+ RUST_HTTP_STATIC_ASSETS_TEST, DEFAULT_MANIFEST_LOCATION
+ ),
+ &[],
None,
- )?;
-
- let apps_vm = hippo.client.list_apps().await?;
- assert_eq!(apps_vm.apps.len(), 1, "hippo apps: {apps_vm:?}");
-
- Ok(())
- }
-
- async fn verify_headers(
- s: &SpinTestController,
- absolute_uri: &str,
- expected: u16,
- expected_env_as_headers: &[(&str, &str)],
- expected_path_info: &str,
- ) -> Result<()> {
- let res = req(s, absolute_uri).await?;
- assert_eq!(res.status(), expected);
+ )
+ .await?;
- // check the environment variables sent back as headers:
- for (k, v) in expected_env_as_headers {
- assert_eq!(
- &res.headers()
- .get(HeaderName::from_bytes(k.as_bytes())?)
- .unwrap_or_else(|| panic!("cannot find header {}", k))
- .to_str()?,
- v
- );
- }
+ assert_status(&s, "/static/thisshouldbemounted/1", 200).await?;
+ assert_status(&s, "/static/thisshouldbemounted/2", 200).await?;
+ assert_status(&s, "/static/thisshouldbemounted/3", 200).await?;
- assert_eq!(
- res.headers()
- .get(HeaderName::from_bytes("spin-path-info".as_bytes())?)
- .unwrap_or_else(|| panic!("cannot find spin-path-info header"))
- .to_str()?,
- expected_path_info
- );
+ assert_status(&s, "/static/donotmount/a", 404).await?;
+ assert_status(
+ &s,
+ "/static/thisshouldbemounted/thisshouldbeexcluded/4",
+ 404,
+ )
+ .await?;
Ok(())
}
@@ -449,6 +694,7 @@ mod integration_tests {
}
// Unfortunately, this is a lot of duplicated code.
+ #[cfg(feature = "e2e-tests")]
pub async fn with_bindle(
id: &str,
bindle_url: &str,
@@ -491,175 +737,6 @@ mod integration_tests {
}
}
- /// Controller for running a Bindle server.
- /// This assumes `bindle-server` is present in the path.
- pub struct BindleTestController {
- pub url: String,
- pub server_cache: TempDir,
- server_handle: Child,
- }
-
- /// Config for the BindleTestController
- pub struct BindleTestControllerConfig {
- pub basic_auth_enabled: bool,
- }
-
- impl BindleTestController {
- pub async fn new(config: BindleTestControllerConfig) -> Result<BindleTestController> {
- let server_cache = tempfile::tempdir()?;
-
- let address = format!("127.0.0.1:{}", get_random_port()?);
- let url = format!("http://{}/v1/", address);
-
- let bindle_server_binary = std::env::var(BINDLE_SERVER_PATH_ENV)
- .unwrap_or_else(|_| BINDLE_SERVER_BINARY.to_owned());
-
- let auth_args = match config.basic_auth_enabled {
- true => vec!["--htpasswd-file", BINDLE_SERVER_BASIC_AUTH_HTPASSWD_FILE],
- false => vec!["--unauthenticated"],
- };
-
- let server_handle_result = Command::new(&bindle_server_binary)
- .args(
- [
- &[
- "-d",
- server_cache.path().to_string_lossy().to_string().as_str(),
- "-i",
- address.as_str(),
- ],
- auth_args.as_slice(),
- ]
- .concat(),
- )
- .spawn();
-
- let mut server_handle = match server_handle_result {
- Ok(h) => Ok(h),
- Err(e) => {
- let is_path_explicit = std::env::var(BINDLE_SERVER_PATH_ENV).is_ok();
- let context = match e.kind() {
- std::io::ErrorKind::NotFound => {
- if is_path_explicit {
- format!(
- "executing {}: is the path/filename correct?",
- bindle_server_binary
- )
- } else {
- format!("executing {}: is binary on PATH?", bindle_server_binary)
- }
- }
- _ => format!("executing {}", bindle_server_binary),
- };
- Err(e).context(context)
- }
- }?;
-
- wait_tcp(&address, &mut server_handle, BINDLE_SERVER_BINARY).await?;
-
- Ok(Self {
- url,
- server_handle,
- server_cache,
- })
- }
- }
-
- impl Drop for BindleTestController {
- fn drop(&mut self) {
- let _ = self.server_handle.kill();
- }
- }
-
- /// Controller for running Nomad.
- pub struct NomadTestController {
- pub url: String,
- nomad_handle: Child,
- }
-
- impl NomadTestController {
- pub async fn new() -> Result<NomadTestController> {
- let url = "127.0.0.1:4646".to_string();
-
- let mut nomad_handle = Command::new(get_process(NOMAD_BINARY))
- .args(["agent", "-dev"])
- .spawn()
- .with_context(|| "executing nomad")?;
-
- wait_tcp(&url, &mut nomad_handle, NOMAD_BINARY).await?;
-
- Ok(Self { url, nomad_handle })
- }
- }
-
- impl Drop for NomadTestController {
- fn drop(&mut self) {
- let _ = self.nomad_handle.kill();
- }
- }
-
- /// Controller for running Hippo.
- pub struct HippoTestController {
- pub url: String,
- pub client: hippo::Client,
- hippo_handle: Child,
- }
-
- impl HippoTestController {
- pub async fn new(bindle_url: &str) -> Result<HippoTestController> {
- let url = format!("http://127.0.0.1:{}", get_random_port()?);
-
- let mut hippo_handle = Command::new(get_process(HIPPO_BINARY))
- .env("ASPNETCORE_URLS", &url)
- .env("Nomad__Driver", "raw_exec")
- .env("Nomad__Datacenters__0", "dc1")
- .env("Database__Driver", "inmemory")
- .env("ConnectionStrings__Bindle", format!("Address={bindle_url}"))
- .env("Jwt__Key", "ceci n'est pas une jeton")
- .env("Jwt__Issuer", "localhost")
- .env("Jwt__Audience", "localhost")
- .spawn()
- .with_context(|| "executing hippo")?;
-
- wait_hippo(&url, &mut hippo_handle, HIPPO_BINARY).await?;
-
- let client = hippo::Client::new(hippo::ConnectionInfo {
- url: url.clone(),
- danger_accept_invalid_certs: true,
- api_key: None,
- });
- client
- .register(
- HIPPO_BASIC_AUTH_USER.into(),
- HIPPO_BASIC_AUTH_PASSWORD.into(),
- )
- .await?;
- let token_info = client
- .login(
- HIPPO_BASIC_AUTH_USER.into(),
- HIPPO_BASIC_AUTH_PASSWORD.into(),
- )
- .await?;
- let client = hippo::Client::new(hippo::ConnectionInfo {
- url: url.clone(),
- danger_accept_invalid_certs: true,
- api_key: token_info.token,
- });
-
- Ok(Self {
- url,
- client,
- hippo_handle,
- })
- }
- }
-
- impl Drop for HippoTestController {
- fn drop(&mut self) {
- let _ = self.hippo_handle.kill();
- }
- }
-
fn run<S: Into<String> + AsRef<OsStr>>(args: Vec<S>, dir: Option<S>) -> Result<()> {
let mut cmd = Command::new(get_os_process());
cmd.stdout(process::Stdio::piped());
@@ -742,67 +819,6 @@ mod integration_tests {
Ok(())
}
- async fn wait_hippo(url: &str, process: &mut Child, target: &str) -> Result<()> {
- let mut wait_count = 0;
- loop {
- if wait_count >= 120 {
- panic!(
- "Ran out of retries waiting for {} to start on URL {}",
- target, url
- );
- }
-
- if let Ok(Some(_)) = process.try_wait() {
- panic!(
- "Process exited before starting to serve {} to start on URL {}",
- target, url
- );
- }
-
- if let Ok(rsp) = reqwest::get(format!("{url}/healthz")).await {
- if let Ok(result) = rsp.text().await {
- if result == "Healthy" {
- break;
- }
- }
- }
-
- wait_count += 1;
- sleep(Duration::from_secs(1)).await;
- }
-
- Ok(())
- }
-
- fn file_digest_string(path: impl AsRef<Path>) -> Result<String> {
- use sha2::{Digest, Sha256};
- let mut file = std::fs::File::open(&path)?;
- let mut sha = Sha256::new();
- std::io::copy(&mut file, &mut sha)?;
- let digest_value = sha.finalize();
- let digest_string = format!("{:x}", digest_value);
- Ok(digest_string)
- }
-
- struct AutoDeleteFile {
- pub path: PathBuf,
- }
-
- fn replace_text(template_path: impl AsRef<Path>, from: &str, to: &str) -> AutoDeleteFile {
- let dest = template_path.as_ref().with_extension("temp");
- let source_text =
- std::fs::read_to_string(template_path).expect("failed to read manifest template");
- let result_text = source_text.replace(from, to);
- std::fs::write(&dest, result_text).expect("failed to write temp manifest");
- AutoDeleteFile { path: dest }
- }
-
- impl Drop for AutoDeleteFile {
- fn drop(&mut self) {
- std::fs::remove_file(&self.path).unwrap();
- }
- }
-
/// Builds app in `dir` and verifies the build succeeded. Expects manifest
/// in `spin.toml` inside `dir`.
async fn do_test_build_command(dir: impl AsRef<Path>) -> Result<()> {
|
e8b6667af92152971faf96e53669531c45b55c1d
|
8e8867af3994e2f0d66153f79299a41b3798ccf0
|
Add a way to exclude patterns from `files` patterns
Per https://github.com/fermyon/spin-fileserver/issues/11, it is easy to accidentally include unwanted files in a `files` glob pattern. We should think of a mechanism to exclude some files from a glob, perhaps something like a `exclude_files` pattern. It might be nice for this to even default to `["**/.*"]` or similar.
|
Poking around, it looks like this would mostly concern `spin-loader` but what other crates would be affected by making an addition to spin component configuration options?
Also, how should `exclude_files` be resolved with `files`? My gut says erring towards anything captured by `exclude_files` is excluded, even when `files` also matches on the given asset.
1. `publish` might also be affected, though I think it uses `loader` for most of that resolution. And `manifest` defines the actual on-disk format; you'd presumably need to add something to that.
2. Anything not mentioned by `files` is already skipped, so any exclusion feature needs to take precedence.
Correction, `manifest` is not used for serialisation and should not be affected.
> Correction, manifest is not used for serialisation and should not be affected.
But it might be by next week...
I have a PR that I was going to try knocking out before considering this one, are the API changes between crates significant enough that I should just wait it out?
If you're ready, go for it. I'll handle any conflicts.
If that's the case, my proposed/anticipated plan of action:
- I'll update more integration tests to help fulfill #216 and #535
- In this process, I will have the excuse/chance to setup an integration test that checks spin's asset loading functionality
- I'll open a corresponding PR off of this work (finished or unfinished) with my attempt at adding `exclude_files` as a config option
I have some other stuff on my plate right now (interview prep) but I should have some progress on this by sometime this Monday.
If anyone else is itching to tackle this issue before that time, please just say as much :slightly_smiling_face:
Hi, I would like to take this after # 618 is merged. Thank you.
|
2022-07-15T16:34:18Z
|
fermyon__spin-645
|
fermyon/spin
|
0.4
|
diff --git a/crates/loader/src/local/assets.rs b/crates/loader/src/local/assets.rs
index 538a1293ed..8ece1d50a1 100644
--- a/crates/loader/src/local/assets.rs
+++ b/crates/loader/src/local/assets.rs
@@ -6,7 +6,10 @@ use crate::assets::{
use anyhow::{anyhow, bail, ensure, Context, Result};
use futures::{future, stream, StreamExt};
use spin_manifest::DirectoryMount;
-use std::path::{Path, PathBuf};
+use std::{
+ path::{Path, PathBuf},
+ vec,
+};
use tracing::log;
use walkdir::WalkDir;
@@ -20,6 +23,7 @@ pub(crate) async fn prepare_component(
base_dst: impl AsRef<Path>,
id: &str,
allow_transient_write: bool,
+ exclude_files: &[String],
) -> Result<Vec<DirectoryMount>> {
log::info!(
"Mounting files from '{}' to '{}'",
@@ -27,7 +31,7 @@ pub(crate) async fn prepare_component(
base_dst.as_ref().display()
);
- let files = collect(raw_mounts, src)?;
+ let files = collect(raw_mounts, exclude_files, src)?;
let host = create_dir(&base_dst, id).await?;
let guest = "/".to_string();
copy_all(&files, &host, allow_transient_write).await?;
@@ -45,11 +49,7 @@ pub struct FileMount {
}
impl FileMount {
- fn from(
- src: Result<impl AsRef<Path>, glob::GlobError>,
- relative_to: impl AsRef<Path>,
- ) -> Result<Self> {
- let src = src?;
+ fn from(src: impl AsRef<Path>, relative_to: impl AsRef<Path>) -> Result<Self> {
let relative_dst = to_relative(&src, &relative_to)?;
let src = src.as_ref().to_path_buf();
Ok(Self { src, relative_dst })
@@ -63,13 +63,19 @@ impl FileMount {
}
/// Generate a vector of file mounts for a component given all its file patterns.
-pub fn collect(raw_mounts: &[RawFileMount], rel: impl AsRef<Path>) -> Result<Vec<FileMount>> {
+pub fn collect(
+ raw_mounts: &[RawFileMount],
+ exclude_files: &[String],
+ rel: impl AsRef<Path>,
+) -> Result<Vec<FileMount>> {
let (patterns, placements) = uncase(raw_mounts);
let pattern_files = collect_patterns(&patterns, &rel)?;
let placement_files = collect_placements(&placements, &rel)?;
let all_files = [pattern_files, placement_files].concat();
- Ok(all_files)
+
+ let exclude_patterns = convert_strings_to_glob_patterns(exclude_files, &rel)?;
+ Ok(get_included_files(all_files, &exclude_patterns))
}
fn collect_placements(
@@ -172,7 +178,7 @@ fn collect_pattern(pattern: &str, rel: impl AsRef<Path>) -> Result<Vec<FileMount
let matches = glob::glob(&abs.to_string_lossy())?;
let specifiers = matches
.into_iter()
- .map(|path| FileMount::from(path, &rel))
+ .map(|path| FileMount::from(path?, &rel))
.collect::<Result<Vec<_>>>()?;
let files: Vec<_> = specifiers.into_iter().filter(|s| s.src.is_file()).collect();
ensure_all_under(&rel, files.iter().map(|s| &s.src))?;
@@ -260,3 +266,47 @@ fn is_absolute_guest_path(path: impl AsRef<Path>) -> bool {
// paths specifically using Unix logic rather than the system function.
path.as_ref().to_string_lossy().starts_with('/')
}
+
+/// Convert strings to glob patterns
+fn convert_strings_to_glob_patterns<T: AsRef<str>>(
+ files: &[T],
+ rel: impl AsRef<Path>,
+) -> Result<Vec<glob::Pattern>> {
+ let file_paths = files
+ .iter()
+ .map(|f| match rel.as_ref().join(f.as_ref()).to_str() {
+ Some(abs) => Ok(abs.to_owned()),
+ None => Err(anyhow!(
+ "Can't join {} and {}",
+ rel.as_ref().display(),
+ f.as_ref()
+ )),
+ })
+ .collect::<Result<Vec<_>>>()?;
+ file_paths
+ .iter()
+ .map(|f| {
+ glob::Pattern::new(f).with_context(|| format!("can't convert {} to glob pattern", f))
+ })
+ .collect::<Result<Vec<glob::Pattern>>>()
+}
+
+/// Remove files which match excluded patterns
+fn get_included_files(files: Vec<FileMount>, exclude_patterns: &[glob::Pattern]) -> Vec<FileMount> {
+ files
+ .into_iter()
+ .filter(|f| {
+ for exclude_pattern in exclude_patterns {
+ if exclude_pattern.matches_path(Path::new(&f.src)) {
+ tracing::info!(
+ "file: {} is excluded by pattern {}",
+ f.src.display(),
+ exclude_pattern
+ );
+ return false;
+ }
+ }
+ true
+ })
+ .collect::<Vec<_>>()
+}
diff --git a/crates/loader/src/local/config.rs b/crates/loader/src/local/config.rs
index d106f232e7..4057ab133d 100644
--- a/crates/loader/src/local/config.rs
+++ b/crates/loader/src/local/config.rs
@@ -98,6 +98,9 @@ pub struct RawWasmConfig {
/// is either a file path or glob relative to the spin.toml file, or a
/// mapping of a source path to an absolute mount path in the guest.
pub files: Option<Vec<RawFileMount>>,
+ /// Optional list of file path or glob relative to the spin.toml that don't mount to wasm.
+ /// When exclude_files conflict with files config, exclude_files take precedence.
+ pub exclude_files: Option<Vec<String>>,
/// Optional list of HTTP hosts the component is allowed to connect.
pub allowed_http_hosts: Option<Vec<String>>,
}
diff --git a/crates/loader/src/local/mod.rs b/crates/loader/src/local/mod.rs
index 8eaa903717..f9da5a7dd4 100644
--- a/crates/loader/src/local/mod.rs
+++ b/crates/loader/src/local/mod.rs
@@ -196,7 +196,16 @@ async fn core(
let description = raw.description;
let mounts = match raw.wasm.files {
Some(f) => {
- assets::prepare_component(&f, src, &base_dst, &id, allow_transient_write).await?
+ let exclude_files = raw.wasm.exclude_files.unwrap_or_default();
+ assets::prepare_component(
+ &f,
+ src,
+ &base_dst,
+ &id,
+ allow_transient_write,
+ &exclude_files,
+ )
+ .await?
}
None => vec![],
};
diff --git a/crates/publish/src/expander.rs b/crates/publish/src/expander.rs
index d5b8f88837..33082bd47e 100644
--- a/crates/publish/src/expander.rs
+++ b/crates/publish/src/expander.rs
@@ -174,7 +174,8 @@ fn collect_assets(
base_dir: impl AsRef<Path>,
) -> Result<Vec<(spin_loader::local::assets::FileMount, String)>> {
let patterns = component.wasm.files.clone().unwrap_or_default();
- let file_mounts = spin_loader::local::assets::collect(&patterns, &base_dir)
+ let exclude_files = component.wasm.exclude_files.clone().unwrap_or_default();
+ let file_mounts = spin_loader::local::assets::collect(&patterns, &exclude_files, &base_dir)
.with_context(|| format!("Failed to get file mounts for component '{}'", component.id))?;
let annotated = file_mounts
.into_iter()
diff --git a/src/commands/deploy.rs b/src/commands/deploy.rs
index 1b7a6df79f..13929cd84a 100644
--- a/src/commands/deploy.rs
+++ b/src/commands/deploy.rs
@@ -229,7 +229,8 @@ impl DeployCommand {
}
if let Some(files) = &x.wasm.files {
let source_dir = crate::app_dir(&self.app)?;
- let fm = assets::collect(files, &source_dir)?;
+ let exclude_files = x.wasm.exclude_files.clone().unwrap_or_default();
+ let fm = assets::collect(files, &exclude_files, &source_dir)?;
for f in fm.iter() {
let mut r = File::open(&f.src)
.with_context(|| anyhow!("Cannot open file {}", &f.src.display()))?;
| 645
|
[
"554"
] |
diff --git a/tests/http/assets-test/spin.toml b/tests/http/assets-test/spin.toml
index 1e8c2bb9b8..4d4437f7ec 100644
--- a/tests/http/assets-test/spin.toml
+++ b/tests/http/assets-test/spin.toml
@@ -9,6 +9,7 @@ id = "fs"
# should we just use git submodules to avoid having binary test files here?
source = "spin_static_fs.wasm"
files = [{source = "static/thisshouldbemounted", destination = "/thisshouldbemounted"}]
+exclude_files = ["static/thisshouldbemounted/thisshouldbeexcluded/*"]
[component.trigger]
executor = {type = "spin"}
route = "/static/..."
diff --git a/tests/http/assets-test/static/thisshouldbemounted/thisshouldbeexcluded/4 b/tests/http/assets-test/static/thisshouldbemounted/thisshouldbeexcluded/4
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/integration.rs b/tests/integration.rs
index 99ca9aa437..a0031e9f18 100644
--- a/tests/integration.rs
+++ b/tests/integration.rs
@@ -185,6 +185,39 @@ mod integration_tests {
assert_status(&s, "/static/thisshouldbemounted/3", 200).await?;
assert_status(&s, "/static/donotmount/a", 404).await?;
+ assert_status(
+ &s,
+ "/static/thisshouldbemounted/thisshouldbeexcluded/4",
+ 404,
+ )
+ .await?;
+
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn test_static_assets_without_bindle() -> Result<()> {
+ let s = SpinTestController::with_manifest(
+ &format!(
+ "{}/{}",
+ RUST_HTTP_STATIC_ASSETS_TEST, DEFAULT_MANIFEST_LOCATION
+ ),
+ &[],
+ None,
+ )
+ .await?;
+
+ assert_status(&s, "/static/thisshouldbemounted/1", 200).await?;
+ assert_status(&s, "/static/thisshouldbemounted/2", 200).await?;
+ assert_status(&s, "/static/thisshouldbemounted/3", 200).await?;
+
+ assert_status(&s, "/static/donotmount/a", 404).await?;
+ assert_status(
+ &s,
+ "/static/thisshouldbemounted/thisshouldbeexcluded/4",
+ 404,
+ )
+ .await?;
Ok(())
}
@@ -682,7 +715,7 @@ mod integration_tests {
async fn wait_tcp(url: &str, process: &mut Child, target: &str) -> Result<()> {
let mut wait_count = 0;
loop {
- if wait_count >= 120 {
+ if wait_count >= 180 {
panic!(
"Ran out of retries waiting for {} to start on URL {}",
target, url
@@ -698,7 +731,8 @@ mod integration_tests {
match TcpStream::connect(&url).await {
Ok(_) => break,
- Err(_) => {
+ Err(e) => {
+ println!("connect {} error {}, retry {}", &url, e, wait_count);
wait_count += 1;
sleep(Duration::from_secs(1)).await;
}
|
e8b6667af92152971faf96e53669531c45b55c1d
|
e06c6b13510d7fd7a57322e0e9e5f1766eab6981
|
GoSDK - TinyGo V0.24.0 / Go 1.18.3 - compile error
Using the latest golang and tiny go versions (go - 1.18.3 and tinygo v0.24.0 ) and running the make file in the Go SDK folder results in:
```
# github.com/fermyon/spin/sdk/go/http
http/internals.go:67:15: cannot use newSpinHeader(k, v[0]) (value of type spinHeader) as C._Ctype_struct___3 value in assignment
http/internals.go:105:9: cannot use (C.spin_http_string_t literal) (value of type C._Ctype_struct___1) as spinString value in return statement
http/internals.go:119:7: cannot use newSpinString(k) (value of type spinString) as C._Ctype_struct___1 value in struct literal
http/internals.go:120:7: cannot use newSpinString(v) (value of type spinString) as C._Ctype_struct___1 value in struct literal
http/internals.go:118:9: cannot use (C.spin_http_tuple2_string_string_t literal) (value of type C._Ctype_struct___3) as spinHeader value in return statement
http/outbound_internals.go:121:9: cannot use (C.wasi_outbound_http_string_t literal) (value of type C._Ctype_struct___10) as spinString value in return statement
http/outbound_internals.go:141:18: cannot use newOutboundString(k) (value of type spinString) as C._Ctype_struct___10 value in assignment
http/outbound_internals.go:142:18: cannot use newOutboundString(v[0]) (value of type spinString) as C._Ctype_struct___10 value in assignment
make: *** [http/testdata/http-tinygo/main.wasm] Error 1
```
This was first reported in the gopher wasm slack channel but I was able to reproduce this error after upgrading locally. I believe this error in TinyGo with their support for go 1.18 but I have not seen any related issues. I am opening this here to see if there are any additional thoughts before opening an issue in the TinyGo repo.
A quick work around is to use v0.22.0 and golang v1.17.+
|
I can confirm that I see the same issue when trying to build a Spin component with TinyGo 0.24 and Go 1.18 on `main`.
I wrote a patch for this last week. I'll open a PR tomorrow.
Yay, thanks, @adamreese!
|
2022-07-11T21:45:42Z
|
fermyon__spin-625
|
fermyon/spin
|
0.3
|
diff --git a/sdk/go/http/internals.go b/sdk/go/http/internals.go
index ce2930da14..39bb840101 100644
--- a/sdk/go/http/internals.go
+++ b/sdk/go/http/internals.go
@@ -17,10 +17,15 @@ import (
func handle_http_request(req *C.spin_http_request_t, res *C.spin_http_response_t) {
defer C.spin_http_request_free(req)
- sr := (*spinRequest)(req)
+ var body []byte
+ if req.body.is_some {
+ body = C.GoBytes(unsafe.Pointer(req.body.val.ptr), C.int(req.body.val.len))
+ }
+ method := methods[req.method]
+ uri := C.GoStringN(req.uri.ptr, C.int(req.uri.len))
// NOTE Host is not included in the URL
- r, err := http.NewRequest(sr.Method(), sr.URL(), bytes.NewReader(sr.Body()))
+ r, err := http.NewRequest(method, uri, bytes.NewReader(body))
if err != nil {
fmt.Fprintln(os.Stderr, err)
res.status = C.uint16_t(http.StatusInternalServerError)
@@ -39,7 +44,7 @@ func handle_http_request(req *C.spin_http_request_t, res *C.spin_http_response_t
if len(w.header) > 0 {
res.headers = C.spin_http_option_headers_t{
is_some: true,
- val: toSpinHeaders(w.header),
+ val: toSpinHeaders(w.header),
}
} else {
res.headers = C.spin_http_option_headers_t{is_some: false}
@@ -67,6 +72,7 @@ func toSpinHeaders(hm http.Header) C.spin_http_headers_t {
ptr[idx] = newSpinHeader(k, v[0])
idx++
}
+
reqHeaders.ptr = &ptr[0]
}
return reqHeaders
@@ -97,48 +103,14 @@ func toSpinBody(body io.Reader) (C.spin_http_option_body_t, error) {
return spinBody, nil
}
-// spinString is the go type for C.spin_http_string_t.
-type spinString C.spin_http_string_t
-
-// newSpinString creates a new spinString with the given string.
-func newSpinString(s string) spinString {
- return C.spin_http_string_t{ptr: C.CString(s), len: C.size_t(len(s))}
-}
-
-// String returns the spinString as a go string.
-func (ss spinString) String() string {
- return C.GoStringN(ss.ptr, C.int(ss.len))
-}
-
-// spinHeader is the go type for C.spin_http_tuple2_string_string_t.
-type spinHeader C.spin_http_tuple2_string_string_t
-
// newSpinHeader creates a new spinHeader with the given key/value.
-func newSpinHeader(k, v string) spinHeader {
+func newSpinHeader(k, v string) C.spin_http_tuple2_string_string_t {
return C.spin_http_tuple2_string_string_t{
- f0: newSpinString(k),
- f1: newSpinString(v),
+ f0: C.spin_http_string_t{ptr: C.CString(k), len: C.size_t(len(k))},
+ f1: C.spin_http_string_t{ptr: C.CString(v), len: C.size_t(len(v))},
}
}
-// Values returns the key/value as strings.
-func (sh spinHeader) Values() (string, string) {
- k := spinString(sh.f0).String()
- v := spinString(sh.f1).String()
- return k, v
-}
-
-// spinBody is the go type for C.spin_http_body_t.
-type spinBody C.spin_http_body_t
-
-// Bytes returns the body as a go []byte.
-func (sb spinBody) Bytes() []byte {
- return C.GoBytes(unsafe.Pointer(sb.ptr), C.int(sb.len))
-}
-
-// spinRequest is the go type for C.spin_http_request_t.
-type spinRequest C.spin_http_request_t
-
var methods = [...]string{
"GET",
"POST",
@@ -149,24 +121,6 @@ var methods = [...]string{
"OPTIONS",
}
-// Method returns the request method as a go string.
-func (sr spinRequest) Method() string {
- return methods[sr.method]
-}
-
-// URL returns the request URL as a go string.
-func (sr spinRequest) URL() string {
- return spinString(sr.uri).String()
-}
-
-// Body returns the request body as a go []byte.
-func (sr spinRequest) Body() []byte {
- if !sr.body.is_some {
- return nil
- }
- return spinBody(sr.body.val).Bytes()
-}
-
func fromSpinHeaders(hm *C.spin_http_headers_t) http.Header {
headersLen := int(hm.len)
headers := make(http.Header, headersLen)
diff --git a/sdk/go/http/outbound_internals.go b/sdk/go/http/outbound_internals.go
index e6a67a1284..5abab87c53 100644
--- a/sdk/go/http/outbound_internals.go
+++ b/sdk/go/http/outbound_internals.go
@@ -113,19 +113,6 @@ func toResponse(res *C.wasi_outbound_http_response_t) (*http.Response, error) {
return t, nil
}
-// outboundString is the go type for C.wasi_outbound_http_string_t.
-type outboundString C.wasi_outbound_http_string_t
-
-// newOutboundString creates a new spinString with the given string.
-func newOutboundString(s string) spinString {
- return C.wasi_outbound_http_string_t{ptr: C.CString(s), len: C.size_t(len(s))}
-}
-
-// String returns the outboundString as a go string.
-func (ws outboundString) String() string {
- return C.GoStringN(ws.ptr, C.int(ws.len))
-}
-
func toOutboundHeaders(hm http.Header) C.wasi_outbound_http_headers_t {
var reqHeaders C.wasi_outbound_http_headers_t
headersLen := len(hm)
@@ -138,8 +125,8 @@ func toOutboundHeaders(hm http.Header) C.wasi_outbound_http_headers_t {
idx := 0
for k, v := range hm {
- ptr[idx].f0 = newOutboundString(k)
- ptr[idx].f1 = newOutboundString(v[0])
+ ptr[idx].f0 = C.wasi_outbound_http_string_t{ptr: C.CString(k), len: C.size_t(len(k))}
+ ptr[idx].f1 = C.wasi_outbound_http_string_t{ptr: C.CString(v[0]), len: C.size_t(len(v[0]))}
idx++
}
reqHeaders.ptr = &ptr[0]
| 625
|
[
"624"
] |
diff --git a/sdk/go/http/internals_test.go b/sdk/go/http/internals_test.go
deleted file mode 100644
index fe498fcc52..0000000000
--- a/sdk/go/http/internals_test.go
+++ /dev/null
@@ -1,21 +0,0 @@
-package http
-
-import "testing"
-
-func TestString(t *testing.T) {
- tt := "hello"
- if tt != newSpinString(tt).String() {
- t.Fatal("strings do not match")
- }
-}
-
-func TestHeader(t *testing.T) {
- k, v := "hello", "world"
- gotK, gotV := newSpinHeader(k, v).Values()
- if k != gotK {
- t.Fatal("keys do not match")
- }
- if v != gotV {
- t.Fatal("values did not match")
- }
-}
diff --git a/sdk/go/integration_test.go b/sdk/go/integration_test.go
index f64bbb7278..a38b236fae 100644
--- a/sdk/go/integration_test.go
+++ b/sdk/go/integration_test.go
@@ -82,6 +82,7 @@ func TestHTTPTriger(t *testing.T) {
if resp.Body == nil {
t.Fatal("body is nil")
}
+ t.Log(resp.Status)
b, err := io.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
|
e06c6b13510d7fd7a57322e0e9e5f1766eab6981
|
e06c6b13510d7fd7a57322e0e9e5f1766eab6981
|
e2e test for spin deploy
|
Hi, I would like to help with this issue and also have a draft PR https://github.com/FrankYang0529/spin/pull/1 in my repo to run integration tests on GitHub Workflow. I have two questions for the PR:
1. What is a proper way to install Hippo as a dependent on GitHub Actions? Looks like [engineerd/configurator](https://github.com/engineerd/configurator) only moves one executable file to the `bin` folder.
2. I install Hippo by moving all files to the `bin` folder, but I always get a 500 status code when I check Hippo health on GitHub Actions. It shows an error message like the following. I have tried to give bindle-server URL by different environment variables like `BINDLE_URL`, `Bindle__Url`, but they all don't work.
```
fail: Microsoft.AspNetCore.Server.Kestrel[13]
Connection id "0HMIO4HRNANO6", Request id "0HMIO4HRNANO6:00000002": An unhandled exception was thrown by the application.
System.NullReferenceException: Object reference not set to an instance of an object.
at Deislabs.Bindle.ConnectionInfo.GetKeyValuePairs(String connectionString)
at Deislabs.Bindle.ConnectionInfo..ctor(String connectionString)
at Deislabs.Bindle.BindleClient..ctor(String connectionString)
at Hippo.Infrastructure.HealthChecks.BindleHealthCheck..ctor(IConfiguration configuration) in /home/runner/work/hippo/hippo/src/Infrastructure/HealthChecks/BindleHealthCheck.cs:line 13
at System.RuntimeMethodHandle.InvokeMethod(Object target, Span`1& arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetServiceOrCreateInstance[T](IServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.HealthChecksBuilderAddCheckExtensions.<>c__3`1.<AddCheck>b__3_0(IServiceProvider s)
at Microsoft.Extensions.Diagnostics.HealthChecks.DefaultHealthCheckService.RunCheckAsync(HealthCheckRegistration registration, CancellationToken cancellationToken)
at Microsoft.Extensions.Diagnostics.HealthChecks.DefaultHealthCheckService.CheckHealthAsync(Func`2 predicate, CancellationToken cancellationToken)
at Microsoft.AspNetCore.Diagnostics.HealthChecks.HealthCheckMiddleware.InvokeAsync(HttpContext httpContext)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)
```
> 2. I install Hippo by moving all files to the `bin` folder, but I always get a 500 status code when I check Hippo health on GitHub Actions. It shows an error message like the following. I have tried to give bindle-server URL by different environment variables like `BINDLE_URL`, `Bindle__Url`, but they all don't work.
I find that I can use `ConnectionStrings__Bindle` to set bindle-server URL.
|
2022-06-28T15:05:07Z
|
fermyon__spin-607
|
fermyon/spin
|
0.3
|
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 9b9e0ef272..3d6ce3d90f 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -28,6 +28,10 @@ jobs:
bindleUrl: "https://bindle.blob.core.windows.net/releases/bindle-v0.8.0-linux-amd64.tar.gz",
bindleBinary: "bindle-server",
pathInBindleArchive: "bindle-server",
+ nomadUrl: "https://releases.hashicorp.com/nomad/1.3.1/nomad_1.3.1_linux_amd64.zip",
+ nomadBinary: "nomad",
+ pathInNomadArchive: "nomad",
+ hippoUrl: "https://github.com/deislabs/hippo/releases/download/v0.17.0/hippo-server-linux-x64.tar.gz",
wasmtimeUrl: "https://github.com/bytecodealliance/wasmtime/releases/download/v0.36.0/wasmtime-v0.36.0-x86_64-linux.tar.xz",
wasmtimeBinary: "wasmtime",
pathInWasmtimeArchive: "wasmtime-v0.36.0-x86_64-linux/wasmtime",
@@ -40,6 +44,10 @@ jobs:
bindleUrl: "https://bindle.blob.core.windows.net/releases/bindle-v0.8.0-macos-amd64.tar.gz",
bindleBinary: "bindle-server",
pathInBindleArchive: "bindle-server",
+ nomadUrl: "https://releases.hashicorp.com/nomad/1.3.1/nomad_1.3.1_darwin_amd64.zip",
+ nomadBinary: "nomad",
+ pathInNomadArchive: "nomad",
+ hippoUrl: "https://github.com/deislabs/hippo/releases/download/v0.17.0/hippo-server-osx-x64.tar.gz",
}
- {
os: "windows-latest",
@@ -48,6 +56,10 @@ jobs:
bindleUrl: "https://bindle.blob.core.windows.net/releases/bindle-v0.8.0-windows-amd64.tar.gz",
bindleBinary: "bindle-server.exe",
pathInBindleArchive: "bindle-server.exe",
+ nomadUrl: "https://releases.hashicorp.com/nomad/1.3.1/nomad_1.3.1_windows_amd64.zip",
+ nomadBinary: "nomad.exe",
+ pathInNomadArchive: "nomad.exe",
+ hippoUrl: "https://github.com/deislabs/hippo/releases/download/v0.17.0/hippo-server-win-x64.zip",
}
steps:
- uses: actions/checkout@v2
@@ -62,12 +74,38 @@ jobs:
- name: "Install Wasm Rust target"
run: rustup target add wasm32-wasi
- - uses: engineerd/configurator@v0.0.8
+ - name: Install bindle
+ uses: engineerd/configurator@v0.0.8
with:
name: ${{ matrix.config.bindleBinary }}
url: ${{ matrix.config.bindleUrl }}
pathInArchive: ${{ matrix.config.pathInBindleArchive }}
+ - name: Install nomad
+ uses: engineerd/configurator@v0.0.8
+ with:
+ name: ${{ matrix.config.nomadBinary }}
+ url: ${{ matrix.config.nomadUrl }}
+ pathInArchive: ${{ matrix.config.pathInNomadArchive }}
+
+ - name: Install hippo
+ if: ${{ fromJSON(matrix.config.os != 'windows-latest') }}
+ run: |
+ curl -L ${{ matrix.config.hippoUrl }} -o hippo-server.tar.gz
+ mkdir hippo-server-output
+ tar xz -C hippo-server-output -f hippo-server.tar.gz
+ cp -r hippo-server-output/**/* ~/configurator/bin
+ chmod +x ~/configurator/bin/Hippo.Web
+
+ - name: Install hippo on Windows
+ if: ${{ fromJSON(matrix.config.os == 'windows-latest') }}
+ run: |
+ (New-Object System.Net.WebClient).DownloadFile("${{ matrix.config.hippoUrl }}","hippo-server.zip");
+ md hippo-server-output;
+ Expand-Archive .\hippo-server.zip .\hippo-server-output;
+ echo "$((Get-Item .\hippo-server-output).FullName)\win-x64";
+ echo "$((Get-Item .\hippo-server-output).FullName)\win-x64" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append;
+
- uses: Swatinem/rust-cache@v1
- name: Cargo Format
@@ -84,8 +122,9 @@ jobs:
run: cargo build --workspace --all-targets --all-features ${{ matrix.config.extraArgs }}
- name: Cargo Test
- run:
- cargo test --workspace --all-targets --all-features --no-fail-fast -- --nocapture
+ run: |
+ make test-unit
+ make test-integration
env:
RUST_LOG: spin=trace
@@ -133,4 +172,4 @@ jobs:
mv bart /usr/local/bin
- name: Check docs site content
- run: make check-content
\ No newline at end of file
+ run: make check-content
diff --git a/Cargo.lock b/Cargo.lock
index 63053748b7..63b54c0c97 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3543,6 +3543,7 @@ dependencies = [
"vergen",
"wasi-outbound-http",
"wasmtime",
+ "which",
]
[[package]]
@@ -5099,6 +5100,17 @@ dependencies = [
"webpki 0.22.0",
]
+[[package]]
+name = "which"
+version = "4.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c4fb54e6113b6a8772ee41c3404fb0301ac79604489467e0a9ce1f3e97c24ae"
+dependencies = [
+ "either",
+ "lazy_static",
+ "libc",
+]
+
[[package]]
name = "wiggle"
version = "0.34.1"
diff --git a/Cargo.toml b/Cargo.toml
index 25260910fb..14ad5eb17a 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -54,6 +54,7 @@ openssl = { version = "0.10" }
[dev-dependencies]
hyper = { version = "0.14", features = [ "full" ] }
sha2 = "0.10.1"
+which = "4.2.5"
[build-dependencies]
cargo-target-dep = { git = "https://github.com/fermyon/cargo-target-dep", rev = "b7b1989fe0984c0f7c4966398304c6538e52fe49" }
diff --git a/Makefile b/Makefile
index f1afb33696..aa69ec697e 100644
--- a/Makefile
+++ b/Makefile
@@ -7,11 +7,22 @@ build:
cargo build --release
.PHONY: test
-test:
- RUST_LOG=$(LOG_LEVEL) cargo test --all --no-fail-fast -- --nocapture --include-ignored
+test: lint test-unit test-integration
+
+.PHONY: lint
+lint:
cargo clippy --all-targets --all-features -- -D warnings
cargo fmt --all -- --check
+.PHONY: test-unit
+test-unit:
+ RUST_LOG=$(LOG_LEVEL) cargo test --no-fail-fast -- --skip integration_tests --nocapture --include-ignored
+
+.PHONY: test-integration
+test-integration:
+ RUST_LOG=$(LOG_LEVEL) cargo test --test integration --no-fail-fast -- integration_tests::test_dependencies --nocapture
+ RUST_LOG=$(LOG_LEVEL) cargo test --test integration --no-fail-fast -- --skip integration_tests::test_dependencies --nocapture --include-ignored
+
.PHONY: test-sdk-go
test-sdk-go:
$(MAKE) -C sdk/go test
diff --git a/src/commands/deploy.rs b/src/commands/deploy.rs
index 62495ad9b7..fa5b2c7dae 100644
--- a/src/commands/deploy.rs
+++ b/src/commands/deploy.rs
@@ -231,8 +231,8 @@ impl DeployCommand {
let source_dir = crate::app_dir(&self.app)?;
let fm = assets::collect(files, &source_dir)?;
for f in fm.iter() {
- let src_path = source_dir.join(&f.src);
- let mut r = File::open(src_path)?;
+ let mut r = File::open(&f.src)
+ .with_context(|| anyhow!("Cannot open file {}", &f.src.display()))?;
copy(&mut r, &mut sha256)?;
}
}
| 607
|
[
"583"
] |
diff --git a/tests/README.md b/tests/README.md
new file mode 100644
index 0000000000..3d38947384
--- /dev/null
+++ b/tests/README.md
@@ -0,0 +1,9 @@
+# Integration test
+
+## Dependencies
+
+Please add following dependencies to your PATH before running `make test-integration`.
+
+* [bindle-server](https://github.com/deislabs/bindle)
+* [nomad](https://github.com/hashicorp/nomad)
+* [Hippo.Web](https://github.com/deislabs/hippo)
diff --git a/tests/http/simple-spin-rust/Cargo.lock b/tests/http/simple-spin-rust/Cargo.lock
index b789d0a2bb..a10a5fa1ea 100644
--- a/tests/http/simple-spin-rust/Cargo.lock
+++ b/tests/http/simple-spin-rust/Cargo.lock
@@ -148,7 +148,7 @@ dependencies = [
[[package]]
name = "spin-sdk"
-version = "0.2.0"
+version = "0.3.0"
dependencies = [
"anyhow",
"bytes",
diff --git a/tests/integration.rs b/tests/integration.rs
index 85c7bebc54..99ca9aa437 100644
--- a/tests/integration.rs
+++ b/tests/integration.rs
@@ -15,6 +15,7 @@ mod integration_tests {
};
use tempfile::TempDir;
use tokio::{net::TcpStream, time::sleep};
+ use which::which;
const RUST_HTTP_INTEGRATION_TEST: &str = "tests/http/simple-spin-rust";
const RUST_HTTP_INTEGRATION_TEST_REF: &str = "spin-hello-world/1.0.0";
@@ -29,14 +30,31 @@ mod integration_tests {
const SPIN_BINARY: &str = "./target/debug/spin";
const BINDLE_SERVER_BINARY: &str = "bindle-server";
+ const NOMAD_BINARY: &str = "nomad";
+ const HIPPO_BINARY: &str = "Hippo.Web";
const BINDLE_SERVER_PATH_ENV: &str = "SPIN_TEST_BINDLE_SERVER_PATH";
const BINDLE_SERVER_BASIC_AUTH_HTPASSWD_FILE: &str = "tests/http/htpasswd";
const BINDLE_SERVER_BASIC_AUTH_USER: &str = "bindle-user";
const BINDLE_SERVER_BASIC_AUTH_PASSWORD: &str = "topsecret";
+ const HIPPO_BASIC_AUTH_USER: &str = "hippo-user";
+ const HIPPO_BASIC_AUTH_PASSWORD: &str = "topsecret";
+
// This assumes all tests have been previously compiled by the top-level build script.
+ #[tokio::test]
+ async fn test_dependencies() -> Result<()> {
+ which(get_process(BINDLE_SERVER_BINARY))
+ .with_context(|| format!("Can't find {}", get_process(BINDLE_SERVER_BINARY)))?;
+ which(get_process(NOMAD_BINARY))
+ .with_context(|| format!("Can't find {}", get_process(NOMAD_BINARY)))?;
+ which(get_process(HIPPO_BINARY))
+ .with_context(|| format!("Can't find {}", get_process(HIPPO_BINARY)))?;
+
+ Ok(())
+ }
+
#[tokio::test]
async fn test_simple_rust_local() -> Result<()> {
let s = SpinTestController::with_manifest(
@@ -269,6 +287,44 @@ mod integration_tests {
Ok(())
}
+ #[tokio::test]
+ async fn test_spin_deploy() -> Result<()> {
+ // start the Bindle registry.
+ let config = BindleTestControllerConfig {
+ basic_auth_enabled: false,
+ };
+ let _nomad = NomadTestController::new().await?;
+ let bindle = BindleTestController::new(config).await?;
+ let hippo = HippoTestController::new(&bindle.url).await?;
+
+ // push the application to the registry using the Spin CLI.
+ run(
+ vec![
+ SPIN_BINARY,
+ "deploy",
+ "--file",
+ &format!(
+ "{}/{}",
+ RUST_HTTP_HEADERS_ENV_ROUTES_TEST, DEFAULT_MANIFEST_LOCATION
+ ),
+ "--bindle-server",
+ &bindle.url,
+ "--hippo-server",
+ &hippo.url,
+ "--hippo-username",
+ HIPPO_BASIC_AUTH_USER,
+ "--hippo-password",
+ HIPPO_BASIC_AUTH_PASSWORD,
+ ],
+ None,
+ )?;
+
+ let apps_vm = hippo.client.list_apps().await?;
+ assert_eq!(apps_vm.apps.len(), 1, "hippo apps: {apps_vm:?}");
+
+ Ok(())
+ }
+
async fn verify_headers(
s: &SpinTestController,
absolute_uri: &str,
@@ -482,6 +538,95 @@ mod integration_tests {
}
}
+ /// Controller for running Nomad.
+ pub struct NomadTestController {
+ pub url: String,
+ nomad_handle: Child,
+ }
+
+ impl NomadTestController {
+ pub async fn new() -> Result<NomadTestController> {
+ let url = "127.0.0.1:4646".to_string();
+
+ let mut nomad_handle = Command::new(get_process(NOMAD_BINARY))
+ .args(["agent", "-dev"])
+ .spawn()
+ .with_context(|| "executing nomad")?;
+
+ wait_tcp(&url, &mut nomad_handle, NOMAD_BINARY).await?;
+
+ Ok(Self { url, nomad_handle })
+ }
+ }
+
+ impl Drop for NomadTestController {
+ fn drop(&mut self) {
+ let _ = self.nomad_handle.kill();
+ }
+ }
+
+ /// Controller for running Hippo.
+ pub struct HippoTestController {
+ pub url: String,
+ pub client: hippo::Client,
+ hippo_handle: Child,
+ }
+
+ impl HippoTestController {
+ pub async fn new(bindle_url: &str) -> Result<HippoTestController> {
+ let url = format!("http://127.0.0.1:{}", get_random_port()?);
+
+ let mut hippo_handle = Command::new(get_process(HIPPO_BINARY))
+ .env("ASPNETCORE_URLS", &url)
+ .env("Nomad__Driver", "raw_exec")
+ .env("Nomad__Datacenters__0", "dc1")
+ .env("Database__Driver", "inmemory")
+ .env("ConnectionStrings__Bindle", format!("Address={bindle_url}"))
+ .env("Jwt__Key", "ceci n'est pas une jeton")
+ .env("Jwt__Issuer", "localhost")
+ .env("Jwt__Audience", "localhost")
+ .spawn()
+ .with_context(|| "executing hippo")?;
+
+ wait_hippo(&url, &mut hippo_handle, HIPPO_BINARY).await?;
+
+ let client = hippo::Client::new(hippo::ConnectionInfo {
+ url: url.clone(),
+ danger_accept_invalid_certs: true,
+ api_key: None,
+ });
+ client
+ .register(
+ HIPPO_BASIC_AUTH_USER.into(),
+ HIPPO_BASIC_AUTH_PASSWORD.into(),
+ )
+ .await?;
+ let token_info = client
+ .login(
+ HIPPO_BASIC_AUTH_USER.into(),
+ HIPPO_BASIC_AUTH_PASSWORD.into(),
+ )
+ .await?;
+ let client = hippo::Client::new(hippo::ConnectionInfo {
+ url: url.clone(),
+ danger_accept_invalid_certs: true,
+ api_key: token_info.token,
+ });
+
+ Ok(Self {
+ url,
+ client,
+ hippo_handle,
+ })
+ }
+ }
+
+ impl Drop for HippoTestController {
+ fn drop(&mut self) {
+ let _ = self.hippo_handle.kill();
+ }
+ }
+
fn run<S: Into<String> + AsRef<OsStr>>(args: Vec<S>, dir: Option<S>) -> Result<()> {
let mut cmd = Command::new(get_os_process());
cmd.stdout(process::Stdio::piped());
@@ -563,6 +708,38 @@ mod integration_tests {
Ok(())
}
+ async fn wait_hippo(url: &str, process: &mut Child, target: &str) -> Result<()> {
+ let mut wait_count = 0;
+ loop {
+ if wait_count >= 120 {
+ panic!(
+ "Ran out of retries waiting for {} to start on URL {}",
+ target, url
+ );
+ }
+
+ if let Ok(Some(_)) = process.try_wait() {
+ panic!(
+ "Process exited before starting to serve {} to start on URL {}",
+ target, url
+ );
+ }
+
+ if let Ok(rsp) = reqwest::get(format!("{url}/healthz")).await {
+ if let Ok(result) = rsp.text().await {
+ if result == "Healthy" {
+ break;
+ }
+ }
+ }
+
+ wait_count += 1;
+ sleep(Duration::from_secs(1)).await;
+ }
+
+ Ok(())
+ }
+
fn file_digest_string(path: impl AsRef<Path>) -> Result<String> {
use sha2::{Digest, Sha256};
let mut file = std::fs::File::open(&path)?;
|
e06c6b13510d7fd7a57322e0e9e5f1766eab6981
|
fab46dea2f9fa38ca5527cf7b3821c47472c6ffd
|
Add tests for the Redis trigger
|
2022-06-08T00:18:12Z
|
fermyon__spin-543
|
fermyon/spin
|
0.2
|
diff --git a/Makefile b/Makefile
index 87299e667f..b7dcfa062e 100644
--- a/Makefile
+++ b/Makefile
@@ -8,7 +8,7 @@ build:
.PHONY: test
test:
- RUST_LOG=$(LOG_LEVEL) cargo test --all --no-fail-fast -- --nocapture
+ RUST_LOG=$(LOG_LEVEL) cargo test --all --no-fail-fast -- --nocapture --include-ignored
cargo clippy --all-targets --all-features -- -D warnings
cargo fmt --all -- --check
| 543
|
[
"179"
] |
diff --git a/crates/redis/src/tests.rs b/crates/redis/src/tests.rs
index d5360cdf41..02c834af73 100644
--- a/crates/redis/src/tests.rs
+++ b/crates/redis/src/tests.rs
@@ -1,5 +1,6 @@
use super::*;
use anyhow::Result;
+use redis::{Msg, Value};
use spin_manifest::{RedisConfig, RedisExecutor};
use spin_testing::TestConfig;
use spin_trigger::build_trigger_from_app;
@@ -16,8 +17,17 @@ pub(crate) fn init() {
});
}
+fn create_trigger_event(channel: &str, payload: &str) -> redis::Msg {
+ Msg::from_value(&redis::Value::Bulk(vec![
+ Value::Data("message".into()),
+ Value::Data(channel.into()),
+ Value::Data(payload.into()),
+ ]))
+ .unwrap()
+}
+
+#[ignore]
#[tokio::test]
-#[allow(unused)]
async fn test_pubsub() -> Result<()> {
init();
@@ -32,11 +42,8 @@ async fn test_pubsub() -> Result<()> {
let trigger: RedisTrigger =
build_trigger_from_app(app, None, FollowComponents::None, None).await?;
- // TODO
- // use redis::{FromRedisValue, Msg, Value};
- // let val = FromRedisValue::from_redis_value(&Value::Data("hello".into()))?;
- // let msg = Msg::from_value(&val).unwrap();
- // trigger.handle(msg).await?;
+ let msg = create_trigger_event("messages", "hello");
+ trigger.handle(msg).await?;
Ok(())
}
|
fab46dea2f9fa38ca5527cf7b3821c47472c6ffd
|
|
95f9da2a41aded597a437ad041a5a13ab19604ee
|
Implement Bindle module source in application manifest
The local configuration allows defining a remote reference to a bindle as the module source:
https://github.com/fermyon/spin/blob/a09fb1f2b6f9a52dee7dbcbe54e6f9ff41a72ea0/crates/loader/src/local/config.rs#L123-L131
However, that is currently not implemented:
https://github.com/fermyon/spin/blob/a09fb1f2b6f9a52dee7dbcbe54e6f9ff41a72ea0/crates/loader/src/local/mod.rs#L142-L144
It would be extremely helpful to have this implemented in order to more easily reuse modules across applications.
|
2022-05-09T04:13:50Z
|
fermyon__spin-456
|
fermyon/spin
|
0.1
|
diff --git a/Cargo.lock b/Cargo.lock
index 7b1cee750e..7da4d209a6 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3449,6 +3449,7 @@ dependencies = [
"reqwest",
"semver",
"serde",
+ "sha2 0.10.2",
"spin-build",
"spin-config",
"spin-engine",
diff --git a/Cargo.toml b/Cargo.toml
index bfc302c744..b3494bee35 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -44,6 +44,7 @@ wasmtime = "0.34"
[dev-dependencies]
hyper = { version = "0.14", features = [ "full" ] }
+sha2 = "0.10.1"
[build-dependencies]
cargo-target-dep = { git = "https://github.com/fermyon/cargo-target-dep", rev = "b7b1989fe0984c0f7c4966398304c6538e52fe49" }
diff --git a/crates/loader/src/bindle/connection.rs b/crates/loader/src/bindle/connection.rs
new file mode 100644
index 0000000000..cb96f3fba5
--- /dev/null
+++ b/crates/loader/src/bindle/connection.rs
@@ -0,0 +1,66 @@
+use std::sync::Arc;
+
+use bindle::client::{
+ tokens::{HttpBasic, NoToken, TokenManager},
+ Client, ClientBuilder,
+};
+
+/// BindleConnectionInfo holds the details of a connection to a
+/// Bindle server, including url, insecure configuration and an
+/// auth token manager
+#[derive(Clone)]
+pub struct BindleConnectionInfo {
+ base_url: String,
+ allow_insecure: bool,
+ token_manager: AnyAuth,
+}
+
+impl BindleConnectionInfo {
+ /// Generates a new BindleConnectionInfo instance using the provided
+ /// base_url, allow_insecure setting and optional username and password
+ /// for basic http auth
+ pub fn new<I: Into<String>>(
+ base_url: I,
+ allow_insecure: bool,
+ username: Option<String>,
+ password: Option<String>,
+ ) -> Self {
+ let token_manager: Box<dyn TokenManager + Send + Sync> = match (username, password) {
+ (Some(u), Some(p)) => Box::new(HttpBasic::new(&u, &p)),
+ _ => Box::new(NoToken::default()),
+ };
+
+ Self {
+ base_url: base_url.into(),
+ allow_insecure,
+ token_manager: AnyAuth {
+ token_manager: Arc::new(token_manager),
+ },
+ }
+ }
+
+ /// Returns a client based on this instance's configuration
+ pub fn client(&self) -> bindle::client::Result<Client<AnyAuth>> {
+ let builder = ClientBuilder::default()
+ .http2_prior_knowledge(false)
+ .danger_accept_invalid_certs(self.allow_insecure);
+ builder.build(&self.base_url, self.token_manager.clone())
+ }
+}
+
+/// AnyAuth wraps an authentication token manager which applies
+/// the appropriate auth header per its configuration
+#[derive(Clone)]
+pub struct AnyAuth {
+ token_manager: Arc<Box<dyn TokenManager + Send + Sync>>,
+}
+
+#[async_trait::async_trait]
+impl TokenManager for AnyAuth {
+ async fn apply_auth_header(
+ &self,
+ builder: reqwest::RequestBuilder,
+ ) -> bindle::client::Result<reqwest::RequestBuilder> {
+ self.token_manager.apply_auth_header(builder).await
+ }
+}
diff --git a/crates/loader/src/bindle/mod.rs b/crates/loader/src/bindle/mod.rs
index 0c25395929..17d9a9786a 100644
--- a/crates/loader/src/bindle/mod.rs
+++ b/crates/loader/src/bindle/mod.rs
@@ -6,18 +6,17 @@
mod assets;
/// Configuration representation for a Spin application in Bindle.
pub mod config;
+mod connection;
/// Bindle helper functions.
mod utils;
use crate::bindle::{
config::{RawAppManifest, RawComponentManifest},
- utils::{find_manifest, parcels_in_group, BindleReader},
+ utils::{find_manifest, parcels_in_group},
};
use anyhow::{anyhow, Context, Result};
-use bindle::{
- client::{tokens::NoToken, Client},
- Invoice,
-};
+use bindle::Invoice;
+pub use connection::BindleConnectionInfo;
use futures::future;
use spin_manifest::{
Application, ApplicationInformation, ApplicationOrigin, CoreComponent, ModuleSource,
@@ -25,7 +24,8 @@ use spin_manifest::{
};
use std::{path::Path, sync::Arc};
use tracing::log;
-pub use utils::{BindleTokenManager, SPIN_MANIFEST_MEDIA_TYPE};
+pub(crate) use utils::BindleReader;
+pub use utils::SPIN_MANIFEST_MEDIA_TYPE;
/// Given a Bindle server URL and reference, pull it, expand its assets locally, and get a
/// prepared application configuration consumable by a Spin execution context.
@@ -34,8 +34,8 @@ pub use utils::{BindleTokenManager, SPIN_MANIFEST_MEDIA_TYPE};
pub async fn from_bindle(id: &str, url: &str, base_dst: impl AsRef<Path>) -> Result<Application> {
// TODO
// Handle Bindle authentication.
- let manager = BindleTokenManager::NoToken(NoToken);
- let client = Client::new(url, manager)?;
+ let connection_info = BindleConnectionInfo::new(url, false, None, None);
+ let client = connection_info.client()?;
let reader = BindleReader::remote(&client, &id.parse()?);
prepare(id, url, &reader, base_dst).await
diff --git a/crates/loader/src/bindle/utils.rs b/crates/loader/src/bindle/utils.rs
index 1edf065fc7..dd41d74c66 100644
--- a/crates/loader/src/bindle/utils.rs
+++ b/crates/loader/src/bindle/utils.rs
@@ -1,23 +1,15 @@
#![deny(missing_docs)]
use anyhow::{anyhow, bail, Context, Error, Result};
-use async_trait::async_trait;
-use bindle::{
- client::{
- self,
- tokens::{NoToken, TokenManager},
- Client,
- },
- standalone::StandaloneRead,
- Id, Invoice, Label, Parcel,
-};
+use bindle::{client::Client, standalone::StandaloneRead, Id, Invoice, Label, Parcel};
use futures::{Stream, StreamExt, TryStreamExt};
use itertools::Itertools;
-use reqwest::RequestBuilder;
use std::{fmt::Debug, path::Path, sync::Arc};
use tokio::fs;
use tokio_util::codec::{BytesCodec, FramedRead};
+use super::connection::AnyAuth;
+
static EMPTY: &Vec<bindle::Parcel> = &vec![];
// Alternative to storing `spin.toml` as a parcel, this could be
@@ -101,30 +93,6 @@ trigger = "http"
*/
-/// Any kind of Bindle authentication.
-#[derive(Clone)]
-pub enum BindleTokenManager {
- /// Anonymous authentication
- NoToken(NoToken),
-}
-
-#[async_trait]
-impl TokenManager for BindleTokenManager {
- async fn apply_auth_header(&self, builder: RequestBuilder) -> client::Result<RequestBuilder> {
- match self {
- Self::NoToken(t) => t.apply_auth_header(builder).await,
- }
- }
-}
-
-impl Debug for BindleTokenManager {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- match self {
- Self::NoToken(_) => f.debug_tuple("NoToken").finish(),
- }
- }
-}
-
/// Encapsulate a Bindle source.
#[derive(Clone, Debug)]
pub(crate) struct BindleReader {
@@ -207,7 +175,7 @@ impl BindleReader {
}
}
- pub(crate) fn remote(c: &Client<BindleTokenManager>, id: &Id) -> Self {
+ pub(crate) fn remote(c: &Client<AnyAuth>, id: &Id) -> Self {
Self {
inner: BindleReaderInner::Remote(c.clone(), id.clone()),
}
@@ -225,7 +193,7 @@ impl BindleReader {
#[derive(Clone)]
enum BindleReaderInner {
Standalone(Arc<StandaloneRead>),
- Remote(Client<BindleTokenManager>, Id),
+ Remote(Client<AnyAuth>, Id),
}
impl Debug for BindleReaderInner {
diff --git a/crates/loader/src/local/mod.rs b/crates/loader/src/local/mod.rs
index a83caa01d6..bf376dc688 100644
--- a/crates/loader/src/local/mod.rs
+++ b/crates/loader/src/local/mod.rs
@@ -18,21 +18,27 @@ use spin_manifest::{
Application, ApplicationInformation, ApplicationOrigin, CoreComponent, ModuleSource,
SpinVersion, WasmConfig,
};
-use std::{path::Path, sync::Arc};
+use std::{path::Path, str::FromStr, sync::Arc};
use tokio::{fs::File, io::AsyncReadExt};
+use crate::bindle::BindleConnectionInfo;
+
/// Given the path to a spin.toml manifest file, prepare its assets locally and
/// get a prepared application configuration consumable by a Spin execution context.
/// If a directory is provided, use it as the base directory to expand the assets,
/// otherwise create a new temporary directory.
-pub async fn from_file(app: impl AsRef<Path>, base_dst: impl AsRef<Path>) -> Result<Application> {
+pub async fn from_file(
+ app: impl AsRef<Path>,
+ base_dst: impl AsRef<Path>,
+ bindle_connection: &Option<BindleConnectionInfo>,
+) -> Result<Application> {
let app = app
.as_ref()
.absolutize()
.context("Failed to resolve absolute path to manifest file")?;
let manifest = raw_manifest_from_file(&app).await?;
- prepare_any_version(manifest, app, base_dst).await
+ prepare_any_version(manifest, app, base_dst, bindle_connection).await
}
/// Reads the spin.toml file as a raw manifest.
@@ -54,9 +60,10 @@ async fn prepare_any_version(
raw: RawAppManifestAnyVersion,
src: impl AsRef<Path>,
base_dst: impl AsRef<Path>,
+ bindle_connection: &Option<BindleConnectionInfo>,
) -> Result<Application> {
match raw {
- RawAppManifestAnyVersion::V1(raw) => prepare(raw, src, base_dst).await,
+ RawAppManifestAnyVersion::V1(raw) => prepare(raw, src, base_dst, bindle_connection).await,
}
}
@@ -79,6 +86,7 @@ async fn prepare(
mut raw: RawAppManifest,
src: impl AsRef<Path>,
base_dst: impl AsRef<Path>,
+ bindle_connection: &Option<BindleConnectionInfo>,
) -> Result<Application> {
let info = info(raw.info, &src);
@@ -104,7 +112,7 @@ async fn prepare(
let components = future::join_all(
raw.components
.into_iter()
- .map(|c| async { core(c, &src, &base_dst).await })
+ .map(|c| async { core(c, &src, &base_dst, bindle_connection).await })
.collect::<Vec<_>>(),
)
.await
@@ -125,7 +133,10 @@ async fn core(
raw: RawComponentManifest,
src: impl AsRef<Path>,
base_dst: impl AsRef<Path>,
+ bindle_connection: &Option<BindleConnectionInfo>,
) -> Result<CoreComponent> {
+ let id = raw.id;
+
let src = src
.as_ref()
.parent()
@@ -139,12 +150,33 @@ async fn core(
ModuleSource::FileReference(p)
}
- config::RawModuleSource::Bindle(_) => {
- todo!("Bindle module sources are not yet supported in file-based app config")
+ config::RawModuleSource::Bindle(b) => {
+ let bindle_id = bindle::Id::from_str(&b.reference).with_context(|| {
+ format!("Invalid bindle ID {} in component {}", b.reference, id)
+ })?;
+ let parcel_sha = &b.parcel;
+ let client = match bindle_connection {
+ None => anyhow::bail!(
+ "Component {} requires a Bindle connection but none was specified",
+ id
+ ),
+ Some(c) => c.client()?,
+ };
+ let bindle_reader = crate::bindle::BindleReader::remote(&client, &bindle_id);
+ let bytes = bindle_reader
+ .get_parcel(parcel_sha)
+ .await
+ .with_context(|| {
+ format!(
+ "Failed to download parcel {}@{} for component {}",
+ bindle_id, parcel_sha, id
+ )
+ })?;
+ let name = format!("{}@{}", bindle_id, parcel_sha);
+ ModuleSource::Buffer(bytes, name)
}
};
- let id = raw.id;
let description = raw.description;
let mounts = match raw.wasm.files {
Some(f) => assets::prepare_component(&f, src, &base_dst, &id).await?,
diff --git a/src/commands/up.rs b/src/commands/up.rs
index 022e69c40e..e0532535e4 100644
--- a/src/commands/up.rs
+++ b/src/commands/up.rs
@@ -3,6 +3,7 @@ use std::sync::Arc;
use anyhow::{bail, Context, Result};
use clap::{Args, Parser};
+use spin_loader::bindle::BindleConnectionInfo;
use tempfile::TempDir;
use spin_engine::io::FollowComponents;
@@ -133,7 +134,8 @@ impl UpCommand {
let manifest_file = app
.as_deref()
.unwrap_or_else(|| DEFAULT_MANIFEST_FILE.as_ref());
- spin_loader::from_file(manifest_file, working_dir).await?
+ let bindle_connection = self.bindle_connection();
+ spin_loader::from_file(manifest_file, working_dir, &bindle_connection).await?
}
(None, Some(bindle)) => match &self.server {
Some(server) => spin_loader::from_bindle(bindle, server, working_dir).await?,
@@ -222,6 +224,12 @@ impl UpCommand {
FollowComponents::Named(followed)
}
}
+
+ fn bindle_connection(&self) -> Option<BindleConnectionInfo> {
+ self.server
+ .as_ref()
+ .map(|url| BindleConnectionInfo::new(url, false, None, None))
+ }
}
enum WorkingDirectory {
| 456
|
[
"454"
] |
diff --git a/crates/loader/src/local/tests.rs b/crates/loader/src/local/tests.rs
index 1cef2e756c..7c4d03b9f3 100644
--- a/crates/loader/src/local/tests.rs
+++ b/crates/loader/src/local/tests.rs
@@ -11,7 +11,7 @@ async fn test_from_local_source() -> Result<()> {
let temp_dir = tempfile::tempdir()?;
let dir = temp_dir.path();
- let app = from_file(MANIFEST, dir).await?;
+ let app = from_file(MANIFEST, dir, &None).await?;
assert_eq!(app.info.name, "spin-local-source-test");
assert_eq!(app.info.version, "1.0.0");
@@ -145,7 +145,7 @@ async fn test_duplicate_component_id_is_rejected() -> Result<()> {
let temp_dir = tempfile::tempdir()?;
let dir = temp_dir.path();
- let app = from_file(MANIFEST, dir).await;
+ let app = from_file(MANIFEST, dir, &None).await;
assert!(
app.is_err(),
diff --git a/tests/http/simple-spin-rust/spin-from-parcel.toml b/tests/http/simple-spin-rust/spin-from-parcel.toml
new file mode 100644
index 0000000000..cbf8f4e08c
--- /dev/null
+++ b/tests/http/simple-spin-rust/spin-from-parcel.toml
@@ -0,0 +1,18 @@
+spin_version = "1"
+authors = ["Fermyon Engineering <engineering@fermyon.com>"]
+description = "A simple application that returns hello and goodbye."
+name = "spin-hello-from-parcel"
+trigger = {type = "http", base = "/test"}
+version = "1.0.0"
+
+[config]
+object = { default = "teapot" }
+
+[[component]]
+id = "hello"
+source = { reference = "spin-hello-world/1.0.0", parcel = "AWAITING_PARCEL_SHA" }
+files = [ { source = "assets", destination = "/" } ]
+[component.trigger]
+route = "/hello/..."
+[component.config]
+message = "I'm a {{object}}"
diff --git a/tests/integration.rs b/tests/integration.rs
index fe5925f7c5..2c482a1f7b 100644
--- a/tests/integration.rs
+++ b/tests/integration.rs
@@ -5,6 +5,7 @@ mod integration_tests {
use std::{
ffi::OsStr,
net::{Ipv4Addr, SocketAddrV4, TcpListener},
+ path::{Path, PathBuf},
process::{self, Child, Command},
time::Duration,
};
@@ -40,6 +41,7 @@ mod integration_tests {
RUST_HTTP_INTEGRATION_TEST, DEFAULT_MANIFEST_LOCATION
),
&[],
+ None,
)
.await?;
@@ -212,6 +214,57 @@ mod integration_tests {
Ok(())
}
+ #[tokio::test]
+ async fn test_using_parcel_as_module_source() -> Result<()> {
+ let wasm_path = PathBuf::from(RUST_HTTP_INTEGRATION_TEST)
+ .join("target")
+ .join("wasm32-wasi")
+ .join("release")
+ .join("spinhelloworld.wasm");
+ let parcel_sha = file_digest_string(&wasm_path).expect("failed to get sha for parcel");
+
+ // start the Bindle registry.
+ let config = BindleTestControllerConfig {
+ basic_auth_enabled: false,
+ };
+ let b = BindleTestController::new(config).await?;
+
+ // push the application to the registry using the Spin CLI.
+ run(
+ vec![
+ SPIN_BINARY,
+ "bindle",
+ "push",
+ "--file",
+ &format!(
+ "{}/{}",
+ RUST_HTTP_INTEGRATION_TEST, DEFAULT_MANIFEST_LOCATION
+ ),
+ "--bindle-server",
+ &b.url,
+ ],
+ None,
+ )?;
+
+ let manifest_template =
+ format!("{}/{}", RUST_HTTP_INTEGRATION_TEST, "spin-from-parcel.toml");
+ let manifest = replace_text(&manifest_template, "AWAITING_PARCEL_SHA", &parcel_sha);
+
+ let s = SpinTestController::with_manifest(
+ &format!("{}", manifest.path.display()),
+ &[],
+ Some(&b.url),
+ )
+ .await?;
+
+ assert_status(&s, "/test/hello", 200).await?;
+ assert_status(&s, "/test/hello/wildcards/should/be/handled", 200).await?;
+ assert_status(&s, "/thisshouldfail", 404).await?;
+ assert_status(&s, "/test/hello/test-placement", 200).await?;
+
+ Ok(())
+ }
+
async fn verify_headers(
s: &SpinTestController,
absolute_uri: &str,
@@ -273,16 +326,21 @@ mod integration_tests {
pub async fn with_manifest(
manifest_path: &str,
env: &[&str],
+ bindle_url: Option<&str>,
) -> Result<SpinTestController> {
// start Spin using the given application manifest and wait for the HTTP server to be available.
let url = format!("127.0.0.1:{}", get_random_port()?);
let mut args = vec!["up", "--file", manifest_path, "--listen", &url];
+ if let Some(b) = bindle_url {
+ args.push("--bindle-server");
+ args.push(b);
+ }
for v in env {
args.push("--env");
args.push(v);
}
- let spin_handle = Command::new(get_process(SPIN_BINARY))
+ let mut spin_handle = Command::new(get_process(SPIN_BINARY))
.args(args)
.env(
"RUST_LOG",
@@ -292,7 +350,7 @@ mod integration_tests {
.with_context(|| "executing Spin")?;
// ensure the server is accepting requests before continuing.
- wait_tcp(&url, SPIN_BINARY).await?;
+ wait_tcp(&url, &mut spin_handle, SPIN_BINARY).await?;
Ok(SpinTestController { url, spin_handle })
}
@@ -318,7 +376,7 @@ mod integration_tests {
args.push(v);
}
- let spin_handle = Command::new(get_process(SPIN_BINARY))
+ let mut spin_handle = Command::new(get_process(SPIN_BINARY))
.args(args)
.env(
"RUST_LOG",
@@ -328,7 +386,7 @@ mod integration_tests {
.with_context(|| "executing Spin")?;
// ensure the server is accepting requests before continuing.
- wait_tcp(&url, SPIN_BINARY).await?;
+ wait_tcp(&url, &mut spin_handle, SPIN_BINARY).await?;
Ok(SpinTestController { url, spin_handle })
}
@@ -383,7 +441,7 @@ mod integration_tests {
)
.spawn();
- let server_handle = match server_handle_result {
+ let mut server_handle = match server_handle_result {
Ok(h) => Ok(h),
Err(e) => {
let is_path_explicit = std::env::var(BINDLE_SERVER_PATH_ENV).is_ok();
@@ -404,7 +462,7 @@ mod integration_tests {
}
}?;
- wait_tcp(&address, BINDLE_SERVER_BINARY).await?;
+ wait_tcp(&address, &mut server_handle, BINDLE_SERVER_BINARY).await?;
Ok(Self {
url,
@@ -472,7 +530,7 @@ mod integration_tests {
)
}
- async fn wait_tcp(url: &str, target: &str) -> Result<()> {
+ async fn wait_tcp(url: &str, process: &mut Child, target: &str) -> Result<()> {
let mut wait_count = 0;
loop {
if wait_count >= 120 {
@@ -481,6 +539,14 @@ mod integration_tests {
target, url
);
}
+
+ if let Ok(Some(_)) = process.try_wait() {
+ panic!(
+ "Process exited before starting to serve {} to start on URL {}",
+ target, url
+ );
+ }
+
match TcpStream::connect(&url).await {
Ok(_) => break,
Err(_) => {
@@ -492,4 +558,33 @@ mod integration_tests {
Ok(())
}
+
+ fn file_digest_string(path: impl AsRef<Path>) -> Result<String> {
+ use sha2::{Digest, Sha256};
+ let mut file = std::fs::File::open(&path)?;
+ let mut sha = Sha256::new();
+ std::io::copy(&mut file, &mut sha)?;
+ let digest_value = sha.finalize();
+ let digest_string = format!("{:x}", digest_value);
+ Ok(digest_string)
+ }
+
+ struct AutoDeleteFile {
+ pub path: PathBuf,
+ }
+
+ fn replace_text(template_path: impl AsRef<Path>, from: &str, to: &str) -> AutoDeleteFile {
+ let dest = template_path.as_ref().with_extension("temp");
+ let source_text =
+ std::fs::read_to_string(template_path).expect("failed to read manifest template");
+ let result_text = source_text.replace(from, to);
+ std::fs::write(&dest, result_text).expect("failed to write temp manifest");
+ AutoDeleteFile { path: dest }
+ }
+
+ impl Drop for AutoDeleteFile {
+ fn drop(&mut self) {
+ std::fs::remove_file(&self.path).unwrap();
+ }
+ }
}
|
95f9da2a41aded597a437ad041a5a13ab19604ee
|
|
f267af00cd0fc0f809e403163763c059c86fbbef
|
Bindle server arg should be `--bindle-server`
Instead of just `--server`.
What else would be impacted by this change?
|
I don't see anything immediate, other than updating the documentation and making sure the argument is consistent across commands.
|
2022-05-06T19:16:17Z
|
fermyon__spin-452
|
fermyon/spin
|
0.1
|
diff --git a/src/commands/up.rs b/src/commands/up.rs
index 2eb078f024..c96a5ff284 100644
--- a/src/commands/up.rs
+++ b/src/commands/up.rs
@@ -41,7 +41,7 @@ pub struct UpCommand {
/// URL of bindle server.
#[clap(
name = BINDLE_SERVER_URL_OPT,
- long = "server",
+ long = "bindle-server",
env = BINDLE_URL_ENV,
)]
pub server: Option<String>,
| 452
|
[
"451"
] |
diff --git a/tests/integration.rs b/tests/integration.rs
index 265b5c4770..fe5925f7c5 100644
--- a/tests/integration.rs
+++ b/tests/integration.rs
@@ -305,7 +305,13 @@ mod integration_tests {
) -> Result<SpinTestController> {
let url = format!("127.0.0.1:{}", get_random_port()?);
let mut args = vec![
- "up", "--bindle", id, "--server", bindle_url, "--listen", &url,
+ "up",
+ "--bindle",
+ id,
+ "--bindle-server",
+ bindle_url,
+ "--listen",
+ &url,
];
for v in env {
args.push("--env");
|
95f9da2a41aded597a437ad041a5a13ab19604ee
|
a09fb1f2b6f9a52dee7dbcbe54e6f9ff41a72ea0
|
Add option to follow the component logs when running `spin up`
When running `spin up`, you see the _Spin_ logs, and the logs of components are saved in the configured logs directory.
I would like to propose optionally following the component logs in the standard output / error of the Spin process.
|
I can take a crack at this, but would like to raise what the UI might look like. A few thoughts (using `follow` as a sighting shot but that is up for grabs too).
**Option 1**
* `spin up --follow` - follows all components
It's terse, but not very selective if you have a lot of components.
**Option 2**
* `spin up --follow comp1 --follow comp2` - follows all specified components
Yes Ivan but what if you really do want to follow all of them what then.
**Option 3**
* `spin up --follow comp1 --follow comp2` - follows those components
* `spin up --follow-all` - follows all
Plenty of control but phew that's a lotta options to go in the help text.
**Option 4**
* `spin up --follow comp1 --follow comp2` - follows those components
* `spin up --follow` - follows all
Confusing? Even possible in structopt?
**Option 5**
* `spin up --follow comp1 --follow comp2` - follows those components
* `spin up --follow all` - follows all
A magic value! Would that be discoverable enough? Could we find one that couldn't clash with a component name and yet would not look weird?
**Option N**
Something else that is obvious but I haven't thought of yet!
cc @michelleN
If it was possible (yay for enum shenanigans?), I would very much like option 4.
I like that too. I will see if I can bend structopt to my will.
Looks like log handling is wired up at the trigger/executor level at the moment - the `http` trigger does various shenanigans to send component logs to files, the `redis` trigger uses the default stdio and so sends component logs to the console.
I tentatively assume that the desired behaviour after this change is as follows:
* By default, all component writes to stdout/stderr should go to the log directory.
* If a follow flag applies, component writes to stdout/stderr should go to Spin's stdout/stderr.
* Specific executors may assign special meaning to one of the component output streams, such as WAGI does to stdout. So executors should be able to opt out of the default behaviour.
But perhaps we should discuss and confirm? We want the behaviour to be useful to users, and perhaps the above is not right for all trigger types?
clap/structopt has defeated me for option 4. It seems to have firm views that an argument either takes a value or does not, and should jolly well make up its mind. You can handcraft `FromArgMatches` to provide smarter parsing, but it still wants a clear indication if the flag itself is to be followed by a value.
I suspect this is because `--follow foo` would be potentially ambiguous. If it allowed either, should it parse this as `--follow` with value `foo` , or `--follow` without value followed by an (unexpected) positional arg with value `foo`?
|
2022-05-03T04:36:34Z
|
fermyon__spin-431
|
fermyon/spin
|
0.1
|
diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs
index 6884a56957..cfa1d091d3 100644
--- a/crates/engine/src/io.rs
+++ b/crates/engine/src/io.rs
@@ -1,22 +1,215 @@
-use std::sync::{Arc, RwLock};
-use wasi_common::pipe::{ReadPipe, WritePipe};
-
-/// Input/Output stream redirects
-#[derive(Clone)]
-pub struct IoStreamRedirects {
- /// Standard input redirect.
- pub stdin: ReadPipe<std::io::Cursor<Vec<u8>>>,
- /// Standard output redirect.
- pub stdout: OutRedirect,
- /// Standard error redirect.
- pub stderr: OutRedirect,
-}
-
-/// Output redirect and lock.
-#[derive(Clone)]
-pub struct OutRedirect {
- /// Output redirect.
- pub out: WritePipe<Vec<u8>>,
- /// Lock for writing.
- pub lock: Arc<RwLock<Vec<u8>>>,
+use std::{
+ collections::HashSet,
+ io::{LineWriter, Write},
+ sync::{Arc, RwLock, RwLockReadGuard},
+};
+use wasi_common::{
+ pipe::{ReadPipe, WritePipe},
+ WasiFile,
+};
+
+/// Which components should have their logs followed on stdout/stderr.
+#[derive(Clone, Debug)]
+pub enum FollowComponents {
+ /// No components should have their logs followed.
+ None,
+ /// Only the specified components should have their logs followed.
+ Named(HashSet<String>),
+ /// All components should have their logs followed.
+ All,
+}
+
+impl FollowComponents {
+ /// Whether a given component should have its logs followed on stdout/stderr.
+ pub fn should_follow(&self, component_id: &str) -> bool {
+ match self {
+ Self::None => false,
+ Self::All => true,
+ Self::Named(ids) => ids.contains(component_id),
+ }
+ }
+}
+
+/// The buffers in which Wasm module output has been saved.
+pub trait OutputBuffers {
+ /// The buffer in which stdout has been saved.
+ fn stdout(&self) -> &[u8];
+ /// The buffer in which stderr has been saved.
+ fn stderr(&self) -> &[u8];
+}
+
+/// A set of redirected standard I/O streams with which
+/// a Wasm module is to be run.
+pub struct ModuleIoRedirects {
+ pub(crate) stdin: Box<dyn WasiFile>,
+ pub(crate) stdout: Box<dyn WasiFile>,
+ pub(crate) stderr: Box<dyn WasiFile>,
+}
+
+impl ModuleIoRedirects {
+ /// Constructs an instance from a set of WasiFile objects.
+ pub fn new(
+ stdin: Box<dyn WasiFile>,
+ stdout: Box<dyn WasiFile>,
+ stderr: Box<dyn WasiFile>,
+ ) -> Self {
+ Self {
+ stdin,
+ stdout,
+ stderr,
+ }
+ }
+}
+
+/// The destinations to which redirected module output will be written.
+/// Used for subsequently reading back the output.
+pub struct RedirectReadHandles {
+ stdout: Arc<RwLock<WriteDestinations>>,
+ stderr: Arc<RwLock<WriteDestinations>>,
+}
+
+impl RedirectReadHandles {
+ /// Acquires a read lock for the in-memory output buffers.
+ pub fn read(&self) -> impl OutputBuffers + '_ {
+ RedirectReadHandlesLock {
+ stdout: self.stdout.read().unwrap(),
+ stderr: self.stderr.read().unwrap(),
+ }
+ }
+}
+
+struct RedirectReadHandlesLock<'a> {
+ stdout: RwLockReadGuard<'a, WriteDestinations>,
+ stderr: RwLockReadGuard<'a, WriteDestinations>,
+}
+
+impl<'a> OutputBuffers for RedirectReadHandlesLock<'a> {
+ fn stdout(&self) -> &[u8] {
+ self.stdout.buffer()
+ }
+ fn stderr(&self) -> &[u8] {
+ self.stderr.buffer()
+ }
+}
+
+/// Prepares WASI pipes which redirect a component's output to
+/// memory buffers.
+pub fn capture_io_to_memory(
+ follow_on_stdout: bool,
+ follow_on_stderr: bool,
+) -> (ModuleIoRedirects, RedirectReadHandles) {
+ let stdout_follow = Follow::stdout(follow_on_stdout);
+ let stderr_follow = Follow::stderr(follow_on_stderr);
+
+ let stdin = ReadPipe::from(vec![]);
+
+ let (stdout_pipe, stdout_lock) = redirect_to_mem_buffer(stdout_follow);
+
+ let (stderr_pipe, stderr_lock) = redirect_to_mem_buffer(stderr_follow);
+
+ let redirects = ModuleIoRedirects {
+ stdin: Box::new(stdin),
+ stdout: Box::new(stdout_pipe),
+ stderr: Box::new(stderr_pipe),
+ };
+
+ let outputs = RedirectReadHandles {
+ stdout: stdout_lock,
+ stderr: stderr_lock,
+ };
+
+ (redirects, outputs)
+}
+
+/// Indicates whether a memory redirect should also pipe the output to
+/// the console so it can be followed live.
+pub enum Follow {
+ /// Do not pipe to console - only write to memory.
+ None,
+ /// Also pipe to stdout.
+ Stdout,
+ /// Also pipe to stderr.
+ Stderr,
+}
+
+impl Follow {
+ pub(crate) fn writer(&self) -> Box<dyn Write + Send + Sync> {
+ match self {
+ Self::None => Box::new(DiscardingWriter),
+ Self::Stdout => Box::new(LineWriter::new(std::io::stdout())),
+ Self::Stderr => Box::new(LineWriter::new(std::io::stderr())),
+ }
+ }
+
+ /// Follow on stdout if so specified.
+ pub fn stdout(follow_on_stdout: bool) -> Self {
+ if follow_on_stdout {
+ Self::Stdout
+ } else {
+ Self::None
+ }
+ }
+
+ /// Follow on stderr if so specified.
+ pub fn stderr(follow_on_stderr: bool) -> Self {
+ if follow_on_stderr {
+ Self::Stderr
+ } else {
+ Self::None
+ }
+ }
+}
+
+/// Prepares a WASI pipe which writes to a memory buffer, optionally
+/// copying to the specified output stream.
+pub fn redirect_to_mem_buffer(
+ follow: Follow,
+) -> (WritePipe<WriteDestinations>, Arc<RwLock<WriteDestinations>>) {
+ let immediate = follow.writer();
+
+ let buffer: Vec<u8> = vec![];
+ let std_dests = WriteDestinations { buffer, immediate };
+ let lock = Arc::new(RwLock::new(std_dests));
+ let std_pipe = WritePipe::from_shared(lock.clone());
+
+ (std_pipe, lock)
+}
+
+/// The destinations to which a component writes an output stream.
+pub struct WriteDestinations {
+ buffer: Vec<u8>,
+ immediate: Box<dyn Write + Send + Sync>,
+}
+
+impl WriteDestinations {
+ /// The memory buffer to which a component writes an output stream.
+ pub fn buffer(&self) -> &[u8] {
+ &self.buffer
+ }
+}
+
+impl Write for WriteDestinations {
+ fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
+ let written = self.buffer.write(buf)?;
+ self.immediate.write_all(&buf[0..written])?;
+ Ok(written)
+ }
+
+ fn flush(&mut self) -> std::io::Result<()> {
+ self.buffer.flush()?;
+ self.immediate.flush()?;
+ Ok(())
+ }
+}
+
+struct DiscardingWriter;
+
+impl Write for DiscardingWriter {
+ fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
+ Ok(buf.len())
+ }
+
+ fn flush(&mut self) -> std::io::Result<()> {
+ Ok(())
+ }
}
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 4ac9c3460b..0027491568 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -9,7 +9,7 @@ pub mod io;
use anyhow::{bail, Context, Result};
use host_component::{HostComponent, HostComponents, HostComponentsState};
-use io::IoStreamRedirects;
+use io::{ModuleIoRedirects, OutputBuffers};
use spin_config::{host_component::ComponentConfig, Resolver};
use spin_manifest::{Application, CoreComponent, DirectoryMount, ModuleSource};
use std::{collections::HashMap, io::Write, path::PathBuf, sync::Arc};
@@ -219,7 +219,7 @@ impl<T: Default> ExecutionContext<T> {
&self,
component: &str,
data: Option<T>,
- io: Option<IoStreamRedirects>,
+ io: Option<ModuleIoRedirects>,
env: Option<HashMap<String, String>>,
args: Option<Vec<String>>,
) -> Result<(Store<RuntimeContext<T>>, Instance)> {
@@ -238,7 +238,7 @@ impl<T: Default> ExecutionContext<T> {
/// Save logs for a given component in the log directory on the host
pub fn save_output_to_logs(
&self,
- io_redirects: IoStreamRedirects,
+ io_redirects: impl OutputBuffers,
component: &str,
save_stdout: bool,
save_stderr: bool,
@@ -274,18 +274,18 @@ impl<T: Default> ExecutionContext<T> {
.append(true)
.create(true)
.open(stdout_filename)?;
- let contents = io_redirects.stdout.lock.read().unwrap();
- file.write_all(&contents)?;
+ let contents = io_redirects.stdout();
+ file.write_all(contents)?;
}
if save_stderr {
- let contents = io_redirects.stderr.lock.read().unwrap();
let mut file = std::fs::OpenOptions::new()
.write(true)
.append(true)
.create(true)
.open(stderr_filename)?;
- file.write_all(&contents)?;
+ let contents = io_redirects.stderr();
+ file.write_all(contents)?;
}
Ok(())
@@ -295,7 +295,7 @@ impl<T: Default> ExecutionContext<T> {
&self,
component: &Component<T>,
data: Option<T>,
- io: Option<IoStreamRedirects>,
+ io: Option<ModuleIoRedirects>,
env: Option<HashMap<String, String>>,
args: Option<Vec<String>>,
) -> Result<Store<RuntimeContext<T>>> {
@@ -307,10 +307,7 @@ impl<T: Default> ExecutionContext<T> {
.envs(&env)?;
match io {
Some(r) => {
- wasi_ctx = wasi_ctx
- .stderr(Box::new(r.stderr.out))
- .stdout(Box::new(r.stdout.out))
- .stdin(Box::new(r.stdin));
+ wasi_ctx = wasi_ctx.stderr(r.stderr).stdout(r.stdout).stdin(r.stdin);
}
None => wasi_ctx = wasi_ctx.inherit_stdio(),
};
diff --git a/crates/http/src/lib.rs b/crates/http/src/lib.rs
index 9997d230f3..f0b16e6fd3 100644
--- a/crates/http/src/lib.rs
+++ b/crates/http/src/lib.rs
@@ -5,6 +5,7 @@ mod spin;
mod tls;
mod wagi;
+use spin_engine::io::FollowComponents;
use spin_manifest::{ComponentMap, HttpConfig, HttpTriggerConfiguration};
pub use tls::TlsConfig;
@@ -52,6 +53,8 @@ pub struct HttpTrigger {
router: Router,
/// Spin execution context.
engine: Arc<ExecutionContext>,
+ /// Which components should have their logs followed on stdout/stderr.
+ follow: FollowComponents,
}
#[derive(Clone)]
@@ -77,6 +80,7 @@ impl Trigger for HttpTrigger {
execution_context: ExecutionContext,
trigger_config: Self::Config,
component_triggers: ComponentMap<Self::ComponentConfig>,
+ follow: FollowComponents,
) -> Result<Self> {
let router = Router::build(&trigger_config.base, &component_triggers)?;
log::trace!(
@@ -90,6 +94,7 @@ impl Trigger for HttpTrigger {
component_triggers,
router,
engine: Arc::new(execution_context),
+ follow,
})
}
@@ -123,6 +128,8 @@ impl HttpTrigger {
None => &spin_manifest::HttpExecutor::Spin,
};
+ let follow = self.follow.should_follow(component_id);
+
let res = match executor {
spin_manifest::HttpExecutor::Spin => {
let executor = SpinHttpExecutor;
@@ -134,6 +141,7 @@ impl HttpTrigger {
&trigger.route,
req,
addr,
+ follow,
)
.await
}
@@ -149,6 +157,7 @@ impl HttpTrigger {
&trigger.route,
req,
addr,
+ follow,
)
.await
}
@@ -391,6 +400,9 @@ pub(crate) fn compute_default_headers<'a>(
/// All HTTP executors must implement this trait.
#[async_trait]
pub(crate) trait HttpExecutor: Clone + Send + Sync + 'static {
+ // TODO: allowing this lint because I want to gather feedback before
+ // investing time in reorganising this
+ #[allow(clippy::too_many_arguments)]
async fn execute(
&self,
engine: &ExecutionContext,
@@ -399,6 +411,7 @@ pub(crate) trait HttpExecutor: Clone + Send + Sync + 'static {
raw_route: &str,
req: Request<Body>,
client_addr: SocketAddr,
+ follow: bool,
) -> Result<Response<Body>>;
}
@@ -547,7 +560,8 @@ mod tests {
});
let app = cfg.build_application();
- let trigger: HttpTrigger = build_trigger_from_app(app, None, None).await?;
+ let trigger: HttpTrigger =
+ build_trigger_from_app(app, None, FollowComponents::None, None).await?;
let body = Body::from("Fermyon".as_bytes().to_vec());
let req = http::Request::post("https://myservice.fermyon.dev/test?abc=def")
@@ -575,7 +589,8 @@ mod tests {
});
let app = cfg.build_application();
- let trigger: HttpTrigger = build_trigger_from_app(app, None, None).await?;
+ let trigger: HttpTrigger =
+ build_trigger_from_app(app, None, FollowComponents::None, None).await?;
let body = Body::from("Fermyon".as_bytes().to_vec());
let req = http::Request::builder()
diff --git a/crates/http/src/spin.rs b/crates/http/src/spin.rs
index 29fee928c2..524edb32f1 100644
--- a/crates/http/src/spin.rs
+++ b/crates/http/src/spin.rs
@@ -6,16 +6,10 @@ use anyhow::Result;
use async_trait::async_trait;
use http::Uri;
use hyper::{Body, Request, Response};
-use spin_engine::io::{IoStreamRedirects, OutRedirect};
-use std::{
- net::SocketAddr,
- str,
- str::FromStr,
- sync::{Arc, RwLock},
-};
+use spin_engine::io::capture_io_to_memory;
+use std::{net::SocketAddr, str, str::FromStr};
use tokio::task::spawn_blocking;
use tracing::log;
-use wasi_common::pipe::{ReadPipe, WritePipe};
use wasmtime::{Instance, Store};
#[derive(Clone)]
@@ -31,22 +25,23 @@ impl HttpExecutor for SpinHttpExecutor {
raw_route: &str,
req: Request<Body>,
_client_addr: SocketAddr,
+ follow: bool,
) -> Result<Response<Body>> {
log::trace!(
"Executing request using the Spin executor for component {}",
component
);
- let io_redirects = prepare_io_redirects()?;
+ let (redirects, outputs) = capture_io_to_memory(follow, follow);
let (store, instance) =
- engine.prepare_component(component, None, Some(io_redirects.clone()), None, None)?;
+ engine.prepare_component(component, None, Some(redirects), None, None)?;
let resp_result = Self::execute_impl(store, instance, base, raw_route, req)
.await
.map_err(contextualise_err);
- let log_result = engine.save_output_to_logs(io_redirects, component, true, true);
+ let log_result = engine.save_output_to_logs(outputs.read(), component, true, true);
// Defer checking for failures until here so that the logging runs
// even if the guest code fails. (And when checking, check the guest
@@ -214,26 +209,6 @@ fn contextualise_err(e: anyhow::Error) -> anyhow::Error {
}
}
-pub fn prepare_io_redirects() -> Result<IoStreamRedirects> {
- let stdin = ReadPipe::from(vec![]);
-
- let stdout_buf: Vec<u8> = vec![];
- let lock = Arc::new(RwLock::new(stdout_buf));
- let stdout = WritePipe::from_shared(lock.clone());
- let stdout = OutRedirect { out: stdout, lock };
-
- let stderr_buf: Vec<u8> = vec![];
- let lock = Arc::new(RwLock::new(stderr_buf));
- let stderr = WritePipe::from_shared(lock.clone());
- let stderr = OutRedirect { out: stderr, lock };
-
- Ok(IoStreamRedirects {
- stdin,
- stdout,
- stderr,
- })
-}
-
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/http/src/wagi.rs b/crates/http/src/wagi.rs
index 7d1ff4bf47..5f3003970f 100644
--- a/crates/http/src/wagi.rs
+++ b/crates/http/src/wagi.rs
@@ -2,12 +2,14 @@ use crate::{routes::RoutePattern, ExecutionContext, HttpExecutor};
use anyhow::Result;
use async_trait::async_trait;
use hyper::{body, Body, Request, Response};
-use spin_engine::io::{IoStreamRedirects, OutRedirect};
+use spin_engine::io::{
+ redirect_to_mem_buffer, Follow, ModuleIoRedirects, OutputBuffers, WriteDestinations,
+};
use spin_manifest::WagiConfig;
use std::{
collections::HashMap,
net::SocketAddr,
- sync::{Arc, RwLock},
+ sync::{Arc, RwLock, RwLockReadGuard},
};
use tokio::task::spawn_blocking;
use tracing::log;
@@ -28,6 +30,7 @@ impl HttpExecutor for WagiHttpExecutor {
raw_route: &str,
req: Request<Body>,
client_addr: SocketAddr,
+ follow: bool,
) -> Result<Response<Body>> {
log::trace!(
"Executing request using the Wagi executor for component {}",
@@ -51,7 +54,7 @@ impl HttpExecutor for WagiHttpExecutor {
let body = body::to_bytes(body).await?.to_vec();
let len = body.len();
- let iostream = Self::streams_from_body(body);
+ let (redirects, outputs) = Self::streams_from_body(body, follow);
// TODO
// The default host and TLS fields are currently hard-coded.
let mut headers = wagi::http_util::build_headers(
@@ -86,7 +89,7 @@ impl HttpExecutor for WagiHttpExecutor {
let (mut store, instance) = engine.prepare_component(
component,
None,
- Some(iostream.clone()),
+ Some(redirects),
Some(headers),
Some(argv.split(' ').map(|s| s.to_owned()).collect()),
)?;
@@ -104,7 +107,7 @@ impl HttpExecutor for WagiHttpExecutor {
let guest_result = spawn_blocking(move || start.call(&mut store, &[], &mut [])).await;
tracing::info!("Module execution complete");
- let log_result = engine.save_output_to_logs(iostream.clone(), component, false, true);
+ let log_result = engine.save_output_to_logs(outputs.read(), component, false, true);
// Defer checking for failures until here so that the logging runs
// even if the guest code fails. (And when checking, check the guest
@@ -113,31 +116,66 @@ impl HttpExecutor for WagiHttpExecutor {
guest_result?.or_else(ignore_successful_proc_exit_trap)?;
log_result?;
- wagi::handlers::compose_response(iostream.stdout.lock)
+ wagi::handlers::compose_response(outputs.stdout)
}
}
impl WagiHttpExecutor {
- fn streams_from_body(body: Vec<u8>) -> IoStreamRedirects {
+ fn streams_from_body(
+ body: Vec<u8>,
+ follow_on_stderr: bool,
+ ) -> (ModuleIoRedirects, WagiRedirectReadHandles) {
let stdin = ReadPipe::from(body);
+
let stdout_buf = vec![];
- let lock = Arc::new(RwLock::new(stdout_buf));
- let stdout = WritePipe::from_shared(lock.clone());
- let stdout = OutRedirect { out: stdout, lock };
-
- let stderr_buf = vec![];
- let lock = Arc::new(RwLock::new(stderr_buf));
- let stderr = WritePipe::from_shared(lock.clone());
- let stderr = OutRedirect { out: stderr, lock };
-
- IoStreamRedirects {
- stdin,
- stdout,
- stderr,
+ let stdout_lock = Arc::new(RwLock::new(stdout_buf));
+ let stdout_pipe = WritePipe::from_shared(stdout_lock.clone());
+
+ let (stderr_pipe, stderr_lock) = redirect_to_mem_buffer(Follow::stderr(follow_on_stderr));
+
+ let rd = ModuleIoRedirects::new(
+ Box::new(stdin),
+ Box::new(stdout_pipe),
+ Box::new(stderr_pipe),
+ );
+
+ let h = WagiRedirectReadHandles {
+ stdout: stdout_lock,
+ stderr: stderr_lock,
+ };
+
+ (rd, h)
+ }
+}
+
+struct WagiRedirectReadHandles {
+ stdout: Arc<RwLock<Vec<u8>>>,
+ stderr: Arc<RwLock<WriteDestinations>>,
+}
+
+impl WagiRedirectReadHandles {
+ fn read(&self) -> impl OutputBuffers + '_ {
+ WagiRedirectReadHandlesLock {
+ stdout: self.stdout.read().unwrap(),
+ stderr: self.stderr.read().unwrap(),
}
}
}
+struct WagiRedirectReadHandlesLock<'a> {
+ stdout: RwLockReadGuard<'a, Vec<u8>>,
+ stderr: RwLockReadGuard<'a, WriteDestinations>,
+}
+
+impl<'a> OutputBuffers for WagiRedirectReadHandlesLock<'a> {
+ fn stdout(&self) -> &[u8] {
+ &self.stdout
+ }
+ fn stderr(&self) -> &[u8] {
+ self.stderr.buffer()
+ }
+}
+
fn ignore_successful_proc_exit_trap(guest_err: anyhow::Error) -> Result<()> {
match guest_err.root_cause().downcast_ref::<wasmtime::Trap>() {
Some(trap) => match trap.i32_exit_status() {
diff --git a/crates/redis/src/lib.rs b/crates/redis/src/lib.rs
index ef894155d9..6960570cd4 100644
--- a/crates/redis/src/lib.rs
+++ b/crates/redis/src/lib.rs
@@ -7,6 +7,7 @@ use anyhow::Result;
use async_trait::async_trait;
use futures::StreamExt;
use redis::{Client, ConnectionLike};
+use spin_engine::io::FollowComponents;
use spin_manifest::{ComponentMap, RedisConfig, RedisTriggerConfiguration};
use spin_redis::SpinRedisData;
use spin_trigger::Trigger;
@@ -28,6 +29,8 @@ pub struct RedisTrigger {
engine: Arc<ExecutionContext>,
/// Map from channel name to tuple of component name & index.
subscriptions: HashMap<String, usize>,
+ /// Which components should have their logs followed on stdout/stderr.
+ follow: FollowComponents,
}
#[async_trait]
@@ -41,6 +44,7 @@ impl Trigger for RedisTrigger {
execution_context: ExecutionContext,
trigger_config: Self::Config,
component_triggers: ComponentMap<Self::ComponentConfig>,
+ follow: FollowComponents,
) -> Result<Self> {
let subscriptions = execution_context
.config
@@ -59,6 +63,7 @@ impl Trigger for RedisTrigger {
component_triggers,
engine: Arc::new(execution_context),
subscriptions,
+ follow,
})
}
@@ -112,6 +117,8 @@ impl RedisTrigger {
.and_then(|t| t.executor.clone())
.unwrap_or_default();
+ let follow = self.follow.should_follow(&component.id);
+
match executor {
spin_manifest::RedisExecutor::Spin => {
log::trace!("Executing Spin Redis component {}", component.id);
@@ -122,6 +129,7 @@ impl RedisTrigger {
&component.id,
channel,
msg.get_payload_bytes(),
+ follow,
)
.await?
}
@@ -144,6 +152,7 @@ pub(crate) trait RedisExecutor: Clone + Send + Sync + 'static {
component: &str,
channel: &str,
payload: &[u8],
+ follow: bool,
) -> Result<()>;
}
diff --git a/crates/redis/src/spin.rs b/crates/redis/src/spin.rs
index 6c9c9c1763..3b258151c8 100644
--- a/crates/redis/src/spin.rs
+++ b/crates/redis/src/spin.rs
@@ -1,6 +1,7 @@
use crate::{spin_redis::SpinRedis, ExecutionContext, RedisExecutor, RuntimeContext};
use anyhow::Result;
use async_trait::async_trait;
+use spin_engine::io::capture_io_to_memory;
use tokio::task::spawn_blocking;
use wasmtime::{Instance, Store};
@@ -15,14 +16,19 @@ impl RedisExecutor for SpinRedisExecutor {
component: &str,
channel: &str,
payload: &[u8],
+ follow: bool,
) -> Result<()> {
log::trace!(
"Executing request using the Spin executor for component {}",
component
);
- let (store, instance) = engine.prepare_component(component, None, None, None, None)?;
- match Self::execute_impl(store, instance, channel, payload.to_vec()).await {
+ let (redirects, outputs) = capture_io_to_memory(follow, follow);
+
+ let (store, instance) =
+ engine.prepare_component(component, None, Some(redirects), None, None)?;
+
+ let result = match Self::execute_impl(store, instance, channel, payload.to_vec()).await {
Ok(()) => {
log::trace!("Request finished OK");
Ok(())
@@ -31,7 +37,11 @@ impl RedisExecutor for SpinRedisExecutor {
log::trace!("Request finished with error {}", e);
Err(e)
}
- }
+ };
+
+ let log_result = engine.save_output_to_logs(outputs.read(), component, true, true);
+
+ result.and(log_result)
}
}
diff --git a/crates/trigger/src/lib.rs b/crates/trigger/src/lib.rs
index 0eefaddadc..2758845375 100644
--- a/crates/trigger/src/lib.rs
+++ b/crates/trigger/src/lib.rs
@@ -2,7 +2,7 @@ use std::{error::Error, path::PathBuf};
use anyhow::{Context, Result};
use async_trait::async_trait;
-use spin_engine::{Builder, ExecutionContext, ExecutionContextConfiguration};
+use spin_engine::{io::FollowComponents, Builder, ExecutionContext, ExecutionContextConfiguration};
use spin_manifest::{Application, ApplicationTrigger, ComponentMap, TriggerConfig};
/// The trigger
@@ -21,6 +21,7 @@ pub trait Trigger: Sized {
execution_context: ExecutionContext<Self::ContextData>,
config: Self::Config,
component_configs: ComponentMap<Self::ComponentConfig>,
+ follow: FollowComponents,
) -> Result<Self>;
async fn run(&self, run_config: Self::ExecutionConfig) -> Result<()>;
@@ -35,13 +36,19 @@ pub trait Trigger: Sized {
pub struct ExecutionOptions<T: Trigger> {
log_dir: Option<PathBuf>,
+ follow: FollowComponents,
execution_config: T::ExecutionConfig,
}
impl<T: Trigger> ExecutionOptions<T> {
- pub fn new(log_dir: Option<PathBuf>, execution_config: T::ExecutionConfig) -> Self {
+ pub fn new(
+ log_dir: Option<PathBuf>,
+ follow: FollowComponents,
+ execution_config: T::ExecutionConfig,
+ ) -> Self {
Self {
log_dir,
+ follow,
execution_config,
}
}
@@ -50,6 +57,7 @@ impl<T: Trigger> ExecutionOptions<T> {
pub async fn build_trigger_from_app<T: Trigger>(
app: Application,
log_dir: Option<PathBuf>,
+ follow: FollowComponents,
wasmtime_config: Option<wasmtime::Config>,
) -> Result<T>
where
@@ -88,7 +96,7 @@ where
})
.collect::<Result<_>>()?;
- T::new(execution_ctx, trigger_config, component_triggers)
+ T::new(execution_ctx, trigger_config, component_triggers, follow)
}
pub async fn run_trigger<T: Trigger>(
@@ -102,6 +110,7 @@ where
<T::Config as TryFrom<ApplicationTrigger>>::Error: Error + Send + Sync + 'static,
<T::ComponentConfig as TryFrom<TriggerConfig>>::Error: Error + Send + Sync + 'static,
{
- let trigger: T = build_trigger_from_app(app, opts.log_dir, wasmtime_config).await?;
+ let trigger: T =
+ build_trigger_from_app(app, opts.log_dir, opts.follow, wasmtime_config).await?;
trigger.run(opts.execution_config).await
}
diff --git a/examples/spin-timer/src/main.rs b/examples/spin-timer/src/main.rs
index 21324a36a1..7dd2dd321e 100644
--- a/examples/spin-timer/src/main.rs
+++ b/examples/spin-timer/src/main.rs
@@ -3,7 +3,7 @@
use anyhow::Result;
use async_trait::async_trait;
-use spin_engine::{Builder, ExecutionContextConfiguration};
+use spin_engine::{io::FollowComponents, Builder, ExecutionContextConfiguration};
use spin_manifest::{ComponentMap, CoreComponent, ModuleSource, WasmConfig};
use spin_timer::SpinTimerData;
use spin_trigger::Trigger;
@@ -27,7 +27,7 @@ async fn main() -> Result<()> {
..Default::default()
})
.await?;
- let trigger = TimerTrigger::new(builder, (), Default::default())?;
+ let trigger = TimerTrigger::new(builder, (), Default::default(), FollowComponents::None)?;
trigger
.run(TimerExecutionConfig {
interval: Duration::from_secs(1),
@@ -61,6 +61,7 @@ impl Trigger for TimerTrigger {
execution_context: ExecutionContext,
_: Self::Config,
_: ComponentMap<Self::ComponentConfig>,
+ _: FollowComponents,
) -> Result<Self> {
Ok(Self {
engine: Arc::new(execution_context),
diff --git a/src/commands/up.rs b/src/commands/up.rs
index c96a5ff284..022e69c40e 100644
--- a/src/commands/up.rs
+++ b/src/commands/up.rs
@@ -5,6 +5,7 @@ use anyhow::{bail, Context, Result};
use clap::{Args, Parser};
use tempfile::TempDir;
+use spin_engine::io::FollowComponents;
use spin_http_engine::{HttpTrigger, HttpTriggerExecutionConfig, TlsConfig};
use spin_manifest::ApplicationTrigger;
use spin_redis_engine::RedisTrigger;
@@ -102,6 +103,21 @@ pub struct UpOpts {
conflicts_with = DISABLE_WASMTIME_CACHE,
)]
pub cache: Option<PathBuf>,
+
+ /// Print output for given component(s) to stdout/stderr
+ #[clap(
+ name = FOLLOW_LOG_OPT,
+ long = "follow",
+ multiple_occurrences = true,
+ )]
+ pub follow_components: Vec<String>,
+
+ /// Print all component output to stdout/stderr
+ #[clap(
+ long = "follow-all",
+ conflicts_with = FOLLOW_LOG_OPT,
+ )]
+ pub follow_all_components: bool,
}
impl UpCommand {
@@ -154,12 +170,15 @@ impl UpCommand {
let wasmtime_config = self.wasmtime_default_config()?;
+ let follow = self.follow_components();
+
match &app.info.trigger {
ApplicationTrigger::Http(_) => {
run_trigger(
app,
ExecutionOptions::<HttpTrigger>::new(
self.opts.log.clone(),
+ follow,
HttpTriggerExecutionConfig::new(self.opts.address, tls),
),
Some(wasmtime_config),
@@ -169,12 +188,12 @@ impl UpCommand {
ApplicationTrigger::Redis(_) => {
run_trigger(
app,
- ExecutionOptions::<RedisTrigger>::new(self.opts.log.clone(), ()),
+ ExecutionOptions::<RedisTrigger>::new(self.opts.log.clone(), follow, ()),
Some(wasmtime_config),
)
.await?;
}
- }
+ };
// We need to be absolutely sure it stays alive until this point: we don't want
// any temp directory to be deleted prematurely.
@@ -192,6 +211,17 @@ impl UpCommand {
}
Ok(wasmtime_config)
}
+
+ fn follow_components(&self) -> FollowComponents {
+ if self.opts.follow_all_components {
+ FollowComponents::All
+ } else if self.opts.follow_components.is_empty() {
+ FollowComponents::None
+ } else {
+ let followed = self.opts.follow_components.clone().into_iter().collect();
+ FollowComponents::Named(followed)
+ }
+ }
}
enum WorkingDirectory {
diff --git a/src/opts.rs b/src/opts.rs
index cf8850d4f7..286db9737c 100644
--- a/src/opts.rs
+++ b/src/opts.rs
@@ -20,3 +20,4 @@ pub const JSON_MIME_TYPE: &str = "application/json";
pub const BUILD_UP_OPT: &str = "UP";
pub const DISABLE_WASMTIME_CACHE: &str = "DISABLE_WASMTIME_CACHE";
pub const WASMTIME_CACHE_FILE: &str = "WASMTIME_CACHE_FILE";
+pub const FOLLOW_LOG_OPT: &str = "FOLLOW_ID";
| 431
|
[
"380"
] |
diff --git a/crates/redis/src/tests.rs b/crates/redis/src/tests.rs
index be0949d31d..d5360cdf41 100644
--- a/crates/redis/src/tests.rs
+++ b/crates/redis/src/tests.rs
@@ -29,7 +29,8 @@ async fn test_pubsub() -> Result<()> {
});
let app = cfg.build_application();
- let trigger: RedisTrigger = build_trigger_from_app(app, None, None).await?;
+ let trigger: RedisTrigger =
+ build_trigger_from_app(app, None, FollowComponents::None, None).await?;
// TODO
// use redis::{FromRedisValue, Msg, Value};
diff --git a/crates/testing/src/lib.rs b/crates/testing/src/lib.rs
index b0eae31d92..7cb7b34fbe 100644
--- a/crates/testing/src/lib.rs
+++ b/crates/testing/src/lib.rs
@@ -8,7 +8,7 @@ use std::{
use http::{Request, Response};
use hyper::Body;
-use spin_engine::Builder;
+use spin_engine::{io::FollowComponents, Builder};
use spin_http_engine::HttpTrigger;
use spin_manifest::{
Application, ApplicationInformation, ApplicationOrigin, ApplicationTrigger, CoreComponent,
@@ -105,7 +105,7 @@ impl TestConfig {
pub async fn build_http_trigger(&self) -> HttpTrigger {
let app = self.build_application();
- spin_trigger::build_trigger_from_app(app, None, None)
+ spin_trigger::build_trigger_from_app(app, None, FollowComponents::None, None)
.await
.unwrap()
}
|
95f9da2a41aded597a437ad041a5a13ab19604ee
|
f04205bb1ff6cb21a0ed310203a4cca289d22496
|
Make Application clonable
We should make `Application` clonable, such that it could be used to constrct customized `ExecutionContext`.
```rust
--> crates/manifest/src/lib.rs:23:5
|
14 | #[derive(Clone, Debug)]
| ----- in this derive macro expansion
...
23 | pub config_resolver: Option<Resolver>,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Clone` is not implemented for `Resolver`
|
= note: required because of the requirements on the impl of `Clone` for `std::option::Option<Resolver>`
= note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info)
For more information about this error, try `rustc --explain E0277`.
error: could not compile `spin-manifest` due to previous error
```
One approach to do this is to change the type of config_resolver to `Option<Arc<Resolver>>`
Discussed with @radu-matei on this issue this morning.
|
cc @lann
I'd really like to remove `Application` from trigger initialization, but unfortunately the HTTP trigger config is currently deeply woven into the component config.
In the meantime it should be fine to wrap `config_resolver` in an `Arc`. It does currently get mutated in the `spin up` init code (which I need to find a better way of dealing with), but it shouldn't be cloned prior to that so `Arc::get_mut` ought to work there. If you don't intend to make that change I can.
@lann thanks for your response! I can get the commented code uncommented.
I happen to be working on some related code so I'll be making this change. If you've already done it I'll take care of conflicts later.
Sure go ahead!
|
2022-04-21T17:44:14Z
|
fermyon__spin-382
|
fermyon/spin
|
0.1
|
diff --git a/Cargo.lock b/Cargo.lock
index b37c0ed6a1..52ea51f938 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3339,6 +3339,7 @@ dependencies = [
"anyhow",
"http 0.2.6",
"hyper",
+ "spin-engine",
"spin-http-engine",
"spin-manifest",
]
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index d80859ba5f..5eb160bcf6 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -39,7 +39,7 @@ impl From<Application<CoreComponent>> for ExecutionContextConfiguration {
Self {
components: app.components,
label: app.info.name,
- config_resolver: app.config_resolver.map(Arc::new),
+ config_resolver: app.config_resolver,
..Default::default()
}
}
@@ -139,6 +139,7 @@ impl<T: Default> Builder<T> {
/// Builds a new instance of the execution context.
#[instrument(skip(self))]
pub async fn build(&mut self) -> Result<ExecutionContext<T>> {
+ let _sloth_warning = warn_if_slothful();
let mut components = HashMap::new();
for c in &self.config.components {
let core = c.clone();
@@ -186,18 +187,16 @@ impl<T: Default> Builder<T> {
})
}
+ /// Configures default host interface implementations.
+ pub fn link_defaults(&mut self) -> Result<&mut Self> {
+ self.link_wasi()?.link_http()?.link_config()
+ }
+
/// Builds a new default instance of the execution context.
pub async fn build_default(
config: ExecutionContextConfiguration,
) -> Result<ExecutionContext<T>> {
- let _sloth_warning = warn_if_slothful();
- Self::new(config)?
- .link_wasi()?
- .link_http()?
- .link_config()?
- .link_redis()?
- .build()
- .await
+ Self::new(config)?.link_defaults()?.build().await
}
}
diff --git a/crates/http/src/lib.rs b/crates/http/src/lib.rs
index 5c9b3da882..20191f4915 100644
--- a/crates/http/src/lib.rs
+++ b/crates/http/src/lib.rs
@@ -4,6 +4,7 @@ mod routes;
mod spin;
mod tls;
mod wagi;
+use spin_engine::Builder;
pub use tls::TlsConfig;
use crate::{
@@ -21,12 +22,11 @@ use hyper::{
service::{make_service_fn, service_fn},
Body, Request, Response, Server,
};
-use spin_engine::{Builder, ExecutionContextConfiguration};
use spin_http::SpinHttpData;
use spin_manifest::{
Application, ComponentMap, CoreComponent, HttpConfig, HttpTriggerConfiguration,
};
-use std::{future::ready, net::SocketAddr, path::PathBuf, sync::Arc};
+use std::{future::ready, net::SocketAddr, sync::Arc};
use tls_listener::TlsListener;
use tokio::net::{TcpListener, TcpStream};
use tokio_rustls::server::TlsStream;
@@ -62,10 +62,10 @@ pub struct HttpTrigger {
impl HttpTrigger {
/// Creates a new Spin HTTP trigger.
pub async fn new(
- address: String,
+ mut builder: Builder<SpinHttpData>,
app: Application<CoreComponent>,
+ address: String,
tls: Option<TlsConfig>,
- log_dir: Option<PathBuf>,
) -> Result<Self> {
let trigger_config = app
.info
@@ -82,12 +82,7 @@ impl HttpTrigger {
})?;
let router = Router::build(&app)?;
-
- let config = ExecutionContextConfiguration {
- log_dir,
- ..app.into()
- };
- let engine = Arc::new(Builder::build_default(config).await?);
+ let engine = Arc::new(builder.build().await?);
log::trace!("Created new HTTP trigger.");
@@ -533,15 +528,16 @@ mod tests {
async fn test_spin_http() -> Result<()> {
init();
- let cfg = spin_testing::TestConfig::default()
- .test_program("rust-http-test.wasm")
+ let mut cfg = spin_testing::TestConfig::default();
+ cfg.test_program("rust-http-test.wasm")
.http_trigger(HttpConfig {
route: "/test".to_string(),
executor: Some(HttpExecutor::Spin),
- })
- .build_application();
+ });
+ let app = cfg.build_application();
+ let engine = cfg.prepare_builder(app.clone()).await;
- let trigger = HttpTrigger::new("".to_string(), cfg, None, None).await?;
+ let trigger = HttpTrigger::new(engine, app, "".to_string(), None).await?;
let body = Body::from("Fermyon".as_bytes().to_vec());
let req = http::Request::post("https://myservice.fermyon.dev/test?abc=def")
@@ -562,15 +558,15 @@ mod tests {
async fn test_wagi_http() -> Result<()> {
init();
- let cfg = spin_testing::TestConfig::default()
- .test_program("wagi-test.wasm")
- .http_trigger(HttpConfig {
- route: "/test".to_string(),
- executor: Some(HttpExecutor::Wagi(Default::default())),
- })
- .build_application();
+ let mut cfg = spin_testing::TestConfig::default();
+ cfg.test_program("wagi-test.wasm").http_trigger(HttpConfig {
+ route: "/test".to_string(),
+ executor: Some(HttpExecutor::Wagi(Default::default())),
+ });
+ let app = cfg.build_application();
+ let engine = cfg.prepare_builder(app.clone()).await;
- let trigger = HttpTrigger::new("".to_string(), cfg, None, None).await?;
+ let trigger = HttpTrigger::new(engine, app, "".to_string(), None).await?;
let body = Body::from("Fermyon".as_bytes().to_vec());
let req = http::Request::builder()
diff --git a/crates/loader/src/bindle/mod.rs b/crates/loader/src/bindle/mod.rs
index 3214942403..0902c79e2b 100644
--- a/crates/loader/src/bindle/mod.rs
+++ b/crates/loader/src/bindle/mod.rs
@@ -23,7 +23,7 @@ use spin_manifest::{
Application, ApplicationInformation, ApplicationOrigin, CoreComponent, ModuleSource,
SpinVersion, WasmConfig,
};
-use std::path::Path;
+use std::{path::Path, sync::Arc};
use tracing::log;
pub use utils::{BindleTokenManager, SPIN_MANIFEST_MEDIA_TYPE};
@@ -72,7 +72,7 @@ async fn prepare(
config_root.merge_defaults(&path, config)?;
}
}
- let config_resolver = Some(spin_config::Resolver::new(config_root)?);
+ let config_resolver = Some(Arc::new(spin_config::Resolver::new(config_root)?));
let info = info(&raw, &invoice, url);
log::trace!("Application information from bindle: {:?}", info);
diff --git a/crates/loader/src/local/mod.rs b/crates/loader/src/local/mod.rs
index 0e336881fb..3b4396f9a5 100644
--- a/crates/loader/src/local/mod.rs
+++ b/crates/loader/src/local/mod.rs
@@ -18,7 +18,7 @@ use spin_manifest::{
Application, ApplicationInformation, ApplicationOrigin, CoreComponent, ModuleSource,
SpinVersion, WasmConfig,
};
-use std::path::Path;
+use std::{path::Path, sync::Arc};
use tokio::{fs::File, io::AsyncReadExt};
/// Given the path to a spin.toml manifest file, prepare its assets locally and
@@ -80,7 +80,7 @@ async fn prepare(
config_root.merge_defaults(&path, config)?;
}
}
- let config_resolver = Some(spin_config::Resolver::new(config_root)?);
+ let config_resolver = Some(Arc::new(spin_config::Resolver::new(config_root)?));
let component_triggers = raw
.components
diff --git a/crates/manifest/src/lib.rs b/crates/manifest/src/lib.rs
index 4eee13db15..a7e698a8fb 100644
--- a/crates/manifest/src/lib.rs
+++ b/crates/manifest/src/lib.rs
@@ -8,10 +8,11 @@ use std::{
collections::HashMap,
fmt::{Debug, Formatter},
path::PathBuf,
+ sync::Arc,
};
/// Application configuration.
-#[derive(Debug)]
+#[derive(Clone, Debug)]
pub struct Application<T> {
/// General application information.
pub info: ApplicationInformation,
@@ -20,7 +21,7 @@ pub struct Application<T> {
/// Configuration for the components' triggers.
pub component_triggers: ComponentMap<TriggerConfig>,
/// Application-specific configuration resolver.
- pub config_resolver: Option<Resolver>,
+ pub config_resolver: Option<Arc<Resolver>>,
}
/// Spin API version.
diff --git a/crates/redis/src/lib.rs b/crates/redis/src/lib.rs
index 1260c5b095..2927462739 100644
--- a/crates/redis/src/lib.rs
+++ b/crates/redis/src/lib.rs
@@ -7,12 +7,12 @@ use anyhow::{anyhow, Result};
use async_trait::async_trait;
use futures::StreamExt;
use redis::{Client, ConnectionLike};
-use spin_engine::{Builder, ExecutionContextConfiguration};
+use spin_engine::Builder;
use spin_manifest::{
Application, ComponentMap, CoreComponent, RedisConfig, RedisTriggerConfiguration,
};
use spin_redis::SpinRedisData;
-use std::{collections::HashMap, path::PathBuf, sync::Arc};
+use std::{collections::HashMap, sync::Arc};
wit_bindgen_wasmtime::import!("../../wit/ephemeral/spin-redis.wit");
@@ -34,7 +34,10 @@ pub struct RedisTrigger {
impl RedisTrigger {
/// Create a new Spin Redis trigger.
- pub async fn new(app: Application<CoreComponent>, log_dir: Option<PathBuf>) -> Result<Self> {
+ pub async fn new(
+ mut builder: Builder<SpinRedisData>,
+ app: Application<CoreComponent>,
+ ) -> Result<Self> {
let trigger_config = app
.info
.trigger
@@ -56,11 +59,8 @@ impl RedisTrigger {
.filter_map(|(idx, c)| component_triggers.get(c).map(|c| (c.channel.clone(), idx)))
.collect();
- let config = ExecutionContextConfiguration {
- log_dir,
- ..app.into()
- };
- let engine = Arc::new(Builder::build_default(config).await?);
+ let engine = Arc::new(builder.build().await?);
+
log::trace!("Created new Redis trigger.");
Ok(Self {
diff --git a/src/commands/up.rs b/src/commands/up.rs
index 4010e93947..817fe0aebb 100644
--- a/src/commands/up.rs
+++ b/src/commands/up.rs
@@ -1,8 +1,12 @@
-use anyhow::{bail, Result};
+use anyhow::{bail, Context, Result};
+use spin_engine::{Builder, ExecutionContextConfiguration};
use spin_http_engine::{HttpTrigger, TlsConfig};
use spin_manifest::{Application, ApplicationTrigger, CoreComponent};
use spin_redis_engine::RedisTrigger;
-use std::path::{Path, PathBuf};
+use std::{
+ path::{Path, PathBuf},
+ sync::Arc,
+};
use structopt::{clap::AppSettings, StructOpt};
use tempfile::TempDir;
@@ -112,11 +116,14 @@ impl UpCommand {
append_env(&mut app, &self.env)?;
if let Some(ref mut resolver) = app.config_resolver {
+ // TODO(lann): This should be safe but ideally this get_mut would be refactored away.
+ let resolver = Arc::get_mut(resolver)
+ .context("Internal error: app.config_resolver unexpectedly shared")?;
// TODO(lann): Make config provider(s) configurable.
resolver.add_provider(spin_config::provider::env::EnvProvider::default());
}
- let tls = match (self.tls_key, self.tls_cert) {
+ let tls = match (self.tls_key.clone(), self.tls_cert.clone()) {
(Some(key_path), Some(cert_path)) => {
if !cert_path.is_file() {
bail!("TLS certificate file does not exist or is not a file")
@@ -135,11 +142,13 @@ impl UpCommand {
match &app.info.trigger {
ApplicationTrigger::Http(_) => {
- let trigger = HttpTrigger::new(self.address, app, tls, self.log).await?;
+ let builder = self.prepare_ctx_builder(app.clone()).await?;
+ let trigger = HttpTrigger::new(builder, app, self.address, tls).await?;
trigger.run().await?;
}
ApplicationTrigger::Redis(_) => {
- let trigger = RedisTrigger::new(app, self.log).await?;
+ let builder = self.prepare_ctx_builder(app.clone()).await?;
+ let trigger = RedisTrigger::new(builder, app).await?;
trigger.run().await?;
}
}
@@ -150,6 +159,19 @@ impl UpCommand {
Ok(())
}
+
+ async fn prepare_ctx_builder<T: Default>(
+ &self,
+ app: Application<CoreComponent>,
+ ) -> Result<Builder<T>> {
+ let config = ExecutionContextConfiguration {
+ log_dir: self.log.clone(),
+ ..app.into()
+ };
+ let mut builder = Builder::new(config)?;
+ builder.link_defaults()?;
+ Ok(builder)
+ }
}
/// Parse the environment variables passed in `key=value` pairs.
| 382
|
[
"376"
] |
diff --git a/crates/redis/src/tests.rs b/crates/redis/src/tests.rs
index 41967ac399..ca45ee7909 100644
--- a/crates/redis/src/tests.rs
+++ b/crates/redis/src/tests.rs
@@ -20,15 +20,16 @@ pub(crate) fn init() {
async fn test_pubsub() -> Result<()> {
init();
- let cfg = TestConfig::default()
- .test_program("redis-rust.wasm")
+ let mut cfg = TestConfig::default();
+ cfg.test_program("redis-rust.wasm")
.redis_trigger(RedisConfig {
channel: "messages".to_string(),
executor: Some(RedisExecutor::Spin),
- })
- .build_application();
+ });
+ let app = cfg.build_application();
+ let engine = cfg.prepare_builder(app.clone()).await;
- let trigger = RedisTrigger::new(cfg, None).await?;
+ let trigger = RedisTrigger::new(engine, app).await?;
// TODO
// use redis::{FromRedisValue, Msg, Value};
diff --git a/crates/testing/Cargo.toml b/crates/testing/Cargo.toml
index 5307ae4708..c8c415a77f 100644
--- a/crates/testing/Cargo.toml
+++ b/crates/testing/Cargo.toml
@@ -8,5 +8,6 @@ authors = ["Fermyon Engineering <engineering@fermyon.com>"]
anyhow = "1.0"
http = "0.2"
hyper = "0.14"
+spin-engine = { path = "../engine" }
spin-manifest = { path = "../manifest" }
spin-http-engine = { path = "../http" }
diff --git a/crates/testing/src/lib.rs b/crates/testing/src/lib.rs
index 6c7c7c4571..65fa3d978c 100644
--- a/crates/testing/src/lib.rs
+++ b/crates/testing/src/lib.rs
@@ -8,6 +8,7 @@ use std::{
use http::{Request, Response};
use hyper::Body;
+use spin_engine::Builder;
use spin_http_engine::HttpTrigger;
use spin_manifest::{
Application, ApplicationInformation, ApplicationOrigin, ApplicationTrigger, CoreComponent,
@@ -95,8 +96,16 @@ impl TestConfig {
}
}
+ pub async fn prepare_builder<T: Default>(&self, app: Application<CoreComponent>) -> Builder<T> {
+ let mut builder = Builder::new(app.into()).expect("Builder::new failed");
+ builder.link_defaults().expect("link_defaults failed");
+ builder
+ }
+
pub async fn build_http_trigger(&self) -> HttpTrigger {
- HttpTrigger::new("".to_string(), self.build_application(), None, None)
+ let app = self.build_application();
+ let builder = self.prepare_builder(app.clone()).await;
+ HttpTrigger::new(builder, app, "".to_string(), None)
.await
.expect("failed to build HttpTrigger")
}
|
95f9da2a41aded597a437ad041a5a13ab19604ee
|
a4079e321f69227632b82963cc2a5279a1cfa3ad
|
refactor: Host components
Currently, host-implemented interfaces have to be hard-coded in `engine` in a couple of places:
- the implementation state is included in `RuntimeContext`: https://github.com/fermyon/spin/blob/2be403465390f1a767181f16190aa4f14512c9f3/crates/engine/src/lib.rs#L49-L50
- a `link_*` method, which is called in `build_default`: https://github.com/fermyon/spin/blob/2be403465390f1a767181f16190aa4f14512c9f3/crates/engine/src/lib.rs#L106-L108
I'd like to invert this dependency by introducing a new `HostComponent` trait. After a little prototyping I think it can look something like:
```rust
pub trait HostComponent {
type State: Default + 'static;
fn add_to_linker<T>(id: String, linker: &mut wasmtime::Linker<crate::RuntimeContext<T>>);
fn initial_state(id: String) -> State;
}
```
implemented like:
```rust
impl HostComponent for OutboundHttp {
type State = Self;
fn add_to_linker<T>(id: String, linker: &mut Linker<RuntimeContext<T>>) {
wasi_outbound_http::add_to_linker(linker, |ctx| ctx.host_components.get_state(&id).unwrap())
}
}
```
_Note: The separate `State` type isn't necessary here but is needed for interfaces that use reftypes, which changes their state data type._
The component state would be held in a mapping on `RuntimeContext` as e.g.:
```rust
/// Host components data,
pub host_components: HashMap<String, Box<dyn Any>>,
```
There might be a performance issue here as this HashMap would be referenced once for every host component function call, but if that is the case we could switch to a more efficient form of mapping (perhaps a Vec with pre-computed indexes or even something more exotic/unsafe :grimacing:). If performance is a real problem here I _think_ its a solvable one but its a real tradeoff vs the organizational benefits of splitting things up like this. Other ideas for how to do this very welcome.
|
How should configuration work for these? A solution that might fit with our current manifest:
```toml
[config]
cat_images_root = { default = "cats/" }
[host-components]
file-object-store = { root = "{{ cat_images_root }}" }
outbound-http = { allowed_hosts = [ "..." ] }
```
Longer-term, I wonder if these could be combined with "normal" component dependencies. I suppose that would live in the mythical "profile"?
Should the configuration of these be in the application manifest, or in an environment configuration? For example, the object store that backs onto a local directory in dev but onto AWS in prod; outbound HTTP that allows connections to the bank's test environment in dev but the real monies in prod.
This may relate to having a general think about how we divide up developer/operator decisions...
It "should" be in the environment config, but we haven't got one.
As 'components' is already a heavily loaded word, could I suggest we call these 'host services'? 'Services' is a rarely used term that has no associated expectations, and will never lead to ambiguity.
Seriously... I'm jittery about the name 'component', as in the Spin environment it could easily cause confusion with the concept referred to by the `[[component]]` entries. The idea of treating them like dependencies which happen to be satisfied by the host rather than another Wasm module is certainly attractive, though.
"Host services" is exactly what I first thought to call them, and then I was attracted to them being dependencies that just happen to be satisfied by the host. 🙂
In some places, we have been referring to one of these as a "host implementation for a WebAssembly interface", which isn't terribly helpful either.
|
2022-04-21T15:25:48Z
|
fermyon__spin-381
|
fermyon/spin
|
0.1
|
diff --git a/Cargo.lock b/Cargo.lock
index 52ea51f938..fcae0caba2 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2145,6 +2145,8 @@ version = "0.1.0"
dependencies = [
"anyhow",
"redis",
+ "spin-engine",
+ "spin-manifest",
"wit-bindgen-wasmtime",
]
@@ -3096,6 +3098,7 @@ dependencies = [
"futures",
"hyper",
"lazy_static",
+ "outbound-redis",
"path-absolutize",
"semver",
"serde",
@@ -3135,7 +3138,6 @@ dependencies = [
"anyhow",
"bytes 1.1.0",
"dirs 4.0.0",
- "outbound-redis",
"sanitize-filename",
"spin-config",
"spin-manifest",
@@ -3251,6 +3253,8 @@ dependencies = [
"async-trait",
"cap-std",
"serde",
+ "spin-engine",
+ "spin-manifest",
"tracing",
"wasmtime",
"wit-bindgen-wasmtime",
diff --git a/Cargo.toml b/Cargo.toml
index b4d3be52f5..2d7f78f892 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -15,6 +15,7 @@ dunce = "1.0"
env_logger = "0.9"
futures = "0.3"
lazy_static = "1.4.0"
+outbound-redis = { path = "crates/outbound-redis" }
path-absolutize = "3.0.11"
semver = "1.0"
serde = { version = "1.0", features = [ "derive" ] }
diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml
index ffc91fe017..84ccfe2fa8 100644
--- a/crates/engine/Cargo.toml
+++ b/crates/engine/Cargo.toml
@@ -8,7 +8,6 @@ authors = ["Fermyon Engineering <engineering@fermyon.com>"]
anyhow = "1.0.44"
bytes = "1.1.0"
dirs = "4.0"
-outbound-redis = { path = "../outbound-redis" }
sanitize-filename = "0.3.0"
spin-config = { path = "../config" }
spin-manifest = { path = "../manifest" }
diff --git a/crates/engine/src/host_component.rs b/crates/engine/src/host_component.rs
new file mode 100644
index 0000000000..6fa1b63ec5
--- /dev/null
+++ b/crates/engine/src/host_component.rs
@@ -0,0 +1,89 @@
+use std::{any::Any, marker::PhantomData};
+
+use spin_manifest::CoreComponent;
+use wasmtime::Linker;
+
+use crate::RuntimeContext;
+
+/// Represents a host implementation of a Wasm interface.
+pub trait HostComponent: Send + Sync {
+ /// Host component runtime state.
+ type Data: Any + Send;
+
+ /// Add this component to the given Linker, using the given runtime state-getting closure.
+ fn add_to_linker<T>(
+ linker: &mut Linker<RuntimeContext<T>>,
+ data_handle: HostComponentsDataHandle<Self::Data>,
+ ) -> anyhow::Result<()>;
+
+ /// Build a new runtime state object for the given component.
+ fn build_data(&self, component: &CoreComponent) -> anyhow::Result<Self::Data>;
+}
+type HostComponentData = Box<dyn Any + Send>;
+
+type DataBuilder = Box<dyn Fn(&CoreComponent) -> anyhow::Result<HostComponentData> + Send + Sync>;
+
+#[derive(Default)]
+pub(crate) struct HostComponents {
+ data_builders: Vec<DataBuilder>,
+}
+
+impl HostComponents {
+ pub(crate) fn insert<'a, T: 'static, Component: HostComponent + 'static>(
+ &mut self,
+ linker: &'a mut Linker<RuntimeContext<T>>,
+ host_component: Component,
+ ) -> anyhow::Result<()> {
+ let handle = HostComponentsDataHandle {
+ idx: self.data_builders.len(),
+ _phantom: PhantomData,
+ };
+ Component::add_to_linker(linker, handle)?;
+ self.data_builders.push(Box::new(move |c| {
+ Ok(Box::new(host_component.build_data(c)?))
+ }));
+ Ok(())
+ }
+
+ pub(crate) fn build_data(&self, c: &CoreComponent) -> anyhow::Result<HostComponentsData> {
+ Ok(HostComponentsData(
+ self.data_builders
+ .iter()
+ .map(|build_data| build_data(c))
+ .collect::<anyhow::Result<_>>()?,
+ ))
+ }
+}
+
+/// A collection of host component data.
+#[derive(Default)]
+pub struct HostComponentsData(Vec<HostComponentData>);
+
+/// A handle to component data, used in HostComponent::add_to_linker.
+pub struct HostComponentsDataHandle<T> {
+ idx: usize,
+ _phantom: PhantomData<fn(T) -> T>,
+}
+
+impl<T: 'static> HostComponentsDataHandle<T> {
+ /// Get the component data associated with this handle from the RuntimeContext.
+ pub fn get_mut<'a, U>(&self, ctx: &'a mut RuntimeContext<U>) -> &'a mut T {
+ ctx.host_components_data
+ .0
+ .get_mut(self.idx)
+ .unwrap()
+ .downcast_mut()
+ .unwrap()
+ }
+}
+
+impl<T> Clone for HostComponentsDataHandle<T> {
+ fn clone(&self) -> Self {
+ Self {
+ idx: self.idx,
+ _phantom: PhantomData,
+ }
+ }
+}
+
+impl<T> Copy for HostComponentsDataHandle<T> {}
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 5eb160bcf6..47d3286513 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -2,10 +2,13 @@
#![deny(missing_docs)]
+/// Host components.
+pub mod host_component;
/// Input / Output redirects.
pub mod io;
use anyhow::{bail, Context, Result};
+use host_component::{HostComponent, HostComponents, HostComponentsData};
use io::IoStreamRedirects;
use spin_config::{host_component::ComponentConfig, Resolver};
use spin_manifest::{Application, CoreComponent, DirectoryMount, ModuleSource};
@@ -56,8 +59,8 @@ pub struct RuntimeContext<T> {
pub outbound_http: Option<wasi_outbound_http::OutboundHttp>,
/// Component configuration.
pub component_config: Option<spin_config::host_component::ComponentConfig>,
- /// Outbound Redis configuration.
- pub outbound_redis: Option<outbound_redis::OutboundRedis>,
+ /// Host components data.
+ pub host_components_data: HostComponentsData,
/// Generic runtime data that can be configured by specialized engines.
pub data: Option<T>,
}
@@ -68,9 +71,10 @@ pub struct Builder<T: Default> {
linker: Linker<RuntimeContext<T>>,
store: Store<RuntimeContext<T>>,
engine: Engine,
+ host_components: HostComponents,
}
-impl<T: Default> Builder<T> {
+impl<T: Default + 'static> Builder<T> {
/// Creates a new instance of the execution builder.
pub fn new(config: ExecutionContextConfiguration) -> Result<Builder<T>> {
Self::with_wasmtime_config(config, Default::default())
@@ -91,12 +95,14 @@ impl<T: Default> Builder<T> {
let engine = Engine::new(&wasmtime)?;
let store = Store::new(&engine, data);
let linker = Linker::new(&engine);
+ let host_components = Default::default();
Ok(Self {
config,
linker,
store,
engine,
+ host_components,
})
}
@@ -128,17 +134,19 @@ impl<T: Default> Builder<T> {
Ok(self)
}
- /// Configures the ability to execute outbound Redis commands.
- pub fn link_redis(&mut self) -> Result<&mut Self> {
- outbound_redis::add_to_linker(&mut self.linker, |ctx| {
- ctx.outbound_redis.as_mut().unwrap()
- })?;
+ /// Adds a HostComponent to the execution context.
+ pub fn add_host_component(
+ &mut self,
+ host_component: impl HostComponent + 'static,
+ ) -> Result<&mut Self> {
+ self.host_components
+ .insert(&mut self.linker, host_component)?;
Ok(self)
}
/// Builds a new instance of the execution context.
#[instrument(skip(self))]
- pub async fn build(&mut self) -> Result<ExecutionContext<T>> {
+ pub async fn build(mut self) -> Result<ExecutionContext<T>> {
let _sloth_warning = warn_if_slothful();
let mut components = HashMap::new();
for c in &self.config.components {
@@ -175,15 +183,13 @@ impl<T: Default> Builder<T> {
components.insert(c.id.clone(), Component { core, pre });
}
- let config = self.config.clone();
- let engine = self.engine.clone();
-
log::trace!("Execution context initialized.");
Ok(ExecutionContext {
- config,
- engine,
+ config: self.config,
+ engine: self.engine,
components,
+ host_components: Arc::new(self.host_components),
})
}
@@ -196,7 +202,9 @@ impl<T: Default> Builder<T> {
pub async fn build_default(
config: ExecutionContextConfiguration,
) -> Result<ExecutionContext<T>> {
- Self::new(config)?.link_defaults()?.build().await
+ let mut builder = Self::new(config)?;
+ builder.link_defaults()?;
+ builder.build().await
}
}
@@ -218,6 +226,8 @@ pub struct ExecutionContext<T: Default> {
pub engine: Engine,
/// Collection of pre-initialized (and already linked) components.
pub components: HashMap<String, Component<T>>,
+
+ host_components: Arc<HostComponents>,
}
impl<T: Default> ExecutionContext<T> {
@@ -344,10 +354,11 @@ impl<T: Default> ExecutionContext<T> {
Some(ComponentConfig::new(&component.core.id, resolver.clone())?);
}
+ ctx.host_components_data = self.host_components.build_data(&component.core)?;
+
ctx.wasi = Some(wasi_ctx.build());
ctx.experimental_http = Some(experimental_http);
ctx.outbound_http = Some(outbound_http);
- ctx.outbound_redis = Some(outbound_redis::OutboundRedis);
ctx.data = data;
let store = Store::new(&self.engine, ctx);
diff --git a/crates/http/src/lib.rs b/crates/http/src/lib.rs
index 20191f4915..30b5b44216 100644
--- a/crates/http/src/lib.rs
+++ b/crates/http/src/lib.rs
@@ -62,7 +62,7 @@ pub struct HttpTrigger {
impl HttpTrigger {
/// Creates a new Spin HTTP trigger.
pub async fn new(
- mut builder: Builder<SpinHttpData>,
+ builder: Builder<SpinHttpData>,
app: Application<CoreComponent>,
address: String,
tls: Option<TlsConfig>,
diff --git a/crates/object-store/Cargo.toml b/crates/object-store/Cargo.toml
index b1d5b8849b..acc208a626 100644
--- a/crates/object-store/Cargo.toml
+++ b/crates/object-store/Cargo.toml
@@ -12,6 +12,8 @@ anyhow = "1.0"
async-trait = "0.1"
cap-std = "0.24.1"
serde = { version = "1.0", features = ["derive"] }
+spin-engine = { path = "../engine" }
+spin-manifest = { path = "../manifest" }
tracing = { version = "0.1", features = ["log"] }
wasmtime = "0.34"
wit-bindgen-wasmtime = { git = "https://github.com/bytecodealliance/wit-bindgen", rev = "2f46ce4cc072107153da0cefe15bdc69aa5b84d0" }
\ No newline at end of file
diff --git a/crates/object-store/src/file.rs b/crates/object-store/src/file.rs
index ee59a859f1..557d5eb74f 100644
--- a/crates/object-store/src/file.rs
+++ b/crates/object-store/src/file.rs
@@ -7,11 +7,8 @@ use std::{
use crate::wit::spin_object_store;
use anyhow::Context;
use cap_std::{ambient_authority, fs::OpenOptions};
-
-pub type FileObjectStoreData = (
- FileObjectStore,
- spin_object_store::SpinObjectStoreTables<FileObjectStore>,
-);
+use spin_engine::host_component::{HostComponent, HostComponentsDataHandle};
+use spin_manifest::CoreComponent;
pub struct FileObjectStore {
root: cap_std::fs::Dir,
@@ -25,9 +22,29 @@ impl FileObjectStore {
}
}
-impl From<FileObjectStore> for FileObjectStoreData {
- fn from(fos: FileObjectStore) -> Self {
- (fos, Default::default())
+pub struct FileObjectStoreComponent {
+ pub root: Path,
+}
+
+impl HostComponent for FileObjectStoreComponent {
+ type Data = (
+ FileObjectStore,
+ spin_object_store::SpinObjectStoreTables<FileObjectStore>,
+ );
+
+ fn add_to_linker<T>(
+ linker: &mut wasmtime::Linker<spin_engine::RuntimeContext<T>>,
+ data_handle: HostComponentsDataHandle<Self::Data>,
+ ) -> anyhow::Result<()> {
+ crate::add_to_linker(linker, move |ctx| {
+ let (data, table) = data_handle.get_mut(ctx);
+ (data, table)
+ })
+ }
+
+ fn build_data(&self, _component: &CoreComponent) -> anyhow::Result<Self::Data> {
+ let store = FileObjectStore::new(&self.root)?;
+ Ok((store, Default::default()))
}
}
diff --git a/crates/outbound-redis/Cargo.toml b/crates/outbound-redis/Cargo.toml
index 55b7211616..8e9d2b136d 100644
--- a/crates/outbound-redis/Cargo.toml
+++ b/crates/outbound-redis/Cargo.toml
@@ -9,4 +9,6 @@ doctest = false
[dependencies]
anyhow = "1.0"
redis = { version = "0.21", features = [ "tokio-comp" ] }
+spin-engine = { path = "../engine" }
+spin-manifest = { path = "../manifest" }
wit-bindgen-wasmtime = { git = "https://github.com/bytecodealliance/wit-bindgen", rev = "2f46ce4cc072107153da0cefe15bdc69aa5b84d0" }
diff --git a/crates/outbound-redis/src/lib.rs b/crates/outbound-redis/src/lib.rs
index 14b054f775..99e5e98c82 100644
--- a/crates/outbound-redis/src/lib.rs
+++ b/crates/outbound-redis/src/lib.rs
@@ -2,6 +2,7 @@ use outbound_redis::*;
use redis::Commands;
pub use outbound_redis::add_to_linker;
+use spin_engine::host_component::HostComponent;
wit_bindgen_wasmtime::export!("../../wit/ephemeral/outbound-redis.wit");
@@ -9,6 +10,21 @@ wit_bindgen_wasmtime::export!("../../wit/ephemeral/outbound-redis.wit");
#[derive(Default, Clone)]
pub struct OutboundRedis;
+impl HostComponent for OutboundRedis {
+ type Data = Self;
+
+ fn add_to_linker<T>(
+ linker: &mut wit_bindgen_wasmtime::wasmtime::Linker<spin_engine::RuntimeContext<T>>,
+ data_handle: spin_engine::host_component::HostComponentsDataHandle<Self::Data>,
+ ) -> anyhow::Result<()> {
+ add_to_linker(linker, move |ctx| data_handle.get_mut(ctx))
+ }
+
+ fn build_data(&self, _component: &spin_manifest::CoreComponent) -> anyhow::Result<Self::Data> {
+ Ok(Self)
+ }
+}
+
impl outbound_redis::OutboundRedis for OutboundRedis {
fn publish(&mut self, address: &str, channel: &str, payload: &[u8]) -> Result<(), Error> {
let client = redis::Client::open(address).map_err(|_| Error::Error)?;
diff --git a/crates/redis/src/lib.rs b/crates/redis/src/lib.rs
index 2927462739..fc4f5e1f94 100644
--- a/crates/redis/src/lib.rs
+++ b/crates/redis/src/lib.rs
@@ -35,7 +35,7 @@ pub struct RedisTrigger {
impl RedisTrigger {
/// Create a new Spin Redis trigger.
pub async fn new(
- mut builder: Builder<SpinRedisData>,
+ builder: Builder<SpinRedisData>,
app: Application<CoreComponent>,
) -> Result<Self> {
let trigger_config = app
diff --git a/src/commands/up.rs b/src/commands/up.rs
index 817fe0aebb..bf94d95faf 100644
--- a/src/commands/up.rs
+++ b/src/commands/up.rs
@@ -160,7 +160,7 @@ impl UpCommand {
Ok(())
}
- async fn prepare_ctx_builder<T: Default>(
+ async fn prepare_ctx_builder<T: Default + 'static>(
&self,
app: Application<CoreComponent>,
) -> Result<Builder<T>> {
@@ -170,6 +170,7 @@ impl UpCommand {
};
let mut builder = Builder::new(config)?;
builder.link_defaults()?;
+ builder.add_host_component(outbound_redis::OutboundRedis)?;
Ok(builder)
}
}
| 381
|
[
"311"
] |
diff --git a/crates/testing/src/lib.rs b/crates/testing/src/lib.rs
index 65fa3d978c..ffd66ed28a 100644
--- a/crates/testing/src/lib.rs
+++ b/crates/testing/src/lib.rs
@@ -96,7 +96,10 @@ impl TestConfig {
}
}
- pub async fn prepare_builder<T: Default>(&self, app: Application<CoreComponent>) -> Builder<T> {
+ pub async fn prepare_builder<T: Default + 'static>(
+ &self,
+ app: Application<CoreComponent>,
+ ) -> Builder<T> {
let mut builder = Builder::new(app.into()).expect("Builder::new failed");
builder.link_defaults().expect("link_defaults failed");
builder
|
95f9da2a41aded597a437ad041a5a13ab19604ee
|
6d650ef75cddb93d6c46f876226b269d28ab769d
|
Rename `config` crate
After discussion about a better name for application config, we're going to rename the current `config` crate to `manifest` and use `config` for #307 unless we can come up with better names for those two things.
|
Do we want to refer to `spin.toml` as a "Spin application manifest" in the docs?
Edit: we call it "manifest file" in one place, but mostly "application configuration".
|
2022-04-06T14:01:05Z
|
fermyon__spin-326
|
fermyon/spin
|
0.1
|
diff --git a/Cargo.lock b/Cargo.lock
index e829c18ab3..8bc9cfe9d9 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3090,10 +3090,10 @@ dependencies = [
"path-absolutize",
"semver",
"serde",
- "spin-config",
"spin-engine",
"spin-http-engine",
"spin-loader",
+ "spin-manifest",
"spin-publish",
"spin-redis-engine",
"spin-templates",
@@ -3107,14 +3107,6 @@ dependencies = [
"vergen",
]
-[[package]]
-name = "spin-config"
-version = "0.1.0"
-dependencies = [
- "anyhow",
- "serde",
-]
-
[[package]]
name = "spin-engine"
version = "0.1.0"
@@ -3123,7 +3115,7 @@ dependencies = [
"bytes 1.1.0",
"dirs 4.0.0",
"sanitize-filename",
- "spin-config",
+ "spin-manifest",
"tempfile",
"tokio",
"tracing",
@@ -3157,8 +3149,8 @@ dependencies = [
"num_cpus",
"rustls-pemfile 0.3.0",
"serde",
- "spin-config",
"spin-engine",
+ "spin-manifest",
"spin-testing",
"tls-listener",
"tokio",
@@ -3194,7 +3186,7 @@ dependencies = [
"reqwest",
"serde",
"sha2 0.10.2",
- "spin-config",
+ "spin-manifest",
"tempfile",
"tokio",
"toml",
@@ -3219,6 +3211,14 @@ dependencies = [
"wit-bindgen-rust",
]
+[[package]]
+name = "spin-manifest"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "serde",
+]
+
[[package]]
name = "spin-publish"
version = "0.1.0"
@@ -3251,8 +3251,8 @@ dependencies = [
"log",
"redis",
"serde",
- "spin-config",
"spin-engine",
+ "spin-manifest",
"spin-testing",
"tokio",
"tracing",
@@ -3301,8 +3301,8 @@ dependencies = [
"anyhow",
"http 0.2.6",
"hyper",
- "spin-config",
"spin-http-engine",
+ "spin-manifest",
]
[[package]]
@@ -3315,8 +3315,8 @@ dependencies = [
"env_logger",
"futures",
"log",
- "spin-config",
"spin-engine",
+ "spin-manifest",
"tokio",
"tracing",
"tracing-futures",
diff --git a/Cargo.toml b/Cargo.toml
index ca2ff3772f..e74387b28c 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -18,7 +18,7 @@ lazy_static = "1.4.0"
path-absolutize = "3.0.11"
semver = "1.0"
serde = { version = "1.0", features = [ "derive" ] }
-spin-config = { path = "crates/config" }
+spin-manifest = { path = "crates/manifest" }
spin-engine = { path = "crates/engine" }
spin-http-engine = { path = "crates/http" }
spin-loader = { path = "crates/loader" }
@@ -42,10 +42,10 @@ vergen = { version = "7", default-features = false, features = [ "build", "git"
[workspace]
members = [
- "crates/config",
"crates/engine",
"crates/http",
"crates/loader",
+ "crates/manifest",
"crates/outbound-http",
"crates/redis",
"crates/templates",
diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml
index 1b971101af..f57cd9719a 100644
--- a/crates/engine/Cargo.toml
+++ b/crates/engine/Cargo.toml
@@ -9,7 +9,7 @@ anyhow = "1.0.44"
bytes = "1.1.0"
dirs = "4.0"
sanitize-filename = "0.3.0"
-spin-config = { path = "../config" }
+spin-manifest = { path = "../manifest" }
tempfile = "3.3.0"
tokio = { version = "1.10.0", features = [ "fs" ] }
tracing = { version = "0.1", features = [ "log" ] }
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 03113dcf78..2e1d99f49f 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -7,7 +7,7 @@ pub mod io;
use anyhow::{bail, Context, Result};
use io::IoStreamRedirects;
-use spin_config::{Application, CoreComponent, DirectoryMount, ModuleSource};
+use spin_manifest::{Application, CoreComponent, DirectoryMount, ModuleSource};
use std::{collections::HashMap, io::Write, path::PathBuf, sync::Arc};
use tokio::task::JoinHandle;
use tokio::time::{sleep, Duration};
diff --git a/crates/http/Cargo.toml b/crates/http/Cargo.toml
index 15454063e4..e670413510 100644
--- a/crates/http/Cargo.toml
+++ b/crates/http/Cargo.toml
@@ -20,7 +20,7 @@ hyper = { version = "0.14", features = ["full"] }
hyper-rustls = { version = "0.23.0" }
indexmap = "1.6"
serde = { version = "1.0", features = ["derive"] }
-spin-config = { path = "../config" }
+spin-manifest = { path = "../manifest" }
spin-engine = { path = "../engine" }
tls-listener = { version = "0.4.0", features = [
"rustls",
diff --git a/crates/http/benches/baseline.rs b/crates/http/benches/baseline.rs
index bbee36e2a4..2e1e7708e2 100644
--- a/crates/http/benches/baseline.rs
+++ b/crates/http/benches/baseline.rs
@@ -4,8 +4,8 @@ use criterion::{black_box, criterion_group, criterion_main, Criterion};
use futures::future::join_all;
use http::Request;
-use spin_config::{HttpConfig, HttpExecutor};
use spin_http_engine::HttpTrigger;
+use spin_manifest::{HttpConfig, HttpExecutor};
use spin_testing::{assert_http_response_success, TestConfig};
use tokio::runtime::Runtime;
use tokio::task;
diff --git a/crates/http/src/lib.rs b/crates/http/src/lib.rs
index a48fbf2907..5c9b3da882 100644
--- a/crates/http/src/lib.rs
+++ b/crates/http/src/lib.rs
@@ -21,9 +21,11 @@ use hyper::{
service::{make_service_fn, service_fn},
Body, Request, Response, Server,
};
-use spin_config::{Application, ComponentMap, CoreComponent, HttpConfig, HttpTriggerConfiguration};
use spin_engine::{Builder, ExecutionContextConfiguration};
use spin_http::SpinHttpData;
+use spin_manifest::{
+ Application, ComponentMap, CoreComponent, HttpConfig, HttpTriggerConfiguration,
+};
use std::{future::ready, net::SocketAddr, path::PathBuf, sync::Arc};
use tls_listener::TlsListener;
use tokio::net::{TcpListener, TcpStream};
@@ -115,11 +117,11 @@ impl HttpTrigger {
let executor = match &trigger.executor {
Some(i) => i,
- None => &spin_config::HttpExecutor::Spin,
+ None => &spin_manifest::HttpExecutor::Spin,
};
let res = match executor {
- spin_config::HttpExecutor::Spin => {
+ spin_manifest::HttpExecutor::Spin => {
let executor = SpinHttpExecutor;
executor
.execute(
@@ -132,7 +134,7 @@ impl HttpTrigger {
)
.await
}
- spin_config::HttpExecutor::Wagi(wagi_config) => {
+ spin_manifest::HttpExecutor::Wagi(wagi_config) => {
let executor = WagiHttpExecutor {
wagi_config: wagi_config.clone(),
};
@@ -400,7 +402,7 @@ pub(crate) trait HttpExecutor: Clone + Send + Sync + 'static {
mod tests {
use super::*;
use anyhow::Result;
- use spin_config::{HttpConfig, HttpExecutor};
+ use spin_manifest::{HttpConfig, HttpExecutor};
use spin_testing::test_socket_addr;
use std::{collections::BTreeMap, sync::Once};
@@ -537,7 +539,7 @@ mod tests {
route: "/test".to_string(),
executor: Some(HttpExecutor::Spin),
})
- .build_configuration();
+ .build_application();
let trigger = HttpTrigger::new("".to_string(), cfg, None, None).await?;
@@ -566,7 +568,7 @@ mod tests {
route: "/test".to_string(),
executor: Some(HttpExecutor::Wagi(Default::default())),
})
- .build_configuration();
+ .build_application();
let trigger = HttpTrigger::new("".to_string(), cfg, None, None).await?;
diff --git a/crates/http/src/routes.rs b/crates/http/src/routes.rs
index 222439a827..3386f8a950 100644
--- a/crates/http/src/routes.rs
+++ b/crates/http/src/routes.rs
@@ -5,7 +5,7 @@
use anyhow::{bail, Result};
use http::Uri;
use indexmap::IndexMap;
-use spin_config::{Application, CoreComponent};
+use spin_manifest::{Application, CoreComponent};
use std::fmt::Debug;
use tracing::log;
@@ -333,8 +333,8 @@ mod route_tests {
fn named_component(id: &str) -> CoreComponent {
CoreComponent {
id: id.to_string(),
- source: spin_config::ModuleSource::FileReference("FAKE".into()),
- wasm: spin_config::WasmConfig::default(),
+ source: spin_manifest::ModuleSource::FileReference("FAKE".into()),
+ wasm: spin_manifest::WasmConfig::default(),
}
}
}
diff --git a/crates/http/src/wagi.rs b/crates/http/src/wagi.rs
index 255a9d6839..9ae4a43973 100644
--- a/crates/http/src/wagi.rs
+++ b/crates/http/src/wagi.rs
@@ -2,8 +2,8 @@ use crate::{routes::RoutePattern, ExecutionContext, HttpExecutor};
use anyhow::Result;
use async_trait::async_trait;
use hyper::{body, Body, Request, Response};
-use spin_config::WagiConfig;
use spin_engine::io::{IoStreamRedirects, OutRedirect};
+use spin_manifest::WagiConfig;
use std::{
collections::HashMap,
net::SocketAddr,
diff --git a/crates/loader/Cargo.toml b/crates/loader/Cargo.toml
index ae362c2721..acf37442bf 100644
--- a/crates/loader/Cargo.toml
+++ b/crates/loader/Cargo.toml
@@ -20,7 +20,7 @@ regex = "1.5.4"
reqwest = "0.11.9"
sha2 = "0.10.1"
serde = { version = "1.0", features = [ "derive" ] }
-spin-config = { path = "../config" }
+spin-manifest = { path = "../manifest" }
tempfile = "3.3.0"
tokio = { version = "1.11", features = [ "full" ] }
toml = "0.5"
diff --git a/crates/loader/src/bindle/assets.rs b/crates/loader/src/bindle/assets.rs
index 3f849eeb79..c83e0a23b5 100644
--- a/crates/loader/src/bindle/assets.rs
+++ b/crates/loader/src/bindle/assets.rs
@@ -7,7 +7,7 @@ use crate::{
use anyhow::{anyhow, bail, Context, Result};
use bindle::{Id, Label};
use futures::future;
-use spin_config::DirectoryMount;
+use spin_manifest::DirectoryMount;
use std::path::Path;
use tokio::fs;
use tracing::log;
diff --git a/crates/loader/src/bindle/config.rs b/crates/loader/src/bindle/config.rs
index 82e7b6ba1c..7de9ccd383 100644
--- a/crates/loader/src/bindle/config.rs
+++ b/crates/loader/src/bindle/config.rs
@@ -6,7 +6,7 @@ use std::collections::HashMap;
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct RawAppManifest {
/// The application trigger.
- pub trigger: spin_config::ApplicationTrigger,
+ pub trigger: spin_manifest::ApplicationTrigger,
/// Configuration for the application components.
#[serde(rename = "component")]
@@ -26,7 +26,7 @@ pub struct RawComponentManifest {
#[serde(flatten)]
pub wasm: RawWasmConfig,
/// Trigger configuration.
- pub trigger: spin_config::TriggerConfig,
+ pub trigger: spin_manifest::TriggerConfig,
}
/// WebAssembly configuration.
diff --git a/crates/loader/src/bindle/mod.rs b/crates/loader/src/bindle/mod.rs
index 452d862654..9374df676e 100644
--- a/crates/loader/src/bindle/mod.rs
+++ b/crates/loader/src/bindle/mod.rs
@@ -19,7 +19,7 @@ use bindle::{
Invoice,
};
use futures::future;
-use spin_config::{
+use spin_manifest::{
Application, ApplicationInformation, ApplicationOrigin, CoreComponent, ModuleSource,
SpinVersion, WasmConfig,
};
diff --git a/crates/loader/src/local/assets.rs b/crates/loader/src/local/assets.rs
index 67d50f941c..304da5ae13 100644
--- a/crates/loader/src/local/assets.rs
+++ b/crates/loader/src/local/assets.rs
@@ -3,7 +3,7 @@
use crate::assets::{create_dir, ensure_all_under, ensure_under, to_relative};
use anyhow::{anyhow, bail, Context, Result};
use futures::future;
-use spin_config::DirectoryMount;
+use spin_manifest::DirectoryMount;
use std::path::{Path, PathBuf};
use tracing::log;
use walkdir::WalkDir;
diff --git a/crates/loader/src/local/config.rs b/crates/loader/src/local/config.rs
index d1065b62a6..0587cf70b7 100644
--- a/crates/loader/src/local/config.rs
+++ b/crates/loader/src/local/config.rs
@@ -5,7 +5,7 @@
#![deny(missing_docs)]
use serde::{Deserialize, Serialize};
-use spin_config::{ApplicationTrigger, TriggerConfig};
+use spin_manifest::{ApplicationTrigger, TriggerConfig};
use std::{collections::HashMap, path::PathBuf};
/// Container for any version of the manifest.
diff --git a/crates/loader/src/local/mod.rs b/crates/loader/src/local/mod.rs
index d9dcf99c73..a1694e5798 100644
--- a/crates/loader/src/local/mod.rs
+++ b/crates/loader/src/local/mod.rs
@@ -14,7 +14,7 @@ use anyhow::{anyhow, Context, Result};
use config::{RawAppInformation, RawAppManifest, RawAppManifestAnyVersion, RawComponentManifest};
use futures::future;
use path_absolutize::Absolutize;
-use spin_config::{
+use spin_manifest::{
Application, ApplicationInformation, ApplicationOrigin, CoreComponent, ModuleSource,
SpinVersion, WasmConfig,
};
diff --git a/crates/config/Cargo.toml b/crates/manifest/Cargo.toml
similarity index 89%
rename from crates/config/Cargo.toml
rename to crates/manifest/Cargo.toml
index 69ac17342b..92b0175a83 100644
--- a/crates/config/Cargo.toml
+++ b/crates/manifest/Cargo.toml
@@ -1,5 +1,5 @@
[package]
-name = "spin-config"
+name = "spin-manifest"
version = "0.1.0"
edition = "2021"
authors = [ "Fermyon Engineering <engineering@fermyon.com>" ]
diff --git a/crates/config/src/lib.rs b/crates/manifest/src/lib.rs
similarity index 100%
rename from crates/config/src/lib.rs
rename to crates/manifest/src/lib.rs
diff --git a/crates/redis/Cargo.toml b/crates/redis/Cargo.toml
index ff79dfec7d..c26dba8517 100644
--- a/crates/redis/Cargo.toml
+++ b/crates/redis/Cargo.toml
@@ -15,7 +15,7 @@ futures = "0.3"
log = { version = "0.4", default-features = false }
serde = { version = "1.0", features = [ "derive" ] }
spin-engine = { path = "../engine" }
-spin-config = { path = "../config" }
+spin-manifest = { path = "../manifest" }
redis = { version = "0.21", features = [ "tokio-comp" ] }
tokio = { version = "1.14", features = [ "full" ] }
tracing = { version = "0.1", features = [ "log" ] }
diff --git a/crates/redis/src/lib.rs b/crates/redis/src/lib.rs
index 1d8f7ac482..b3826c4419 100644
--- a/crates/redis/src/lib.rs
+++ b/crates/redis/src/lib.rs
@@ -7,10 +7,10 @@ use anyhow::{anyhow, Result};
use async_trait::async_trait;
use futures::StreamExt;
use redis::Client;
-use spin_config::{
+use spin_engine::{Builder, ExecutionContextConfiguration};
+use spin_manifest::{
Application, ComponentMap, CoreComponent, RedisConfig, RedisTriggerConfiguration,
};
-use spin_engine::{Builder, ExecutionContextConfiguration};
use spin_redis::SpinRedisData;
use std::{collections::HashMap, path::PathBuf, sync::Arc};
@@ -114,7 +114,7 @@ impl RedisTrigger {
.unwrap_or_default();
match executor {
- spin_config::RedisExecutor::Spin => {
+ spin_manifest::RedisExecutor::Spin => {
log::trace!("Executing Spin Redis component {}", component.id);
let executor = SpinRedisExecutor;
executor
diff --git a/docs/content/architecture.md b/docs/content/architecture.md
index 6e6f57e130..7877e4e2da 100644
--- a/docs/content/architecture.md
+++ b/docs/content/architecture.md
@@ -17,8 +17,8 @@ be pushed to the registry then referenced using its remote ID
Regardless of the application origin (local file or remote reference from the
registry), a Spin application is defined by
-`spin_config::Application<CoreComponent>` (contained in the
-[`spin-config`](https://github.com/fermyon/spin/tree/main/crates/config) crate),
+`spin_manifest::Application<CoreComponent>` (contained in the
+[`spin-manifest`](https://github.com/fermyon/spin/tree/main/crates/manifest) crate),
which is the canonical representation of a Spin application.
The crate responsible for transforming a custom configuration into a canonical
diff --git a/docs/content/configuration.md b/docs/content/configuration.md
index c478ee9fb3..96206cb296 100644
--- a/docs/content/configuration.md
+++ b/docs/content/configuration.md
@@ -7,8 +7,9 @@ url = "https://github.com/fermyon/spin/blob/main/docs/content/configuration.md"
Spin applications are comprised of general information (metadata), and a collection
of at least one _component_. Configuration for a Spin application lives in a TOML
-file called `spin.toml`. In the example below we can see a simple HTTP application
-with a single component executed when the `/hello` endpoint is accessed:
+file called `spin.toml` (the _application manifest_). In the example below we can see
+a simple HTTP application with a single component executed when the `/hello` endpoint
+is accessed:
```toml
spin_version = "1"
@@ -26,9 +27,9 @@ route = "/hello"
## Configuration reference
-### Application configuration
+### Application manifest
-The following are the fields supported by the `spin.toml` configuration file:
+The following are the fields supported by the `spin.toml` manifest file:
- `spin_version` (REQUIRED): Spin API version. Currently, this value MUST be
`"1"`.
diff --git a/docs/content/distributing-apps.md b/docs/content/distributing-apps.md
index e8a0fdbbd1..3d3fdbe61e 100644
--- a/docs/content/distributing-apps.md
+++ b/docs/content/distributing-apps.md
@@ -7,7 +7,7 @@ url = "https://github.com/fermyon/spin/blob/main/docs/content/distributing-apps.
Packaging and distributing Spin applications is done using [Bindle](https://github.com/deislabs/bindle),
an open source aggregate object storage system. This allows the packaging of the
-application configuration, components, and static assets together, and
+application manifest, components, and static assets together, and
takes advantage of the features of a modern object storage system.
To distribute applications, we first need a Bindle registry. You can
diff --git a/docs/content/extending-and-embedding.md b/docs/content/extending-and-embedding.md
index 4e59b505e9..0f39b9a776 100644
--- a/docs/content/extending-and-embedding.md
+++ b/docs/content/extending-and-embedding.md
@@ -86,7 +86,7 @@ Finally, whenever there is a new event (in the case of our timer-based trigger
every `n` seconds), we execute the entry point of a selected component:
```rust
-/// Execute the first component in the application configuration.
+/// Execute the first component in the application manifest.
async fn handle(&self, msg: String) -> Result<()> {
// create a new Wasmtime store and instance based on the first component's WebAssembly module.
let (mut store, instance) =
@@ -139,7 +139,7 @@ fn handle_timer_request(msg: String) -> String {
```
Components can be compiled to WebAssembly, then used from a `spin.toml`
-application configuration.
+application manifest.
Embedding the new trigger in a Rust application is done by creating a new trigger
instance, then calling its `run` function:
@@ -155,7 +155,7 @@ trigger.run().await
> such as Go or C#.
In this example, we built a simple timer trigger — building more complex triggers
-would also involve updating the Spin application configuration, and extending
+would also involve updating the Spin application manifest, and extending
the application-level trigger configuration, as well as component-level
trigger configuration (an example of component-level trigger configuration
for this scenario would be each component being able to define its own
@@ -167,7 +167,7 @@ Besides building custom triggers, the internals of Spin could also be used
independently:
- the Spin execution context can be used entirely without a `spin.toml`
-application configuration — for embedding scenarios, the configuration for the
+application manifest — for embedding scenarios, the configuration for the
execution can be constructed without a `spin.toml` (see [issue #229](https://github.com/fermyon/spin/issues/229)
for context)
- the standard way of distributing a Spin application can be changed by
diff --git a/docs/content/go-components.md b/docs/content/go-components.md
index 345c7b439f..a2b67718e3 100644
--- a/docs/content/go-components.md
+++ b/docs/content/go-components.md
@@ -97,7 +97,7 @@ $ tinygo build -wasm-abi=generic -target=wasi -o main.wasm main.go
```
Before we can execute this component, we need to add the
-`https://some-random-api.ml` domain to the application configuration
+`https://some-random-api.ml` domain to the application manifest `allowed_http_hosts`
list containing the list of domains the component is allowed to make HTTP
requests to:
diff --git a/docs/content/http-trigger.md b/docs/content/http-trigger.md
index ba73b667a8..dad9c4fd37 100644
--- a/docs/content/http-trigger.md
+++ b/docs/content/http-trigger.md
@@ -12,7 +12,7 @@ some implementation details around the WebAssembly component model and how it
is used in Spin.
The HTTP trigger in Spin is a web server. It listens for incoming requests and
-based on the [application configuration](/configuration), it routes them to an
+based on the [application manifest](/configuration), it routes them to an
_executor_ which instantiates the appropriate component, executes its
entry point function, then returns an HTTP response.
diff --git a/docs/content/index.md b/docs/content/index.md
index 4644721c17..2fd55ed13e 100644
--- a/docs/content/index.md
+++ b/docs/content/index.md
@@ -14,8 +14,8 @@ microservices.
### Structure of a Spin Application
-1. A `spin.toml` file which defines where your WebAssembly components live and what
- triggers them.
+1. A Spin application manifest (`spin.toml`) file which defines where your WebAssembly
+ components live and what triggers them.
2. One or more WebAssembly _components_.
Spin executes the component(s) as a result of events being generated by the trigger(s)
@@ -38,7 +38,7 @@ fn hello_world(_req: http::Request) -> Result<http::Response> {
}
```
-#### Spin Configuration
+#### Spin Manifest
Once the code is compiled to a WebAssembly component, it can be referenced in a `spin.toml`
file to create an HTTP application like below.
diff --git a/docs/content/quickstart.md b/docs/content/quickstart.md
index b5e4d376fe..395c2acf41 100644
--- a/docs/content/quickstart.md
+++ b/docs/content/quickstart.md
@@ -67,7 +67,7 @@ This represents a simple Spin HTTP application (triggered by an HTTP request), w
a single component called `hello`. Spin will execute the `spinhelloworld.wasm`
WebAssembly module for HTTP requests on the route `/hello`.
(See the [configuration document](/configuration) for a detailed guide on the Spin
-application configuration.)
+application manifest.)
Now let's have a look at the `hello` component (`examples/http-rust/src/lib.rs`). Below is the complete source
code for a Spin HTTP component written in Rust — a regular Rust function that
@@ -121,7 +121,7 @@ $ spin up
INFO spin_http_engine: Serving HTTP on address 127.0.0.1:3000
```
-Spin will instantiate all components from the application configuration, and
+Spin will instantiate all components from the application manifest, and
will create the router configuration for the HTTP trigger accordingly. The
component can now be invoked by making requests to `http://localhost:3000/hello`
(see route field in the configuration):
@@ -138,7 +138,7 @@ Hello, Fermyon!
You can add as many components as needed in `spin.toml`, mount files and
directories, allow granular outbound HTTP connections, or set environment variables
(see the [configuration document](/configuration) for a detailed guide on
-the Spin application configuration) and iterate locally with
+the Spin application manifest) and iterate locally with
`spin up --file spin.toml` until you are ready to distribute the application.
Congratulations! You just completed building and running your first Spin
diff --git a/docs/content/rust-components.md b/docs/content/rust-components.md
index 59325f1acf..1f8d3f9138 100644
--- a/docs/content/rust-components.md
+++ b/docs/content/rust-components.md
@@ -90,7 +90,7 @@ fn hello_world(_req: Request) -> Result<Response> {
```
Before we can execute this component, we need to add the `https://some-random-api.ml`
-domain to the application configuration list containing the list of
+domain to the application manifest `allowed_http_hosts` list containing the list of
domains the component is allowed to make HTTP requests to:
```toml
@@ -167,7 +167,7 @@ The component can be built with Cargo by executing:
$ cargo build --target wasm32-wasi --release
```
-The configuration for a Redis application must contain the address of the Redis
+The manifest for a Redis application must contain the address of the Redis
instance the trigger must connect to:
```toml
diff --git a/examples/spin-timer/Cargo.toml b/examples/spin-timer/Cargo.toml
index 1d43f0bc14..701f8bf04a 100644
--- a/examples/spin-timer/Cargo.toml
+++ b/examples/spin-timer/Cargo.toml
@@ -12,7 +12,7 @@ env_logger = "0.9"
futures = "0.3"
log = { version = "0.4", default-features = false }
spin-engine = { path = "../../crates/engine" }
-spin-config = { path = "../../crates/config" }
+spin-manifest = { path = "../../crates/manifest" }
tokio = { version = "1.14", features = [ "full" ] }
tracing = { version = "0.1", features = [ "log" ] }
tracing-futures = "0.2"
diff --git a/examples/spin-timer/src/main.rs b/examples/spin-timer/src/main.rs
index facc6a58bb..01b74c53da 100644
--- a/examples/spin-timer/src/main.rs
+++ b/examples/spin-timer/src/main.rs
@@ -2,8 +2,8 @@
#![allow(clippy::needless_question_mark)]
use anyhow::Result;
-use spin_config::{CoreComponent, ModuleSource, WasmConfig};
use spin_engine::{Builder, ExecutionContextConfiguration};
+use spin_manifest::{CoreComponent, ModuleSource, WasmConfig};
use std::{sync::Arc, time::Duration};
use tokio::task::spawn_blocking;
diff --git a/src/commands/up.rs b/src/commands/up.rs
index 037294ac93..643f4c62a4 100644
--- a/src/commands/up.rs
+++ b/src/commands/up.rs
@@ -1,6 +1,6 @@
use anyhow::{bail, Result};
-use spin_config::{Application, ApplicationTrigger, CoreComponent};
use spin_http_engine::{HttpTrigger, TlsConfig};
+use spin_manifest::{Application, ApplicationTrigger, CoreComponent};
use spin_redis_engine::RedisTrigger;
use std::path::{Path, PathBuf};
use structopt::{clap::AppSettings, StructOpt};
| 326
|
[
"318"
] |
diff --git a/crates/loader/src/local/tests.rs b/crates/loader/src/local/tests.rs
index 2769a9ab22..a900e64caf 100644
--- a/crates/loader/src/local/tests.rs
+++ b/crates/loader/src/local/tests.rs
@@ -2,7 +2,7 @@ use crate::local::config::{RawDirectoryPlacement, RawFileMount, RawModuleSource}
use super::*;
use anyhow::Result;
-use spin_config::HttpExecutor;
+use spin_manifest::HttpExecutor;
use std::path::PathBuf;
#[tokio::test]
@@ -131,7 +131,7 @@ fn test_wagi_executor_with_custom_entrypoint() -> Result<()> {
match http_config.executor.as_ref().unwrap() {
HttpExecutor::Spin => panic!("expected wagi http executor"),
- HttpExecutor::Wagi(spin_config::WagiConfig { entrypoint, argv }) => {
+ HttpExecutor::Wagi(spin_manifest::WagiConfig { entrypoint, argv }) => {
assert_eq!(entrypoint, EXPECTED_CUSTOM_ENTRYPOINT);
assert_eq!(argv, EXPECTED_DEFAULT_ARGV);
}
diff --git a/crates/redis/src/tests.rs b/crates/redis/src/tests.rs
index 90123e7bdb..41967ac399 100644
--- a/crates/redis/src/tests.rs
+++ b/crates/redis/src/tests.rs
@@ -1,6 +1,6 @@
use super::*;
use anyhow::Result;
-use spin_config::{RedisConfig, RedisExecutor};
+use spin_manifest::{RedisConfig, RedisExecutor};
use spin_testing::TestConfig;
use std::sync::Once;
@@ -26,7 +26,7 @@ async fn test_pubsub() -> Result<()> {
channel: "messages".to_string(),
executor: Some(RedisExecutor::Spin),
})
- .build_configuration();
+ .build_application();
let trigger = RedisTrigger::new(cfg, None).await?;
diff --git a/crates/testing/Cargo.toml b/crates/testing/Cargo.toml
index 6393690161..5307ae4708 100644
--- a/crates/testing/Cargo.toml
+++ b/crates/testing/Cargo.toml
@@ -8,5 +8,5 @@ authors = ["Fermyon Engineering <engineering@fermyon.com>"]
anyhow = "1.0"
http = "0.2"
hyper = "0.14"
-spin-config = { path = "../config" }
+spin-manifest = { path = "../manifest" }
spin-http-engine = { path = "../http" }
diff --git a/crates/testing/src/lib.rs b/crates/testing/src/lib.rs
index 3a42636f1a..f978a3bbda 100644
--- a/crates/testing/src/lib.rs
+++ b/crates/testing/src/lib.rs
@@ -8,11 +8,11 @@ use std::{
use http::{Request, Response};
use hyper::Body;
-use spin_config::{
+use spin_http_engine::HttpTrigger;
+use spin_manifest::{
Application, ApplicationInformation, ApplicationOrigin, ApplicationTrigger, CoreComponent,
HttpConfig, ModuleSource, RedisConfig, RedisTriggerConfiguration, SpinVersion, TriggerConfig,
};
-use spin_http_engine::HttpTrigger;
#[derive(Default)]
pub struct TestConfig {
@@ -79,7 +79,7 @@ impl TestConfig {
}
}
- pub fn build_configuration(&self) -> Application<CoreComponent> {
+ pub fn build_application(&self) -> Application<CoreComponent> {
Application {
info: self.build_application_information(),
components: vec![self.build_component()],
@@ -95,7 +95,7 @@ impl TestConfig {
}
pub async fn build_http_trigger(&self) -> HttpTrigger {
- HttpTrigger::new("".to_string(), self.build_configuration(), None, None)
+ HttpTrigger::new("".to_string(), self.build_application(), None, None)
.await
.expect("failed to build HttpTrigger")
}
|
95f9da2a41aded597a437ad041a5a13ab19604ee
|
6d650ef75cddb93d6c46f876226b269d28ab769d
|
Rename `config` crate
After discussion about a better name for application config, we're going to rename the current `config` crate to `manifest` and use `config` for #307 unless we can come up with better names for those two things.
|
Do we want to refer to `spin.toml` as a "Spin application manifest" in the docs?
Edit: we call it "manifest file" in one place, but mostly "application configuration".
|
2022-04-05T20:24:31Z
|
fermyon__spin-319
|
fermyon/spin
|
0.1
|
diff --git a/Cargo.lock b/Cargo.lock
index e829c18ab3..8bc9cfe9d9 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3090,10 +3090,10 @@ dependencies = [
"path-absolutize",
"semver",
"serde",
- "spin-config",
"spin-engine",
"spin-http-engine",
"spin-loader",
+ "spin-manifest",
"spin-publish",
"spin-redis-engine",
"spin-templates",
@@ -3107,14 +3107,6 @@ dependencies = [
"vergen",
]
-[[package]]
-name = "spin-config"
-version = "0.1.0"
-dependencies = [
- "anyhow",
- "serde",
-]
-
[[package]]
name = "spin-engine"
version = "0.1.0"
@@ -3123,7 +3115,7 @@ dependencies = [
"bytes 1.1.0",
"dirs 4.0.0",
"sanitize-filename",
- "spin-config",
+ "spin-manifest",
"tempfile",
"tokio",
"tracing",
@@ -3157,8 +3149,8 @@ dependencies = [
"num_cpus",
"rustls-pemfile 0.3.0",
"serde",
- "spin-config",
"spin-engine",
+ "spin-manifest",
"spin-testing",
"tls-listener",
"tokio",
@@ -3194,7 +3186,7 @@ dependencies = [
"reqwest",
"serde",
"sha2 0.10.2",
- "spin-config",
+ "spin-manifest",
"tempfile",
"tokio",
"toml",
@@ -3219,6 +3211,14 @@ dependencies = [
"wit-bindgen-rust",
]
+[[package]]
+name = "spin-manifest"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "serde",
+]
+
[[package]]
name = "spin-publish"
version = "0.1.0"
@@ -3251,8 +3251,8 @@ dependencies = [
"log",
"redis",
"serde",
- "spin-config",
"spin-engine",
+ "spin-manifest",
"spin-testing",
"tokio",
"tracing",
@@ -3301,8 +3301,8 @@ dependencies = [
"anyhow",
"http 0.2.6",
"hyper",
- "spin-config",
"spin-http-engine",
+ "spin-manifest",
]
[[package]]
@@ -3315,8 +3315,8 @@ dependencies = [
"env_logger",
"futures",
"log",
- "spin-config",
"spin-engine",
+ "spin-manifest",
"tokio",
"tracing",
"tracing-futures",
diff --git a/Cargo.toml b/Cargo.toml
index ca2ff3772f..e74387b28c 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -18,7 +18,7 @@ lazy_static = "1.4.0"
path-absolutize = "3.0.11"
semver = "1.0"
serde = { version = "1.0", features = [ "derive" ] }
-spin-config = { path = "crates/config" }
+spin-manifest = { path = "crates/manifest" }
spin-engine = { path = "crates/engine" }
spin-http-engine = { path = "crates/http" }
spin-loader = { path = "crates/loader" }
@@ -42,10 +42,10 @@ vergen = { version = "7", default-features = false, features = [ "build", "git"
[workspace]
members = [
- "crates/config",
"crates/engine",
"crates/http",
"crates/loader",
+ "crates/manifest",
"crates/outbound-http",
"crates/redis",
"crates/templates",
diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml
index 1b971101af..f57cd9719a 100644
--- a/crates/engine/Cargo.toml
+++ b/crates/engine/Cargo.toml
@@ -9,7 +9,7 @@ anyhow = "1.0.44"
bytes = "1.1.0"
dirs = "4.0"
sanitize-filename = "0.3.0"
-spin-config = { path = "../config" }
+spin-manifest = { path = "../manifest" }
tempfile = "3.3.0"
tokio = { version = "1.10.0", features = [ "fs" ] }
tracing = { version = "0.1", features = [ "log" ] }
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 03113dcf78..2e1d99f49f 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -7,7 +7,7 @@ pub mod io;
use anyhow::{bail, Context, Result};
use io::IoStreamRedirects;
-use spin_config::{Application, CoreComponent, DirectoryMount, ModuleSource};
+use spin_manifest::{Application, CoreComponent, DirectoryMount, ModuleSource};
use std::{collections::HashMap, io::Write, path::PathBuf, sync::Arc};
use tokio::task::JoinHandle;
use tokio::time::{sleep, Duration};
diff --git a/crates/http/Cargo.toml b/crates/http/Cargo.toml
index 15454063e4..e670413510 100644
--- a/crates/http/Cargo.toml
+++ b/crates/http/Cargo.toml
@@ -20,7 +20,7 @@ hyper = { version = "0.14", features = ["full"] }
hyper-rustls = { version = "0.23.0" }
indexmap = "1.6"
serde = { version = "1.0", features = ["derive"] }
-spin-config = { path = "../config" }
+spin-manifest = { path = "../manifest" }
spin-engine = { path = "../engine" }
tls-listener = { version = "0.4.0", features = [
"rustls",
diff --git a/crates/http/benches/baseline.rs b/crates/http/benches/baseline.rs
index bbee36e2a4..2e1e7708e2 100644
--- a/crates/http/benches/baseline.rs
+++ b/crates/http/benches/baseline.rs
@@ -4,8 +4,8 @@ use criterion::{black_box, criterion_group, criterion_main, Criterion};
use futures::future::join_all;
use http::Request;
-use spin_config::{HttpConfig, HttpExecutor};
use spin_http_engine::HttpTrigger;
+use spin_manifest::{HttpConfig, HttpExecutor};
use spin_testing::{assert_http_response_success, TestConfig};
use tokio::runtime::Runtime;
use tokio::task;
diff --git a/crates/http/src/lib.rs b/crates/http/src/lib.rs
index a48fbf2907..5c9b3da882 100644
--- a/crates/http/src/lib.rs
+++ b/crates/http/src/lib.rs
@@ -21,9 +21,11 @@ use hyper::{
service::{make_service_fn, service_fn},
Body, Request, Response, Server,
};
-use spin_config::{Application, ComponentMap, CoreComponent, HttpConfig, HttpTriggerConfiguration};
use spin_engine::{Builder, ExecutionContextConfiguration};
use spin_http::SpinHttpData;
+use spin_manifest::{
+ Application, ComponentMap, CoreComponent, HttpConfig, HttpTriggerConfiguration,
+};
use std::{future::ready, net::SocketAddr, path::PathBuf, sync::Arc};
use tls_listener::TlsListener;
use tokio::net::{TcpListener, TcpStream};
@@ -115,11 +117,11 @@ impl HttpTrigger {
let executor = match &trigger.executor {
Some(i) => i,
- None => &spin_config::HttpExecutor::Spin,
+ None => &spin_manifest::HttpExecutor::Spin,
};
let res = match executor {
- spin_config::HttpExecutor::Spin => {
+ spin_manifest::HttpExecutor::Spin => {
let executor = SpinHttpExecutor;
executor
.execute(
@@ -132,7 +134,7 @@ impl HttpTrigger {
)
.await
}
- spin_config::HttpExecutor::Wagi(wagi_config) => {
+ spin_manifest::HttpExecutor::Wagi(wagi_config) => {
let executor = WagiHttpExecutor {
wagi_config: wagi_config.clone(),
};
@@ -400,7 +402,7 @@ pub(crate) trait HttpExecutor: Clone + Send + Sync + 'static {
mod tests {
use super::*;
use anyhow::Result;
- use spin_config::{HttpConfig, HttpExecutor};
+ use spin_manifest::{HttpConfig, HttpExecutor};
use spin_testing::test_socket_addr;
use std::{collections::BTreeMap, sync::Once};
@@ -537,7 +539,7 @@ mod tests {
route: "/test".to_string(),
executor: Some(HttpExecutor::Spin),
})
- .build_configuration();
+ .build_application();
let trigger = HttpTrigger::new("".to_string(), cfg, None, None).await?;
@@ -566,7 +568,7 @@ mod tests {
route: "/test".to_string(),
executor: Some(HttpExecutor::Wagi(Default::default())),
})
- .build_configuration();
+ .build_application();
let trigger = HttpTrigger::new("".to_string(), cfg, None, None).await?;
diff --git a/crates/http/src/routes.rs b/crates/http/src/routes.rs
index 222439a827..3386f8a950 100644
--- a/crates/http/src/routes.rs
+++ b/crates/http/src/routes.rs
@@ -5,7 +5,7 @@
use anyhow::{bail, Result};
use http::Uri;
use indexmap::IndexMap;
-use spin_config::{Application, CoreComponent};
+use spin_manifest::{Application, CoreComponent};
use std::fmt::Debug;
use tracing::log;
@@ -333,8 +333,8 @@ mod route_tests {
fn named_component(id: &str) -> CoreComponent {
CoreComponent {
id: id.to_string(),
- source: spin_config::ModuleSource::FileReference("FAKE".into()),
- wasm: spin_config::WasmConfig::default(),
+ source: spin_manifest::ModuleSource::FileReference("FAKE".into()),
+ wasm: spin_manifest::WasmConfig::default(),
}
}
}
diff --git a/crates/http/src/wagi.rs b/crates/http/src/wagi.rs
index 255a9d6839..9ae4a43973 100644
--- a/crates/http/src/wagi.rs
+++ b/crates/http/src/wagi.rs
@@ -2,8 +2,8 @@ use crate::{routes::RoutePattern, ExecutionContext, HttpExecutor};
use anyhow::Result;
use async_trait::async_trait;
use hyper::{body, Body, Request, Response};
-use spin_config::WagiConfig;
use spin_engine::io::{IoStreamRedirects, OutRedirect};
+use spin_manifest::WagiConfig;
use std::{
collections::HashMap,
net::SocketAddr,
diff --git a/crates/loader/Cargo.toml b/crates/loader/Cargo.toml
index ae362c2721..acf37442bf 100644
--- a/crates/loader/Cargo.toml
+++ b/crates/loader/Cargo.toml
@@ -20,7 +20,7 @@ regex = "1.5.4"
reqwest = "0.11.9"
sha2 = "0.10.1"
serde = { version = "1.0", features = [ "derive" ] }
-spin-config = { path = "../config" }
+spin-manifest = { path = "../manifest" }
tempfile = "3.3.0"
tokio = { version = "1.11", features = [ "full" ] }
toml = "0.5"
diff --git a/crates/loader/src/bindle/assets.rs b/crates/loader/src/bindle/assets.rs
index 3f849eeb79..c83e0a23b5 100644
--- a/crates/loader/src/bindle/assets.rs
+++ b/crates/loader/src/bindle/assets.rs
@@ -7,7 +7,7 @@ use crate::{
use anyhow::{anyhow, bail, Context, Result};
use bindle::{Id, Label};
use futures::future;
-use spin_config::DirectoryMount;
+use spin_manifest::DirectoryMount;
use std::path::Path;
use tokio::fs;
use tracing::log;
diff --git a/crates/loader/src/bindle/config.rs b/crates/loader/src/bindle/config.rs
index 82e7b6ba1c..7de9ccd383 100644
--- a/crates/loader/src/bindle/config.rs
+++ b/crates/loader/src/bindle/config.rs
@@ -6,7 +6,7 @@ use std::collections::HashMap;
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct RawAppManifest {
/// The application trigger.
- pub trigger: spin_config::ApplicationTrigger,
+ pub trigger: spin_manifest::ApplicationTrigger,
/// Configuration for the application components.
#[serde(rename = "component")]
@@ -26,7 +26,7 @@ pub struct RawComponentManifest {
#[serde(flatten)]
pub wasm: RawWasmConfig,
/// Trigger configuration.
- pub trigger: spin_config::TriggerConfig,
+ pub trigger: spin_manifest::TriggerConfig,
}
/// WebAssembly configuration.
diff --git a/crates/loader/src/bindle/mod.rs b/crates/loader/src/bindle/mod.rs
index 452d862654..9374df676e 100644
--- a/crates/loader/src/bindle/mod.rs
+++ b/crates/loader/src/bindle/mod.rs
@@ -19,7 +19,7 @@ use bindle::{
Invoice,
};
use futures::future;
-use spin_config::{
+use spin_manifest::{
Application, ApplicationInformation, ApplicationOrigin, CoreComponent, ModuleSource,
SpinVersion, WasmConfig,
};
diff --git a/crates/loader/src/local/assets.rs b/crates/loader/src/local/assets.rs
index 67d50f941c..304da5ae13 100644
--- a/crates/loader/src/local/assets.rs
+++ b/crates/loader/src/local/assets.rs
@@ -3,7 +3,7 @@
use crate::assets::{create_dir, ensure_all_under, ensure_under, to_relative};
use anyhow::{anyhow, bail, Context, Result};
use futures::future;
-use spin_config::DirectoryMount;
+use spin_manifest::DirectoryMount;
use std::path::{Path, PathBuf};
use tracing::log;
use walkdir::WalkDir;
diff --git a/crates/loader/src/local/config.rs b/crates/loader/src/local/config.rs
index d1065b62a6..0587cf70b7 100644
--- a/crates/loader/src/local/config.rs
+++ b/crates/loader/src/local/config.rs
@@ -5,7 +5,7 @@
#![deny(missing_docs)]
use serde::{Deserialize, Serialize};
-use spin_config::{ApplicationTrigger, TriggerConfig};
+use spin_manifest::{ApplicationTrigger, TriggerConfig};
use std::{collections::HashMap, path::PathBuf};
/// Container for any version of the manifest.
diff --git a/crates/loader/src/local/mod.rs b/crates/loader/src/local/mod.rs
index d9dcf99c73..a1694e5798 100644
--- a/crates/loader/src/local/mod.rs
+++ b/crates/loader/src/local/mod.rs
@@ -14,7 +14,7 @@ use anyhow::{anyhow, Context, Result};
use config::{RawAppInformation, RawAppManifest, RawAppManifestAnyVersion, RawComponentManifest};
use futures::future;
use path_absolutize::Absolutize;
-use spin_config::{
+use spin_manifest::{
Application, ApplicationInformation, ApplicationOrigin, CoreComponent, ModuleSource,
SpinVersion, WasmConfig,
};
diff --git a/crates/config/Cargo.toml b/crates/manifest/Cargo.toml
similarity index 89%
rename from crates/config/Cargo.toml
rename to crates/manifest/Cargo.toml
index 69ac17342b..92b0175a83 100644
--- a/crates/config/Cargo.toml
+++ b/crates/manifest/Cargo.toml
@@ -1,5 +1,5 @@
[package]
-name = "spin-config"
+name = "spin-manifest"
version = "0.1.0"
edition = "2021"
authors = [ "Fermyon Engineering <engineering@fermyon.com>" ]
diff --git a/crates/config/src/lib.rs b/crates/manifest/src/lib.rs
similarity index 100%
rename from crates/config/src/lib.rs
rename to crates/manifest/src/lib.rs
diff --git a/crates/redis/Cargo.toml b/crates/redis/Cargo.toml
index ff79dfec7d..c26dba8517 100644
--- a/crates/redis/Cargo.toml
+++ b/crates/redis/Cargo.toml
@@ -15,7 +15,7 @@ futures = "0.3"
log = { version = "0.4", default-features = false }
serde = { version = "1.0", features = [ "derive" ] }
spin-engine = { path = "../engine" }
-spin-config = { path = "../config" }
+spin-manifest = { path = "../manifest" }
redis = { version = "0.21", features = [ "tokio-comp" ] }
tokio = { version = "1.14", features = [ "full" ] }
tracing = { version = "0.1", features = [ "log" ] }
diff --git a/crates/redis/src/lib.rs b/crates/redis/src/lib.rs
index 1d8f7ac482..b3826c4419 100644
--- a/crates/redis/src/lib.rs
+++ b/crates/redis/src/lib.rs
@@ -7,10 +7,10 @@ use anyhow::{anyhow, Result};
use async_trait::async_trait;
use futures::StreamExt;
use redis::Client;
-use spin_config::{
+use spin_engine::{Builder, ExecutionContextConfiguration};
+use spin_manifest::{
Application, ComponentMap, CoreComponent, RedisConfig, RedisTriggerConfiguration,
};
-use spin_engine::{Builder, ExecutionContextConfiguration};
use spin_redis::SpinRedisData;
use std::{collections::HashMap, path::PathBuf, sync::Arc};
@@ -114,7 +114,7 @@ impl RedisTrigger {
.unwrap_or_default();
match executor {
- spin_config::RedisExecutor::Spin => {
+ spin_manifest::RedisExecutor::Spin => {
log::trace!("Executing Spin Redis component {}", component.id);
let executor = SpinRedisExecutor;
executor
diff --git a/docs/content/architecture.md b/docs/content/architecture.md
index 6e6f57e130..7877e4e2da 100644
--- a/docs/content/architecture.md
+++ b/docs/content/architecture.md
@@ -17,8 +17,8 @@ be pushed to the registry then referenced using its remote ID
Regardless of the application origin (local file or remote reference from the
registry), a Spin application is defined by
-`spin_config::Application<CoreComponent>` (contained in the
-[`spin-config`](https://github.com/fermyon/spin/tree/main/crates/config) crate),
+`spin_manifest::Application<CoreComponent>` (contained in the
+[`spin-manifest`](https://github.com/fermyon/spin/tree/main/crates/manifest) crate),
which is the canonical representation of a Spin application.
The crate responsible for transforming a custom configuration into a canonical
diff --git a/examples/spin-timer/Cargo.toml b/examples/spin-timer/Cargo.toml
index 1d43f0bc14..701f8bf04a 100644
--- a/examples/spin-timer/Cargo.toml
+++ b/examples/spin-timer/Cargo.toml
@@ -12,7 +12,7 @@ env_logger = "0.9"
futures = "0.3"
log = { version = "0.4", default-features = false }
spin-engine = { path = "../../crates/engine" }
-spin-config = { path = "../../crates/config" }
+spin-manifest = { path = "../../crates/manifest" }
tokio = { version = "1.14", features = [ "full" ] }
tracing = { version = "0.1", features = [ "log" ] }
tracing-futures = "0.2"
diff --git a/examples/spin-timer/src/main.rs b/examples/spin-timer/src/main.rs
index facc6a58bb..01b74c53da 100644
--- a/examples/spin-timer/src/main.rs
+++ b/examples/spin-timer/src/main.rs
@@ -2,8 +2,8 @@
#![allow(clippy::needless_question_mark)]
use anyhow::Result;
-use spin_config::{CoreComponent, ModuleSource, WasmConfig};
use spin_engine::{Builder, ExecutionContextConfiguration};
+use spin_manifest::{CoreComponent, ModuleSource, WasmConfig};
use std::{sync::Arc, time::Duration};
use tokio::task::spawn_blocking;
diff --git a/src/commands/up.rs b/src/commands/up.rs
index 037294ac93..643f4c62a4 100644
--- a/src/commands/up.rs
+++ b/src/commands/up.rs
@@ -1,6 +1,6 @@
use anyhow::{bail, Result};
-use spin_config::{Application, ApplicationTrigger, CoreComponent};
use spin_http_engine::{HttpTrigger, TlsConfig};
+use spin_manifest::{Application, ApplicationTrigger, CoreComponent};
use spin_redis_engine::RedisTrigger;
use std::path::{Path, PathBuf};
use structopt::{clap::AppSettings, StructOpt};
| 319
|
[
"318"
] |
diff --git a/crates/loader/src/local/tests.rs b/crates/loader/src/local/tests.rs
index 2769a9ab22..a900e64caf 100644
--- a/crates/loader/src/local/tests.rs
+++ b/crates/loader/src/local/tests.rs
@@ -2,7 +2,7 @@ use crate::local::config::{RawDirectoryPlacement, RawFileMount, RawModuleSource}
use super::*;
use anyhow::Result;
-use spin_config::HttpExecutor;
+use spin_manifest::HttpExecutor;
use std::path::PathBuf;
#[tokio::test]
@@ -131,7 +131,7 @@ fn test_wagi_executor_with_custom_entrypoint() -> Result<()> {
match http_config.executor.as_ref().unwrap() {
HttpExecutor::Spin => panic!("expected wagi http executor"),
- HttpExecutor::Wagi(spin_config::WagiConfig { entrypoint, argv }) => {
+ HttpExecutor::Wagi(spin_manifest::WagiConfig { entrypoint, argv }) => {
assert_eq!(entrypoint, EXPECTED_CUSTOM_ENTRYPOINT);
assert_eq!(argv, EXPECTED_DEFAULT_ARGV);
}
diff --git a/crates/redis/src/tests.rs b/crates/redis/src/tests.rs
index 90123e7bdb..41967ac399 100644
--- a/crates/redis/src/tests.rs
+++ b/crates/redis/src/tests.rs
@@ -1,6 +1,6 @@
use super::*;
use anyhow::Result;
-use spin_config::{RedisConfig, RedisExecutor};
+use spin_manifest::{RedisConfig, RedisExecutor};
use spin_testing::TestConfig;
use std::sync::Once;
@@ -26,7 +26,7 @@ async fn test_pubsub() -> Result<()> {
channel: "messages".to_string(),
executor: Some(RedisExecutor::Spin),
})
- .build_configuration();
+ .build_application();
let trigger = RedisTrigger::new(cfg, None).await?;
diff --git a/crates/testing/Cargo.toml b/crates/testing/Cargo.toml
index 6393690161..5307ae4708 100644
--- a/crates/testing/Cargo.toml
+++ b/crates/testing/Cargo.toml
@@ -8,5 +8,5 @@ authors = ["Fermyon Engineering <engineering@fermyon.com>"]
anyhow = "1.0"
http = "0.2"
hyper = "0.14"
-spin-config = { path = "../config" }
+spin-manifest = { path = "../manifest" }
spin-http-engine = { path = "../http" }
diff --git a/crates/testing/src/lib.rs b/crates/testing/src/lib.rs
index 3a42636f1a..f978a3bbda 100644
--- a/crates/testing/src/lib.rs
+++ b/crates/testing/src/lib.rs
@@ -8,11 +8,11 @@ use std::{
use http::{Request, Response};
use hyper::Body;
-use spin_config::{
+use spin_http_engine::HttpTrigger;
+use spin_manifest::{
Application, ApplicationInformation, ApplicationOrigin, ApplicationTrigger, CoreComponent,
HttpConfig, ModuleSource, RedisConfig, RedisTriggerConfiguration, SpinVersion, TriggerConfig,
};
-use spin_http_engine::HttpTrigger;
#[derive(Default)]
pub struct TestConfig {
@@ -79,7 +79,7 @@ impl TestConfig {
}
}
- pub fn build_configuration(&self) -> Application<CoreComponent> {
+ pub fn build_application(&self) -> Application<CoreComponent> {
Application {
info: self.build_application_information(),
components: vec![self.build_component()],
@@ -95,7 +95,7 @@ impl TestConfig {
}
pub async fn build_http_trigger(&self) -> HttpTrigger {
- HttpTrigger::new("".to_string(), self.build_configuration(), None, None)
+ HttpTrigger::new("".to_string(), self.build_application(), None, None)
.await
.expect("failed to build HttpTrigger")
}
|
95f9da2a41aded597a437ad041a5a13ab19604ee
|
d235bc1c23ac15a6c737d295a146476c86e0432a
|
Missing request headers when using the Go SDK
Consider the following Go program:
```go
func main() {
spin.HandleRequest(func(w http.ResponseWriter, r *http.Request) {
for k, v := range r.Header {
fmt.Fprintf(w, "Header field %q, Value %q\n", k, v)
}
})
}
```
This should print all request headers for an HTTP request (https://spin.fermyon.dev/http-trigger/). However, it only prints the accept and user agent headers:
```
Header field "Accept", Value ["*/*"]
Header field "User-Agent", Value ["curl/7.77.0"]
```
When printing all environment variables instead:
```
[CONTENT_LENGTH=0 QUERY_STRING= HTTP_ACCEPT=*/* REMOTE_USER= PATH_TRANSLATED=/ X_BASE_PATH=/ X_COMPONENT_ROUTE= AUTH_TYPE= REMOTE_HOST=127.0.0.1 X_MATCHED_ROUTE=/... SERVER_SOFTWARE=WAGI/1 PATH_INFO=/ SCRIPT_NAME=/ X_FULL_URL=http://localhost:3000/ X_RAW_PATH_INFO=/ CONTENT_TYPE= SERVER_PORT=3000 HTTP_USER_AGENT=curl/7.77.0 X_RAW_COMPONENT_ROUTE=/... REQUEST_METHOD=GET HTTP_HOST=localhost:3000 SERVER_NAME=localhost REMOTE_ADDR=127.0.0.1 GATEWAY_INTERFACE=CGI/1.1 SERVER_PROTOCOL=HTTP/1.1]%
```
Parsing the headers set by Wagi doesn't seem to work properly in Go's standard implementation for the `net/http/cgi` package.
|
The commonality between the two headers set is the `HTTP_` prefix (`HTTP_ACCEPT` and `HTTP_USER_AGENT` being translated into `Accept` and `User-Agent`.
The CGI implementation from the Go standard library (https://cs.opensource.google/go/go/+/refs/tags/go1.18:src/net/http/cgi/child.go;l=83;drc=refs%2Ftags%2Fgo1.18) expects the HTTP headers to have the `HTTP_` prefix:
```go
// Copy "HTTP_FOO_BAR" variables to "Foo-Bar" Headers
for k, v := range params {
if !strings.HasPrefix(k, "HTTP_") || k == "HTTP_HOST" {
continue
}
r.Header.Add(strings.ReplaceAll(k[5:], "_", "-"), v)
}
```
ref https://datatracker.ietf.org/doc/html/rfc3875#section-4.1.18
If we want to use the Go CGI implementation out of the box, I suspect Wagi should have to set all headers with the `HTTP_` prefix as well.
Using the updated Wagi to also append the `HTTP_` prefix to all headers (https://github.com/deislabs/wagi/compare/main...radu-matei:headers-http-underscore-prefix?expand=1), this is the result:
```
Header field "Remote-User", Value [""]
Header field "Http-User-Agent", Value ["curl/7.77.0"]
Header field "Path-Translated", Value ["/"]
Header field "Content-Length", Value ["0"]
Header field "Gateway-Interface", Value ["CGI/1.1"]
Header field "Path-Info", Value ["/"]
Header field "X-Full-Url", Value ["http://localhost:3000/"]
Header field "Query-String", Value [""]
Header field "Server-Protocol", Value ["HTTP/1.1"]
Header field "Remote-Addr", Value ["127.0.0.1"]
Header field "Accept", Value ["*/*"]
Header field "X-Raw-Path-Info", Value ["/"]
Header field "Content-Type", Value [""]
Header field "Server-Software", Value ["WAGI/1"]
Header field "Script-Name", Value ["/"]
Header field "Http-Host", Value ["localhost:3000"]
Header field "Request-Method", Value ["GET"]
Header field "Http-Accept", Value ["*/*"]
Header field "X-Matched-Route", Value ["/..."]
Header field "Remote-Host", Value ["127.0.0.1"]
Header field "Server-Port", Value ["3000"]
Header field "Auth-Type", Value [""]
Header field "User-Agent", Value ["curl/7.77.0"]
Header field "Server-Name", Value ["localhost"]
```
The Go implementation also replaces `_` with `-` in the header keys.
Should the Rust SDK update them as well?
```
Meta-variables with names beginning with "HTTP_" contain values read
from the client request header fields, if the protocol used is HTTP.
The HTTP header field name is converted to upper case, has all
occurrences of "-" replaced with "_" and has "HTTP_" prepended to
give the meta-variable name. The header data can be presented as
sent by the client, or can be rewritten in ways which do not change
its semantics. If multiple header fields with the same field-name
are received then the server MUST rewrite them as a single value
having the same semantics. Similarly, a header field that spans
multiple lines MUST be merged onto a single line. The server MUST,
if necessary, change the representation of the data (for example, the
character set) to be appropriate for a CGI meta-variable.
```
Ugh, the naming section of the RFC is maddeningly ambiguous. With one hand it says "prepend HTTP", with the other hand it says `meta-variable-name = "AUTH_TYPE" | "CONTENT_LENGTH" | "CONTENT_TYPE" | ...` and with a _third_ hand it throws its fourth and fifth hands in the air and says "A particular system can define a different representation."
I guess we should take a look at that Rust CGI implementation that Butcher found, and see what it expects - even though we're not allowed to use it, it should give us a sense of what users expect to work with. On the other hand, it would be a significant breaking change for WAGI at this point, wouldn't it?
I would trust the CGI implementation in the Go standard library a bit more than some random library.
And while discussing this, Lann made a point that I just hadn't considered:
> Meta-variables with names beginning with "HTTP_" contain values read
> from the client request header fields, if the protocol used is HTTP.
Only the meta-variables that begin with `HTTP_` are to be used as request headers, NOT all of them. So while the Wagi implementation is correct, in that all of the meta-variables are supposed to be passed to the module as environment variables, two points arise from this:
- the Spin HTTP implementation (based on WIT) also sets the `PATH_INFO` (and other related values) as headers — this comes from a misunderstanding of the CGI spec on my part. We want to pass this information to the request (even for a Spin HTTP component), and perhaps as a header, but it should definitely not be `PATH_INFO` (headers do not usually contain `_`, and we should have a convention for Spin-specific headers, for example `spin-path-info`, or something similar).
- in Wagi, we should make sure request headers set by clients do not override meta-variables (ref https://github.com/deislabs/wagi/issues/9)
|
2022-03-29T13:12:46Z
|
fermyon__spin-274
|
fermyon/spin
|
0.1
|
diff --git a/crates/http/src/lib.rs b/crates/http/src/lib.rs
index da0423258e..a48fbf2907 100644
--- a/crates/http/src/lib.rs
+++ b/crates/http/src/lib.rs
@@ -333,20 +333,24 @@ fn on_ctrl_c() -> Result<impl std::future::Future<Output = Result<(), tokio::tas
Ok(rx_future)
}
-// The default headers set across both executors.
-const X_FULL_URL_HEADER: &str = "X_FULL_URL";
-const PATH_INFO_HEADER: &str = "PATH_INFO";
-const X_MATCHED_ROUTE_HEADER: &str = "X_MATCHED_ROUTE";
-const X_COMPONENT_ROUTE_HEADER: &str = "X_COMPONENT_ROUTE";
-const X_RAW_COMPONENT_ROUTE_HEADER: &str = "X_RAW_COMPONENT_ROUTE";
-const X_BASE_PATH_HEADER: &str = "X_BASE_PATH";
-
-pub(crate) fn default_headers(
+// We need to make the following pieces of information available to both executors.
+// While the values we set are identical, the way they are passed to the
+// modules is going to be different, so each executor must must use the info
+// in its standardized way (environment variables for the Wagi executor, and custom headers
+// for the Spin HTTP executor).
+const FULL_URL: &[&str] = &["SPIN_FULL_URL", "X_FULL_URL"];
+const PATH_INFO: &[&str] = &["SPIN_PATH_INFO", "PATH_INFO"];
+const MATCHED_ROUTE: &[&str] = &["SPIN_MATCHED_ROUTE", "X_MATCHED_ROUTE"];
+const COMPONENT_ROUTE: &[&str] = &["SPIN_COMPONENT_ROUTE", "X_COMPONENT_ROUTE"];
+const RAW_COMPONENT_ROUTE: &[&str] = &["SPIN_RAW_COMPONENT_ROUTE", "X_RAW_COMPONENT_ROUTE"];
+const BASE_PATH: &[&str] = &["SPIN_BASE_PATH", "X_BASE_PATH"];
+
+pub(crate) fn compute_default_headers<'a>(
uri: &Uri,
raw: &str,
base: &str,
host: &str,
-) -> Result<Vec<(String, String)>> {
+) -> Result<Vec<(&'a [&'a str], String)>> {
let mut res = vec![];
let abs_path = uri
.path_and_query()
@@ -360,14 +364,14 @@ pub(crate) fn default_headers(
let full_url = format!("{}://{}{}", scheme, host, abs_path);
let matched_route = RoutePattern::sanitize_with_base(base, raw);
- res.push((PATH_INFO_HEADER.to_string(), path_info));
- res.push((X_FULL_URL_HEADER.to_string(), full_url));
- res.push((X_MATCHED_ROUTE_HEADER.to_string(), matched_route));
+ res.push((PATH_INFO, path_info));
+ res.push((FULL_URL, full_url));
+ res.push((MATCHED_ROUTE, matched_route));
- res.push((X_BASE_PATH_HEADER.to_string(), base.to_string()));
- res.push((X_RAW_COMPONENT_ROUTE_HEADER.to_string(), raw.to_string()));
+ res.push((BASE_PATH, base.to_string()));
+ res.push((RAW_COMPONENT_ROUTE, raw.to_string()));
res.push((
- X_COMPONENT_ROUTE_HEADER.to_string(),
+ COMPONENT_ROUTE,
raw.to_string()
.strip_suffix("/...")
.unwrap_or(raw)
@@ -430,30 +434,30 @@ mod tests {
.uri(req_uri)
.body("")?;
- let default_headers = crate::default_headers(req.uri(), trigger_route, base, host)?;
+ let default_headers = crate::compute_default_headers(req.uri(), trigger_route, base, host)?;
assert_eq!(
- search(X_FULL_URL_HEADER, &default_headers).unwrap(),
+ search(FULL_URL, &default_headers).unwrap(),
"https://fermyon.dev/base/foo/bar?key1=value1&key2=value2".to_string()
);
assert_eq!(
- search(PATH_INFO_HEADER, &default_headers).unwrap(),
+ search(PATH_INFO, &default_headers).unwrap(),
"/bar".to_string()
);
assert_eq!(
- search(X_MATCHED_ROUTE_HEADER, &default_headers).unwrap(),
+ search(MATCHED_ROUTE, &default_headers).unwrap(),
"/base/foo/...".to_string()
);
assert_eq!(
- search(X_BASE_PATH_HEADER, &default_headers).unwrap(),
+ search(BASE_PATH, &default_headers).unwrap(),
"/base".to_string()
);
assert_eq!(
- search(X_RAW_COMPONENT_ROUTE_HEADER, &default_headers).unwrap(),
+ search(RAW_COMPONENT_ROUTE, &default_headers).unwrap(),
"/foo/...".to_string()
);
assert_eq!(
- search(X_COMPONENT_ROUTE_HEADER, &default_headers).unwrap(),
+ search(COMPONENT_ROUTE, &default_headers).unwrap(),
"/foo".to_string()
);
@@ -479,41 +483,43 @@ mod tests {
.uri(req_uri)
.body("")?;
- let default_headers = crate::default_headers(req.uri(), trigger_route, base, host)?;
+ let default_headers = crate::compute_default_headers(req.uri(), trigger_route, base, host)?;
// TODO: we currently replace the scheme with HTTP. When TLS is supported, this should be fixed.
assert_eq!(
- search(X_FULL_URL_HEADER, &default_headers).unwrap(),
+ search(FULL_URL, &default_headers).unwrap(),
"https://fermyon.dev/foo/bar?key1=value1&key2=value2".to_string()
);
assert_eq!(
- search(PATH_INFO_HEADER, &default_headers).unwrap(),
+ search(PATH_INFO, &default_headers).unwrap(),
"/bar".to_string()
);
assert_eq!(
- search(X_MATCHED_ROUTE_HEADER, &default_headers).unwrap(),
+ search(MATCHED_ROUTE, &default_headers).unwrap(),
"/foo/...".to_string()
);
assert_eq!(
- search(X_BASE_PATH_HEADER, &default_headers).unwrap(),
+ search(BASE_PATH, &default_headers).unwrap(),
"/".to_string()
);
assert_eq!(
- search(X_RAW_COMPONENT_ROUTE_HEADER, &default_headers).unwrap(),
+ search(RAW_COMPONENT_ROUTE, &default_headers).unwrap(),
"/foo/...".to_string()
);
assert_eq!(
- search(X_COMPONENT_ROUTE_HEADER, &default_headers).unwrap(),
+ search(COMPONENT_ROUTE, &default_headers).unwrap(),
"/foo".to_string()
);
Ok(())
}
- fn search(key: &str, headers: &[(String, String)]) -> Option<String> {
+ // fn _search(key: &str, headers: &[(String, String)]) -> Option<String> {}
+
+ fn search<'a>(keys: &'a [&'a str], headers: &[(&[&str], String)]) -> Option<String> {
let mut res: Option<String> = None;
for (k, v) in headers {
- if k == key {
+ if k[0] == keys[0] && k[1] == keys[1] {
res = Some(v.clone());
}
}
diff --git a/crates/http/src/spin.rs b/crates/http/src/spin.rs
index 24f48db0e2..cace5ad8a5 100644
--- a/crates/http/src/spin.rs
+++ b/crates/http/src/spin.rs
@@ -149,14 +149,20 @@ impl SpinHttpExecutor {
.as_bytes(),
)?;
- // Add the default headers.
- for pair in crate::default_headers(req.uri(), raw, base, host)? {
- res.push(pair);
+ // Set the environment information (path info, base path, etc) as headers.
+ // In the future, we might want to have this information in a context
+ // object as opposed to headers.
+ for (keys, val) in crate::compute_default_headers(req.uri(), raw, base, host)? {
+ res.push((Self::prepare_header_key(keys[0]), val));
}
Ok(res)
}
+ fn prepare_header_key(key: &str) -> String {
+ key.replace('_', "-").to_ascii_lowercase()
+ }
+
fn append_headers(res: &mut http::HeaderMap, src: Option<Vec<(String, String)>>) -> Result<()> {
if let Some(src) = src {
for (k, v) in src.iter() {
@@ -199,3 +205,24 @@ pub fn prepare_io_redirects() -> Result<IoStreamRedirects> {
stderr,
})
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_spin_header_keys() {
+ assert_eq!(
+ SpinHttpExecutor::prepare_header_key("SPIN_FULL_URL"),
+ "spin-full-url".to_string()
+ );
+ assert_eq!(
+ SpinHttpExecutor::prepare_header_key("SPIN_PATH_INFO"),
+ "spin-path-info".to_string()
+ );
+ assert_eq!(
+ SpinHttpExecutor::prepare_header_key("SPIN_RAW_COMPONENT_ROUTE"),
+ "spin-raw-component-route".to_string()
+ );
+ }
+}
diff --git a/crates/http/src/wagi.rs b/crates/http/src/wagi.rs
index 9a5496b4fd..255a9d6839 100644
--- a/crates/http/src/wagi.rs
+++ b/crates/http/src/wagi.rs
@@ -76,10 +76,13 @@ impl HttpExecutor for WagiHttpExecutor {
)?;
// Add the default Spin headers.
+ // This sets the current environment variables Wagi expects (such as
+ // `PATH_INFO`, or `X_FULL_URL`).
// Note that this overrides any existing headers previously set by Wagi.
- for (k, v) in crate::default_headers(&parts.uri, raw_route, base, host)? {
- headers.insert(k, v);
+ for (keys, val) in crate::compute_default_headers(&parts.uri, raw_route, base, host)? {
+ headers.insert(keys[1].to_string(), val);
}
+
let (mut store, instance) = engine.prepare_component(
component,
None,
diff --git a/docs/content/http-trigger.md b/docs/content/http-trigger.md
index b976afd613..ba73b667a8 100644
--- a/docs/content/http-trigger.md
+++ b/docs/content/http-trigger.md
@@ -238,11 +238,30 @@ Array.forEach(print, Process.argv());
> You can find examples on how to build Wagi applications in
> [the DeisLabs GitHub organization](https://github.com/deislabs?q=wagi&type=public&language=&sort=).
-## The default headers set in Spin HTTP components
+### The default headers set in Spin HTTP components
Spin sets a few default headers on the request based on the base path, component
route, and request URI, which will always be available when writing a module:
+- `spin-full-url` - the full URL of the request —
+ `http://localhost:3000/test/wagi/abc/def?foo=bar`
+- `spin-path-info` - the path info, relative to both the base application path _and_
+ component route — in our example, where the base path is `/test`, and the
+ component route is `/hello`, this is `/abc/def`.
+- `spin-matched-route` - the base path and route pattern matched (including the
+ wildcard pattern, if applicable) (this updates the header set in Wagi to
+ include the base path) — in our case `"/test/hello/..."`.
+- `spin-raw-component-route` - the route pattern matched (including the wildcard
+ pattern, if applicable) — in our case `/hello/...`.
+- `spin-component-route` - the route path matched (stripped of the wildcard
+ pattern) — in our case `/hello`
+- `spin-base-path` - the application base path — in our case `/test`.
+
+### The default headers set in Wagi HTTP components
+
+For Wagi HTTP components, the following are set as environment variables for the
+handler WebAssembly modules:
+
- `X_FULL_URL` - the full URL of the request —
`http://localhost:3000/test/wagi/abc/def?foo=bar`
- `PATH_INFO` - the path info, relative to both the base application path _and_
@@ -257,6 +276,5 @@ route, and request URI, which will always be available when writing a module:
pattern) — in our case `/hello`
- `X_BASE_PATH` - the application base path — in our case `/test`.
-Besides the headers above, components that use the Wagi executor also have
-available
+Besides the headers above, components that use the Wagi executor also have set
[all headers set by Wagi, following the CGI spec](https://github.com/deislabs/wagi/blob/main/docs/environment_variables.md).
diff --git a/docs/content/url-shortener.md b/docs/content/url-shortener.md
index a801043d9f..963e88c77a 100644
--- a/docs/content/url-shortener.md
+++ b/docs/content/url-shortener.md
@@ -70,10 +70,10 @@ The `Router` structure is a Rust representation of the TOML configuration above.
```rust
pub fn redirect(self, req: Request) -> Result<Response> {
- // read the request path from the `PATH_INFO` header
+ // read the request path from the `spin-path-info` header
let path_info = req
.headers()
- .get("PATH_INFO")
+ .get("spin-path-info")
.expect("cannot get path info from request headers");
// if the path is not present in the router configuration,
// return 404 Not Found.
@@ -91,7 +91,7 @@ pub fn redirect(self, req: Request) -> Result<Response> {
```
The `redirect` function is straightforward — it reads the request path from the
-`PATH_INFO` header (make sure to read the [document about the HTTP trigger](/http-trigger)
+`spin-path-info` header (make sure to read the [document about the HTTP trigger](/http-trigger)
for an overview of the HTTP headers present in Spin components), selects the
corresponding destination from the router configuration, then sends the
HTTP redirect to the new location.
diff --git a/docs/modules/spin_static_fs.wasm b/docs/modules/spin_static_fs.wasm
index fbc6914aa1..d3a97b2ea1 100755
Binary files a/docs/modules/spin_static_fs.wasm and b/docs/modules/spin_static_fs.wasm differ
| 274
|
[
"270"
] |
diff --git a/tests/http/assets-test/spin.toml b/tests/http/assets-test/spin.toml
index 28bb37ca70..1e8c2bb9b8 100644
--- a/tests/http/assets-test/spin.toml
+++ b/tests/http/assets-test/spin.toml
@@ -6,8 +6,9 @@ version = "1.0.0"
[[component]]
id = "fs"
+# should we just use git submodules to avoid having binary test files here?
source = "spin_static_fs.wasm"
files = [{source = "static/thisshouldbemounted", destination = "/thisshouldbemounted"}]
[component.trigger]
executor = {type = "spin"}
-route = "/static/..."
\ No newline at end of file
+route = "/static/..."
diff --git a/tests/http/assets-test/spin_static_fs.wasm b/tests/http/assets-test/spin_static_fs.wasm
index 23d3abb666..d3a97b2ea1 100755
Binary files a/tests/http/assets-test/spin_static_fs.wasm and b/tests/http/assets-test/spin_static_fs.wasm differ
diff --git a/tests/integration.rs b/tests/integration.rs
index a58b2b5eef..31e96cbf0e 100644
--- a/tests/integration.rs
+++ b/tests/integration.rs
@@ -183,8 +183,8 @@ mod integration_tests {
assert_eq!(
res.headers()
- .get(HeaderName::from_bytes("PATH_INFO".as_bytes())?)
- .unwrap_or_else(|| panic!("cannot find PATH_INFO header"))
+ .get(HeaderName::from_bytes("spin-path-info".as_bytes())?)
+ .unwrap_or_else(|| panic!("cannot find spin-path-info header"))
.to_str()?,
expected_path_info
);
|
95f9da2a41aded597a437ad041a5a13ab19604ee
|
ea0aafa346ee9f7cfcf6b680e9564105d6c2163a
|
Component configuration used by the internal execution context should not contain trigger configuration
As the issue title suggests, the component configuration used by the internal execution context should not contain trigger configuration — which is a _trigger_-specific piece of configuration:
https://github.com/fermyon/spin/blob/47019687450cc426968718bf8deda4acffb875be/crates/config/src/lib.rs#L54-L66
This is critical for two scenarios:
- adding new triggers with custom configuration requires constantly updating `CoreComponent` (as well as the top-level application configuration).
- using the Spin execution context as a standalone crate (without necessarily an accompanying trigger) requires passing trigger configuration for components, which just has no meaning.
|
I ran into this with the object store implementation. Going to take a look.
Do we want to do something about #86 with this?
|
2022-03-25T19:06:29Z
|
fermyon__spin-261
|
fermyon/spin
|
0.1
|
diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs
index 210fe978ef..94fa2ad848 100644
--- a/crates/config/src/lib.rs
+++ b/crates/config/src/lib.rs
@@ -16,6 +16,8 @@ pub struct Application<T> {
pub info: ApplicationInformation,
/// Configuration for the application components.
pub components: Vec<T>,
+ /// Configuration for the components' triggers.
+ pub component_triggers: ComponentMap<TriggerConfig>,
}
/// Spin API version.
@@ -61,8 +63,6 @@ pub struct CoreComponent {
pub id: String,
/// Per-component WebAssembly configuration.
pub wasm: WasmConfig,
- /// Trigger configuration.
- pub trigger: TriggerConfig,
}
/// The location from which an application was loaded.
@@ -297,3 +297,36 @@ impl TriggerConfig {
}
}
}
+
+/// Component trigger configurations.
+#[derive(Clone, Debug)]
+pub struct ComponentMap<T>(HashMap<String, T>);
+
+impl<T> ComponentMap<T> {
+ /// Get a value for the given component.
+ pub fn get(&self, component: &CoreComponent) -> Option<&T> {
+ self.0.get(&component.id)
+ }
+
+ /// Iterate over all (component id, value) pairs.
+ pub fn iter(&self) -> impl Iterator<Item = (&str, &T)> {
+ self.0.iter().map(|(k, v)| (k.as_str(), v))
+ }
+
+ /// Transforms the ComponentMap into a new one with different values, with possible failures.
+ pub fn try_map_values<U, E>(
+ &self,
+ mut f: impl FnMut(&str, &T) -> Result<U, E>,
+ ) -> Result<ComponentMap<U>, E> {
+ self.0
+ .iter()
+ .map(|(id, val)| Ok((id.clone(), f(id.as_str(), val)?)))
+ .collect()
+ }
+}
+
+impl<T> FromIterator<(String, T)> for ComponentMap<T> {
+ fn from_iter<I: IntoIterator<Item = (String, T)>>(iter: I) -> Self {
+ Self(HashMap::from_iter(iter))
+ }
+}
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 45a838f07e..03113dcf78 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -7,7 +7,7 @@ pub mod io;
use anyhow::{bail, Context, Result};
use io::IoStreamRedirects;
-use spin_config::{CoreComponent, DirectoryMount, ModuleSource};
+use spin_config::{Application, CoreComponent, DirectoryMount, ModuleSource};
use std::{collections::HashMap, io::Write, path::PathBuf, sync::Arc};
use tokio::task::JoinHandle;
use tokio::time::{sleep, Duration};
@@ -19,32 +19,22 @@ use wasmtime_wasi::{ambient_authority, Dir, WasiCtxBuilder};
const SPIN_HOME: &str = ".spin";
/// Builder-specific configuration.
-#[derive(Clone, Debug)]
+#[derive(Clone, Debug, Default)]
pub struct ExecutionContextConfiguration {
- /// Spin application configuration.
- pub app: spin_config::Application<CoreComponent>,
- /// Wasmtime engine configuration.
- pub wasmtime: wasmtime::Config,
- /// Log directory on host
+ /// Component configuration.
+ pub components: Vec<CoreComponent>,
+ /// Label for logging, etc.
+ pub label: String,
+ /// Log directory on host.
pub log_dir: Option<PathBuf>,
}
-impl ExecutionContextConfiguration {
- /// Creates a new execution context configuration.
- pub fn new(app: spin_config::Application<CoreComponent>, log_dir: Option<PathBuf>) -> Self {
- // In order for Wasmtime to run WebAssembly components, multi memory
- // and module linking must always be enabled.
- // See https://github.com/bytecodealliance/wit-bindgen/blob/main/crates/wasmlink.
- let mut wasmtime = wasmtime::Config::default();
- wasmtime.wasm_multi_memory(true);
- wasmtime.wasm_module_linking(true);
-
- log::trace!("Created execution context configuration.");
-
+impl From<Application<CoreComponent>> for ExecutionContextConfiguration {
+ fn from(app: Application<CoreComponent>) -> Self {
Self {
- app,
- wasmtime,
- log_dir,
+ components: app.components,
+ label: app.info.name,
+ ..Default::default()
}
}
}
@@ -64,21 +54,31 @@ pub struct RuntimeContext<T> {
/// An execution context builder.
pub struct Builder<T: Default> {
- /// Top level configuration for
- pub config: ExecutionContextConfiguration,
- /// Linker used to configure the execution context.
- pub linker: Linker<RuntimeContext<T>>,
- /// Store used to configure the execution context.
- pub store: Store<RuntimeContext<T>>,
- /// Wasmtime engine.
- pub engine: Engine,
+ config: ExecutionContextConfiguration,
+ linker: Linker<RuntimeContext<T>>,
+ store: Store<RuntimeContext<T>>,
+ engine: Engine,
}
impl<T: Default> Builder<T> {
/// Creates a new instance of the execution builder.
pub fn new(config: ExecutionContextConfiguration) -> Result<Builder<T>> {
+ Self::with_wasmtime_config(config, Default::default())
+ }
+
+ /// Creates a new instance of the execution builder with the given wasmtime::Config.
+ pub fn with_wasmtime_config(
+ config: ExecutionContextConfiguration,
+ mut wasmtime: wasmtime::Config,
+ ) -> Result<Builder<T>> {
+ // In order for Wasmtime to run WebAssembly components, multi memory
+ // and module linking must always be enabled.
+ // See https://github.com/bytecodealliance/wit-bindgen/blob/main/crates/wasmlink.
+ wasmtime.wasm_multi_memory(true);
+ wasmtime.wasm_module_linking(true);
+
let data = RuntimeContext::default();
- let engine = Engine::new(&config.wasmtime)?;
+ let engine = Engine::new(&wasmtime)?;
let store = Store::new(&engine, data);
let linker = Linker::new(&engine);
@@ -91,13 +91,13 @@ impl<T: Default> Builder<T> {
}
/// Configures the WASI linker imports for the current execution context.
- pub fn link_wasi(&mut self) -> Result<&Self> {
+ pub fn link_wasi(&mut self) -> Result<&mut Self> {
wasmtime_wasi::add_to_linker(&mut self.linker, |ctx| ctx.wasi.as_mut().unwrap())?;
Ok(self)
}
/// Configures the ability to execute outbound HTTP requests.
- pub fn link_http(&mut self) -> Result<&Self> {
+ pub fn link_http(&mut self) -> Result<&mut Self> {
wasi_experimental_http_wasmtime::HttpState::new()?
.add_to_linker(&mut self.linker, |ctx| {
ctx.experimental_http.as_ref().unwrap()
@@ -114,7 +114,7 @@ impl<T: Default> Builder<T> {
#[instrument(skip(self))]
pub async fn build(&mut self) -> Result<ExecutionContext<T>> {
let mut components = HashMap::new();
- for c in &self.config.app.components {
+ for c in &self.config.components {
let core = c.clone();
let module = match c.source.clone() {
ModuleSource::FileReference(p) => {
@@ -165,12 +165,7 @@ impl<T: Default> Builder<T> {
config: ExecutionContextConfiguration,
) -> Result<ExecutionContext<T>> {
let _sloth_warning = warn_if_slothful();
-
- let mut builder = Self::new(config)?;
- builder.link_wasi()?;
- builder.link_http()?;
-
- builder.build().await
+ Self::new(config)?.link_wasi()?.link_http()?.build().await
}
}
@@ -225,14 +220,14 @@ impl<T: Default> ExecutionContext<T> {
save_stdout: bool,
save_stderr: bool,
) -> Result<()> {
- let sanitized_app_name = sanitize(&self.config.app.info.name);
+ let sanitized_label = sanitize(&self.config.label);
let sanitized_component_name = sanitize(&component);
let log_dir = match &self.config.log_dir {
Some(l) => l.clone(),
None => match dirs::home_dir() {
- Some(h) => h.join(SPIN_HOME).join(sanitized_app_name).join("logs"),
- None => PathBuf::from(sanitized_app_name).join("logs"),
+ Some(h) => h.join(SPIN_HOME).join(&sanitized_label).join("logs"),
+ None => PathBuf::from(&sanitized_label).join("logs"),
},
};
diff --git a/crates/http/src/lib.rs b/crates/http/src/lib.rs
index 1ae08e6a18..2bde8d6aee 100644
--- a/crates/http/src/lib.rs
+++ b/crates/http/src/lib.rs
@@ -11,7 +11,7 @@ use crate::{
spin::SpinHttpExecutor,
wagi::WagiHttpExecutor,
};
-use anyhow::{anyhow, ensure, Context, Error, Result};
+use anyhow::{anyhow, Context, Error, Result};
use async_trait::async_trait;
use futures_util::stream::StreamExt;
use http::{uri::Scheme, StatusCode, Uri};
@@ -21,7 +21,7 @@ use hyper::{
service::{make_service_fn, service_fn},
Body, Request, Response, Server,
};
-use spin_config::{Application, CoreComponent};
+use spin_config::{Application, ComponentMap, CoreComponent, HttpConfig, HttpTriggerConfiguration};
use spin_engine::{Builder, ExecutionContextConfiguration};
use spin_http::SpinHttpData;
use std::{future::ready, net::SocketAddr, path::PathBuf, sync::Arc};
@@ -45,10 +45,12 @@ type RuntimeContext = spin_engine::RuntimeContext<SpinHttpData>;
pub struct HttpTrigger {
/// Listening address for the server.
address: String,
- /// Configuration for the application.
- app: Application<CoreComponent>,
/// TLS configuration for the server.
tls: Option<TlsConfig>,
+ /// Trigger configuration.
+ trigger_config: HttpTriggerConfiguration,
+ /// Component trigger configurations.
+ component_triggers: ComponentMap<HttpConfig>,
/// Router.
router: Router,
/// Spin execution context.
@@ -60,28 +62,38 @@ impl HttpTrigger {
pub async fn new(
address: String,
app: Application<CoreComponent>,
- wasmtime: Option<wasmtime::Config>,
tls: Option<TlsConfig>,
log_dir: Option<PathBuf>,
) -> Result<Self> {
- ensure!(
- app.info.trigger.as_http().is_some(),
- "Application trigger is not HTTP"
- );
+ let trigger_config = app
+ .info
+ .trigger
+ .as_http()
+ .ok_or_else(|| anyhow!("Application trigger is not HTTP"))?
+ .clone();
+
+ let component_triggers = app.component_triggers.try_map_values(|id, trigger| {
+ trigger
+ .as_http()
+ .cloned()
+ .ok_or_else(|| anyhow!("Expected HTTP configuration for component {}", id))
+ })?;
- let mut config = ExecutionContextConfiguration::new(app.clone(), log_dir);
- if let Some(wasmtime) = wasmtime {
- config.wasmtime = wasmtime;
- };
+ let router = Router::build(&app)?;
+ let config = ExecutionContextConfiguration {
+ log_dir,
+ ..app.into()
+ };
let engine = Arc::new(Builder::build_default(config).await?);
- let router = Router::build(&app)?;
+
log::trace!("Created new HTTP trigger.");
Ok(Self {
address,
- app,
tls,
+ trigger_config,
+ component_triggers,
router,
engine,
})
@@ -91,20 +103,16 @@ impl HttpTrigger {
pub async fn handle(&self, req: Request<Body>, addr: SocketAddr) -> Result<Response<Body>> {
log::info!(
"Processing request for application {} on URI {}",
- &self.app.info.name,
+ &self.engine.config.label,
req.uri()
);
- // We can unwrap here because the trigger type has already been asserted in `HttpTrigger::new`
- let app_trigger = self.app.info.trigger.as_http().cloned().unwrap();
-
match req.uri().path() {
"/healthz" => Ok(Response::new(Body::from("OK"))),
route => match self.router.route(route) {
Ok(c) => {
- let trigger = c.trigger.as_http().ok_or_else(|| {
- anyhow!("Expected HTTP configuration for component {}", c.id)
- })?;
+ let trigger = self.component_triggers.get(&c).unwrap();
+
let executor = match &trigger.executor {
Some(i) => i,
None => &spin_config::HttpExecutor::Spin,
@@ -117,7 +125,7 @@ impl HttpTrigger {
.execute(
&self.engine,
&c.id,
- &app_trigger.base,
+ &self.trigger_config.base,
&trigger.route,
req,
addr,
@@ -132,7 +140,7 @@ impl HttpTrigger {
.execute(
&self.engine,
&c.id,
- &app_trigger.base,
+ &self.trigger_config.base,
&trigger.route,
req,
addr,
@@ -525,7 +533,7 @@ mod tests {
})
.build_configuration();
- let trigger = HttpTrigger::new("".to_string(), cfg, None, None, None).await?;
+ let trigger = HttpTrigger::new("".to_string(), cfg, None, None).await?;
let body = Body::from("Fermyon".as_bytes().to_vec());
let req = http::Request::post("https://myservice.fermyon.dev/test?abc=def")
@@ -554,7 +562,7 @@ mod tests {
})
.build_configuration();
- let trigger = HttpTrigger::new("".to_string(), cfg, None, None, None).await?;
+ let trigger = HttpTrigger::new("".to_string(), cfg, None, None).await?;
let body = Body::from("Fermyon".as_bytes().to_vec());
let req = http::Request::builder()
diff --git a/crates/http/src/routes.rs b/crates/http/src/routes.rs
index d303caeb24..222439a827 100644
--- a/crates/http/src/routes.rs
+++ b/crates/http/src/routes.rs
@@ -34,7 +34,7 @@ impl Router {
.components
.iter()
.map(|c| {
- let trigger = c.trigger.as_http().unwrap();
+ let trigger = app.component_triggers.get(c).unwrap().as_http().unwrap();
(
RoutePattern::from(&app_trigger.base, &trigger.route),
c.clone(),
@@ -334,10 +334,6 @@ mod route_tests {
CoreComponent {
id: id.to_string(),
source: spin_config::ModuleSource::FileReference("FAKE".into()),
- trigger: spin_config::TriggerConfig::Http(spin_config::HttpConfig {
- route: "/test".to_string(),
- executor: Some(spin_config::HttpExecutor::Spin),
- }),
wasm: spin_config::WasmConfig::default(),
}
}
diff --git a/crates/loader/src/bindle/mod.rs b/crates/loader/src/bindle/mod.rs
index fd80a0a687..452d862654 100644
--- a/crates/loader/src/bindle/mod.rs
+++ b/crates/loader/src/bindle/mod.rs
@@ -65,6 +65,11 @@ async fn prepare(
let info = info(&raw, &invoice, url);
log::trace!("Application information from bindle: {:?}", info);
+ let component_triggers = raw
+ .components
+ .iter()
+ .map(|c| (c.id.clone(), c.trigger.clone()))
+ .collect();
let components = future::join_all(
raw.components
.into_iter()
@@ -76,7 +81,11 @@ async fn prepare(
.map(|x| x.expect("Cannot prepare component"))
.collect::<Vec<_>>();
- Ok(Application { info, components })
+ Ok(Application {
+ info,
+ components,
+ component_triggers,
+ })
}
/// Given a raw component manifest, prepare its assets and return a fully formed core component.
@@ -113,14 +122,7 @@ async fn core(
mounts,
allowed_http_hosts,
};
- let trigger = raw.trigger;
-
- Ok(CoreComponent {
- source,
- id,
- wasm,
- trigger,
- })
+ Ok(CoreComponent { source, id, wasm })
}
/// Converts the raw application manifest from the bindle invoice into the
diff --git a/crates/loader/src/local/mod.rs b/crates/loader/src/local/mod.rs
index c340be604d..d9dcf99c73 100644
--- a/crates/loader/src/local/mod.rs
+++ b/crates/loader/src/local/mod.rs
@@ -71,6 +71,11 @@ async fn prepare(
) -> Result<Application<CoreComponent>> {
let info = info(raw.info, &src);
+ let component_triggers = raw
+ .components
+ .iter()
+ .map(|c| (c.id.clone(), c.trigger.clone()))
+ .collect();
let components = future::join_all(
raw.components
.into_iter()
@@ -82,7 +87,11 @@ async fn prepare(
.collect::<Result<Vec<_>>>()
.context("Failed to prepare configuration")?;
- Ok(Application { info, components })
+ Ok(Application {
+ info,
+ components,
+ component_triggers,
+ })
}
/// Given a raw component manifest, prepare its assets and return a fully formed core component.
@@ -121,14 +130,7 @@ async fn core(
mounts,
allowed_http_hosts,
};
- let trigger = raw.trigger;
-
- Ok(CoreComponent {
- source,
- id,
- wasm,
- trigger,
- })
+ Ok(CoreComponent { source, id, wasm })
}
/// Converts the raw application information from the spin.toml manifest to the standard configuration.
diff --git a/crates/redis/src/lib.rs b/crates/redis/src/lib.rs
index 1906f6d6dd..1d8f7ac482 100644
--- a/crates/redis/src/lib.rs
+++ b/crates/redis/src/lib.rs
@@ -3,11 +3,13 @@
mod spin;
use crate::spin::SpinRedisExecutor;
-use anyhow::{ensure, Result};
+use anyhow::{anyhow, Result};
use async_trait::async_trait;
use futures::StreamExt;
use redis::Client;
-use spin_config::{Application, CoreComponent, RedisConfig};
+use spin_config::{
+ Application, ComponentMap, CoreComponent, RedisConfig, RedisTriggerConfiguration,
+};
use spin_engine::{Builder, ExecutionContextConfiguration};
use spin_redis::SpinRedisData;
use std::{collections::HashMap, path::PathBuf, sync::Arc};
@@ -20,8 +22,10 @@ type RuntimeContext = spin_engine::RuntimeContext<SpinRedisData>;
/// The Spin Redis trigger.
#[derive(Clone)]
pub struct RedisTrigger {
- /// Configuration for the application.
- app: Application<CoreComponent>,
+ /// Trigger configuration.
+ trigger_config: RedisTriggerConfiguration,
+ /// Component trigger configurations.
+ component_triggers: ComponentMap<RedisConfig>,
/// Spin execution context.
engine: Arc<ExecutionContext>,
/// Map from channel name to tuple of component name & index.
@@ -30,36 +34,38 @@ pub struct RedisTrigger {
impl RedisTrigger {
/// Create a new Spin Redis trigger.
- pub async fn new(
- app: Application<CoreComponent>,
- wasmtime: Option<wasmtime::Config>,
- log_dir: Option<PathBuf>,
- ) -> Result<Self> {
- ensure!(
- app.info.trigger.as_redis().is_some(),
- "Application trigger is not Redis"
- );
-
- let mut config = ExecutionContextConfiguration::new(app.clone(), log_dir);
- if let Some(wasmtime) = wasmtime {
- config.wasmtime = wasmtime;
+ pub async fn new(app: Application<CoreComponent>, log_dir: Option<PathBuf>) -> Result<Self> {
+ let trigger_config = app
+ .info
+ .trigger
+ .as_redis()
+ .ok_or_else(|| anyhow!("Application trigger is not Redis"))?
+ .clone();
+
+ let component_triggers = app.component_triggers.try_map_values(|id, trigger| {
+ trigger
+ .as_redis()
+ .cloned()
+ .ok_or_else(|| anyhow!("Expected Redis configuration for component {}", id))
+ })?;
+
+ let subscriptions = app
+ .components
+ .iter()
+ .enumerate()
+ .filter_map(|(idx, c)| component_triggers.get(c).map(|c| (c.channel.clone(), idx)))
+ .collect();
+
+ let config = ExecutionContextConfiguration {
+ log_dir,
+ ..app.into()
};
let engine = Arc::new(Builder::build_default(config).await?);
log::trace!("Created new Redis trigger.");
- let subscriptions =
- app.components
- .iter()
- .enumerate()
- .fold(HashMap::new(), |mut map, (idx, c)| {
- if let Some(RedisConfig { channel, .. }) = c.trigger.as_redis() {
- map.insert(channel.clone(), idx);
- }
- map
- });
-
Ok(Self {
- app,
+ trigger_config,
+ component_triggers,
engine,
subscriptions,
})
@@ -67,19 +73,18 @@ impl RedisTrigger {
/// Run the Redis trigger indefinitely.
pub async fn run(&self) -> Result<()> {
- // We can unwrap here because the trigger type has already been asserted in `RedisTrigger::new`
- let address = self.app.info.trigger.as_redis().cloned().unwrap().address;
+ let address = self.trigger_config.address.as_str();
log::info!("Connecting to Redis server at {}", address);
- let client = Client::open(address.clone())?;
+ let client = Client::open(address.to_string())?;
let mut pubsub = client.get_async_connection().await?.into_pubsub();
// Subscribe to channels
- for (subscription, id) in self.subscriptions.iter() {
- let name = &self.app.components[*id].id;
+ for (subscription, idx) in self.subscriptions.iter() {
+ let name = &self.engine.config.components[*idx].id;
log::info!(
"Subscribed component #{} ({}) to channel: {}",
- id,
+ idx,
name,
subscription
);
@@ -100,14 +105,12 @@ impl RedisTrigger {
let channel = msg.get_channel_name();
log::info!("Received message on channel {:?}", channel);
- if let Some(id) = self.subscriptions.get(channel).copied() {
- let component = &self.app.components[id];
- let executor = component
- .trigger
- .as_redis()
- .cloned()
- .unwrap() // TODO
- .executor
+ if let Some(idx) = self.subscriptions.get(channel).copied() {
+ let component = &self.engine.config.components[idx];
+ let executor = self
+ .component_triggers
+ .get(component)
+ .and_then(|t| t.executor.clone())
.unwrap_or_default();
match executor {
diff --git a/docs/content/extending-and-embedding.md b/docs/content/extending-and-embedding.md
index 8975510e1c..4e59b505e9 100644
--- a/docs/content/extending-and-embedding.md
+++ b/docs/content/extending-and-embedding.md
@@ -56,14 +56,11 @@ Let's have a look at building the timer trigger:
wit_bindgen_wasmtime::import!("spin-timer.wit");
type ExecutionContext = spin_engine::ExecutionContext<spin_timer::SpinTimerData>;
-/// A custom timer trigger that executes the
-/// first component of an application on every interval.
+/// A custom timer trigger that executes a component on every interval.
#[derive(Clone)]
pub struct TimerTrigger {
/// The interval at which the component is executed.
pub interval: Duration,
- /// The application configuration.
- app: Application<CoreComponent>,
/// The Spin execution context.
engine: Arc<ExecutionContext>,
}
diff --git a/examples/spin-timer/src/main.rs b/examples/spin-timer/src/main.rs
index 29df651a31..facc6a58bb 100644
--- a/examples/spin-timer/src/main.rs
+++ b/examples/spin-timer/src/main.rs
@@ -2,10 +2,7 @@
#![allow(clippy::needless_question_mark)]
use anyhow::Result;
-use spin_config::{
- Application, ApplicationInformation, ApplicationOrigin, CoreComponent, ModuleSource,
- TriggerConfig, WasmConfig,
-};
+use spin_config::{CoreComponent, ModuleSource, WasmConfig};
use spin_engine::{Builder, ExecutionContextConfiguration};
use std::{sync::Arc, time::Duration};
use tokio::task::spawn_blocking;
@@ -20,7 +17,7 @@ async fn main() -> Result<()> {
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
.init();
- let trigger = TimerTrigger::new(Duration::from_secs(1), app()).await?;
+ let trigger = TimerTrigger::new(Duration::from_secs(1), component()).await?;
trigger.run().await
}
@@ -30,24 +27,22 @@ async fn main() -> Result<()> {
pub struct TimerTrigger {
/// The interval at which the component is executed.
pub interval: Duration,
- /// The application configuration.
- app: Application<CoreComponent>,
/// The Spin execution context.
engine: Arc<ExecutionContext>,
}
impl TimerTrigger {
/// Creates a new trigger.
- pub async fn new(interval: Duration, app: Application<CoreComponent>) -> Result<Self> {
- let config = ExecutionContextConfiguration::new(app.clone(), None);
+ pub async fn new(interval: Duration, component: CoreComponent) -> Result<Self> {
+ let config = ExecutionContextConfiguration {
+ components: vec![component],
+ label: "timer-app".to_string(),
+ ..Default::default()
+ };
let engine = Arc::new(Builder::build_default(config).await?);
log::debug!("Created new Timer trigger.");
- Ok(Self {
- interval,
- app,
- engine,
- })
+ Ok(Self { interval, engine })
}
/// Runs the trigger at every interval.
@@ -66,9 +61,13 @@ impl TimerTrigger {
/// Execute the first component in the application configuration.
async fn handle(&self, msg: String) -> Result<()> {
- let (mut store, instance) =
- self.engine
- .prepare_component(&self.app.components[0].id, None, None, None, None)?;
+ let (mut store, instance) = self.engine.prepare_component(
+ &self.engine.config.components[0].id,
+ None,
+ None,
+ None,
+ None,
+ )?;
let res = spawn_blocking(move || -> Result<String> {
let t = spin_timer::SpinTimer::new(&mut store, &instance, |host| {
@@ -83,27 +82,10 @@ impl TimerTrigger {
}
}
-pub fn app() -> Application<CoreComponent> {
- let info = ApplicationInformation {
- spin_version: spin_config::SpinVersion::V1,
- name: "test-app".to_string(),
- version: "1.0.0".to_string(),
- description: None,
- authors: vec![],
- trigger: spin_config::ApplicationTrigger::Http(spin_config::HttpTriggerConfiguration {
- base: "/".to_owned(),
- }),
- namespace: None,
- origin: ApplicationOrigin::File("".into()),
- };
-
- let component = CoreComponent {
+pub fn component() -> CoreComponent {
+ CoreComponent {
source: ModuleSource::FileReference("target/test-programs/echo.wasm".into()),
id: "test".to_string(),
- trigger: TriggerConfig::default(),
wasm: WasmConfig::default(),
- };
- let components = vec![component];
-
- Application::<CoreComponent> { info, components }
+ }
}
diff --git a/src/commands/up.rs b/src/commands/up.rs
index 343c4eca8f..6d1bb7c69b 100644
--- a/src/commands/up.rs
+++ b/src/commands/up.rs
@@ -130,11 +130,11 @@ impl UpCommand {
match &app.info.trigger {
ApplicationTrigger::Http(_) => {
- let trigger = HttpTrigger::new(self.address, app, None, tls, self.log).await?;
+ let trigger = HttpTrigger::new(self.address, app, tls, self.log).await?;
trigger.run().await?;
}
ApplicationTrigger::Redis(_) => {
- let trigger = RedisTrigger::new(app, None, self.log).await?;
+ let trigger = RedisTrigger::new(app, self.log).await?;
trigger.run().await?;
}
}
| 261
|
[
"229"
] |
diff --git a/crates/loader/src/local/tests.rs b/crates/loader/src/local/tests.rs
index aa320a8d30..2769a9ab22 100644
--- a/crates/loader/src/local/tests.rs
+++ b/crates/loader/src/local/tests.rs
@@ -11,28 +11,35 @@ async fn test_from_local_source() -> Result<()> {
let temp_dir = tempfile::tempdir()?;
let dir = temp_dir.path();
- let cfg = from_file(MANIFEST, dir).await?;
+ let app = from_file(MANIFEST, dir).await?;
- assert_eq!(cfg.info.name, "spin-local-source-test");
- assert_eq!(cfg.info.version, "1.0.0");
- assert_eq!(cfg.info.spin_version, SpinVersion::V1);
+ assert_eq!(app.info.name, "spin-local-source-test");
+ assert_eq!(app.info.version, "1.0.0");
+ assert_eq!(app.info.spin_version, SpinVersion::V1);
assert_eq!(
- cfg.info.authors[0],
+ app.info.authors[0],
"Fermyon Engineering <engineering@fermyon.com>"
);
- let http = cfg.info.trigger.as_http().unwrap().clone();
+ let http = app.info.trigger.as_http().unwrap().clone();
assert_eq!(http.base, "/".to_string());
- let http = cfg.components[0].trigger.as_http().unwrap().clone();
+ let component = &app.components[0];
+ assert_eq!(component.wasm.mounts.len(), 1);
+
+ let http = app
+ .component_triggers
+ .get(component)
+ .unwrap()
+ .as_http()
+ .unwrap()
+ .clone();
assert_eq!(http.executor.unwrap(), HttpExecutor::Spin);
assert_eq!(http.route, "/...".to_string());
- assert_eq!(cfg.components[0].wasm.mounts.len(), 1);
-
let expected_path =
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/valid-with-files/spin.toml");
- assert_eq!(cfg.info.origin, ApplicationOrigin::File(expected_path));
+ assert_eq!(app.info.origin, ApplicationOrigin::File(expected_path));
Ok(())
}
diff --git a/crates/redis/src/tests.rs b/crates/redis/src/tests.rs
index 008699283f..90123e7bdb 100644
--- a/crates/redis/src/tests.rs
+++ b/crates/redis/src/tests.rs
@@ -28,7 +28,7 @@ async fn test_pubsub() -> Result<()> {
})
.build_configuration();
- let trigger = RedisTrigger::new(cfg, None, None).await?;
+ let trigger = RedisTrigger::new(cfg, None).await?;
// TODO
// use redis::{FromRedisValue, Msg, Value};
diff --git a/crates/testing/src/lib.rs b/crates/testing/src/lib.rs
index eb6c08e633..3a42636f1a 100644
--- a/crates/testing/src/lib.rs
+++ b/crates/testing/src/lib.rs
@@ -75,10 +75,6 @@ impl TestConfig {
CoreComponent {
source: ModuleSource::FileReference(module_path),
id: "test-component".to_string(),
- trigger: self
- .trigger_config
- .clone()
- .expect("http_trigger or redis_trigger required"),
wasm: Default::default(),
}
}
@@ -87,11 +83,19 @@ impl TestConfig {
Application {
info: self.build_application_information(),
components: vec![self.build_component()],
+ component_triggers: [(
+ "test-component".to_string(),
+ self.trigger_config
+ .clone()
+ .expect("http_trigger or redis_trigger required"),
+ )]
+ .into_iter()
+ .collect(),
}
}
pub async fn build_http_trigger(&self) -> HttpTrigger {
- HttpTrigger::new("".to_string(), self.build_configuration(), None, None, None)
+ HttpTrigger::new("".to_string(), self.build_configuration(), None, None)
.await
.expect("failed to build HttpTrigger")
}
|
95f9da2a41aded597a437ad041a5a13ab19604ee
|
f830e5462ab3d89717e660e425d6ae8f32ee4341
|
Use `.cargo/config.toml` `target = "wasm32-wasi"` in test crates
Some quick testing suggests that a [`rust-toolchain.toml`](https://rust-lang.github.io/rustup/overrides.html#the-toolchain-file) file like this:
```toml
[toolchain]
targets = [ "wasm32-wasi" ]
```
will make `cargo` default to `--target wasm32-wasi`
|
In the examples / templates (specifically for `rust`) there is a `.cargo/config.toml` that contains
```toml
[build]
target = "wasm32-wasi"
```
To enable `cargo build --release`
Oh cool. Why aren't we doing that everywhere?
Ha, thats exactly where I was testing the rust-toolchain.toml file, so it might not have actually been doing anything :laughing:
I think for all our examples we include the `.cargo/config.toml`. I made a point to include that in the generated template code.
Yeah we just don't have it in all our test crates.
|
2022-03-25T12:48:24Z
|
fermyon__spin-255
|
fermyon/spin
|
0.1
|
diff --git a/crates/http/benches/spin-http-benchmark/.cargo/config.toml b/crates/http/benches/spin-http-benchmark/.cargo/config.toml
new file mode 100644
index 0000000000..6b77899cb3
--- /dev/null
+++ b/crates/http/benches/spin-http-benchmark/.cargo/config.toml
@@ -0,0 +1,2 @@
+[build]
+target = "wasm32-wasi"
diff --git a/crates/http/benches/wagi-benchmark/.cargo/config.toml b/crates/http/benches/wagi-benchmark/.cargo/config.toml
new file mode 100644
index 0000000000..6b77899cb3
--- /dev/null
+++ b/crates/http/benches/wagi-benchmark/.cargo/config.toml
@@ -0,0 +1,2 @@
+[build]
+target = "wasm32-wasi"
| 255
|
[
"234"
] |
diff --git a/crates/http/tests/rust-http-test/.cargo/config.toml b/crates/http/tests/rust-http-test/.cargo/config.toml
new file mode 100644
index 0000000000..6b77899cb3
--- /dev/null
+++ b/crates/http/tests/rust-http-test/.cargo/config.toml
@@ -0,0 +1,2 @@
+[build]
+target = "wasm32-wasi"
diff --git a/crates/http/tests/wagi-test/.cargo/config.toml b/crates/http/tests/wagi-test/.cargo/config.toml
new file mode 100644
index 0000000000..6b77899cb3
--- /dev/null
+++ b/crates/http/tests/wagi-test/.cargo/config.toml
@@ -0,0 +1,2 @@
+[build]
+target = "wasm32-wasi"
|
95f9da2a41aded597a437ad041a5a13ab19604ee
|
67b222b136ab936ae5a9ec00e99432191fe0c896
|
Add a `spin-testing` crate with common testing utilities
We have a lot of code duplication in some of our tests around e.g. setting up `ApplicationInformation`. I'd like a e.g. `crates/testing` :bike::derelict_house: crate that would be used in `[dev-dependencies]` with helpers like `build_test_application_information`
|
2022-03-24T20:58:17Z
|
fermyon__spin-245
|
fermyon/spin
|
0.1
|
diff --git a/Cargo.lock b/Cargo.lock
index 7b9f30931a..ad800b4df5 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3143,6 +3143,7 @@ dependencies = [
"serde",
"spin-config",
"spin-engine",
+ "spin-testing",
"tls-listener",
"tokio",
"tokio-rustls 0.23.3",
@@ -3235,6 +3236,7 @@ dependencies = [
"serde",
"spin-config",
"spin-engine",
+ "spin-testing",
"tokio",
"tracing",
"tracing-futures",
@@ -3276,6 +3278,17 @@ dependencies = [
"walkdir",
]
+[[package]]
+name = "spin-testing"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "http 0.2.6",
+ "hyper",
+ "spin-config",
+ "spin-http-engine",
+]
+
[[package]]
name = "spin-timer"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index 32ff707594..c2c4843b67 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -47,6 +47,7 @@ members = [
"crates/outbound-http",
"crates/redis",
"crates/templates",
+ "crates/testing",
"examples/spin-timer",
"sdk/rust",
"sdk/rust/macro"
diff --git a/crates/http/Cargo.toml b/crates/http/Cargo.toml
index 8e40827e32..32270cece2 100644
--- a/crates/http/Cargo.toml
+++ b/crates/http/Cargo.toml
@@ -45,6 +45,7 @@ wit-bindgen-wasmtime = { git = "https://github.com/bytecodealliance/wit-bindgen"
criterion = { version = "0.3.5", features = ["async_tokio"] }
miniserde = "0.1"
num_cpus = "1"
+spin-testing = { path = "../testing" }
[[bench]]
name = "baseline"
diff --git a/crates/http/benches/baseline.rs b/crates/http/benches/baseline.rs
index 9701772fdc..bbee36e2a4 100644
--- a/crates/http/benches/baseline.rs
+++ b/crates/http/benches/baseline.rs
@@ -1,15 +1,12 @@
-use std::path::PathBuf;
use std::time::Instant;
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use futures::future::join_all;
-use http::{Request, StatusCode};
-use spin_config::{
- ApplicationInformation, ApplicationOrigin, Configuration, CoreComponent, HttpConfig,
- HttpExecutor, ModuleSource, SpinVersion, TriggerConfig,
-};
+use http::Request;
+use spin_config::{HttpConfig, HttpExecutor};
use spin_http_engine::HttpTrigger;
+use spin_testing::{assert_http_response_success, TestConfig};
use tokio::runtime::Runtime;
use tokio::task;
@@ -21,10 +18,6 @@ criterion_group!(
bench_wagi_concurrency_minimal,
);
-const SPIN_HTTP_MINIMAL_PATH: &str = "../../target/test-programs/spin-http-benchmark.wasm";
-
-const WAGI_MINIMAL_PATH: &str = "../../target/test-programs/wagi-benchmark.wasm";
-
// Benchmark time to start and process one request
fn bench_startup(c: &mut Criterion) {
let async_runtime = Runtime::new().unwrap();
@@ -32,14 +25,24 @@ fn bench_startup(c: &mut Criterion) {
let mut group = c.benchmark_group("startup");
group.bench_function("spin-executor", |b| {
b.to_async(&async_runtime).iter(|| async {
- let trigger = build_trigger(SPIN_HTTP_MINIMAL_PATH, HttpExecutor::Spin).await;
+ let trigger = TestConfig::default()
+ .test_program("spin-http-benchmark.wasm")
+ .http_trigger(Default::default())
+ .build_http_trigger()
+ .await;
run_concurrent_requests(&trigger, 0, 1).await;
});
});
group.bench_function("spin-wagi-executor", |b| {
b.to_async(&async_runtime).iter(|| async {
- let trigger =
- build_trigger(WAGI_MINIMAL_PATH, HttpExecutor::Wagi(Default::default())).await;
+ let trigger = TestConfig::default()
+ .test_program("wagi-benchmark.wasm")
+ .http_trigger(HttpConfig {
+ executor: Some(HttpExecutor::Wagi(Default::default())),
+ ..Default::default()
+ })
+ .build_http_trigger()
+ .await;
run_concurrent_requests(&trigger, 0, 1).await;
});
});
@@ -49,8 +52,12 @@ fn bench_startup(c: &mut Criterion) {
fn bench_spin_concurrency_minimal(c: &mut Criterion) {
let async_runtime = Runtime::new().unwrap();
- let spin_trigger =
- async_runtime.block_on(build_trigger(SPIN_HTTP_MINIMAL_PATH, HttpExecutor::Spin));
+ let spin_trigger = async_runtime.block_on(
+ TestConfig::default()
+ .test_program("spin-http-benchmark.wasm")
+ .http_trigger(Default::default())
+ .build_http_trigger(),
+ );
let sleep_ms = 1;
let mut group = c.benchmark_group(format!("spin-executor/sleep-{}ms", sleep_ms));
@@ -79,10 +86,15 @@ fn bench_spin_concurrency_minimal(c: &mut Criterion) {
fn bench_wagi_concurrency_minimal(c: &mut Criterion) {
let async_runtime = Runtime::new().unwrap();
- let wagi_trigger = async_runtime.block_on(build_trigger(
- WAGI_MINIMAL_PATH,
- HttpExecutor::Wagi(Default::default()),
- ));
+ let wagi_trigger = async_runtime.block_on(
+ TestConfig::default()
+ .test_program("wagi-benchmark.wasm")
+ .http_trigger(HttpConfig {
+ executor: Some(HttpExecutor::Wagi(Default::default())),
+ ..Default::default()
+ })
+ .build_http_trigger(),
+ );
let sleep_ms = 1;
let mut group = c.benchmark_group(format!("spin-wagi-executor/sleep-{}ms", sleep_ms));
@@ -129,41 +141,8 @@ async fn run_concurrent_requests(trigger: &HttpTrigger, sleep_ms: u32, concurren
.handle(req, "127.0.0.1:55555".parse().unwrap())
.await
.unwrap();
- assert_eq!(resp.status(), StatusCode::OK);
+ assert_http_response_success(&resp);
})
}))
.await;
}
-
-async fn build_trigger(entrypoint_path: &str, executor: HttpExecutor) -> HttpTrigger {
- let entrypoint_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(entrypoint_path);
-
- let info = ApplicationInformation {
- spin_version: SpinVersion::V1,
- name: "bench-app".to_string(),
- version: "1.0.0".to_string(),
- description: None,
- authors: vec![],
- trigger: spin_config::ApplicationTrigger::Http(spin_config::HttpTriggerConfiguration {
- base: "/".to_owned(),
- }),
- namespace: None,
- origin: ApplicationOrigin::File("bench_spin.toml".into()),
- };
-
- let component = CoreComponent {
- source: ModuleSource::FileReference(entrypoint_path),
- id: "bench".to_string(),
- trigger: TriggerConfig::Http(HttpConfig {
- route: "/".to_string(),
- executor: Some(executor),
- }),
- wasm: Default::default(),
- };
- let components = vec![component];
-
- let cfg = Configuration::<CoreComponent> { info, components };
- HttpTrigger::new("".to_string(), cfg, None, None, None)
- .await
- .unwrap()
-}
diff --git a/crates/http/src/lib.rs b/crates/http/src/lib.rs
index ca0800315a..16dd487ea9 100644
--- a/crates/http/src/lib.rs
+++ b/crates/http/src/lib.rs
@@ -384,22 +384,12 @@ pub(crate) trait HttpExecutor: Clone + Send + Sync + 'static {
mod tests {
use super::*;
use anyhow::Result;
- use spin_config::{
- ApplicationInformation, Configuration, HttpConfig, HttpExecutor, ModuleSource,
- TriggerConfig,
- };
- use std::{
- collections::BTreeMap,
- net::{IpAddr, Ipv4Addr},
- sync::Once,
- };
+ use spin_config::{HttpConfig, HttpExecutor};
+ use spin_testing::test_socket_addr;
+ use std::{collections::BTreeMap, sync::Once};
static LOGGER: Once = Once::new();
- const RUST_ENTRYPOINT_PATH: &str = "../../target/test-programs/rust-http-test.wasm";
-
- const WAGI_ENTRYPOINT_PATH: &str = "../../target/test-programs/wagi-test.wasm";
-
/// We can only initialize the tracing subscriber once per crate.
pub(crate) fn init() {
LOGGER.call_once(|| {
@@ -409,12 +399,6 @@ mod tests {
});
}
- fn fake_file_origin() -> spin_config::ApplicationOrigin {
- let dir = env!("CARGO_MANIFEST_DIR");
- let fake_path = std::path::PathBuf::from(dir).join("fake_spin.toml");
- spin_config::ApplicationOrigin::File(fake_path)
- }
-
#[test]
fn test_default_headers_with_base_path() -> Result<()> {
let scheme = "https";
@@ -529,48 +513,24 @@ mod tests {
async fn test_spin_http() -> Result<()> {
init();
- let info = ApplicationInformation {
- spin_version: spin_config::SpinVersion::V1,
- name: "test-app".to_string(),
- version: "1.0.0".to_string(),
- description: None,
- authors: vec![],
- trigger: spin_config::ApplicationTrigger::Http(spin_config::HttpTriggerConfiguration {
- base: "/".to_owned(),
- }),
- namespace: None,
- origin: fake_file_origin(),
- };
-
- let component = CoreComponent {
- source: ModuleSource::FileReference(RUST_ENTRYPOINT_PATH.into()),
- id: "test".to_string(),
- trigger: TriggerConfig::Http(HttpConfig {
+ let cfg = spin_testing::TestConfig::default()
+ .test_program("rust-http-test.wasm")
+ .http_trigger(HttpConfig {
route: "/test".to_string(),
executor: Some(HttpExecutor::Spin),
- }),
- wasm: Default::default(),
- };
- let components = vec![component];
+ })
+ .build_configuration();
- let cfg = Configuration::<CoreComponent> { info, components };
let trigger = HttpTrigger::new("".to_string(), cfg, None, None, None).await?;
let body = Body::from("Fermyon".as_bytes().to_vec());
- let req = http::Request::builder()
- .method("POST")
- .uri("https://myservice.fermyon.dev/test?abc=def")
+ let req = http::Request::post("https://myservice.fermyon.dev/test?abc=def")
.header("x-custom-foo", "bar")
.header("x-custom-foo2", "bar2")
.body(body)
.unwrap();
- let res = trigger
- .handle(
- req,
- SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 1234),
- )
- .await?;
+ let res = trigger.handle(req, test_socket_addr()).await?;
assert_eq!(res.status(), StatusCode::OK);
let body_bytes = hyper::body::to_bytes(res.into_body()).await.unwrap();
assert_eq!(body_bytes.to_vec(), "Hello, Fermyon".as_bytes());
@@ -582,31 +542,14 @@ mod tests {
async fn test_wagi_http() -> Result<()> {
init();
- let info = ApplicationInformation {
- spin_version: spin_config::SpinVersion::V1,
- name: "test-app".to_string(),
- version: "1.0.0".to_string(),
- description: None,
- authors: vec![],
- trigger: spin_config::ApplicationTrigger::Http(spin_config::HttpTriggerConfiguration {
- base: "/".to_owned(),
- }),
- namespace: None,
- origin: fake_file_origin(),
- };
-
- let component = CoreComponent {
- source: ModuleSource::FileReference(WAGI_ENTRYPOINT_PATH.into()),
- id: "test".to_string(),
- trigger: TriggerConfig::Http(HttpConfig {
+ let cfg = spin_testing::TestConfig::default()
+ .test_program("wagi-test.wasm")
+ .http_trigger(HttpConfig {
route: "/test".to_string(),
executor: Some(HttpExecutor::Wagi(Default::default())),
- }),
- wasm: spin_config::WasmConfig::default(),
- };
- let components = vec![component];
+ })
+ .build_configuration();
- let cfg = Configuration::<CoreComponent> { info, components };
let trigger = HttpTrigger::new("".to_string(), cfg, None, None, None).await?;
let body = Body::from("Fermyon".as_bytes().to_vec());
@@ -618,12 +561,7 @@ mod tests {
.body(body)
.unwrap();
- let res = trigger
- .handle(
- req,
- SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 1234),
- )
- .await?;
+ let res = trigger.handle(req, test_socket_addr()).await?;
assert_eq!(res.status(), StatusCode::OK);
let body_bytes = hyper::body::to_bytes(res.into_body()).await.unwrap();
diff --git a/crates/redis/Cargo.toml b/crates/redis/Cargo.toml
index c63019a89c..ff79dfec7d 100644
--- a/crates/redis/Cargo.toml
+++ b/crates/redis/Cargo.toml
@@ -24,4 +24,7 @@ tracing-subscriber = { version = "0.3.7", features = [ "env-filter" ] }
wasi-common = "0.34"
wasmtime = "0.34"
wasmtime-wasi = "0.34"
-wit-bindgen-wasmtime = { git = "https://github.com/bytecodealliance/wit-bindgen", rev = "2f46ce4cc072107153da0cefe15bdc69aa5b84d0" }
\ No newline at end of file
+wit-bindgen-wasmtime = { git = "https://github.com/bytecodealliance/wit-bindgen", rev = "2f46ce4cc072107153da0cefe15bdc69aa5b84d0" }
+
+[dev-dependencies]
+spin-testing = { path = "../testing" }
\ No newline at end of file
| 245
|
[
"233"
] |
diff --git a/crates/redis/src/tests.rs b/crates/redis/src/tests.rs
index 1cd5fd37ad..008699283f 100644
--- a/crates/redis/src/tests.rs
+++ b/crates/redis/src/tests.rs
@@ -1,15 +1,11 @@
use super::*;
use anyhow::Result;
-use spin_config::{
- ApplicationInformation, Configuration, CoreComponent, ModuleSource, RedisConfig, RedisExecutor,
- SpinVersion, TriggerConfig,
-};
+use spin_config::{RedisConfig, RedisExecutor};
+use spin_testing::TestConfig;
use std::sync::Once;
static LOGGER: Once = Once::new();
-const RUST_ENTRYPOINT_PATH: &str = "../../target/test-programs/redis-rust.wasm";
-
/// We can only initialize the tracing subscriber once per crate.
pub(crate) fn init() {
LOGGER.call_once(|| {
@@ -19,42 +15,20 @@ pub(crate) fn init() {
});
}
-fn fake_file_origin() -> spin_config::ApplicationOrigin {
- let dir = env!("CARGO_MANIFEST_DIR");
- let fake_path = std::path::PathBuf::from(dir).join("fake_spin.toml");
- spin_config::ApplicationOrigin::File(fake_path)
-}
-
#[tokio::test]
#[allow(unused)]
async fn test_pubsub() -> Result<()> {
init();
- let info = ApplicationInformation {
- spin_version: SpinVersion::V1,
- name: "test-redis".to_string(),
- version: "0.1.0".to_string(),
- description: None,
- authors: vec![],
- trigger: spin_config::ApplicationTrigger::Redis(spin_config::RedisTriggerConfiguration {
- address: "redis://localhost:6379".to_owned(),
- }),
- namespace: None,
- origin: fake_file_origin(),
- };
-
- let components = vec![CoreComponent {
- source: ModuleSource::FileReference(RUST_ENTRYPOINT_PATH.into()),
- id: "test".to_string(),
- trigger: TriggerConfig::Redis(RedisConfig {
+ let cfg = TestConfig::default()
+ .test_program("redis-rust.wasm")
+ .redis_trigger(RedisConfig {
channel: "messages".to_string(),
executor: Some(RedisExecutor::Spin),
- }),
- wasm: spin_config::WasmConfig::default(),
- }];
+ })
+ .build_configuration();
- let app = Configuration::<CoreComponent> { info, components };
- let trigger = RedisTrigger::new(app, None, None).await?;
+ let trigger = RedisTrigger::new(cfg, None, None).await?;
// TODO
// use redis::{FromRedisValue, Msg, Value};
diff --git a/crates/testing/Cargo.toml b/crates/testing/Cargo.toml
new file mode 100644
index 0000000000..6393690161
--- /dev/null
+++ b/crates/testing/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+name = "spin-testing"
+version = "0.1.0"
+edition = "2021"
+authors = ["Fermyon Engineering <engineering@fermyon.com>"]
+
+[dependencies]
+anyhow = "1.0"
+http = "0.2"
+hyper = "0.14"
+spin-config = { path = "../config" }
+spin-http-engine = { path = "../http" }
diff --git a/crates/testing/src/lib.rs b/crates/testing/src/lib.rs
new file mode 100644
index 0000000000..eacf0d3e3e
--- /dev/null
+++ b/crates/testing/src/lib.rs
@@ -0,0 +1,115 @@
+//! This crates contains common code for use in tests. Many methods will panic
+//! in the slightest breeze, so DO NOT USE IN NON-TEST CODE.
+
+use std::{
+ net::SocketAddr,
+ path::{Path, PathBuf},
+};
+
+use http::{Request, Response};
+use hyper::Body;
+use spin_config::{
+ ApplicationInformation, ApplicationOrigin, ApplicationTrigger, Configuration, CoreComponent,
+ HttpConfig, ModuleSource, RedisConfig, RedisTriggerConfiguration, SpinVersion, TriggerConfig,
+};
+use spin_http_engine::HttpTrigger;
+
+#[derive(Default)]
+pub struct TestConfig {
+ module_path: Option<PathBuf>,
+ application_trigger: Option<ApplicationTrigger>,
+ trigger_config: Option<TriggerConfig>,
+}
+
+impl TestConfig {
+ pub fn module_path(&mut self, path: impl Into<PathBuf>) -> &mut Self {
+ self.module_path = Some(path.into());
+ self
+ }
+
+ pub fn test_program(&mut self, name: impl AsRef<Path>) -> &mut Self {
+ self.module_path(
+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+ .join("../../target/test-programs")
+ .join(name),
+ )
+ }
+
+ pub fn http_trigger(&mut self, config: HttpConfig) -> &mut Self {
+ self.application_trigger = Some(ApplicationTrigger::Http(Default::default()));
+ self.trigger_config = Some(TriggerConfig::Http(config));
+ self
+ }
+
+ pub fn redis_trigger(&mut self, config: RedisConfig) -> &mut Self {
+ self.application_trigger = Some(ApplicationTrigger::Redis(RedisTriggerConfiguration {
+ address: "redis://localhost:6379".to_owned(),
+ }));
+ self.trigger_config = Some(TriggerConfig::Redis(config));
+ self
+ }
+
+ pub fn build_application_information(&self) -> ApplicationInformation {
+ ApplicationInformation {
+ spin_version: SpinVersion::V1,
+ name: "test-app".to_string(),
+ version: "1.0.0".to_string(),
+ description: None,
+ authors: vec![],
+ trigger: self
+ .application_trigger
+ .clone()
+ .expect("http_trigger or redis_trigger required"),
+ namespace: None,
+ origin: ApplicationOrigin::File(
+ PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("fake_spin.toml"),
+ ),
+ }
+ }
+
+ pub fn build_component(&self) -> CoreComponent {
+ let module_path = self
+ .module_path
+ .clone()
+ .expect("module_path or test_program required");
+ CoreComponent {
+ source: ModuleSource::FileReference(module_path),
+ id: "test-component".to_string(),
+ trigger: self
+ .trigger_config
+ .clone()
+ .expect("http_trigger or redis_trigger required"),
+ wasm: Default::default(),
+ }
+ }
+
+ pub fn build_configuration(&self) -> Configuration<CoreComponent> {
+ Configuration {
+ info: self.build_application_information(),
+ components: vec![self.build_component()],
+ }
+ }
+
+ pub async fn build_http_trigger(&self) -> HttpTrigger {
+ HttpTrigger::new("".to_string(), self.build_configuration(), None, None, None)
+ .await
+ .expect("failed to build HttpTrigger")
+ }
+
+ pub async fn handle_http_request(&self, req: Request<Body>) -> anyhow::Result<Response<Body>> {
+ self.build_http_trigger()
+ .await
+ .handle(req, test_socket_addr())
+ .await
+ }
+}
+
+pub fn test_socket_addr() -> SocketAddr {
+ "127.0.0.1:55555".parse().unwrap()
+}
+
+pub fn assert_http_response_success(resp: &Response<Body>) {
+ if !resp.status().is_success() {
+ panic!("non-success response {}: {:?}", resp.status(), resp.body());
+ }
+}
|
95f9da2a41aded597a437ad041a5a13ab19604ee
|
|
3a4b61a2c29cf351a42525f4296f207bcbfa086f
|
Error in static assets logic on Windows
When building `spin` on Windows, I'm running into an error regarding the path of static assets files:
```
PS C:\Users\jdboh\OneDrive\Documents\Fermyon\spin\docs> spin up --file spin.toml
Error: Failed to prepare configuration
Caused by:
0: Failed to collect file mounts for static/
1: Cannot place /: guest paths must be absolute
```
|
cc @itowlson
Can you share the `spin.toml` file please?
I think James was testing with the docs website in `docs/spin.toml`.
> I think James was testing with the docs website in `docs/spin.toml`.
This is correct
Mystic Ivan predicts all
```
// TODO: check if this works if the host is Windows
```
|
2022-03-22T21:47:04Z
|
fermyon__spin-211
|
fermyon/spin
|
0.1
|
diff --git a/crates/loader/src/local/assets.rs b/crates/loader/src/local/assets.rs
index 0294e888af..2b222de8ef 100644
--- a/crates/loader/src/local/assets.rs
+++ b/crates/loader/src/local/assets.rs
@@ -112,10 +112,9 @@ fn collect_placement(
source.display()
);
}
- // TODO: check if this works if the host is Windows
- if !guest_path.is_absolute() {
+ if !is_absolute_guest_path(guest_path) {
bail!(
- "Cannot place {}: guest paths must be absolute",
+ "Cannot place at {}: guest paths must be absolute",
guest_path.display()
);
}
@@ -236,3 +235,14 @@ fn as_placement(fm: &RawFileMount) -> Option<RawDirectoryPlacement> {
_ => None,
}
}
+
+fn is_absolute_guest_path(path: impl AsRef<Path>) -> bool {
+ // We can't use `is_absolute` to check that guest paths are absolute,
+ // because that would use the logic of the host filesystem. If the
+ // host is Windows, that would mean a path like `/assets` would not
+ // be considered absolute, and a path like `e:\assets` would be. But
+ // the Wasmtime preopened directory interface only works - as far as I
+ // can tell - with Unix-style guest paths. So we have to check these
+ // paths specifically using Unix logic rather than the system function.
+ path.as_ref().to_string_lossy().starts_with('/')
+}
| 211
|
[
"204"
] |
diff --git a/tests/http/simple-spin-rust/assets/test.txt b/tests/http/simple-spin-rust/assets/test.txt
new file mode 100644
index 0000000000..56ff8c93da
--- /dev/null
+++ b/tests/http/simple-spin-rust/assets/test.txt
@@ -0,0 +1,1 @@
+text for test
\ No newline at end of file
diff --git a/tests/http/simple-spin-rust/spin.toml b/tests/http/simple-spin-rust/spin.toml
index c022cdebea..9f7600d3cd 100644
--- a/tests/http/simple-spin-rust/spin.toml
+++ b/tests/http/simple-spin-rust/spin.toml
@@ -8,5 +8,6 @@ version = "1.0.0"
[[component]]
id = "hello"
source = "target/wasm32-wasi/release/spinhelloworld.wasm"
+files = [ { source = "assets", destination = "/" } ]
[component.trigger]
route = "/hello/..."
diff --git a/tests/http/simple-spin-rust/src/lib.rs b/tests/http/simple-spin-rust/src/lib.rs
index 691e66df4a..645b5e3d72 100644
--- a/tests/http/simple-spin-rust/src/lib.rs
+++ b/tests/http/simple-spin-rust/src/lib.rs
@@ -7,11 +7,30 @@ wit_bindgen_rust::export!("spin-http.wit");
struct SpinHttp {}
impl spin_http::SpinHttp for SpinHttp {
// Implement the `handler` entrypoint for Spin HTTP components.
- fn handle_http_request(_req: Request) -> Response {
- Response {
- status: 200,
- headers: None,
- body: Some("I'm a teapot".as_bytes().to_vec()),
+ fn handle_http_request(req: Request) -> Response {
+ let path = req.uri;
+
+ if path.contains("test-placement") {
+ match std::fs::read_to_string("/test.txt") {
+ Ok(text) =>
+ Response {
+ status: 200,
+ headers: None,
+ body: Some(text.as_bytes().to_vec()),
+ },
+ Err(e) =>
+ Response {
+ status: 500,
+ headers: None,
+ body: Some(format!("ERROR! {:?}", e).as_bytes().to_vec()),
+ },
+ }
+ } else {
+ Response {
+ status: 200,
+ headers: None,
+ body: Some("I'm a teapot".as_bytes().to_vec()),
+ }
}
}
}
diff --git a/tests/integration.rs b/tests/integration.rs
index ffa942bf17..a58b2b5eef 100644
--- a/tests/integration.rs
+++ b/tests/integration.rs
@@ -43,6 +43,7 @@ mod integration_tests {
assert_status(&s, "/test/hello", 200).await?;
assert_status(&s, "/test/hello/wildcards/should/be/handled", 200).await?;
assert_status(&s, "/thisshouldfail", 404).await?;
+ assert_status(&s, "/test/hello/test-placement", 200).await?;
Ok(())
}
|
95f9da2a41aded597a437ad041a5a13ab19604ee
|
6ec44284e6e933b536a7461740844d428f3d69cf
|
Camel case vs. snake case for TOML configuration
The current `spin.toml` file format expects multi-word identifiers to be camel case, which, as far as I can tell, is not that common for TOML files.
Should we update all identifiers in TOML configuration files to be snake case instead?
|
While I really don't have much of an opinion, what tilted me in favor of snake_case in Bindle was the TOML spec, which uses snake_case. https://toml.io/en/v1.0.0#array
I figure that as long as we're consistent, though, it probably doesn't matter much.
+1 for snake
If we're going to change it we should do so soon because I don't think serde allows parallel running, so it's a very breaking change!
(My vote is firmly in the "don't care as long as we're consistent" camp.)
|
2022-03-10T12:08:41Z
|
fermyon__spin-157
|
fermyon/spin
|
0.1
|
diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs
index 1d58db56de..486e2b95ad 100644
--- a/crates/config/src/lib.rs
+++ b/crates/config/src/lib.rs
@@ -18,11 +18,18 @@ pub struct Configuration<T> {
pub components: Vec<T>,
}
+/// Spin API version.
+#[derive(Copy, Clone, Debug, Eq, PartialEq)]
+pub enum SpinVersion {
+ /// Version 1 format.
+ V1,
+}
+
/// General application information.
#[derive(Clone, Debug)]
pub struct ApplicationInformation {
/// Spin API version.
- pub api_version: String,
+ pub spin_version: SpinVersion,
/// Name of the application.
pub name: String,
/// Version of the application.
diff --git a/crates/http/src/lib.rs b/crates/http/src/lib.rs
index 2fb2d00e1d..412db79dac 100644
--- a/crates/http/src/lib.rs
+++ b/crates/http/src/lib.rs
@@ -521,7 +521,7 @@ mod tests {
init();
let info = ApplicationInformation {
- api_version: "0.1.0".to_string(),
+ spin_version: spin_config::SpinVersion::V1,
name: "test-app".to_string(),
version: "1.0.0".to_string(),
description: None,
@@ -578,7 +578,7 @@ mod tests {
init();
let info = ApplicationInformation {
- api_version: "0.1.0".to_string(),
+ spin_version: spin_config::SpinVersion::V1,
name: "test-app".to_string(),
version: "1.0.0".to_string(),
description: None,
diff --git a/crates/loader/src/bindle/mod.rs b/crates/loader/src/bindle/mod.rs
index 3252456c95..845ffcdd5e 100644
--- a/crates/loader/src/bindle/mod.rs
+++ b/crates/loader/src/bindle/mod.rs
@@ -21,7 +21,7 @@ use bindle::{
use futures::future;
use spin_config::{
ApplicationInformation, ApplicationOrigin, Configuration, CoreComponent, ModuleSource,
- WasmConfig,
+ SpinVersion, WasmConfig,
};
use std::path::Path;
use tracing::log;
@@ -129,7 +129,7 @@ fn info(raw: &RawAppManifest, invoice: &Invoice, url: &str) -> ApplicationInform
ApplicationInformation {
// TODO
// Handle API version and namespace.
- api_version: "0.1.0".to_string(),
+ spin_version: SpinVersion::V1,
name: invoice.bindle.id.name().to_string(),
version: invoice.bindle.id.version_string(),
description: invoice.bindle.description.clone(),
diff --git a/crates/loader/src/local/config.rs b/crates/loader/src/local/config.rs
index 90ec6a3e91..d1065b62a6 100644
--- a/crates/loader/src/local/config.rs
+++ b/crates/loader/src/local/config.rs
@@ -10,17 +10,17 @@ use std::{collections::HashMap, path::PathBuf};
/// Container for any version of the manifest.
#[derive(Clone, Debug, Deserialize, Serialize)]
-#[serde(tag = "apiVersion")]
+#[serde(tag = "spin_version")]
pub enum RawAppManifestAnyVersion {
- /// A manifest with API version 0.1.0.
- #[serde(rename = "0.1.0")]
- V0_1_0(RawAppManifest),
+ /// A manifest with API version 1.
+ #[serde(rename = "1")]
+ V1(RawAppManifest),
}
/// Application configuration local file format.
/// This is the main structure spin.toml deserializes into.
#[derive(Clone, Debug, Deserialize, Serialize)]
-#[serde(deny_unknown_fields, rename_all = "camelCase")]
+#[serde(deny_unknown_fields, rename_all = "snake_case")]
pub struct RawAppManifest {
/// General application information.
#[serde(flatten)]
@@ -33,7 +33,7 @@ pub struct RawAppManifest {
/// General application information.
#[derive(Clone, Debug, Deserialize, Serialize)]
-#[serde(deny_unknown_fields, rename_all = "camelCase")]
+#[serde(deny_unknown_fields, rename_all = "snake_case")]
pub struct RawAppInformation {
/// Name of the application.
pub name: String,
@@ -51,7 +51,7 @@ pub struct RawAppInformation {
/// Core component configuration.
#[derive(Clone, Debug, Deserialize, Serialize)]
-#[serde(deny_unknown_fields, rename_all = "camelCase")]
+#[serde(deny_unknown_fields, rename_all = "snake_case")]
pub struct RawComponentManifest {
/// The module source.
pub source: RawModuleSource,
@@ -67,7 +67,7 @@ pub struct RawComponentManifest {
/// WebAssembly configuration.
#[derive(Clone, Debug, Deserialize, Serialize)]
-#[serde(deny_unknown_fields, rename_all = "camelCase")]
+#[serde(deny_unknown_fields, rename_all = "snake_case")]
pub struct RawWasmConfig {
/// Environment variables to be mapped inside the Wasm module at runtime.
pub environment: Option<HashMap<String, String>>,
@@ -84,7 +84,7 @@ pub struct RawWasmConfig {
/// An entry in the `files` list mapping a source path to an absolute
/// mount path in the guest.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
-#[serde(deny_unknown_fields, rename_all = "camelCase")]
+#[serde(deny_unknown_fields, rename_all = "snake_case")]
pub struct RawDirectoryPlacement {
/// The source to mount.
pub source: PathBuf,
@@ -95,7 +95,7 @@ pub struct RawDirectoryPlacement {
/// A specification for a file or set of files to mount in the
/// Wasm module.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
-#[serde(deny_unknown_fields, rename_all = "camelCase", untagged)]
+#[serde(deny_unknown_fields, rename_all = "snake_case", untagged)]
pub enum RawFileMount {
/// Mount a specified directory at a specified location.
Placement(RawDirectoryPlacement),
@@ -105,7 +105,7 @@ pub enum RawFileMount {
/// Source for the module.
#[derive(Clone, Debug, Deserialize, Serialize)]
-#[serde(deny_unknown_fields, rename_all = "camelCase", untagged)]
+#[serde(deny_unknown_fields, rename_all = "snake_case", untagged)]
pub enum RawModuleSource {
/// Local path or parcel reference to a module that needs to be linked.
FileReference(PathBuf),
@@ -118,7 +118,7 @@ pub enum RawModuleSource {
/// The component and its entrypoint should be pulled from Bindle.
/// This assumes access to the Bindle server.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
-#[serde(deny_unknown_fields, rename_all = "camelCase")]
+#[serde(deny_unknown_fields, rename_all = "snake_case")]
pub struct FileComponentBindleSource {
/// Reference to the bindle (name/version)
pub reference: String,
diff --git a/crates/loader/src/local/mod.rs b/crates/loader/src/local/mod.rs
index 83daca79e5..fcc848cf51 100644
--- a/crates/loader/src/local/mod.rs
+++ b/crates/loader/src/local/mod.rs
@@ -16,7 +16,7 @@ use futures::future;
use path_absolutize::Absolutize;
use spin_config::{
ApplicationInformation, ApplicationOrigin, Configuration, CoreComponent, ModuleSource,
- WasmConfig,
+ SpinVersion, WasmConfig,
};
use std::path::Path;
use tokio::{fs::File, io::AsyncReadExt};
@@ -59,7 +59,7 @@ async fn prepare_any_version(
base_dst: impl AsRef<Path>,
) -> Result<Configuration<CoreComponent>> {
match raw {
- RawAppManifestAnyVersion::V0_1_0(raw) => prepare(raw, src, base_dst).await,
+ RawAppManifestAnyVersion::V1(raw) => prepare(raw, src, base_dst).await,
}
}
@@ -134,7 +134,7 @@ async fn core(
/// Converts the raw application information from the spin.toml manifest to the standard configuration.
fn info(raw: RawAppInformation, src: impl AsRef<Path>) -> ApplicationInformation {
ApplicationInformation {
- api_version: "0.1.0".to_owned(),
+ spin_version: SpinVersion::V1,
name: raw.name,
version: raw.version,
description: raw.description,
diff --git a/crates/publish/src/expander.rs b/crates/publish/src/expander.rs
index a066480ade..000384a144 100644
--- a/crates/publish/src/expander.rs
+++ b/crates/publish/src/expander.rs
@@ -18,7 +18,7 @@ pub async fn expand_manifest(
.absolutize()
.context("Failed to resolve absolute path to manifest file")?;
let manifest = spin_loader::local::raw_manifest_from_file(&app_file).await?;
- let local_schema::RawAppManifestAnyVersion::V0_1_0(manifest) = manifest;
+ let local_schema::RawAppManifestAnyVersion::V1(manifest) = manifest;
let app_dir = app_dir(&app_file)?;
// * create a new spin.toml-like document where
diff --git a/docs/content/docs/configuration.md b/docs/content/docs/configuration.md
index 4abbee00a9..28a49e5488 100644
--- a/docs/content/docs/configuration.md
+++ b/docs/content/docs/configuration.md
@@ -5,7 +5,7 @@ least one _component_. In the example below we can see a simple HTTP application
with a single component executed when the `/hello` endpoint is accessed:
```toml
-apiVersion = "0.1.0"
+spin_version = "1"
name = "spin-hello-world"
description = "A simple application that returns hello world."
trigger = { type = "http", base = "/" }
@@ -22,7 +22,7 @@ route = "/hello"
The following are the fields supported by the `spin.toml` configuration file:
-- `apiVersion` (REQUIRED): Spin API version. Currently, this value MUST be
+- `spin_version` (REQUIRED): Spin API version. Currently, this value MUST be
`"0.1.0"`.
- `name` (REQUIRED): Name of the application.
- `version` (REQUIRED): Version of the application.
diff --git a/docs/content/docs/quickstart.md b/docs/content/docs/quickstart.md
index 58ac8b4a9f..3533aa86d8 100644
--- a/docs/content/docs/quickstart.md
+++ b/docs/content/docs/quickstart.md
@@ -56,7 +56,7 @@ Let's first look at the Rust example from the `examples/http-rust` directory.
Let's have a look at `spin.toml`:
```toml
-apiVersion = "0.1.0"
+spin_version = "1"
name = "spin-hello-world"
description = "A simple application that returns hello world."
trigger = { type = "http", base = "/" }
diff --git a/docs/content/docs/writing-http-apps.md b/docs/content/docs/writing-http-apps.md
index 819f9fa242..5a609d655d 100644
--- a/docs/content/docs/writing-http-apps.md
+++ b/docs/content/docs/writing-http-apps.md
@@ -102,7 +102,7 @@ configuration:
[[component]]
id = "hello"
source = "target/wasm32-wasi/release/spinhelloworld.wasm"
-allowedHttpHosts = [ "https://fermyon.com" ]
+allowed_http_hosts = [ "https://fermyon.com" ]
[component.trigger]
route = "/hello"
```
diff --git a/docs/spin.toml b/docs/spin.toml
index 127e7e55f1..69596291d8 100644
--- a/docs/spin.toml
+++ b/docs/spin.toml
@@ -1,5 +1,5 @@
name = "spin-docs"
-apiVersion = "0.1.0"
+spin_version = "1"
version = "0.1.0"
description = "The Spin documentation website running on... Spin."
authors = [ "Fermyon Engineering <engineering@fermyon.com>" ]
diff --git a/examples/http-rust/spin.toml b/examples/http-rust/spin.toml
index 8f8fc06cf6..6e041b0db6 100644
--- a/examples/http-rust/spin.toml
+++ b/examples/http-rust/spin.toml
@@ -1,4 +1,4 @@
-apiVersion = "0.1.0"
+spin_version = "1"
authors = ["Fermyon Engineering <engineering@fermyon.com>"]
description = "A simple application that returns hello."
name = "spin-hello-world"
diff --git a/examples/http-tinygo/spin.toml b/examples/http-tinygo/spin.toml
index a890aff39c..e2d5d4cab5 100644
--- a/examples/http-tinygo/spin.toml
+++ b/examples/http-tinygo/spin.toml
@@ -1,4 +1,4 @@
-apiVersion = "0.1.0"
+spin_version = "1"
authors = ["Fermyon Engineering <engineering@fermyon.com>"]
description = "A simple Spin application written in (Tiny)Go."
name = "spin-hello-world"
diff --git a/examples/wagi-http-rust/spin.toml b/examples/wagi-http-rust/spin.toml
index 95d86b82ac..f4b8919a81 100644
--- a/examples/wagi-http-rust/spin.toml
+++ b/examples/wagi-http-rust/spin.toml
@@ -1,4 +1,4 @@
-apiVersion = "0.1.0"
+spin_version = "1"
authors = ["Fermyon Engineering <engineering@fermyon.com>"]
description = "An application that returns the arguments the program started with, the environment variables set, and current time"
name = "wagi-hello-world"
diff --git a/sdk/rust/readme.md b/sdk/rust/readme.md
index d8dd41cc21..08d1913fe7 100644
--- a/sdk/rust/readme.md
+++ b/sdk/rust/readme.md
@@ -69,7 +69,7 @@ configuration:
[[component]]
id = "hello"
source = "target/wasm32-wasi/release/spinhelloworld.wasm"
-allowedHttpHosts = [ "https://fermyon.com" ]
+allowed_http_hosts = [ "https://fermyon.com" ]
[component.trigger]
route = "/hello"
```
| 157
|
[
"132"
] |
diff --git a/crates/loader/src/local/tests.rs b/crates/loader/src/local/tests.rs
index 2d3c1d3bc8..200d897b25 100644
--- a/crates/loader/src/local/tests.rs
+++ b/crates/loader/src/local/tests.rs
@@ -15,7 +15,7 @@ async fn test_from_local_source() -> Result<()> {
assert_eq!(cfg.info.name, "spin-local-source-test");
assert_eq!(cfg.info.version, "1.0.0");
- assert_eq!(cfg.info.api_version, "0.1.0");
+ assert_eq!(cfg.info.spin_version, SpinVersion::V1);
assert_eq!(
cfg.info.authors[0],
"Fermyon Engineering <engineering@fermyon.com>"
@@ -42,7 +42,7 @@ fn test_manifest() -> Result<()> {
const MANIFEST: &str = include_str!("../../tests/valid-manifest.toml");
let cfg_any: RawAppManifestAnyVersion = toml::from_str(MANIFEST)?;
- let RawAppManifestAnyVersion::V0_1_0(cfg) = cfg_any;
+ let RawAppManifestAnyVersion::V1(cfg) = cfg_any;
assert_eq!(cfg.info.name, "chain-of-command");
assert_eq!(cfg.info.version, "6.11.2");
@@ -105,8 +105,8 @@ fn test_unknown_version_is_rejected() {
let e = cfg.unwrap_err().to_string();
assert!(
- e.contains("apiVersion"),
- "Expected error to mention `apiVersion`"
+ e.contains("spin_version"),
+ "Expected error to mention `spin_version`"
);
}
@@ -118,7 +118,7 @@ fn test_wagi_executor_with_custom_entrypoint() -> Result<()> {
const EXPECTED_DEFAULT_ARGV: &str = "${SCRIPT_NAME} ${ARGS}";
let cfg_any: RawAppManifestAnyVersion = toml::from_str(MANIFEST)?;
- let RawAppManifestAnyVersion::V0_1_0(cfg) = cfg_any;
+ let RawAppManifestAnyVersion::V1(cfg) = cfg_any;
let TriggerConfig::Http(http_config) = &cfg.components[0].trigger;
diff --git a/crates/loader/tests/invalid-version.toml b/crates/loader/tests/invalid-version.toml
index dce9009bc6..502f9b492c 100644
--- a/crates/loader/tests/invalid-version.toml
+++ b/crates/loader/tests/invalid-version.toml
@@ -1,4 +1,4 @@
-apiVersion = "77.301.12"
+spin_version = "77.301.12"
authors = ["Gul Madred", "Edward Jellico", "JL"]
description = "Because if we get to API version 77.301.12 then we have bigger problems"
name = "chain-of-command"
diff --git a/crates/loader/tests/valid-manifest.toml b/crates/loader/tests/valid-manifest.toml
index c4c3b387f0..d6cf5cac6e 100644
--- a/crates/loader/tests/valid-manifest.toml
+++ b/crates/loader/tests/valid-manifest.toml
@@ -1,4 +1,4 @@
-apiVersion = "0.1.0"
+spin_version = "1"
authors = ["Gul Madred", "Edward Jellico", "JL"]
description = "A simple application that returns the number of lights"
name = "chain-of-command"
diff --git a/crates/loader/tests/valid-with-files/spin.toml b/crates/loader/tests/valid-with-files/spin.toml
index 7cda92e376..5524ff0ae2 100644
--- a/crates/loader/tests/valid-with-files/spin.toml
+++ b/crates/loader/tests/valid-with-files/spin.toml
@@ -1,4 +1,4 @@
-apiVersion = "0.1.0"
+spin_version = "1"
authors = ["Fermyon Engineering <engineering@fermyon.com>"]
name = "spin-local-source-test"
trigger = {type = "http", base = "/"}
diff --git a/crates/loader/tests/wagi-custom-entrypoint.toml b/crates/loader/tests/wagi-custom-entrypoint.toml
index 4cf2bc6f7d..1e44fbf57e 100644
--- a/crates/loader/tests/wagi-custom-entrypoint.toml
+++ b/crates/loader/tests/wagi-custom-entrypoint.toml
@@ -1,5 +1,5 @@
name = "spin-wagi-custom-entrypoint"
-apiVersion = "0.1.0"
+spin_version = "1"
version = "1.0.0"
authors = [ "Fermyon Engineering <engineering@fermyon.com>" ]
trigger = { type = "http", base = "/" }
diff --git a/tests/http/assets-test/spin.toml b/tests/http/assets-test/spin.toml
index 8b6b94beb7..474a2b624c 100644
--- a/tests/http/assets-test/spin.toml
+++ b/tests/http/assets-test/spin.toml
@@ -1,4 +1,4 @@
-apiVersion = "0.1.0"
+spin_version = "1"
authors = ["Fermyon Engineering <engineering@fermyon.com>"]
name = "spin-assets-test"
trigger = {type = "http", base = "/"}
diff --git a/tests/http/headers-env-routes-test/spin.toml b/tests/http/headers-env-routes-test/spin.toml
index d1959a9370..e2775c70c6 100644
--- a/tests/http/headers-env-routes-test/spin.toml
+++ b/tests/http/headers-env-routes-test/spin.toml
@@ -1,4 +1,4 @@
-apiVersion = "0.1.0"
+spin_version = "1"
name = "spin-headers-env-routes-test"
version = "1.0.0"
authors = ["Fermyon Engineering <engineering@fermyon.com>"]
diff --git a/tests/http/simple-spin-rust/spin.toml b/tests/http/simple-spin-rust/spin.toml
index 13cbfe0ace..c022cdebea 100644
--- a/tests/http/simple-spin-rust/spin.toml
+++ b/tests/http/simple-spin-rust/spin.toml
@@ -1,4 +1,4 @@
-apiVersion = "0.1.0"
+spin_version = "1"
authors = ["Fermyon Engineering <engineering@fermyon.com>"]
description = "A simple application that returns hello and goodbye."
name = "spin-hello-world"
|
95f9da2a41aded597a437ad041a5a13ab19604ee
|
56203d9d83f833ee9472c552be6b9610554a20a0
|
Implement Redis trigger
There is a very early skeleton for a Redis trigger (https://github.com/fermyon/spin/tree/main/crates/redis) that we should update to be usable using the new application configuration.
|
2022-03-10T00:01:58Z
|
fermyon__spin-155
|
fermyon/spin
|
0.1
|
diff --git a/Cargo.lock b/Cargo.lock
index 9133e8c851..68cf59f7c7 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -23,7 +23,7 @@ version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fcb51a0695d8f838b1ee009b3fbf66bda078cd64590202a864a8f3e8c4315c47"
dependencies = [
- "getrandom 0.2.4",
+ "getrandom 0.2.5",
"once_cell",
"version_check 0.9.4",
]
@@ -54,9 +54,9 @@ dependencies = [
[[package]]
name = "anyhow"
-version = "1.0.53"
+version = "1.0.56"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "94a45b455c14666b85fc40a019e8ab9eb75e3a124e05494f5397122bc9eb06e0"
+checksum = "4361135be9122e0870de935d7c439aef945b9f9ddd4199a553b5270b49c82a27"
[[package]]
name = "async-compression"
@@ -158,7 +158,7 @@ checksum = "f691e63585950d8c1c43644d11bab9073e40f5060dd2822734ae7c3dc69a3a80"
dependencies = [
"base64 0.13.0",
"blowfish",
- "getrandom 0.2.4",
+ "getrandom 0.2.5",
]
[[package]]
@@ -200,7 +200,7 @@ dependencies = [
"serde",
"serde_cbor",
"serde_json",
- "sha2 0.10.1",
+ "sha2 0.10.2",
"sled",
"tempfile",
"thiserror",
@@ -423,11 +423,25 @@ dependencies = [
"vec_map",
]
+[[package]]
+name = "combine"
+version = "4.6.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "50b727aacc797f9fc28e355d21f34709ac4fc9adecfe470ad07b8f4464f53062"
+dependencies = [
+ "bytes 1.1.0",
+ "futures-core",
+ "memchr",
+ "pin-project-lite",
+ "tokio",
+ "tokio-util",
+]
+
[[package]]
name = "comfy-table"
-version = "5.0.0"
+version = "5.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c42350b81f044f576ff88ac750419f914abb46a03831bb1747134344ee7a4e64"
+checksum = "b103d85ca6e209388771bfb7aa6b68a7aeec4afbf6f0a0264bfbf50360e5212e"
dependencies = [
"crossterm",
"strum",
@@ -613,15 +627,15 @@ dependencies = [
[[package]]
name = "crossterm"
-version = "0.22.1"
+version = "0.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c85525306c4291d1b73ce93c8acf9c339f9b213aef6c1d85c3830cbf1c16325c"
+checksum = "77b75a27dc8d220f1f8521ea69cd55a34d720a200ebb3a624d9aa19193d3b432"
dependencies = [
"bitflags",
"crossterm_winapi",
"libc",
"mio 0.7.14",
- "parking_lot 0.11.2",
+ "parking_lot 0.12.0",
"signal-hook",
"signal-hook-mio",
"winapi",
@@ -765,6 +779,12 @@ dependencies = [
"serde_json",
]
+[[package]]
+name = "dtoa"
+version = "0.4.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "56899898ce76aaf4a0f24d914c97ea6ed976d42fec6ad33fcbb0a1103e07b2b0"
+
[[package]]
name = "dunce"
version = "1.0.2"
@@ -773,9 +793,9 @@ checksum = "453440c271cf5577fd2a40e4942540cb7d0d2f85e27c8d07dd0023c925a67541"
[[package]]
name = "ed25519"
-version = "1.3.0"
+version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "74e1069e39f1454367eb2de793ed062fac4c35c2934b76a81d90dd9abcd28816"
+checksum = "eed12bbf7b5312f8da1c2722bc06d8c6b12c2d86a7fb35a194c7f3e6fc2bbe39"
dependencies = [
"signature",
]
@@ -1080,9 +1100,9 @@ dependencies = [
[[package]]
name = "getrandom"
-version = "0.2.4"
+version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "418d37c8b1d42553c93648be529cb70f920d3baf8ef469b74b9638df426e0b4c"
+checksum = "d39cd93900197114fa1fcb7ae84ca742095eed9442088988ae74fa744e930e77"
dependencies = [
"cfg-if",
"js-sys",
@@ -1299,7 +1319,7 @@ dependencies = [
"http 0.2.6",
"hyper",
"log",
- "rustls 0.20.3",
+ "rustls 0.20.4",
"rustls-native-certs",
"tokio",
"tokio-rustls 0.23.2",
@@ -1421,9 +1441,9 @@ dependencies = [
[[package]]
name = "ipnet"
-version = "2.3.1"
+version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "68f2d64f2edebec4ce84ad108148e67e1064789bee435edc5b60ad398714a3a9"
+checksum = "35e70ee094dc02fd9c13fdad4940090f22dbd6ac7c9e7094a46cf0232a50bc7c"
[[package]]
name = "is-terminal"
@@ -1510,9 +1530,9 @@ checksum = "884e2677b40cc8c339eaefcb701c32ef1fd2493d71118dc0ca4b6a736c93bd67"
[[package]]
name = "libc"
-version = "0.2.118"
+version = "0.2.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "06e509672465a0504304aa87f9f176f2b2b716ed8fb105ebe5c02dc6dce96a94"
+checksum = "1bf2e165bb3457c8e098ea76f3e3bc9db55f87aa90d52d0e6be741470916aaa4"
[[package]]
name = "libgit2-sys"
@@ -1544,9 +1564,9 @@ dependencies = [
[[package]]
name = "libz-sys"
-version = "1.1.3"
+version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "de5435b8549c16d423ed0c03dbaafe57cf6c3344744f1242520d59c9d8ecec66"
+checksum = "6f35facd4a5673cb5a48822be2be1d4236c1c99cb4113cab7061ac720d5bf859"
dependencies = [
"cc",
"libc",
@@ -1556,9 +1576,9 @@ dependencies = [
[[package]]
name = "linux-raw-sys"
-version = "0.0.40"
+version = "0.0.42"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5bdc16c6ce4c85d9b46b4e66f2a814be5b3f034dbd5131c268a24ca26d970db8"
+checksum = "5284f00d480e1c39af34e72f8ad60b94f47007e3481cd3b731c1d67190ddc7b7"
[[package]]
name = "lock_api"
@@ -1580,9 +1600,9 @@ dependencies = [
[[package]]
name = "lru"
-version = "0.7.2"
+version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "274353858935c992b13c0ca408752e2121da852d07dec7ce5f108c77dfa14d1f"
+checksum = "fcb87f3080f6d1d69e8c564c0fcfde1d7aa8cc451ce40cae89479111f03bc0eb"
dependencies = [
"hashbrown 0.11.2",
]
@@ -1659,9 +1679,9 @@ dependencies = [
[[package]]
name = "mini-internal"
-version = "0.1.22"
+version = "0.1.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f33afa7f6ca9045791ac23797bf517c9c881c65ba9d8bf83df0e33385050d312"
+checksum = "68a9cec2df85e49afd5bd4c4afb21678e2177736ebe31e4b8836b821ffd806bd"
dependencies = [
"proc-macro2",
"quote",
@@ -1670,9 +1690,9 @@ dependencies = [
[[package]]
name = "miniserde"
-version = "0.1.22"
+version = "0.1.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "80f4a832d68a3f48c31237c73be79574b40884b50b86368f70d7332252f0c2e0"
+checksum = "6b4f376d897db27bdf4e318542322eca8fd41839cc56a12cc8f8d8a05b4386af"
dependencies = [
"itoa 1.0.1",
"mini-internal",
@@ -1902,7 +1922,7 @@ checksum = "80e47cfc4c0a1a519d9a025ebfbac3a2439d1b5cdf397d72dcb79b11d9920dab"
dependencies = [
"base64 0.13.0",
"chrono",
- "getrandom 0.2.4",
+ "getrandom 0.2.5",
"http 0.2.6",
"rand 0.8.5",
"reqwest",
@@ -1947,9 +1967,9 @@ dependencies = [
[[package]]
name = "once_cell"
-version = "1.9.0"
+version = "1.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "da32515d9f6e6e489d7bc9d84c71b060db7247dc035bbe44eac88cf87486d8d5"
+checksum = "87f3e037eac156d1775da914196f0f37741a274155e34a0b7e427c35d2a2ecb9"
[[package]]
name = "opaque-debug"
@@ -2281,7 +2301,7 @@ version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d34f1408f55294453790c48b2f1ebbb1c5b4b7563eb1f418bcfcfdbb06ebb4e7"
dependencies = [
- "getrandom 0.2.4",
+ "getrandom 0.2.5",
]
[[package]]
@@ -2318,11 +2338,31 @@ dependencies = [
"num_cpus",
]
+[[package]]
+name = "redis"
+version = "0.21.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1a80b5f38d7f5a020856a0e16e40a9cfabf88ae8f0e4c2dcd8a3114c1e470852"
+dependencies = [
+ "async-trait",
+ "bytes 1.1.0",
+ "combine",
+ "dtoa",
+ "futures-util",
+ "itoa 0.4.8",
+ "percent-encoding 2.1.0",
+ "pin-project-lite",
+ "sha1",
+ "tokio",
+ "tokio-util",
+ "url 2.2.2",
+]
+
[[package]]
name = "redox_syscall"
-version = "0.2.10"
+version = "0.2.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8383f39639269cde97d255a32bdb68c047337295414940c68bdd30c2e13203ff"
+checksum = "8380fe0152551244f0747b1bf41737e0f8a74f97a14ccefd1148187271634f3c"
dependencies = [
"bitflags",
]
@@ -2333,7 +2373,7 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "528532f3d801c87aec9def2add9ca802fe569e44a544afe633765267840abe64"
dependencies = [
- "getrandom 0.2.4",
+ "getrandom 0.2.5",
"redox_syscall",
]
@@ -2420,7 +2460,7 @@ dependencies = [
"native-tls",
"percent-encoding 2.1.0",
"pin-project-lite",
- "rustls 0.20.3",
+ "rustls 0.20.4",
"rustls-pemfile 0.2.1",
"serde",
"serde_json",
@@ -2466,9 +2506,9 @@ checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"
[[package]]
name = "rustix"
-version = "0.33.2"
+version = "0.33.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "db890a96e64911e67fa84e58ce061a40a6a65c231e5fad20b190933f8991a27c"
+checksum = "a9466f25b92a648960ac1042fd3baa6b0bf285e60f754d7e5070770c813a177a"
dependencies = [
"bitflags",
"errno",
@@ -2495,9 +2535,9 @@ dependencies = [
[[package]]
name = "rustls"
-version = "0.20.3"
+version = "0.20.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b323592e3164322f5b193dc4302e4e36cd8d37158a712d664efae1a5c2791700"
+checksum = "4fbfeb8d0ddb84706bc597a5574ab8912817c52a397f819e5b614e2265206921"
dependencies = [
"log",
"ring",
@@ -2535,6 +2575,12 @@ dependencies = [
"base64 0.13.0",
]
+[[package]]
+name = "rustversion"
+version = "1.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2cc38e8fa666e2de3c4aba7edeb5ffc5246c1c2ed0e3d17e560aeeba736b23f"
+
[[package]]
name = "ryu"
version = "1.0.9"
@@ -2623,9 +2669,9 @@ dependencies = [
[[package]]
name = "semver"
-version = "1.0.5"
+version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0486718e92ec9a68fbed73bb5ef687d71103b142595b406835649bebd33f72c7"
+checksum = "a4a3381e03edd24287172047536f20cabde766e2cd3e65e6b00fb3af51c4f38d"
dependencies = [
"serde",
]
@@ -2717,6 +2763,21 @@ dependencies = [
"digest 0.10.3",
]
+[[package]]
+name = "sha1"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c1da05c97445caa12d05e848c4a4fcbbea29e748ac28f7e80e9b010392063770"
+dependencies = [
+ "sha1_smol",
+]
+
+[[package]]
+name = "sha1_smol"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae1a47186c03a32177042e55dbc5fd5aee900b8e0069a8d70fba96a9375cd012"
+
[[package]]
name = "sha2"
version = "0.9.9"
@@ -2732,9 +2793,9 @@ dependencies = [
[[package]]
name = "sha2"
-version = "0.10.1"
+version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "99c3bd8169c58782adad9290a9af5939994036b76187f7b4f0e6de91dbbfc0ec"
+checksum = "55deaec60f81eefe3cce0dc50bda92d6d8e88f2a27df7c5033b42afeb1ed2676"
dependencies = [
"cfg-if",
"cpufeatures",
@@ -2873,6 +2934,7 @@ dependencies = [
"spin-http-engine",
"spin-loader",
"spin-publish",
+ "spin-redis-engine",
"spin-templates",
"structopt",
"tempfile",
@@ -2880,7 +2942,7 @@ dependencies = [
"toml",
"tracing",
"tracing-futures",
- "tracing-subscriber 0.3.8",
+ "tracing-subscriber 0.3.9",
]
[[package]]
@@ -2936,7 +2998,7 @@ dependencies = [
"tokio-rustls 0.23.2",
"tracing",
"tracing-futures",
- "tracing-subscriber 0.3.8",
+ "tracing-subscriber 0.3.9",
"url 2.2.2",
"wagi",
"wasi-cap-std-sync",
@@ -2964,14 +3026,14 @@ dependencies = [
"regex",
"reqwest",
"serde",
- "sha2 0.10.1",
+ "sha2 0.10.2",
"spin-config",
"tempfile",
"tokio",
"toml",
"tracing",
"tracing-futures",
- "tracing-subscriber 0.3.8",
+ "tracing-subscriber 0.3.9",
"walkdir",
]
@@ -3003,13 +3065,36 @@ dependencies = [
"mime_guess",
"path-absolutize",
"serde",
- "sha2 0.10.1",
+ "sha2 0.10.2",
"spin-loader",
"tempfile",
"tokio",
"toml",
]
+[[package]]
+name = "spin-redis-engine"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "async-trait",
+ "env_logger",
+ "futures",
+ "log",
+ "redis",
+ "serde",
+ "spin-config",
+ "spin-engine",
+ "tokio",
+ "tracing",
+ "tracing-futures",
+ "tracing-subscriber 0.3.9",
+ "wasi-common",
+ "wasmtime",
+ "wasmtime-wasi",
+ "wit-bindgen-wasmtime",
+]
+
[[package]]
name = "spin-sdk"
version = "0.1.0"
@@ -3079,19 +3164,20 @@ dependencies = [
[[package]]
name = "strum"
-version = "0.22.0"
+version = "0.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f7ac893c7d471c8a21f31cfe213ec4f6d9afeed25537c772e08ef3f005f8729e"
+checksum = "cae14b91c7d11c9a851d3fbc80a963198998c2a64eec840477fa92d8ce9b70bb"
[[package]]
name = "strum_macros"
-version = "0.22.0"
+version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "339f799d8b549e3744c7ac7feb216383e4005d94bdb22561b3ab8f3b808ae9fb"
+checksum = "5bb0dc7ee9c15cea6199cde9a127fa16a4c5819af85395457ad72d68edc85a38"
dependencies = [
"heck",
"proc-macro2",
"quote",
+ "rustversion",
"syn",
]
@@ -3168,9 +3254,9 @@ dependencies = [
[[package]]
name = "termcolor"
-version = "1.1.2"
+version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2dfed899f0eb03f32ee8c6a0aabdb8a7949659e3466561fc0adf54e26d88c5f4"
+checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755"
dependencies = [
"winapi-util",
]
@@ -3331,7 +3417,7 @@ version = "0.23.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a27d5f2b839802bd8267fa19b0530f5a08b9c08cd417976be2a65d130fe1c11b"
dependencies = [
- "rustls 0.20.3",
+ "rustls 0.20.4",
"tokio",
"webpki 0.22.0",
]
@@ -3406,9 +3492,9 @@ checksum = "360dfd1d6d30e05fda32ace2c8c70e9c0a9da713275777f5a4dbb8a1893930c6"
[[package]]
name = "tracing"
-version = "0.1.30"
+version = "0.1.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2d8d93354fe2a8e50d5953f5ae2e47a3fc2ef03292e7ea46e3cc38f549525fb9"
+checksum = "f6c650a8ef0cd2dd93736f033d21cbd1224c5a967aa0c258d00fcf7dafef9b9f"
dependencies = [
"cfg-if",
"log",
@@ -3493,9 +3579,9 @@ dependencies = [
[[package]]
name = "tracing-subscriber"
-version = "0.3.8"
+version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "74786ce43333fcf51efe947aed9718fbe46d5c7328ec3f1029e818083966d9aa"
+checksum = "9e0ab7bdc962035a87fba73f3acca9b8a8d0034c2e6f60b84aeaaddddc155dce"
dependencies = [
"ansi_term",
"lazy_static",
@@ -4505,9 +4591,9 @@ dependencies = [
[[package]]
name = "zeroize_derive"
-version = "1.3.1"
+version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "81e8f13fef10b63c06356d65d416b070798ddabcadc10d3ece0c5be9b3c7eddb"
+checksum = "3f8f187641dad4f680d25c4bfc4225b418165984179f26ca76ec4fb6441d3a17"
dependencies = [
"proc-macro2",
"quote",
diff --git a/Cargo.toml b/Cargo.toml
index 9c9fbd6bbe..5cb9893aca 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -2,7 +2,7 @@
name = "spin-cli"
version = "0.1.0"
edition = "2021"
-authors = [ "Radu Matei <radu.matei@fermyon.com>" ]
+authors = [ "Fermyon Engineering <engineering@fermyon.com>" ]
[dependencies]
anyhow = "1.0"
@@ -22,6 +22,7 @@ spin-engine = { path = "crates/engine" }
spin-http-engine = { path = "crates/http" }
spin-loader = { path = "crates/loader" }
spin-publish = { path = "crates/publish" }
+spin-redis-engine = { path = "crates/redis" }
spin-templates = { path = "crates/templates" }
structopt = "0.3"
tempfile = "3.3.0"
@@ -35,7 +36,7 @@ tracing-subscriber = { version = "0.3.7", features = [ "env-filter" ] }
hyper = { version = "0.14", features = [ "full" ] }
[workspace]
-members = [ "crates/config", "crates/engine", "crates/http", "crates/loader", "crates/templates", "sdk/rust", "sdk/rust/macro" ]
+members = [ "crates/config", "crates/engine", "crates/http", "crates/loader", "crates/redis", "crates/templates", "sdk/rust", "sdk/rust/macro" ]
[[bin]]
name = "spin"
diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs
index 486e2b95ad..8d55878c64 100644
--- a/crates/config/src/lib.rs
+++ b/crates/config/src/lib.rs
@@ -85,6 +85,8 @@ pub enum ApplicationOrigin {
pub enum ApplicationTrigger {
/// HTTP trigger type.
Http(HttpTriggerConfiguration),
+ /// Redis trigger type.
+ Redis(RedisTriggerConfiguration),
}
/// HTTP trigger configuration.
@@ -99,6 +101,31 @@ impl Default for HttpTriggerConfiguration {
}
}
+/// Redis trigger configuration.
+#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
+pub struct RedisTriggerConfiguration {
+ /// Address of Redis server.
+ pub address: String,
+}
+
+impl ApplicationTrigger {
+ /// Returns the HttpTriggerConfiguration else None.
+ pub fn as_http(&self) -> Option<&HttpTriggerConfiguration> {
+ match self {
+ ApplicationTrigger::Http(http) => Some(http),
+ _ => None,
+ }
+ }
+
+ /// Returns the RedisTriggerConfiguration else None.
+ pub fn as_redis(&self) -> Option<&RedisTriggerConfiguration> {
+ match self {
+ ApplicationTrigger::Redis(redis) => Some(redis),
+ _ => None,
+ }
+ }
+}
+
/// WebAssembly configuration.
#[derive(Clone, Debug)]
pub struct WasmConfig {
@@ -213,12 +240,41 @@ impl Default for WagiConfig {
}
}
+/// Configuration for the Redis trigger.
+#[derive(Clone, Debug, Deserialize, Serialize)]
+pub struct RedisConfig {
+ /// Redis channel to subscribe.
+ pub channel: String,
+ /// The Redis executor the component requires.
+ pub executor: Option<RedisExecutor>,
+}
+
+/// The executor for the Redis component.
+///
+/// If an executor is not specified, the inferred default is `RedisExecutor::Spin`.
+#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
+#[serde(deny_unknown_fields, rename_all = "camelCase", tag = "type")]
+pub enum RedisExecutor {
+ /// The component implements the Spin Redis interface.
+ Spin,
+ /// The component implements the Wagi CGI interface.
+ Wagi(WagiConfig),
+}
+
+impl Default for RedisExecutor {
+ fn default() -> Self {
+ Self::Spin
+ }
+}
+
/// Trigger configuration.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase", untagged)]
pub enum TriggerConfig {
/// HTTP trigger configuration
Http(HttpConfig),
+ /// Redis trigger configuration
+ Redis(RedisConfig),
}
impl Default for TriggerConfig {
@@ -226,3 +282,20 @@ impl Default for TriggerConfig {
Self::Http(Default::default())
}
}
+
+impl TriggerConfig {
+ /// Returns the HttpConfig else None.
+ pub fn as_http(&self) -> Option<&HttpConfig> {
+ match self {
+ TriggerConfig::Http(http) => Some(http),
+ _ => None,
+ }
+ }
+ /// Returns the RedisConfig else None.
+ pub fn as_redis(&self) -> Option<&RedisConfig> {
+ match self {
+ TriggerConfig::Redis(redis) => Some(redis),
+ _ => None,
+ }
+ }
+}
diff --git a/crates/http/src/lib.rs b/crates/http/src/lib.rs
index 412db79dac..aae561a9b7 100644
--- a/crates/http/src/lib.rs
+++ b/crates/http/src/lib.rs
@@ -11,7 +11,7 @@ use crate::{
spin::SpinHttpExecutor,
wagi::WagiHttpExecutor,
};
-use anyhow::{Context, Error, Result};
+use anyhow::{anyhow, ensure, Context, Error, Result};
use async_trait::async_trait;
use futures_util::stream::StreamExt;
use http::{uri::Scheme, StatusCode, Uri};
@@ -21,7 +21,7 @@ use hyper::{
service::{make_service_fn, service_fn},
Body, Request, Response, Server,
};
-use spin_config::{ApplicationTrigger, Configuration, CoreComponent, TriggerConfig};
+use spin_config::{Configuration, CoreComponent};
use spin_engine::{Builder, ExecutionContextConfiguration};
use spin_http::SpinHttpData;
use std::{future::ready, net::SocketAddr, path::PathBuf, sync::Arc};
@@ -44,9 +44,9 @@ type RuntimeContext = spin_engine::RuntimeContext<SpinHttpData>;
#[derive(Clone)]
pub struct HttpTrigger {
/// Listening address for the server.
- pub address: String,
+ address: String,
/// Configuration for the application.
- pub app: Configuration<CoreComponent>,
+ app: Configuration<CoreComponent>,
/// TLS configuration for the server.
tls: Option<TlsConfig>,
/// Router.
@@ -64,6 +64,11 @@ impl HttpTrigger {
tls: Option<TlsConfig>,
log_dir: Option<PathBuf>,
) -> Result<Self> {
+ ensure!(
+ app.info.trigger.as_http().is_some(),
+ "Application trigger is not HTTP"
+ );
+
let mut config = ExecutionContextConfiguration::new(app.clone(), log_dir);
if let Some(wasmtime) = wasmtime {
config.wasmtime = wasmtime;
@@ -94,13 +99,16 @@ impl HttpTrigger {
req.uri()
);
- let ApplicationTrigger::Http(app_trigger) = &self.app.info.trigger.clone();
+ // We can unwrap here because the trigger type has already been asserted in `HttpTrigger::new`
+ let app_trigger = self.app.info.trigger.as_http().cloned().unwrap();
match req.uri().path() {
"/healthz" => Ok(Response::new(Body::from("OK"))),
route => match self.router.route(route) {
Ok(c) => {
- let TriggerConfig::Http(trigger) = &c.trigger;
+ let trigger = c.trigger.as_http().ok_or_else(|| {
+ anyhow!("Expected HTTP configuration for component {}", c.id)
+ })?;
let executor = match &trigger.executor {
Some(i) => i,
None => &spin_config::HttpExecutor::Spin,
diff --git a/crates/http/src/routes.rs b/crates/http/src/routes.rs
index 1f95394e28..99aeced18a 100644
--- a/crates/http/src/routes.rs
+++ b/crates/http/src/routes.rs
@@ -5,7 +5,7 @@
use anyhow::{bail, Result};
use http::Uri;
use indexmap::IndexMap;
-use spin_config::{ApplicationTrigger, Configuration, CoreComponent};
+use spin_config::{Configuration, CoreComponent};
use std::fmt::Debug;
use tracing::log;
@@ -29,12 +29,12 @@ pub(crate) struct Router {
impl Router {
/// Builds a router based on application configuration.
pub(crate) fn build(app: &Configuration<CoreComponent>) -> Result<Self> {
- let ApplicationTrigger::Http(app_trigger) = app.info.trigger.clone();
+ let app_trigger = app.info.trigger.as_http().unwrap().clone();
let routes = app
.components
.iter()
.map(|c| {
- let spin_config::TriggerConfig::Http(trigger) = &c.trigger;
+ let trigger = c.trigger.as_http().unwrap();
(
RoutePattern::from(&app_trigger.base, &trigger.route),
c.clone(),
diff --git a/crates/redis/Cargo.toml b/crates/redis/Cargo.toml
index 4706db09e4..56992e66f8 100644
--- a/crates/redis/Cargo.toml
+++ b/crates/redis/Cargo.toml
@@ -1,8 +1,11 @@
[package]
-name = "spin-redis"
+name = "spin-redis-engine"
version = "0.1.0"
edition = "2021"
-authors = [ "Radu Matei <radu.matei@fermyon.com>" ]
+authors = [ "Fermyon Engineering <engineering@fermyon.com>" ]
+
+[lib]
+doctest = false
[dependencies]
anyhow = "1.0"
@@ -12,10 +15,13 @@ futures = "0.3"
log = { version = "0.4", default-features = false }
serde = { version = "1.0", features = [ "derive" ] }
spin-engine = { path = "../engine" }
+spin-config = { path = "../config" }
redis = { version = "0.21", features = [ "tokio-comp" ] }
tokio = { version = "1.14", features = [ "full" ] }
-wit-bindgen-rust = { git = "https://github.com/bytecodealliance/wit-bindgen", rev = "e9c7c0a3405845cecd3fe06f3c20ab413302fc73" }
-wit-bindgen-wasmtime = { git = "https://github.com/bytecodealliance/wit-bindgen", rev = "e9c7c0a3405845cecd3fe06f3c20ab413302fc73" }
-wasi-common = "0.33"
-wasmtime = "0.33"
-wasmtime-wasi = "0.33"
+tracing = { version = "0.1", features = [ "log" ] }
+tracing-futures = "0.2"
+tracing-subscriber = { version = "0.3.7", features = [ "env-filter" ] }
+wasi-common = "0.34"
+wasmtime = "0.34"
+wasmtime-wasi = "0.34"
+wit-bindgen-wasmtime = { git = "https://github.com/bytecodealliance/wit-bindgen", rev = "e9c7c0a3405845cecd3fe06f3c20ab413302fc73" }
\ No newline at end of file
diff --git a/crates/redis/src/lib.rs b/crates/redis/src/lib.rs
index 81db2c60a4..050fcbb435 100644
--- a/crates/redis/src/lib.rs
+++ b/crates/redis/src/lib.rs
@@ -1,99 +1,152 @@
-use anyhow::Result;
+//! Implementation for the Spin Redis engine.
+
+mod spin;
+
+use crate::spin::SpinRedisExecutor;
+use anyhow::{ensure, Result};
use async_trait::async_trait;
use futures::StreamExt;
use redis::Client;
-use spin_redis_trigger::{SpinRedisTrigger, SpinRedisTriggerData};
-use std::{sync::Arc, time::Instant};
-use wasmtime::{Instance, Store};
+use spin_config::{Configuration, CoreComponent, RedisConfig};
+use spin_engine::{Builder, ExecutionContextConfiguration};
+use spin_redis_trigger::SpinRedisTriggerData;
+use std::{collections::HashMap, path::PathBuf, sync::Arc};
wit_bindgen_wasmtime::import!("wit/ephemeral/spin-redis-trigger.wit");
type ExecutionContext = spin_engine::ExecutionContext<SpinRedisTriggerData>;
type RuntimeContext = spin_engine::RuntimeContext<SpinRedisTriggerData>;
+/// The Spin Redis trigger.
#[derive(Clone)]
-pub struct RedisEngine(pub Arc<ExecutionContext>);
-
-#[async_trait]
-impl Redis for RedisEngine {
- async fn execute(&self, payload: &[u8]) -> Result<()> {
- let start = Instant::now();
-
- let (store, instance) = self.0.prepare(None)?;
- self.execute_impl(store, instance, payload)?;
- log::trace!("Request execution time: {:#?}", start.elapsed());
-
- Ok(())
- }
+pub struct RedisTrigger {
+ /// Configuration for the application.
+ app: Configuration<CoreComponent>,
+ /// Spin execution context.
+ engine: Arc<ExecutionContext>,
+ /// Map from channel name to tuple of component name & index.
+ subscriptions: HashMap<String, usize>,
}
-impl RedisEngine {
- pub fn execute_impl(
- &self,
- mut store: Store<RuntimeContext>,
- instance: Instance,
- payload: &[u8],
- ) -> Result<()> {
- let r = SpinRedisTrigger::new(&mut store, &instance, |host| host.data.as_mut().unwrap())?;
-
- let _ = r.handler(&mut store, payload)?;
- Ok(())
+impl RedisTrigger {
+ /// Create a new Spin Redis trigger.
+ pub async fn new(
+ app: Configuration<CoreComponent>,
+ wasmtime: Option<wasmtime::Config>,
+ log_dir: Option<PathBuf>,
+ ) -> Result<Self> {
+ ensure!(
+ app.info.trigger.as_redis().is_some(),
+ "Application trigger is not Redis"
+ );
+
+ let mut config = ExecutionContextConfiguration::new(app.clone(), log_dir);
+ if let Some(wasmtime) = wasmtime {
+ config.wasmtime = wasmtime;
+ };
+ let engine = Arc::new(Builder::build_default(config).await?);
+ log::debug!("Created new Redis trigger.");
+
+ let subscriptions =
+ app.components
+ .iter()
+ .enumerate()
+ .fold(HashMap::new(), |mut map, (idx, c)| {
+ if let Some(RedisConfig { channel, .. }) = c.trigger.as_redis() {
+ map.insert(channel.clone(), idx);
+ }
+ map
+ });
+
+ Ok(Self {
+ app,
+ engine,
+ subscriptions,
+ })
}
-}
-#[async_trait]
-pub trait Redis {
- async fn execute(&self, payload: &[u8]) -> Result<()>;
-}
+ /// Run the Redis trigger indefinitely.
+ pub async fn run(&self) -> Result<()> {
+ // We can unwrap here because the trigger type has already been asserted in `RedisTrigger::new`
+ let address = self.app.info.trigger.as_redis().cloned().unwrap().address;
-pub struct RedisTrigger {
- pub address: String,
- pub channel: String,
-}
+ log::info!("Connecting to Redis server at {}", address);
+ let client = Client::open(address.clone())?;
+ let mut pubsub = client.get_async_connection().await?.into_pubsub();
-impl RedisTrigger {
- pub async fn run(&self, runtime: impl Redis) -> Result<()> {
- let addr = &self.address.clone();
- let ch = &self.channel.clone();
+ // Subscribe to channels
+ for (subscription, id) in self.subscriptions.iter() {
+ let name = &self.app.components[*id].id;
+ log::info!(
+ "Subscribed component #{} ({}) to channel: {}",
+ id,
+ name,
+ subscription
+ );
+ pubsub.subscribe(subscription).await?;
+ }
- let client = Client::open(addr.as_str())?;
- let mut pubsub = client.get_async_connection().await?.into_pubsub();
- pubsub.subscribe(ch).await?;
- println!("Subscribed to channel: {}", ch);
let mut stream = pubsub.on_message();
loop {
match stream.next().await {
- Some(p) => {
- let payload = p.get_payload_bytes();
- runtime.execute(payload).await?;
- }
+ Some(msg) => drop(self.handle(msg).await),
None => log::debug!("Empty message"),
};
}
}
-}
-#[cfg(test)]
-mod tests {
- use crate::{RedisEngine, RedisTrigger};
- use spin_engine::{Config, ExecutionContextBuilder};
- use std::sync::Arc;
-
- const RUST_ENTRYPOINT_PATH: &str = "tests/rust/target/wasm32-wasi/release/rust.wasm";
-
- // #[tokio::test]
- #[allow(unused)]
- async fn test_pubsub() {
- let trigger = RedisTrigger {
- address: "redis://localhost:6379".to_string(),
- channel: "channel".to_string(),
- };
-
- let engine =
- ExecutionContextBuilder::build_default(RUST_ENTRYPOINT_PATH, Config::default())
- .unwrap();
- let engine = RedisEngine(Arc::new(engine));
+ // Handle the message.
+ async fn handle(&self, msg: redis::Msg) -> Result<()> {
+ let channel = msg.get_channel_name();
+ log::info!("Received message on channel {:?}", channel);
+
+ if let Some(id) = self.subscriptions.get(channel).copied() {
+ let component = &self.app.components[id];
+ let executor = component
+ .trigger
+ .as_redis()
+ .cloned()
+ .unwrap() // TODO
+ .executor
+ .unwrap_or_default();
+
+ match executor {
+ spin_config::RedisExecutor::Spin => {
+ log::trace!("Executing Spin Redis component {}", component.id);
+ let executor = SpinRedisExecutor;
+ executor
+ .execute(
+ &self.engine,
+ &component.id,
+ channel,
+ msg.get_payload_bytes(),
+ )
+ .await?
+ }
+ spin_config::RedisExecutor::Wagi(_) => {
+ todo!();
+ }
+ };
+ } else {
+ log::debug!("No subscription found for {:?}", channel);
+ }
- trigger.run(engine).await.unwrap();
+ Ok(())
}
}
+
+/// The Redis executor trait.
+/// All Redis executors must implement this trait.
+#[async_trait]
+pub(crate) trait RedisExecutor: Clone + Send + Sync + 'static {
+ async fn execute(
+ &self,
+ engine: &ExecutionContext,
+ component: &str,
+ channel: &str,
+ payload: &[u8],
+ ) -> Result<()>;
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/redis/src/spin.rs b/crates/redis/src/spin.rs
new file mode 100644
index 0000000000..1c26265152
--- /dev/null
+++ b/crates/redis/src/spin.rs
@@ -0,0 +1,60 @@
+use crate::{
+ spin_redis_trigger::SpinRedisTrigger, ExecutionContext, RedisExecutor, RuntimeContext,
+};
+use anyhow::Result;
+use async_trait::async_trait;
+use tokio::task::spawn_blocking;
+use wasmtime::{Instance, Store};
+
+#[derive(Clone)]
+pub struct SpinRedisExecutor;
+
+#[async_trait]
+impl RedisExecutor for SpinRedisExecutor {
+ async fn execute(
+ &self,
+ engine: &ExecutionContext,
+ component: &str,
+ channel: &str,
+ payload: &[u8],
+ ) -> Result<()> {
+ log::trace!(
+ "Executing request using the Spin executor for component {}",
+ component
+ );
+ let (store, instance) = engine.prepare_component(component, None, None, None, None)?;
+
+ match Self::execute_impl(store, instance, channel, payload.to_vec()).await {
+ Ok(()) => {
+ log::trace!("Request finished OK");
+ Ok(())
+ }
+ Err(e) => {
+ log::trace!("Request finished with error {}", e);
+ Err(e)
+ }
+ }
+ }
+}
+
+impl SpinRedisExecutor {
+ pub async fn execute_impl(
+ mut store: Store<RuntimeContext>,
+ instance: Instance,
+ _channel: &str,
+ payload: Vec<u8>,
+ ) -> Result<()> {
+ let engine =
+ SpinRedisTrigger::new(&mut store, &instance, |host| host.data.as_mut().unwrap())?;
+
+ let _res = spawn_blocking(move || -> Result<crate::spin_redis_trigger::Error> {
+ match engine.handler(&mut store, &payload) {
+ Ok(_) => Ok(crate::spin_redis_trigger::Error::Success),
+ Err(_) => Ok(crate::spin_redis_trigger::Error::Error),
+ }
+ })
+ .await??;
+
+ Ok(())
+ }
+}
diff --git a/examples/http-rust/Cargo.toml b/examples/http-rust/Cargo.toml
index f73f750371..c9e8dd77c9 100644
--- a/examples/http-rust/Cargo.toml
+++ b/examples/http-rust/Cargo.toml
@@ -18,4 +18,4 @@ spin-sdk = { path = "../../sdk/rust", version = "0.1.0" }
# Crate that generates Rust Wasm bindings from a WebAssembly interface.
wit-bindgen-rust = { git = "https://github.com/bytecodealliance/wit-bindgen", rev = "e9c7c0a3405845cecd3fe06f3c20ab413302fc73" }
-[workspace]
+[workspace]
\ No newline at end of file
diff --git a/examples/redis-rust/.cargo/config.toml b/examples/redis-rust/.cargo/config.toml
new file mode 100644
index 0000000000..6b77899cb3
--- /dev/null
+++ b/examples/redis-rust/.cargo/config.toml
@@ -0,0 +1,2 @@
+[build]
+target = "wasm32-wasi"
diff --git a/examples/redis-rust/Cargo.lock b/examples/redis-rust/Cargo.lock
new file mode 100644
index 0000000000..c3764645d8
--- /dev/null
+++ b/examples/redis-rust/Cargo.lock
@@ -0,0 +1,356 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 3
+
+[[package]]
+name = "anyhow"
+version = "1.0.55"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "159bb86af3a200e19a068f4224eae4c8bb2d0fa054c7e5d1cacd5cef95e684cd"
+
+[[package]]
+name = "async-trait"
+version = "0.1.52"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "061a7acccaa286c011ddc30970520b98fa40e00c9d644633fb26b5fc63a265e3"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "bitflags"
+version = "1.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
+
+[[package]]
+name = "bytes"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c4872d67bab6358e59559027aa3b9157c53d9358c51423c17554809a8858e0f8"
+
+[[package]]
+name = "cfg-if"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
+
+[[package]]
+name = "fnv"
+version = "1.0.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
+
+[[package]]
+name = "heck"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6d621efb26863f0e9924c6ac577e8275e5e6b77455db64ffa6c65c904e9e132c"
+dependencies = [
+ "unicode-segmentation",
+]
+
+[[package]]
+name = "http"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "31f4c6746584866f0feabcc69893c5b51beef3831656a968ed7ae254cdc4fd03"
+dependencies = [
+ "bytes",
+ "fnv",
+ "itoa",
+]
+
+[[package]]
+name = "id-arena"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "25a2bc672d1148e28034f176e01fffebb08b35768468cc954630da77a1449005"
+
+[[package]]
+name = "itoa"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1aab8fc367588b89dcee83ab0fd66b72b50b72fa1904d7095045ace2b0c81c35"
+
+[[package]]
+name = "lazy_static"
+version = "1.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
+
+[[package]]
+name = "log"
+version = "0.4.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "51b9bbe6c47d51fc3e1a9b945965946b4c44142ab8792c50835a980d362c2710"
+dependencies = [
+ "cfg-if",
+]
+
+[[package]]
+name = "memchr"
+version = "2.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "308cc39be01b73d0d18f82a0e7b2a3df85245f84af96fdddc5d202d27e47b86a"
+
+[[package]]
+name = "pin-project-lite"
+version = "0.2.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e280fbe77cc62c91527259e9442153f4688736748d24660126286329742b4c6c"
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.36"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c7342d5883fbccae1cc37a2353b09c87c9b0f3afd73f5fb9bba687a1f733b029"
+dependencies = [
+ "unicode-xid",
+]
+
+[[package]]
+name = "pulldown-cmark"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ffade02495f22453cd593159ea2f59827aae7f53fa8323f756799b670881dcf8"
+dependencies = [
+ "bitflags",
+ "memchr",
+ "unicase",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "864d3e96a899863136fc6e99f3d7cae289dafe43bf2c5ac19b70df7210c0a145"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "spin-macro"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "bytes",
+ "http",
+ "proc-macro2",
+ "quote",
+ "syn",
+ "wit-bindgen-gen-core",
+ "wit-bindgen-gen-rust-wasm",
+ "wit-bindgen-rust",
+]
+
+[[package]]
+name = "spin-sdk"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "bytes",
+ "http",
+ "spin-macro",
+ "wasi-experimental-http",
+]
+
+[[package]]
+name = "spinredis"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "bytes",
+ "spin-sdk",
+ "wit-bindgen-rust",
+]
+
+[[package]]
+name = "syn"
+version = "1.0.86"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a65b3f4ffa0092e9887669db0eae07941f023991ab58ea44da8fe8e2d511c6b"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-xid",
+]
+
+[[package]]
+name = "thiserror"
+version = "1.0.30"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "854babe52e4df1653706b98fcfc05843010039b406875930a70e4d9644e5c417"
+dependencies = [
+ "thiserror-impl",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "1.0.30"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aa32fd3f627f367fe16f893e2597ae3c05020f8bba2666a4e6ea73d377e5714b"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "tinyvec"
+version = "1.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2c1c1d5a42b6245520c249549ec267180beaffcc0615401ac8e31853d4b6d8d2"
+dependencies = [
+ "tinyvec_macros",
+]
+
+[[package]]
+name = "tinyvec_macros"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c"
+
+[[package]]
+name = "tracing"
+version = "0.1.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f6c650a8ef0cd2dd93736f033d21cbd1224c5a967aa0c258d00fcf7dafef9b9f"
+dependencies = [
+ "cfg-if",
+ "log",
+ "pin-project-lite",
+ "tracing-attributes",
+ "tracing-core",
+]
+
+[[package]]
+name = "tracing-attributes"
+version = "0.1.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2e65ce065b4b5c53e73bb28912318cb8c9e9ad3921f1d669eb0e68b4c8143a2b"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "tracing-core"
+version = "0.1.22"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "03cfcb51380632a72d3111cb8d3447a8d908e577d31beeac006f836383d29a23"
+dependencies = [
+ "lazy_static",
+]
+
+[[package]]
+name = "unicase"
+version = "2.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "50f37be617794602aabbeee0be4f259dc1778fabe05e2d67ee8f79326d5cb4f6"
+dependencies = [
+ "version_check",
+]
+
+[[package]]
+name = "unicode-normalization"
+version = "0.1.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d54590932941a9e9266f0832deed84ebe1bf2e4c9e4a3554d393d18f5e854bf9"
+dependencies = [
+ "tinyvec",
+]
+
+[[package]]
+name = "unicode-segmentation"
+version = "1.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7e8820f5d777f6224dc4be3632222971ac30164d4a258d595640799554ebfd99"
+
+[[package]]
+name = "unicode-xid"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3"
+
+[[package]]
+name = "version_check"
+version = "0.9.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
+
+[[package]]
+name = "wasi-experimental-http"
+version = "0.9.0"
+source = "git+https://github.com/radu-matei/wasi-experimental-http?branch=from-client#410e9c598131aeec4d21ffdb65dfd703304da37d"
+dependencies = [
+ "anyhow",
+ "bytes",
+ "http",
+ "thiserror",
+ "tracing",
+]
+
+[[package]]
+name = "wit-bindgen-gen-core"
+version = "0.1.0"
+source = "git+https://github.com/bytecodealliance/wit-bindgen?rev=e9c7c0a3405845cecd3fe06f3c20ab413302fc73#e9c7c0a3405845cecd3fe06f3c20ab413302fc73"
+dependencies = [
+ "anyhow",
+ "wit-parser",
+]
+
+[[package]]
+name = "wit-bindgen-gen-rust"
+version = "0.1.0"
+source = "git+https://github.com/bytecodealliance/wit-bindgen?rev=e9c7c0a3405845cecd3fe06f3c20ab413302fc73#e9c7c0a3405845cecd3fe06f3c20ab413302fc73"
+dependencies = [
+ "heck",
+ "wit-bindgen-gen-core",
+]
+
+[[package]]
+name = "wit-bindgen-gen-rust-wasm"
+version = "0.1.0"
+source = "git+https://github.com/bytecodealliance/wit-bindgen?rev=e9c7c0a3405845cecd3fe06f3c20ab413302fc73#e9c7c0a3405845cecd3fe06f3c20ab413302fc73"
+dependencies = [
+ "heck",
+ "wit-bindgen-gen-core",
+ "wit-bindgen-gen-rust",
+]
+
+[[package]]
+name = "wit-bindgen-rust"
+version = "0.1.0"
+source = "git+https://github.com/bytecodealliance/wit-bindgen?rev=e9c7c0a3405845cecd3fe06f3c20ab413302fc73#e9c7c0a3405845cecd3fe06f3c20ab413302fc73"
+dependencies = [
+ "async-trait",
+ "bitflags",
+ "wit-bindgen-rust-impl",
+]
+
+[[package]]
+name = "wit-bindgen-rust-impl"
+version = "0.1.0"
+source = "git+https://github.com/bytecodealliance/wit-bindgen?rev=e9c7c0a3405845cecd3fe06f3c20ab413302fc73#e9c7c0a3405845cecd3fe06f3c20ab413302fc73"
+dependencies = [
+ "proc-macro2",
+ "syn",
+ "wit-bindgen-gen-core",
+ "wit-bindgen-gen-rust-wasm",
+]
+
+[[package]]
+name = "wit-parser"
+version = "0.1.0"
+source = "git+https://github.com/bytecodealliance/wit-bindgen?rev=e9c7c0a3405845cecd3fe06f3c20ab413302fc73#e9c7c0a3405845cecd3fe06f3c20ab413302fc73"
+dependencies = [
+ "anyhow",
+ "id-arena",
+ "pulldown-cmark",
+ "unicode-normalization",
+ "unicode-xid",
+]
diff --git a/examples/redis-rust/Cargo.toml b/examples/redis-rust/Cargo.toml
new file mode 100644
index 0000000000..0d8089d787
--- /dev/null
+++ b/examples/redis-rust/Cargo.toml
@@ -0,0 +1,19 @@
+[package]
+name = "spinredis"
+version = "0.1.0"
+edition = "2021"
+
+[lib]
+crate-type = [ "cdylib" ]
+
+[dependencies]
+# Useful crate to handle errors.
+anyhow = "1"
+# Crate to simplify working with bytes.
+bytes = "1"
+# The Spin SDK.
+spin-sdk = { path = "../../sdk/rust", version = "0.1.0" }
+# Crate that generates Rust Wasm bindings from a WebAssembly interface.
+wit-bindgen-rust = { git = "https://github.com/bytecodealliance/wit-bindgen", rev = "e9c7c0a3405845cecd3fe06f3c20ab413302fc73" }
+
+[workspace]
\ No newline at end of file
diff --git a/examples/redis-rust/spin.toml b/examples/redis-rust/spin.toml
new file mode 100644
index 0000000000..048777e988
--- /dev/null
+++ b/examples/redis-rust/spin.toml
@@ -0,0 +1,12 @@
+spin_version = "1"
+authors = ["Fermyon Engineering <engineering@fermyon.com>"]
+description = "A redis application."
+name = "spin-redis"
+trigger = {type = "redis", address = "redis://localhost:6379"}
+version = "0.1.0"
+
+[[component]]
+id = "example"
+source = "target/wasm32-wasi/release/spinredis.wasm"
+[component.trigger]
+channel="messages"
\ No newline at end of file
diff --git a/examples/redis-rust/src/lib.rs b/examples/redis-rust/src/lib.rs
new file mode 100644
index 0000000000..7424a8d983
--- /dev/null
+++ b/examples/redis-rust/src/lib.rs
@@ -0,0 +1,11 @@
+use anyhow::Result;
+use bytes::Bytes;
+use spin_sdk::redis_component;
+use std::str::from_utf8;
+
+/// A simple Spin Redis component.
+#[redis_component]
+fn on_message(message: Bytes) -> Result<()> {
+ println!("{}", from_utf8(&message)?);
+ Ok(())
+}
diff --git a/sdk/rust/macro/src/lib.rs b/sdk/rust/macro/src/lib.rs
index 8275ac1862..db8f5eba2b 100644
--- a/sdk/rust/macro/src/lib.rs
+++ b/sdk/rust/macro/src/lib.rs
@@ -6,10 +6,12 @@ use wit_bindgen_gen_rust_wasm::RustWasm;
/// The entrypoint to a Spin HTTP component written in Rust.
#[proc_macro_attribute]
pub fn http_component(_attr: TokenStream, item: TokenStream) -> TokenStream {
+ const HTTP_COMPONENT_WIT_PATH: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/wit/spin-http.wit");
+
let func = syn::parse_macro_input!(item as syn::ItemFn);
let func_name = &func.sig.ident;
- let iface = Interface::parse_file(concat!(env!("CARGO_MANIFEST_DIR"), "/wit/spin-http.wit"))
+ let iface = Interface::parse_file(HTTP_COMPONENT_WIT_PATH)
.expect("cannot parse Spin HTTP interface file");
let mut files = Files::default();
@@ -174,3 +176,35 @@ pub fn http_component(_attr: TokenStream, item: TokenStream) -> TokenStream {
)
.into()
}
+
+/// Generates the entrypoint to a Spin Redis component written in Rust.
+#[proc_macro_attribute]
+pub fn redis_component(_attr: TokenStream, item: TokenStream) -> TokenStream {
+ const REDIS_COMPONENT_WIT: &str =
+ include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/wit/spin-redis.wit"));
+
+ let func = syn::parse_macro_input!(item as syn::ItemFn);
+ let func_name = &func.sig.ident;
+
+ quote!(
+ wit_bindgen_rust::export!({src["spin_redis"]: #REDIS_COMPONENT_WIT});
+
+ struct SpinRedis;
+
+ impl spin_redis::SpinRedis for SpinRedis {
+ fn handler(payload: spin_redis::Payload) -> Result<(), spin_redis::Error> {
+ #func
+
+ match #func_name(payload.try_into().expect("cannot convert from Spin Redis payload")) {
+ Ok(()) => Ok(()),
+ Err(e) => {
+ eprintln!("{}", e);
+ Err(spin_redis::Error::Error)
+ },
+ }
+ }
+ }
+
+ )
+ .into()
+}
diff --git a/sdk/rust/macro/wit/spin-redis.wit b/sdk/rust/macro/wit/spin-redis.wit
new file mode 100644
index 0000000000..c3a6987291
--- /dev/null
+++ b/sdk/rust/macro/wit/spin-redis.wit
@@ -0,0 +1,11 @@
+// The entrypoint for a Redis handler.
+handler: function(p: payload) -> expected<_, error>
+
+// The message payload.
+type payload = list<u8>
+
+// General purpose error.
+enum error {
+ success,
+ error,
+}
\ No newline at end of file
diff --git a/src/commands/up.rs b/src/commands/up.rs
index 8b43e56ecb..3f00df381e 100644
--- a/src/commands/up.rs
+++ b/src/commands/up.rs
@@ -1,6 +1,7 @@
use anyhow::{bail, Result};
-use spin_config::{Configuration, CoreComponent};
+use spin_config::{ApplicationTrigger, Configuration, CoreComponent};
use spin_http_engine::{HttpTrigger, TlsConfig};
+use spin_redis_engine::RedisTrigger;
use std::path::{Path, PathBuf};
use structopt::{clap::AppSettings, StructOpt};
use tempfile::TempDir;
@@ -121,8 +122,16 @@ impl UpCommand {
_ => unreachable!(),
};
- let trigger = HttpTrigger::new(self.address, app, None, tls, self.log).await?;
- trigger.run().await?;
+ match &app.info.trigger {
+ ApplicationTrigger::Http(_) => {
+ let trigger = HttpTrigger::new(self.address, app, None, tls, self.log).await?;
+ trigger.run().await?;
+ }
+ ApplicationTrigger::Redis(_) => {
+ let trigger = RedisTrigger::new(app, None, self.log).await?;
+ trigger.run().await?;
+ }
+ }
// We need to be absolutely sure it stays alive until this point: we don't want
// any temp directory to be deleted prematurely.
diff --git a/wit/ephemeral/types.wit b/wit/ephemeral/types.wit
index c02d914c5d..25160551b6 100644
--- a/wit/ephemeral/types.wit
+++ b/wit/ephemeral/types.wit
@@ -4,4 +4,5 @@ enum error {
error,
}
+// The message payload.
type payload = list<u8>
| 155
|
[
"59"
] |
diff --git a/crates/loader/src/local/tests.rs b/crates/loader/src/local/tests.rs
index 200d897b25..aa320a8d30 100644
--- a/crates/loader/src/local/tests.rs
+++ b/crates/loader/src/local/tests.rs
@@ -2,7 +2,7 @@ use crate::local::config::{RawDirectoryPlacement, RawFileMount, RawModuleSource}
use super::*;
use anyhow::Result;
-use spin_config::{ApplicationTrigger, HttpExecutor, TriggerConfig};
+use spin_config::HttpExecutor;
use std::path::PathBuf;
#[tokio::test]
@@ -21,10 +21,10 @@ async fn test_from_local_source() -> Result<()> {
"Fermyon Engineering <engineering@fermyon.com>"
);
- let ApplicationTrigger::Http(http) = cfg.info.trigger;
+ let http = cfg.info.trigger.as_http().unwrap().clone();
assert_eq!(http.base, "/".to_string());
- let TriggerConfig::Http(http) = cfg.components[0].trigger.clone();
+ let http = cfg.components[0].trigger.as_http().unwrap().clone();
assert_eq!(http.executor.unwrap(), HttpExecutor::Spin);
assert_eq!(http.route, "/...".to_string());
@@ -51,13 +51,13 @@ fn test_manifest() -> Result<()> {
Some("A simple application that returns the number of lights".to_string())
);
- let ApplicationTrigger::Http(http) = cfg.info.trigger;
+ let http = cfg.info.trigger.as_http().unwrap().clone();
assert_eq!(http.base, "/".to_string());
assert_eq!(cfg.info.authors.unwrap().len(), 3);
assert_eq!(cfg.components[0].id, "four-lights".to_string());
- let TriggerConfig::Http(http) = cfg.components[0].trigger.clone();
+ let http = cfg.components[0].trigger.as_http().unwrap().clone();
assert_eq!(http.executor.unwrap(), HttpExecutor::Spin);
assert_eq!(http.route, "/lights".to_string());
@@ -120,7 +120,7 @@ fn test_wagi_executor_with_custom_entrypoint() -> Result<()> {
let cfg_any: RawAppManifestAnyVersion = toml::from_str(MANIFEST)?;
let RawAppManifestAnyVersion::V1(cfg) = cfg_any;
- let TriggerConfig::Http(http_config) = &cfg.components[0].trigger;
+ let http_config = cfg.components[0].trigger.as_http().unwrap();
match http_config.executor.as_ref().unwrap() {
HttpExecutor::Spin => panic!("expected wagi http executor"),
diff --git a/crates/redis/src/tests.rs b/crates/redis/src/tests.rs
new file mode 100644
index 0000000000..27f72e1290
--- /dev/null
+++ b/crates/redis/src/tests.rs
@@ -0,0 +1,70 @@
+use super::*;
+use anyhow::Result;
+use spin_config::{
+ ApplicationInformation, Configuration, CoreComponent, ModuleSource, RedisConfig, RedisExecutor,
+ SpinVersion, TriggerConfig,
+};
+use std::{collections::HashMap, sync::Once};
+
+static LOGGER: Once = Once::new();
+
+const RUST_ENTRYPOINT_PATH: &str = "tests/rust/target/wasm32-wasi/release/rust.wasm";
+
+/// We can only initialize the tracing subscriber once per crate.
+pub(crate) fn init() {
+ LOGGER.call_once(|| {
+ tracing_subscriber::fmt()
+ .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
+ .init();
+ });
+}
+
+fn fake_file_origin() -> spin_config::ApplicationOrigin {
+ let dir = env!("CARGO_MANIFEST_DIR");
+ let fake_path = std::path::PathBuf::from(dir).join("fake_spin.toml");
+ spin_config::ApplicationOrigin::File(fake_path)
+}
+
+#[tokio::test]
+#[allow(unused)]
+async fn test_pubsub() -> Result<()> {
+ init();
+
+ let info = ApplicationInformation {
+ spin_version: SpinVersion::V1,
+ name: "test-redis".to_string(),
+ version: "0.1.0".to_string(),
+ description: None,
+ authors: vec![],
+ trigger: spin_config::ApplicationTrigger::Redis(spin_config::RedisTriggerConfiguration {
+ address: "redis://localhost:6379".to_owned(),
+ }),
+ namespace: None,
+ origin: fake_file_origin(),
+ };
+
+ let components = vec![CoreComponent {
+ source: ModuleSource::FileReference(RUST_ENTRYPOINT_PATH.into()),
+ id: "test".to_string(),
+ trigger: TriggerConfig::Redis(RedisConfig {
+ channel: "messages".to_string(),
+ executor: Some(RedisExecutor::Spin),
+ }),
+ wasm: spin_config::WasmConfig {
+ environment: HashMap::new(),
+ mounts: vec![],
+ allowed_http_hosts: vec![],
+ },
+ }];
+
+ let app = Configuration::<CoreComponent> { info, components };
+ let trigger = RedisTrigger::new(app, None, None).await?;
+
+ // TODO
+ // use redis::{FromRedisValue, Msg, Value};
+ // let val = FromRedisValue::from_redis_value(&Value::Data("hello".into()))?;
+ // let msg = Msg::from_value(&val).unwrap();
+ // trigger.handle(msg).await?;
+
+ Ok(())
+}
diff --git a/crates/redis/tests/rust/src/lib.rs b/crates/redis/tests/rust/src/lib.rs
index 78b7ed0735..aa70d2d72f 100644
--- a/crates/redis/tests/rust/src/lib.rs
+++ b/crates/redis/tests/rust/src/lib.rs
@@ -1,14 +1,13 @@
+use spin_redis_trigger::{Error, Payload};
use std::str::{from_utf8, Utf8Error};
-use spin_redis_trigger::*;
-
wit_bindgen_rust::export!("../../../../wit/ephemeral/spin-redis-trigger.wit");
struct SpinRedisTrigger {}
impl spin_redis_trigger::SpinRedisTrigger for SpinRedisTrigger {
fn handler(payload: Payload) -> Result<(), Error> {
- println!("Message: {}", from_utf8(&payload)?);
+ println!("Message: {:?}", from_utf8(&payload));
Ok(())
}
}
|
95f9da2a41aded597a437ad041a5a13ab19604ee
|
|
e80696c95ac711fe6635fe0f59e7798d5a479670
|
Leaking temporary asset directories
In my testing, it appears temporary directories used for copying static assets are not deleted after stopping Spin.
Repro: run an application with file mounts multiple times, then check the temporary directories.
|
2022-03-09T02:53:38Z
|
fermyon__spin-149
|
fermyon/spin
|
0.1
|
diff --git a/crates/loader/src/bindle/mod.rs b/crates/loader/src/bindle/mod.rs
index 7fbc50dd27..3252456c95 100644
--- a/crates/loader/src/bindle/mod.rs
+++ b/crates/loader/src/bindle/mod.rs
@@ -23,7 +23,7 @@ use spin_config::{
ApplicationInformation, ApplicationOrigin, Configuration, CoreComponent, ModuleSource,
WasmConfig,
};
-use std::path::{Path, PathBuf};
+use std::path::Path;
use tracing::log;
pub use utils::{BindleTokenManager, SPIN_MANIFEST_MEDIA_TYPE};
@@ -34,7 +34,7 @@ pub use utils::{BindleTokenManager, SPIN_MANIFEST_MEDIA_TYPE};
pub async fn from_bindle(
id: &str,
url: &str,
- base_dst: Option<PathBuf>,
+ base_dst: impl AsRef<Path>,
) -> Result<Configuration<CoreComponent>> {
// TODO
// Handle Bindle authentication.
@@ -50,13 +50,8 @@ async fn prepare(
id: &str,
url: &str,
reader: &BindleReader,
- base_dst: Option<PathBuf>,
+ base_dst: impl AsRef<Path>,
) -> Result<Configuration<CoreComponent>> {
- let dir = match base_dst {
- Some(d) => d,
- None => tempfile::tempdir()?.into_path(),
- };
-
// First, get the invoice from the Bindle server.
let invoice = reader
.get_invoice()
@@ -73,7 +68,7 @@ async fn prepare(
let components = future::join_all(
raw.components
.into_iter()
- .map(|c| async { core(c, &invoice, reader, &dir).await })
+ .map(|c| async { core(c, &invoice, reader, &base_dst).await })
.collect::<Vec<_>>(),
)
.await
diff --git a/crates/loader/src/local/mod.rs b/crates/loader/src/local/mod.rs
index 0593c9bbc4..83daca79e5 100644
--- a/crates/loader/src/local/mod.rs
+++ b/crates/loader/src/local/mod.rs
@@ -18,7 +18,7 @@ use spin_config::{
ApplicationInformation, ApplicationOrigin, Configuration, CoreComponent, ModuleSource,
WasmConfig,
};
-use std::path::{Path, PathBuf};
+use std::path::Path;
use tokio::{fs::File, io::AsyncReadExt};
/// Given the path to a spin.toml manifest file, prepare its assets locally and
@@ -27,7 +27,7 @@ use tokio::{fs::File, io::AsyncReadExt};
/// otherwise create a new temporary directory.
pub async fn from_file(
app: impl AsRef<Path>,
- base_dst: Option<PathBuf>,
+ base_dst: impl AsRef<Path>,
) -> Result<Configuration<CoreComponent>> {
let app = app
.as_ref()
@@ -56,7 +56,7 @@ pub async fn raw_manifest_from_file(app: &impl AsRef<Path>) -> Result<RawAppMani
async fn prepare_any_version(
raw: RawAppManifestAnyVersion,
src: impl AsRef<Path>,
- base_dst: Option<PathBuf>,
+ base_dst: impl AsRef<Path>,
) -> Result<Configuration<CoreComponent>> {
match raw {
RawAppManifestAnyVersion::V0_1_0(raw) => prepare(raw, src, base_dst).await,
@@ -67,19 +67,14 @@ async fn prepare_any_version(
async fn prepare(
raw: RawAppManifest,
src: impl AsRef<Path>,
- base_dst: Option<PathBuf>,
+ base_dst: impl AsRef<Path>,
) -> Result<Configuration<CoreComponent>> {
- let dir = match base_dst {
- Some(d) => d,
- None => tempfile::tempdir()?.into_path(),
- };
-
let info = info(raw.info, &src);
let components = future::join_all(
raw.components
.into_iter()
- .map(|c| async { core(c, &src, &dir).await })
+ .map(|c| async { core(c, &src, &base_dst).await })
.collect::<Vec<_>>(),
)
.await
diff --git a/src/commands/up.rs b/src/commands/up.rs
index d354c5719a..5821f695d4 100644
--- a/src/commands/up.rs
+++ b/src/commands/up.rs
@@ -1,8 +1,9 @@
use anyhow::{bail, Result};
use spin_config::{Configuration, CoreComponent};
use spin_http_engine::{HttpTrigger, TlsConfig};
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
use structopt::{clap::AppSettings, StructOpt};
+use tempfile::TempDir;
const APP_CONFIG_FILE_OPT: &str = "APP_CONFIG_FILE";
const BINDLE_ID_OPT: &str = "BINDLE_ID";
@@ -78,11 +79,17 @@ pub struct UpCommand {
impl UpCommand {
pub async fn run(self) -> Result<()> {
+ let working_dir_holder = match &self.tmp {
+ None => WorkingDirectory::Temporary(tempfile::tempdir()?),
+ Some(d) => WorkingDirectory::Given(d.to_owned()),
+ };
+ let working_dir = working_dir_holder.path();
+
let mut app = match (&self.app, &self.bindle) {
(None, None) => bail!("Must specify app file or bindle id"),
- (Some(app), None) => spin_loader::from_file(app, self.tmp).await?,
+ (Some(app), None) => spin_loader::from_file(app, working_dir).await?,
(None, Some(bindle)) => match &self.server {
- Some(server) => spin_loader::from_bindle(bindle, server, self.tmp).await?,
+ Some(server) => spin_loader::from_bindle(bindle, server, working_dir).await?,
_ => bail!("Loading from a bindle requires a Bindle server URL"),
},
(Some(_), Some(_)) => bail!("Specify only one of app file or bindle ID"),
@@ -107,7 +114,13 @@ impl UpCommand {
};
let trigger = HttpTrigger::new(self.address, app, None, tls).await?;
- trigger.run().await
+ trigger.run().await?;
+
+ // We need to be absolutely sure it stays alive until this point: we don't want
+ // any temp directory to be deleted prematurely.
+ drop(working_dir_holder);
+
+ Ok(())
}
}
@@ -129,3 +142,17 @@ fn append_env(app: &mut Configuration<CoreComponent>, env: &[(String, String)])
}
Ok(())
}
+
+enum WorkingDirectory {
+ Given(PathBuf),
+ Temporary(TempDir),
+}
+
+impl WorkingDirectory {
+ fn path(&self) -> &Path {
+ match self {
+ Self::Given(p) => p,
+ Self::Temporary(t) => t.path(),
+ }
+ }
+}
| 149
|
[
"146"
] |
diff --git a/crates/loader/src/local/tests.rs b/crates/loader/src/local/tests.rs
index 710600f482..2d3c1d3bc8 100644
--- a/crates/loader/src/local/tests.rs
+++ b/crates/loader/src/local/tests.rs
@@ -9,7 +9,8 @@ use std::path::PathBuf;
async fn test_from_local_source() -> Result<()> {
const MANIFEST: &str = "tests/valid-with-files/spin.toml";
- let dir: Option<PathBuf> = None;
+ let temp_dir = tempfile::tempdir()?;
+ let dir = temp_dir.path();
let cfg = from_file(MANIFEST, dir).await?;
assert_eq!(cfg.info.name, "spin-local-source-test");
|
95f9da2a41aded597a437ad041a5a13ab19604ee
|
|
d393dd47617b57affeb92b842e5ce670c1f762a4
|
Volume mounting
Mapping volume mounts would allow for flexible directories within a spin project. I have a module that expects files mounted as standard linux directories. In wagi you can map a volume in modules.toml as `volumes = { "/usr" = "ruby-wasm32-wasi/usr" }` which is much cleaner than having a `usr` directory in the repo root.
https://github.com/deislabs/wagi/blob/main/docs/configuring_and_running.md#volume-mounting
|
This is biting me, too. Treating volumes as maps is much better, because it is often not possible to make the outside directory structure exactly match the internal directory structure. In multi-module/component repos, I need to map the same external path to different internal paths (otherwise I have to copy the same data in two places in my source code and then keep them synced). In two different modules, I basically want to be able to do this:
```
# Module 1: Image resizing server that looks only in / for images
volumes = {"/" = "static/images"}
#module 2: File server that can serve anything under /
volumes = {"/" = "static"}
```
Also, we had to introduce an [unholy hack](https://github.com/deislabs/wagi-fileserver/blob/main/fileserver.gr#L86-L88) in the fileserver.gr in order to work around Hippo's assumption that the external directory and the internal directory are exact mirrors.
The pattern Adam suggests is basically the way Docker maps volumes, so this seems like a safe way of doing things.
Also, in UNIX and in most platforms i have used, doing things like `cp foo/` automatically copies the entire subtree (see also `mv`, `mount`, `rsync`, etc). I am unclear why I have to sometimes do `foo/**/*` to do a deep copy/map. I can't find any precedent elsewhere for that behavior. It's nice to have fine-grained control when I want it. But I think the default behavior should match the patterns people see in other systems. If I find it confusing, I am pretty sure lots of other people will as well.
The reason for doing `foo/**/*` is that we treat specifications as glob patterns, I suspect because we inherited Hippo's view of "this is a recipe for a bindle rather than a mapping of a local directory." We could certainly augment that by treating matches that are directories as implicit "the entire directory." Right now, though, this isn't a Docker mount where the guest has access to the host directory: rather, a Spin guest gets access to a _snapshot copy_ of the files that were mounted, again so that the user gets the same behaviour locally and when packaged as a bindle.
Again, we could modify that in the local case where directories (as opposed to file patterns) are mounted directly. We'd need to figure out what that means in the bindle case, though.
At the very least, though, we should provide a way to map a pattern at a specific location - this was something we proposed for Hippo but never got round to defining (because the main use case was the fileserver and that hacked around it instead).
What is the desired syntax? I see `{ path = other_path }` proposed but personally I struggle with "which is the guest and which is the host" - are other folks happy that this is clear, or should we consider a more verbose syntax like `{ source = foo, mount_at = bar }`?
(Also would this syntax allow patterns or only directories? Part of the trouble with defining this for Hippo was identifying what part of the pattern to strip; that's not an issue if the semantics are "mount THIS directory at THIS location".)
Is it also unambiguous to specify an individual file to mount at a specific location? E.g. `{ source = foo.txt, mount_at = /assets/bar.txt }`? Possibly unclear whether the destination is a file or directory.
Another thing to consider, which may be an implementation detail: if we say to mount a directory at `/bar`, but also have a `**` pattern mounted at `/`, is that an error because the trees overlap, or do we need to make sure they merge correctly? (How does `wasmtime` handle this? If guest code requests `/bar/baz.txt`, and the file doesn't exist at the `/bar` mount, does it look to see if a `bar` directory exists under the `/` mount? Whee!)
I'm happy to look at this but we probably need to spec it out a bit
|
2022-03-01T23:09:22Z
|
fermyon__spin-118
|
fermyon/spin
|
0.1
|
diff --git a/Cargo.lock b/Cargo.lock
index 066f728539..ebc91e0e08 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2987,6 +2987,7 @@ dependencies = [
"tracing",
"tracing-futures",
"tracing-subscriber 0.3.8",
+ "walkdir",
]
[[package]]
diff --git a/crates/loader/Cargo.toml b/crates/loader/Cargo.toml
index 6488640f1c..6ee52292ba 100644
--- a/crates/loader/Cargo.toml
+++ b/crates/loader/Cargo.toml
@@ -26,3 +26,4 @@ toml = "0.5"
tracing = { version = "0.1", features = [ "log" ] }
tracing-futures = "0.2"
tracing-subscriber = { version = "0.3.7", features = [ "env-filter" ] }
+walkdir = "2.3.2"
diff --git a/crates/loader/src/local/assets.rs b/crates/loader/src/local/assets.rs
index 244a22ac07..cdf7ea760a 100644
--- a/crates/loader/src/local/assets.rs
+++ b/crates/loader/src/local/assets.rs
@@ -6,31 +6,34 @@ use futures::future;
use spin_config::DirectoryMount;
use std::path::{Path, PathBuf};
use tracing::log;
+use walkdir::WalkDir;
+
+use super::config::{RawDirectoryPlacement, RawFileMount};
/// Prepare all local assets given a component ID and its file patterns.
/// This file will copy all assets into a temporary directory as read-only.
pub(crate) async fn prepare_component(
- patterns: &[String],
+ raw_mounts: &[RawFileMount],
src: impl AsRef<Path>,
base_dst: impl AsRef<Path>,
id: &str,
-) -> Result<DirectoryMount> {
+) -> Result<Vec<DirectoryMount>> {
log::info!(
"Mounting files from '{}' to '{}'",
src.as_ref().display(),
base_dst.as_ref().display()
);
- let files = collect(patterns, src)?;
+ let files = collect(raw_mounts, src)?;
let host = create_dir(&base_dst, id).await?;
let guest = "/".to_string();
copy_all(&files, &host).await?;
- Ok(DirectoryMount { guest, host })
+ Ok(vec![DirectoryMount { guest, host }])
}
/// A file that a component requires to be present at runtime.
-#[derive(Debug)]
+#[derive(Debug, Clone)]
pub struct FileMount {
/// The source
pub src: PathBuf,
@@ -41,17 +44,52 @@ pub struct FileMount {
impl FileMount {
fn from(
src: Result<impl AsRef<Path>, glob::GlobError>,
- relative_dst: impl AsRef<Path>,
+ relative_to: impl AsRef<Path>,
) -> Result<Self> {
let src = src?;
- let relative_dst = to_relative(&src, &relative_dst)?;
+ let relative_dst = to_relative(&src, &relative_to)?;
let src = src.as_ref().to_path_buf();
Ok(Self { src, relative_dst })
}
+
+ fn from_exact(src: impl AsRef<Path>, dest: impl AsRef<Path>) -> Result<Self> {
+ let src = src.as_ref().to_path_buf();
+ let relative_dst = dest.as_ref().to_string_lossy().to_string();
+ Ok(Self { src, relative_dst })
+ }
}
/// Generate a vector of file mounts for a component given all its file patterns.
-pub fn collect(patterns: &[String], rel: impl AsRef<Path>) -> Result<Vec<FileMount>> {
+pub fn collect(raw_mounts: &[RawFileMount], rel: impl AsRef<Path>) -> Result<Vec<FileMount>> {
+ let (patterns, placements) = uncase(raw_mounts);
+
+ let pattern_files = collect_patterns(&patterns, &rel)?;
+ let placement_files = collect_placements(&placements, &rel)?;
+ let all_files = [pattern_files, placement_files].concat();
+ Ok(all_files)
+}
+
+fn collect_placements(
+ placements: &[RawDirectoryPlacement],
+ rel: impl AsRef<Path>,
+) -> Result<Vec<FileMount>, anyhow::Error> {
+ let results = placements.iter().map(|placement| {
+ collect_placement(placement, &rel).with_context(|| {
+ format!(
+ "Failed to collect file mounts for {}",
+ placement.source.display()
+ )
+ })
+ });
+ let collections = results.collect::<Result<Vec<_>>>()?;
+ let collection = collections.into_iter().flatten().collect();
+ Ok(collection)
+}
+
+fn collect_patterns(
+ patterns: &[String],
+ rel: impl AsRef<Path>,
+) -> Result<Vec<FileMount>, anyhow::Error> {
let results = patterns.iter().map(|pattern| {
collect_pattern(pattern, &rel)
.with_context(|| format!("Failed to collect file mounts for {}", pattern))
@@ -61,6 +99,69 @@ pub fn collect(patterns: &[String], rel: impl AsRef<Path>) -> Result<Vec<FileMou
Ok(collection)
}
+fn collect_placement(
+ placement: &RawDirectoryPlacement,
+ rel: impl AsRef<Path>,
+) -> Result<Vec<FileMount>> {
+ let source = &placement.source;
+ let guest_path = &placement.destination;
+
+ if !source.is_relative() {
+ bail!(
+ "Cannot place {}: source paths must be relative",
+ source.display()
+ );
+ }
+ // TODO: check if this works if the host is Windows
+ if !guest_path.is_absolute() {
+ bail!(
+ "Cannot place {}: guest paths must be absolute",
+ guest_path.display()
+ );
+ }
+ // TODO: okay to assume that absolute guest paths start with '/'?
+ let relative_guest_path = guest_path.strip_prefix("/")?;
+
+ let abs = rel.as_ref().join(source);
+ if !abs.is_dir() {
+ bail!("Cannot place {}: source must be a directory", abs.display());
+ }
+
+ let walker = WalkDir::new(&abs);
+ let files = walker
+ .into_iter()
+ .filter_map(|de| match de {
+ Err(e) => Some(
+ Err(e).with_context(|| format!("Failed to walk directory under {}", abs.display())),
+ ),
+ Ok(dir_entry) => {
+ if dir_entry.file_type().is_file() {
+ let match_path = dir_entry.path();
+ match to_relative(match_path, &abs) {
+ Ok(relative_to_match_root_dst) => {
+ let guest_dst = relative_guest_path.join(relative_to_match_root_dst);
+ Some(FileMount::from_exact(match_path, &guest_dst))
+ }
+ Err(e) => {
+ let err = Err(e).with_context(|| {
+ format!(
+ "Failed to establish relative path for '{}'",
+ match_path.display()
+ )
+ });
+ Some(err)
+ }
+ }
+ } else {
+ None
+ }
+ }
+ })
+ .collect::<Result<Vec<_>>>()?;
+
+ Ok(files)
+}
+
/// Generate a vector of file mounts given a file pattern.
fn collect_pattern(pattern: &str, rel: impl AsRef<Path>) -> Result<Vec<FileMount>> {
let abs = rel.as_ref().join(pattern);
@@ -115,3 +216,23 @@ async fn copy(file: &FileMount, dir: impl AsRef<Path>) -> Result<()> {
Ok(())
}
+
+fn uncase(raw_mounts: &[RawFileMount]) -> (Vec<String>, Vec<RawDirectoryPlacement>) {
+ (
+ raw_mounts.iter().filter_map(as_pattern).collect(),
+ raw_mounts.iter().filter_map(as_placement).collect(),
+ )
+}
+
+fn as_pattern(fm: &RawFileMount) -> Option<String> {
+ match fm {
+ RawFileMount::Pattern(p) => Some(p.to_owned()),
+ _ => None,
+ }
+}
+fn as_placement(fm: &RawFileMount) -> Option<RawDirectoryPlacement> {
+ match fm {
+ RawFileMount::Placement(p) => Some(p.clone()),
+ _ => None,
+ }
+}
diff --git a/crates/loader/src/local/config.rs b/crates/loader/src/local/config.rs
index 90941e8373..54eaa1b001 100644
--- a/crates/loader/src/local/config.rs
+++ b/crates/loader/src/local/config.rs
@@ -73,13 +73,36 @@ pub struct RawWasmConfig {
pub environment: Option<HashMap<String, String>>,
/// Files to be mapped inside the Wasm module at runtime.
///
- /// In the local configuration file, this is a vector or file paths or
- /// globs relative to the spin.toml file.
- pub files: Option<Vec<String>>,
+ /// In the local configuration file, this is a vector, each element of which
+ /// is either a file paths or glob relative to the spin.toml file, or a
+ /// mapping of a source path to an absolute mount path in the guest.
+ pub files: Option<Vec<RawFileMount>>,
/// Optional list of HTTP hosts the component is allowed to connect.
pub allowed_http_hosts: Option<Vec<String>>,
}
+/// An entry in the `files` list mapping a source path to an absolute
+/// mount path in the guest.
+#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
+#[serde(deny_unknown_fields, rename_all = "camelCase")]
+pub struct RawDirectoryPlacement {
+ /// The source to mount.
+ pub source: PathBuf,
+ /// Where to mount the directory specified in `source`.
+ pub destination: PathBuf,
+}
+
+/// A specification for a file or set of files to mount in the
+/// Wasm module.
+#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
+#[serde(deny_unknown_fields, rename_all = "camelCase", untagged)]
+pub enum RawFileMount {
+ /// Mount a specified directory at a specified location.
+ Placement(RawDirectoryPlacement),
+ /// Mount a file or set of files at their relative path.
+ Pattern(String),
+}
+
/// Source for the module.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase", untagged)]
diff --git a/crates/loader/src/local/mod.rs b/crates/loader/src/local/mod.rs
index 0ae43b2a1b..16f0704a0b 100644
--- a/crates/loader/src/local/mod.rs
+++ b/crates/loader/src/local/mod.rs
@@ -81,8 +81,8 @@ async fn prepare(
)
.await
.into_iter()
- .map(|x| x.expect("Cannot prepare component."))
- .collect::<Vec<_>>();
+ .collect::<Result<Vec<_>>>()
+ .context("Failed to prepare configuration")?;
Ok(Configuration { info, components })
}
@@ -113,7 +113,7 @@ async fn core(
let id = raw.id;
let mounts = match raw.wasm.files {
- Some(f) => vec![assets::prepare_component(&f, src, &base_dst, &id).await?],
+ Some(f) => assets::prepare_component(&f, src, &base_dst, &id).await?,
None => vec![],
};
let environment = raw.wasm.environment.unwrap_or_default();
diff --git a/crates/publish/src/bindle_writer.rs b/crates/publish/src/bindle_writer.rs
index 81e674b64c..04fe9103cf 100644
--- a/crates/publish/src/bindle_writer.rs
+++ b/crates/publish/src/bindle_writer.rs
@@ -89,7 +89,7 @@ impl BindleWriter {
}
#[derive(Debug, Clone)]
-struct ParcelSource {
+pub struct ParcelSource {
digest: String,
source_path: PathBuf,
}
@@ -116,6 +116,17 @@ impl ParcelSources {
sources: vec![parcel_source],
}
}
+
+ pub fn from_iter(paths: impl Iterator<Item = (String, impl AsRef<Path>)>) -> Self {
+ let sources = paths
+ .map(|(digest, path)| ParcelSource {
+ digest,
+ source_path: path.as_ref().to_owned(),
+ })
+ .collect();
+
+ Self { sources }
+ }
}
fn has_annotation(parcel: &Parcel, key: &str) -> bool {
diff --git a/crates/publish/src/expander.rs b/crates/publish/src/expander.rs
index e743028e8c..d2b6fe5151 100644
--- a/crates/publish/src/expander.rs
+++ b/crates/publish/src/expander.rs
@@ -4,13 +4,13 @@ use anyhow::{Context, Result};
use bindle::{BindleSpec, Condition, Group, Invoice, Label, Parcel};
use path_absolutize::Absolutize;
use sha2::{Digest, Sha256};
-use std::path::Path;
+use std::path::{Path, PathBuf};
use crate::bindle_writer;
use crate::bindle_writer::ParcelSources;
use spin_loader::bindle::config as bindle_schema;
-use spin_loader::local::config::{self as local_schema, RawAppManifestAnyVersion};
+use spin_loader::local::config as local_schema;
/// Expands a file-based application manifest to a Bindle invoice.
pub async fn expand_manifest(
@@ -22,7 +22,7 @@ pub async fn expand_manifest(
.absolutize()
.context("Failed to resolve absoiute path to manifest file")?;
let manifest = spin_loader::local::raw_manifest_from_file(&app_file).await?;
- let RawAppManifestAnyVersion::V0_1_0(manifest) = manifest;
+ let local_schema::RawAppManifestAnyVersion::V0_1_0(manifest) = manifest;
let app_dir = app_dir(&app_file)?;
// * create a new spin.toml-like document where
@@ -50,9 +50,10 @@ pub async fn expand_manifest(
.context("Failed to collect asset files")?;
let asset_parcels = consolidate_asset_parcels(asset_parcels);
// - one parcel to rule them all, and in the Spin app bind them
- let (manifest_parcel, sources) = manifest_parcel(&dest_manifest, &scratch_dir).await?;
+ let manifest_parcel = manifest_parcel(&dest_manifest, &scratch_dir).await?;
- let parcels = itertools::concat([vec![manifest_parcel], wasm_parcels, asset_parcels]);
+ let sourced_parcels = itertools::concat([vec![manifest_parcel], wasm_parcels, asset_parcels]);
+ let (parcels, sources) = split_sources(sourced_parcels);
let bindle_id = bindle_id(&manifest.info)?;
let groups = build_groups(&manifest);
@@ -125,7 +126,7 @@ fn bindle_component_manifest(
async fn wasm_parcels(
manifest: &local_schema::RawAppManifest,
base_dir: &Path,
-) -> Result<Vec<Parcel>> {
+) -> Result<Vec<SourcedParcel>> {
let parcel_futures = manifest.components.iter().map(|c| wasm_parcel(c, base_dir));
let parcels = futures::future::join_all(parcel_futures).await;
parcels.into_iter().collect()
@@ -134,7 +135,7 @@ async fn wasm_parcels(
async fn wasm_parcel(
component: &local_schema::RawComponentManifest,
base_dir: &Path,
-) -> Result<Parcel> {
+) -> Result<SourcedParcel> {
let wasm_file = match &component.source {
local_schema::RawModuleSource::FileReference(path) => path,
local_schema::RawModuleSource::Bindle(_) => {
@@ -151,7 +152,7 @@ async fn wasm_parcel(
async fn asset_parcels(
manifest: &local_schema::RawAppManifest,
base_dir: impl AsRef<Path>,
-) -> Result<Vec<Parcel>> {
+) -> Result<Vec<SourcedParcel>> {
let assets_by_component: Vec<Vec<_>> = manifest
.components
.iter()
@@ -183,7 +184,7 @@ fn collect_assets(
async fn file_parcel_from_mount(
file_mount: &spin_loader::local::assets::FileMount,
component_id: &str,
-) -> Result<Parcel> {
+) -> Result<SourcedParcel> {
let source_file = &file_mount.src;
let media_type = mime_guess::from_path(&source_file)
@@ -197,6 +198,7 @@ async fn file_parcel_from_mount(
&media_type,
)
.await
+ .with_context(|| format!("Failed to assemble parcel from '{}'", source_file.display()))
}
async fn file_parcel(
@@ -204,14 +206,14 @@ async fn file_parcel(
dest_relative_path: impl AsRef<Path>,
component_id: Option<&str>,
media_type: impl Into<String>,
-) -> Result<Parcel> {
+) -> Result<SourcedParcel> {
let digest = file_digest_string(&abs_src)
.with_context(|| format!("Failed to calculate digest for '{}'", abs_src.display()))?;
let size = tokio::fs::metadata(&abs_src).await?.len();
let member_of = component_id.map(|id| vec![group_name_for(id)]);
- Ok(Parcel {
+ let parcel = Parcel {
label: Label {
sha256: digest,
name: dest_relative_path.as_ref().display().to_string(),
@@ -225,13 +227,18 @@ async fn file_parcel(
member_of,
requires: None,
}),
+ };
+
+ Ok(SourcedParcel {
+ parcel,
+ source: abs_src.to_owned(),
})
}
async fn manifest_parcel(
manifest: &bindle_schema::RawAppManifest,
scratch_dir: impl AsRef<Path>,
-) -> Result<(Parcel, ParcelSources)> {
+) -> Result<SourcedParcel> {
let text = toml::to_string_pretty(&manifest).context("Failed to write app manifest to TOML")?;
let bytes = text.as_bytes();
let digest = bytes_digest_string(bytes);
@@ -263,26 +270,27 @@ async fn manifest_parcel(
conditions: None,
};
- let parcel_sources = ParcelSources::single(&digest, &absolute_path);
-
- Ok((parcel, parcel_sources))
+ Ok(SourcedParcel {
+ parcel,
+ source: absolute_path,
+ })
}
-fn consolidate_wasm_parcels(parcels: Vec<Parcel>) -> Vec<Parcel> {
+fn consolidate_wasm_parcels(parcels: Vec<SourcedParcel>) -> Vec<SourcedParcel> {
// We use only the content of Wasm parcels, not their names, so we only
// care if the content is the same.
let mut parcels = parcels;
- parcels.dedup_by_key(|p| p.label.sha256.clone());
+ parcels.dedup_by_key(|p| p.parcel.label.sha256.clone());
parcels
}
-fn consolidate_asset_parcels(parcels: Vec<Parcel>) -> Vec<Parcel> {
+fn consolidate_asset_parcels(parcels: Vec<SourcedParcel>) -> Vec<SourcedParcel> {
let mut consolidated = vec![];
for mut parcel in parcels {
match consolidated
.iter_mut()
- .find(|p| can_consolidate_asset_parcels(p, &parcel))
+ .find(|p: &&mut SourcedParcel| can_consolidate_asset_parcels(&p.parcel, &parcel.parcel))
{
None => consolidated.push(parcel),
Some(existing) => {
@@ -292,8 +300,8 @@ fn consolidate_asset_parcels(parcels: Vec<Parcel>) -> Vec<Parcel> {
//
// TODO: modify can_consolidate to return suitable stuff so we don't
// have to unwrap.
- let existing_conds = existing.conditions.as_mut().unwrap();
- let conds_to_merge = parcel.conditions.as_mut().unwrap();
+ let existing_conds = existing.parcel.conditions.as_mut().unwrap();
+ let conds_to_merge = parcel.parcel.conditions.as_mut().unwrap();
let existing_member_of = existing_conds.member_of.as_mut().unwrap();
let member_of_to_merge = conds_to_merge.member_of.as_mut().unwrap();
existing_member_of.append(member_of_to_merge);
@@ -386,3 +394,18 @@ fn app_dir(app_file: impl AsRef<Path>) -> Result<std::path::PathBuf> {
.to_owned();
Ok(path_buf)
}
+
+struct SourcedParcel {
+ parcel: Parcel,
+ source: PathBuf,
+}
+
+fn split_sources(sourced_parcels: Vec<SourcedParcel>) -> (Vec<Parcel>, ParcelSources) {
+ let sources = sourced_parcels
+ .iter()
+ .map(|sp| (sp.parcel.label.sha256.clone(), &sp.source));
+ let parcel_sources = ParcelSources::from_iter(sources);
+ let parcels = sourced_parcels.into_iter().map(|sp| sp.parcel);
+
+ (parcels.collect(), parcel_sources)
+}
| 118
|
[
"106"
] |
diff --git a/crates/loader/src/local/tests.rs b/crates/loader/src/local/tests.rs
index 00830456c7..649b0ac274 100644
--- a/crates/loader/src/local/tests.rs
+++ b/crates/loader/src/local/tests.rs
@@ -1,4 +1,4 @@
-use crate::local::config::RawModuleSource;
+use crate::local::config::{RawDirectoryPlacement, RawFileMount, RawModuleSource};
use super::*;
use anyhow::Result;
@@ -67,9 +67,19 @@ fn test_manifest() -> Result<()> {
assert_eq!(test_env.get("env2").unwrap(), "second");
let test_files = &test_component.wasm.files.as_ref().unwrap();
- assert_eq!(test_files.len(), 2);
- assert_eq!(test_files[0], "file.txt");
- assert_eq!(test_files[1], "subdir/another.txt");
+ assert_eq!(test_files.len(), 3);
+ assert_eq!(test_files[0], RawFileMount::Pattern("file.txt".to_owned()));
+ assert_eq!(
+ test_files[1],
+ RawFileMount::Placement(RawDirectoryPlacement {
+ source: PathBuf::from("valid-with-files"),
+ destination: PathBuf::from("/vwf"),
+ })
+ );
+ assert_eq!(
+ test_files[2],
+ RawFileMount::Pattern("subdir/another.txt".to_owned())
+ );
let b = match cfg.components[1].source.clone() {
RawModuleSource::Bindle(b) => b,
diff --git a/crates/loader/tests/valid-manifest.toml b/crates/loader/tests/valid-manifest.toml
index f543f4e9dc..c4c3b387f0 100644
--- a/crates/loader/tests/valid-manifest.toml
+++ b/crates/loader/tests/valid-manifest.toml
@@ -6,7 +6,7 @@ trigger = {type = "http", base = "/"}
version = "6.11.2"
[[component]]
-files = ["file.txt", "subdir/another.txt"]
+files = ["file.txt", { source = "valid-with-files", destination = "/vwf" }, "subdir/another.txt"]
id = "four-lights"
source = "path/to/wasm/file.wasm"
[component.trigger]
|
95f9da2a41aded597a437ad041a5a13ab19604ee
|
6651c2ca8d4592a41e1816e70f3af1cb47aee7d5
|
Add TLS support for the HTTP trigger
The new HTTP trigger should have support for TLS — https://github.com/fermyon/spin/blob/751cda3ee182675b00f05bfd3f18c05086978bf2/crates/http/src/lib.rs#L33
|
2022-02-28T18:54:55Z
|
fermyon__spin-114
|
fermyon/spin
|
0.1
|
diff --git a/Cargo.lock b/Cargo.lock
index 0e3d6952c3..066f728539 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1298,7 +1298,9 @@ checksum = "d87c48c02e0dc5e3b849a2041db3029fd066650f8f717c07bf8ed78ccb895cac"
dependencies = [
"http 0.2.6",
"hyper",
+ "log",
"rustls 0.20.3",
+ "rustls-native-certs",
"tokio",
"tokio-rustls 0.23.2",
]
@@ -2419,7 +2421,7 @@ dependencies = [
"percent-encoding 2.1.0",
"pin-project-lite",
"rustls 0.20.3",
- "rustls-pemfile",
+ "rustls-pemfile 0.2.1",
"serde",
"serde_json",
"serde_urlencoded",
@@ -2503,6 +2505,18 @@ dependencies = [
"webpki 0.22.0",
]
+[[package]]
+name = "rustls-native-certs"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5ca9ebdfa27d3fc180e42879037b5338ab1c040c06affd00d8338598e7800943"
+dependencies = [
+ "openssl-probe",
+ "rustls-pemfile 0.2.1",
+ "schannel",
+ "security-framework",
+]
+
[[package]]
name = "rustls-pemfile"
version = "0.2.1"
@@ -2512,6 +2526,15 @@ dependencies = [
"base64 0.13.0",
]
+[[package]]
+name = "rustls-pemfile"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ee86d63972a7c661d1536fefe8c3c8407321c3df668891286de28abcd087360"
+dependencies = [
+ "base64 0.13.0",
+]
+
[[package]]
name = "ryu"
version = "1.0.9"
@@ -2913,14 +2936,19 @@ dependencies = [
"bytes 1.1.0",
"ctrlc",
"futures",
+ "futures-util",
"http 0.2.6",
"hyper",
+ "hyper-rustls",
"indexmap",
"miniserde",
+ "rustls-pemfile 0.3.0",
"serde",
"spin-config",
"spin-engine",
+ "tls-listener",
"tokio",
+ "tokio-rustls 0.23.2",
"tracing",
"tracing-futures",
"tracing-subscriber 0.3.8",
@@ -3219,6 +3247,20 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c"
+[[package]]
+name = "tls-listener"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "42257668593ac35c772fa8bfb4bfd4d357298d5a6b816cb9a4462ec3b7627d26"
+dependencies = [
+ "futures-util",
+ "hyper",
+ "pin-project-lite",
+ "thiserror",
+ "tokio",
+ "tokio-rustls 0.23.2",
+]
+
[[package]]
name = "tokio"
version = "1.17.0"
diff --git a/Makefile b/Makefile
index 29f6875e90..32b19a6e14 100644
--- a/Makefile
+++ b/Makefile
@@ -1,4 +1,5 @@
LOG_LEVEL ?= spin=trace
+CERT_NAME ?= local
.PHONY: build
build:
@@ -9,3 +10,10 @@ test:
RUST_LOG=$(LOG_LEVEL) cargo test --all -- --nocapture
cargo clippy --all-targets --all-features -- -D warnings
cargo fmt --all -- --check
+
+# simple convenience for developing with TLS
+.PHONY: tls
+tls: ${CERT_NAME}.crt.pem
+
+$(CERT_NAME).crt.pem:
+ openssl req -newkey rsa:2048 -nodes -keyout $(CERT_NAME).key.pem -x509 -days 365 -out $(CERT_NAME).crt.pem
\ No newline at end of file
diff --git a/crates/http/Cargo.toml b/crates/http/Cargo.toml
index a8e7744971..f574c584b8 100644
--- a/crates/http/Cargo.toml
+++ b/crates/http/Cargo.toml
@@ -13,13 +13,18 @@ async-trait = "0.1"
bytes = "1.1"
ctrlc = "3.2.1"
futures = "0.3"
+futures-util = "0.3.8"
http = "0.2"
hyper = { version = "0.14", features = [ "full" ] }
+hyper-rustls = { version = "0.23.0" }
indexmap = "1.6"
serde = { version = "1.0", features = [ "derive" ] }
spin-config = { path = "../config" }
spin-engine = { path = "../engine" }
+tls-listener = { version = "0.4.0", features = ["rustls", "hyper-h1", "hyper-h2"] }
tokio = { version = "1.10", features = [ "full" ] }
+tokio-rustls = { version = "0.23.2" }
+rustls-pemfile = "0.3.0"
tracing = { version = "0.1", features = [ "log" ] }
tracing-futures = "0.2"
tracing-subscriber = { version = "0.3.7", features = [ "env-filter" ] }
diff --git a/crates/http/src/lib.rs b/crates/http/src/lib.rs
index 2defb03235..fc833b0d35 100644
--- a/crates/http/src/lib.rs
+++ b/crates/http/src/lib.rs
@@ -2,13 +2,16 @@
mod routes;
mod spin;
+mod tls;
mod wagi;
use crate::wagi::WagiHttpExecutor;
-use anyhow::{Error, Result};
+use anyhow::{Context, Error, Result};
use async_trait::async_trait;
-use http::{StatusCode, Uri};
+use futures_util::stream::StreamExt;
+use http::{uri::Scheme, StatusCode, Uri};
use hyper::{
+ server::accept,
server::conn::AddrStream,
service::{make_service_fn, service_fn},
Body, Request, Response, Server,
@@ -18,7 +21,11 @@ use spin::SpinHttpExecutor;
use spin_config::{ApplicationTrigger, Configuration, CoreComponent, TriggerConfig};
use spin_engine::{Builder, ExecutionContextConfiguration};
use spin_http::SpinHttpData;
-use std::{net::SocketAddr, sync::Arc};
+use std::{future::ready, net::SocketAddr, sync::Arc};
+pub use tls::TlsConfig;
+use tls_listener::TlsListener;
+use tokio::net::{TcpListener, TcpStream};
+use tokio_rustls::server::TlsStream;
use tracing::log;
wit_bindgen_wasmtime::import!("wit/ephemeral/spin-http.wit");
@@ -27,8 +34,6 @@ type ExecutionContext = spin_engine::ExecutionContext<SpinHttpData>;
type RuntimeContext = spin_engine::RuntimeContext<SpinHttpData>;
/// The Spin HTTP trigger.
-/// TODO
-/// This should contain TLS configuration.
///
/// Could this contain a list of multiple HTTP applications?
/// (there could be a field apps: HashMap<String, Config>, where
@@ -40,6 +45,8 @@ pub struct HttpTrigger {
pub address: String,
/// Configuration for the application.
pub app: Configuration<CoreComponent>,
+ /// TLS configuration for the server.
+ tls: Option<TlsConfig>,
/// Router.
router: Router,
/// Spin execution context.
@@ -52,6 +59,7 @@ impl HttpTrigger {
address: String,
app: Configuration<CoreComponent>,
wasmtime: Option<wasmtime::Config>,
+ tls: Option<TlsConfig>,
) -> Result<Self> {
let mut config = ExecutionContextConfiguration::new(app.clone());
if let Some(wasmtime) = wasmtime {
@@ -65,6 +73,7 @@ impl HttpTrigger {
Ok(Self {
address,
app,
+ tls,
router,
engine,
})
@@ -96,76 +105,103 @@ impl HttpTrigger {
let res = match executor {
spin_config::HttpExecutor::Spin => {
- SpinHttpExecutor::execute(
- &self.engine,
- &c.id,
- &app_trigger.base,
- &trigger.route,
- req,
- addr,
- &(),
- )
- .await
+ let executor = SpinHttpExecutor;
+ executor
+ .execute(
+ &self.engine,
+ &c.id,
+ &app_trigger.base,
+ &trigger.route,
+ req,
+ addr,
+ )
+ .await
}
spin_config::HttpExecutor::Wagi(wagi_config) => {
- WagiHttpExecutor::execute(
- &self.engine,
- &c.id,
- &app_trigger.base,
- &trigger.route,
- req,
- addr,
- wagi_config,
- )
- .await
+ let executor = WagiHttpExecutor {
+ wagi_config: wagi_config.clone(),
+ };
+ executor
+ .execute(
+ &self.engine,
+ &c.id,
+ &app_trigger.base,
+ &trigger.route,
+ req,
+ addr,
+ )
+ .await
}
};
match res {
Ok(res) => Ok(res),
Err(e) => {
log::error!("Error processing request: {:?}", e);
- Ok(Self::internal_error())
+ Self::internal_error(None)
}
}
}
- Err(_) => Ok(Self::not_found()),
+ Err(_) => Self::not_found(),
},
}
}
/// Create an HTTP 500 response.
- fn internal_error() -> Response<Body> {
- let mut err = Response::default();
- *err.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
- err
+ fn internal_error(body: Option<&str>) -> Result<Response<Body>> {
+ let body = match body {
+ Some(body) => Body::from(body.as_bytes().to_vec()),
+ None => Body::empty(),
+ };
+
+ Ok(Response::builder()
+ .status(StatusCode::INTERNAL_SERVER_ERROR)
+ .body(body)?)
}
/// Create an HTTP 404 response.
- fn not_found() -> Response<Body> {
+ fn not_found() -> Result<Response<Body>> {
let mut not_found = Response::default();
*not_found.status_mut() = StatusCode::NOT_FOUND;
- not_found
+ Ok(not_found)
}
/// Run the HTTP trigger indefinitely.
pub async fn run(&self) -> Result<()> {
+ match self.tls.as_ref() {
+ Some(tls) => self.serve_tls(tls).await?,
+ None => self.serve().await?,
+ }
+ Ok(())
+ }
+
+ async fn serve(&self) -> Result<()> {
let mk_svc = make_service_fn(move |addr: &AddrStream| {
let t = self.clone();
let addr = addr.remote_addr();
async move {
- Ok::<_, Error>(service_fn(move |req| {
+ Ok::<_, Error>(service_fn(move |mut req| {
let t2 = t.clone();
- async move { t2.handle(req, addr).await }
+ async move {
+ match set_req_uri(&mut req, Scheme::HTTPS) {
+ Ok(()) => t2.handle(req, addr).await,
+ Err(e) => {
+ log::warn!("{}", e);
+ Self::internal_error(Some("Socket connection error"))
+ }
+ }
+ }
}))
}
});
+ let addr: SocketAddr = self.address.parse()?;
+
+ log::info!("Serving HTTP on address {:?}", addr);
+
let shutdown_signal = on_ctrl_c()?;
- let addr: SocketAddr = self.address.parse()?;
- log::info!("Serving on address {:?}", addr);
Server::bind(&addr)
.serve(mk_svc)
.with_graceful_shutdown(async {
@@ -177,6 +213,88 @@ impl HttpTrigger {
Ok(())
}
+
+ async fn serve_tls(&self, tls: &TlsConfig) -> Result<()> {
+ let mk_svc = make_service_fn(move |conn: &TlsStream<TcpStream>| {
+ let (inner, _) = conn.get_ref();
+ let addr_res = inner.peer_addr().map_err(|e| e.to_string());
+ let t = self.clone();
+
+ Box::pin(async move {
+ Ok::<_, Error>(service_fn(move |mut req| {
+ let t2 = t.clone();
+ let a_res = addr_res.clone();
+
+ async move {
+ match set_req_uri(&mut req, Scheme::HTTPS) {
+ Ok(()) => {}
+ Err(e) => {
+ log::warn!("{}", e);
+ return Self::internal_error(Some("Socket connection error"));
+ }
+ }
+
+ match a_res {
+ Ok(addr) => t2.handle(req, addr).await,
+ Err(e) => {
+ log::warn!("Socket connection error on new connection: {}", e);
+ Self::internal_error(Some("Socket connection error"))
+ }
+ }
+ }
+ }))
+ })
+ });
+
+ let addr: SocketAddr = self.address.parse()?;
+ let listener = TcpListener::bind(&addr).await?;
+
+ let tls_srv_cfg = tls.server_config()?;
+
+ let incoming =
+ accept::from_stream(TlsListener::new(tls_srv_cfg, listener).filter(|conn| {
+ if let Err(err) = conn {
+ log::warn!("{:?}", err);
+ ready(false)
+ } else {
+ ready(true)
+ }
+ }));
+
+ log::info!("Serving HTTPS on address {:?}", addr);
+
+ let shutdown_signal = on_ctrl_c()?;
+
+ Server::builder(incoming)
+ .serve(mk_svc)
+ .with_graceful_shutdown(async {
+ shutdown_signal.await.ok();
+ })
+ .await?;
+
+ log::debug!("User requested shutdown: exiting");
+
+ Ok(())
+ }
+}
+
+fn set_req_uri(req: &mut Request<Body>, scheme: Scheme) -> Result<()> {
+ const DEFAULT_HOST: &str = "localhost";
+
+ let authority_hdr = req
+ .headers()
+ .get(http::header::HOST)
+ .map(|h| h.to_str().context("Expected UTF8 header value (authority)"))
+ .unwrap_or(Ok(DEFAULT_HOST))?;
+ let uri = req.uri().clone();
+ let mut parts = uri.into_parts();
+ parts.authority = authority_hdr
+ .parse()
+ .map(Option::Some)
+ .map_err(|e| anyhow::anyhow!("Invalid authority {:?}", e))?;
+ parts.scheme = Some(scheme);
+ *req.uri_mut() = Uri::from_parts(parts).unwrap();
+ Ok(())
}
fn on_ctrl_c() -> Result<impl std::future::Future<Output = Result<(), tokio::task::JoinError>>> {
@@ -203,7 +321,6 @@ pub(crate) fn default_headers(
raw: &str,
base: &str,
host: &str,
- // scheme: &str,
) -> Result<Vec<(String, String)>> {
let mut res = vec![];
let abs_path = uri
@@ -213,8 +330,8 @@ pub(crate) fn default_headers(
let path_info = RoutePattern::from(base, raw).relative(abs_path)?;
- // TODO: check if TLS is enabled and change the scheme to "https".
- let scheme = "http";
+ let scheme = uri.scheme_str().unwrap_or("http");
+
let full_url = format!("{}://{}{}", scheme, host, abs_path);
let matched_route = RoutePattern::sanitize_with_base(base, raw);
@@ -239,17 +356,14 @@ pub(crate) fn default_headers(
/// All HTTP executors must implement this trait.
#[async_trait]
pub(crate) trait HttpExecutor: Clone + Send + Sync + 'static {
- /// Configuration specific to the implementor of this trait.
- type Config;
-
async fn execute(
+ &self,
engine: &ExecutionContext,
component: &str,
base: &str,
raw_route: &str,
req: Request<Body>,
client_addr: SocketAddr,
- config: &Self::Config,
) -> Result<Response<Body>>;
}
@@ -310,10 +424,9 @@ mod tests {
let default_headers = crate::default_headers(req.uri(), trigger_route, base, host)?;
- // TODO: we currently replace the scheme with HTTP. When TLS is supported, this should be fixed.
assert_eq!(
search(X_FULL_URL_HEADER, &default_headers).unwrap(),
- "http://fermyon.dev/base/foo/bar?key1=value1&key2=value2".to_string()
+ "https://fermyon.dev/base/foo/bar?key1=value1&key2=value2".to_string()
);
assert_eq!(
search(PATH_INFO_HEADER, &default_headers).unwrap(),
@@ -363,7 +476,7 @@ mod tests {
// TODO: we currently replace the scheme with HTTP. When TLS is supported, this should be fixed.
assert_eq!(
search(X_FULL_URL_HEADER, &default_headers).unwrap(),
- "http://fermyon.dev/foo/bar?key1=value1&key2=value2".to_string()
+ "https://fermyon.dev/foo/bar?key1=value1&key2=value2".to_string()
);
assert_eq!(
search(PATH_INFO_HEADER, &default_headers).unwrap(),
@@ -433,7 +546,7 @@ mod tests {
let components = vec![component];
let cfg = Configuration::<CoreComponent> { info, components };
- let trigger = HttpTrigger::new("".to_string(), cfg, None).await?;
+ let trigger = HttpTrigger::new("".to_string(), cfg, None, None).await?;
let body = Body::from("Fermyon".as_bytes().to_vec());
let req = http::Request::builder()
@@ -490,7 +603,7 @@ mod tests {
let components = vec![component];
let cfg = Configuration::<CoreComponent> { info, components };
- let trigger = HttpTrigger::new("".to_string(), cfg, None).await?;
+ let trigger = HttpTrigger::new("".to_string(), cfg, None, None).await?;
let body = Body::from("Fermyon".as_bytes().to_vec());
let req = http::Request::builder()
diff --git a/crates/http/src/spin.rs b/crates/http/src/spin.rs
index 1e53467ff0..3d52ec990a 100644
--- a/crates/http/src/spin.rs
+++ b/crates/http/src/spin.rs
@@ -15,16 +15,14 @@ pub struct SpinHttpExecutor;
#[async_trait]
impl HttpExecutor for SpinHttpExecutor {
- type Config = ();
-
async fn execute(
+ &self,
engine: &ExecutionContext,
component: &str,
base: &str,
raw_route: &str,
req: Request<Body>,
_client_addr: SocketAddr,
- _config: &Self::Config,
) -> Result<Response<Body>> {
log::trace!(
"Executing request using the Spin executor for component {}",
diff --git a/crates/http/src/tls.rs b/crates/http/src/tls.rs
new file mode 100644
index 0000000000..648299584f
--- /dev/null
+++ b/crates/http/src/tls.rs
@@ -0,0 +1,46 @@
+use rustls_pemfile::{certs, pkcs8_private_keys};
+use std::{
+ fs, io,
+ path::{Path, PathBuf},
+ sync::Arc,
+};
+use tokio_rustls::{rustls, TlsAcceptor};
+
+/// Tls configuration for the server.
+#[derive(Clone)]
+pub struct TlsConfig {
+ /// Path to TLS certificate.
+ pub cert_path: PathBuf,
+ /// Path to TLS key.
+ pub key_path: PathBuf,
+}
+
+impl TlsConfig {
+ // Create a TLS acceptor from server config.
+ pub(super) fn server_config(&self) -> anyhow::Result<TlsAcceptor> {
+ let certs = load_certs(&self.cert_path)?;
+ let mut keys = load_keys(&self.key_path)?;
+
+ let cfg = rustls::ServerConfig::builder()
+ .with_safe_defaults()
+ .with_no_client_auth()
+ .with_single_cert(certs, keys.remove(0))
+ .map_err(|e| anyhow::anyhow!("{}", e))?;
+
+ Ok(Arc::new(cfg).into())
+ }
+}
+
+// Load public certificate from file.
+fn load_certs(path: impl AsRef<Path>) -> io::Result<Vec<rustls::Certificate>> {
+ certs(&mut io::BufReader::new(fs::File::open(path)?))
+ .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "invalid cert"))
+ .map(|mut certs| certs.drain(..).map(rustls::Certificate).collect())
+}
+
+// Load private key from file.
+fn load_keys(path: impl AsRef<Path>) -> io::Result<Vec<rustls::PrivateKey>> {
+ pkcs8_private_keys(&mut io::BufReader::new(fs::File::open(path)?))
+ .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "invalid key"))
+ .map(|mut keys| keys.drain(..).map(rustls::PrivateKey).collect())
+}
diff --git a/crates/http/src/wagi.rs b/crates/http/src/wagi.rs
index 0fa66a6fd2..0d5ebbc882 100644
--- a/crates/http/src/wagi.rs
+++ b/crates/http/src/wagi.rs
@@ -16,20 +16,20 @@ use tracing::log;
use wasi_common::pipe::{ReadPipe, WritePipe};
#[derive(Clone)]
-pub struct WagiHttpExecutor;
+pub struct WagiHttpExecutor {
+ pub wagi_config: WagiConfig,
+}
#[async_trait]
impl HttpExecutor for WagiHttpExecutor {
- type Config = WagiConfig;
-
async fn execute(
+ &self,
engine: &ExecutionContext,
component: &str,
base: &str,
raw_route: &str,
req: Request<Body>,
client_addr: SocketAddr,
- wagi_config: &Self::Config,
) -> Result<Response<Body>> {
log::trace!(
"Executing request using the Wagi executor for component {}",
@@ -72,6 +72,7 @@ impl HttpExecutor for WagiHttpExecutor {
.unwrap_or(&default_host)
.as_bytes(),
)?;
+
// Add the default Spin headers.
// Note that this overrides any existing headers previously set by Wagi.
for (k, v) in crate::default_headers(&parts.uri, raw_route, base, host)? {
@@ -87,11 +88,11 @@ impl HttpExecutor for WagiHttpExecutor {
)?;
let start = instance
- .get_func(&mut store, &wagi_config.entrypoint)
+ .get_func(&mut store, &self.wagi_config.entrypoint)
.ok_or_else(|| {
anyhow::anyhow!(
"No such function '{}' in {}",
- wagi_config.entrypoint,
+ self.wagi_config.entrypoint,
component
)
})?;
diff --git a/src/commands/up.rs b/src/commands/up.rs
index edc6de71a9..d354c5719a 100644
--- a/src/commands/up.rs
+++ b/src/commands/up.rs
@@ -1,6 +1,6 @@
use anyhow::{bail, Result};
use spin_config::{Configuration, CoreComponent};
-use spin_http_engine::HttpTrigger;
+use spin_http_engine::{HttpTrigger, TlsConfig};
use std::path::PathBuf;
use structopt::{clap::AppSettings, StructOpt};
@@ -9,6 +9,12 @@ const BINDLE_ID_OPT: &str = "BINDLE_ID";
const BINDLE_SERVER_URL_OPT: &str = "BINDLE_SERVER_URL";
const BINDLE_URL_ENV: &str = "BINDLE_URL";
+const TLS_CERT_FILE_OPT: &str = "TLS_CERT_FILE";
+const TLS_KEY_FILE_OPT: &str = "TLS_KEY_FILE";
+
+const TLS_CERT_ENV_VAR: &str = "SPIN_TLS_CERT";
+const TLS_KEY_ENV_VAR: &str = "SPIN_TLS_KEY";
+
/// Start the Fermyon HTTP runtime.
#[derive(StructOpt, Debug)]
#[structopt(
@@ -50,6 +56,24 @@ pub struct UpCommand {
/// Pass an environment variable (key=value) to all components of the application.
#[structopt(long = "env", short = "e", parse(try_from_str = parse_env_var))]
env: Vec<(String, String)>,
+
+ /// The path to the certificate to use for https, if this is not set, normal http will be used. The cert should be in PEM format
+ #[structopt(
+ name = TLS_CERT_FILE_OPT,
+ long = "tls-cert",
+ env = TLS_CERT_ENV_VAR,
+ requires = TLS_KEY_FILE_OPT,
+ )]
+ pub tls_cert: Option<PathBuf>,
+
+ /// The path to the certificate key to use for https, if this is not set, normal http will be used. The key should be in PKCS#8 format
+ #[structopt(
+ name = TLS_KEY_FILE_OPT,
+ long = "tls-key",
+ env = TLS_KEY_ENV_VAR,
+ requires = TLS_CERT_FILE_OPT,
+ )]
+ pub tls_key: Option<PathBuf>,
}
impl UpCommand {
@@ -65,7 +89,24 @@ impl UpCommand {
};
append_env(&mut app, &self.env)?;
- let trigger = HttpTrigger::new(self.address, app, None).await?;
+ let tls = match (self.tls_key, self.tls_cert) {
+ (Some(key_path), Some(cert_path)) => {
+ if !cert_path.is_file() {
+ bail!("TLS certificate file does not exist or is not a file")
+ }
+ if !key_path.is_file() {
+ bail!("TLS key file does not exist or is not a file")
+ }
+ Some(TlsConfig {
+ cert_path,
+ key_path,
+ })
+ }
+ (None, None) => None,
+ _ => unreachable!(),
+ };
+
+ let trigger = HttpTrigger::new(self.address, app, None, tls).await?;
trigger.run().await
}
}
| 114
|
[
"33"
] |
diff --git a/crates/http/tests/local.crt.pem b/crates/http/tests/local.crt.pem
new file mode 100644
index 0000000000..efd51f6707
--- /dev/null
+++ b/crates/http/tests/local.crt.pem
@@ -0,0 +1,17 @@
+-----BEGIN CERTIFICATE-----
+MIICujCCAaICCQClexHj2O4K/TANBgkqhkiG9w0BAQsFADAfMQswCQYDVQQGEwJV
+UzEQMA4GA1UECgwHRmVybXlvbjAeFw0yMjAyMjUxNzQ3MTFaFw0yMzAyMjUxNzQ3
+MTFaMB8xCzAJBgNVBAYTAlVTMRAwDgYDVQQKDAdGZXJteW9uMIIBIjANBgkqhkiG
+9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwMbUZ2eoIaJfgcBJ2fILUViWYApnA9SU+Ruf
+nm6DNm9Gy5+YThqxd/0mhbPwYVkfi2/3UddWDl3VPOAYcvYoHDqH0tHm10wo+UzY
+DDcNZB9enLRfGCv9Fful4bqNd3Vtx2xNwc8+F0WiljtYeMc+9wp7M5WWbKJqzKPe
+VQBADRlfGoG3jCLGaQ2fyVp/73nWdqbbluWJopxHph7v1alb/BxLcDi/tjWKgZut
+Vr9ZtBBPDSjRbfjHarn6pibYZAWgzanpfsaSBdbpVNn1MQ/gNXIHmNFwfbsN0V+3
+LN/Z4VNZrkc+C7CjGhJOcBj0xtrSDhoHnOmDS/z+lBUdlNOUrQIDAQABMA0GCSqG
+SIb3DQEBCwUAA4IBAQAOnRPnUJoEE8s9+ADUpKkWBXFCiRajtBSBDNDX3phRPwly
+q2zG+gXyV+Axx1qvsis9yXQBF9DcD+lx0rEgGzQjYGfmEA45E8Co2Tih2ON7JkCu
+bYoT+wMkgfOMci/S2BBOJ+d0LI3K0b1qDfc4KwHe6g3p5ywuEBFOaWKiMemJyywd
+zpoD6QmcQ9qlp5/2pf12bNRUIdXe5+vMU3qVIZcWM49u04L2/Swyc6EFXfEtnp/m
+6184isfCkc3egMvqEfrKUaf0lgNzCksmRD9sLF8wWaV4lcidzsNDdU47EPFutVMU
+3iLgXAhmRuZ+eoBf56QkzVTQWnCYQdlGwZp1Fcoj
+-----END CERTIFICATE-----
diff --git a/crates/http/tests/local.key.pem b/crates/http/tests/local.key.pem
new file mode 100644
index 0000000000..6b080db693
--- /dev/null
+++ b/crates/http/tests/local.key.pem
@@ -0,0 +1,28 @@
+-----BEGIN PRIVATE KEY-----
+MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDAxtRnZ6ghol+B
+wEnZ8gtRWJZgCmcD1JT5G5+eboM2b0bLn5hOGrF3/SaFs/BhWR+Lb/dR11YOXdU8
+4Bhy9igcOofS0ebXTCj5TNgMNw1kH16ctF8YK/0V+6Xhuo13dW3HbE3Bzz4XRaKW
+O1h4xz73CnszlZZsomrMo95VAEANGV8agbeMIsZpDZ/JWn/vedZ2ptuW5YminEem
+Hu/VqVv8HEtwOL+2NYqBm61Wv1m0EE8NKNFt+MdqufqmJthkBaDNqel+xpIF1ulU
+2fUxD+A1cgeY0XB9uw3RX7cs39nhU1muRz4LsKMaEk5wGPTG2tIOGgec6YNL/P6U
+FR2U05StAgMBAAECggEAfpcSjATJp6yUwwOee3wyamyd8tth4mYKnbrCCqvPhkN0
+XeqjfUaSG5UlYs9SntqDmHEiG6AoZq6/hIY0B+oVVNQqtQoZaHAex/bqOLs+E+11
+l7nqaFkajQD/YUe79iIqwLYiKY8J2wZjSfwWkNlmQ5uiY7FrYlMVhuRk77SGWxKW
+UbWfgTTMgEWIK6bU77FShQ7b0px5ZIulRPQeRaH8USdx0yktqUMwUakIrNyZ64u+
+Gx9k4ma2bCmbWxGlCEp0EQsYOlWDBeKu3Elq2g48KmADzbjvKlS7S/0fhcVqi2dE
+Fj0BrmzxWjPzJwqxA6Z/8tykqzL5Nr6tOm0e6ZhBEQKBgQDhfy83jLfIWLt3rMcx
+dFA4TGFSEUVJE9ESV0Za5zriLeGzM66JGut+Bph9Kk7XmDt+q3ewFJv7oDVibhzG
+4nit+TakfSMWUAronsf2wQuUvpE6rNoZlWjhd7AE5f/eBZTYhNm5cp7ujGwnEn47
+vmfSVev+1yQcEUeV10OSWWaCrwKBgQDa2pEwps6htnZqiZsJP86LfxbTA1P+BgsV
+nFvVkcCT0Uy7V0pSSdA82Ua/1KfcQ3BAJiBkINSL6Sob1+3lSQTeTHLVbXySacnh
+c7UDDoayWJxtYNyjJeBzrjlZCDIkipJqz26pGfIhxePwVgbj30O/EB55y44gkxqn
+JIvqIWBlYwKBgQDVqR4DI3lMAw92QKbo7A3KmkyoZybgLD+wgjNulKQNhW3Sz4hz
+7qbt3bAFAN59l4ff6PZaR9zYWh/bKPxpUlMIfRdSWiOx05vSeAh+fMHNaZfQIdHx
+5cjfwfltWsTLCTzUv2RRPBLtcu5TQ0mKsEpNWQ5ohE95rMHIb5ReCgmAjwKBgCb6
+NlGL49E5Re3DhDEphAekItSCCzt6qA65QkHPK5Un+ZqD+WCedM/hgpA3t42rFRrX
+r30lu7UPWciLtHrZflx5ERqh3UXWQXY9vUdGFwc8cN+qGKGV5Vu089G/e+62H02W
+lAbZ8B3DuMzdBW0gHliw7jyS3EVA7cZG5ARW3WwxAoGAW+FkrJKsPyyScHBdu/LD
+GeDMGRBRBdthXVbtB7xkzi2Tla4TywlHTm32rK3ywtoBxzvhlxbVnbBODMO/83xZ
+DKjq2leuKfXUNsuMEre7uhhs7ezEM6QfiKTTosD/D8Z3S8AA4q1NKu3iEBUjtXcS
+FSaIdbf6aHPcvbRB9cDv5ho=
+-----END PRIVATE KEY-----
diff --git a/tests/integration.rs b/tests/integration.rs
index e6857aabf5..37a04fe0e6 100644
--- a/tests/integration.rs
+++ b/tests/integration.rs
@@ -386,7 +386,7 @@ mod integration_tests {
Ok(_) => break,
Err(_) => {
wait_count += 1;
- sleep(Duration::from_secs(1)).await;
+ sleep(Duration::from_secs(120)).await;
}
}
}
|
95f9da2a41aded597a437ad041a5a13ab19604ee
|
|
2782bb320dbb4a671691acab2d4c20f8191c1806
|
Verify apiVersion
I didn't know what `apiVersion` was meant to be, so in my test app I used `1.0.0`. Looking at the template, that uses `0.1.0`, so my guess was wrong - but still seems to work.
If the `apiVersion` isn't recognised, we must reject the manifest. Otherwise mistakes like mine will proliferate and we'll be in the position that any new version we adopt risks breaking _someone_.
|
2022-02-22T23:29:38Z
|
fermyon__spin-97
|
fermyon/spin
|
0.1
|
diff --git a/crates/loader/src/local/config.rs b/crates/loader/src/local/config.rs
index 9f3d863308..90941e8373 100644
--- a/crates/loader/src/local/config.rs
+++ b/crates/loader/src/local/config.rs
@@ -8,6 +8,15 @@ use serde::{Deserialize, Serialize};
use spin_config::{ApplicationTrigger, TriggerConfig};
use std::{collections::HashMap, path::PathBuf};
+/// Container for any version of the manifest.
+#[derive(Clone, Debug, Deserialize, Serialize)]
+#[serde(tag = "apiVersion")]
+pub enum RawAppManifestAnyVersion {
+ /// A manifest with API version 0.1.0.
+ #[serde(rename = "0.1.0")]
+ V0_1_0(RawAppManifest),
+}
+
/// Application configuration local file format.
/// This is the main structure spin.toml deserializes into.
#[derive(Clone, Debug, Deserialize, Serialize)]
@@ -26,8 +35,6 @@ pub struct RawAppManifest {
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct RawAppInformation {
- /// Spin API version.
- pub api_version: String,
/// Name of the application.
pub name: String,
/// Version of the application.
diff --git a/crates/loader/src/local/mod.rs b/crates/loader/src/local/mod.rs
index 24cb0d919f..0ae43b2a1b 100644
--- a/crates/loader/src/local/mod.rs
+++ b/crates/loader/src/local/mod.rs
@@ -10,8 +10,8 @@ pub mod config;
#[cfg(test)]
mod tests;
-use anyhow::{Context, Result};
-use config::{RawAppInformation, RawAppManifest, RawComponentManifest};
+use anyhow::{anyhow, Context, Result};
+use config::{RawAppInformation, RawAppManifest, RawAppManifestAnyVersion, RawComponentManifest};
use futures::future;
use path_absolutize::Absolutize;
use spin_config::{
@@ -35,21 +35,32 @@ pub async fn from_file(
.context("Failed to resolve absolute path to manifest file")?;
let manifest = raw_manifest_from_file(&app).await?;
- prepare(manifest, app, base_dst).await
+ prepare_any_version(manifest, app, base_dst).await
}
/// Reads the spin.toml file as a raw manifest.
-pub async fn raw_manifest_from_file(app: &impl AsRef<Path>) -> Result<RawAppManifest> {
+pub async fn raw_manifest_from_file(app: &impl AsRef<Path>) -> Result<RawAppManifestAnyVersion> {
let mut buf = vec![];
File::open(app.as_ref())
.await?
.read_to_end(&mut buf)
.await
- .with_context(|| format!("Cannot read manifest file from {:?}", app.as_ref()))?;
- let manifest: RawAppManifest = toml::from_slice(&buf)?;
+ .with_context(|| anyhow!("Cannot read manifest file from {:?}", app.as_ref()))?;
+
+ let manifest: RawAppManifestAnyVersion = toml::from_slice(&buf)?;
Ok(manifest)
}
+async fn prepare_any_version(
+ raw: RawAppManifestAnyVersion,
+ src: impl AsRef<Path>,
+ base_dst: Option<PathBuf>,
+) -> Result<Configuration<CoreComponent>> {
+ match raw {
+ RawAppManifestAnyVersion::V0_1_0(raw) => prepare(raw, src, base_dst).await,
+ }
+}
+
async fn prepare(
raw: RawAppManifest,
src: impl AsRef<Path>,
@@ -59,6 +70,7 @@ async fn prepare(
Some(d) => d,
None => tempfile::tempdir()?.into_path(),
};
+
let info = info(raw.info, &src);
let components = future::join_all(
@@ -124,7 +136,7 @@ async fn core(
/// Convert the raw application information from the spin.toml manifest to the standard configuration.
fn info(raw: RawAppInformation, src: impl AsRef<Path>) -> ApplicationInformation {
ApplicationInformation {
- api_version: raw.api_version,
+ api_version: "0.1.0".to_owned(),
name: raw.name,
version: raw.version,
description: raw.description,
diff --git a/crates/publish/src/expander.rs b/crates/publish/src/expander.rs
index 77c5b89ff3..e743028e8c 100644
--- a/crates/publish/src/expander.rs
+++ b/crates/publish/src/expander.rs
@@ -10,7 +10,7 @@ use crate::bindle_writer;
use crate::bindle_writer::ParcelSources;
use spin_loader::bindle::config as bindle_schema;
-use spin_loader::local::config as local_schema;
+use spin_loader::local::config::{self as local_schema, RawAppManifestAnyVersion};
/// Expands a file-based application manifest to a Bindle invoice.
pub async fn expand_manifest(
@@ -22,6 +22,7 @@ pub async fn expand_manifest(
.absolutize()
.context("Failed to resolve absoiute path to manifest file")?;
let manifest = spin_loader::local::raw_manifest_from_file(&app_file).await?;
+ let RawAppManifestAnyVersion::V0_1_0(manifest) = manifest;
let app_dir = app_dir(&app_file)?;
// * create a new spin.toml-like document where
| 97
|
[
"91"
] |
diff --git a/crates/loader/src/local/tests.rs b/crates/loader/src/local/tests.rs
index b16f321a28..00830456c7 100644
--- a/crates/loader/src/local/tests.rs
+++ b/crates/loader/src/local/tests.rs
@@ -40,7 +40,8 @@ async fn test_from_local_source() -> Result<()> {
fn test_manifest() -> Result<()> {
const MANIFEST: &str = include_str!("../../tests/valid-manifest.toml");
- let cfg: RawAppManifest = toml::from_str(MANIFEST)?;
+ let cfg_any: RawAppManifestAnyVersion = toml::from_str(MANIFEST)?;
+ let RawAppManifestAnyVersion::V0_1_0(cfg) = cfg_any;
assert_eq!(cfg.info.name, "chain-of-command");
assert_eq!(cfg.info.version, "6.11.2");
@@ -81,13 +82,31 @@ fn test_manifest() -> Result<()> {
Ok(())
}
+#[test]
+fn test_unknown_version_is_rejected() {
+ const MANIFEST: &str = include_str!("../../tests/invalid-version.toml");
+
+ let cfg = toml::from_str::<RawAppManifestAnyVersion>(MANIFEST);
+ assert!(
+ cfg.is_err(),
+ "Expected version to be validated but it wasn't"
+ );
+
+ let e = cfg.unwrap_err().to_string();
+ assert!(
+ e.contains("apiVersion"),
+ "Expected error to mention `apiVersion`"
+ );
+}
+
#[test]
fn test_wagi_executor_with_custom_entrypoint() -> Result<()> {
const MANIFEST: &str = include_str!("../../tests/wagi-custom-entrypoint.toml");
const EXPECTED_CUSTOM_ENTRYPOINT: &str = "custom-entrypoint";
- let cfg: RawAppManifest = toml::from_str(MANIFEST)?;
+ let cfg_any: RawAppManifestAnyVersion = toml::from_str(MANIFEST)?;
+ let RawAppManifestAnyVersion::V0_1_0(cfg) = cfg_any;
let TriggerConfig::Http(http_config) = &cfg.components[0].trigger;
diff --git a/crates/loader/tests/invalid-version.toml b/crates/loader/tests/invalid-version.toml
new file mode 100644
index 0000000000..dce9009bc6
--- /dev/null
+++ b/crates/loader/tests/invalid-version.toml
@@ -0,0 +1,14 @@
+apiVersion = "77.301.12"
+authors = ["Gul Madred", "Edward Jellico", "JL"]
+description = "Because if we get to API version 77.301.12 then we have bigger problems"
+name = "chain-of-command"
+trigger = {type = "http", base = "/"}
+version = "6.11.2"
+
+[[component]]
+id = "abc"
+[component.source]
+parcel = "parcel"
+reference = "bindle reference"
+[component.trigger]
+route = "/test"
|
95f9da2a41aded597a437ad041a5a13ab19604ee
|
|
fa95701bc2384259fc9677d5c96e2cddd9eb0556
|
Custom entrypoints for Wagi components
#54 adds support for Wagi components.
However, the only supported entrypoint is `_start` — https://github.com/fermyon/spin/pull/54#discussion_r804378999
There should be a way in the component configuration to specify the custom Wagi entrypoint.
|
Do you see that change in configuration as something like:
```
[component.trigger]
...
entrypoint = "_start"
```
Yes, but keep in mind this is a config that only makes sense for Wagi components.
Perfect. That was my next question.
What is a "WAGI component" in this context? Is the idea to allow the mounting of entire WAGI bindles in Spin, or just to allow the use of WAGI _handlers_ (individual Wasm modules) in Spin?
(I agree, the name "Wagi component" is very confusing.
How about "Spin HTTP component handled by the Wagi executor"?)
#54 allows using a Wagi module as the source for a Spin component — _just_ the Wasm module. For example, the following component is runnable by #54:
```toml
[[component]]
source = "bartholomew.wasm"
id = "bartholomew"
files = [ "content/**/*" , "templates/*", "scripts/*", "config/*"]
[component.trigger]
route = "/..."
executor = "wagi"
entrypoint = "some-other-export" # not implemented yet
```
However, if the same Wasm module exported multiple functions, each of which is a "Wagi handler", there should be a way to indicate which export to use, as right now `_start` is always used.
|
2022-02-18T16:40:08Z
|
fermyon__spin-88
|
fermyon/spin
|
0.1
|
diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs
index b396f02e20..77aa5e926a 100644
--- a/crates/config/src/lib.rs
+++ b/crates/config/src/lib.rs
@@ -137,12 +137,12 @@ impl Default for HttpConfig {
/// The type of interface the component implements.
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
-#[serde(deny_unknown_fields, rename_all = "camelCase")]
+#[serde(deny_unknown_fields, rename_all = "camelCase", tag = "type")]
pub enum HttpExecutor {
/// The component implements the Spin HTTP interface.
Spin,
/// The component implements the Wagi interface.
- Wagi,
+ Wagi(WagiConfig),
}
impl Default for HttpExecutor {
@@ -151,6 +151,25 @@ impl Default for HttpExecutor {
}
}
+/// Wagi specific configuration for the http executor.
+#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
+#[serde(default, deny_unknown_fields, rename_all = "camelCase")]
+pub struct WagiConfig {
+ /// The name of the entrypoint.
+ pub entrypoint: String,
+}
+
+impl Default for WagiConfig {
+ fn default() -> WagiConfig {
+ /// This is the default Wagi entrypoint.
+ const WAGI_DEFAULT_ENTRYPOINT: &str = "_start";
+
+ WagiConfig {
+ entrypoint: WAGI_DEFAULT_ENTRYPOINT.into(),
+ }
+ }
+}
+
/// Trigger configuration.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase", untagged)]
diff --git a/crates/http/src/lib.rs b/crates/http/src/lib.rs
index 5b641933d4..7bb3b002bb 100644
--- a/crates/http/src/lib.rs
+++ b/crates/http/src/lib.rs
@@ -103,10 +103,11 @@ impl HttpTrigger {
&trigger.route,
req,
addr,
+ &(),
)
.await
}
- spin_config::HttpExecutor::Wagi => {
+ spin_config::HttpExecutor::Wagi(wagi_config) => {
WagiHttpExecutor::execute(
&self.engine,
&c.id,
@@ -114,6 +115,7 @@ impl HttpTrigger {
&trigger.route,
req,
addr,
+ wagi_config,
)
.await
}
@@ -237,6 +239,9 @@ pub(crate) fn default_headers(
/// All HTTP executors must implement this trait.
#[async_trait]
pub(crate) trait HttpExecutor: Clone + Send + Sync + 'static {
+ /// Configuration specific to the implementor of this trait.
+ type Config;
+
async fn execute(
engine: &ExecutionContext,
component: &str,
@@ -244,6 +249,7 @@ pub(crate) trait HttpExecutor: Clone + Send + Sync + 'static {
raw_route: &str,
req: Request<Body>,
client_addr: SocketAddr,
+ config: &Self::Config,
) -> Result<Response<Body>>;
}
diff --git a/crates/http/src/spin.rs b/crates/http/src/spin.rs
index 695776f0a9..c112788eed 100644
--- a/crates/http/src/spin.rs
+++ b/crates/http/src/spin.rs
@@ -14,6 +14,8 @@ pub struct SpinHttpExecutor;
#[async_trait]
impl HttpExecutor for SpinHttpExecutor {
+ type Config = ();
+
async fn execute(
engine: &ExecutionContext,
component: &str,
@@ -21,6 +23,7 @@ impl HttpExecutor for SpinHttpExecutor {
raw_route: &str,
req: Request<Body>,
_client_addr: SocketAddr,
+ _config: &Self::Config,
) -> Result<Response<Body>> {
log::trace!(
"Executing request using the Spin executor for component {}",
diff --git a/crates/http/src/wagi.rs b/crates/http/src/wagi.rs
index 47c2e55237..3ee12969ee 100644
--- a/crates/http/src/wagi.rs
+++ b/crates/http/src/wagi.rs
@@ -4,6 +4,7 @@ use crate::HttpExecutor;
use anyhow::Result;
use async_trait::async_trait;
use hyper::{body, Body, Request, Response};
+use spin_config::WagiConfig;
use spin_engine::io::{IoStreamRedirects, OutRedirect};
use std::collections::HashMap;
use std::{
@@ -13,16 +14,13 @@ use std::{
use tracing::log;
use wasi_common::pipe::{ReadPipe, WritePipe};
-/// This is the default Wagi entrypoint.
-/// There should be a way to set this in the component
-/// configuration of the trigger / executor.
-const WAGI_DEFAULT_ENTRYPOINT: &str = "_start";
-
#[derive(Clone)]
pub struct WagiHttpExecutor;
#[async_trait]
impl HttpExecutor for WagiHttpExecutor {
+ type Config = WagiConfig;
+
async fn execute(
engine: &ExecutionContext,
component: &str,
@@ -30,6 +28,7 @@ impl HttpExecutor for WagiHttpExecutor {
raw_route: &str,
req: Request<Body>,
client_addr: SocketAddr,
+ wagi_config: &Self::Config,
) -> Result<Response<Body>> {
log::trace!(
"Executing request using the Wagi executor for component {}",
@@ -75,11 +74,11 @@ impl HttpExecutor for WagiHttpExecutor {
engine.prepare_component(component, None, Some(iostream.clone()), Some(headers))?;
let start = instance
- .get_func(&mut store, WAGI_DEFAULT_ENTRYPOINT)
+ .get_func(&mut store, &wagi_config.entrypoint)
.ok_or_else(|| {
anyhow::anyhow!(
"No such function '{}' in {}",
- WAGI_DEFAULT_ENTRYPOINT,
+ wagi_config.entrypoint,
component
)
})?;
diff --git a/crates/loader/src/local/mod.rs b/crates/loader/src/local/mod.rs
index fa4e8e24aa..bc30f3bb32 100644
--- a/crates/loader/src/local/mod.rs
+++ b/crates/loader/src/local/mod.rs
@@ -7,6 +7,9 @@ mod assets;
/// Configuration representation for a Spin apoplication as a local spin.toml file.
mod config;
+#[cfg(test)]
+mod tests;
+
use anyhow::{anyhow, Context, Result};
use config::{RawAppInformation, RawAppManifest, RawComponentManifest};
use futures::future;
@@ -121,115 +124,3 @@ fn info(raw: RawAppInformation, src: impl AsRef<Path>) -> ApplicationInformation
origin: ApplicationOrigin::File(src.as_ref().to_path_buf()),
}
}
-
-#[cfg(test)]
-mod tests {
- use crate::local::config::RawModuleSource;
-
- use super::*;
- use anyhow::Result;
- use spin_config::{ApplicationTrigger, HttpExecutor, TriggerConfig};
- use std::path::PathBuf;
-
- const MANIFEST: &str = "tests/valid-with-files/spin.toml";
- #[tokio::test]
- async fn test_from_local_source() -> Result<()> {
- let dir: Option<PathBuf> = None;
- let cfg = from_file(MANIFEST, dir).await?;
-
- assert_eq!(cfg.info.name, "spin-local-source-test");
- assert_eq!(cfg.info.version, "1.0.0");
- assert_eq!(cfg.info.api_version, "0.1.0");
- assert_eq!(
- cfg.info.authors[0],
- "Fermyon Engineering <engineering@fermyon.com>"
- );
-
- let ApplicationTrigger::Http(http) = cfg.info.trigger;
- assert_eq!(http.base, "/".to_string());
-
- let TriggerConfig::Http(http) = cfg.components[0].trigger.clone();
- assert_eq!(http.executor.unwrap(), HttpExecutor::Spin);
- assert_eq!(http.route, "/...".to_string());
-
- assert_eq!(cfg.components[0].wasm.mounts.len(), 1);
-
- assert_eq!(
- cfg.info.origin,
- ApplicationOrigin::File("tests/valid-with-files/spin.toml".into())
- );
-
- Ok(())
- }
-
- const CFG_TEST: &str = r#"
- apiVersion = "0.1.0"
- name = "chain-of-command"
- version = "6.11.2"
- description = "A simple application that returns the number of lights"
- authors = [ "Gul Madred", "Edward Jellico", "JL" ]
- trigger = { type = "http", base = "/" }
-
- [[component]]
- source = "path/to/wasm/file.wasm"
- id = "four-lights"
- files = ["file.txt", "subdir/another.txt"]
- [component.trigger]
- route = "/lights"
- executor = "spin"
- [component.environment]
- env1 = "first"
- env2 = "second"
-
- [[component]]
- id = "abc"
- [component.source]
- reference = "bindle reference"
- parcel = "parcel"
- [component.trigger]
- route = "/test"
- "#;
-
- #[test]
- fn test_manifest() -> Result<()> {
- let cfg: RawAppManifest = toml::from_str(CFG_TEST)?;
-
- assert_eq!(cfg.info.name, "chain-of-command");
- assert_eq!(cfg.info.version, "6.11.2");
- assert_eq!(
- cfg.info.description,
- Some("A simple application that returns the number of lights".to_string())
- );
-
- let ApplicationTrigger::Http(http) = cfg.info.trigger;
- assert_eq!(http.base, "/".to_string());
-
- assert_eq!(cfg.info.authors.unwrap().len(), 3);
- assert_eq!(cfg.components[0].id, "four-lights".to_string());
-
- let TriggerConfig::Http(http) = cfg.components[0].trigger.clone();
- assert_eq!(http.executor.unwrap(), HttpExecutor::Spin);
- assert_eq!(http.route, "/lights".to_string());
-
- let test_component = &cfg.components[0];
- let test_env = &test_component.wasm.environment.as_ref().unwrap();
- assert_eq!(test_env.len(), 2);
- assert_eq!(test_env.get("env1").unwrap(), "first");
- assert_eq!(test_env.get("env2").unwrap(), "second");
-
- let test_files = &test_component.wasm.files.as_ref().unwrap();
- assert_eq!(test_files.len(), 2);
- assert_eq!(test_files[0], "file.txt");
- assert_eq!(test_files[1], "subdir/another.txt");
-
- let b = match cfg.components[1].source.clone() {
- RawModuleSource::Bindle(b) => b,
- RawModuleSource::FileReference(_) => panic!("expected bindle source"),
- };
-
- assert_eq!(b.reference, "bindle reference".to_string());
- assert_eq!(b.parcel, "parcel".to_string());
-
- Ok(())
- }
-}
diff --git a/templates/spin-http/spin.toml b/templates/spin-http/spin.toml
index 0a42898ec7..12baa02417 100644
--- a/templates/spin-http/spin.toml
+++ b/templates/spin-http/spin.toml
@@ -1,11 +1,12 @@
+apiVersion = "0.1.0"
+authors = ["Radu Matei <radu@fermyon.com>"]
+description = "A simple application that returns hello and goodbye."
name = "spin-hello-world"
+trigger = {type = "http", base = "/test"}
version = "1.0.0"
-description = "A simple application that returns hello and goodbye."
-authors = [ "Radu Matei <radu@fermyon.com>" ]
-trigger = { type = "http", base = "/test" }
[[component]]
-source = "target/wasm32-wasi/release/spinhelloworld.wasm"
id = "hello"
+source = "target/wasm32-wasi/release/spinhelloworld.wasm"
[component.trigger]
route = "/hello"
| 88
|
[
"69"
] |
diff --git a/crates/loader/src/local/tests.rs b/crates/loader/src/local/tests.rs
new file mode 100644
index 0000000000..ab7254adf1
--- /dev/null
+++ b/crates/loader/src/local/tests.rs
@@ -0,0 +1,103 @@
+use crate::local::config::RawModuleSource;
+
+use super::*;
+use anyhow::Result;
+use spin_config::{ApplicationTrigger, HttpExecutor, TriggerConfig};
+use std::path::PathBuf;
+
+#[tokio::test]
+async fn test_from_local_source() -> Result<()> {
+ const MANIFEST: &str = "tests/valid-with-files/spin.toml";
+
+ let dir: Option<PathBuf> = None;
+ let cfg = from_file(MANIFEST, dir).await?;
+
+ assert_eq!(cfg.info.name, "spin-local-source-test");
+ assert_eq!(cfg.info.version, "1.0.0");
+ assert_eq!(cfg.info.api_version, "0.1.0");
+ assert_eq!(
+ cfg.info.authors[0],
+ "Fermyon Engineering <engineering@fermyon.com>"
+ );
+
+ let ApplicationTrigger::Http(http) = cfg.info.trigger;
+ assert_eq!(http.base, "/".to_string());
+
+ let TriggerConfig::Http(http) = cfg.components[0].trigger.clone();
+ assert_eq!(http.executor.unwrap(), HttpExecutor::Spin);
+ assert_eq!(http.route, "/...".to_string());
+
+ assert_eq!(cfg.components[0].wasm.mounts.len(), 1);
+
+ assert_eq!(
+ cfg.info.origin,
+ ApplicationOrigin::File("tests/valid-with-files/spin.toml".into())
+ );
+
+ Ok(())
+}
+
+#[test]
+fn test_manifest() -> Result<()> {
+ const MANIFEST: &str = include_str!("../../tests/valid-manifest.toml");
+
+ let cfg: RawAppManifest = toml::from_str(MANIFEST)?;
+
+ assert_eq!(cfg.info.name, "chain-of-command");
+ assert_eq!(cfg.info.version, "6.11.2");
+ assert_eq!(
+ cfg.info.description,
+ Some("A simple application that returns the number of lights".to_string())
+ );
+
+ let ApplicationTrigger::Http(http) = cfg.info.trigger;
+ assert_eq!(http.base, "/".to_string());
+
+ assert_eq!(cfg.info.authors.unwrap().len(), 3);
+ assert_eq!(cfg.components[0].id, "four-lights".to_string());
+
+ let TriggerConfig::Http(http) = cfg.components[0].trigger.clone();
+ assert_eq!(http.executor.unwrap(), HttpExecutor::Spin);
+ assert_eq!(http.route, "/lights".to_string());
+
+ let test_component = &cfg.components[0];
+ let test_env = &test_component.wasm.environment.as_ref().unwrap();
+ assert_eq!(test_env.len(), 2);
+ assert_eq!(test_env.get("env1").unwrap(), "first");
+ assert_eq!(test_env.get("env2").unwrap(), "second");
+
+ let test_files = &test_component.wasm.files.as_ref().unwrap();
+ assert_eq!(test_files.len(), 2);
+ assert_eq!(test_files[0], "file.txt");
+ assert_eq!(test_files[1], "subdir/another.txt");
+
+ let b = match cfg.components[1].source.clone() {
+ RawModuleSource::Bindle(b) => b,
+ RawModuleSource::FileReference(_) => panic!("expected bindle source"),
+ };
+
+ assert_eq!(b.reference, "bindle reference".to_string());
+ assert_eq!(b.parcel, "parcel".to_string());
+
+ Ok(())
+}
+
+#[test]
+fn test_wagi_executor_with_custom_entrypoint() -> Result<()> {
+ const MANIFEST: &str = include_str!("../../tests/wagi-custom-entrypoint.toml");
+
+ const EXPECTED_CUSTOM_ENTRYPOINT: &str = "custom-entrypoint";
+
+ let cfg: RawAppManifest = toml::from_str(MANIFEST)?;
+
+ let TriggerConfig::Http(http_config) = &cfg.components[0].trigger;
+
+ match http_config.executor.as_ref().unwrap() {
+ HttpExecutor::Spin => panic!("expected wagi http executor"),
+ HttpExecutor::Wagi(spin_config::WagiConfig { entrypoint }) => {
+ assert_eq!(entrypoint, EXPECTED_CUSTOM_ENTRYPOINT);
+ }
+ };
+
+ Ok(())
+}
diff --git a/crates/loader/tests/valid-manifest.toml b/crates/loader/tests/valid-manifest.toml
new file mode 100644
index 0000000000..f543f4e9dc
--- /dev/null
+++ b/crates/loader/tests/valid-manifest.toml
@@ -0,0 +1,25 @@
+apiVersion = "0.1.0"
+authors = ["Gul Madred", "Edward Jellico", "JL"]
+description = "A simple application that returns the number of lights"
+name = "chain-of-command"
+trigger = {type = "http", base = "/"}
+version = "6.11.2"
+
+[[component]]
+files = ["file.txt", "subdir/another.txt"]
+id = "four-lights"
+source = "path/to/wasm/file.wasm"
+[component.trigger]
+executor = {type = "spin"}
+route = "/lights"
+[component.environment]
+env1 = "first"
+env2 = "second"
+
+[[component]]
+id = "abc"
+[component.source]
+parcel = "parcel"
+reference = "bindle reference"
+[component.trigger]
+route = "/test"
diff --git a/crates/loader/tests/valid-with-files/spin.toml b/crates/loader/tests/valid-with-files/spin.toml
index 95c54222c2..7cda92e376 100644
--- a/crates/loader/tests/valid-with-files/spin.toml
+++ b/crates/loader/tests/valid-with-files/spin.toml
@@ -1,11 +1,14 @@
-name = "spin-local-source-test"
apiVersion = "0.1.0"
+authors = ["Fermyon Engineering <engineering@fermyon.com>"]
+name = "spin-local-source-test"
+trigger = {type = "http", base = "/"}
version = "1.0.0"
-authors = [ "Fermyon Engineering <engineering@fermyon.com>" ]
-trigger = { type = "http", base = "/" }
[[component]]
-source = "spin-fs.wasm"
-id = "fs"
files = ["**/*"]
-trigger = { route = "/...", executor = "spin" }
+id = "fs"
+source = "spin-fs.wasm"
+
+[component.trigger]
+executor = {type = "spin"}
+route = "/..."
diff --git a/crates/loader/tests/wagi-custom-entrypoint.toml b/crates/loader/tests/wagi-custom-entrypoint.toml
new file mode 100644
index 0000000000..4cf2bc6f7d
--- /dev/null
+++ b/crates/loader/tests/wagi-custom-entrypoint.toml
@@ -0,0 +1,14 @@
+name = "spin-wagi-custom-entrypoint"
+apiVersion = "0.1.0"
+version = "1.0.0"
+authors = [ "Fermyon Engineering <engineering@fermyon.com>" ]
+trigger = { type = "http", base = "/" }
+
+[[component]]
+source = "spin-fs.wasm"
+id = "fs"
+files = ["**/*"]
+
+[component.trigger]
+route = "/hello"
+executor = { type = "wagi", entrypoint = "custom-entrypoint" }
\ No newline at end of file
|
95f9da2a41aded597a437ad041a5a13ab19604ee
|
1b33dc526ca077fe8dcab7b011be6a359d523656
|
Normalize the paths between the configuration file and module source
`spin up --app spin.toml` must currently be run from the same directory as `spin.toml`, because a relative path for the component `source` is not handled properly:
https://github.com/fermyon/spin/blob/751cda3ee182675b00f05bfd3f18c05086978bf2/src/commands/up.rs#L19-L25
|
Should we make it so that the path must be relative to the directory that the Spin.toml file lives? What happens if the user wants to specify absolutely path?
Right now I'm thinking.. if component source is a path, check if it is relative or not. Relative paths are relative to the directory where the Spin.toml file lives. If not relative, use absolute path given. How should a user denote they're supplying an absolute path? Should it be by using `/` at the beginning of the component source string? Should they specify the file URI scheme? https://en.wikipedia.org/wiki/File_URI_scheme
The current implicit assumption is that the module `source` _is_ relative to `spin.toml`, and I think the newly introduced `ApplicationOrigin` structure in the configuration should help with this — https://github.com/fermyon/spin/blob/ec5a000f05d0586aeda52f0e27577dd2384c195c/crates/config/src/lib.rs#L130-L135
I'd start with implicit relative vs. absolute path (i.e. "if it starts with `/`), and stay away of the file scheme for now. We could add it later if we think it's a use case we want to support.
|
2022-02-16T22:27:27Z
|
fermyon__spin-87
|
fermyon/spin
|
0.1
|
diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs
index 31c510b188..ce57601214 100644
--- a/crates/config/src/lib.rs
+++ b/crates/config/src/lib.rs
@@ -21,8 +21,12 @@ pub use bindle_utils::BindleReader;
/// Reads the application configuration from the specified file.
pub fn read_from_file(app_file: impl AsRef<Path>) -> Result<Configuration<CoreComponent>> {
let mut buf = vec![];
- let mut file = File::open(&app_file)
- .with_context(|| format!("Failed to open configuration file '{}'", app_file.as_ref().display()))?;
+ let mut file = File::open(&app_file).with_context(|| {
+ format!(
+ "Failed to open configuration file '{}'",
+ app_file.as_ref().display()
+ )
+ })?;
file.read_to_end(&mut buf)?;
let absolute_app_path = app_file.as_ref().absolutize()?.into_owned();
@@ -49,12 +53,16 @@ pub async fn read_from_bindle(
let manifest_id = bindle_utils::find_application_manifest(&invoice)
.with_context(|| format!("Failed to find application manifest in '{}'", id))?;
- let manifest_content = reader.get_parcel(&manifest_id).await
+ let manifest_content = reader
+ .get_parcel(&manifest_id)
+ .await
.with_context(|| format!("Failed to fetch manifest from server '{}'", server_url))?;
- let manifest: schema::parcel::AppManifest = toml::from_slice(&manifest_content)
- .context("Failed to parse application manifest")?;
+ let manifest: schema::parcel::AppManifest =
+ toml::from_slice(&manifest_content).context("Failed to parse application manifest")?;
- Ok(parser::bindle::parse(manifest, &invoice, &reader, server_url))
+ Ok(parser::bindle::parse(
+ manifest, &invoice, &reader, server_url,
+ ))
}
/// Application configuration.
@@ -137,6 +145,21 @@ pub enum ApplicationOrigin {
Bindle(bindle::Id, String),
}
+impl ApplicationOrigin {
+ /// Returns Path if File, otherwise None
+ pub fn to_file(&self) -> Option<&PathBuf> {
+ match self {
+ Self::File(p) => Some(p),
+ _ => None,
+ }
+ }
+
+ /// Returns parent path of application origin if file
+ pub fn parent_dir(&self) -> Option<&Path> {
+ self.to_file().map(|path| path.parent()).flatten()
+ }
+}
+
/// The trigger type.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase", tag = "type")]
@@ -190,20 +213,18 @@ pub enum ReferencedFiles {
impl std::fmt::Debug for ReferencedFiles {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
- Self::None =>
- f.debug_tuple("None")
- .finish(),
- Self::FilePatterns(path, patterns) =>
- f.debug_tuple("FilePatterns")
- .field(path)
- .field(patterns)
- .finish(),
- Self::BindleParcels(_, invoice_id, labels) =>
- f.debug_tuple("BindleParcels")
- // We can't provide any debug info about the client or token manager it seems?
- .field(invoice_id)
- .field(labels)
- .finish(),
+ Self::None => f.debug_tuple("None").finish(),
+ Self::FilePatterns(path, patterns) => f
+ .debug_tuple("FilePatterns")
+ .field(path)
+ .field(patterns)
+ .finish(),
+ Self::BindleParcels(_, invoice_id, labels) => f
+ .debug_tuple("BindleParcels")
+ // We can't provide any debug info about the client or token manager it seems?
+ .field(invoice_id)
+ .field(labels)
+ .finish(),
}
}
}
@@ -377,9 +398,16 @@ mod tests {
let test_files = match &test_component.wasm.files {
ReferencedFiles::FilePatterns(_, fps) => fps,
_ => {
- assert!(false, "Expected file patterns but got {:?}", test_component.wasm.files);
- panic!("Expected file patterns but got {:?}", test_component.wasm.files)
- },
+ assert!(
+ false,
+ "Expected file patterns but got {:?}",
+ test_component.wasm.files
+ );
+ panic!(
+ "Expected file patterns but got {:?}",
+ test_component.wasm.files
+ )
+ }
};
// TODO: restore
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 0d11926468..60ec2f9183 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -7,10 +7,10 @@ mod assets;
pub mod io;
use anyhow::{bail, Result};
-use assets::{DirectoryMount};
+use assets::DirectoryMount;
use io::IoStreamRedirects;
-use spin_config::{CoreComponent, ModuleSource};
-use std::{collections::HashMap, sync::Arc};
+use spin_config::{ApplicationOrigin, CoreComponent, ModuleSource};
+use std::{collections::HashMap, path::Path, path::PathBuf, sync::Arc};
use tracing::{instrument, log};
use wasi_common::WasiCtx;
use wasmtime::{Engine, Instance, InstancePre, Linker, Module, Store};
@@ -114,33 +114,40 @@ impl<T: Default> Builder<T> {
);
let mut components = HashMap::new();
+
for c in &self.config.app.components {
let config = c.clone();
// TODO
let module = match c.source.clone() {
ModuleSource::FileReference(p) => {
- let module = Module::from_file(&self.engine, &p)?;
- log::trace!("Created module from file {:?}", p);
+ let path_to_component: PathBuf = self
+ .config
+ .app
+ .info
+ .origin
+ .parent_dir()
+ .map(|app_origin| complete_path(app_origin, &p))
+ .unwrap_or(p);
+ let module = Module::from_file(&self.engine, &path_to_component)?;
+ log::trace!("Created module from path {:?}", path_to_component);
module
- },
+ }
ModuleSource::Bindle(bcs) => {
let module_bytes = bcs.reader.get_parcel(&bcs.parcel).await?;
let module = Module::from_binary(&self.engine, &module_bytes)?;
- log::trace!("Created module from parcel {:?}", bcs.parcel); // TODO: invoice id? parcel name?
+ log::trace!("Created module from parcel {:?}", bcs.parcel); // TODO: invoice id? parcel name?
module
- },
+ }
+
ModuleSource::Linked(_) => panic!(),
};
let pre = Arc::new(self.linker.instantiate_pre(&mut self.store, &module)?);
- log::debug!("Created pre-instance from module"); // TODO: show source?
+ log::debug!("Created pre-instance from module"); // TODO: show source?
- let asset_directories = assets::prepare(
- &c.id,
- &c.wasm.files,
- working_directory.path()
- ).await?;
+ let asset_directories =
+ assets::prepare(&c.id, &c.wasm.files, working_directory.path()).await?;
components.insert(
c.id.clone(),
@@ -285,41 +292,13 @@ impl<T: Default> ExecutionContext<T> {
}
}
-#[cfg(test)]
-mod tests {
- use super::*;
- use anyhow::Result;
- use std::io::Write;
- use spin_config::Configuration;
-
- const CFG_TEST: &str = r#"
- name = "spin-hello-world"
- version = "1.0.0"
- description = "A simple application that returns hello and goodbye."
- authors = [ "Radu Matei <radu@fermyon.com>" ]
- trigger = { type = "http", base = "/" }
-
- [[component]]
- source = "target/wasm32-wasi/release/hello.wasm"
- id = "hello"
- [component.trigger]
- route = "/hello"
- "#;
-
- fn read_from_temp_file(toml_text: &str) -> Result<Configuration<CoreComponent>> {
- let mut f = tempfile::NamedTempFile::new()?;
- f.write_all(toml_text.as_bytes())?;
- let config = spin_config::read_from_file(&f)?;
- drop(f);
- Ok(config)
- }
-
- #[test]
- fn test_simple_config() -> Result<()> {
- let app = read_from_temp_file(CFG_TEST)?;
- let config = ExecutionContextConfiguration::new(app);
-
- assert_eq!(config.app.info.name, "spin-hello-world".to_string());
- Ok(())
+fn complete_path(app_origin: impl AsRef<Path>, component_source_path: impl AsRef<Path>) -> PathBuf {
+ if component_source_path.as_ref().is_absolute() {
+ component_source_path.as_ref().to_path_buf()
+ } else {
+ app_origin.as_ref().join(component_source_path)
}
}
+
+#[cfg(test)]
+mod tests;
| 87
|
[
"35"
] |
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
new file mode 100644
index 0000000000..feecdc0630
--- /dev/null
+++ b/crates/engine/src/tests.rs
@@ -0,0 +1,55 @@
+use super::*;
+use anyhow::Result;
+use spin_config::Configuration;
+use std::io::Write;
+
+const CFG_TEST: &str = r#"
+name = "spin-hello-world"
+version = "1.0.0"
+description = "A simple application that returns hello and goodbye."
+authors = [ "Radu Matei <radu@fermyon.com>" ]
+trigger = { type = "http", base = "/" }
+
+[[component]]
+ source = "target/wasm32-wasi/release/hello.wasm"
+ id = "hello"
+[component.trigger]
+ route = "/hello"
+"#;
+
+fn read_from_temp_file(toml_text: &str) -> Result<Configuration<CoreComponent>> {
+ let mut f = tempfile::NamedTempFile::new()?;
+ f.write_all(toml_text.as_bytes())?;
+ let config = spin_config::read_from_file(&f)?;
+ drop(f);
+ Ok(config)
+}
+
+#[test]
+fn test_simple_config() -> Result<()> {
+ let app = read_from_temp_file(CFG_TEST)?;
+ let config = ExecutionContextConfiguration::new(app);
+
+ assert_eq!(config.app.info.name, "spin-hello-world".to_string());
+ Ok(())
+}
+
+#[test]
+fn test_component_path() -> Result<()> {
+ let test_app_origin = "dir/nested_dir";
+
+ assert_eq!(
+ complete_path(test_app_origin, "component/source.wasm"),
+ PathBuf::from("dir/nested_dir/component/source.wasm")
+ );
+
+ // TODO write windows specific test
+ //let abs_source_windows = "c:\\windows/nested_dir";
+ let abs_source_linux = r#"/somedir/nested_dir"#;
+
+ assert_eq!(
+ complete_path(test_app_origin, abs_source_linux),
+ PathBuf::from(abs_source_linux)
+ );
+ Ok(())
+}
|
95f9da2a41aded597a437ad041a5a13ab19604ee
|
ae95bc05814267c5559fbed3d5263b3dcb54fd55
|
Handle route patterns for the HTTP trigger
A component will only be executed if the request's URI path matches the route defined in the trigger configuration exactly:
https://github.com/fermyon/spin/blob/751cda3ee182675b00f05bfd3f18c05086978bf2/crates/http/src/lib.rs#L80-L87
This needs to handle route patterns like `route = /hello/...`.
|
2022-02-09T04:38:05Z
|
fermyon__spin-57
|
fermyon/spin
|
0.1
|
diff --git a/Cargo.lock b/Cargo.lock
index 61de1bd702..39a294ce01 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -807,9 +807,9 @@ dependencies = [
[[package]]
name = "hashbrown"
-version = "0.9.1"
+version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d7afe4a420e3fe79967a00898cc1f4db7c8a49a9333a29f8a4bd76a253d5cd04"
+checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e"
[[package]]
name = "heck"
@@ -952,9 +952,9 @@ dependencies = [
[[package]]
name = "indexmap"
-version = "1.6.2"
+version = "1.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "824845a0bf897a9042383849b02c1bc219c2383772efcd5c6f9766fa4b81aef3"
+checksum = "282a6247722caba404c065016bbfa522806e51714c34f5dfc3e4a3a46fcb4223"
dependencies = [
"autocfg",
"hashbrown",
@@ -1949,6 +1949,7 @@ dependencies = [
"futures",
"http",
"hyper",
+ "indexmap",
"serde",
"spin-config",
"spin-engine",
diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs
index 852d9c3c3b..d44d2f5e41 100644
--- a/crates/config/src/lib.rs
+++ b/crates/config/src/lib.rs
@@ -149,17 +149,15 @@ impl Default for ModuleSource {
pub struct HttpConfig {
/// HTTP route the component will be invoked for.
pub route: String,
- /// The interface the component implements.
- /// TODO
- /// This is a weird name.
- pub implementation: Option<HttpImplementation>,
+ /// The HTTP executor the component requires.
+ pub executor: Option<HttpExecutor>,
}
impl Default for HttpConfig {
fn default() -> Self {
Self {
route: "/".to_string(),
- implementation: Default::default(),
+ executor: Default::default(),
}
}
}
@@ -170,14 +168,14 @@ impl Default for HttpConfig {
/// These should be versioned.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
-pub enum HttpImplementation {
+pub enum HttpExecutor {
/// The component implements the Spin HTTP interface.
Spin,
/// The component implements the Wagi interface.
Wagi,
}
-impl Default for HttpImplementation {
+impl Default for HttpExecutor {
fn default() -> Self {
Self::Spin
}
@@ -249,7 +247,7 @@ mod tests {
files = []
[component.trigger]
route = "/lights"
- implementation = "spin"
+ executor = "spin"
[component.dependencies]
cache = { type = "host" }
markdown = { type = "component", reference = "github/octo-markdown/1.0.0", parcel = "md.wasm" }
@@ -277,7 +275,7 @@ mod tests {
assert_eq!(cfg.components[0].core.id, "four-lights".to_string());
let TriggerConfig::Http(http) = cfg.components[0].core.trigger.clone();
- assert_eq!(http.implementation.unwrap(), HttpImplementation::Spin);
+ assert_eq!(http.executor.unwrap(), HttpExecutor::Spin);
assert_eq!(http.route, "/lights".to_string());
assert_eq!(
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index c920eb9645..d0574bbb32 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -187,13 +187,13 @@ impl<T: Default> ExecutionContext<T> {
#[instrument(skip(self, data))]
pub fn prepare_component(
&self,
- component: String,
+ component: &String,
data: Option<T>,
) -> Result<(Store<RuntimeContext<T>>, Instance)> {
log::info!("Preparing component {}", component);
let component = self
.components
- .get(&component)
+ .get(component)
.expect(&format!("cannot find component {}", component));
let mut store = self.store(component, data)?;
let instance = component.pre.instantiate(&mut store)?;
diff --git a/crates/http/Cargo.toml b/crates/http/Cargo.toml
index c0826dd9bb..87250e35af 100644
--- a/crates/http/Cargo.toml
+++ b/crates/http/Cargo.toml
@@ -14,6 +14,7 @@
futures = "0.3"
http = "0.2"
hyper = { version = "0.14", features = [ "full" ] }
+ indexmap = "1.8"
serde = { version = "1.0", features = [ "derive" ] }
spin-config = { path = "../config" }
spin-engine = { path = "../engine" }
diff --git a/crates/http/src/lib.rs b/crates/http/src/lib.rs
index 2b475a16db..812b6a79e7 100644
--- a/crates/http/src/lib.rs
+++ b/crates/http/src/lib.rs
@@ -1,5 +1,9 @@
//! Implementation for the Spin HTTP engine.
+mod routes;
+mod spin;
+mod wagi;
+
use anyhow::{Error, Result};
use async_trait::async_trait;
use http::StatusCode;
@@ -8,13 +12,14 @@ use hyper::{
service::{make_service_fn, service_fn},
Body, Request, Response, Server,
};
-use spin_config::{Configuration, CoreComponent};
+use routes::Router;
+use spin::SpinHttpExecutor;
+use spin_config::{Configuration, CoreComponent, TriggerConfig};
use spin_engine::{Builder, ExecutionContextConfiguration};
-use spin_http::{Method, SpinHttp, SpinHttpData};
-use std::{collections::HashMap, net::SocketAddr, str::FromStr, sync::Arc};
+use spin_http::SpinHttpData;
+use std::{net::SocketAddr, sync::Arc};
use tracing::{instrument, log};
-use url::Url;
-use wasmtime::{Instance, Store};
+use wagi::WagiHttpExecutor;
wit_bindgen_wasmtime::import!("wit/ephemeral/spin-http.wit");
@@ -69,38 +74,75 @@ impl HttpTrigger {
})
}
- /// Handle an incoming request using an HTTP executor.
- pub async fn handle(&self, req: Request<Body>) -> Result<Response<Body>> {
+ /// Handle incoming requests using an HTTP executor.
+ pub(crate) async fn handle(
+ &self,
+ req: Request<Body>,
+ addr: SocketAddr,
+ ) -> Result<Response<Body>> {
log::info!(
- "Processing request for application {} on path {}",
+ "Processing request for application {} on URI {}",
&self.app.info.name,
- req.uri().path()
+ req.uri()
);
match req.uri().path() {
"/healthz" => Ok(Response::new(Body::from("OK"))),
- route => match self.router.routes.get(&route.to_string()) {
- Some(c) => return SpinHttpExecutor::execute(&self.engine, c.id.clone(), req).await,
- None => return Ok(Self::not_found()),
+ route => match self.router.route(route) {
+ Ok(c) => {
+ let TriggerConfig::Http(trigger) = &c.trigger;
+ let executor = match &trigger.executor {
+ Some(i) => i,
+ None => &spin_config::HttpExecutor::Spin,
+ };
+
+ let res = match executor {
+ spin_config::HttpExecutor::Spin => {
+ SpinHttpExecutor::execute(&self.engine, &c.id, req, addr).await
+ }
+ spin_config::HttpExecutor::Wagi => {
+ WagiHttpExecutor::execute(&self.engine, &c.id, req, addr).await
+ }
+ };
+ match res {
+ Ok(res) => return Ok(res),
+ Err(e) => {
+ log::error!("Error processing request: {:?}", e);
+ return Ok(Self::internal_error());
+ }
+ }
+ }
+ Err(_) => return Ok(Self::not_found()),
},
}
}
- /// Create an HTTP 404 response
+ /// Create an HTTP 500 response.
+ fn internal_error() -> Response<Body> {
+ let mut err = Response::default();
+ *err.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
+ err
+ }
+
+ /// Create an HTTP 404 response.
fn not_found() -> Response<Body> {
let mut not_found = Response::default();
*not_found.status_mut() = StatusCode::NOT_FOUND;
not_found
}
+ /// Run the HTTP trigger indefinitely.
#[instrument(skip(self))]
pub async fn run(&self) -> Result<()> {
- let mk_svc = make_service_fn(move |_: &AddrStream| {
+ let mk_svc = make_service_fn(move |addr: &AddrStream| {
let t = self.clone();
+ let addr = addr.remote_addr();
+
async move {
Ok::<_, Error>(service_fn(move |req| {
let t2 = t.clone();
- async move { t2.handle(req).await }
+
+ async move { t2.handle(req, addr).await }
}))
}
});
@@ -113,188 +155,43 @@ impl HttpTrigger {
}
}
-/// Router for the HTTP trigger.
-#[derive(Clone)]
-pub struct Router {
- /// Map between a path and the component that should handle it.
- pub routes: HashMap<String, CoreComponent>,
-}
-
-impl Router {
- /// Build a router based on application configuration.
- #[instrument]
- pub fn build(app: &Configuration<CoreComponent>) -> Result<Self> {
- let mut routes = HashMap::new();
- for component in &app.components {
- let spin_config::TriggerConfig::Http(trigger) = &component.trigger;
- log::info!("Trying route path {}", trigger.route);
-
- routes.insert(trigger.route.clone(), component.clone());
- }
-
- log::info!(
- "Constructed router for application {}: {:?}",
- app.info.name,
- routes
- );
-
- Ok(Self { routes })
- }
-}
-
+/// The HTTP executor trait.
+/// All HTTP executors must implement this trait.
#[async_trait]
-pub trait HttpExecutor: Clone + Send + Sync + 'static {
+pub(crate) trait HttpExecutor: Clone + Send + Sync + 'static {
async fn execute(
engine: &ExecutionContext,
- component: String,
+ component: &String,
req: Request<Body>,
+ client_addr: SocketAddr,
) -> Result<Response<Body>>;
}
-#[derive(Clone)]
-pub struct SpinHttpExecutor;
-
-#[async_trait]
-impl HttpExecutor for SpinHttpExecutor {
- #[instrument(skip(engine))]
- async fn execute(
- engine: &ExecutionContext,
- component: String,
- req: Request<Body>,
- ) -> Result<Response<Body>> {
- log::info!("Executing request for component {}", component);
- let (store, instance) = engine.prepare_component(component, None)?;
- let res = Self::execute_impl(store, instance, req).await?;
- log::info!("Request finished, sending response.");
- Ok(res)
- }
-}
-
-impl SpinHttpExecutor {
- pub async fn execute_impl(
- mut store: Store<RuntimeContext>,
- instance: Instance,
- req: Request<Body>,
- ) -> Result<Response<Body>> {
- let engine = SpinHttp::new(&mut store, &instance, |host| host.data.as_mut().unwrap())?;
- let (parts, bytes) = req.into_parts();
- let bytes = hyper::body::to_bytes(bytes).await?.to_vec();
- let body = Some(&bytes[..]);
-
- let method = Self::method(&parts.method);
- let uri = &parts.uri.to_string();
- let headers = &Self::headers(&parts.headers)?;
- // TODO
- // Currently, this silently crashes the running thread.
- // let params = &Self::params(&uri)?;
- // let params: &Vec<(&str, &str)> = ¶ms.into_iter().map(|(k, v)| (&**k, &**v)).collect();
- let params = &Vec::new();
- let req = spin_http::Request {
- method,
- uri,
- headers,
- params,
- body,
- };
- log::info!("Request URI: {:?}", req.uri);
- let res = engine.handler(&mut store, req)?;
- log::info!("Response status code: {:?}", res.status);
- let mut response = http::Response::builder().status(res.status);
- Self::append_headers(response.headers_mut().unwrap(), res.headers)?;
-
- let body = match res.body {
- Some(b) => Body::from(b),
- None => Body::empty(),
- };
-
- Ok(response.body(body)?)
- }
-
- fn method(m: &http::Method) -> Method {
- match *m {
- http::Method::GET => Method::Get,
- http::Method::POST => Method::Post,
- http::Method::PUT => Method::Put,
- http::Method::DELETE => Method::Delete,
- http::Method::PATCH => Method::Patch,
- http::Method::HEAD => Method::Head,
- _ => todo!(),
- }
- }
-
- fn headers(hm: &http::HeaderMap) -> Result<Vec<(&str, &str)>> {
- let mut res = Vec::new();
- for (name, value) in hm
- .iter()
- .map(|(name, value)| (name.as_str(), std::str::from_utf8(value.as_bytes())))
- {
- let value = value?;
- res.push((name, value));
- }
-
- Ok(res)
- }
-
- fn append_headers(res: &mut http::HeaderMap, src: Option<Vec<(String, String)>>) -> Result<()> {
- if let Some(src) = src {
- for (k, v) in src.iter() {
- res.insert(
- http::header::HeaderName::from_str(k)?,
- http::header::HeaderValue::from_str(v)?,
- );
- }
- };
-
- Ok(())
- }
-
- #[allow(unused)]
- fn params(uri: &str) -> Result<Vec<(String, String)>> {
- let url = Url::parse(uri)?;
- Ok(url
- .query_pairs()
- .into_iter()
- .map(|(k, v)| (k.to_string(), v.to_string()))
- .collect())
- }
-}
-
-// TODO
-//
-// Implement a Wagi executor.
-
-#[derive(Clone)]
-pub struct WagiHttpExecutor;
-
-#[async_trait]
-impl HttpExecutor for WagiHttpExecutor {
- #[instrument(skip(_engine))]
- async fn execute(
- _engine: &ExecutionContext,
- _component: String,
- _req: Request<Body>,
- ) -> Result<Response<Body>> {
- log::info!("Executing request for component {}", _component);
- todo!("Wagi executor not implemented yet.")
- }
-}
-
#[cfg(test)]
mod tests {
use super::*;
use anyhow::Result;
use spin_config::{
- ApplicationInformation, Configuration, HttpConfig, HttpImplementation, ModuleSource,
+ ApplicationInformation, Configuration, HttpConfig, HttpExecutor, ModuleSource,
TriggerConfig,
};
+ use std::{
+ net::{IpAddr, Ipv4Addr},
+ sync::Once,
+ };
+
+ static LOGGER: Once = Once::new();
const RUST_ENTRYPOINT_PATH: &str =
"tests/rust-http-test/target/wasm32-wasi/release/rust_http_test.wasm";
- fn init() {
- tracing_subscriber::fmt()
- .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
- .init();
+ /// We can only initialize the tracing subscriber once per crate.
+ pub(crate) fn init() {
+ LOGGER.call_once(|| {
+ tracing_subscriber::fmt()
+ .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
+ .init();
+ });
}
#[tokio::test]
@@ -313,7 +210,7 @@ mod tests {
id: "test".to_string(),
trigger: TriggerConfig::Http(HttpConfig {
route: "/test".to_string(),
- implementation: Some(HttpImplementation::Spin),
+ executor: Some(HttpExecutor::Spin),
}),
..Default::default()
};
@@ -325,13 +222,18 @@ mod tests {
let body = Body::from("Fermyon".as_bytes().to_vec());
let req = http::Request::builder()
.method("POST")
- .uri("https://myservice.fermyon.dev/test")
- .header("X-Custom-Foo", "Bar")
- .header("X-Custom-Foo2", "Bar2")
+ .uri("https://myservice.fermyon.dev/test?abc=def")
+ .header("x-custom-foo", "bar")
+ .header("x-custom-foo2", "bar2")
.body(body)
.unwrap();
- let res = trigger.handle(req).await?;
+ let res = trigger
+ .handle(
+ req,
+ SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 1234),
+ )
+ .await?;
assert_eq!(res.status(), StatusCode::OK);
let body_bytes = hyper::body::to_bytes(res.into_body()).await.unwrap();
assert_eq!(body_bytes.to_vec(), "Hello, Fermyon".as_bytes());
diff --git a/crates/http/src/routes.rs b/crates/http/src/routes.rs
new file mode 100644
index 0000000000..55378bd75a
--- /dev/null
+++ b/crates/http/src/routes.rs
@@ -0,0 +1,236 @@
+//! Route matching for the HTTP trigger.
+
+#![deny(missing_docs)]
+
+use anyhow::{bail, Result};
+use indexmap::IndexMap;
+use spin_config::{Configuration, CoreComponent};
+use std::fmt::Debug;
+use tracing::{instrument, log};
+
+// TODO
+// The current implementation of the router clones the components, which could
+// become costly if we have a lot of components.
+// The router should borrow the components, which needs to introduce a lifetime
+// paramter which surfaces in the HTTP trigger (and which needs a &'static because
+// of the Hyper server.)
+//
+// For now we continue to use the router using owned data, but in the future it might
+// make sense to try borrowing the components from the trigger.
+
+/// Router for the HTTP trigger.
+#[derive(Clone, Debug)]
+pub(crate) struct Router {
+ /// Ordered map between a path and the component that should handle it.
+ pub(crate) routes: IndexMap<RoutePattern, CoreComponent>,
+}
+
+impl Router {
+ /// Build a router based on application configuration.
+ #[instrument]
+ pub(crate) fn build(app: &Configuration<CoreComponent>) -> Result<Self> {
+ let routes = app
+ .components
+ .iter()
+ .map(|c| {
+ let spin_config::TriggerConfig::Http(trigger) = &c.trigger;
+ (RoutePattern::from(&trigger.route), c.clone())
+ })
+ .collect();
+
+ log::info!(
+ "Constructed router for application {}: {:?}",
+ app.info.name,
+ routes
+ );
+
+ Ok(Self { routes })
+ }
+
+ // This assumes the order of the components in the app configuration vector
+ // has been preserved, so the routing algorithm, which takes the order into
+ // account, is correct. This seems to be the case with the TOML deserializer,
+ // but might not hold if the application configuration is deserialized in
+ // other ways.
+
+ /// Return the component that should handle the given path, or an error
+ /// if no component matches.
+ /// If there are multiple possible components registered for the same route or
+ /// wildcard, return the last one in the components vector.
+ #[instrument]
+ pub(crate) fn route<S: Into<String> + Debug>(&self, p: S) -> Result<CoreComponent> {
+ let p = p.into();
+
+ let matches = &self
+ .routes
+ .iter()
+ .filter(|(rp, _)| rp.matches(&p))
+ .map(|(_, c)| c)
+ .collect::<Vec<&CoreComponent>>();
+
+ match matches.last() {
+ Some(c) => Ok((*c).clone()),
+ None => bail!("Cannot match route for path {}", p),
+ }
+ }
+}
+
+/// Route patterns for HTTP components.
+#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
+pub(crate) enum RoutePattern {
+ Exact(String),
+ Wildcard(String),
+}
+
+impl RoutePattern {
+ /// Return a RoutePattern given a path fragment.
+ pub fn from<S: Into<String>>(path: S) -> Self {
+ let path = path.into();
+ match path.strip_suffix("/...") {
+ Some(p) => Self::Wildcard(p.to_owned()),
+ None => Self::Exact(path),
+ }
+ }
+
+ /// Returns true if the given path fragment can be handled
+ /// by the route pattern.
+ pub(crate) fn matches<S: Into<String>>(&self, p: S) -> bool {
+ let p = Self::sanitize(p);
+ match self {
+ RoutePattern::Exact(path) => &p == path,
+ RoutePattern::Wildcard(pattern) => {
+ &p == pattern || p.starts_with(&format!("{}/", pattern))
+ }
+ }
+ }
+
+ /// Strip the trailing slash from a string.
+ fn sanitize<S: Into<String>>(s: S) -> String {
+ let s = s.into();
+ // TODO
+ // This only strips a single trailing slash.
+ // Should we attempt to strip all trailing slashes?
+ match s.strip_suffix("/") {
+ Some(s) => s.into(),
+ None => s,
+ }
+ }
+}
+
+#[cfg(test)]
+mod route_tests {
+ use super::*;
+ use crate::tests::init;
+
+ #[test]
+ fn test_exact_route() {
+ init();
+
+ let rp = RoutePattern::from("/foo/bar");
+ assert_eq!(rp.matches("/foo/bar"), true);
+ assert_eq!(rp.matches("/foo/bar/"), true);
+ assert_eq!(rp.matches("/foo"), false);
+ assert_eq!(rp.matches("/foo/bar/thisshouldbefalse"), false);
+ assert_eq!(rp.matches("/abc"), false);
+ }
+
+ #[test]
+ fn test_pattern_route() {
+ let rp = RoutePattern::from("/...");
+ assert_eq!(rp.matches("/foo/bar/"), true);
+ assert_eq!(rp.matches("/foo"), true);
+ assert_eq!(rp.matches("/foo/bar/baz"), true);
+ assert_eq!(rp.matches("/this/should/really/match/everything/"), true);
+ assert_eq!(rp.matches("/"), true);
+
+ let rp = RoutePattern::from("/foo/...");
+ assert_eq!(rp.matches("/foo/bar/"), true);
+ assert_eq!(rp.matches("/foo"), true);
+ assert_eq!(rp.matches("/foo/bar/baz"), true);
+ assert_eq!(
+ rp.matches("/this/should/really/not/match/everything/"),
+ false
+ );
+ assert_eq!(rp.matches("/"), false);
+ }
+
+ #[test]
+ fn test_router() -> Result<()> {
+ let mut routes = IndexMap::new();
+
+ let foo_component = named_component("foo");
+ let foobar_component = named_component("foobar");
+
+ routes.insert(RoutePattern::from("/foo"), foo_component);
+ routes.insert(RoutePattern::from("/foo/bar"), foobar_component);
+
+ let r = Router { routes };
+
+ assert_eq!(r.route("/foo")?.id, "foo".to_string());
+ assert_eq!(r.route("/foo/bar")?.id, "foobar".to_string());
+
+ let mut routes = IndexMap::new();
+
+ let all_component = named_component("all");
+ routes.insert(RoutePattern::from("/..."), all_component);
+
+ let r = Router { routes };
+
+ assert_eq!(r.route("/foo/bar")?.id, "all".to_string());
+ assert_eq!(r.route("/abc/")?.id, "all".to_string());
+ assert_eq!(r.route("/")?.id, "all".to_string());
+ assert_eq!(
+ r.route("/this/should/be/captured?abc=def")?.id,
+ "all".to_string()
+ );
+
+ let mut routes = IndexMap::new();
+
+ let one_wildcard = named_component("one_wildcard");
+ let onetwo_wildcard = named_component("onetwo_wildcard");
+ let onetwothree_wildcard = named_component("onetwothree_wildcard");
+
+ routes.insert(RoutePattern::from("/one/..."), one_wildcard);
+ routes.insert(RoutePattern::from("/one/two/..."), onetwo_wildcard);
+ routes.insert(
+ RoutePattern::from("/one/two/three/..."),
+ onetwothree_wildcard,
+ );
+
+ let r = Router { routes };
+
+ assert_eq!(
+ r.route("/one/two/three/four")?.id,
+ "onetwothree_wildcard".to_string()
+ );
+
+ let mut routes = IndexMap::new();
+
+ let one_wildcard = named_component("one_wildcard");
+ let onetwo_wildcard = named_component("onetwo_wildcard");
+ let onetwothree_wildcard = named_component("onetwothree_wildcard");
+
+ routes.insert(
+ RoutePattern::from("/one/two/three/..."),
+ onetwothree_wildcard,
+ );
+ routes.insert(RoutePattern::from("/one/two/..."), onetwo_wildcard);
+ routes.insert(RoutePattern::from("/one/..."), one_wildcard);
+
+ let r = Router { routes };
+
+ assert_eq!(
+ r.route("/one/two/three/four")?.id,
+ "one_wildcard".to_string()
+ );
+
+ Ok(())
+ }
+
+ fn named_component(id: &str) -> CoreComponent {
+ CoreComponent {
+ id: id.to_string(),
+ ..Default::default()
+ }
+ }
+}
diff --git a/crates/http/src/spin.rs b/crates/http/src/spin.rs
new file mode 100644
index 0000000000..d3940957e4
--- /dev/null
+++ b/crates/http/src/spin.rs
@@ -0,0 +1,123 @@
+use crate::spin_http::{Method, SpinHttp};
+use crate::HttpExecutor;
+use crate::{ExecutionContext, RuntimeContext};
+use anyhow::Result;
+use async_trait::async_trait;
+use http::Uri;
+use hyper::{Body, Request, Response};
+use std::{net::SocketAddr, str::FromStr};
+use tracing::{instrument, log};
+use wasmtime::{Instance, Store};
+
+#[derive(Clone)]
+pub struct SpinHttpExecutor;
+
+#[async_trait]
+impl HttpExecutor for SpinHttpExecutor {
+ #[instrument(skip(engine))]
+ async fn execute(
+ engine: &ExecutionContext,
+ component: &String,
+ req: Request<Body>,
+ _client_addr: SocketAddr,
+ ) -> Result<Response<Body>> {
+ log::info!(
+ "Executing request using the Spin executor for component {}",
+ component
+ );
+ let (store, instance) = engine.prepare_component(component, None)?;
+ let res = Self::execute_impl(store, instance, req).await?;
+ log::info!(
+ "Request finished, sending response with status code {}",
+ res.status()
+ );
+ Ok(res)
+ }
+}
+
+impl SpinHttpExecutor {
+ pub async fn execute_impl(
+ mut store: Store<RuntimeContext>,
+ instance: Instance,
+ req: Request<Body>,
+ ) -> Result<Response<Body>> {
+ let engine = SpinHttp::new(&mut store, &instance, |host| host.data.as_mut().unwrap())?;
+ let (parts, bytes) = req.into_parts();
+ let bytes = hyper::body::to_bytes(bytes).await?.to_vec();
+ let body = Some(&bytes[..]);
+
+ let method = Self::method(&parts.method);
+ let headers = &Self::headers(&parts.headers)?;
+ let params = &Self::params(&parts.uri)?;
+ let params: Vec<(&str, &str)> = params
+ .iter()
+ .map(|(k, v)| (k.as_str(), v.as_str()))
+ .collect();
+
+ let req = crate::spin_http::Request {
+ method,
+ uri: &parts.uri.to_string(),
+ headers,
+ params: ¶ms,
+ body,
+ };
+
+ let res = engine.handler(&mut store, req)?;
+ let mut response = http::Response::builder().status(res.status);
+ Self::append_headers(response.headers_mut().unwrap(), res.headers)?;
+
+ let body = match res.body {
+ Some(b) => Body::from(b),
+ None => Body::empty(),
+ };
+
+ Ok(response.body(body)?)
+ }
+
+ fn method(m: &http::Method) -> Method {
+ match *m {
+ http::Method::GET => Method::Get,
+ http::Method::POST => Method::Post,
+ http::Method::PUT => Method::Put,
+ http::Method::DELETE => Method::Delete,
+ http::Method::PATCH => Method::Patch,
+ http::Method::HEAD => Method::Head,
+ _ => todo!(),
+ }
+ }
+
+ fn headers(hm: &http::HeaderMap) -> Result<Vec<(&str, &str)>> {
+ let mut res = Vec::new();
+ for (name, value) in hm
+ .iter()
+ .map(|(name, value)| (name.as_str(), std::str::from_utf8(value.as_bytes())))
+ {
+ let value = value?;
+ res.push((name, value));
+ }
+
+ Ok(res)
+ }
+
+ fn append_headers(res: &mut http::HeaderMap, src: Option<Vec<(String, String)>>) -> Result<()> {
+ if let Some(src) = src {
+ for (k, v) in src.iter() {
+ res.insert(
+ http::header::HeaderName::from_str(k)?,
+ http::header::HeaderValue::from_str(v)?,
+ );
+ }
+ };
+
+ Ok(())
+ }
+
+ fn params(uri: &Uri) -> Result<Vec<(String, String)>> {
+ match uri.query() {
+ Some(q) => Ok(url::form_urlencoded::parse(q.as_bytes())
+ .into_owned()
+ .collect::<Vec<_>>()),
+ None => Ok(vec![]),
+ }
+ }
+}
diff --git a/crates/http/src/wagi.rs b/crates/http/src/wagi.rs
new file mode 100644
index 0000000000..7052570abc
--- /dev/null
+++ b/crates/http/src/wagi.rs
@@ -0,0 +1,28 @@
+use crate::ExecutionContext;
+use crate::HttpExecutor;
+use anyhow::Result;
+use async_trait::async_trait;
+use hyper::{Body, Request, Response};
+use std::net::SocketAddr;
+use tracing::{instrument, log};
+
+#[derive(Clone)]
+pub struct WagiHttpExecutor;
+
+#[async_trait]
+impl HttpExecutor for WagiHttpExecutor {
+ #[instrument(skip(_engine))]
+ async fn execute(
+ _engine: &ExecutionContext,
+ _component: &String,
+ _req: Request<Body>,
+ _client_addr: SocketAddr,
+ ) -> Result<Response<Body>> {
+ log::info!(
+ "Executing request using the Wagi executor for component {}",
+ _component
+ );
+
+ todo!("Wagi executor not implemented yet.")
+ }
+}
diff --git a/templates/spin-http/Cargo.lock b/templates/spin-http/Cargo.lock
index a17f51ac00..871746f7f6 100644
--- a/templates/spin-http/Cargo.lock
+++ b/templates/spin-http/Cargo.lock
@@ -3,153 +3,204 @@
version = 3
[[package]]
- name = "anyhow"
- version = "1.0.52"
- source = "registry+https://github.com/rust-lang/crates.io-index"
- checksum = "84450d0b4a8bd1ba4144ce8ce718fbc5d071358b1e5384bace6536b3d1f2d5b3"
-
-[[package]]
- name = "async-trait"
- version = "0.1.52"
- source = "registry+https://github.com/rust-lang/crates.io-index"
- checksum = "061a7acccaa286c011ddc30970520b98fa40e00c9d644633fb26b5fc63a265e3"
- dependencies = [ "proc-macro2", "quote", "syn" ]
-
-[[package]]
- name = "bitflags"
- version = "1.3.2"
- source = "registry+https://github.com/rust-lang/crates.io-index"
- checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
-
+name = "anyhow"
+version = "1.0.52"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "84450d0b4a8bd1ba4144ce8ce718fbc5d071358b1e5384bace6536b3d1f2d5b3"
+
[[package]]
- name = "heck"
- version = "0.3.3"
- source = "registry+https://github.com/rust-lang/crates.io-index"
- checksum = "6d621efb26863f0e9924c6ac577e8275e5e6b77455db64ffa6c65c904e9e132c"
- dependencies = [ "unicode-segmentation" ]
+name = "async-trait"
+version = "0.1.52"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "061a7acccaa286c011ddc30970520b98fa40e00c9d644633fb26b5fc63a265e3"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "bitflags"
+version = "1.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
+
+[[package]]
+name = "heck"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6d621efb26863f0e9924c6ac577e8275e5e6b77455db64ffa6c65c904e9e132c"
+dependencies = [
+ "unicode-segmentation",
+]
-[[package]]
- name = "id-arena"
- version = "2.2.1"
- source = "registry+https://github.com/rust-lang/crates.io-index"
- checksum = "25a2bc672d1148e28034f176e01fffebb08b35768468cc954630da77a1449005"
-
-[[package]]
- name = "memchr"
- version = "2.4.1"
- source = "registry+https://github.com/rust-lang/crates.io-index"
- checksum = "308cc39be01b73d0d18f82a0e7b2a3df85245f84af96fdddc5d202d27e47b86a"
-
-[[package]]
- name = "proc-macro2"
- version = "1.0.36"
- source = "registry+https://github.com/rust-lang/crates.io-index"
- checksum = "c7342d5883fbccae1cc37a2353b09c87c9b0f3afd73f5fb9bba687a1f733b029"
- dependencies = [ "unicode-xid" ]
+[[package]]
+name = "id-arena"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "25a2bc672d1148e28034f176e01fffebb08b35768468cc954630da77a1449005"
[[package]]
- name = "pulldown-cmark"
- version = "0.8.0"
- source = "registry+https://github.com/rust-lang/crates.io-index"
- checksum = "ffade02495f22453cd593159ea2f59827aae7f53fa8323f756799b670881dcf8"
- dependencies = [ "bitflags", "memchr", "unicase" ]
+name = "memchr"
+version = "2.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "308cc39be01b73d0d18f82a0e7b2a3df85245f84af96fdddc5d202d27e47b86a"
[[package]]
- name = "quote"
- version = "1.0.14"
- source = "registry+https://github.com/rust-lang/crates.io-index"
- checksum = "47aa80447ce4daf1717500037052af176af5d38cc3e571d9ec1c7353fc10c87d"
- dependencies = [ "proc-macro2" ]
+name = "proc-macro2"
+version = "1.0.36"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c7342d5883fbccae1cc37a2353b09c87c9b0f3afd73f5fb9bba687a1f733b029"
+dependencies = [
+ "unicode-xid",
+]
[[package]]
- name = "spinhelloworld"
- version = "0.1.0"
- dependencies = [ "wit-bindgen-rust" ]
+name = "pulldown-cmark"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ffade02495f22453cd593159ea2f59827aae7f53fa8323f756799b670881dcf8"
+dependencies = [
+ "bitflags",
+ "memchr",
+ "unicase",
+]
-[[package]]
- name = "syn"
- version = "1.0.85"
- source = "registry+https://github.com/rust-lang/crates.io-index"
- checksum = "a684ac3dcd8913827e18cd09a68384ee66c1de24157e3c556c9ab16d85695fb7"
- dependencies = [ "proc-macro2", "quote", "unicode-xid" ]
-
-[[package]]
- name = "tinyvec"
- version = "1.5.1"
- source = "registry+https://github.com/rust-lang/crates.io-index"
- checksum = "2c1c1d5a42b6245520c249549ec267180beaffcc0615401ac8e31853d4b6d8d2"
- dependencies = [ "tinyvec_macros" ]
-
-[[package]]
- name = "tinyvec_macros"
- version = "0.1.0"
- source = "registry+https://github.com/rust-lang/crates.io-index"
- checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c"
-
-[[package]]
- name = "unicase"
- version = "2.6.0"
- source = "registry+https://github.com/rust-lang/crates.io-index"
- checksum = "50f37be617794602aabbeee0be4f259dc1778fabe05e2d67ee8f79326d5cb4f6"
- dependencies = [ "version_check" ]
-
-[[package]]
- name = "unicode-normalization"
- version = "0.1.19"
- source = "registry+https://github.com/rust-lang/crates.io-index"
- checksum = "d54590932941a9e9266f0832deed84ebe1bf2e4c9e4a3554d393d18f5e854bf9"
- dependencies = [ "tinyvec" ]
-
-[[package]]
- name = "unicode-segmentation"
- version = "1.8.0"
- source = "registry+https://github.com/rust-lang/crates.io-index"
- checksum = "8895849a949e7845e06bd6dc1aa51731a103c42707010a5b591c0038fb73385b"
-
-[[package]]
- name = "unicode-xid"
- version = "0.2.2"
- source = "registry+https://github.com/rust-lang/crates.io-index"
- checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3"
-
-[[package]]
- name = "version_check"
- version = "0.9.4"
- source = "registry+https://github.com/rust-lang/crates.io-index"
- checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
-
-[[package]]
- name = "wit-bindgen-gen-core"
- version = "0.1.0"
- source = "git+https://github.com/bytecodealliance/wit-bindgen?rev=439c5f8cee12a7f831103c27e2198cfd4b4bad24#439c5f8cee12a7f831103c27e2198cfd4b4bad24"
- dependencies = [ "anyhow", "wit-parser" ]
-
-[[package]]
- name = "wit-bindgen-gen-rust"
- version = "0.1.0"
- source = "git+https://github.com/bytecodealliance/wit-bindgen?rev=439c5f8cee12a7f831103c27e2198cfd4b4bad24#439c5f8cee12a7f831103c27e2198cfd4b4bad24"
- dependencies = [ "heck", "wit-bindgen-gen-core" ]
-
-[[package]]
- name = "wit-bindgen-gen-rust-wasm"
- version = "0.1.0"
- source = "git+https://github.com/bytecodealliance/wit-bindgen?rev=439c5f8cee12a7f831103c27e2198cfd4b4bad24#439c5f8cee12a7f831103c27e2198cfd4b4bad24"
- dependencies = [ "heck", "wit-bindgen-gen-core", "wit-bindgen-gen-rust" ]
-
-[[package]]
- name = "wit-bindgen-rust"
- version = "0.1.0"
- source = "git+https://github.com/bytecodealliance/wit-bindgen?rev=439c5f8cee12a7f831103c27e2198cfd4b4bad24#439c5f8cee12a7f831103c27e2198cfd4b4bad24"
- dependencies = [ "async-trait", "bitflags", "wit-bindgen-rust-impl" ]
-
-[[package]]
- name = "wit-bindgen-rust-impl"
- version = "0.1.0"
- source = "git+https://github.com/bytecodealliance/wit-bindgen?rev=439c5f8cee12a7f831103c27e2198cfd4b4bad24#439c5f8cee12a7f831103c27e2198cfd4b4bad24"
- dependencies = [ "proc-macro2", "syn", "wit-bindgen-gen-core", "wit-bindgen-gen-rust-wasm" ]
-
-[[package]]
- name = "wit-parser"
- version = "0.1.0"
- source = "git+https://github.com/bytecodealliance/wit-bindgen?rev=439c5f8cee12a7f831103c27e2198cfd4b4bad24#439c5f8cee12a7f831103c27e2198cfd4b4bad24"
- dependencies = [ "anyhow", "id-arena", "pulldown-cmark", "unicode-normalization", "unicode-xid" ]
+[[package]]
+name = "quote"
+version = "1.0.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47aa80447ce4daf1717500037052af176af5d38cc3e571d9ec1c7353fc10c87d"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "spinhelloworld"
+version = "0.1.0"
+dependencies = [
+ "wit-bindgen-rust",
+]
+
+[[package]]
+name = "syn"
+version = "1.0.85"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a684ac3dcd8913827e18cd09a68384ee66c1de24157e3c556c9ab16d85695fb7"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-xid",
+]
+
+[[package]]
+name = "tinyvec"
+version = "1.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2c1c1d5a42b6245520c249549ec267180beaffcc0615401ac8e31853d4b6d8d2"
+dependencies = [
+ "tinyvec_macros",
+]
+
+[[package]]
+name = "tinyvec_macros"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c"
+
+[[package]]
+name = "unicase"
+version = "2.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "50f37be617794602aabbeee0be4f259dc1778fabe05e2d67ee8f79326d5cb4f6"
+dependencies = [
+ "version_check",
+]
+
+[[package]]
+name = "unicode-normalization"
+version = "0.1.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d54590932941a9e9266f0832deed84ebe1bf2e4c9e4a3554d393d18f5e854bf9"
+dependencies = [
+ "tinyvec",
+]
+
+[[package]]
+name = "unicode-segmentation"
+version = "1.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8895849a949e7845e06bd6dc1aa51731a103c42707010a5b591c0038fb73385b"
+
+[[package]]
+name = "unicode-xid"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3"
+
+[[package]]
+name = "version_check"
+version = "0.9.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
+
+[[package]]
+name = "wit-bindgen-gen-core"
+version = "0.1.0"
+source = "git+https://github.com/bytecodealliance/wit-bindgen?rev=439c5f8cee12a7f831103c27e2198cfd4b4bad24#439c5f8cee12a7f831103c27e2198cfd4b4bad24"
+dependencies = [
+ "anyhow",
+ "wit-parser",
+]
+
+[[package]]
+name = "wit-bindgen-gen-rust"
+version = "0.1.0"
+source = "git+https://github.com/bytecodealliance/wit-bindgen?rev=439c5f8cee12a7f831103c27e2198cfd4b4bad24#439c5f8cee12a7f831103c27e2198cfd4b4bad24"
+dependencies = [
+ "heck",
+ "wit-bindgen-gen-core",
+]
+
+[[package]]
+name = "wit-bindgen-gen-rust-wasm"
+version = "0.1.0"
+source = "git+https://github.com/bytecodealliance/wit-bindgen?rev=439c5f8cee12a7f831103c27e2198cfd4b4bad24#439c5f8cee12a7f831103c27e2198cfd4b4bad24"
+dependencies = [
+ "heck",
+ "wit-bindgen-gen-core",
+ "wit-bindgen-gen-rust",
+]
+
+[[package]]
+name = "wit-bindgen-rust"
+version = "0.1.0"
+source = "git+https://github.com/bytecodealliance/wit-bindgen?rev=439c5f8cee12a7f831103c27e2198cfd4b4bad24#439c5f8cee12a7f831103c27e2198cfd4b4bad24"
+dependencies = [
+ "async-trait",
+ "bitflags",
+ "wit-bindgen-rust-impl",
+]
+
+[[package]]
+name = "wit-bindgen-rust-impl"
+version = "0.1.0"
+source = "git+https://github.com/bytecodealliance/wit-bindgen?rev=439c5f8cee12a7f831103c27e2198cfd4b4bad24#439c5f8cee12a7f831103c27e2198cfd4b4bad24"
+dependencies = [
+ "proc-macro2",
+ "syn",
+ "wit-bindgen-gen-core",
+ "wit-bindgen-gen-rust-wasm",
+]
+
+[[package]]
+name = "wit-parser"
+version = "0.1.0"
+source = "git+https://github.com/bytecodealliance/wit-bindgen?rev=439c5f8cee12a7f831103c27e2198cfd4b4bad24#439c5f8cee12a7f831103c27e2198cfd4b4bad24"
+dependencies = [
+ "anyhow",
+ "id-arena",
+ "pulldown-cmark",
+ "unicode-normalization",
+ "unicode-xid",
+]
diff --git a/templates/spin-http/spin.toml b/templates/spin-http/spin.toml
index f6d57709f0..4b3cf522b6 100644
--- a/templates/spin-http/spin.toml
+++ b/templates/spin-http/spin.toml
@@ -8,4 +8,4 @@ trigger = "http"
source = "target/wasm32-wasi/release/spinhelloworld.wasm"
id = "hello"
[component.trigger]
- route = "/hello"
+ route = "/hello/..."
| 57
|
[
"36"
] |
diff --git a/crates/http/tests/rust-http-test/src/lib.rs b/crates/http/tests/rust-http-test/src/lib.rs
index 02de4a9d30..5b46a74a37 100644
--- a/crates/http/tests/rust-http-test/src/lib.rs
+++ b/crates/http/tests/rust-http-test/src/lib.rs
@@ -6,6 +6,15 @@ struct SpinHttp {}
impl spin_http::SpinHttp for SpinHttp {
fn handler(req: Request) -> Response {
+ assert!(req.params.contains(&("abc".to_string(), "def".to_string())));
+
+ assert!(req
+ .headers
+ .contains(&("x-custom-foo".to_string(), "bar".to_string())));
+ assert!(req
+ .headers
+ .contains(&("x-custom-foo2".to_string(), "bar2".to_string())));
+
let body = Some(
format!(
"Hello, {}",
|
95f9da2a41aded597a437ad041a5a13ab19604ee
|
|
561b3e132b99537d823b33984e371bb8326ad3e6
|
Using the llm 2.0 crate with Rust SDK fails with `import `fermyon:spin/llm@2.0.0` has the wrong type`
Using the Rust SDK from version `spin 2.0.0-pre0 (561b3e1 2023-10-30)` with a following reference to the SDK `spin-sdk = { git = "https://github.com/fermyon/spin", branch = "main" }`, fails with the following error, when trying to use the `llm` crate:
```
Error: Failed to instantiate component 'sentiment-analysis-rust'
Caused by:
0: import `fermyon:spin/llm@2.0.0` has the wrong type
1: instance export `infer` has the wrong type
2: expected func found nothing
```
|
2023-10-31T12:01:57Z
|
fermyon__spin-1997
|
fermyon/spin
|
3.2
|
diff --git a/Cargo.lock b/Cargo.lock
index 44ef3f4b38..605a9cad82 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1830,7 +1830,6 @@ dependencies = [
"anyhow",
"async-trait",
"derive_builder 0.12.0",
- "hyper 0.14.25",
"hyper-tls",
"nix 0.26.2",
"regex",
diff --git a/crates/llm-local/src/lib.rs b/crates/llm-local/src/lib.rs
index aa9d1355b0..60e1b7c02a 100644
--- a/crates/llm-local/src/lib.rs
+++ b/crates/llm-local/src/lib.rs
@@ -11,7 +11,7 @@ use llm::{
use rand::SeedableRng;
use spin_core::async_trait;
use spin_llm::{LlmEngine, MODEL_ALL_MINILM_L6_V2};
-use spin_world::v1::llm::{self as wasi_llm};
+use spin_world::v2::llm::{self as wasi_llm};
use std::{
collections::hash_map::Entry,
collections::HashMap,
diff --git a/crates/llm-remote-http/src/lib.rs b/crates/llm-remote-http/src/lib.rs
index 6110dc8979..15c29baf60 100644
--- a/crates/llm-remote-http/src/lib.rs
+++ b/crates/llm-remote-http/src/lib.rs
@@ -7,7 +7,7 @@ use serde::{Deserialize, Serialize};
use serde_json::json;
use spin_core::async_trait;
use spin_llm::LlmEngine;
-use spin_world::v1::llm::{self as wasi_llm};
+use spin_world::v2::llm::{self as wasi_llm};
#[derive(Clone)]
pub struct RemoteHttpLlmEngine {
diff --git a/crates/llm/src/host_component.rs b/crates/llm/src/host_component.rs
index 62d9476b0b..8574e6bb0e 100644
--- a/crates/llm/src/host_component.rs
+++ b/crates/llm/src/host_component.rs
@@ -25,7 +25,8 @@ impl HostComponent for LlmComponent {
linker: &mut spin_core::Linker<T>,
get: impl Fn(&mut spin_core::Data<T>) -> &mut Self::Data + Send + Sync + Copy + 'static,
) -> anyhow::Result<()> {
- spin_world::v1::llm::add_to_linker(linker, get)
+ spin_world::v1::llm::add_to_linker(linker, get)?;
+ spin_world::v2::llm::add_to_linker(linker, get)
}
fn build_data(&self) -> Self::Data {
diff --git a/crates/llm/src/lib.rs b/crates/llm/src/lib.rs
index 2d12769497..f322fe01dd 100644
--- a/crates/llm/src/lib.rs
+++ b/crates/llm/src/lib.rs
@@ -2,7 +2,8 @@ pub mod host_component;
use spin_app::MetadataKey;
use spin_core::async_trait;
-use spin_world::v1::llm::{self as wasi_llm};
+use spin_world::v1::llm::{self as v1};
+use spin_world::v2::llm::{self as v2};
use std::collections::HashSet;
pub use crate::host_component::LlmComponent;
@@ -14,16 +15,16 @@ pub const AI_MODELS_KEY: MetadataKey<HashSet<String>> = MetadataKey::new("ai_mod
pub trait LlmEngine: Send + Sync {
async fn infer(
&mut self,
- model: wasi_llm::InferencingModel,
+ model: v1::InferencingModel,
prompt: String,
- params: wasi_llm::InferencingParams,
- ) -> Result<wasi_llm::InferencingResult, wasi_llm::Error>;
+ params: v2::InferencingParams,
+ ) -> Result<v2::InferencingResult, v2::Error>;
async fn generate_embeddings(
&mut self,
- model: wasi_llm::EmbeddingModel,
+ model: v2::EmbeddingModel,
data: Vec<String>,
- ) -> Result<wasi_llm::EmbeddingsResult, wasi_llm::Error>;
+ ) -> Result<v2::EmbeddingsResult, v2::Error>;
}
pub struct LlmDispatch {
@@ -32,13 +33,13 @@ pub struct LlmDispatch {
}
#[async_trait]
-impl wasi_llm::Host for LlmDispatch {
+impl v2::Host for LlmDispatch {
async fn infer(
&mut self,
- model: wasi_llm::InferencingModel,
+ model: v2::InferencingModel,
prompt: String,
- params: Option<wasi_llm::InferencingParams>,
- ) -> anyhow::Result<Result<wasi_llm::InferencingResult, wasi_llm::Error>> {
+ params: Option<v2::InferencingParams>,
+ ) -> anyhow::Result<Result<v2::InferencingResult, v2::Error>> {
if !self.allowed_models.contains(&model) {
return Ok(Err(access_denied_error(&model)));
}
@@ -47,7 +48,7 @@ impl wasi_llm::Host for LlmDispatch {
.infer(
model,
prompt,
- params.unwrap_or(wasi_llm::InferencingParams {
+ params.unwrap_or(v2::InferencingParams {
max_tokens: 100,
repeat_penalty: 1.1,
repeat_penalty_last_n_token_count: 64,
@@ -61,9 +62,9 @@ impl wasi_llm::Host for LlmDispatch {
async fn generate_embeddings(
&mut self,
- m: wasi_llm::EmbeddingModel,
+ m: v1::EmbeddingModel,
data: Vec<String>,
- ) -> anyhow::Result<Result<wasi_llm::EmbeddingsResult, wasi_llm::Error>> {
+ ) -> anyhow::Result<Result<v2::EmbeddingsResult, v2::Error>> {
if !self.allowed_models.contains(&m) {
return Ok(Err(access_denied_error(&m)));
}
@@ -71,8 +72,36 @@ impl wasi_llm::Host for LlmDispatch {
}
}
-fn access_denied_error(model: &str) -> wasi_llm::Error {
- wasi_llm::Error::InvalidInput(format!(
+#[async_trait]
+impl v1::Host for LlmDispatch {
+ async fn infer(
+ &mut self,
+ model: v1::InferencingModel,
+ prompt: String,
+ params: Option<v1::InferencingParams>,
+ ) -> anyhow::Result<Result<v1::InferencingResult, v1::Error>> {
+ Ok(
+ <Self as v2::Host>::infer(self, model, prompt, params.map(Into::into))
+ .await?
+ .map(Into::into)
+ .map_err(Into::into),
+ )
+ }
+
+ async fn generate_embeddings(
+ &mut self,
+ model: v1::EmbeddingModel,
+ data: Vec<String>,
+ ) -> anyhow::Result<Result<v1::EmbeddingsResult, v1::Error>> {
+ Ok(<Self as v2::Host>::generate_embeddings(self, model, data)
+ .await?
+ .map(Into::into)
+ .map_err(Into::into))
+ }
+}
+
+fn access_denied_error(model: &str) -> v2::Error {
+ v2::Error::InvalidInput(format!(
"The component does not have access to use '{model}'. To give the component access, add '{model}' to the 'ai_models' key for the component in your spin.toml manifest"
))
}
diff --git a/crates/trigger/src/runtime_config/llm.rs b/crates/trigger/src/runtime_config/llm.rs
index bead39107c..af5f2a3629 100644
--- a/crates/trigger/src/runtime_config/llm.rs
+++ b/crates/trigger/src/runtime_config/llm.rs
@@ -1,7 +1,7 @@
use async_trait::async_trait;
use spin_llm::LlmEngine;
use spin_llm_remote_http::RemoteHttpLlmEngine;
-use spin_world::v1::llm as wasi_llm;
+use spin_world::v2::llm as wasi_llm;
use url::Url;
#[derive(Default)]
diff --git a/crates/world/src/conversions.rs b/crates/world/src/conversions.rs
index f2b068b14e..5430f17860 100644
--- a/crates/world/src/conversions.rs
+++ b/crates/world/src/conversions.rs
@@ -168,3 +168,53 @@ mod redis {
}
}
}
+
+mod llm {
+ use super::*;
+
+ impl From<v1::llm::InferencingParams> for v2::llm::InferencingParams {
+ fn from(value: v1::llm::InferencingParams) -> Self {
+ Self {
+ max_tokens: value.max_tokens,
+ repeat_penalty: value.repeat_penalty,
+ repeat_penalty_last_n_token_count: value.repeat_penalty_last_n_token_count,
+ temperature: value.temperature,
+ top_k: value.top_k,
+ top_p: value.top_p,
+ }
+ }
+ }
+
+ impl From<v2::llm::InferencingResult> for v1::llm::InferencingResult {
+ fn from(value: v2::llm::InferencingResult) -> Self {
+ Self {
+ text: value.text,
+ usage: v1::llm::InferencingUsage {
+ prompt_token_count: value.usage.prompt_token_count,
+ generated_token_count: value.usage.prompt_token_count,
+ },
+ }
+ }
+ }
+
+ impl From<v2::llm::EmbeddingsResult> for v1::llm::EmbeddingsResult {
+ fn from(value: v2::llm::EmbeddingsResult) -> Self {
+ Self {
+ embeddings: value.embeddings,
+ usage: v1::llm::EmbeddingsUsage {
+ prompt_token_count: value.usage.prompt_token_count,
+ },
+ }
+ }
+ }
+
+ impl From<v2::llm::Error> for v1::llm::Error {
+ fn from(value: v2::llm::Error) -> Self {
+ match value {
+ v2::llm::Error::ModelNotSupported => Self::ModelNotSupported,
+ v2::llm::Error::RuntimeError(s) => Self::RuntimeError(s),
+ v2::llm::Error::InvalidInput(s) => Self::InvalidInput(s),
+ }
+ }
+ }
+}
diff --git a/sdk/rust/src/http.rs b/sdk/rust/src/http.rs
index 9a74d134d6..ae166fbdaf 100644
--- a/sdk/rust/src/http.rs
+++ b/sdk/rust/src/http.rs
@@ -262,7 +262,8 @@ impl Response {
ResponseBuilder { response: self }
}
- fn builder() -> ResponseBuilder {
+ /// Creates a [`ResponseBuilder`]
+ pub fn builder() -> ResponseBuilder {
ResponseBuilder::new(200)
}
}
| 1,997
|
[
"1995"
] |
diff --git a/crates/e2e-testing/Cargo.toml b/crates/e2e-testing/Cargo.toml
index 7fbd464ec6..de23d7f786 100644
--- a/crates/e2e-testing/Cargo.toml
+++ b/crates/e2e-testing/Cargo.toml
@@ -10,12 +10,11 @@ doctest = false
[dependencies]
anyhow = "1.0"
async-trait = "0.1"
-tokio = { version = "1.23", features = [ "full" ] }
-hyper = { version = "0.14", features = [ "full" ] }
+tokio = { version = "1.23", features = ["full"] }
regex = "1.5.5"
reqwest = { version = "0.11", features = ["blocking"] }
nix = "0.26.1"
url = "2.2.2"
derive_builder = "0.12.0"
hyper-tls = "0.5.0"
-tempfile = "3.3.0"
\ No newline at end of file
+tempfile = "3.3.0"
diff --git a/crates/e2e-testing/src/http_asserts.rs b/crates/e2e-testing/src/http_asserts.rs
index 314427e156..5e5133a079 100644
--- a/crates/e2e-testing/src/http_asserts.rs
+++ b/crates/e2e-testing/src/http_asserts.rs
@@ -1,16 +1,14 @@
use crate::ensure_eq;
use anyhow::Result;
-use hyper::client::HttpConnector;
-use hyper::{body, Body, Client, Method, Request, Response};
-use hyper_tls::HttpsConnector;
+use reqwest::{Method, Request, Response};
use std::str;
pub async fn assert_status(url: &str, expected: u16) -> Result<()> {
let resp = make_request(Method::GET, url, "").await?;
let status = resp.status();
- let response = body::to_bytes(resp.into_body()).await.unwrap().to_vec();
- let actual_body = str::from_utf8(&response).unwrap().to_string();
+ let body = resp.bytes().await?;
+ let actual_body = str::from_utf8(&body).unwrap().to_string();
ensure_eq!(status, expected, "{}", actual_body);
@@ -29,8 +27,8 @@ pub async fn assert_http_response(
let status = res.status();
let headers = res.headers().clone();
- let response = body::to_bytes(res.into_body()).await.unwrap().to_vec();
- let actual_body = str::from_utf8(&response).unwrap().to_string();
+ let body = res.bytes().await?;
+ let actual_body = str::from_utf8(&body).unwrap().to_string();
ensure_eq!(
expected,
@@ -55,26 +53,15 @@ pub async fn assert_http_response(
Ok(())
}
-pub async fn create_request(method: Method, url: &str, body: &str) -> Result<Request<Body>> {
- let req = Request::builder()
- .method(method)
- .uri(url)
- .body(Body::from(body.to_string()))
- .expect("request builder");
+pub async fn create_request(method: Method, url: &str, body: &str) -> Result<Request> {
+ let mut req = reqwest::Request::new(method, url.try_into()?);
+ *req.body_mut() = Some(body.to_owned().into());
Ok(req)
}
-pub fn create_client() -> Client<HttpsConnector<HttpConnector>> {
- let connector = HttpsConnector::new();
- Client::builder()
- .pool_max_idle_per_host(0)
- .build::<_, hyper::Body>(connector)
-}
-
-pub async fn make_request(method: Method, path: &str, body: &str) -> Result<Response<Body>> {
- let c = create_client();
- let req = create_request(method, path, body);
- let resp = c.request(req.await?).await.unwrap();
- Ok(resp)
+pub async fn make_request(method: Method, path: &str, body: &str) -> Result<Response> {
+ let req = create_request(method, path, body).await?;
+ let client = reqwest::Client::new();
+ Ok(client.execute(req).await?)
}
diff --git a/tests/spinup_tests.rs b/tests/spinup_tests.rs
index 6cd484fa64..1943827f0e 100644
--- a/tests/spinup_tests.rs
+++ b/tests/spinup_tests.rs
@@ -103,6 +103,11 @@ mod spinup_tests {
testcases::head_rust_sdk_redis(CONTROLLER).await
}
+ #[tokio::test]
+ async fn llm_works() {
+ testcases::llm_works(CONTROLLER).await
+ }
+
#[tokio::test]
async fn header_env_routes_works() {
testcases::header_env_routes_works(CONTROLLER).await
diff --git a/tests/testcases/llm/Cargo.lock b/tests/testcases/llm/Cargo.lock
new file mode 100644
index 0000000000..afea20d9a5
--- /dev/null
+++ b/tests/testcases/llm/Cargo.lock
@@ -0,0 +1,582 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 3
+
+[[package]]
+name = "ai"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "spin-sdk",
+]
+
+[[package]]
+name = "anyhow"
+version = "1.0.72"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b13c32d80ecc7ab747b80c3784bce54ee8a7a0cc4fbda9bf4cda2cf6fe90854"
+
+[[package]]
+name = "async-trait"
+version = "0.1.74"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.28",
+]
+
+[[package]]
+name = "autocfg"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
+
+[[package]]
+name = "bitflags"
+version = "2.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b4682ae6287fcf752ecaabbfcc7b6f9b72aa33933dc23a554d853aea8eea8635"
+
+[[package]]
+name = "bytes"
+version = "1.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "89b2fd2a0dcf38d7971e2194b6b6eebab45ae01067456a7fd93d5547a61b70be"
+
+[[package]]
+name = "equivalent"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5"
+
+[[package]]
+name = "fnv"
+version = "1.0.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
+
+[[package]]
+name = "form_urlencoded"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a62bc1cf6f830c2ec14a513a9fb124d0a213a629668a4186f329db21fe045652"
+dependencies = [
+ "percent-encoding",
+]
+
+[[package]]
+name = "futures"
+version = "0.3.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "da0290714b38af9b4a7b094b8a37086d1b4e61f2df9122c3cad2577669145335"
+dependencies = [
+ "futures-channel",
+ "futures-core",
+ "futures-executor",
+ "futures-io",
+ "futures-sink",
+ "futures-task",
+ "futures-util",
+]
+
+[[package]]
+name = "futures-channel"
+version = "0.3.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff4dd66668b557604244583e3e1e1eada8c5c2e96a6d0d6653ede395b78bbacb"
+dependencies = [
+ "futures-core",
+ "futures-sink",
+]
+
+[[package]]
+name = "futures-core"
+version = "0.3.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eb1d22c66e66d9d72e1758f0bd7d4fd0bee04cad842ee34587d68c07e45d088c"
+
+[[package]]
+name = "futures-executor"
+version = "0.3.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0f4fb8693db0cf099eadcca0efe2a5a22e4550f98ed16aba6c48700da29597bc"
+dependencies = [
+ "futures-core",
+ "futures-task",
+ "futures-util",
+]
+
+[[package]]
+name = "futures-io"
+version = "0.3.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8bf34a163b5c4c52d0478a4d757da8fb65cabef42ba90515efee0f6f9fa45aaa"
+
+[[package]]
+name = "futures-macro"
+version = "0.3.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "53b153fd91e4b0147f4aced87be237c98248656bb01050b96bf3ee89220a8ddb"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.28",
+]
+
+[[package]]
+name = "futures-sink"
+version = "0.3.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e36d3378ee38c2a36ad710c5d30c2911d752cb941c00c72dbabfb786a7970817"
+
+[[package]]
+name = "futures-task"
+version = "0.3.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "efd193069b0ddadc69c46389b740bbccdd97203899b48d09c5f7969591d6bae2"
+
+[[package]]
+name = "futures-util"
+version = "0.3.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a19526d624e703a3179b3d322efec918b6246ea0fa51d41124525f00f1cc8104"
+dependencies = [
+ "futures-channel",
+ "futures-core",
+ "futures-io",
+ "futures-macro",
+ "futures-sink",
+ "futures-task",
+ "memchr",
+ "pin-project-lite",
+ "pin-utils",
+ "slab",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.14.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f93e7192158dbcda357bdec5fb5788eebf8bbac027f3f33e719d29135ae84156"
+
+[[package]]
+name = "heck"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
+dependencies = [
+ "unicode-segmentation",
+]
+
+[[package]]
+name = "http"
+version = "0.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bd6effc99afb63425aff9b05836f029929e345a6148a14b7ecd5ab67af944482"
+dependencies = [
+ "bytes",
+ "fnv",
+ "itoa",
+]
+
+[[package]]
+name = "id-arena"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "25a2bc672d1148e28034f176e01fffebb08b35768468cc954630da77a1449005"
+
+[[package]]
+name = "indexmap"
+version = "2.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8adf3ddd720272c6ea8bf59463c04e0f93d0bbf7c5439b691bca2987e0270897"
+dependencies = [
+ "equivalent",
+ "hashbrown",
+ "serde",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38"
+
+[[package]]
+name = "leb128"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "884e2677b40cc8c339eaefcb701c32ef1fd2493d71118dc0ca4b6a736c93bd67"
+
+[[package]]
+name = "log"
+version = "0.4.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b06a4cde4c0f271a446782e3eff8de789548ce57dbc8eca9292c27f4a42004b4"
+
+[[package]]
+name = "memchr"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d"
+
+[[package]]
+name = "once_cell"
+version = "1.18.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d"
+
+[[package]]
+name = "percent-encoding"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b2a4787296e9989611394c33f193f676704af1686e70b8f8033ab5ba9a35a94"
+
+[[package]]
+name = "pin-project-lite"
+version = "0.2.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8afb450f006bf6385ca15ef45d71d2288452bc3683ce2e2cacc0d18e4be60b58"
+
+[[package]]
+name = "pin-utils"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.66"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "18fb31db3f9bddb2ea821cde30a9f70117e3f119938b5ee630b7403aa6e2ead9"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "50f3b39ccfb720540debaa0164757101c08ecb8d326b15358ce76a62c7e85965"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "routefinder"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "94f8f99b10dedd317514253dda1fa7c14e344aac96e1f78149a64879ce282aca"
+dependencies = [
+ "smartcow",
+ "smartstring",
+]
+
+[[package]]
+name = "ryu"
+version = "1.0.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741"
+
+[[package]]
+name = "semver"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b0293b4b29daaf487284529cc2f5675b8e57c61f70167ba415a463651fd6a918"
+
+[[package]]
+name = "serde"
+version = "1.0.183"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32ac8da02677876d532745a130fc9d8e6edfa81a269b107c5b00829b91d8eb3c"
+
+[[package]]
+name = "serde_derive"
+version = "1.0.183"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aafe972d60b0b9bee71a91b92fee2d4fb3c9d7e8f6b179aa99f27203d99a4816"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.28",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.108"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d1c7e3eac408d115102c4c24ad393e0821bb3a5df4d506a80f85f7a742a526b"
+dependencies = [
+ "itoa",
+ "ryu",
+ "serde",
+]
+
+[[package]]
+name = "slab"
+version = "0.4.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "smallvec"
+version = "1.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "942b4a808e05215192e39f4ab80813e599068285906cc91aa64f923db842bd5a"
+
+[[package]]
+name = "smartcow"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "656fcb1c1fca8c4655372134ce87d8afdf5ec5949ebabe8d314be0141d8b5da2"
+dependencies = [
+ "smartstring",
+]
+
+[[package]]
+name = "smartstring"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3fb72c633efbaa2dd666986505016c32c3044395ceaf881518399d2f4127ee29"
+dependencies = [
+ "autocfg",
+ "static_assertions",
+ "version_check",
+]
+
+[[package]]
+name = "spdx"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b19b32ed6d899ab23174302ff105c1577e45a06b08d4fe0a9dd13ce804bbbf71"
+dependencies = [
+ "smallvec",
+]
+
+[[package]]
+name = "spin-macro"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "bytes",
+ "http",
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+]
+
+[[package]]
+name = "spin-sdk"
+version = "2.0.0-pre0"
+dependencies = [
+ "anyhow",
+ "async-trait",
+ "bytes",
+ "form_urlencoded",
+ "futures",
+ "http",
+ "once_cell",
+ "routefinder",
+ "serde",
+ "serde_json",
+ "spin-macro",
+ "thiserror",
+ "wit-bindgen",
+]
+
+[[package]]
+name = "static_assertions"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
+
+[[package]]
+name = "syn"
+version = "1.0.109"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "syn"
+version = "2.0.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "04361975b3f5e348b2189d8dc55bc942f278b2d482a6a0365de5bdd62d351567"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "thiserror"
+version = "1.0.44"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "611040a08a0439f8248d1990b111c95baa9c704c805fa1f62104b39655fd7f90"
+dependencies = [
+ "thiserror-impl",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "1.0.44"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "090198534930841fab3a5d1bb637cde49e339654e606195f8d9c76eeb081dc96"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.28",
+]
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "301abaae475aa91687eb82514b328ab47a211a533026cb25fc3e519b86adfc3c"
+
+[[package]]
+name = "unicode-segmentation"
+version = "1.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1dd624098567895118886609431a7c3b8f516e41d30e0643f03d94592a147e36"
+
+[[package]]
+name = "unicode-xid"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f962df74c8c05a667b5ee8bcf162993134c104e96440b663c8daa176dc772d8c"
+
+[[package]]
+name = "version_check"
+version = "0.9.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
+
+[[package]]
+name = "wasm-encoder"
+version = "0.36.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "53ae0be20bf87918df4fa831bfbbd0b491d24aee407ed86360eae4c2c5608d38"
+dependencies = [
+ "leb128",
+]
+
+[[package]]
+name = "wasm-metadata"
+version = "0.10.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5621910462c61a8efc3248fdfb1739bf649bb335b0df935c27b340418105f9d8"
+dependencies = [
+ "anyhow",
+ "indexmap",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "spdx",
+ "wasm-encoder",
+ "wasmparser",
+]
+
+[[package]]
+name = "wasmparser"
+version = "0.116.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "53290b1276c5c2d47d694fb1a920538c01f51690e7e261acbe1d10c5fc306ea1"
+dependencies = [
+ "indexmap",
+ "semver",
+]
+
+[[package]]
+name = "wit-bindgen"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "38726c54a5d7c03cac28a2a8de1006cfe40397ddf6def3f836189033a413bc08"
+dependencies = [
+ "bitflags",
+ "wit-bindgen-rust-macro",
+]
+
+[[package]]
+name = "wit-bindgen-core"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c8bf1fddccaff31a1ad57432d8bfb7027a7e552969b6c68d6d8820dcf5c2371f"
+dependencies = [
+ "anyhow",
+ "wit-component",
+ "wit-parser",
+]
+
+[[package]]
+name = "wit-bindgen-rust"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0e7200e565124801e01b7b5ddafc559e1da1b2e1bed5364d669cd1d96fb88722"
+dependencies = [
+ "anyhow",
+ "heck",
+ "wasm-metadata",
+ "wit-bindgen-core",
+ "wit-component",
+]
+
+[[package]]
+name = "wit-bindgen-rust-macro"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ae33920ad8119fe72cf59eb00f127c0b256a236b9de029a1a10397b1f38bdbd"
+dependencies = [
+ "anyhow",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.28",
+ "wit-bindgen-core",
+ "wit-bindgen-rust",
+ "wit-component",
+]
+
+[[package]]
+name = "wit-component"
+version = "0.17.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "480cc1a078b305c1b8510f7c455c76cbd008ee49935f3a6c5fd5e937d8d95b1e"
+dependencies = [
+ "anyhow",
+ "bitflags",
+ "indexmap",
+ "log",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "wasm-encoder",
+ "wasm-metadata",
+ "wasmparser",
+ "wit-parser",
+]
+
+[[package]]
+name = "wit-parser"
+version = "0.12.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "43771ee863a16ec4ecf9da0fc65c3bbd4a1235c8e3da5f094b562894843dfa76"
+dependencies = [
+ "anyhow",
+ "id-arena",
+ "indexmap",
+ "log",
+ "semver",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "unicode-xid",
+]
diff --git a/tests/testcases/llm/Cargo.toml b/tests/testcases/llm/Cargo.toml
new file mode 100644
index 0000000000..c7d87f5f05
--- /dev/null
+++ b/tests/testcases/llm/Cargo.toml
@@ -0,0 +1,15 @@
+[package]
+name = "ai"
+authors = ["Ryan Levick <me@ryanlevick.com>"]
+description = ""
+version = "0.1.0"
+edition = "2021"
+
+[lib]
+crate-type = ["cdylib"]
+
+[dependencies]
+anyhow = "1"
+spin-sdk = { path = "../../../sdk/rust" }
+
+[workspace]
diff --git a/tests/testcases/llm/spin.toml b/tests/testcases/llm/spin.toml
new file mode 100644
index 0000000000..101d5c10d4
--- /dev/null
+++ b/tests/testcases/llm/spin.toml
@@ -0,0 +1,17 @@
+spin_manifest_version = "1"
+authors = ["Ryan Levick <me@ryanlevick.com>"]
+description = ""
+name = "ai"
+trigger = { type = "http", base = "/" }
+version = "0.1.0"
+
+[[component]]
+id = "ai"
+source = "target/wasm32-wasi/release/ai.wasm"
+allowed_http_hosts = []
+ai_models = ["llama2-chat","all-minilm-l6-v2"]
+[component.trigger]
+route = "/..."
+[component.build]
+command = "cargo build --target wasm32-wasi --release"
+watch = ["src/**/*.rs", "Cargo.toml"]
diff --git a/tests/testcases/llm/src/lib.rs b/tests/testcases/llm/src/lib.rs
new file mode 100644
index 0000000000..ad40acbb4f
--- /dev/null
+++ b/tests/testcases/llm/src/lib.rs
@@ -0,0 +1,14 @@
+use anyhow::Result;
+use spin_sdk::{
+ http::{Request, Response},
+ http_component, llm,
+};
+
+/// A simple Spin HTTP component.
+#[http_component]
+fn hello_world(_req: Request) -> Result<Response> {
+ let model = llm::InferencingModel::Llama2Chat;
+ let inference = llm::infer(model, "say hello")?;
+
+ Ok(Response::builder().status(200).body(inference.text).build())
+}
diff --git a/tests/testcases/mod.rs b/tests/testcases/mod.rs
index 59edc2b863..121cf94fe6 100644
--- a/tests/testcases/mod.rs
+++ b/tests/testcases/mod.rs
@@ -845,6 +845,45 @@ pub async fn head_rust_sdk_redis(controller: &dyn Controller) {
tc.run(controller).await.unwrap()
}
+pub async fn llm_works(controller: &dyn Controller) {
+ async fn checks(
+ metadata: AppMetadata,
+ _: Option<Pin<Box<dyn AsyncBufRead>>>,
+ _: Option<Pin<Box<dyn AsyncBufRead>>>,
+ ) -> Result<()> {
+ let response = e2e_testing::http_asserts::make_request(
+ Method::GET,
+ get_url(metadata.base.as_str(), "/").as_str(),
+ "",
+ )
+ .await?;
+ // We avoid actually running inferencing because it's slow and instead just
+ // ensure that the app boots properly.
+ assert_eq!(response.status(), 500);
+ let body = std::str::from_utf8(&response.bytes().await?)
+ .unwrap()
+ .to_string();
+ assert!(body.contains("Could not read model registry directory"));
+
+ Ok(())
+ }
+
+ let tc = TestCaseBuilder::default()
+ .name("llm".to_string())
+ .appname(Some("llm".to_string()))
+ .assertions(
+ |metadata: AppMetadata,
+ stdout_stream: Option<Pin<Box<dyn AsyncBufRead>>>,
+ stderr_stream: Option<Pin<Box<dyn AsyncBufRead>>>| {
+ Box::pin(checks(metadata, stdout_stream, stderr_stream))
+ },
+ )
+ .build()
+ .unwrap();
+
+ tc.run(controller).await.unwrap()
+}
+
pub async fn header_env_routes_works(controller: &dyn Controller) {
async fn checks(
metadata: AppMetadata,
|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
|
12becdcc33b6e59bb3aea3dd511f24616a239852
|
Consider deprecation of old style `outbound-http` and `inbound-http` in the Spin guest world
With `wasi-http` affording the ability to do inbound and outbound http, there is little reason to have an the old style `outbound-http` and `inbound-http` interfaces. We should consider getting rid of them - potentially in Spin 2.0. Of course, we'll need to keep support around for legacy components, but perhaps this can be implemented in terms of wasi-http?
The only advantage those interfaces afford is that non-streaming bodies are simplier to use. However, we'll want to ensure that we make usage of the streaming APIs as simple as possible and having an additional two interfaces just for this is confusing and hard to maintain.
|
What would "deprecation" look like here?
With Spin 2.0 we could conceivably just remove them from the Spin 2.0 world. This would mean the SDK would no longer expose them. Legacy apps would still run fine, but anything new would go through using `wasi-http` instead.
If we get rid of the imports that would imply that support for old interfaces would be added by spin-componentize? My main concern there is that I believe it would require double-buffering http bodies.
I'm talking about deprecation from the *guest's perspectives*. Host deprecation is something much more long term since we want to continue to support apps built to target Spin 1.0. This means this is (for now) almost purely a cosmetic change meant to push users towards `wasi-http` and away from the Spin specific `http` interface.
So in general the following is what would happen:
* Apps compiled against the Spin 1.0 world continue to work exactly as they always have. Spin internally continues to support the old http interface. There's no "double buffering" issue because the host implementation has not changed.
* Apps compiled against Spin 2.0 will only use `wasi-http` - their world does not contain the `http` or `http-types` interfaces. Since the SDK hides most of this from the user not much changes from the user's perspective with the caveat that the `http` module in the SDK will go away.
* Note: There are some open questions of whether we'd want to reimplement `Request` and `Response` types since the `wasi-http` types are by default much more complex (since they assume streaming bodies which for many use cases is overkill).
|
2023-10-17T14:45:13Z
|
fermyon__spin-1901
|
fermyon/spin
|
3.2
|
diff --git a/Cargo.lock b/Cargo.lock
index 4d1863cb16..66598d7526 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1225,7 +1225,7 @@ dependencies = [
[[package]]
name = "cranelift-bforest"
version = "0.101.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"cranelift-entity",
]
@@ -1233,7 +1233,7 @@ dependencies = [
[[package]]
name = "cranelift-codegen"
version = "0.101.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"bumpalo",
"cranelift-bforest",
@@ -1253,7 +1253,7 @@ dependencies = [
[[package]]
name = "cranelift-codegen-meta"
version = "0.101.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"cranelift-codegen-shared",
]
@@ -1261,12 +1261,12 @@ dependencies = [
[[package]]
name = "cranelift-codegen-shared"
version = "0.101.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
[[package]]
name = "cranelift-control"
version = "0.101.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"arbitrary",
]
@@ -1274,7 +1274,7 @@ dependencies = [
[[package]]
name = "cranelift-entity"
version = "0.101.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"serde",
"serde_derive",
@@ -1283,7 +1283,7 @@ dependencies = [
[[package]]
name = "cranelift-frontend"
version = "0.101.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"cranelift-codegen",
"log",
@@ -1294,12 +1294,12 @@ dependencies = [
[[package]]
name = "cranelift-isle"
version = "0.101.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
[[package]]
name = "cranelift-native"
version = "0.101.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"cranelift-codegen",
"libc",
@@ -1309,7 +1309,7 @@ dependencies = [
[[package]]
name = "cranelift-wasm"
version = "0.101.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"cranelift-codegen",
"cranelift-entity",
@@ -1317,7 +1317,7 @@ dependencies = [
"itertools 0.10.5",
"log",
"smallvec",
- "wasmparser 0.113.3",
+ "wasmparser",
"wasmtime-types",
]
@@ -4634,17 +4634,6 @@ dependencies = [
"cc",
]
-[[package]]
-name = "pulldown-cmark"
-version = "0.9.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "77a1a2f1f0a7ecff9c31abbe177637be0e97a0aef46cf8738ece09327985d998"
-dependencies = [
- "bitflags 1.3.2",
- "memchr",
- "unicase",
-]
-
[[package]]
name = "quote"
version = "1.0.33"
@@ -5700,13 +5689,13 @@ dependencies = [
[[package]]
name = "spin-componentize"
version = "0.1.0"
-source = "git+https://github.com/fermyon/spin-componentize?rev=00820a455086c3d04b1a01236af03be38aac38a1#00820a455086c3d04b1a01236af03be38aac38a1"
+source = "git+https://github.com/fermyon/spin-componentize?rev=191789170abde10cd55590466c0660dd6c7d472a#191789170abde10cd55590466c0660dd6c7d472a"
dependencies = [
"anyhow",
- "wasm-encoder 0.35.0",
- "wasmparser 0.115.0",
- "wit-component 0.15.0",
- "wit-parser 0.12.1",
+ "wasm-encoder",
+ "wasmparser",
+ "wit-component",
+ "wit-parser",
]
[[package]]
@@ -6204,6 +6193,7 @@ dependencies = [
"tracing",
"url",
"wasmtime",
+ "wasmtime-wasi-http",
]
[[package]]
@@ -6237,6 +6227,7 @@ dependencies = [
"tokio",
"tokio-rustls 0.23.4",
"tracing",
+ "url",
"wasi-common",
"wasmtime",
"wasmtime-wasi",
@@ -7175,7 +7166,7 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]]
name = "wasi-cap-std-sync"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"anyhow",
"async-trait",
@@ -7197,7 +7188,7 @@ dependencies = [
[[package]]
name = "wasi-common"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"anyhow",
"bitflags 2.4.0",
@@ -7216,7 +7207,7 @@ dependencies = [
[[package]]
name = "wasi-tokio"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"anyhow",
"cap-std",
@@ -7295,15 +7286,6 @@ version = "0.2.84"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0046fef7e28c3804e5e38bfa31ea2a0f73905319b677e57ebe37e49358989b5d"
-[[package]]
-name = "wasm-encoder"
-version = "0.33.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "34180c89672b3e4825c3a8db4b61a674f1447afd5fe2445b2d22c3d8b6ea086c"
-dependencies = [
- "leb128",
-]
-
[[package]]
name = "wasm-encoder"
version = "0.35.0"
@@ -7325,8 +7307,8 @@ dependencies = [
"serde_derive",
"serde_json",
"spdx",
- "wasm-encoder 0.35.0",
- "wasmparser 0.115.0",
+ "wasm-encoder",
+ "wasmparser",
]
[[package]]
@@ -7342,16 +7324,6 @@ dependencies = [
"web-sys",
]
-[[package]]
-name = "wasmparser"
-version = "0.113.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "286049849b5a5bd09a8773171be96824afabffc7cc3df6caaf33a38db6cd07ae"
-dependencies = [
- "indexmap 2.0.0",
- "semver",
-]
-
[[package]]
name = "wasmparser"
version = "0.115.0"
@@ -7364,18 +7336,18 @@ dependencies = [
[[package]]
name = "wasmprinter"
-version = "0.2.68"
+version = "0.2.70"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "537030718ce76e985896e91fe2cac77c1913c8dccd46eaf8ab1a4cd56d824cc3"
+checksum = "e74458a9bc5cc9c7108abfa0fe4dc88d5abf1f3baf194df3264985f17d559b5e"
dependencies = [
"anyhow",
- "wasmparser 0.113.3",
+ "wasmparser",
]
[[package]]
name = "wasmtime"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"anyhow",
"async-trait",
@@ -7396,8 +7368,8 @@ dependencies = [
"serde_derive",
"serde_json",
"target-lexicon",
- "wasm-encoder 0.33.2",
- "wasmparser 0.113.3",
+ "wasm-encoder",
+ "wasmparser",
"wasmtime-cache",
"wasmtime-component-macro",
"wasmtime-component-util",
@@ -7414,7 +7386,7 @@ dependencies = [
[[package]]
name = "wasmtime-asm-macros"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"cfg-if",
]
@@ -7422,7 +7394,7 @@ dependencies = [
[[package]]
name = "wasmtime-cache"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"anyhow",
"base64 0.21.4",
@@ -7441,7 +7413,7 @@ dependencies = [
[[package]]
name = "wasmtime-component-macro"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"anyhow",
"proc-macro2",
@@ -7449,18 +7421,18 @@ dependencies = [
"syn 2.0.29",
"wasmtime-component-util",
"wasmtime-wit-bindgen",
- "wit-parser 0.11.3",
+ "wit-parser",
]
[[package]]
name = "wasmtime-component-util"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
[[package]]
name = "wasmtime-cranelift"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"anyhow",
"cfg-if",
@@ -7475,7 +7447,7 @@ dependencies = [
"object 0.32.1",
"target-lexicon",
"thiserror",
- "wasmparser 0.113.3",
+ "wasmparser",
"wasmtime-cranelift-shared",
"wasmtime-environ",
"wasmtime-versioned-export-macros",
@@ -7484,7 +7456,7 @@ dependencies = [
[[package]]
name = "wasmtime-cranelift-shared"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"anyhow",
"cranelift-codegen",
@@ -7499,7 +7471,7 @@ dependencies = [
[[package]]
name = "wasmtime-environ"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"anyhow",
"cranelift-entity",
@@ -7511,8 +7483,8 @@ dependencies = [
"serde_derive",
"target-lexicon",
"thiserror",
- "wasm-encoder 0.33.2",
- "wasmparser 0.113.3",
+ "wasm-encoder",
+ "wasmparser",
"wasmprinter",
"wasmtime-component-util",
"wasmtime-types",
@@ -7521,7 +7493,7 @@ dependencies = [
[[package]]
name = "wasmtime-fiber"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"cc",
"cfg-if",
@@ -7534,7 +7506,7 @@ dependencies = [
[[package]]
name = "wasmtime-jit"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"addr2line 0.21.0",
"anyhow",
@@ -7560,7 +7532,7 @@ dependencies = [
[[package]]
name = "wasmtime-jit-debug"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"object 0.32.1",
"once_cell",
@@ -7571,7 +7543,7 @@ dependencies = [
[[package]]
name = "wasmtime-jit-icache-coherence"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"cfg-if",
"libc",
@@ -7581,7 +7553,7 @@ dependencies = [
[[package]]
name = "wasmtime-runtime"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"anyhow",
"cc",
@@ -7597,7 +7569,7 @@ dependencies = [
"rand 0.8.5",
"rustix 0.38.13",
"sptr",
- "wasm-encoder 0.33.2",
+ "wasm-encoder",
"wasmtime-asm-macros",
"wasmtime-environ",
"wasmtime-fiber",
@@ -7610,19 +7582,19 @@ dependencies = [
[[package]]
name = "wasmtime-types"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"cranelift-entity",
"serde",
"serde_derive",
"thiserror",
- "wasmparser 0.113.3",
+ "wasmparser",
]
[[package]]
name = "wasmtime-versioned-export-macros"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"proc-macro2",
"quote",
@@ -7632,7 +7604,7 @@ dependencies = [
[[package]]
name = "wasmtime-wasi"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"anyhow",
"async-trait",
@@ -7667,7 +7639,7 @@ dependencies = [
[[package]]
name = "wasmtime-wasi-http"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"anyhow",
"async-trait",
@@ -7689,14 +7661,14 @@ dependencies = [
[[package]]
name = "wasmtime-winch"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"anyhow",
"cranelift-codegen",
"gimli 0.28.0",
"object 0.32.1",
"target-lexicon",
- "wasmparser 0.113.3",
+ "wasmparser",
"wasmtime-cranelift-shared",
"wasmtime-environ",
"winch-codegen",
@@ -7705,18 +7677,18 @@ dependencies = [
[[package]]
name = "wasmtime-wit-bindgen"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"anyhow",
"heck 0.4.1",
"indexmap 2.0.0",
- "wit-parser 0.11.3",
+ "wit-parser",
]
[[package]]
name = "wasmtime-wmemcheck"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
[[package]]
name = "wast"
@@ -7729,23 +7701,23 @@ dependencies = [
[[package]]
name = "wast"
-version = "66.0.0"
+version = "66.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0da7529bb848d58ab8bf32230fc065b363baee2bd338d5e58c589a1e7d83ad07"
+checksum = "93cb43b0ac6dd156f2c375735ccfd72b012a7c0a6e6d09503499b8d3cb6e6072"
dependencies = [
"leb128",
"memchr",
"unicode-width",
- "wasm-encoder 0.33.2",
+ "wasm-encoder",
]
[[package]]
name = "wat"
-version = "1.0.75"
+version = "1.0.77"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4780374047c65b6b6e86019093fe80c18b66825eb684df778a4e068282a780e7"
+checksum = "e367582095d2903caeeea9acbb140e1db9c7677001efa4347c3687fd34fe7072"
dependencies = [
- "wast 66.0.0",
+ "wast 66.0.2",
]
[[package]]
@@ -7857,7 +7829,7 @@ dependencies = [
[[package]]
name = "wiggle"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"anyhow",
"async-trait",
@@ -7871,7 +7843,7 @@ dependencies = [
[[package]]
name = "wiggle-generate"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"anyhow",
"heck 0.4.1",
@@ -7885,7 +7857,7 @@ dependencies = [
[[package]]
name = "wiggle-macro"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"proc-macro2",
"quote",
@@ -7927,7 +7899,7 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "winch-codegen"
version = "0.12.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"anyhow",
"cranelift-codegen",
@@ -7935,7 +7907,7 @@ dependencies = [
"regalloc2",
"smallvec",
"target-lexicon",
- "wasmparser 0.113.3",
+ "wasmparser",
"wasmtime-environ",
]
@@ -8156,8 +8128,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "565b945ae074886071eccf9cdaf8ccd7b959c2b0d624095bea5fe62003e8b3e0"
dependencies = [
"anyhow",
- "wit-component 0.16.0",
- "wit-parser 0.12.1",
+ "wit-component",
+ "wit-parser",
]
[[package]]
@@ -8170,7 +8142,7 @@ dependencies = [
"heck 0.4.1",
"wasm-metadata",
"wit-bindgen-core",
- "wit-component 0.16.0",
+ "wit-component",
]
[[package]]
@@ -8185,26 +8157,7 @@ dependencies = [
"syn 2.0.29",
"wit-bindgen-core",
"wit-bindgen-rust",
- "wit-component 0.16.0",
-]
-
-[[package]]
-name = "wit-component"
-version = "0.15.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c1bc644bb4205a2ee74035e5d35958777575fa4c6dd38ce7226c7680be2861c1"
-dependencies = [
- "anyhow",
- "bitflags 2.4.0",
- "indexmap 2.0.0",
- "log",
- "serde",
- "serde_derive",
- "serde_json",
- "wasm-encoder 0.35.0",
- "wasm-metadata",
- "wasmparser 0.115.0",
- "wit-parser 0.12.1",
+ "wit-component",
]
[[package]]
@@ -8220,28 +8173,10 @@ dependencies = [
"serde",
"serde_derive",
"serde_json",
- "wasm-encoder 0.35.0",
+ "wasm-encoder",
"wasm-metadata",
- "wasmparser 0.115.0",
- "wit-parser 0.12.1",
-]
-
-[[package]]
-name = "wit-parser"
-version = "0.11.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a39edca9abb16309def3843af73b58d47d243fe33a9ceee572446bcc57556b9a"
-dependencies = [
- "anyhow",
- "id-arena",
- "indexmap 2.0.0",
- "log",
- "pulldown-cmark",
- "semver",
- "serde",
- "serde_json",
- "unicode-xid",
- "url",
+ "wasmparser",
+ "wit-parser",
]
[[package]]
@@ -8264,7 +8199,7 @@ dependencies = [
[[package]]
name = "witx"
version = "0.9.1"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"anyhow",
"log",
diff --git a/Cargo.toml b/Cargo.toml
index 320040bf2f..9bd44e647a 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -111,15 +111,15 @@ members = ["crates/*", "sdk/rust", "sdk/rust/macro"]
[workspace.dependencies]
anyhow = "1.0.75"
tracing = { version = "0.1", features = ["log"] }
-wasmtime-wasi = { git = "https://github.com/bytecodealliance/wasmtime", rev = "c796ce7376a57a40605f03e74bd78cefcc9acf3a", features = [
+wasmtime-wasi = { git = "https://github.com/bytecodealliance/wasmtime", rev = "2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb", features = [
"tokio",
] }
-wasi-common-preview1 = { git = "https://github.com/bytecodealliance/wasmtime", rev = "c796ce7376a57a40605f03e74bd78cefcc9acf3a", package = "wasi-common" }
-wasmtime = { git = "https://github.com/bytecodealliance/wasmtime", rev = "c796ce7376a57a40605f03e74bd78cefcc9acf3a", features = [
+wasi-common-preview1 = { git = "https://github.com/bytecodealliance/wasmtime", rev = "2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb", package = "wasi-common" }
+wasmtime = { git = "https://github.com/bytecodealliance/wasmtime", rev = "2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb", features = [
"component-model",
] }
-wasmtime-wasi-http = { git = "https://github.com/bytecodealliance/wasmtime", rev = "c796ce7376a57a40605f03e74bd78cefcc9acf3a" }
-spin-componentize = { git = "https://github.com/fermyon/spin-componentize", rev = "00820a455086c3d04b1a01236af03be38aac38a1" }
+wasmtime-wasi-http = { git = "https://github.com/bytecodealliance/wasmtime", rev = "2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb" }
+spin-componentize = { git = "https://github.com/fermyon/spin-componentize", rev = "191789170abde10cd55590466c0660dd6c7d472a" }
hyper = { version = "=1.0.0-rc.3", features = ["full"] }
http-body-util = "=0.1.0-rc.2"
diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs
index 838e0d6b0b..b3c13916d5 100644
--- a/crates/core/src/lib.rs
+++ b/crates/core/src/lib.rs
@@ -20,7 +20,7 @@ use crossbeam_channel::Sender;
use tracing::instrument;
use wasmtime::{InstanceAllocationStrategy, PoolingAllocationConfig};
use wasmtime_wasi::preview2::Table;
-use wasmtime_wasi_http::types::{WasiHttpCtx, WasiHttpView};
+use wasmtime_wasi_http::types::{default_send_request, WasiHttpCtx, WasiHttpView};
use self::host_component::{HostComponents, HostComponentsBuilder};
@@ -191,7 +191,7 @@ impl<T: Send> wasmtime_wasi::preview2::WasiView for Data<T> {
}
}
-impl<T: Send> WasiHttpView for Data<T> {
+impl<T: Send + OutboundWasiHttpHandler> WasiHttpView for Data<T> {
fn ctx(&mut self) -> &mut WasiHttpCtx {
match &mut self.wasi {
Wasi::Preview1(_) => panic!("using WASI Preview 1 functions with Preview 2 store"),
@@ -202,6 +202,45 @@ impl<T: Send> WasiHttpView for Data<T> {
fn table(&mut self) -> &mut Table {
&mut self.table
}
+
+ fn send_request(
+ &mut self,
+ request: wasmtime_wasi_http::types::OutgoingRequest,
+ ) -> wasmtime::Result<
+ wasmtime::component::Resource<wasmtime_wasi_http::types::HostFutureIncomingResponse>,
+ >
+ where
+ Self: Sized,
+ {
+ T::send_request(self, request)
+ }
+}
+
+/// Handler for wasi-http based requests
+pub trait OutboundWasiHttpHandler {
+ /// Send the request
+ fn send_request(
+ data: &mut Data<Self>,
+ request: wasmtime_wasi_http::types::OutgoingRequest,
+ ) -> wasmtime::Result<
+ wasmtime::component::Resource<wasmtime_wasi_http::types::HostFutureIncomingResponse>,
+ >
+ where
+ Self: Sized;
+}
+
+impl OutboundWasiHttpHandler for () {
+ fn send_request(
+ data: &mut Data<Self>,
+ request: wasmtime_wasi_http::types::OutgoingRequest,
+ ) -> wasmtime::Result<
+ wasmtime::component::Resource<wasmtime_wasi_http::types::HostFutureIncomingResponse>,
+ >
+ where
+ Self: Sized,
+ {
+ default_send_request(data, request)
+ }
}
/// An alias for [`wasmtime::Linker`] specialized to [`Data`].
@@ -222,13 +261,10 @@ pub struct EngineBuilder<T> {
epoch_ticker_thread: bool,
}
-impl<T: Send + Sync> EngineBuilder<T> {
+impl<T: Send + Sync + OutboundWasiHttpHandler> EngineBuilder<T> {
fn new(config: &Config) -> Result<Self> {
let engine = wasmtime::Engine::new(&config.inner)?;
-
- let mut linker: Linker<T> = Linker::new(&engine);
- wasmtime_wasi_http::proxy::add_to_linker(&mut linker)?;
-
+ let linker: Linker<T> = Linker::new(&engine);
let mut module_linker = ModuleLinker::new(&engine);
wasmtime_wasi::tokio::add_to_linker(&mut module_linker, |data| match &mut data.wasi {
Wasi::Preview1(ctx) => ctx,
@@ -244,7 +280,9 @@ impl<T: Send + Sync> EngineBuilder<T> {
epoch_ticker_thread: true,
})
}
+}
+impl<T: Send + Sync> EngineBuilder<T> {
/// Adds definition(s) to the built [`Engine`].
///
/// This method's signature is meant to be used with
@@ -345,7 +383,7 @@ pub struct Engine<T> {
_epoch_ticker_signal: Option<Sender<()>>,
}
-impl<T: Send + Sync> Engine<T> {
+impl<T: OutboundWasiHttpHandler + Send + Sync> Engine<T> {
/// Creates a new [`EngineBuilder`] with the given [`Config`].
pub fn builder(config: &Config) -> Result<EngineBuilder<T>> {
EngineBuilder::new(config)
diff --git a/crates/http/src/config.rs b/crates/http/src/config.rs
index 41fbe74c69..9fb1db5482 100644
--- a/crates/http/src/config.rs
+++ b/crates/http/src/config.rs
@@ -21,14 +21,14 @@ pub struct HttpTriggerConfig {
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields, rename_all = "lowercase", tag = "type")]
pub enum HttpExecutorType {
- /// The component implements the Spin HTTP interface.
+ /// The component implements an HTTP based interface.
+ ///
+ /// This can be either `fermyon:spin/inbound-http` or `wasi:http/incoming-handler`
#[default]
- Spin,
+ #[serde(alias = "spin")]
+ Http,
/// The component implements the Wagi CGI interface.
Wagi(WagiTriggerConfig),
- /// The component implements [`wasi-http`](https://github.com/WebAssembly/wasi-http)
- /// interface (experimental, subject to change)
- Wasi,
}
/// Wagi specific configuration for the http executor.
diff --git a/crates/outbound-http/src/allowed_http_hosts.rs b/crates/outbound-http/src/allowed_http_hosts.rs
index b876681246..3f758e8838 100644
--- a/crates/outbound-http/src/allowed_http_hosts.rs
+++ b/crates/outbound-http/src/allowed_http_hosts.rs
@@ -20,14 +20,14 @@ impl Default for AllowedHttpHosts {
impl AllowedHttpHosts {
/// Tests whether the given URL is allowed according to the allow-list.
- pub fn allow(&self, url: &url::Url) -> bool {
+ pub fn allows(&self, url: &url::Url) -> bool {
match self {
Self::AllowAll => true,
Self::AllowSpecific(hosts) => hosts.iter().any(|h| h.allow(url)),
}
}
- pub fn allow_relative_url(&self) -> bool {
+ pub fn allows_relative_url(&self) -> bool {
match self {
Self::AllowAll => true,
Self::AllowSpecific(hosts) => hosts.contains(&AllowedHttpHost::host("self")),
@@ -295,21 +295,21 @@ mod test {
fn test_allowed_hosts_can_be_specific() {
let allowed =
parse_allowed_http_hosts(&["spin.fermyon.dev", "http://example.com:8383"]).unwrap();
- assert!(allowed.allow(&Url::parse("http://example.com:8383/foo/bar").unwrap()));
- assert!(allowed.allow(&Url::parse("https://spin.fermyon.dev/").unwrap()));
- assert!(!allowed.allow(&Url::parse("http://example.com/").unwrap()));
- assert!(!allowed.allow(&Url::parse("http://google.com/").unwrap()));
+ assert!(allowed.allows(&Url::parse("http://example.com:8383/foo/bar").unwrap()));
+ assert!(allowed.allows(&Url::parse("https://spin.fermyon.dev/").unwrap()));
+ assert!(!allowed.allows(&Url::parse("http://example.com/").unwrap()));
+ assert!(!allowed.allows(&Url::parse("http://google.com/").unwrap()));
}
#[test]
fn test_allowed_hosts_allow_relative_url() {
let allowed = parse_allowed_http_hosts(&["self", "http://example.com:8383"]).unwrap();
- assert!(allowed.allow_relative_url());
+ assert!(allowed.allows_relative_url());
let not_allowed = parse_allowed_http_hosts(&["http://example.com:8383"]).unwrap();
- assert!(!not_allowed.allow_relative_url());
+ assert!(!not_allowed.allows_relative_url());
let allow_all = parse_allowed_http_hosts(&["insecure:allow-all"]).unwrap();
- assert!(allow_all.allow_relative_url());
+ assert!(allow_all.allows_relative_url());
}
}
diff --git a/crates/outbound-http/src/host_impl.rs b/crates/outbound-http/src/host_impl.rs
index 2fc7cd4328..903dd99884 100644
--- a/crates/outbound-http/src/host_impl.rs
+++ b/crates/outbound-http/src/host_impl.rs
@@ -28,11 +28,11 @@ impl OutboundHttp {
/// If `None` is passed, the guest module is not allowed to send the request.
fn is_allowed(&mut self, url: &str) -> Result<bool, HttpError> {
if url.starts_with('/') {
- return Ok(self.allowed_hosts.allow_relative_url());
+ return Ok(self.allowed_hosts.allows_relative_url());
}
let url = Url::parse(url).map_err(|_| HttpError::InvalidUrl)?;
- Ok(self.allowed_hosts.allow(&url))
+ Ok(self.allowed_hosts.allows(&url))
}
}
diff --git a/crates/trigger-http/Cargo.toml b/crates/trigger-http/Cargo.toml
index 7b73735b39..5964b50d1d 100644
--- a/crates/trigger-http/Cargo.toml
+++ b/crates/trigger-http/Cargo.toml
@@ -35,6 +35,7 @@ tls-listener = { version = "0.4.0", features = [
] }
tokio = { version = "1.23", features = ["full"] }
tokio-rustls = { version = "0.23.2" }
+url = "2.4.1"
tracing = { workspace = true }
wasmtime = { workspace = true }
wasmtime-wasi = { workspace = true }
diff --git a/crates/trigger-http/src/spin.rs b/crates/trigger-http/src/handler.rs
similarity index 61%
rename from crates/trigger-http/src/spin.rs
rename to crates/trigger-http/src/handler.rs
index 9dfba4a772..0c079f2a05 100644
--- a/crates/trigger-http/src/spin.rs
+++ b/crates/trigger-http/src/handler.rs
@@ -1,22 +1,26 @@
use std::{net::SocketAddr, str, str::FromStr};
use crate::{Body, HttpExecutor, HttpTrigger, Store};
-use anyhow::{anyhow, Result};
-use async_trait::async_trait;
+use anyhow::bail;
+use anyhow::{anyhow, Context, Result};
+use http::{HeaderName, HeaderValue};
use http_body_util::BodyExt;
use hyper::{Request, Response};
use outbound_http::OutboundHttpComponent;
+use spin_core::async_trait;
use spin_core::Instance;
use spin_http::body;
use spin_trigger::{EitherInstance, TriggerAppEngine};
use spin_world::v1::http_types;
use std::sync::Arc;
+use tokio::{sync::oneshot, task};
+use wasmtime_wasi_http::{proxy::Proxy, WasiHttpView};
#[derive(Clone)]
-pub struct SpinHttpExecutor;
+pub struct HttpHandlerExecutor;
#[async_trait]
-impl HttpExecutor for SpinHttpExecutor {
+impl HttpExecutor for HttpHandlerExecutor {
async fn execute(
&self,
engine: &TriggerAppEngine<HttpTrigger>,
@@ -38,9 +42,15 @@ impl HttpExecutor for SpinHttpExecutor {
set_http_origin_from_request(&mut store, engine, &req);
- let resp = Self::execute_impl(store, instance, base, raw_route, req, client_addr)
- .await
- .map_err(contextualise_err)?;
+ let resp = match HandlerType::from_exports(instance.exports(&mut store)) {
+ Some(HandlerType::Wasi) => Self::execute_wasi(store, instance, base, raw_route, req, client_addr).await?,
+ Some(HandlerType::Spin) => {
+ Self::execute_spin(store, instance, base, raw_route, req, client_addr)
+ .await
+ .map_err(contextualise_err)?
+ }
+ None => bail!("Expected component to either export `{}` or `fermyon:spin/inbound-http` but it exported neither", WASI_HTTP_EXPORT)
+ };
tracing::info!(
"Request finished, sending response with status code {}",
@@ -50,8 +60,8 @@ impl HttpExecutor for SpinHttpExecutor {
}
}
-impl SpinHttpExecutor {
- pub async fn execute_impl(
+impl HttpHandlerExecutor {
+ pub async fn execute_spin(
mut store: Store,
instance: Instance,
base: &str,
@@ -59,16 +69,12 @@ impl SpinHttpExecutor {
req: Request<Body>,
client_addr: SocketAddr,
) -> Result<Response<Body>> {
- let headers;
- let mut req = req;
- {
- headers = Self::headers(&mut req, raw_route, base, client_addr)?;
- }
-
+ let headers = Self::headers(&req, raw_route, base, client_addr)?;
let func = instance
.exports(&mut store)
.instance("fermyon:spin/inbound-http")
- .ok_or_else(|| anyhow!("no fermyon:spin/inbound-http instance found"))?
+ // Safe since we have already checked that this instance exists
+ .expect("no fermyon:spin/inbound-http found")
.typed_func::<(http_types::Request,), (http_types::Response,)>("handle-request")?;
let (parts, body) = req.into_parts();
@@ -135,8 +141,68 @@ impl SpinHttpExecutor {
})
}
+ async fn execute_wasi(
+ mut store: Store,
+ instance: Instance,
+ base: &str,
+ raw_route: &str,
+ mut req: Request<Body>,
+ client_addr: SocketAddr,
+ ) -> anyhow::Result<Response<Body>> {
+ let headers = Self::headers(&req, raw_route, base, client_addr)?;
+ req.headers_mut().clear();
+ req.headers_mut()
+ .extend(headers.into_iter().filter_map(|(n, v)| {
+ let Ok(name) = n.parse::<HeaderName>() else {
+ return None;
+ };
+ let Ok(value) = HeaderValue::from_bytes(v.as_bytes()) else {
+ return None;
+ };
+ Some((name, value))
+ }));
+ let request = store.as_mut().data_mut().new_incoming_request(req)?;
+
+ let (response_tx, response_rx) = oneshot::channel();
+ let response = store
+ .as_mut()
+ .data_mut()
+ .new_response_outparam(response_tx)?;
+
+ let proxy = Proxy::new(&mut store, &instance)?;
+
+ let handle = task::spawn(async move {
+ let result = proxy
+ .wasi_http_incoming_handler()
+ .call_handle(&mut store, request, response)
+ .await;
+
+ tracing::trace!(
+ "wasi-http memory consumed: {}",
+ store.as_ref().data().memory_consumed()
+ );
+
+ result
+ });
+
+ match response_rx.await {
+ Ok(response) => Ok(response.context("guest failed to produce a response")?),
+
+ Err(_) => {
+ handle
+ .await
+ .context("guest invocation panicked")?
+ .context("guest invocation failed")?;
+
+ Err(anyhow!(
+ "guest failed to produce a response prior to returning"
+ ))
+ }
+ }
+ }
+
fn headers(
- req: &mut Request<Body>,
+ req: &Request<Body>,
raw: &str,
base: &str,
client_addr: SocketAddr,
@@ -188,6 +254,27 @@ impl SpinHttpExecutor {
}
}
+/// Whether this handler uses the custom Spin http handler interface for wasi-http
+enum HandlerType {
+ Spin,
+ Wasi,
+}
+
+const WASI_HTTP_EXPORT: &str = "wasi:http/incoming-handler@0.2.0-rc-2023-10-18";
+
+impl HandlerType {
+ /// Determine the handler type from the exports
+ fn from_exports(mut exports: wasmtime::component::Exports<'_>) -> Option<HandlerType> {
+ if exports.instance(WASI_HTTP_EXPORT).is_some() {
+ return Some(HandlerType::Wasi);
+ }
+ if exports.instance("fermyon:spin/inbound-http").is_some() {
+ return Some(HandlerType::Spin);
+ }
+ None
+ }
+}
+
fn set_http_origin_from_request(
store: &mut Store,
engine: &TriggerAppEngine<HttpTrigger>,
@@ -195,6 +282,7 @@ fn set_http_origin_from_request(
) {
if let Some(authority) = req.uri().authority() {
if let Some(scheme) = req.uri().scheme_str() {
+ let origin = format!("{}://{}", scheme, authority);
if let Some(outbound_http_handle) = engine
.engine
.find_host_component_handle::<Arc<OutboundHttpComponent>>()
@@ -203,8 +291,11 @@ fn set_http_origin_from_request(
.host_components_data()
.get_or_insert(outbound_http_handle);
- outbound_http_data.origin = format!("{}://{}", scheme, authority);
+ outbound_http_data.origin = origin.clone();
+ store.as_mut().data_mut().as_mut().allowed_hosts =
+ outbound_http_data.allowed_hosts.clone();
}
+ store.as_mut().data_mut().as_mut().origin = Some(origin);
}
}
}
@@ -228,15 +319,15 @@ mod tests {
#[test]
fn test_spin_header_keys() {
assert_eq!(
- SpinHttpExecutor::prepare_header_key("SPIN_FULL_URL"),
+ HttpHandlerExecutor::prepare_header_key("SPIN_FULL_URL"),
"spin-full-url".to_string()
);
assert_eq!(
- SpinHttpExecutor::prepare_header_key("SPIN_PATH_INFO"),
+ HttpHandlerExecutor::prepare_header_key("SPIN_PATH_INFO"),
"spin-path-info".to_string()
);
assert_eq!(
- SpinHttpExecutor::prepare_header_key("SPIN_RAW_COMPONENT_ROUTE"),
+ HttpHandlerExecutor::prepare_header_key("SPIN_RAW_COMPONENT_ROUTE"),
"spin-raw-component-route".to_string()
);
}
diff --git a/crates/trigger-http/src/lib.rs b/crates/trigger-http/src/lib.rs
index 9d88f4aaa7..e8666a1954 100644
--- a/crates/trigger-http/src/lib.rs
+++ b/crates/trigger-http/src/lib.rs
@@ -1,9 +1,8 @@
//! Implementation for the Spin HTTP engine.
-mod spin;
+mod handler;
mod tls;
mod wagi;
-mod wasi;
use std::{
collections::HashMap,
@@ -23,8 +22,9 @@ use hyper::{
service::service_fn,
Request, Response,
};
+use outbound_http::allowed_http_hosts::AllowedHttpHosts;
use spin_app::{AppComponent, APP_DESCRIPTION_KEY};
-use spin_core::Engine;
+use spin_core::{Engine, OutboundWasiHttpHandler};
use spin_http::{
app_info::AppInfo,
body,
@@ -40,11 +40,11 @@ use tokio::{
use tracing::log;
use wasmtime_wasi_http::body::HyperIncomingBody as Body;
-use crate::{spin::SpinHttpExecutor, wagi::WagiHttpExecutor, wasi::WasiHttpExecutor};
+use crate::{handler::HttpHandlerExecutor, wagi::WagiHttpExecutor};
pub use tls::TlsConfig;
-pub(crate) type RuntimeData = ();
+pub(crate) type RuntimeData = HttpRuntimeData;
pub(crate) type Store = spin_core::Store<RuntimeData>;
/// The Spin HTTP trigger.
@@ -212,12 +212,11 @@ impl HttpTrigger {
Ok(component_id) => {
let trigger = self.component_trigger_configs.get(component_id).unwrap();
- let executor = trigger.executor.as_ref().unwrap_or(&HttpExecutorType::Spin);
+ let executor = trigger.executor.as_ref().unwrap_or(&HttpExecutorType::Http);
let res = match executor {
- HttpExecutorType::Spin => {
- let executor = SpinHttpExecutor;
- executor
+ HttpExecutorType::Http => {
+ HttpHandlerExecutor
.execute(
&self.engine,
component_id,
@@ -243,18 +242,6 @@ impl HttpTrigger {
)
.await
}
- HttpExecutorType::Wasi => {
- WasiHttpExecutor
- .execute(
- &self.engine,
- component_id,
- &self.base,
- &trigger.route,
- req,
- addr,
- )
- .await
- }
};
match res {
Ok(res) => Ok(res),
@@ -457,6 +444,78 @@ pub(crate) trait HttpExecutor: Clone + Send + Sync + 'static {
) -> Result<Response<Body>>;
}
+#[derive(Default)]
+pub struct HttpRuntimeData {
+ origin: Option<String>,
+ allowed_hosts: AllowedHttpHosts,
+}
+
+impl OutboundWasiHttpHandler for HttpRuntimeData {
+ fn send_request(
+ data: &mut spin_core::Data<Self>,
+ mut request: wasmtime_wasi_http::types::OutgoingRequest,
+ ) -> wasmtime::Result<
+ wasmtime::component::Resource<wasmtime_wasi_http::types::HostFutureIncomingResponse>,
+ >
+ where
+ Self: Sized,
+ {
+ let this = data.as_ref();
+ let is_relative_url = request
+ .request
+ .uri()
+ .authority()
+ .map(|a| a.host().trim() == "")
+ .unwrap_or_default();
+ if is_relative_url {
+ // Origin must be set in the incoming http handler
+ let origin = this.origin.clone().unwrap();
+ let path_and_query = request
+ .request
+ .uri()
+ .path_and_query()
+ .map(|p| p.as_str())
+ .unwrap_or("/");
+ let uri: Uri = format!("{origin}{path_and_query}")
+ .parse()
+ // origin together with the path and query must be a valid URI
+ .unwrap();
+
+ request.use_tls = uri
+ .scheme()
+ .map(|s| s == &Scheme::HTTPS)
+ .unwrap_or_default();
+ // We know that `uri` has an authority because we set it above
+ request.authority = uri.authority().unwrap().as_str().to_owned();
+ *request.request.uri_mut() = uri;
+ }
+
+ let unallowed_relative = is_relative_url && !this.allowed_hosts.allows_relative_url();
+ let unallowed_absolute = !is_relative_url
+ && !this
+ .allowed_hosts
+ .allows(&url::Url::parse(&request.request.uri().to_string()).unwrap());
+ if unallowed_relative || unallowed_absolute {
+ tracing::log::error!("Destination not allowed: {}", request.request.uri());
+ let host = if unallowed_absolute {
+ // Safe to unwrap because absolute urls have a host by definition.
+ let host = request.request.uri().authority().map(|a| a.host()).unwrap();
+ terminal::warn!(
+ "A component tried to make a HTTP request to non-allowed host '{host}'."
+ );
+ host
+ } else {
+ terminal::warn!("A component tried to make a HTTP request to the same component but it does not have permission.");
+ "self"
+ };
+ eprintln!("To allow requests, add 'allowed_http_hosts = [\"{}\"]' to the manifest component section.", host);
+ anyhow::bail!("destination-not-allowed (error 1)")
+ }
+
+ wasmtime_wasi_http::types::default_send_request(data, request)
+ }
+}
+
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
diff --git a/crates/trigger-http/src/wasi.rs b/crates/trigger-http/src/wasi.rs
deleted file mode 100644
index 2cc1155889..0000000000
--- a/crates/trigger-http/src/wasi.rs
+++ /dev/null
@@ -1,72 +0,0 @@
-use crate::{Body, HttpExecutor, HttpTrigger};
-use anyhow::{anyhow, Context, Result};
-use hyper::{Request, Response};
-use spin_core::async_trait;
-use spin_trigger::{EitherInstance, TriggerAppEngine};
-use std::{net::SocketAddr, str};
-use tokio::{sync::oneshot, task};
-use wasmtime_wasi_http::{proxy::Proxy, WasiHttpView};
-
-#[derive(Clone)]
-pub struct WasiHttpExecutor;
-
-#[async_trait]
-impl HttpExecutor for WasiHttpExecutor {
- async fn execute(
- &self,
- engine: &TriggerAppEngine<HttpTrigger>,
- component_id: &str,
- _base: &str,
- _raw_route: &str,
- req: Request<Body>,
- _client_addr: SocketAddr,
- ) -> Result<Response<Body>> {
- tracing::trace!("Executing request using the WASI executor for component {component_id}",);
-
- let (instance, mut store) = engine.prepare_instance(component_id).await?;
- let EitherInstance::Component(instance) = instance else {
- unreachable!()
- };
-
- let request = store.as_mut().data_mut().new_incoming_request(req)?;
-
- let (response_tx, response_rx) = oneshot::channel();
- let response = store
- .as_mut()
- .data_mut()
- .new_response_outparam(response_tx)?;
-
- let proxy = Proxy::new(&mut store, &instance)?;
-
- let handle = task::spawn(async move {
- let result = proxy
- .wasi_http_incoming_handler()
- .call_handle(&mut store, request, response)
- .await;
-
- tracing::trace!("result: {result:?}",);
-
- tracing::trace!(
- "memory consumed: {}",
- store.as_ref().data().memory_consumed()
- );
-
- result
- });
-
- match response_rx.await {
- Ok(response) => Ok(response.context("guest failed to produce a response")?),
-
- Err(_) => {
- handle
- .await
- .context("guest invocation panicked")?
- .context("guest invocation failed")?;
-
- Err(anyhow!(
- "guest failed to produce a response prior to returning"
- ))
- }
- }
- }
-}
diff --git a/crates/trigger/Cargo.toml b/crates/trigger/Cargo.toml
index cca9ac6a7b..36795663fe 100644
--- a/crates/trigger/Cargo.toml
+++ b/crates/trigger/Cargo.toml
@@ -44,10 +44,11 @@ spin-manifest = { path = "../manifest" }
terminal = { path = "../terminal" }
tokio = { version = "1.23", features = ["fs"] }
toml = "0.5.9"
-tracing = { workspace = true }
url = "2"
-wasmtime = { workspace = true }
spin-componentize = { workspace = true }
+tracing = { workspace = true }
+wasmtime = { workspace = true }
+wasmtime-wasi-http = { workspace = true }
[dev-dependencies]
-tempfile = "3.8.0"
\ No newline at end of file
+tempfile = "3.8.0"
diff --git a/crates/trigger/src/lib.rs b/crates/trigger/src/lib.rs
index e5a58fe875..d062f4b97b 100644
--- a/crates/trigger/src/lib.rs
+++ b/crates/trigger/src/lib.rs
@@ -13,8 +13,8 @@ use serde::de::DeserializeOwned;
use spin_app::{App, AppComponent, AppLoader, AppTrigger, Loader, OwnedApp, APP_NAME_KEY};
use spin_core::{
- Config, Engine, EngineBuilder, Instance, InstancePre, ModuleInstance, ModuleInstancePre, Store,
- StoreBuilder, WasiVersion,
+ Config, Engine, EngineBuilder, Instance, InstancePre, ModuleInstance, ModuleInstancePre,
+ OutboundWasiHttpHandler, Store, StoreBuilder, WasiVersion,
};
pub use crate::runtime_config::RuntimeConfig;
@@ -32,7 +32,7 @@ pub enum EitherInstance {
#[async_trait]
pub trait TriggerExecutor: Sized + Send + Sync {
const TRIGGER_TYPE: &'static str;
- type RuntimeData: Default + Send + Sync + 'static;
+ type RuntimeData: OutboundWasiHttpHandler + Default + Send + Sync + 'static;
type TriggerConfig;
type RunConfig;
@@ -111,6 +111,7 @@ impl<Executor: TriggerExecutor> TriggerExecutorBuilder<Executor> {
let mut builder = Engine::builder(&self.config)?;
if !self.disable_default_host_components {
+ builder.link_import(|l, _| wasmtime_wasi_http::proxy::add_to_linker(l))?;
builder.add_host_component(outbound_redis::OutboundRedisComponent)?;
builder.add_host_component(outbound_pg::OutboundPg::default())?;
builder.add_host_component(outbound_mysql::OutboundMysql::default())?;
diff --git a/examples/config-rust/src/lib.rs b/examples/config-rust/src/lib.rs
index 977b53deca..034ed6a0a2 100644
--- a/examples/config-rust/src/lib.rs
+++ b/examples/config-rust/src/lib.rs
@@ -7,7 +7,7 @@ use spin_sdk::{
/// This endpoint returns the config value specified by key.
#[http_component]
fn get(req: Request) -> anyhow::Result<Response> {
- if req.uri.contains("dotenv") {
+ if req.path_and_query.contains("dotenv") {
let val = config::get("dotenv").expect("Failed to acquire dotenv from spin.toml");
return Ok(Response::new(200, val));
}
diff --git a/examples/http-rust-outbound-http/outbound-http-to-same-app/src/lib.rs b/examples/http-rust-outbound-http/outbound-http-to-same-app/src/lib.rs
index 8a0abeae7f..23cd6c6f91 100644
--- a/examples/http-rust-outbound-http/outbound-http-to-same-app/src/lib.rs
+++ b/examples/http-rust-outbound-http/outbound-http-to-same-app/src/lib.rs
@@ -6,13 +6,14 @@ use spin_sdk::{
/// Send an HTTP request and return the response.
#[http_component]
-fn send_outbound(_req: Request) -> Result<impl IntoResponse> {
+async fn send_outbound(_req: Request) -> Result<impl IntoResponse> {
let mut res: http::Response<()> = spin_sdk::http::send(
http::Request::builder()
.method("GET")
.uri("/hello") // relative routes are not yet supported in cloud
.body(())?,
- )?;
+ )
+ .await?;
res.headers_mut()
.insert("spin-component", "rust-outbound-http".try_into()?);
println!("{:?}", res);
diff --git a/examples/http-rust-outbound-http/outbound-http/src/lib.rs b/examples/http-rust-outbound-http/outbound-http/src/lib.rs
index 627556f335..d99e87359a 100644
--- a/examples/http-rust-outbound-http/outbound-http/src/lib.rs
+++ b/examples/http-rust-outbound-http/outbound-http/src/lib.rs
@@ -6,13 +6,14 @@ use spin_sdk::{
/// Send an HTTP request and return the response.
#[http_component]
-fn send_outbound(_req: Request) -> Result<impl IntoResponse> {
+async fn send_outbound(_req: Request) -> Result<impl IntoResponse> {
let mut res: http::Response<()> = spin_sdk::http::send(
http::Request::builder()
.method("GET")
.uri("https://random-data-api.fermyon.app/animals/json")
.body(())?,
- )?;
+ )
+ .await?;
res.headers_mut()
.insert("spin-component", "rust-outbound-http".try_into()?);
println!("{:?}", res);
diff --git a/examples/rust-outbound-redis/spin.toml b/examples/rust-outbound-redis/spin.toml
index d50fa2cc22..83eeaa409d 100644
--- a/examples/rust-outbound-redis/spin.toml
+++ b/examples/rust-outbound-redis/spin.toml
@@ -12,4 +12,3 @@ source = "target/wasm32-wasi/release/rust_outbound_redis.wasm"
route = "/publish"
[component.build]
command = "cargo build --target wasm32-wasi --release"
-
diff --git a/examples/spin-timer/Cargo.lock b/examples/spin-timer/Cargo.lock
index f67612c861..35dcff4c5b 100644
--- a/examples/spin-timer/Cargo.lock
+++ b/examples/spin-timer/Cargo.lock
@@ -601,7 +601,7 @@ dependencies = [
[[package]]
name = "cranelift-bforest"
version = "0.101.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"cranelift-entity",
]
@@ -609,7 +609,7 @@ dependencies = [
[[package]]
name = "cranelift-codegen"
version = "0.101.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"bumpalo",
"cranelift-bforest",
@@ -629,7 +629,7 @@ dependencies = [
[[package]]
name = "cranelift-codegen-meta"
version = "0.101.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"cranelift-codegen-shared",
]
@@ -637,12 +637,12 @@ dependencies = [
[[package]]
name = "cranelift-codegen-shared"
version = "0.101.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
[[package]]
name = "cranelift-control"
version = "0.101.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"arbitrary",
]
@@ -650,7 +650,7 @@ dependencies = [
[[package]]
name = "cranelift-entity"
version = "0.101.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"serde",
"serde_derive",
@@ -659,7 +659,7 @@ dependencies = [
[[package]]
name = "cranelift-frontend"
version = "0.101.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"cranelift-codegen",
"log",
@@ -670,12 +670,12 @@ dependencies = [
[[package]]
name = "cranelift-isle"
version = "0.101.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
[[package]]
name = "cranelift-native"
version = "0.101.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"cranelift-codegen",
"libc",
@@ -685,7 +685,7 @@ dependencies = [
[[package]]
name = "cranelift-wasm"
version = "0.101.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"cranelift-codegen",
"cranelift-entity",
@@ -693,7 +693,7 @@ dependencies = [
"itertools 0.10.5",
"log",
"smallvec",
- "wasmparser 0.113.3",
+ "wasmparser",
"wasmtime-types",
]
@@ -2868,17 +2868,6 @@ dependencies = [
"cc",
]
-[[package]]
-name = "pulldown-cmark"
-version = "0.9.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "77a1a2f1f0a7ecff9c31abbe177637be0e97a0aef46cf8738ece09327985d998"
-dependencies = [
- "bitflags 1.3.2",
- "memchr",
- "unicase",
-]
-
[[package]]
name = "quote"
version = "1.0.33"
@@ -3604,13 +3593,13 @@ dependencies = [
[[package]]
name = "spin-componentize"
version = "0.1.0"
-source = "git+https://github.com/fermyon/spin-componentize?rev=00820a455086c3d04b1a01236af03be38aac38a1#00820a455086c3d04b1a01236af03be38aac38a1"
+source = "git+https://github.com/fermyon/spin-componentize?rev=191789170abde10cd55590466c0660dd6c7d472a#191789170abde10cd55590466c0660dd6c7d472a"
dependencies = [
"anyhow",
- "wasm-encoder 0.35.0",
- "wasmparser 0.115.0",
+ "wasm-encoder",
+ "wasmparser",
"wit-component",
- "wit-parser 0.12.0",
+ "wit-parser",
]
[[package]]
@@ -3883,6 +3872,7 @@ dependencies = [
"tracing",
"url",
"wasmtime",
+ "wasmtime-wasi-http",
]
[[package]]
@@ -4635,7 +4625,7 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]]
name = "wasi-cap-std-sync"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"anyhow",
"async-trait",
@@ -4657,7 +4647,7 @@ dependencies = [
[[package]]
name = "wasi-common"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"anyhow",
"bitflags 2.4.0",
@@ -4676,7 +4666,7 @@ dependencies = [
[[package]]
name = "wasi-tokio"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"anyhow",
"cap-std",
@@ -4755,15 +4745,6 @@ version = "0.2.87"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca6ad05a4870b2bf5fe995117d3728437bd27d7cd5f06f13c17443ef369775a1"
-[[package]]
-name = "wasm-encoder"
-version = "0.33.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "34180c89672b3e4825c3a8db4b61a674f1447afd5fe2445b2d22c3d8b6ea086c"
-dependencies = [
- "leb128",
-]
-
[[package]]
name = "wasm-encoder"
version = "0.35.0"
@@ -4785,8 +4766,8 @@ dependencies = [
"serde_derive",
"serde_json",
"spdx",
- "wasm-encoder 0.35.0",
- "wasmparser 0.115.0",
+ "wasm-encoder",
+ "wasmparser",
]
[[package]]
@@ -4802,16 +4783,6 @@ dependencies = [
"web-sys",
]
-[[package]]
-name = "wasmparser"
-version = "0.113.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "286049849b5a5bd09a8773171be96824afabffc7cc3df6caaf33a38db6cd07ae"
-dependencies = [
- "indexmap 2.0.2",
- "semver",
-]
-
[[package]]
name = "wasmparser"
version = "0.115.0"
@@ -4824,18 +4795,18 @@ dependencies = [
[[package]]
name = "wasmprinter"
-version = "0.2.68"
+version = "0.2.70"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "537030718ce76e985896e91fe2cac77c1913c8dccd46eaf8ab1a4cd56d824cc3"
+checksum = "e74458a9bc5cc9c7108abfa0fe4dc88d5abf1f3baf194df3264985f17d559b5e"
dependencies = [
"anyhow",
- "wasmparser 0.113.3",
+ "wasmparser",
]
[[package]]
name = "wasmtime"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"anyhow",
"async-trait",
@@ -4856,8 +4827,8 @@ dependencies = [
"serde_derive",
"serde_json",
"target-lexicon",
- "wasm-encoder 0.33.2",
- "wasmparser 0.113.3",
+ "wasm-encoder",
+ "wasmparser",
"wasmtime-cache",
"wasmtime-component-macro",
"wasmtime-component-util",
@@ -4874,7 +4845,7 @@ dependencies = [
[[package]]
name = "wasmtime-asm-macros"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"cfg-if",
]
@@ -4882,7 +4853,7 @@ dependencies = [
[[package]]
name = "wasmtime-cache"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"anyhow",
"base64 0.21.4",
@@ -4901,7 +4872,7 @@ dependencies = [
[[package]]
name = "wasmtime-component-macro"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"anyhow",
"proc-macro2",
@@ -4909,18 +4880,18 @@ dependencies = [
"syn 2.0.38",
"wasmtime-component-util",
"wasmtime-wit-bindgen",
- "wit-parser 0.11.3",
+ "wit-parser",
]
[[package]]
name = "wasmtime-component-util"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
[[package]]
name = "wasmtime-cranelift"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"anyhow",
"cfg-if",
@@ -4935,7 +4906,7 @@ dependencies = [
"object",
"target-lexicon",
"thiserror",
- "wasmparser 0.113.3",
+ "wasmparser",
"wasmtime-cranelift-shared",
"wasmtime-environ",
"wasmtime-versioned-export-macros",
@@ -4944,7 +4915,7 @@ dependencies = [
[[package]]
name = "wasmtime-cranelift-shared"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"anyhow",
"cranelift-codegen",
@@ -4959,7 +4930,7 @@ dependencies = [
[[package]]
name = "wasmtime-environ"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"anyhow",
"cranelift-entity",
@@ -4971,8 +4942,8 @@ dependencies = [
"serde_derive",
"target-lexicon",
"thiserror",
- "wasm-encoder 0.33.2",
- "wasmparser 0.113.3",
+ "wasm-encoder",
+ "wasmparser",
"wasmprinter",
"wasmtime-component-util",
"wasmtime-types",
@@ -4981,7 +4952,7 @@ dependencies = [
[[package]]
name = "wasmtime-fiber"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"cc",
"cfg-if",
@@ -4994,7 +4965,7 @@ dependencies = [
[[package]]
name = "wasmtime-jit"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"addr2line",
"anyhow",
@@ -5020,7 +4991,7 @@ dependencies = [
[[package]]
name = "wasmtime-jit-debug"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"object",
"once_cell",
@@ -5031,7 +5002,7 @@ dependencies = [
[[package]]
name = "wasmtime-jit-icache-coherence"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"cfg-if",
"libc",
@@ -5041,7 +5012,7 @@ dependencies = [
[[package]]
name = "wasmtime-runtime"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"anyhow",
"cc",
@@ -5057,7 +5028,7 @@ dependencies = [
"rand 0.8.5",
"rustix 0.38.18",
"sptr",
- "wasm-encoder 0.33.2",
+ "wasm-encoder",
"wasmtime-asm-macros",
"wasmtime-environ",
"wasmtime-fiber",
@@ -5070,19 +5041,19 @@ dependencies = [
[[package]]
name = "wasmtime-types"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"cranelift-entity",
"serde",
"serde_derive",
"thiserror",
- "wasmparser 0.113.3",
+ "wasmparser",
]
[[package]]
name = "wasmtime-versioned-export-macros"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"proc-macro2",
"quote",
@@ -5092,7 +5063,7 @@ dependencies = [
[[package]]
name = "wasmtime-wasi"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"anyhow",
"async-trait",
@@ -5127,7 +5098,7 @@ dependencies = [
[[package]]
name = "wasmtime-wasi-http"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"anyhow",
"async-trait",
@@ -5149,14 +5120,14 @@ dependencies = [
[[package]]
name = "wasmtime-winch"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"anyhow",
"cranelift-codegen",
"gimli",
"object",
"target-lexicon",
- "wasmparser 0.113.3",
+ "wasmparser",
"wasmtime-cranelift-shared",
"wasmtime-environ",
"winch-codegen",
@@ -5165,18 +5136,18 @@ dependencies = [
[[package]]
name = "wasmtime-wit-bindgen"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"anyhow",
"heck",
"indexmap 2.0.2",
- "wit-parser 0.11.3",
+ "wit-parser",
]
[[package]]
name = "wasmtime-wmemcheck"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
[[package]]
name = "wast"
@@ -5189,23 +5160,23 @@ dependencies = [
[[package]]
name = "wast"
-version = "66.0.0"
+version = "66.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0da7529bb848d58ab8bf32230fc065b363baee2bd338d5e58c589a1e7d83ad07"
+checksum = "93cb43b0ac6dd156f2c375735ccfd72b012a7c0a6e6d09503499b8d3cb6e6072"
dependencies = [
"leb128",
"memchr",
"unicode-width",
- "wasm-encoder 0.33.2",
+ "wasm-encoder",
]
[[package]]
name = "wat"
-version = "1.0.75"
+version = "1.0.77"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4780374047c65b6b6e86019093fe80c18b66825eb684df778a4e068282a780e7"
+checksum = "e367582095d2903caeeea9acbb140e1db9c7677001efa4347c3687fd34fe7072"
dependencies = [
- "wast 66.0.0",
+ "wast 66.0.2",
]
[[package]]
@@ -5237,7 +5208,7 @@ dependencies = [
[[package]]
name = "wiggle"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"anyhow",
"async-trait",
@@ -5251,7 +5222,7 @@ dependencies = [
[[package]]
name = "wiggle-generate"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"anyhow",
"heck",
@@ -5265,7 +5236,7 @@ dependencies = [
[[package]]
name = "wiggle-macro"
version = "14.0.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"proc-macro2",
"quote",
@@ -5307,7 +5278,7 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "winch-codegen"
version = "0.12.0"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"anyhow",
"cranelift-codegen",
@@ -5315,7 +5286,7 @@ dependencies = [
"regalloc2",
"smallvec",
"target-lexicon",
- "wasmparser 0.113.3",
+ "wasmparser",
"wasmtime-environ",
]
@@ -5482,9 +5453,9 @@ dependencies = [
[[package]]
name = "wit-component"
-version = "0.15.0"
+version = "0.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c1bc644bb4205a2ee74035e5d35958777575fa4c6dd38ce7226c7680be2861c1"
+checksum = "e87488b57a08e2cbbd076b325acbe7f8666965af174d69d5929cd373bd54547f"
dependencies = [
"anyhow",
"bitflags 2.4.0",
@@ -5493,35 +5464,17 @@ dependencies = [
"serde",
"serde_derive",
"serde_json",
- "wasm-encoder 0.35.0",
+ "wasm-encoder",
"wasm-metadata",
- "wasmparser 0.115.0",
- "wit-parser 0.12.0",
-]
-
-[[package]]
-name = "wit-parser"
-version = "0.11.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a39edca9abb16309def3843af73b58d47d243fe33a9ceee572446bcc57556b9a"
-dependencies = [
- "anyhow",
- "id-arena",
- "indexmap 2.0.2",
- "log",
- "pulldown-cmark",
- "semver",
- "serde",
- "serde_json",
- "unicode-xid",
- "url",
+ "wasmparser",
+ "wit-parser",
]
[[package]]
name = "wit-parser"
-version = "0.12.0"
+version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d08c9557c65c428ac18a3cce80bf2527dbec24ab06639642c7db73f2c7613f93"
+checksum = "f6ace9943d89bbf3dbbc71b966da0e7302057b311f36a4ac3d65ddfef17b52cf"
dependencies = [
"anyhow",
"id-arena",
@@ -5537,7 +5490,7 @@ dependencies = [
[[package]]
name = "witx"
version = "0.9.1"
-source = "git+https://github.com/bytecodealliance/wasmtime?rev=c796ce7376a57a40605f03e74bd78cefcc9acf3a#c796ce7376a57a40605f03e74bd78cefcc9acf3a"
+source = "git+https://github.com/bytecodealliance/wasmtime?rev=2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb#2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb"
dependencies = [
"anyhow",
"log",
diff --git a/examples/spin-timer/Cargo.toml b/examples/spin-timer/Cargo.toml
index c7576a9b66..dc16079dfc 100644
--- a/examples/spin-timer/Cargo.toml
+++ b/examples/spin-timer/Cargo.toml
@@ -14,7 +14,7 @@ spin-core = { path = "../../crates/core" }
spin-trigger = { path = "../../crates/trigger" }
tokio = { version = "1.11", features = ["full"] }
tokio-scoped = "0.2.0"
-wasmtime = { git = "https://github.com/bytecodealliance/wasmtime", rev = "c796ce7376a57a40605f03e74bd78cefcc9acf3a", features = [
+wasmtime = { git = "https://github.com/bytecodealliance/wasmtime", rev = "2da78ca5c4c1e5a8cbc88a8ad3accf24bb4e6cfb", features = [
"component-model",
] }
diff --git a/examples/spin-wagi-http/spin.toml b/examples/spin-wagi-http/spin.toml
index 7747a3c144..4f45977913 100644
--- a/examples/spin-wagi-http/spin.toml
+++ b/examples/spin-wagi-http/spin.toml
@@ -10,7 +10,7 @@ id = "hello"
source = "wagi-http-cpp/main.wasm"
[component.trigger]
route = "/hello"
-executor = { type = "wagi" } # _start (the default entrypoint) is automatically mapped to main()
+executor = { type = "wagi" } # _start (the default entrypoint) is automatically mapped to main()
[component.build]
command = "make build -C wagi-http-cpp"
@@ -19,6 +19,6 @@ id = "goodbye"
source = "http-rust/target/wasm32-wasi/release/goodbyerust.wasm"
[component.trigger]
route = "/goodbye"
-executor = { type = "spin" }
+executor = { type = "wasi_http" }
[component.build]
command = "cargo build --target wasm32-wasi --release --manifest-path http-rust/Cargo.toml"
diff --git a/examples/wasi-http-rust-streaming-outgoing-body/spin.toml b/examples/wasi-http-rust-streaming-outgoing-body/spin.toml
index ec3b07eca0..31e0cc1d74 100644
--- a/examples/wasi-http-rust-streaming-outgoing-body/spin.toml
+++ b/examples/wasi-http-rust-streaming-outgoing-body/spin.toml
@@ -8,9 +8,9 @@ version = "1.0.0"
[[component]]
id = "wasi-http-async"
source = "target/wasm32-wasi/release/wasi_http_rust_streaming_outgoing_body.wasm"
+allowed_http_hosts = ["insecure:allow-all"]
[component.trigger]
route = "/..."
-executor = { type = "wasi" }
[component.build]
command = "cargo build --target wasm32-wasi --release"
watch = ["src/**/*.rs", "Cargo.toml"]
diff --git a/examples/wasi-http-rust-streaming-outgoing-body/src/lib.rs b/examples/wasi-http-rust-streaming-outgoing-body/src/lib.rs
index f1438fc48c..e12e65757f 100644
--- a/examples/wasi-http-rust-streaming-outgoing-body/src/lib.rs
+++ b/examples/wasi-http-rust-streaming-outgoing-body/src/lib.rs
@@ -1,16 +1,16 @@
use anyhow::{bail, Result};
use futures::{stream, SinkExt, StreamExt, TryStreamExt};
-use spin_sdk::wasi_http::send;
-use spin_sdk::wasi_http::{
+use spin_sdk::http::send;
+use spin_sdk::http::{
Fields, IncomingRequest, IncomingResponse, Method, OutgoingBody, OutgoingRequest,
OutgoingResponse, ResponseOutparam, Scheme,
};
-use spin_sdk::wasi_http_component;
+use spin_sdk::http_component;
use url::Url;
const MAX_CONCURRENCY: usize = 16;
-#[wasi_http_component]
+#[http_component]
async fn handle_request(request: IncomingRequest, response_out: ResponseOutparam) {
let headers = request.headers().entries();
diff --git a/examples/wasi-http-rust/spin.toml b/examples/wasi-http-rust/spin.toml
index 45050117e3..7b3f39a42a 100644
--- a/examples/wasi-http-rust/spin.toml
+++ b/examples/wasi-http-rust/spin.toml
@@ -11,7 +11,6 @@ source = "target/wasm32-wasi/release/wasi_http_rust.wasm"
description = "A simple component that returns hello."
[component.trigger]
route = "/hello"
-executor = { type = "wasi" }
[component.build]
command = "cargo build --target wasm32-wasi --release"
watch = ["src/**/*.rs", "Cargo.toml"]
diff --git a/examples/wasi-http-rust/src/lib.rs b/examples/wasi-http-rust/src/lib.rs
index d01241ace0..853d6b02b2 100644
--- a/examples/wasi-http-rust/src/lib.rs
+++ b/examples/wasi-http-rust/src/lib.rs
@@ -1,5 +1,5 @@
use spin_sdk::http::{IntoResponse, Json, Response};
-use spin_sdk::wasi_http_component;
+use spin_sdk::http_component;
#[derive(serde::Deserialize, Debug)]
struct Greeted {
@@ -7,7 +7,7 @@ struct Greeted {
}
/// A simple Spin HTTP component.
-#[wasi_http_component]
+#[http_component]
async fn hello_world(req: http::Request<Json<Greeted>>) -> anyhow::Result<impl IntoResponse> {
Ok(Response::new(200, format!("Hello, {}", req.body().name)))
}
diff --git a/sdk/rust/Cargo.toml b/sdk/rust/Cargo.toml
index f2fb52868e..542d972f7f 100644
--- a/sdk/rust/Cargo.toml
+++ b/sdk/rust/Cargo.toml
@@ -14,8 +14,6 @@ async-trait = "0.1.74"
form_urlencoded = "1.0"
spin-macro = { path = "macro" }
thiserror = "1.0.37"
-# Use a sha commit for now to include https://github.com/bytecodealliance/wit-bindgen/pull/693
-# Once wit-bindgen 0.13 is released we can move to that version.
wit-bindgen = "0.13.0"
routefinder = "0.5.3"
once_cell = "1.18.0"
diff --git a/sdk/rust/macro/src/lib.rs b/sdk/rust/macro/src/lib.rs
index e98acbf2c4..03e84ff5a3 100644
--- a/sdk/rust/macro/src/lib.rs
+++ b/sdk/rust/macro/src/lib.rs
@@ -3,68 +3,6 @@ use quote::quote;
const WIT_PATH: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/wit");
-/// The entrypoint to a Spin HTTP component written in Rust.
-#[proc_macro_attribute]
-pub fn http_component(_attr: TokenStream, item: TokenStream) -> TokenStream {
- let func = syn::parse_macro_input!(item as syn::ItemFn);
- let func_name = &func.sig.ident;
- let preamble = preamble(Export::Http);
-
- quote!(
- #func
- mod __spin_http {
- #preamble
- impl self::exports::fermyon::spin::inbound_http::Guest for Spin {
- fn handle_request(req: self::exports::fermyon::spin::inbound_http::Request) -> self::exports::fermyon::spin::inbound_http::Response {
- let req: ::spin_sdk::http::Request = ::std::convert::Into::into(req);
- let resp = match ::spin_sdk::http::conversions::TryFromRequest::try_from_request(req) {
- ::std::result::Result::Ok(req) => ::spin_sdk::http::IntoResponse::into_response(super::#func_name(req)),
- ::std::result::Result::Err(e) => ::spin_sdk::http::IntoResponse::into_response(e),
- };
- ::std::convert::Into::into(resp)
- }
- }
-
- impl ::std::convert::From<self::fermyon::spin::http_types::Request> for ::spin_sdk::http::Request {
- fn from(req: self::fermyon::spin::http_types::Request) -> Self {
- Self {
- method: ::std::convert::Into::into(req.method),
- uri: req.uri,
- params: req.params,
- headers: req.headers,
- body: req.body
- }
- }
- }
-
- impl ::std::convert::From<self::fermyon::spin::http_types::Method> for ::spin_sdk::http::Method {
- fn from(method: self::fermyon::spin::http_types::Method) -> Self {
- match method {
- self::fermyon::spin::http_types::Method::Get => Self::Get,
- self::fermyon::spin::http_types::Method::Post => Self::Post,
- self::fermyon::spin::http_types::Method::Put => Self::Put,
- self::fermyon::spin::http_types::Method::Patch => Self::Patch,
- self::fermyon::spin::http_types::Method::Delete => Self::Delete,
- self::fermyon::spin::http_types::Method::Head => Self::Head,
- self::fermyon::spin::http_types::Method::Options => Self::Options,
- }
- }
- }
-
- impl ::std::convert::From<::spin_sdk::http::Response> for self::fermyon::spin::http_types::Response {
- fn from(resp: ::spin_sdk::http::Response) -> Self {
- Self {
- status: resp.status,
- headers: resp.headers,
- body: resp.body,
- }
- }
- }
- }
- )
- .into()
-}
-
/// Generates the entrypoint to a Spin Redis component written in Rust.
#[proc_macro_attribute]
pub fn redis_component(_attr: TokenStream, item: TokenStream) -> TokenStream {
@@ -102,34 +40,48 @@ pub fn redis_component(_attr: TokenStream, item: TokenStream) -> TokenStream {
///
/// ### Request/Response
///
-/// This form has the same shape as the `http_component` handlers. The only difference is that the underlying handling
-/// happens through the `wasi-http` interface instead of the Spin specific `http` interface and thus requests are
-/// anything that implements `spin_sdk::wasi_http::conversions::TryFromIncomingRequest` and responses are anything that
-/// implements `spin_sdk::http::IntoResponse`.
+/// This form takes the form of a function with one `request` param and one `response` return value.
+///
+/// Requests are anything that implements `spin_sdk::http::conversions::TryFromIncomingRequest` which includes
+/// `spin_sdk::http::Request`, `spin_sdk::http::IncomingRequest`, and even hyperium's popular `http` crate's `Request`
+/// type.
+///
+/// Responses are anything that implements `spin_sdk::http::IntoResponse`. This includes `Result<impl IntoResponse, impl IntoResponse`,
+/// `spin_sdk::http::Response`, and even the `http` crate's `Response` type.
///
/// For example:
/// ```ignore
-/// #[wasi_http_component]
-/// async fn my_handler(request: IncomingRequest) -> anyhow::Result<impl IntoResponse> {
+/// use spin_sdk::http_component;
+/// use spin_sdk::http::{Request, IntoResponse};
+///
+/// #[http_component]
+/// async fn my_handler(request: Request) -> anyhow::Result<impl IntoResponse> {
/// // Your logic goes here
/// }
/// ```
///
/// ### Input/Output Params
///
-/// Input/Output functions allow for streaming HTTP bodies. They are expected generally to be in the form:
+/// Input/Output functions allow for streaming HTTP bodies. This form is by its very nature harder to use than
+/// the request/response form above so it should only be favored when stream response bodies is desired.
+///
+/// The `request` param can be anything that implements `spin_sdk::http::TryFromIncomingRequest`. And
+/// the `response_out` param must be a `spin_sdk::http::ResponseOutparam`. See the docs of `ResponseOutparam`
+/// for how to use this type.
+///
+/// For example:
+///
/// ```ignore
-/// #[wasi_http_component]
+/// use spin_sdk::http_component;
+/// use spin_sdk::http::{IncomingRequest, ResponseOutparam};
+///
+/// #[http_component]
/// async fn my_handler(request: IncomingRequest, response_out: ResponseOutparam) {
/// // Your logic goes here
/// }
/// ```
-///
-/// The `request` param can be anything that implements `spin_sdk::wasi_http::conversions::TryFromIncomingRequest`.
-/// This includes all types that implement `spin_sdk::http::conversions::TryIntoRequest` (which may be more convenient to use
-/// when you don't need streaming request bodies).
#[proc_macro_attribute]
-pub fn wasi_http_component(_attr: TokenStream, item: TokenStream) -> TokenStream {
+pub fn http_component(_attr: TokenStream, item: TokenStream) -> TokenStream {
let func = syn::parse_macro_input!(item as syn::ItemFn);
let func_name = &func.sig.ident;
let preamble = preamble(Export::WasiHttp);
@@ -147,10 +99,10 @@ pub fn wasi_http_component(_attr: TokenStream, item: TokenStream) -> TokenStream
#preamble
impl self::exports::wasi::http::incoming_handler::Guest for Spin {
fn handle(request: wasi::http::types::IncomingRequest, response_out: self::wasi::http::types::ResponseOutparam) {
- let request: ::spin_sdk::wasi_http::IncomingRequest = ::std::convert::Into::into(request);
- let response_out: ::spin_sdk::wasi_http::ResponseOutparam = ::std::convert::Into::into(response_out);
- ::spin_sdk::wasi_http::run(async move {
- match ::spin_sdk::wasi_http::conversions::TryFromIncomingRequest::try_from_incoming_request(request).await {
+ let request: ::spin_sdk::http::IncomingRequest = ::std::convert::Into::into(request);
+ let response_out: ::spin_sdk::http::ResponseOutparam = ::std::convert::Into::into(response_out);
+ ::spin_sdk::http::run(async move {
+ match ::spin_sdk::http::conversions::TryFromIncomingRequest::try_from_incoming_request(request).await {
::std::result::Result::Ok(req) => #handler,
::std::result::Result::Err(e) => handle_response(response_out, e).await,
}
@@ -158,29 +110,29 @@ pub fn wasi_http_component(_attr: TokenStream, item: TokenStream) -> TokenStream
}
}
- async fn handle_response<R: ::spin_sdk::http::IntoResponse>(response_out: ::spin_sdk::wasi_http::ResponseOutparam, resp: R) {
+ async fn handle_response<R: ::spin_sdk::http::IntoResponse>(response_out: ::spin_sdk::http::ResponseOutparam, resp: R) {
let mut response = ::spin_sdk::http::IntoResponse::into_response(resp);
- let body = response.body.take().unwrap_or_default();
+ let body = std::mem::take(&mut response.body);
let response = ::std::convert::Into::into(response);
- if let Err(e) = ::spin_sdk::wasi_http::ResponseOutparam::set_with_body(response_out, response, body).await {
+ if let Err(e) = ::spin_sdk::http::ResponseOutparam::set_with_body(response_out, response, body).await {
eprintln!("Could not set `ResponseOutparam`: {e}");
}
}
- impl From<self::wasi::http::types::IncomingRequest> for ::spin_sdk::wasi_http::IncomingRequest {
+ impl From<self::wasi::http::types::IncomingRequest> for ::spin_sdk::http::IncomingRequest {
fn from(req: self::wasi::http::types::IncomingRequest) -> Self {
let req = ::std::mem::ManuallyDrop::new(req);
unsafe { Self::from_handle(req.handle()) }
}
}
- impl From<::spin_sdk::wasi_http::OutgoingResponse> for self::wasi::http::types::OutgoingResponse {
- fn from(resp: ::spin_sdk::wasi_http::OutgoingResponse) -> Self {
+ impl From<::spin_sdk::http::OutgoingResponse> for self::wasi::http::types::OutgoingResponse {
+ fn from(resp: ::spin_sdk::http::OutgoingResponse) -> Self {
unsafe { Self::from_handle(resp.into_handle()) }
}
}
- impl From<self::wasi::http::types::ResponseOutparam> for ::spin_sdk::wasi_http::ResponseOutparam {
+ impl From<self::wasi::http::types::ResponseOutparam> for ::spin_sdk::http::ResponseOutparam {
fn from(resp: self::wasi::http::types::ResponseOutparam) -> Self {
let resp = ::std::mem::ManuallyDrop::new(resp);
unsafe { Self::from_handle(resp.handle()) }
@@ -195,19 +147,16 @@ pub fn wasi_http_component(_attr: TokenStream, item: TokenStream) -> TokenStream
#[derive(Copy, Clone)]
enum Export {
WasiHttp,
- Http,
Redis,
}
fn preamble(export: Export) -> proc_macro2::TokenStream {
let export_decl = match export {
Export::WasiHttp => quote!("wasi:http/incoming-handler": Spin),
- Export::Http => quote!("fermyon:spin/inbound-http": Spin),
Export::Redis => quote!("fermyon:spin/inbound-redis": Spin),
};
let world = match export {
Export::WasiHttp => quote!("wasi-http-trigger"),
- Export::Http => quote!("http-trigger"),
Export::Redis => quote!("redis-trigger"),
};
quote! {
diff --git a/sdk/rust/macro/wit/deps/http/types.wit b/sdk/rust/macro/wit/deps/http/types.wit
index 2b64e40eb6..9563efdfd2 100644
--- a/sdk/rust/macro/wit/deps/http/types.wit
+++ b/sdk/rust/macro/wit/deps/http/types.wit
@@ -1,11 +1,9 @@
-package wasi:http
-
// The `wasi:http/types` interface is meant to be imported by components to
// define the HTTP resource types and operations used by the component's
// imported and exported interfaces.
interface types {
- use wasi:io/streams.{input-stream, output-stream}
- use wasi:io/poll.{pollable}
+ use wasi:io/streams@0.2.0-rc-2023-10-18.{input-stream, output-stream}
+ use wasi:io/poll@0.2.0-rc-2023-10-18.{pollable}
// This type corresponds to HTTP standard Methods.
variant method {
diff --git a/sdk/rust/macro/wit/deps/http/world.wit b/sdk/rust/macro/wit/deps/http/world.wit
new file mode 100644
index 0000000000..0798c84292
--- /dev/null
+++ b/sdk/rust/macro/wit/deps/http/world.wit
@@ -0,0 +1,1 @@
+package wasi:http@0.2.0-rc-2023-10-18
diff --git a/sdk/rust/macro/wit/deps/io/poll.wit b/sdk/rust/macro/wit/deps/io/poll.wit
index e95762b915..4ff4765c99 100644
--- a/sdk/rust/macro/wit/deps/io/poll.wit
+++ b/sdk/rust/macro/wit/deps/io/poll.wit
@@ -1,5 +1,3 @@
-package wasi:io
-
/// A poll API intended to let users wait for I/O events on multiple handles
/// at once.
interface poll {
diff --git a/sdk/rust/macro/wit/deps/io/streams.wit b/sdk/rust/macro/wit/deps/io/streams.wit
index 55562d1cbf..d5c7835e4e 100644
--- a/sdk/rust/macro/wit/deps/io/streams.wit
+++ b/sdk/rust/macro/wit/deps/io/streams.wit
@@ -1,5 +1,3 @@
-package wasi:io
-
/// WASI I/O is an I/O abstraction API which is currently focused on providing
/// stream types.
///
diff --git a/sdk/rust/macro/wit/deps/io/world.wit b/sdk/rust/macro/wit/deps/io/world.wit
index 8738dba756..0fdcfcd969 100644
--- a/sdk/rust/macro/wit/deps/io/world.wit
+++ b/sdk/rust/macro/wit/deps/io/world.wit
@@ -1,6 +1,1 @@
-package wasi:io
-
-world imports {
- import streams
- import poll
-}
+package wasi:io@0.2.0-rc-2023-10-18
diff --git a/sdk/rust/macro/wit/http-types.wit b/sdk/rust/macro/wit/http-types.wit
deleted file mode 100644
index 5d156046bd..0000000000
--- a/sdk/rust/macro/wit/http-types.wit
+++ /dev/null
@@ -1,44 +0,0 @@
-interface http-types {
- type http-status = u16
-
- type body = list<u8>
-
- type headers = list<tuple<string, string>>
-
- type params = list<tuple<string, string>>
-
- type uri = string
-
- enum method {
- get,
- post,
- put,
- delete,
- patch,
- head,
- options,
- }
-
- record request {
- method: method,
- uri: uri,
- headers: headers,
- params: params,
- body: option<body>,
- }
-
- record response {
- status: http-status,
- headers: option<headers>,
- body: option<body>,
- }
-
- enum http-error {
- success,
- destination-not-allowed,
- invalid-url,
- request-error,
- runtime-error,
- too-many-requests,
- }
-}
diff --git a/sdk/rust/macro/wit/inbound-http.wit b/sdk/rust/macro/wit/inbound-http.wit
deleted file mode 100644
index 0fef7f58dd..0000000000
--- a/sdk/rust/macro/wit/inbound-http.wit
+++ /dev/null
@@ -1,5 +0,0 @@
-interface inbound-http {
- use http-types.{request, response}
-
- handle-request: func(req: request) -> response
-}
diff --git a/sdk/rust/macro/wit/world.wit b/sdk/rust/macro/wit/world.wit
index 54d7bfd7f8..dc65710b11 100644
--- a/sdk/rust/macro/wit/world.wit
+++ b/sdk/rust/macro/wit/world.wit
@@ -1,14 +1,10 @@
package fermyon:spin
-world http-trigger {
- export inbound-http
-}
-
world redis-trigger {
export inbound-redis
}
world wasi-http-trigger {
- import wasi:http/outgoing-handler
- export wasi:http/incoming-handler
+ import wasi:http/outgoing-handler@0.2.0-rc-2023-10-18
+ export wasi:http/incoming-handler@0.2.0-rc-2023-10-18
}
diff --git a/sdk/rust/readme.md b/sdk/rust/readme.md
index 3702b5c5f5..ef24d00a4b 100644
--- a/sdk/rust/readme.md
+++ b/sdk/rust/readme.md
@@ -40,13 +40,13 @@ server, modifies the result, then returns it:
```rust
#[http_component]
-fn hello_world(_req: Request) -> Result<Response> {
+async fn hello_world(_req: Request) -> Result<Response> {
let mut res: http::Response<()> = spin_sdk::http::send(
http::Request::builder()
.method("GET")
.uri("https://fermyon.com")
.body(())?,
- )?;
+ ).await?;
res.headers_mut()
.insert(http::header::SERVER, "spin/0.1.0".try_into()?);
diff --git a/sdk/rust/src/http.rs b/sdk/rust/src/http.rs
index 5ee37acfed..8e912e9e43 100644
--- a/sdk/rust/src/http.rs
+++ b/sdk/rust/src/http.rs
@@ -1,50 +1,87 @@
-use std::fmt::Display;
-use std::hash::Hash;
-
-use crate::wit::v1::{http::send_request, http_types::HttpError};
-
/// Traits for converting between the various types
pub mod conversions;
#[doc(inline)]
pub use conversions::IntoResponse;
+use self::conversions::TryFromIncomingResponse;
+
#[doc(inline)]
-pub use crate::wit::v1::http_types::{Method, Request, Response};
+pub use super::wit::wasi::http::types::*;
-/// Perform an HTTP request getting back a response or an error
-pub fn send<I, O>(req: I) -> Result<O, SendError>
-where
- I: TryInto<Request>,
- I::Error: Into<Box<dyn std::error::Error + Send + Sync>> + 'static,
- O: TryFrom<Response>,
- O::Error: Into<Box<dyn std::error::Error + Send + Sync>> + 'static,
-{
- let response = send_request(
- &req.try_into()
- .map_err(|e| SendError::RequestConversion(e.into()))?,
- )
- .map_err(SendError::Http)?;
- response
- .try_into()
- .map_err(|e: O::Error| SendError::ResponseConversion(e.into()))
+/// A unified request object that can represent both incoming and outgoing requests.
+///
+/// This should be used in favor of `IncomingRequest` and `OutgoingRequest` when there
+/// is no need for streaming bodies.
+pub struct Request {
+ /// The method of the request
+ pub method: Method,
+ /// The path together with the query string
+ pub path_and_query: String,
+ /// The request headers
+ pub headers: Vec<(String, Vec<u8>)>,
+ /// The request body as bytes
+ pub body: Vec<u8>,
}
-/// An error encountered when performing an HTTP request
-#[derive(thiserror::Error, Debug)]
-pub enum SendError {
- /// Error converting to a request
- #[error(transparent)]
- RequestConversion(Box<dyn std::error::Error + Send + Sync>),
- /// Error converting from a response
- #[error(transparent)]
- ResponseConversion(Box<dyn std::error::Error + Send + Sync>),
- /// An HTTP error
- #[error(transparent)]
- Http(HttpError),
+/// A unified response object that can represent both outgoing and incoming responses.
+///
+/// This should be used in favor of `OutgoingResponse` and `IncomingResponse` when there
+/// is no need for streaming bodies.
+pub struct Response {
+ /// The status of the response
+ pub status: StatusCode,
+ /// The response headers
+ pub headers: Vec<(String, Vec<u8>)>,
+ /// The body of the response as bytes
+ pub body: Vec<u8>,
+}
+
+impl Response {
+ /// Create a new response from a status and optional headers and body
+ pub fn new<S: conversions::IntoStatusCode, B: conversions::IntoBody>(
+ status: S,
+ body: B,
+ ) -> Self {
+ Self {
+ status: status.into_status_code(),
+ headers: Default::default(),
+ body: body.into_body(),
+ }
+ }
+
+ /// Create a new response from a status and optional headers and body
+ pub fn new_with_headers<S: conversions::IntoStatusCode, B: conversions::IntoBody>(
+ status: S,
+ headers: Vec<(String, Vec<u8>)>,
+ body: B,
+ ) -> Self {
+ Self {
+ status: status.into_status_code(),
+ headers,
+ body: body.into_body(),
+ }
+ }
}
-impl Display for Method {
+impl std::hash::Hash for Method {
+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
+ core::mem::discriminant(self).hash(state);
+ }
+}
+
+impl Eq for Method {}
+
+impl PartialEq for Method {
+ fn eq(&self, other: &Self) -> bool {
+ match (self, other) {
+ (Self::Other(l), Self::Other(r)) => l == r,
+ _ => core::mem::discriminant(self) == core::mem::discriminant(other),
+ }
+ }
+}
+
+impl std::fmt::Display for Method {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Method::Get => "GET",
@@ -54,43 +91,124 @@ impl Display for Method {
Method::Patch => "PATCH",
Method::Head => "HEAD",
Method::Options => "OPTIONS",
+ Method::Connect => "CONNECT",
+ Method::Trace => "TRACE",
+ Method::Other(o) => o,
})
}
}
-impl Hash for Method {
- fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
- core::mem::discriminant(self).hash(state);
+impl IncomingRequest {
+ /// Return a `Stream` from which the body of the specified request may be read.
+ ///
+ /// # Panics
+ ///
+ /// Panics if the body was already consumed.
+ pub fn into_body_stream(self) -> impl futures::Stream<Item = anyhow::Result<Vec<u8>>> {
+ executor::incoming_body(self.consume().expect("request body was already consumed"))
}
-}
-impl Response {
- /// Create a new response from a status and optional headers and body
- pub fn new<S: conversions::IntoStatusCode, B: conversions::IntoBody>(
- status: S,
- body: B,
- ) -> Self {
- Self {
- status: status.into_status_code(),
- headers: None,
- body: body.into_body(),
+ /// Return a `Vec<u8>` of the body or fails
+ pub async fn into_body(self) -> anyhow::Result<Vec<u8>> {
+ use futures::TryStreamExt;
+ let mut stream = self.into_body_stream();
+ let mut body = Vec::new();
+ while let Some(chunk) = stream.try_next().await? {
+ body.extend(chunk);
}
+ Ok(body)
}
+}
- /// Create a new response from a status and optional headers and body
- pub fn new_with_headers(
- status: u16,
- headers: Vec<(String, String)>,
- body: Option<Vec<u8>>,
- ) -> Self {
- Self {
- status,
- headers: Some(headers),
- body,
+impl IncomingResponse {
+ /// Return a `Stream` from which the body of the specified response may be read.
+ ///
+ /// # Panics
+ ///
+ /// Panics if the body was already consumed.
+ pub fn into_body_stream(self) -> impl futures::Stream<Item = anyhow::Result<Vec<u8>>> {
+ executor::incoming_body(self.consume().expect("response body was already consumed"))
+ }
+
+ /// Return a `Vec<u8>` of the body or fails
+ pub async fn into_body(self) -> anyhow::Result<Vec<u8>> {
+ use futures::TryStreamExt;
+ let mut stream = self.into_body_stream();
+ let mut body = Vec::new();
+ while let Some(chunk) = stream.try_next().await? {
+ body.extend(chunk);
}
+ Ok(body)
+ }
+}
+
+impl OutgoingResponse {
+ /// Construct a `Sink` which writes chunks to the body of the specified response.
+ ///
+ /// # Panics
+ ///
+ /// Panics if the body was already taken.
+ pub fn take_body(&self) -> impl futures::Sink<Vec<u8>, Error = anyhow::Error> {
+ executor::outgoing_body(self.write().expect("response body was already taken"))
}
}
+impl ResponseOutparam {
+ /// Set with the outgoing response and the supplied buffer
+ ///
+ /// Will panic if response body has already been taken
+ pub async fn set_with_body(
+ self,
+ response: OutgoingResponse,
+ buffer: Vec<u8>,
+ ) -> anyhow::Result<()> {
+ use futures::SinkExt;
+ let mut body = response.take_body();
+ ResponseOutparam::set(self, Ok(response));
+ body.send(buffer).await
+ }
+}
+
+/// Send an outgoing request
+pub async fn send<I, O>(request: I) -> Result<O, SendError>
+where
+ I: TryInto<OutgoingRequest>,
+ I::Error: Into<Box<dyn std::error::Error + Send + Sync>> + 'static,
+ O: TryFromIncomingResponse,
+ O::Error: Into<Box<dyn std::error::Error + Send + Sync>> + 'static,
+{
+ let response = executor::outgoing_request_send(
+ request
+ .try_into()
+ .map_err(|e| SendError::RequestConversion(e.into()))?,
+ )
+ .await
+ .map_err(SendError::Http)?;
+ TryFromIncomingResponse::try_from_incoming_response(response)
+ .await
+ .map_err(|e: O::Error| SendError::ResponseConversion(e.into()))
+}
+
+/// An error encountered when performing an HTTP request
+#[derive(thiserror::Error, Debug)]
+pub enum SendError {
+ /// Error converting to a request
+ #[error(transparent)]
+ RequestConversion(Box<dyn std::error::Error + Send + Sync>),
+ /// Error converting from a response
+ #[error(transparent)]
+ ResponseConversion(Box<dyn std::error::Error + Send + Sync>),
+ /// An HTTP error
+ #[error(transparent)]
+ Http(Error),
+}
+
+#[doc(hidden)]
+/// The executor for driving wasi-http futures to completion
+mod executor;
+#[doc(hidden)]
+pub use executor::run;
+
/// An error parsing a JSON body
#[cfg(feature = "json")]
#[derive(Debug)]
@@ -100,7 +218,7 @@ pub struct JsonBodyError(serde_json::Error);
impl std::error::Error for JsonBodyError {}
#[cfg(feature = "json")]
-impl Display for JsonBodyError {
+impl std::fmt::Display for JsonBodyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("could not convert body to json")
}
@@ -112,7 +230,7 @@ pub struct NonUtf8BodyError;
impl std::error::Error for NonUtf8BodyError {}
-impl Display for NonUtf8BodyError {
+impl std::fmt::Display for NonUtf8BodyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("body was expected to be utf8 but was not")
}
diff --git a/sdk/rust/src/http/conversions.rs b/sdk/rust/src/http/conversions.rs
index 631bc6549a..bc4ec78617 100644
--- a/sdk/rust/src/http/conversions.rs
+++ b/sdk/rust/src/http/conversions.rs
@@ -1,6 +1,104 @@
-use crate::wit::v1::http::{Request, Response};
+use async_trait::async_trait;
-use super::{responses, NonUtf8BodyError};
+use super::{
+ Fields, Headers, IncomingRequest, IncomingResponse, OutgoingRequest, OutgoingResponse,
+};
+
+use super::{responses, NonUtf8BodyError, Request, Response};
+
+impl From<Response> for OutgoingResponse {
+ fn from(response: Response) -> Self {
+ OutgoingResponse::new(response.status, &Headers::new(&response.headers))
+ }
+}
+
+/// A trait for trying to convert from an `IncomingRequest` to the implementing type
+#[async_trait]
+pub trait TryFromIncomingRequest {
+ /// The error if conversion fails
+ type Error;
+
+ /// Try to turn the `IncomingRequest` into the implementing type
+ async fn try_from_incoming_request(value: IncomingRequest) -> Result<Self, Self::Error>
+ where
+ Self: Sized;
+}
+
+#[async_trait]
+impl TryFromIncomingRequest for IncomingRequest {
+ type Error = std::convert::Infallible;
+ async fn try_from_incoming_request(request: IncomingRequest) -> Result<Self, Self::Error> {
+ Ok(request)
+ }
+}
+
+#[async_trait]
+impl<R> TryFromIncomingRequest for R
+where
+ R: TryNonRequestFromRequest,
+{
+ type Error = IncomingRequestError<R::Error>;
+
+ async fn try_from_incoming_request(request: IncomingRequest) -> Result<Self, Self::Error> {
+ let req = Request::try_from_incoming_request(request)
+ .await
+ .map_err(convert_error)?;
+ R::try_from_request(req).map_err(IncomingRequestError::ConversionError)
+ }
+}
+
+#[async_trait]
+impl TryFromIncomingRequest for Request {
+ type Error = IncomingRequestError;
+
+ async fn try_from_incoming_request(request: IncomingRequest) -> Result<Self, Self::Error> {
+ let headers = request.headers().entries();
+ Ok(Self {
+ method: request.method(),
+ path_and_query: request
+ .path_with_query()
+ .unwrap_or_else(|| String::from("/")),
+ headers,
+ body: request
+ .into_body()
+ .await
+ .map_err(IncomingRequestError::BodyConversionError)?,
+ })
+ }
+}
+
+#[derive(Debug, thiserror::Error)]
+/// An error converting an `IncomingRequest`
+pub enum IncomingRequestError<E = std::convert::Infallible> {
+ /// There was an error converting the body to an `Option<Vec<u8>>k`
+ #[error(transparent)]
+ BodyConversionError(anyhow::Error),
+ /// There was an error converting the `Request` into the requested type
+ #[error(transparent)]
+ ConversionError(E),
+}
+
+/// Helper for converting `IncomingRequestError`s that cannot fail due to conversion errors
+/// into ones that can.
+fn convert_error<E>(
+ error: IncomingRequestError<std::convert::Infallible>,
+) -> IncomingRequestError<E> {
+ match error {
+ IncomingRequestError::BodyConversionError(e) => {
+ IncomingRequestError::BodyConversionError(e)
+ }
+ IncomingRequestError::ConversionError(_) => unreachable!(),
+ }
+}
+
+impl<E: IntoResponse> IntoResponse for IncomingRequestError<E> {
+ fn into_response(self) -> Response {
+ match self {
+ IncomingRequestError::BodyConversionError(e) => e.into_response(),
+ IncomingRequestError::ConversionError(e) => e.into_response(),
+ }
+ }
+}
/// A trait for any type that can be constructor from a `Request`
pub trait TryFromRequest {
@@ -53,7 +151,9 @@ pub trait TryNonRequestFromRequest {
impl<B: TryFromBody> TryNonRequestFromRequest for hyperium::Request<B> {
type Error = B::Error;
fn try_from_request(req: Request) -> Result<Self, Self::Error> {
- let mut builder = hyperium::Request::builder().uri(req.uri).method(req.method);
+ let mut builder = hyperium::Request::builder()
+ .uri(req.path_and_query)
+ .method(req.method);
for (n, v) in req.headers {
builder = builder.header(n, v);
}
@@ -72,6 +172,9 @@ impl From<super::Method> for hyperium::Method {
super::Method::Patch => hyperium::Method::PATCH,
super::Method::Head => hyperium::Method::HEAD,
super::Method::Options => hyperium::Method::OPTIONS,
+ super::Method::Connect => hyperium::Method::CONNECT,
+ super::Method::Trace => hyperium::Method::TRACE,
+ super::Method::Other(o) => hyperium::Method::from_bytes(o.as_bytes()).expect("TODO"),
}
}
}
@@ -97,12 +200,7 @@ where
let headers = self
.headers()
.into_iter()
- .map(|(n, v)| {
- (
- n.as_str().to_owned(),
- String::from_utf8_lossy(v.as_bytes()).into_owned(),
- )
- })
+ .map(|(n, v)| (n.as_str().to_owned(), v.as_bytes().to_owned()))
.collect();
Response::new_with_headers(
self.status().as_u16(),
@@ -132,8 +230,8 @@ impl IntoResponse for anyhow::Error {
}
Response {
status: 500,
- headers: None,
- body: Some(body.as_bytes().to_vec()),
+ headers: Default::default(),
+ body: body.as_bytes().to_vec(),
}
}
}
@@ -149,8 +247,8 @@ impl IntoResponse for Box<dyn std::error::Error> {
}
Response {
status: 500,
- headers: None,
- body: Some(body.as_bytes().to_vec()),
+ headers: Default::default(),
+ body: body.as_bytes().to_vec(),
}
}
}
@@ -198,43 +296,43 @@ impl IntoStatusCode for hyperium::StatusCode {
/// A trait for any type that can be turned into a `Response` body
pub trait IntoBody {
/// Turn `self` into a `Response` body
- fn into_body(self) -> Option<Vec<u8>>;
+ fn into_body(self) -> Vec<u8>;
}
impl<T: IntoBody> IntoBody for Option<T> {
- fn into_body(self) -> Option<Vec<u8>> {
- self.and_then(|b| IntoBody::into_body(b))
+ fn into_body(self) -> Vec<u8> {
+ self.map(|b| IntoBody::into_body(b)).unwrap_or_default()
}
}
impl IntoBody for Vec<u8> {
- fn into_body(self) -> Option<Vec<u8>> {
- Some(self)
+ fn into_body(self) -> Vec<u8> {
+ self
}
}
#[cfg(feature = "http")]
impl IntoBody for bytes::Bytes {
- fn into_body(self) -> Option<Vec<u8>> {
- Some(self.to_vec())
+ fn into_body(self) -> Vec<u8> {
+ self.to_vec()
}
}
impl IntoBody for () {
- fn into_body(self) -> Option<Vec<u8>> {
- None
+ fn into_body(self) -> Vec<u8> {
+ Default::default()
}
}
impl IntoBody for &str {
- fn into_body(self) -> Option<Vec<u8>> {
- Some(self.to_owned().into_bytes())
+ fn into_body(self) -> Vec<u8> {
+ self.to_owned().into_bytes()
}
}
impl IntoBody for String {
- fn into_body(self) -> Option<Vec<u8>> {
- Some(self.to_owned().into_bytes())
+ fn into_body(self) -> Vec<u8> {
+ self.to_owned().into_bytes()
}
}
@@ -243,7 +341,7 @@ pub trait TryFromBody {
/// The error encountered if conversion fails
type Error: IntoResponse;
/// Convert from a body to `Self` or fail
- fn try_from_body(body: Option<Vec<u8>>) -> Result<Self, Self::Error>
+ fn try_from_body(body: Vec<u8>) -> Result<Self, Self::Error>
where
Self: Sized;
}
@@ -251,21 +349,18 @@ pub trait TryFromBody {
impl<T: TryFromBody> TryFromBody for Option<T> {
type Error = T::Error;
- fn try_from_body(body: Option<Vec<u8>>) -> Result<Self, Self::Error>
+ fn try_from_body(body: Vec<u8>) -> Result<Self, Self::Error>
where
Self: Sized,
{
- Ok(match body {
- None => None,
- Some(v) => Some(TryFromBody::try_from_body(Some(v))?),
- })
+ Ok(Some(TryFromBody::try_from_body(body)?))
}
}
impl<T: FromBody> TryFromBody for T {
type Error = std::convert::Infallible;
- fn try_from_body(body: Option<Vec<u8>>) -> Result<Self, Self::Error>
+ fn try_from_body(body: Vec<u8>) -> Result<Self, Self::Error>
where
Self: Sized,
{
@@ -276,20 +371,20 @@ impl<T: FromBody> TryFromBody for T {
impl TryFromBody for String {
type Error = NonUtf8BodyError;
- fn try_from_body(body: Option<Vec<u8>>) -> Result<Self, Self::Error>
+ fn try_from_body(body: Vec<u8>) -> Result<Self, Self::Error>
where
Self: Sized,
{
- String::from_utf8(body.unwrap_or_default()).map_err(|_| NonUtf8BodyError)
+ String::from_utf8(body).map_err(|_| NonUtf8BodyError)
}
}
#[cfg(feature = "json")]
impl<T: serde::de::DeserializeOwned> TryFromBody for super::Json<T> {
type Error = super::JsonBodyError;
- fn try_from_body(body: Option<Vec<u8>>) -> Result<Self, Self::Error> {
+ fn try_from_body(body: Vec<u8>) -> Result<Self, Self::Error> {
Ok(super::Json(
- serde_json::from_slice(&body.unwrap_or_default()).map_err(super::JsonBodyError)?,
+ serde_json::from_slice(&body).map_err(super::JsonBodyError)?,
))
}
}
@@ -297,23 +392,23 @@ impl<T: serde::de::DeserializeOwned> TryFromBody for super::Json<T> {
/// A trait from converting from a body
pub trait FromBody {
/// Convert from a body into the type
- fn from_body(body: Option<Vec<u8>>) -> Self;
+ fn from_body(body: Vec<u8>) -> Self;
}
impl FromBody for Vec<u8> {
- fn from_body(body: Option<Vec<u8>>) -> Self {
- body.unwrap_or_default()
+ fn from_body(body: Vec<u8>) -> Self {
+ body
}
}
impl FromBody for () {
- fn from_body(_body: Option<Vec<u8>>) -> Self {}
+ fn from_body(_body: Vec<u8>) -> Self {}
}
#[cfg(feature = "http")]
impl FromBody for bytes::Bytes {
- fn from_body(body: Option<Vec<u8>>) -> Self {
- Into::into(body.unwrap_or_default())
+ fn from_body(body: Vec<u8>) -> Self {
+ Into::into(body)
}
}
@@ -322,7 +417,7 @@ pub trait TryIntoBody {
/// The type of error if the conversion fails
type Error;
/// Turn `self` into an Error
- fn try_into_body(self) -> Result<Option<Vec<u8>>, Self::Error>;
+ fn try_into_body(self) -> Result<Vec<u8>, Self::Error>;
}
impl<B> TryIntoBody for B
@@ -331,13 +426,13 @@ where
{
type Error = std::convert::Infallible;
- fn try_into_body(self) -> Result<Option<Vec<u8>>, Self::Error> {
+ fn try_into_body(self) -> Result<Vec<u8>, Self::Error> {
Ok(self.into_body())
}
}
#[cfg(feature = "http")]
-impl<B> TryFrom<hyperium::Request<B>> for Request
+impl<B> TryFrom<hyperium::Request<B>> for OutgoingRequest
where
B: TryIntoBody,
B::Error: std::error::Error + Send + Sync + 'static,
@@ -357,31 +452,54 @@ where
let headers = req
.headers()
.into_iter()
- .map(|(n, v)| {
- (
- n.as_str().to_owned(),
- String::from_utf8_lossy(v.as_bytes()).into_owned(),
- )
- })
- .collect();
- Ok(Request {
- method,
- uri: req.uri().to_string(),
- headers,
- params: Vec::new(),
- body: B::try_into_body(req.into_body())?,
- })
+ .map(|(n, v)| (n.as_str().to_owned(), v.as_bytes().to_owned()))
+ .collect::<Vec<_>>();
+ Ok(OutgoingRequest::new(
+ &method,
+ req.uri().path_and_query().map(|p| p.as_str()),
+ req.uri()
+ .scheme()
+ .map(|s| match s.as_str() {
+ "http" => super::Scheme::Http,
+ "https" => super::Scheme::Https,
+ s => super::Scheme::Other(s.to_owned()),
+ })
+ .as_ref(),
+ req.uri().authority().map(|a| a.as_str()),
+ &Fields::new(&headers),
+ ))
+ }
+}
+
+#[async_trait]
+/// TODO
+pub trait TryFromIncomingResponse {
+ /// TODO
+ type Error;
+ /// TODO
+ async fn try_from_incoming_response(resp: IncomingResponse) -> Result<Self, Self::Error>
+ where
+ Self: Sized;
+}
+
+#[async_trait]
+impl TryFromIncomingResponse for IncomingResponse {
+ type Error = std::convert::Infallible;
+ async fn try_from_incoming_response(resp: IncomingResponse) -> Result<Self, Self::Error> {
+ Ok(resp)
}
}
#[cfg(feature = "http")]
-impl<B: TryFromBody> TryFrom<Response> for hyperium::Response<B> {
+#[async_trait]
+impl<B: TryFromBody> TryFromIncomingResponse for hyperium::Response<B> {
type Error = B::Error;
- fn try_from(resp: Response) -> Result<Self, Self::Error> {
- let mut builder = hyperium::Response::builder().status(resp.status);
- for (n, v) in resp.headers.unwrap_or_default() {
+ async fn try_from_incoming_response(resp: IncomingResponse) -> Result<Self, Self::Error> {
+ let mut builder = hyperium::Response::builder().status(resp.status());
+ for (n, v) in resp.headers().entries() {
builder = builder.header(n, v);
}
- Ok(builder.body(B::try_from_body(resp.body)?).unwrap())
+ let body = resp.into_body().await.expect("TODO");
+ Ok(builder.body(B::try_from_body(body)?).unwrap())
}
}
diff --git a/sdk/rust/src/wasi_http/executor.rs b/sdk/rust/src/http/executor.rs
similarity index 98%
rename from sdk/rust/src/wasi_http/executor.rs
rename to sdk/rust/src/http/executor.rs
index 0dcefa5c10..720c81b07a 100644
--- a/sdk/rust/src/wasi_http/executor.rs
+++ b/sdk/rust/src/http/executor.rs
@@ -188,9 +188,9 @@ pub fn incoming_body(body: IncomingBody) -> impl Stream<Item = Result<Vec<u8>>>
}
}
Err(StreamError::Closed) => Poll::Ready(None),
- Err(StreamError::LastOperationFailed(error)) => {
- Poll::Ready(Some(Err(anyhow!("{}", error.to_debug_string()))))
- }
+ Err(StreamError::LastOperationFailed(error)) => Poll::Ready(Some(Err(
+ anyhow!("Last operation failed: {}", error.to_debug_string()),
+ ))),
}
} else {
Poll::Ready(None)
diff --git a/sdk/rust/src/http/router.rs b/sdk/rust/src/http/router.rs
index cd5075090a..33024c65e4 100644
--- a/sdk/rust/src/http/router.rs
+++ b/sdk/rust/src/http/router.rs
@@ -41,8 +41,8 @@ impl Router {
/// Dispatches a request to the appropriate handler along with the URI parameters.
pub fn handle<R: Into<Request>>(&self, request: R) -> Response {
let request = request.into();
- let method = request.method;
- let path = &request.uri;
+ let method = request.method.clone();
+ let path = &request.path_and_query;
let RouteMatch { params, handler } = self.find(path, method);
handler(request, params)
}
@@ -247,9 +247,9 @@ fn method_not_allowed(_req: Request, _params: Params) -> Response {
macro_rules! http_router {
($($method:tt $path:literal => $h:expr),*) => {
{
- let mut router = spin_sdk::http::Router::new();
+ let mut router = $crate::http::Router::new();
$(
- spin_sdk::http_router!(@build router $method $path => $h);
+ $crate::http_router!(@build router $method $path => $h);
)*
router
}
@@ -287,10 +287,9 @@ mod tests {
fn make_request(method: Method, path: &str) -> Request {
Request {
method,
- uri: path.into(),
+ path_and_query: path.into(),
headers: Vec::new(),
- params: Vec::new(),
- body: None,
+ body: Default::default(),
}
}
@@ -339,7 +338,7 @@ mod tests {
let req = make_request(Method::Get, "/multiply/2/4");
let res = router.handle(req);
- assert_eq!(res.body.unwrap(), "8".to_owned().into_bytes());
+ assert_eq!(res.body, "8".to_owned().into_bytes());
}
#[test]
@@ -350,7 +349,7 @@ mod tests {
let req = make_request(Method::Get, "/y");
let res = router.handle(req);
- assert_eq!(res.body.unwrap(), "y".to_owned().into_bytes());
+ assert_eq!(res.body, "y".to_owned().into_bytes());
}
#[test]
@@ -368,7 +367,7 @@ mod tests {
let req = make_request(Method::Get, "/foo/bar");
let res = router.handle(req);
assert_eq!(res.status, hyperium::StatusCode::OK);
- assert_eq!(res.body.unwrap(), "foo/bar".to_owned().into_bytes());
+ assert_eq!(res.body, "foo/bar".to_owned().into_bytes());
}
#[test]
@@ -378,7 +377,7 @@ mod tests {
let req = make_request(Method::Get, "/foo/bar");
let res = router.handle(req);
- assert_eq!(res.body.unwrap(), "foo".to_owned().into_bytes());
+ assert_eq!(res.body, "foo".to_owned().into_bytes());
}
#[test]
@@ -409,6 +408,6 @@ mod tests {
let req = make_request(Method::Get, "/posts/2");
let res = router.handle(req);
- assert_eq!(res.body.unwrap(), "posts/*".to_owned().into_bytes());
+ assert_eq!(res.body, "posts/*".to_owned().into_bytes());
}
}
diff --git a/sdk/rust/src/lib.rs b/sdk/rust/src/lib.rs
index c3d9edbf59..580e56111a 100644
--- a/sdk/rust/src/lib.rs
+++ b/sdk/rust/src/lib.rs
@@ -46,11 +46,8 @@ extern "C" fn __spin_sdk_language() {}
#[export_name = concat!("spin-sdk-commit-", env!("SDK_COMMIT"))]
extern "C" fn __spin_sdk_hash() {}
-/// Helpers for building Spin HTTP components.
-pub mod http;
-
/// Helpers for building Spin `wasi-http` components.
-pub mod wasi_http;
+pub mod http;
/// Implementation of the spin redis interface.
#[allow(missing_docs)]
diff --git a/sdk/rust/src/wasi_http.rs b/sdk/rust/src/wasi_http.rs
deleted file mode 100644
index 9ad770eaa5..0000000000
--- a/sdk/rust/src/wasi_http.rs
+++ /dev/null
@@ -1,105 +0,0 @@
-/// Traits for converting between the various types
-pub mod conversions;
-
-#[doc(inline)]
-pub use super::wit::wasi::http::types::*;
-
-impl IncomingRequest {
- /// Return a `Stream` from which the body of the specified request may be read.
- ///
- /// # Panics
- ///
- /// Panics if the body was already consumed.
- pub fn into_body_stream(self) -> impl futures::Stream<Item = anyhow::Result<Vec<u8>>> {
- executor::incoming_body(self.consume().expect("request body was already consumed"))
- }
-
- /// Return a `Vec<u8>` of the body or fails
- pub async fn into_body(self) -> anyhow::Result<Vec<u8>> {
- use futures::TryStreamExt;
- let mut stream = self.into_body_stream();
- let mut body = Vec::new();
- while let Some(chunk) = stream.try_next().await? {
- body.extend(chunk);
- }
- Ok(body)
- }
-}
-
-impl IncomingResponse {
- /// Return a `Stream` from which the body of the specified response may be read.
- ///
- /// # Panics
- ///
- /// Panics if the body was already consumed.
- pub fn into_body_stream(self) -> impl futures::Stream<Item = anyhow::Result<Vec<u8>>> {
- executor::incoming_body(self.consume().expect("response body was already consumed"))
- }
-}
-
-impl OutgoingResponse {
- /// Construct a `Sink` which writes chunks to the body of the specified response.
- ///
- /// # Panics
- ///
- /// Panics if the body was already taken.
- pub fn take_body(&self) -> impl futures::Sink<Vec<u8>, Error = anyhow::Error> {
- executor::outgoing_body(self.write().expect("response body was already taken"))
- }
-}
-
-impl ResponseOutparam {
- /// Set with the outgoing response and the supplied buffer
- ///
- /// Will panic if response body has already been taken
- pub async fn set_with_body(
- self,
- response: OutgoingResponse,
- buffer: Vec<u8>,
- ) -> anyhow::Result<()> {
- use futures::SinkExt;
- let mut body = response.take_body();
- ResponseOutparam::set(self, Ok(response));
- body.send(buffer).await
- }
-}
-
-/// Send an outgoing request
-pub async fn send<I, O>(request: I) -> Result<O, SendError>
-where
- I: TryInto<OutgoingRequest>,
- I::Error: Into<Box<dyn std::error::Error + Send + Sync>> + 'static,
- O: TryFrom<IncomingResponse>,
- O::Error: Into<Box<dyn std::error::Error + Send + Sync>> + 'static,
-{
- let response = executor::outgoing_request_send(
- request
- .try_into()
- .map_err(|e| SendError::RequestConversion(e.into()))?,
- )
- .await
- .map_err(SendError::Http)?;
- response
- .try_into()
- .map_err(|e: O::Error| SendError::ResponseConversion(e.into()))
-}
-
-/// An error encountered when performing an HTTP request
-#[derive(thiserror::Error, Debug)]
-pub enum SendError {
- /// Error converting to a request
- #[error(transparent)]
- RequestConversion(Box<dyn std::error::Error + Send + Sync>),
- /// Error converting from a response
- #[error(transparent)]
- ResponseConversion(Box<dyn std::error::Error + Send + Sync>),
- /// An HTTP error
- #[error(transparent)]
- Http(Error),
-}
-
-#[doc(hidden)]
-/// The executor for driving wasi-http futures to completion
-mod executor;
-#[doc(hidden)]
-pub use executor::run;
diff --git a/sdk/rust/src/wasi_http/conversions.rs b/sdk/rust/src/wasi_http/conversions.rs
deleted file mode 100644
index c83dfa982d..0000000000
--- a/sdk/rust/src/wasi_http/conversions.rs
+++ /dev/null
@@ -1,139 +0,0 @@
-use async_trait::async_trait;
-
-use super::{Headers, IncomingRequest, Method, OutgoingResponse};
-use crate::http::conversions as http_conversions;
-
-impl From<crate::http::Response> for OutgoingResponse {
- fn from(response: crate::http::Response) -> Self {
- let headers = response
- .headers
- .unwrap_or_default()
- .into_iter()
- .map(|(k, v)| (k, v.into_bytes()))
- .collect::<Vec<_>>();
- OutgoingResponse::new(response.status, &Headers::new(&headers))
- }
-}
-
-/// A trait for trying to convert from an `IncomingRequest` to the implementing type
-#[async_trait]
-pub trait TryFromIncomingRequest {
- /// The error if conversion fails
- type Error;
-
- /// Try to turn the `IncomingRequest` into the implementing type
- async fn try_from_incoming_request(value: IncomingRequest) -> Result<Self, Self::Error>
- where
- Self: Sized;
-}
-
-#[async_trait]
-impl TryFromIncomingRequest for IncomingRequest {
- type Error = std::convert::Infallible;
- async fn try_from_incoming_request(request: IncomingRequest) -> Result<Self, Self::Error> {
- Ok(request)
- }
-}
-
-#[async_trait]
-impl<R> TryFromIncomingRequest for R
-where
- R: crate::http::conversions::TryNonRequestFromRequest,
-{
- type Error = IncomingRequestError<R::Error>;
-
- async fn try_from_incoming_request(request: IncomingRequest) -> Result<Self, Self::Error> {
- let req = crate::http::Request::try_from_incoming_request(request)
- .await
- .map_err(convert_error)?;
- R::try_from_request(req).map_err(IncomingRequestError::ConversionError)
- }
-}
-
-#[async_trait]
-impl TryFromIncomingRequest for crate::http::Request {
- type Error = IncomingRequestError;
-
- async fn try_from_incoming_request(request: IncomingRequest) -> Result<Self, Self::Error> {
- let headers = request
- .headers()
- .entries()
- .iter()
- .map(|(k, v)| (k.clone(), String::from_utf8_lossy(v).into_owned()))
- .collect();
- Ok(Self {
- method: request
- .method()
- .try_into()
- .map_err(|_| IncomingRequestError::UnexpectedMethod(request.method()))?,
- uri: request
- .path_with_query()
- .unwrap_or_else(|| String::from("/")),
- headers,
- params: Vec::new(),
- body: Some(
- request
- .into_body()
- .await
- .map_err(IncomingRequestError::BodyConversionError)?,
- ),
- })
- }
-}
-
-#[derive(Debug, thiserror::Error)]
-/// An error converting an `IncomingRequest`
-pub enum IncomingRequestError<E = std::convert::Infallible> {
- /// The `IncomingRequest` has a method not supported by `Request`
- #[error("unexpected method: {0:?}")]
- UnexpectedMethod(Method),
- /// There was an error converting the body to an `Option<Vec<u8>>k`
- #[error(transparent)]
- BodyConversionError(anyhow::Error),
- /// There was an error converting the `Request` into the requested type
- #[error(transparent)]
- ConversionError(E),
-}
-
-/// Helper for converting `IncomingRequestError`s that cannot fail due to conversion errors
-/// into ones that can.
-fn convert_error<E>(
- error: IncomingRequestError<std::convert::Infallible>,
-) -> IncomingRequestError<E> {
- match error {
- IncomingRequestError::UnexpectedMethod(e) => IncomingRequestError::UnexpectedMethod(e),
- IncomingRequestError::BodyConversionError(e) => {
- IncomingRequestError::BodyConversionError(e)
- }
- IncomingRequestError::ConversionError(_) => unreachable!(),
- }
-}
-
-impl<E: http_conversions::IntoResponse> http_conversions::IntoResponse for IncomingRequestError<E> {
- fn into_response(self) -> crate::http::Response {
- match self {
- IncomingRequestError::UnexpectedMethod(_) => {
- crate::http::responses::method_not_allowed()
- }
- IncomingRequestError::BodyConversionError(e) => e.into_response(),
- IncomingRequestError::ConversionError(e) => e.into_response(),
- }
- }
-}
-
-impl TryFrom<Method> for crate::http::Method {
- type Error = ();
- fn try_from(method: Method) -> Result<Self, Self::Error> {
- let method = match method {
- Method::Get => Self::Get,
- Method::Head => Self::Head,
- Method::Post => Self::Post,
- Method::Put => Self::Put,
- Method::Patch => Self::Patch,
- Method::Delete => Self::Delete,
- Method::Options => Self::Options,
- _ => return Err(()),
- };
- Ok(method)
- }
-}
diff --git a/wit/preview2/deps/http/types.wit b/wit/preview2/deps/http/types.wit
index 3ba1a71290..33a4cfde53 100644
--- a/wit/preview2/deps/http/types.wit
+++ b/wit/preview2/deps/http/types.wit
@@ -1,11 +1,9 @@
-package wasi:http
-
/// The `wasi:http/types` interface is meant to be imported by components to
/// define the HTTP resource types and operations used by the component's
/// imported and exported interfaces.
interface types {
- use wasi:io/streams.{input-stream, output-stream}
- use wasi:io/poll.{pollable}
+ use wasi:io/streams@0.2.0-rc-2023-10-18.{input-stream, output-stream}
+ use wasi:io/poll@0.2.0-rc-2023-10-18.{pollable}
/// This type corresponds to HTTP standard Methods.
variant method {
diff --git a/wit/preview2/deps/http/world.wit b/wit/preview2/deps/http/world.wit
new file mode 100644
index 0000000000..0798c84292
--- /dev/null
+++ b/wit/preview2/deps/http/world.wit
@@ -0,0 +1,1 @@
+package wasi:http@0.2.0-rc-2023-10-18
diff --git a/wit/preview2/deps/io/poll.wit b/wit/preview2/deps/io/poll.wit
index e95762b915..4ff4765c99 100644
--- a/wit/preview2/deps/io/poll.wit
+++ b/wit/preview2/deps/io/poll.wit
@@ -1,5 +1,3 @@
-package wasi:io
-
/// A poll API intended to let users wait for I/O events on multiple handles
/// at once.
interface poll {
diff --git a/wit/preview2/deps/io/streams.wit b/wit/preview2/deps/io/streams.wit
index 55562d1cbf..d5c7835e4e 100644
--- a/wit/preview2/deps/io/streams.wit
+++ b/wit/preview2/deps/io/streams.wit
@@ -1,5 +1,3 @@
-package wasi:io
-
/// WASI I/O is an I/O abstraction API which is currently focused on providing
/// stream types.
///
diff --git a/wit/preview2/deps/io/world.wit b/wit/preview2/deps/io/world.wit
index 8738dba756..0fdcfcd969 100644
--- a/wit/preview2/deps/io/world.wit
+++ b/wit/preview2/deps/io/world.wit
@@ -1,6 +1,1 @@
-package wasi:io
-
-world imports {
- import streams
- import poll
-}
+package wasi:io@0.2.0-rc-2023-10-18
diff --git a/wit/preview2/deps/spin@1.0.0/world.wit b/wit/preview2/deps/spin@1.0.0/world.wit
index 53bb08a522..46ed53a68c 100644
--- a/wit/preview2/deps/spin@1.0.0/world.wit
+++ b/wit/preview2/deps/spin@1.0.0/world.wit
@@ -19,8 +19,8 @@ world http-trigger {
world wasi-http-trigger {
include platform
- import wasi:http/outgoing-handler
- export wasi:http/incoming-handler
+ import wasi:http/outgoing-handler@0.2.0-rc-2023-10-18
+ export wasi:http/incoming-handler@0.2.0-rc-2023-10-18
}
world platform {
diff --git a/wit/preview2/world.wit b/wit/preview2/world.wit
index 7c2259b33a..bc596eacdf 100644
--- a/wit/preview2/world.wit
+++ b/wit/preview2/world.wit
@@ -17,9 +17,8 @@ world http-trigger {
world platform {
import fermyon:spin/config
- import fermyon:spin/http
import fermyon:spin/llm
- import wasi:http/outgoing-handler
+ import wasi:http/outgoing-handler@0.2.0-rc-2023-10-18
import redis
import postgres
| 1,901
|
[
"1871"
] |
diff --git a/crates/core/tests/integration_test.rs b/crates/core/tests/integration_test.rs
index abc32f8d35..a5a0994880 100644
--- a/crates/core/tests/integration_test.rs
+++ b/crates/core/tests/integration_test.rs
@@ -178,6 +178,9 @@ fn test_config() -> Config {
fn test_engine() -> Engine<()> {
let mut builder = Engine::builder(&test_config()).unwrap();
builder.add_host_component(MultiplierHostComponent).unwrap();
+ builder
+ .link_import(|l, _| wasmtime_wasi::preview2::command::add_to_linker(l))
+ .unwrap();
builder.build()
}
@@ -212,8 +215,8 @@ async fn run_core_wasi_test_engine<'a>(
let mut exports = instance.exports(&mut store);
let mut instance = exports
- .instance("wasi:cli/run")
- .context("missing the expected 'wasi:cli/run' instance")?;
+ .instance("wasi:cli/run@0.2.0-rc-2023-10-18")
+ .context("missing the expected 'wasi:cli/run@0.2.0-rc-2023-10-18' instance")?;
instance.typed_func::<(), (Result<(), ()>,)>("run")?
};
update_store(&mut store);
diff --git a/crates/loader/tests/triggers/http.toml b/crates/loader/tests/triggers/http.toml
index 66133d5ff2..d8b09d8274 100644
--- a/crates/loader/tests/triggers/http.toml
+++ b/crates/loader/tests/triggers/http.toml
@@ -2,7 +2,7 @@ spin_version = "1"
authors = ["Fermyon Engineering <engineering@fermyon.com>"]
description = "A dummy manifest for testing parsing."
name = "spin-hello-world"
-trigger = {type = "http", base = "/test"}
+trigger = { type = "http", base = "/test" }
version = "1.0.0"
[variables]
@@ -13,6 +13,7 @@ id = "http-spin"
source = "dummy.wasm.txt"
[component.trigger]
route = "/hello/..."
+executor = { type = "wagi" }
[component.config]
message = "I'm a {{object}}"
@@ -21,6 +22,6 @@ id = "http-wagi"
source = "dummy.wasm.txt"
[component.trigger]
route = "/waggy/..."
-executor = { type = "wagi" }
+executor = { type = "wagi" }
[component.config]
message = "I'm a {{object}}"
diff --git a/crates/loader/tests/ui/valid-manifest.lock b/crates/loader/tests/ui/valid-manifest.lock
index 55da64bc90..9cdd631121 100644
--- a/crates/loader/tests/ui/valid-manifest.lock
+++ b/crates/loader/tests/ui/valid-manifest.lock
@@ -24,7 +24,7 @@
"trigger_config": {
"component": "four-lights",
"executor": {
- "type": "spin"
+ "type": "http"
},
"route": "/lights"
}
diff --git a/crates/loader/tests/ui/valid-manifest.toml b/crates/loader/tests/ui/valid-manifest.toml
index 816da19833..6d2b8b9a30 100644
--- a/crates/loader/tests/ui/valid-manifest.toml
+++ b/crates/loader/tests/ui/valid-manifest.toml
@@ -2,14 +2,14 @@ spin_version = "1"
authors = ["Gul Madred", "Edward Jellico", "JL"]
description = "A simple application that returns the number of lights"
name = "chain-of-command"
-trigger = {type = "http"}
+trigger = { type = "http" }
version = "6.11.2"
[[component]]
id = "four-lights"
source = "wasm/dummy.wasm"
[component.trigger]
-executor = {type = "spin"}
+executor = { type = "http" }
route = "/lights"
[component.environment]
env1 = "first"
diff --git a/crates/loader/tests/ui/valid-with-files/spin.lock b/crates/loader/tests/ui/valid-with-files/spin.lock
index 1bdfafff9f..f7e4457d9b 100644
--- a/crates/loader/tests/ui/valid-with-files/spin.lock
+++ b/crates/loader/tests/ui/valid-with-files/spin.lock
@@ -21,7 +21,7 @@
"trigger_config": {
"component": "fs",
"executor": {
- "type": "spin"
+ "type": "http"
},
"route": "/..."
}
diff --git a/crates/loader/tests/ui/valid-with-files/spin.toml b/crates/loader/tests/ui/valid-with-files/spin.toml
index e5368fce48..64ebe127be 100644
--- a/crates/loader/tests/ui/valid-with-files/spin.toml
+++ b/crates/loader/tests/ui/valid-with-files/spin.toml
@@ -1,7 +1,7 @@
spin_version = "1"
authors = ["Fermyon Engineering <engineering@fermyon.com>"]
name = "spin-local-source-test"
-trigger = {type = "http"}
+trigger = { type = "http" }
version = "1.0.0"
[[component]]
@@ -10,5 +10,5 @@ id = "fs"
source = "spin-fs.wasm"
[component.trigger]
-executor = {type = "spin"}
+executor = { type = "http" }
route = "/..."
diff --git a/tests/http/simple-spin-rust/Cargo.lock b/tests/http/simple-spin-rust/Cargo.lock
index 78dbd27362..df52e94277 100644
--- a/tests/http/simple-spin-rust/Cargo.lock
+++ b/tests/http/simple-spin-rust/Cargo.lock
@@ -314,7 +314,6 @@ name = "simple-spin-rust"
version = "0.1.0"
dependencies = [
"anyhow",
- "bytes",
"http",
"spin-sdk",
]
diff --git a/tests/http/simple-spin-rust/Cargo.toml b/tests/http/simple-spin-rust/Cargo.toml
index 7c70eab7e0..923c6d210c 100644
--- a/tests/http/simple-spin-rust/Cargo.toml
+++ b/tests/http/simple-spin-rust/Cargo.toml
@@ -1,19 +1,15 @@
[package]
-name = "simple-spin-rust"
+name = "simple-spin-rust"
version = "0.1.0"
edition = "2021"
[lib]
-crate-type = [ "cdylib" ]
+crate-type = ["cdylib"]
[dependencies]
-# Useful crate to handle errors.
anyhow = "1"
-# Crate to simplify working with bytes.
-bytes = "1"
-# General-purpose crate with common HTTP types.
http = "0.2"
-spin-sdk = { path = "../../../sdk/rust"}
+spin-sdk = { path = "../../../sdk/rust" }
[workspace]
diff --git a/tests/http/simple-spin-rust/spin.toml b/tests/http/simple-spin-rust/spin.toml
index 160e7fd29f..6fd14fe29d 100644
--- a/tests/http/simple-spin-rust/spin.toml
+++ b/tests/http/simple-spin-rust/spin.toml
@@ -2,7 +2,7 @@ spin_version = "1"
authors = ["Fermyon Engineering <engineering@fermyon.com>"]
description = "A simple application that returns hello and goodbye."
name = "spin-hello-world"
-trigger = {type = "http", base = "/test"}
+trigger = { type = "http", base = "/test" }
version = "1.0.0"
[variables]
@@ -11,7 +11,7 @@ object = { default = "teapot" }
[[component]]
id = "hello"
source = "target/wasm32-wasi/release/simple_spin_rust.wasm"
-files = [ { source = "assets", destination = "/" } ]
+files = [{ source = "assets", destination = "/" }]
[component.trigger]
route = "/hello/..."
[component.config]
diff --git a/tests/testcases/assets-test/spin.toml b/tests/testcases/assets-test/spin.toml
index e54fa76b15..774146222d 100644
--- a/tests/testcases/assets-test/spin.toml
+++ b/tests/testcases/assets-test/spin.toml
@@ -1,14 +1,16 @@
spin_version = "1"
authors = ["Fermyon Engineering <engineering@fermyon.com>"]
name = "assets-test"
-trigger = {type = "http"}
+trigger = { type = "http" }
version = "1.0.0"
[[component]]
id = "fs"
source = { url = "https://github.com/fermyon/spin-fileserver/releases/download/v0.1.0/spin_static_fs.wasm", digest = "sha256:96c76d9af86420b39eb6cd7be5550e3cb5d4cc4de572ce0fd1f6a29471536cb4" }
-files = [{source = "static/thisshouldbemounted", destination = "/thisshouldbemounted"}]
+files = [
+ { source = "static/thisshouldbemounted", destination = "/thisshouldbemounted" },
+]
exclude_files = ["static/thisshouldbemounted/thisshouldbeexcluded/*"]
[component.trigger]
-executor = {type = "spin"}
+executor = { type = "http" }
route = "/static/..."
diff --git a/tests/testcases/mod.rs b/tests/testcases/mod.rs
index 0394d3fe6c..a5fe6bff6b 100644
--- a/tests/testcases/mod.rs
+++ b/tests/testcases/mod.rs
@@ -36,7 +36,7 @@ pub async fn component_outbound_http_works(controller: &dyn Controller) {
"",
500,
&[],
- Some("destination-not-allowed (error 1)"),
+ None,
)
.await?;
diff --git a/tests/testcases/outbound-http-to-same-app/outbound-http-component/src/lib.rs b/tests/testcases/outbound-http-to-same-app/outbound-http-component/src/lib.rs
index 5acd429cbb..788e34fa23 100644
--- a/tests/testcases/outbound-http-to-same-app/outbound-http-component/src/lib.rs
+++ b/tests/testcases/outbound-http-to-same-app/outbound-http-component/src/lib.rs
@@ -6,13 +6,14 @@ use spin_sdk::{
/// Send an HTTP request and return the response.
#[http_component]
-fn send_outbound(_req: Request) -> Result<impl IntoResponse> {
+async fn send_outbound(_req: Request) -> Result<impl IntoResponse> {
let mut res: http::Response<String> = spin_sdk::http::send(
http::Request::builder()
.method("GET")
.uri("/test/hello")
.body(())?,
- )?;
+ )
+ .await?;
res.headers_mut()
.insert("spin-component", "outbound-http-component".try_into()?);
println!("{:?}", res);
|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
503917f58269d500d0efe201a8ecb7df6427ddc3
|
Improve Rust SDK HTTP handler macro with an `IntoResponse` trait
Right now the http handler in the Rust SDK assumes that the annotated function will return `Result<T, E> where T: TryInto<spin_http::Response>` and where `E` has the same API as `std::error::Error` (which one should note `anyhow::Error` does not implement but has a similar enough API that things just work). This can make error handling in spin http less than ideal. If the user wants to return a non-500 error they need to construct a response using something like `http::ResponseBuilder` which has an awkward API.
## Proposal
Instead, we could take some inspiration from other HTTP frameworks and make the response handling a bit more fluid. My proposal would be that we could require that the handler return anything that implements an `IntoResponse` trait that ultimately gets used to turn the user's return value into a response.
Ultimately, this could end up with something that looks like this:
```rust
fn handler(req: Request) -> anyhow::Result<impl IntoResponse> {
let query = req.uri().query();
let Some(query) = query else { return Ok((StatusCode::BAD_REQUEST, "no query string")) };
let Ok(query) = serde_qs::from_str::<Query>(query) else {
return Ok((StatusCode::BAD_REQUEST, "could not parse query string"));
};
let store = key_value::Store::open_default()?;
let mut filter = get_state(&store)?;
let status = match filter.exists(&query.email) {
Exists::Maybe if expensive_user_lookup(&query.email)? => 409,
Exists::No | Exists::Maybe => 200,
};
Ok((StatusCode::from_u16(status).unwrap(), ""))
}
```
`IntoResponse` could be extended for any types that look like a response.
## Issues
The only issue is that making this work in a backwards compatible way will be difficult. This is largely because the macro currently assumes a `Result` type where the error is anything that kind of looks like a `std::error::Error`. Importantly it does not require that that error type actually *implement* `std::error::Error` (e.g., just as `anyhow::Error` does not).
Due to limitations in the Rust type system, it's basically impossible to do the following:
```rust
impl IntoError for anyhow::Error {
// ...
}
impl <E: std::error::Error> IntoError for E {
// ...
}
```
This does not work because the Rust is conservatively allowing future versions of `anyhow` to implement `std::error::Error` for `anyhow::Error`.
## Next steps
So with that in mind, the next questions are:
* Is such an API change worth it?
* If so, can anyone think of a clever way to make this a backwards compatible change?
* If not, how do we introduce a second macro in a way that makes sense?
|
This is a great idea. I definitely think this API change is worth it because it significantly improves the ergonomics of the Rust SDK, however, i'm not quite sure either how to support this in a backwards compatible way. It might be worth exploring the third bullet of a second macro; if we do that i'd like us to explore what other improvements we could make as well (if any).
|
2023-10-12T14:08:48Z
|
fermyon__spin-1887
|
fermyon/spin
|
3.2
|
diff --git a/Cargo.lock b/Cargo.lock
index 90eabbae4f..defa627a52 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -390,9 +390,9 @@ checksum = "b9441c6b2fe128a7c2bf680a44c34d0df31ce09e5b7e401fcca3faa483dbc921"
[[package]]
name = "async-trait"
-version = "0.1.73"
+version = "0.1.74"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bc00ceb34980c03614e35a3a4e218276a0a824e911d07651cd0d858a51e8c0f0"
+checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
dependencies = [
"proc-macro2",
"quote",
@@ -2001,9 +2001,9 @@ checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"
[[package]]
name = "form_urlencoded"
-version = "1.1.0"
+version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a9c384f161156f5260c24a097c56119f9be8c798586aecc13afbcbe7b7e26bf8"
+checksum = "a62bc1cf6f830c2ec14a513a9fb124d0a213a629668a4186f329db21fe045652"
dependencies = [
"percent-encoding",
]
@@ -2793,9 +2793,9 @@ checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
[[package]]
name = "idna"
-version = "0.3.0"
+version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e14ddfc70884202db2244c223200c204c2bda1bc6e0998d11b5e024d657209e6"
+checksum = "7d20d6b07bfbc108882d88ed8e37d39636dcc260e15e30c45e6ba089610b917c"
dependencies = [
"unicode-bidi",
"unicode-normalization",
@@ -4304,9 +4304,9 @@ dependencies = [
[[package]]
name = "percent-encoding"
-version = "2.2.0"
+version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "478c572c3d73181ff3c2539045f6eb99e5491218eae919370993b890cdbdd98e"
+checksum = "9b2a4787296e9989611394c33f193f676704af1686e70b8f8033ab5ba9a35a94"
[[package]]
name = "pest"
@@ -6014,6 +6014,7 @@ name = "spin-sdk"
version = "2.0.0-pre0"
dependencies = [
"anyhow",
+ "async-trait",
"bytes",
"form_urlencoded",
"futures",
@@ -6980,9 +6981,9 @@ checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a"
[[package]]
name = "url"
-version = "2.3.1"
+version = "2.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0d68c799ae75762b8c3fe375feb6600ef5602c883c5d21eb51c09f22b83c4643"
+checksum = "143b538f18257fac9cad154828a57c6bf5157e1aa604d4816b5995bf6de87ae5"
dependencies = [
"form_urlencoded",
"idna",
diff --git a/build.rs b/build.rs
index 40bd8ad5ab..9a146f52e1 100644
--- a/build.rs
+++ b/build.rs
@@ -12,7 +12,7 @@ const RUST_HTTP_INTEGRATION_ENV_TEST: &str = "tests/http/headers-env-routes-test
const RUST_HTTP_VAULT_CONFIG_TEST: &str = "tests/http/vault-config-test";
const RUST_OUTBOUND_REDIS_INTEGRATION_TEST: &str = "tests/outbound-redis/http-rust-outbound-redis";
const TIMER_TRIGGER_INTEGRATION_TEST: &str = "examples/spin-timer/app-example";
-const WASI_HTTP_INTEGRATION_TEST: &str = "examples/wasi-http-rust-async";
+const WASI_HTTP_INTEGRATION_TEST: &str = "examples/wasi-http-rust-streaming-outgoing-body";
fn main() {
// Extract environment information to be passed to plugins.
diff --git a/examples/config-rust/Cargo.lock b/examples/config-rust/Cargo.lock
index f9d42fbb67..fd7a0d7a51 100644
--- a/examples/config-rust/Cargo.lock
+++ b/examples/config-rust/Cargo.lock
@@ -8,6 +8,17 @@ version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
+[[package]]
+name = "async-trait"
+version = "0.1.74"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.38",
+]
+
[[package]]
name = "autocfg"
version = "1.1.0"
@@ -347,8 +358,6 @@ name = "spin-config-example"
version = "0.1.0"
dependencies = [
"anyhow",
- "bytes",
- "http",
"spin-sdk",
]
@@ -369,12 +378,15 @@ name = "spin-sdk"
version = "2.0.0-pre0"
dependencies = [
"anyhow",
+ "async-trait",
"bytes",
"form_urlencoded",
"futures",
"http",
"once_cell",
"routefinder",
+ "serde",
+ "serde_json",
"spin-macro",
"thiserror",
"wit-bindgen",
diff --git a/examples/config-rust/Cargo.toml b/examples/config-rust/Cargo.toml
index 107aa9bf67..243922eb39 100644
--- a/examples/config-rust/Cargo.toml
+++ b/examples/config-rust/Cargo.toml
@@ -4,15 +4,11 @@ version = "0.1.0"
edition = "2021"
[lib]
-crate-type = [ "cdylib" ]
+crate-type = ["cdylib"]
[dependencies]
# Useful crate to handle errors.
anyhow = "1"
-# Crate to simplify working with bytes.
-bytes = "1"
-# General-purpose crate with common HTTP types.
-http = "0.2"
# The Spin SDK.
spin-sdk = { path = "../../sdk/rust" }
-[workspace]
\ No newline at end of file
+[workspace]
diff --git a/examples/config-rust/src/lib.rs b/examples/config-rust/src/lib.rs
index fb39b7f5b8..977b53deca 100644
--- a/examples/config-rust/src/lib.rs
+++ b/examples/config-rust/src/lib.rs
@@ -1,4 +1,3 @@
-use anyhow::Result;
use spin_sdk::{
config,
http::{Request, Response},
@@ -7,17 +6,11 @@ use spin_sdk::{
/// This endpoint returns the config value specified by key.
#[http_component]
-fn get(req: Request) -> Result<Response> {
- let path = req.uri().path();
-
- if path.contains("dotenv") {
+fn get(req: Request) -> anyhow::Result<Response> {
+ if req.uri.contains("dotenv") {
let val = config::get("dotenv").expect("Failed to acquire dotenv from spin.toml");
- return Ok(http::Response::builder()
- .status(200)
- .body(Some(val.into()))?);
+ return Ok(Response::new(200, val));
}
let val = format!("message: {}", config::get("message")?);
- Ok(http::Response::builder()
- .status(200)
- .body(Some(val.into()))?)
+ Ok(Response::new(200, val))
}
diff --git a/examples/http-rust-outbound-http/http-hello/Cargo.lock b/examples/http-rust-outbound-http/http-hello/Cargo.lock
index a9785d304f..dec3e21642 100644
--- a/examples/http-rust-outbound-http/http-hello/Cargo.lock
+++ b/examples/http-rust-outbound-http/http-hello/Cargo.lock
@@ -8,6 +8,17 @@ version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
+[[package]]
+name = "async-trait"
+version = "0.1.74"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.38",
+]
+
[[package]]
name = "autocfg"
version = "1.1.0"
@@ -167,7 +178,6 @@ name = "http-hello"
version = "0.1.0"
dependencies = [
"anyhow",
- "bytes",
"http",
"spin-sdk",
]
@@ -369,12 +379,15 @@ name = "spin-sdk"
version = "2.0.0-pre0"
dependencies = [
"anyhow",
+ "async-trait",
"bytes",
"form_urlencoded",
"futures",
"http",
"once_cell",
"routefinder",
+ "serde",
+ "serde_json",
"spin-macro",
"thiserror",
"wit-bindgen",
diff --git a/examples/http-rust-outbound-http/http-hello/Cargo.toml b/examples/http-rust-outbound-http/http-hello/Cargo.toml
index 7db45bda22..3d3943d9f0 100644
--- a/examples/http-rust-outbound-http/http-hello/Cargo.toml
+++ b/examples/http-rust-outbound-http/http-hello/Cargo.toml
@@ -9,8 +9,6 @@ crate-type = ["cdylib"]
[dependencies]
# Useful crate to handle errors.
anyhow = "1"
-# Crate to simplify working with bytes.
-bytes = "1"
# General-purpose crate with common HTTP types.
http = "0.2"
# The Spin SDK.
diff --git a/examples/http-rust-outbound-http/http-hello/src/lib.rs b/examples/http-rust-outbound-http/http-hello/src/lib.rs
index ff2cc7c880..900afda3f2 100644
--- a/examples/http-rust-outbound-http/http-hello/src/lib.rs
+++ b/examples/http-rust-outbound-http/http-hello/src/lib.rs
@@ -1,14 +1,10 @@
use anyhow::Result;
-use spin_sdk::{
- http::{Request, Response},
- http_component,
-};
+use spin_sdk::http_component;
/// A simple Spin HTTP component.
#[http_component]
-fn hello_world(_req: Request) -> Result<Response> {
+fn hello_world(_req: http::Request<()>) -> Result<http::Response<&'static str>> {
Ok(http::Response::builder()
.status(200)
- .header("foo", "bar")
- .body(Some("Hello, Fermyon!\n".into()))?)
+ .body("Hello, Fermyon!\n")?)
}
diff --git a/examples/http-rust-outbound-http/outbound-http-to-same-app/Cargo.lock b/examples/http-rust-outbound-http/outbound-http-to-same-app/Cargo.lock
index 1b2e1cb4f1..ca23245e44 100644
--- a/examples/http-rust-outbound-http/outbound-http-to-same-app/Cargo.lock
+++ b/examples/http-rust-outbound-http/outbound-http-to-same-app/Cargo.lock
@@ -8,6 +8,17 @@ version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
+[[package]]
+name = "async-trait"
+version = "0.1.74"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.38",
+]
+
[[package]]
name = "autocfg"
version = "1.1.0"
@@ -224,7 +235,6 @@ name = "outbound-http-to-same-app"
version = "0.1.0"
dependencies = [
"anyhow",
- "bytes",
"http",
"spin-sdk",
"url",
@@ -380,12 +390,15 @@ name = "spin-sdk"
version = "2.0.0-pre0"
dependencies = [
"anyhow",
+ "async-trait",
"bytes",
"form_urlencoded",
"futures",
"http",
"once_cell",
"routefinder",
+ "serde",
+ "serde_json",
"spin-macro",
"thiserror",
"wit-bindgen",
diff --git a/examples/http-rust-outbound-http/outbound-http-to-same-app/Cargo.toml b/examples/http-rust-outbound-http/outbound-http-to-same-app/Cargo.toml
index 665de8b45c..b8d9f1d457 100644
--- a/examples/http-rust-outbound-http/outbound-http-to-same-app/Cargo.toml
+++ b/examples/http-rust-outbound-http/outbound-http-to-same-app/Cargo.toml
@@ -10,8 +10,6 @@ crate-type = ["cdylib"]
# Useful crate to handle errors.
anyhow = "1"
# Crate to simplify working with bytes.
-bytes = "1"
-# General-purpose crate with common HTTP types.
http = "0.2"
# The Spin SDK.
spin-sdk = { path = "../../../sdk/rust" }
diff --git a/examples/http-rust-outbound-http/outbound-http-to-same-app/src/lib.rs b/examples/http-rust-outbound-http/outbound-http-to-same-app/src/lib.rs
index 2a809a3ccc..8a0abeae7f 100644
--- a/examples/http-rust-outbound-http/outbound-http-to-same-app/src/lib.rs
+++ b/examples/http-rust-outbound-http/outbound-http-to-same-app/src/lib.rs
@@ -1,18 +1,17 @@
use anyhow::Result;
use spin_sdk::{
- http::{Request, Response},
+ http::{IntoResponse, Request},
http_component,
};
/// Send an HTTP request and return the response.
#[http_component]
-fn send_outbound(_req: Request) -> Result<Response> {
- let mut res = spin_sdk::outbound_http::send_request(
+fn send_outbound(_req: Request) -> Result<impl IntoResponse> {
+ let mut res: http::Response<()> = spin_sdk::http::send(
http::Request::builder()
.method("GET")
.uri("/hello") // relative routes are not yet supported in cloud
- .body(None)
- .unwrap(),
+ .body(())?,
)?;
res.headers_mut()
.insert("spin-component", "rust-outbound-http".try_into()?);
diff --git a/examples/http-rust-outbound-http/outbound-http/Cargo.lock b/examples/http-rust-outbound-http/outbound-http/Cargo.lock
index 1a19db1adc..fd1ac00962 100644
--- a/examples/http-rust-outbound-http/outbound-http/Cargo.lock
+++ b/examples/http-rust-outbound-http/outbound-http/Cargo.lock
@@ -8,6 +8,17 @@ version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
+[[package]]
+name = "async-trait"
+version = "0.1.74"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.38",
+]
+
[[package]]
name = "autocfg"
version = "1.1.0"
@@ -167,7 +178,6 @@ name = "http-rust-outbound-http"
version = "0.1.0"
dependencies = [
"anyhow",
- "bytes",
"http",
"spin-sdk",
]
@@ -369,12 +379,15 @@ name = "spin-sdk"
version = "2.0.0-pre0"
dependencies = [
"anyhow",
+ "async-trait",
"bytes",
"form_urlencoded",
"futures",
"http",
"once_cell",
"routefinder",
+ "serde",
+ "serde_json",
"spin-macro",
"thiserror",
"wit-bindgen",
diff --git a/examples/http-rust-outbound-http/outbound-http/Cargo.toml b/examples/http-rust-outbound-http/outbound-http/Cargo.toml
index 28a9232eb5..8fa2ae0491 100644
--- a/examples/http-rust-outbound-http/outbound-http/Cargo.toml
+++ b/examples/http-rust-outbound-http/outbound-http/Cargo.toml
@@ -9,8 +9,6 @@ crate-type = ["cdylib"]
[dependencies]
# Useful crate to handle errors.
anyhow = "1"
-# Crate to simplify working with bytes.
-bytes = "1"
# General-purpose crate with common HTTP types.
http = "0.2"
# The Spin SDK.
diff --git a/examples/http-rust-outbound-http/outbound-http/src/lib.rs b/examples/http-rust-outbound-http/outbound-http/src/lib.rs
index 7ab21681b9..627556f335 100644
--- a/examples/http-rust-outbound-http/outbound-http/src/lib.rs
+++ b/examples/http-rust-outbound-http/outbound-http/src/lib.rs
@@ -1,17 +1,17 @@
use anyhow::Result;
use spin_sdk::{
- http::{Request, Response},
+ http::{IntoResponse, Request},
http_component,
};
/// Send an HTTP request and return the response.
#[http_component]
-fn send_outbound(_req: Request) -> Result<Response> {
- let mut res = spin_sdk::outbound_http::send_request(
+fn send_outbound(_req: Request) -> Result<impl IntoResponse> {
+ let mut res: http::Response<()> = spin_sdk::http::send(
http::Request::builder()
.method("GET")
.uri("https://random-data-api.fermyon.app/animals/json")
- .body(None)?,
+ .body(())?,
)?;
res.headers_mut()
.insert("spin-component", "rust-outbound-http".try_into()?);
diff --git a/examples/http-rust-router-macro/Cargo.lock b/examples/http-rust-router-macro/Cargo.lock
index 18f789ba13..d855968a85 100644
--- a/examples/http-rust-router-macro/Cargo.lock
+++ b/examples/http-rust-router-macro/Cargo.lock
@@ -8,6 +8,17 @@ version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
+[[package]]
+name = "async-trait"
+version = "0.1.74"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.38",
+]
+
[[package]]
name = "autocfg"
version = "1.1.0"
@@ -167,8 +178,6 @@ name = "http-rust-router-macro"
version = "0.1.0"
dependencies = [
"anyhow",
- "bytes",
- "http",
"spin-sdk",
]
@@ -369,12 +378,15 @@ name = "spin-sdk"
version = "2.0.0-pre0"
dependencies = [
"anyhow",
+ "async-trait",
"bytes",
"form_urlencoded",
"futures",
"http",
"once_cell",
"routefinder",
+ "serde",
+ "serde_json",
"spin-macro",
"thiserror",
"wit-bindgen",
diff --git a/examples/http-rust-router-macro/Cargo.toml b/examples/http-rust-router-macro/Cargo.toml
index 98495e0a36..2947b86761 100644
--- a/examples/http-rust-router-macro/Cargo.toml
+++ b/examples/http-rust-router-macro/Cargo.toml
@@ -4,15 +4,11 @@ version = "0.1.0"
edition = "2021"
[lib]
-crate-type = [ "cdylib" ]
+crate-type = ["cdylib"]
[dependencies]
# Useful crate to handle errors.
anyhow = "1"
-# Crate to simplify working with bytes.
-bytes = "1"
-# General-purpose crate with common HTTP types.
-http = "0.2"
# The Spin SDK.
spin-sdk = { path = "../../sdk/rust" }
diff --git a/examples/http-rust-router-macro/src/lib.rs b/examples/http-rust-router-macro/src/lib.rs
index 94a8dcc0cc..d533b6ec55 100644
--- a/examples/http-rust-router-macro/src/lib.rs
+++ b/examples/http-rust-router-macro/src/lib.rs
@@ -1,18 +1,16 @@
+#![allow(dead_code, unused_imports)]
use spin_sdk::{
- http::{Params, Request, Response},
+ http::{IntoResponse, Params, Request, Response},
http_component, http_router,
};
#[http_component]
-fn handle_route(req: Request) -> anyhow::Result<Response> {
+fn handle_route(req: Request) -> impl IntoResponse {
let router = http_router! {
GET "/hello/:planet" => api::hello_planet,
- _ "/*" => |_req, params| {
+ _ "/*" => |_req: Request, params| {
let capture = params.wildcard().unwrap_or_default();
- Ok(http::Response::builder()
- .status(http::StatusCode::OK)
- .body(Some(capture.to_string().into()))
- .unwrap())
+ Response::new(200, capture.to_string())
}
};
router.handle(req)
@@ -22,12 +20,9 @@ mod api {
use super::*;
// /hello/:planet
- pub fn hello_planet(_req: Request, params: Params) -> anyhow::Result<Response> {
+ pub fn hello_planet(_req: Request, params: Params) -> anyhow::Result<impl IntoResponse> {
let planet = params.get("planet").expect("PLANET");
- Ok(http::Response::builder()
- .status(http::StatusCode::OK)
- .body(Some(planet.to_string().into()))
- .unwrap())
+ Ok(Response::new(200, planet.to_string()))
}
}
diff --git a/examples/http-rust-router/Cargo.lock b/examples/http-rust-router/Cargo.lock
index fc3bf605a7..50323254e9 100644
--- a/examples/http-rust-router/Cargo.lock
+++ b/examples/http-rust-router/Cargo.lock
@@ -8,6 +8,17 @@ version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
+[[package]]
+name = "async-trait"
+version = "0.1.74"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.38",
+]
+
[[package]]
name = "autocfg"
version = "1.1.0"
@@ -167,8 +178,6 @@ name = "http-rust-router"
version = "0.1.0"
dependencies = [
"anyhow",
- "bytes",
- "http",
"spin-sdk",
]
@@ -369,12 +378,15 @@ name = "spin-sdk"
version = "2.0.0-pre0"
dependencies = [
"anyhow",
+ "async-trait",
"bytes",
"form_urlencoded",
"futures",
"http",
"once_cell",
"routefinder",
+ "serde",
+ "serde_json",
"spin-macro",
"thiserror",
"wit-bindgen",
diff --git a/examples/http-rust-router/Cargo.toml b/examples/http-rust-router/Cargo.toml
index 75b693dba3..b9bbcef8e9 100644
--- a/examples/http-rust-router/Cargo.toml
+++ b/examples/http-rust-router/Cargo.toml
@@ -4,15 +4,11 @@ version = "0.1.0"
edition = "2021"
[lib]
-crate-type = [ "cdylib" ]
+crate-type = ["cdylib"]
[dependencies]
# Useful crate to handle errors.
anyhow = "1"
-# Crate to simplify working with bytes.
-bytes = "1"
-# General-purpose crate with common HTTP types.
-http = "0.2"
# The Spin SDK.
spin-sdk = { path = "../../sdk/rust" }
[workspace]
diff --git a/examples/http-rust-router/src/lib.rs b/examples/http-rust-router/src/lib.rs
index 2150e8d811..97c18b48e1 100644
--- a/examples/http-rust-router/src/lib.rs
+++ b/examples/http-rust-router/src/lib.rs
@@ -1,12 +1,12 @@
use anyhow::Result;
use spin_sdk::{
- http::{Params, Request, Response, Router},
+ http::{IntoResponse, Params, Request, Response, Router},
http_component,
};
/// A Spin HTTP component that internally routes requests.
#[http_component]
-fn handle_route(req: Request) -> Result<Response> {
+fn handle_route(req: Request) -> Response {
let mut router = Router::new();
router.get("/hello/:planet", api::hello_planet);
router.any("/*", api::echo_wildcard);
@@ -17,19 +17,15 @@ mod api {
use super::*;
// /hello/:planet
- pub fn hello_planet(_req: Request, params: Params) -> Result<Response> {
+ pub fn hello_planet(_req: Request, params: Params) -> Result<impl IntoResponse> {
let planet = params.get("planet").expect("PLANET");
- Ok(http::Response::builder()
- .status(http::StatusCode::OK)
- .body(Some(planet.to_string().into()))?)
+ Ok(Response::new(200, planet.to_string()))
}
// /*
- pub fn echo_wildcard(_req: Request, params: Params) -> Result<Response> {
+ pub fn echo_wildcard(_req: Request, params: Params) -> Result<impl IntoResponse> {
let capture = params.wildcard().unwrap_or_default();
- Ok(http::Response::builder()
- .status(http::StatusCode::OK)
- .body(Some(capture.to_string().into()))?)
+ Ok(Response::new(200, capture.to_string()))
}
}
diff --git a/examples/http-rust/Cargo.lock b/examples/http-rust/Cargo.lock
index e3bf5ea056..dedc606b43 100644
--- a/examples/http-rust/Cargo.lock
+++ b/examples/http-rust/Cargo.lock
@@ -8,6 +8,17 @@ version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
+[[package]]
+name = "async-trait"
+version = "0.1.74"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.38",
+]
+
[[package]]
name = "autocfg"
version = "1.1.0"
@@ -167,8 +178,8 @@ name = "http-rust"
version = "0.1.0"
dependencies = [
"anyhow",
- "bytes",
"http",
+ "serde",
"spin-sdk",
]
@@ -369,12 +380,15 @@ name = "spin-sdk"
version = "2.0.0-pre0"
dependencies = [
"anyhow",
+ "async-trait",
"bytes",
"form_urlencoded",
"futures",
"http",
"once_cell",
"routefinder",
+ "serde",
+ "serde_json",
"spin-macro",
"thiserror",
"wit-bindgen",
diff --git a/examples/http-rust/Cargo.toml b/examples/http-rust/Cargo.toml
index 5581102e48..afad911a21 100644
--- a/examples/http-rust/Cargo.toml
+++ b/examples/http-rust/Cargo.toml
@@ -4,15 +4,12 @@ version = "0.1.0"
edition = "2021"
[lib]
-crate-type = [ "cdylib" ]
+crate-type = ["cdylib"]
[dependencies]
-# Useful crate to handle errors.
anyhow = "1"
-# Crate to simplify working with bytes.
-bytes = "1"
-# General-purpose crate with common HTTP types.
-http = "0.2"
-# The Spin SDK.
+http = "0.2.9"
+serde = { version = "1.0", features = ["derive"] }
spin-sdk = { path = "../../sdk/rust" }
+
[workspace]
diff --git a/examples/http-rust/src/lib.rs b/examples/http-rust/src/lib.rs
index fe34f4338c..47f8a81547 100644
--- a/examples/http-rust/src/lib.rs
+++ b/examples/http-rust/src/lib.rs
@@ -1,15 +1,13 @@
-use anyhow::Result;
-use spin_sdk::{
- http::{Request, Response},
- http_component,
-};
+use spin_sdk::http::{IntoResponse, Json, Response};
+use spin_sdk::http_component;
+
+#[derive(serde::Deserialize, Debug)]
+struct Greeted {
+ name: String,
+}
/// A simple Spin HTTP component.
#[http_component]
-fn hello_world(req: Request) -> Result<Response> {
- println!("{:?}", req.headers());
- Ok(http::Response::builder()
- .status(200)
- .header("foo", "bar")
- .body(Some("Hello, Fermyon!\n".into()))?)
+fn hello_world(req: http::Request<Json<Greeted>>) -> anyhow::Result<impl IntoResponse> {
+ Ok(Response::new(200, format!("Hello, {}", req.body().name)))
}
diff --git a/examples/redis-rust/Cargo.lock b/examples/redis-rust/Cargo.lock
index 8c284392ea..75b791b6ec 100644
--- a/examples/redis-rust/Cargo.lock
+++ b/examples/redis-rust/Cargo.lock
@@ -8,6 +8,17 @@ version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
+[[package]]
+name = "async-trait"
+version = "0.1.74"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.38",
+]
+
[[package]]
name = "autocfg"
version = "1.1.0"
@@ -359,12 +370,15 @@ name = "spin-sdk"
version = "2.0.0-pre0"
dependencies = [
"anyhow",
+ "async-trait",
"bytes",
"form_urlencoded",
"futures",
"http",
"once_cell",
"routefinder",
+ "serde",
+ "serde_json",
"spin-macro",
"thiserror",
"wit-bindgen",
diff --git a/examples/rust-key-value/Cargo.lock b/examples/rust-key-value/Cargo.lock
index 5802f8b588..a81173d9e7 100644
--- a/examples/rust-key-value/Cargo.lock
+++ b/examples/rust-key-value/Cargo.lock
@@ -8,6 +8,17 @@ version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
+[[package]]
+name = "async-trait"
+version = "0.1.74"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.38",
+]
+
[[package]]
name = "autocfg"
version = "1.1.0"
@@ -260,7 +271,6 @@ name = "rust-key-value"
version = "0.1.0"
dependencies = [
"anyhow",
- "bytes",
"http",
"spin-sdk",
]
@@ -369,12 +379,15 @@ name = "spin-sdk"
version = "2.0.0-pre0"
dependencies = [
"anyhow",
+ "async-trait",
"bytes",
"form_urlencoded",
"futures",
"http",
"once_cell",
"routefinder",
+ "serde",
+ "serde_json",
"spin-macro",
"thiserror",
"wit-bindgen",
diff --git a/examples/rust-key-value/Cargo.toml b/examples/rust-key-value/Cargo.toml
index 1e0fa827fe..56cf74643c 100644
--- a/examples/rust-key-value/Cargo.toml
+++ b/examples/rust-key-value/Cargo.toml
@@ -1,18 +1,14 @@
[package]
-name = "rust-key-value"
+name = "rust-key-value"
version = "0.1.0"
edition = "2021"
[lib]
-crate-type = [ "cdylib" ]
+crate-type = ["cdylib"]
[dependencies]
-# Useful crate to handle errors.
anyhow = "1"
-# Crate to simplify working with bytes.
-bytes = "1"
-# General-purpose crate with common HTTP types.
http = "0.2"
-spin-sdk = { path = "../../sdk/rust"}
+spin-sdk = { path = "../../sdk/rust" }
[workspace]
diff --git a/examples/rust-key-value/src/lib.rs b/examples/rust-key-value/src/lib.rs
index 152e7cce37..f37cb61e07 100644
--- a/examples/rust-key-value/src/lib.rs
+++ b/examples/rust-key-value/src/lib.rs
@@ -1,26 +1,25 @@
-use anyhow::Result;
use http::{Method, StatusCode};
use spin_sdk::{
- http::{Request, Response},
+ http::{IntoResponse, Response},
http_component,
key_value::Store,
};
#[http_component]
-fn handle_request(req: Request) -> Result<Response> {
+fn handle_request(req: http::Request<Vec<u8>>) -> anyhow::Result<impl IntoResponse> {
// Open the default key-value store
let store = Store::open_default()?;
let (status, body) = match *req.method() {
Method::POST => {
// Add the request (URI, body) tuple to the store
- store.set(req.uri().path(), req.body().as_deref().unwrap_or(&[]))?;
+ store.set(req.uri().path(), req.body().as_slice())?;
(StatusCode::OK, None)
}
Method::GET => {
// Get the value associated with the request URI, or return a 404 if it's not present
match store.get(req.uri().path())? {
- Some(value) => (StatusCode::OK, Some(value.into())),
+ Some(value) => (StatusCode::OK, Some(value)),
None => (StatusCode::NOT_FOUND, None),
}
}
@@ -31,15 +30,15 @@ fn handle_request(req: Request) -> Result<Response> {
}
Method::HEAD => {
// Like GET, except do not return the value
- match store.exists(req.uri().path()) {
- Ok(true) => (StatusCode::OK, None),
- Ok(false) => (StatusCode::NOT_FOUND, None),
- Err(error) => return Err(error.into()),
- }
+ let code = if store.exists(req.uri().path())? {
+ StatusCode::OK
+ } else {
+ StatusCode::NOT_FOUND
+ };
+ (code, None)
}
// No other methods are currently supported
_ => (StatusCode::METHOD_NOT_ALLOWED, None),
};
-
- Ok(http::Response::builder().status(status).body(body)?)
+ Ok(Response::new(status, body))
}
diff --git a/examples/rust-outbound-mysql/Cargo.lock b/examples/rust-outbound-mysql/Cargo.lock
index 26e0756c09..647b2adc68 100644
--- a/examples/rust-outbound-mysql/Cargo.lock
+++ b/examples/rust-outbound-mysql/Cargo.lock
@@ -8,6 +8,17 @@ version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
+[[package]]
+name = "async-trait"
+version = "0.1.74"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.38",
+]
+
[[package]]
name = "autocfg"
version = "1.1.0"
@@ -260,7 +271,6 @@ name = "rust-outbound-mysql"
version = "0.1.0"
dependencies = [
"anyhow",
- "bytes",
"http",
"serde",
"serde_json",
@@ -371,12 +381,15 @@ name = "spin-sdk"
version = "2.0.0-pre0"
dependencies = [
"anyhow",
+ "async-trait",
"bytes",
"form_urlencoded",
"futures",
"http",
"once_cell",
"routefinder",
+ "serde",
+ "serde_json",
"spin-macro",
"thiserror",
"wit-bindgen",
diff --git a/examples/rust-outbound-mysql/Cargo.toml b/examples/rust-outbound-mysql/Cargo.toml
index 2e96997075..83b7aa30a0 100644
--- a/examples/rust-outbound-mysql/Cargo.toml
+++ b/examples/rust-outbound-mysql/Cargo.toml
@@ -6,13 +6,11 @@ version = "0.1.0"
edition = "2021"
[lib]
-crate-type = [ "cdylib" ]
+crate-type = ["cdylib"]
[dependencies]
# Useful crate to handle errors.
anyhow = "1"
-# Crate to simplify working with bytes.
-bytes = "1"
# General-purpose crate with common HTTP types.
http = "0.2"
serde = "1.0.144"
diff --git a/examples/rust-outbound-mysql/src/lib.rs b/examples/rust-outbound-mysql/src/lib.rs
index 924b9ba554..f01adebb25 100644
--- a/examples/rust-outbound-mysql/src/lib.rs
+++ b/examples/rust-outbound-mysql/src/lib.rs
@@ -1,7 +1,7 @@
use anyhow::{anyhow, Result};
-use http::{HeaderValue, Method};
+use http::{HeaderValue, Method, Request, Response};
use spin_sdk::{
- http::{Request, Response},
+ http::Json,
http_component,
mysql::{self, ParameterValue},
};
@@ -23,7 +23,9 @@ enum RequestAction {
}
#[http_component]
-fn rust_outbound_mysql(req: Request) -> Result<Response> {
+fn rust_outbound_mysql(
+ req: Request<Json<HashMap<String, String>>>,
+) -> Result<Response<Option<String>>> {
match parse_request(req) {
RequestAction::List => list(),
RequestAction::Get(id) => get(id),
@@ -32,7 +34,7 @@ fn rust_outbound_mysql(req: Request) -> Result<Response> {
}
}
-fn parse_request(req: Request) -> RequestAction {
+fn parse_request(req: Request<Json<HashMap<String, String>>>) -> RequestAction {
match *req.method() {
Method::GET => match req.headers().get("spin-path-info") {
None => RequestAction::Error(500),
@@ -43,21 +45,17 @@ fn parse_request(req: Request) -> RequestAction {
},
},
Method::POST => {
- match body_json_to_map(&req) {
- Ok(map) => {
- let name = match map.get("name") {
- Some(n) => n.to_owned(),
- None => return RequestAction::Error(400), // If this were a real app it would have error messages
- };
- let prey = map.get("prey").cloned();
- let is_finicky = map
- .get("is_finicky")
- .map(|s| s == "true")
- .unwrap_or_default();
- RequestAction::Create(name, prey, is_finicky)
- }
- Err(_) => RequestAction::Error(400), // Sorry no this isn't helpful either
- }
+ let map = req.body();
+ let name = match map.get("name") {
+ Some(n) => n.to_owned(),
+ None => return RequestAction::Error(400), // If this were a real app it would have error messages
+ };
+ let prey = map.get("prey").cloned();
+ let is_finicky = map
+ .get("is_finicky")
+ .map(|s| s == "true")
+ .unwrap_or_default();
+ RequestAction::Create(name, prey, is_finicky)
}
_ => RequestAction::Error(405),
}
@@ -80,16 +78,7 @@ fn header_val_to_int(header_val: &HeaderValue) -> Result<Option<i32>, ()> {
}
}
-fn body_json_to_map(req: &Request) -> Result<HashMap<String, String>> {
- // TODO: easier way?
- let body = match req.body().as_ref() {
- Some(bytes) => bytes.slice(..),
- None => bytes::Bytes::default(),
- };
- Ok(serde_json::from_slice::<HashMap<String, String>>(&body)?)
-}
-
-fn list() -> Result<Response> {
+fn list() -> Result<Response<Option<String>>> {
let address = std::env::var(DB_URL_ENV)?;
let sql = "SELECT id, name, prey, is_finicky FROM pets";
@@ -117,12 +106,10 @@ fn list() -> Result<Response> {
column_summary,
);
- Ok(http::Response::builder()
- .status(200)
- .body(Some(response.into()))?)
+ Ok(http::Response::builder().status(200).body(Some(response))?)
}
-fn get(id: i32) -> Result<Response> {
+fn get(id: i32) -> Result<Response<Option<String>>> {
let address = std::env::var(DB_URL_ENV)?;
let sql = "SELECT id, name, prey, is_finicky FROM pets WHERE id = ?";
@@ -134,14 +121,16 @@ fn get(id: i32) -> Result<Response> {
Some(row) => {
let pet = as_pet(row)?;
let response = format!("{:?}", pet);
- Ok(http::Response::builder()
- .status(200)
- .body(Some(response.into()))?)
+ Ok(http::Response::builder().status(200).body(Some(response))?)
}
}
}
-fn create(name: String, prey: Option<String>, is_finicky: bool) -> Result<Response> {
+fn create(
+ name: String,
+ prey: Option<String>,
+ is_finicky: bool,
+) -> Result<Response<Option<String>>> {
let address = std::env::var(DB_URL_ENV)?;
let id = max_pet_id(&address)? + 1;
@@ -170,7 +159,7 @@ fn create(name: String, prey: Option<String>, is_finicky: bool) -> Result<Respon
.body(None)?)
}
-fn error(status: u16) -> Result<Response> {
+fn error(status: u16) -> Result<Response<Option<String>>> {
Ok(http::Response::builder().status(status).body(None)?)
}
diff --git a/examples/rust-outbound-pg/Cargo.lock b/examples/rust-outbound-pg/Cargo.lock
index e721d2caf3..23ccd0eea8 100644
--- a/examples/rust-outbound-pg/Cargo.lock
+++ b/examples/rust-outbound-pg/Cargo.lock
@@ -8,6 +8,17 @@ version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
+[[package]]
+name = "async-trait"
+version = "0.1.74"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.38",
+]
+
[[package]]
name = "autocfg"
version = "1.1.0"
@@ -260,7 +271,6 @@ name = "rust-outbound-pg"
version = "0.1.0"
dependencies = [
"anyhow",
- "bytes",
"http",
"spin-sdk",
]
@@ -369,12 +379,15 @@ name = "spin-sdk"
version = "2.0.0-pre0"
dependencies = [
"anyhow",
+ "async-trait",
"bytes",
"form_urlencoded",
"futures",
"http",
"once_cell",
"routefinder",
+ "serde",
+ "serde_json",
"spin-macro",
"thiserror",
"wit-bindgen",
diff --git a/examples/rust-outbound-pg/Cargo.toml b/examples/rust-outbound-pg/Cargo.toml
index 9ee0b83a11..6822a33e17 100644
--- a/examples/rust-outbound-pg/Cargo.toml
+++ b/examples/rust-outbound-pg/Cargo.toml
@@ -4,13 +4,11 @@ version = "0.1.0"
edition = "2021"
[lib]
-crate-type = [ "cdylib" ]
+crate-type = ["cdylib"]
[dependencies]
# Useful crate to handle errors.
anyhow = "1"
-# Crate to simplify working with bytes.
-bytes = "1"
# General-purpose crate with common HTTP types.
http = "0.2"
# The Spin SDK.
diff --git a/examples/rust-outbound-pg/src/lib.rs b/examples/rust-outbound-pg/src/lib.rs
index 58e34e8312..94c4f6f1c6 100644
--- a/examples/rust-outbound-pg/src/lib.rs
+++ b/examples/rust-outbound-pg/src/lib.rs
@@ -1,7 +1,7 @@
#![allow(dead_code)]
use anyhow::Result;
+use http::{Request, Response};
use spin_sdk::{
- http::{Request, Response},
http_component,
pg::{self, Decode},
};
@@ -40,18 +40,18 @@ impl TryFrom<&pg::Row> for Article {
}
#[http_component]
-fn process(req: Request) -> Result<Response> {
+fn process(req: Request<()>) -> Result<Response<String>> {
match req.uri().path() {
"/read" => read(req),
"/write" => write(req),
"/pg_backend_pid" => pg_backend_pid(req),
_ => Ok(http::Response::builder()
.status(404)
- .body(Some("Not found".into()))?),
+ .body("Not found".into())?),
}
}
-fn read(_req: Request) -> Result<Response> {
+fn read(_req: Request<()>) -> Result<Response<String>> {
let address = std::env::var(DB_URL_ENV)?;
let conn = pg::Connection::open(&address)?;
@@ -83,12 +83,10 @@ fn read(_req: Request) -> Result<Response> {
column_summary,
);
- Ok(http::Response::builder()
- .status(200)
- .body(Some(response.into()))?)
+ Ok(http::Response::builder().status(200).body(response)?)
}
-fn write(_req: Request) -> Result<Response> {
+fn write(_req: Request<()>) -> Result<Response<String>> {
let address = std::env::var(DB_URL_ENV)?;
let conn = pg::Connection::open(&address)?;
@@ -103,12 +101,10 @@ fn write(_req: Request) -> Result<Response> {
let count = i64::decode(&row[0])?;
let response = format!("Count: {}\n", count);
- Ok(http::Response::builder()
- .status(200)
- .body(Some(response.into()))?)
+ Ok(http::Response::builder().status(200).body(response)?)
}
-fn pg_backend_pid(_req: Request) -> Result<Response> {
+fn pg_backend_pid(_req: Request<()>) -> Result<Response<String>> {
let address = std::env::var(DB_URL_ENV)?;
let conn = pg::Connection::open(&address)?;
let sql = "SELECT pg_backend_pid()";
@@ -124,9 +120,7 @@ fn pg_backend_pid(_req: Request) -> Result<Response> {
let response = format!("pg_backend_pid: {}\n", get_pid()?);
- Ok(http::Response::builder()
- .status(200)
- .body(Some(response.into()))?)
+ Ok(http::Response::builder().status(200).body(response)?)
}
fn format_col(column: &pg::Column) -> String {
diff --git a/examples/rust-outbound-redis/Cargo.lock b/examples/rust-outbound-redis/Cargo.lock
index 32024db520..a07ed99942 100644
--- a/examples/rust-outbound-redis/Cargo.lock
+++ b/examples/rust-outbound-redis/Cargo.lock
@@ -8,6 +8,17 @@ version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
+[[package]]
+name = "async-trait"
+version = "0.1.74"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.38",
+]
+
[[package]]
name = "autocfg"
version = "1.1.0"
@@ -260,8 +271,6 @@ name = "rust-outbound-redis"
version = "0.1.0"
dependencies = [
"anyhow",
- "bytes",
- "http",
"spin-sdk",
]
@@ -369,12 +378,15 @@ name = "spin-sdk"
version = "2.0.0-pre0"
dependencies = [
"anyhow",
+ "async-trait",
"bytes",
"form_urlencoded",
"futures",
"http",
"once_cell",
"routefinder",
+ "serde",
+ "serde_json",
"spin-macro",
"thiserror",
"wit-bindgen",
diff --git a/examples/rust-outbound-redis/Cargo.toml b/examples/rust-outbound-redis/Cargo.toml
index db1439c0c8..1f53f9638f 100644
--- a/examples/rust-outbound-redis/Cargo.toml
+++ b/examples/rust-outbound-redis/Cargo.toml
@@ -4,15 +4,11 @@ version = "0.1.0"
edition = "2021"
[lib]
-crate-type = [ "cdylib" ]
+crate-type = ["cdylib"]
[dependencies]
# Useful crate to handle errors.
anyhow = "1"
-# Crate to simplify working with bytes.
-bytes = "1"
-# General-purpose crate with common HTTP types.
-http = "0.2"
# The Spin SDK.
spin-sdk = { path = "../../sdk/rust" }
diff --git a/examples/rust-outbound-redis/src/lib.rs b/examples/rust-outbound-redis/src/lib.rs
index 0f72e4a50c..a9333f8e02 100644
--- a/examples/rust-outbound-redis/src/lib.rs
+++ b/examples/rust-outbound-redis/src/lib.rs
@@ -1,6 +1,7 @@
use anyhow::{anyhow, Context, Result};
use spin_sdk::{
- http::{internal_server_error, Request, Response},
+ http::responses::internal_server_error,
+ http::{IntoResponse, Request, Response},
http_component, redis,
};
@@ -18,7 +19,7 @@ const REDIS_CHANNEL_ENV: &str = "REDIS_CHANNEL";
/// to a Redis channel. The component is triggered by an HTTP
/// request served on the route configured in the `spin.toml`.
#[http_component]
-fn publish(_req: Request) -> Result<Response> {
+fn publish(_req: Request) -> Result<impl IntoResponse> {
let address = std::env::var(REDIS_ADDRESS_ENV)?;
let channel = std::env::var(REDIS_CHANNEL_ENV)?;
@@ -44,7 +45,7 @@ fn publish(_req: Request) -> Result<Response> {
// Publish to Redis
match conn.publish(&channel, &payload) {
- Ok(()) => Ok(http::Response::builder().status(200).body(None)?),
- Err(_e) => internal_server_error(),
+ Ok(()) => Ok(Response::new(200, ())),
+ Err(_e) => Ok(internal_server_error()),
}
}
diff --git a/examples/spin-wagi-http/http-rust/Cargo.lock b/examples/spin-wagi-http/http-rust/Cargo.lock
index 210a80b44a..ffaa317e02 100644
--- a/examples/spin-wagi-http/http-rust/Cargo.lock
+++ b/examples/spin-wagi-http/http-rust/Cargo.lock
@@ -8,6 +8,17 @@ version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
+[[package]]
+name = "async-trait"
+version = "0.1.74"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.38",
+]
+
[[package]]
name = "autocfg"
version = "1.1.0"
@@ -40,9 +51,9 @@ checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "form_urlencoded"
-version = "1.1.0"
+version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a9c384f161156f5260c24a097c56119f9be8c798586aecc13afbcbe7b7e26bf8"
+checksum = "a62bc1cf6f830c2ec14a513a9fb124d0a213a629668a4186f329db21fe045652"
dependencies = [
"percent-encoding",
]
@@ -221,9 +232,9 @@ checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d"
[[package]]
name = "percent-encoding"
-version = "2.2.0"
+version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "478c572c3d73181ff3c2539045f6eb99e5491218eae919370993b890cdbdd98e"
+checksum = "9b2a4787296e9989611394c33f193f676704af1686e70b8f8033ab5ba9a35a94"
[[package]]
name = "pin-project-lite"
@@ -248,9 +259,9 @@ dependencies = [
[[package]]
name = "quote"
-version = "1.0.28"
+version = "1.0.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1b9ab9c7eadfd8df19006f1cf1a4aed13540ed5cbc047010ece5826e10825488"
+checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae"
dependencies = [
"proc-macro2",
]
@@ -369,12 +380,15 @@ name = "spin-sdk"
version = "2.0.0-pre0"
dependencies = [
"anyhow",
+ "async-trait",
"bytes",
"form_urlencoded",
"futures",
"http",
"once_cell",
"routefinder",
+ "serde",
+ "serde_json",
"spin-macro",
"thiserror",
"wit-bindgen",
diff --git a/examples/spin-wagi-http/http-rust/src/lib.rs b/examples/spin-wagi-http/http-rust/src/lib.rs
index 6c258c5e92..b3983253e2 100644
--- a/examples/spin-wagi-http/http-rust/src/lib.rs
+++ b/examples/spin-wagi-http/http-rust/src/lib.rs
@@ -1,15 +1,12 @@
use anyhow::Result;
-use spin_sdk::{
- http::{Request, Response},
- http_component,
-};
+use spin_sdk::http_component;
/// A simple Spin HTTP component.
#[http_component]
-fn goodbye_world(req: Request) -> Result<Response> {
+fn goodbye_world(req: http::Request<()>) -> Result<http::Response<&'static str>> {
println!("{:?}", req.headers());
Ok(http::Response::builder()
.status(200)
.header("foo", "bar")
- .body(Some("Goodbye, Fermyon!\n".into()))?)
+ .body("Goodbye, Fermyon!\n")?)
}
diff --git a/examples/wasi-http-rust-async/.cargo/config.toml b/examples/wasi-http-rust-streaming-outgoing-body/.cargo/config.toml
similarity index 100%
rename from examples/wasi-http-rust-async/.cargo/config.toml
rename to examples/wasi-http-rust-streaming-outgoing-body/.cargo/config.toml
diff --git a/examples/wasi-http-rust-async/.gitignore b/examples/wasi-http-rust-streaming-outgoing-body/.gitignore
similarity index 100%
rename from examples/wasi-http-rust-async/.gitignore
rename to examples/wasi-http-rust-streaming-outgoing-body/.gitignore
diff --git a/examples/wasi-http-rust-async/Cargo.lock b/examples/wasi-http-rust-streaming-outgoing-body/Cargo.lock
similarity index 98%
rename from examples/wasi-http-rust-async/Cargo.lock
rename to examples/wasi-http-rust-streaming-outgoing-body/Cargo.lock
index bb233e9d38..c685f1a7f0 100644
--- a/examples/wasi-http-rust-async/Cargo.lock
+++ b/examples/wasi-http-rust-streaming-outgoing-body/Cargo.lock
@@ -8,6 +8,17 @@ version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
+[[package]]
+name = "async-trait"
+version = "0.1.74"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.38",
+]
+
[[package]]
name = "autocfg"
version = "1.1.0"
@@ -446,12 +457,15 @@ name = "spin-sdk"
version = "2.0.0-pre0"
dependencies = [
"anyhow",
+ "async-trait",
"bytes",
"form_urlencoded",
"futures",
"http",
"once_cell",
"routefinder",
+ "serde",
+ "serde_json",
"spin-macro",
"thiserror",
"wit-bindgen",
@@ -577,7 +591,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
[[package]]
-name = "wasi-http-rust-async"
+name = "wasi-http-rust-streaming-outgoing-body"
version = "0.1.0"
dependencies = [
"anyhow",
diff --git a/examples/wasi-http-rust-async/Cargo.toml b/examples/wasi-http-rust-streaming-outgoing-body/Cargo.toml
similarity index 73%
rename from examples/wasi-http-rust-async/Cargo.toml
rename to examples/wasi-http-rust-streaming-outgoing-body/Cargo.toml
index 431b599f9d..b3587d079c 100644
--- a/examples/wasi-http-rust-async/Cargo.toml
+++ b/examples/wasi-http-rust-streaming-outgoing-body/Cargo.toml
@@ -1,10 +1,10 @@
[package]
-name = "wasi-http-rust-async"
+name = "wasi-http-rust-streaming-outgoing-body"
version = "0.1.0"
edition = "2021"
[lib]
-crate-type = [ "cdylib" ]
+crate-type = ["cdylib"]
[dependencies]
anyhow = "1.0.71"
diff --git a/examples/wasi-http-rust-async/spin.toml b/examples/wasi-http-rust-streaming-outgoing-body/spin.toml
similarity index 100%
rename from examples/wasi-http-rust-async/spin.toml
rename to examples/wasi-http-rust-streaming-outgoing-body/spin.toml
diff --git a/examples/wasi-http-rust-async/src/lib.rs b/examples/wasi-http-rust-streaming-outgoing-body/src/lib.rs
similarity index 55%
rename from examples/wasi-http-rust-async/src/lib.rs
rename to examples/wasi-http-rust-streaming-outgoing-body/src/lib.rs
index a75627d6aa..309d2c4858 100644
--- a/examples/wasi-http-rust-async/src/lib.rs
+++ b/examples/wasi-http-rust-streaming-outgoing-body/src/lib.rs
@@ -1,34 +1,32 @@
-use {
- self::wasi::http::types::{
- Fields, IncomingRequest, Method, OutgoingBody, OutgoingRequest, OutgoingResponse,
- ResponseOutparam, Scheme,
- },
- anyhow::{bail, Result},
- futures::{stream, FutureExt, SinkExt, StreamExt, TryStreamExt},
- sha2::{Digest, Sha256},
- spin_sdk::wasi_http_component,
- std::str,
- url::Url,
+use anyhow::{bail, Result};
+use futures::{stream, SinkExt, StreamExt, TryStreamExt};
+use spin_sdk::wasi_http::send;
+use spin_sdk::wasi_http::{
+ Fields, IncomingRequest, IncomingResponse, Method, OutgoingBody, OutgoingRequest,
+ OutgoingResponse, ResponseOutparam, Scheme,
};
+use spin_sdk::wasi_http_component;
+use url::Url;
const MAX_CONCURRENCY: usize = 16;
#[wasi_http_component]
-async fn handle_request(request: IncomingRequest, response_out: ResponseOutparam) -> Result<()> {
- let method = request.method();
- let path = request.path_with_query();
+async fn handle_request(request: IncomingRequest, response_out: ResponseOutparam) {
let headers = request.headers().entries();
- match (method, path.as_deref()) {
+ match (request.method(), request.path_with_query().as_deref()) {
(Method::Get, Some("/hash-all")) => {
let urls = headers.iter().filter_map(|(k, v)| {
(k == "url")
.then_some(v)
- .and_then(|v| str::from_utf8(v).ok())
+ .and_then(|v| std::str::from_utf8(v).ok())
.and_then(|v| Url::parse(v).ok())
});
- let results = urls.map(move |url| hash(url.clone()).map(move |result| (url, result)));
+ let results = urls.map(|url| async move {
+ let result = hash(&url).await;
+ (url, result)
+ });
let mut results = stream::iter(results).buffer_unordered(MAX_CONCURRENCY);
@@ -37,19 +35,19 @@ async fn handle_request(request: IncomingRequest, response_out: ResponseOutparam
&Fields::new(&[("content-type".to_string(), b"text/plain".to_vec())]),
);
- let mut sink = executor::outgoing_response_body(&response);
+ let mut body = response.take_body();
ResponseOutparam::set(response_out, Ok(response));
while let Some((url, result)) = results.next().await {
- sink.send(
- match result {
- Ok(hash) => format!("{url}: {hash}\n"),
- Err(e) => format!("{url}: {e:?}\n"),
- }
- .into_bytes(),
- )
- .await?;
+ let payload = match result {
+ Ok(hash) => format!("{url}: {hash}\n"),
+ Err(e) => format!("{url}: {e:?}\n"),
+ }
+ .into_bytes();
+ if let Err(e) = body.send(payload).await {
+ eprintln!("Error sending payload: {e}");
+ }
}
}
@@ -58,21 +56,21 @@ async fn handle_request(request: IncomingRequest, response_out: ResponseOutparam
200,
&Fields::new(
&headers
- .iter()
- .filter_map(|(k, v)| {
- (k == "content-type").then_some((k.clone(), v.clone()))
- })
+ .into_iter()
+ .filter_map(|(k, v)| (k == "content-type").then_some((k, v)))
.collect::<Vec<_>>(),
),
);
- let mut sink = executor::outgoing_response_body(&response);
+ let mut body = response.take_body();
ResponseOutparam::set(response_out, Ok(response));
- let mut stream = executor::incoming_request_body(request);
- while let Some(chunk) = stream.try_next().await? {
- sink.send(chunk).await?;
+ let mut stream = request.into_body_stream();
+ while let Ok(Some(chunk)) = stream.try_next().await {
+ if let Err(e) = body.send(chunk).await {
+ eprintln!("Error sending body: {e}");
+ }
}
}
@@ -86,11 +84,9 @@ async fn handle_request(request: IncomingRequest, response_out: ResponseOutparam
OutgoingBody::finish(body, None);
}
}
-
- Ok(())
}
-async fn hash(url: Url) -> Result<String> {
+async fn hash(url: &Url) -> Result<String> {
let request = OutgoingRequest::new(
&Method::Get,
Some(url.path()),
@@ -103,7 +99,7 @@ async fn hash(url: Url) -> Result<String> {
&Fields::new(&[]),
);
- let response = executor::outgoing_request_send(request).await?;
+ let response: IncomingResponse = send(request).await?;
let status = response.status();
@@ -111,9 +107,10 @@ async fn hash(url: Url) -> Result<String> {
bail!("unexpected status: {status}");
}
- let mut body = executor::incoming_response_body(response);
+ let mut body = response.into_body_stream();
- let mut hasher = Sha256::new();
+ use sha2::Digest;
+ let mut hasher = sha2::Sha256::new();
while let Some(chunk) = body.try_next().await? {
hasher.update(&chunk);
}
diff --git a/examples/wasi-http-rust/.cargo/config.toml b/examples/wasi-http-rust/.cargo/config.toml
new file mode 100644
index 0000000000..6b77899cb3
--- /dev/null
+++ b/examples/wasi-http-rust/.cargo/config.toml
@@ -0,0 +1,2 @@
+[build]
+target = "wasm32-wasi"
diff --git a/examples/wasi-http-rust/.gitignore b/examples/wasi-http-rust/.gitignore
new file mode 100644
index 0000000000..2f7896d1d1
--- /dev/null
+++ b/examples/wasi-http-rust/.gitignore
@@ -0,0 +1,1 @@
+target/
diff --git a/examples/wasi-http-rust/Cargo.lock b/examples/wasi-http-rust/Cargo.lock
new file mode 100644
index 0000000000..dedc606b43
--- /dev/null
+++ b/examples/wasi-http-rust/Cargo.lock
@@ -0,0 +1,583 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 3
+
+[[package]]
+name = "anyhow"
+version = "1.0.75"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
+
+[[package]]
+name = "async-trait"
+version = "0.1.74"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.38",
+]
+
+[[package]]
+name = "autocfg"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
+
+[[package]]
+name = "bitflags"
+version = "2.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b4682ae6287fcf752ecaabbfcc7b6f9b72aa33933dc23a554d853aea8eea8635"
+
+[[package]]
+name = "bytes"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2bd12c1caf447e69cd4528f47f94d203fd2582878ecb9e9465484c4148a8223"
+
+[[package]]
+name = "equivalent"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5"
+
+[[package]]
+name = "fnv"
+version = "1.0.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
+
+[[package]]
+name = "form_urlencoded"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a62bc1cf6f830c2ec14a513a9fb124d0a213a629668a4186f329db21fe045652"
+dependencies = [
+ "percent-encoding",
+]
+
+[[package]]
+name = "futures"
+version = "0.3.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23342abe12aba583913b2e62f22225ff9c950774065e4bfb61a19cd9770fec40"
+dependencies = [
+ "futures-channel",
+ "futures-core",
+ "futures-executor",
+ "futures-io",
+ "futures-sink",
+ "futures-task",
+ "futures-util",
+]
+
+[[package]]
+name = "futures-channel"
+version = "0.3.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "955518d47e09b25bbebc7a18df10b81f0c766eaf4c4f1cccef2fca5f2a4fb5f2"
+dependencies = [
+ "futures-core",
+ "futures-sink",
+]
+
+[[package]]
+name = "futures-core"
+version = "0.3.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4bca583b7e26f571124fe5b7561d49cb2868d79116cfa0eefce955557c6fee8c"
+
+[[package]]
+name = "futures-executor"
+version = "0.3.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ccecee823288125bd88b4d7f565c9e58e41858e47ab72e8ea2d64e93624386e0"
+dependencies = [
+ "futures-core",
+ "futures-task",
+ "futures-util",
+]
+
+[[package]]
+name = "futures-io"
+version = "0.3.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4fff74096e71ed47f8e023204cfd0aa1289cd54ae5430a9523be060cdb849964"
+
+[[package]]
+name = "futures-macro"
+version = "0.3.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.38",
+]
+
+[[package]]
+name = "futures-sink"
+version = "0.3.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f43be4fe21a13b9781a69afa4985b0f6ee0e1afab2c6f454a8cf30e2b2237b6e"
+
+[[package]]
+name = "futures-task"
+version = "0.3.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "76d3d132be6c0e6aa1534069c705a74a5997a356c0dc2f86a47765e5617c5b65"
+
+[[package]]
+name = "futures-util"
+version = "0.3.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "26b01e40b772d54cf6c6d721c1d1abd0647a0106a12ecaa1c186273392a69533"
+dependencies = [
+ "futures-channel",
+ "futures-core",
+ "futures-io",
+ "futures-macro",
+ "futures-sink",
+ "futures-task",
+ "memchr",
+ "pin-project-lite",
+ "pin-utils",
+ "slab",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.14.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7dfda62a12f55daeae5015f81b0baea145391cb4520f86c248fc615d72640d12"
+
+[[package]]
+name = "heck"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
+dependencies = [
+ "unicode-segmentation",
+]
+
+[[package]]
+name = "http"
+version = "0.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bd6effc99afb63425aff9b05836f029929e345a6148a14b7ecd5ab67af944482"
+dependencies = [
+ "bytes",
+ "fnv",
+ "itoa",
+]
+
+[[package]]
+name = "http-rust"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "http",
+ "serde",
+ "spin-sdk",
+]
+
+[[package]]
+name = "id-arena"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "25a2bc672d1148e28034f176e01fffebb08b35768468cc954630da77a1449005"
+
+[[package]]
+name = "indexmap"
+version = "2.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8adf3ddd720272c6ea8bf59463c04e0f93d0bbf7c5439b691bca2987e0270897"
+dependencies = [
+ "equivalent",
+ "hashbrown",
+ "serde",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38"
+
+[[package]]
+name = "leb128"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "884e2677b40cc8c339eaefcb701c32ef1fd2493d71118dc0ca4b6a736c93bd67"
+
+[[package]]
+name = "log"
+version = "0.4.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f"
+
+[[package]]
+name = "memchr"
+version = "2.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f665ee40bc4a3c5590afb1e9677db74a508659dfd71e126420da8274909a0167"
+
+[[package]]
+name = "once_cell"
+version = "1.18.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d"
+
+[[package]]
+name = "percent-encoding"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b2a4787296e9989611394c33f193f676704af1686e70b8f8033ab5ba9a35a94"
+
+[[package]]
+name = "pin-project-lite"
+version = "0.2.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8afb450f006bf6385ca15ef45d71d2288452bc3683ce2e2cacc0d18e4be60b58"
+
+[[package]]
+name = "pin-utils"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.69"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "134c189feb4956b20f6f547d2cf727d4c0fe06722b20a0eec87ed445a97f92da"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.33"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "routefinder"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "94f8f99b10dedd317514253dda1fa7c14e344aac96e1f78149a64879ce282aca"
+dependencies = [
+ "smartcow",
+ "smartstring",
+]
+
+[[package]]
+name = "ryu"
+version = "1.0.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741"
+
+[[package]]
+name = "semver"
+version = "1.0.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "836fa6a3e1e547f9a2c4040802ec865b5d85f4014efe00555d7090a3dcaa1090"
+
+[[package]]
+name = "serde"
+version = "1.0.188"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf9e0fcba69a370eed61bcf2b728575f726b50b55cba78064753d708ddc7549e"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.188"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4eca7ac642d82aa35b60049a6eccb4be6be75e599bd2e9adb5f875a737654af2"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.38",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.107"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6b420ce6e3d8bd882e9b243c6eed35dbc9a6110c9769e74b584e0d68d1f20c65"
+dependencies = [
+ "itoa",
+ "ryu",
+ "serde",
+]
+
+[[package]]
+name = "slab"
+version = "0.4.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "smallvec"
+version = "1.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "942b4a808e05215192e39f4ab80813e599068285906cc91aa64f923db842bd5a"
+
+[[package]]
+name = "smartcow"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "656fcb1c1fca8c4655372134ce87d8afdf5ec5949ebabe8d314be0141d8b5da2"
+dependencies = [
+ "smartstring",
+]
+
+[[package]]
+name = "smartstring"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3fb72c633efbaa2dd666986505016c32c3044395ceaf881518399d2f4127ee29"
+dependencies = [
+ "autocfg",
+ "static_assertions",
+ "version_check",
+]
+
+[[package]]
+name = "spdx"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b19b32ed6d899ab23174302ff105c1577e45a06b08d4fe0a9dd13ce804bbbf71"
+dependencies = [
+ "smallvec",
+]
+
+[[package]]
+name = "spin-macro"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "bytes",
+ "http",
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+]
+
+[[package]]
+name = "spin-sdk"
+version = "2.0.0-pre0"
+dependencies = [
+ "anyhow",
+ "async-trait",
+ "bytes",
+ "form_urlencoded",
+ "futures",
+ "http",
+ "once_cell",
+ "routefinder",
+ "serde",
+ "serde_json",
+ "spin-macro",
+ "thiserror",
+ "wit-bindgen",
+]
+
+[[package]]
+name = "static_assertions"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
+
+[[package]]
+name = "syn"
+version = "1.0.109"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "syn"
+version = "2.0.38"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e96b79aaa137db8f61e26363a0c9b47d8b4ec75da28b7d1d614c2303e232408b"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "thiserror"
+version = "1.0.49"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1177e8c6d7ede7afde3585fd2513e611227efd6481bd78d2e82ba1ce16557ed4"
+dependencies = [
+ "thiserror-impl",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "1.0.49"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "10712f02019e9288794769fba95cd6847df9874d49d871d062172f9dd41bc4cc"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.38",
+]
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
+
+[[package]]
+name = "unicode-segmentation"
+version = "1.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1dd624098567895118886609431a7c3b8f516e41d30e0643f03d94592a147e36"
+
+[[package]]
+name = "unicode-xid"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f962df74c8c05a667b5ee8bcf162993134c104e96440b663c8daa176dc772d8c"
+
+[[package]]
+name = "version_check"
+version = "0.9.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
+
+[[package]]
+name = "wasm-encoder"
+version = "0.35.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ca90ba1b5b0a70d3d49473c5579951f3bddc78d47b59256d2f9d4922b150aca"
+dependencies = [
+ "leb128",
+]
+
+[[package]]
+name = "wasm-metadata"
+version = "0.10.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "14abc161bfda5b519aa229758b68f2a52b45a12b993808665c857d1a9a00223c"
+dependencies = [
+ "anyhow",
+ "indexmap",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "spdx",
+ "wasm-encoder",
+ "wasmparser",
+]
+
+[[package]]
+name = "wasmparser"
+version = "0.115.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e06c0641a4add879ba71ccb3a1e4278fd546f76f1eafb21d8f7b07733b547cd5"
+dependencies = [
+ "indexmap",
+ "semver",
+]
+
+[[package]]
+name = "wit-bindgen"
+version = "0.12.0"
+source = "git+https://github.com/bytecodealliance/wit-bindgen?rev=2405a79c74c5d61b9bc88c378d475c6c21ed6a9f#2405a79c74c5d61b9bc88c378d475c6c21ed6a9f"
+dependencies = [
+ "bitflags",
+ "wit-bindgen-rust-macro",
+]
+
+[[package]]
+name = "wit-bindgen-core"
+version = "0.12.0"
+source = "git+https://github.com/bytecodealliance/wit-bindgen?rev=2405a79c74c5d61b9bc88c378d475c6c21ed6a9f#2405a79c74c5d61b9bc88c378d475c6c21ed6a9f"
+dependencies = [
+ "anyhow",
+ "wit-component",
+ "wit-parser",
+]
+
+[[package]]
+name = "wit-bindgen-rust"
+version = "0.12.0"
+source = "git+https://github.com/bytecodealliance/wit-bindgen?rev=2405a79c74c5d61b9bc88c378d475c6c21ed6a9f#2405a79c74c5d61b9bc88c378d475c6c21ed6a9f"
+dependencies = [
+ "anyhow",
+ "heck",
+ "wasm-metadata",
+ "wit-bindgen-core",
+ "wit-component",
+]
+
+[[package]]
+name = "wit-bindgen-rust-macro"
+version = "0.12.0"
+source = "git+https://github.com/bytecodealliance/wit-bindgen?rev=2405a79c74c5d61b9bc88c378d475c6c21ed6a9f#2405a79c74c5d61b9bc88c378d475c6c21ed6a9f"
+dependencies = [
+ "anyhow",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.38",
+ "wit-bindgen-core",
+ "wit-bindgen-rust",
+ "wit-component",
+]
+
+[[package]]
+name = "wit-component"
+version = "0.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c1bc644bb4205a2ee74035e5d35958777575fa4c6dd38ce7226c7680be2861c1"
+dependencies = [
+ "anyhow",
+ "bitflags",
+ "indexmap",
+ "log",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "wasm-encoder",
+ "wasm-metadata",
+ "wasmparser",
+ "wit-parser",
+]
+
+[[package]]
+name = "wit-parser"
+version = "0.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d08c9557c65c428ac18a3cce80bf2527dbec24ab06639642c7db73f2c7613f93"
+dependencies = [
+ "anyhow",
+ "id-arena",
+ "indexmap",
+ "log",
+ "semver",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "unicode-xid",
+]
diff --git a/examples/wasi-http-rust/Cargo.toml b/examples/wasi-http-rust/Cargo.toml
new file mode 100644
index 0000000000..afad911a21
--- /dev/null
+++ b/examples/wasi-http-rust/Cargo.toml
@@ -0,0 +1,15 @@
+[package]
+name = "http-rust"
+version = "0.1.0"
+edition = "2021"
+
+[lib]
+crate-type = ["cdylib"]
+
+[dependencies]
+anyhow = "1"
+http = "0.2.9"
+serde = { version = "1.0", features = ["derive"] }
+spin-sdk = { path = "../../sdk/rust" }
+
+[workspace]
diff --git a/examples/wasi-http-rust/spin.toml b/examples/wasi-http-rust/spin.toml
new file mode 100644
index 0000000000..46ed20d286
--- /dev/null
+++ b/examples/wasi-http-rust/spin.toml
@@ -0,0 +1,17 @@
+spin_manifest_version = "1"
+authors = ["Fermyon Engineering <engineering@fermyon.com>"]
+description = "A simple application that returns hello."
+name = "spin-hello-world"
+trigger = { type = "http" }
+version = "1.0.0"
+
+[[component]]
+id = "hello"
+source = "target/wasm32-wasi/release/http_rust.wasm"
+description = "A simple component that returns hello."
+[component.trigger]
+route = "/hello"
+executor = { type = "wasi" }
+[component.build]
+command = "cargo build --target wasm32-wasi --release"
+watch = ["src/**/*.rs", "Cargo.toml"]
diff --git a/examples/wasi-http-rust/src/lib.rs b/examples/wasi-http-rust/src/lib.rs
new file mode 100644
index 0000000000..d01241ace0
--- /dev/null
+++ b/examples/wasi-http-rust/src/lib.rs
@@ -0,0 +1,13 @@
+use spin_sdk::http::{IntoResponse, Json, Response};
+use spin_sdk::wasi_http_component;
+
+#[derive(serde::Deserialize, Debug)]
+struct Greeted {
+ name: String,
+}
+
+/// A simple Spin HTTP component.
+#[wasi_http_component]
+async fn hello_world(req: http::Request<Json<Greeted>>) -> anyhow::Result<impl IntoResponse> {
+ Ok(Response::new(200, format!("Hello, {}", req.body().name)))
+}
diff --git a/sdk/rust/Cargo.toml b/sdk/rust/Cargo.toml
index 4f7c2fb2e2..16736b477e 100644
--- a/sdk/rust/Cargo.toml
+++ b/sdk/rust/Cargo.toml
@@ -10,22 +10,24 @@ name = "spin_sdk"
[dependencies]
anyhow = "1"
-bytes = "1"
+async-trait = "0.1.74"
form_urlencoded = "1.0"
-http_types = { package = "http", version = "0.2" }
spin-macro = { path = "macro" }
thiserror = "1.0.37"
# Use a sha commit for now to include https://github.com/bytecodealliance/wit-bindgen/pull/693
# Once wit-bindgen 0.13 is released we can move to that version.
wit-bindgen = { git = "https://github.com/bytecodealliance/wit-bindgen", rev = "2405a79c74c5d61b9bc88c378d475c6c21ed6a9f" }
routefinder = "0.5.3"
-serde_json = { version = "1.0.96", optional = true }
-serde = { version = "1.0.163", optional = true }
once_cell = "1.18.0"
futures = "0.3.28"
+serde_json = { version = "1.0.96", optional = true }
+serde = { version = "1.0.163", optional = true }
+hyperium = { package = "http", version = "0.2", optional = true }
+bytes = { version = "1", optional = true }
[features]
-default = ["export-sdk-language"]
+default = ["export-sdk-language", "http", "json"]
+http = ["dep:hyperium", "dep:bytes"]
export-sdk-language = []
json = ["dep:serde", "dep:serde_json"]
experimental = []
diff --git a/sdk/rust/macro/src/lib.rs b/sdk/rust/macro/src/lib.rs
index dac4b6d260..e98acbf2c4 100644
--- a/sdk/rust/macro/src/lib.rs
+++ b/sdk/rust/macro/src/lib.rs
@@ -15,143 +15,50 @@ pub fn http_component(_attr: TokenStream, item: TokenStream) -> TokenStream {
mod __spin_http {
#preamble
impl self::exports::fermyon::spin::inbound_http::Guest for Spin {
- // Implement the `handler` entrypoint for Spin HTTP components.
fn handle_request(req: self::exports::fermyon::spin::inbound_http::Request) -> self::exports::fermyon::spin::inbound_http::Response {
- match super::#func_name(req.try_into().expect("cannot convert from Spin HTTP request")) {
- Ok(resp) => resp.try_into().expect("cannot convert to Spin HTTP response"),
- Err(error) => {
- let body = error.to_string();
- eprintln!("Handler returned an error: {}", body);
- let mut source = error.source();
- while let Some(s) = source {
- eprintln!(" caused by: {}", s);
- source = s.source();
- }
- self::exports::fermyon::spin::inbound_http::Response {
- status: 500,
- headers: None,
- body: Some(body.as_bytes().to_vec()),
- }
- },
- }
+ let req: ::spin_sdk::http::Request = ::std::convert::Into::into(req);
+ let resp = match ::spin_sdk::http::conversions::TryFromRequest::try_from_request(req) {
+ ::std::result::Result::Ok(req) => ::spin_sdk::http::IntoResponse::into_response(super::#func_name(req)),
+ ::std::result::Result::Err(e) => ::spin_sdk::http::IntoResponse::into_response(e),
+ };
+ ::std::convert::Into::into(resp)
}
}
- mod inbound_http_helpers {
- use super::fermyon::spin::http_types as spin_http_types;
-
- impl TryFrom<spin_http_types::Request> for http::Request<Option<bytes::Bytes>> {
- type Error = anyhow::Error;
-
- fn try_from(spin_req: spin_http_types::Request) -> Result<Self, Self::Error> {
- let mut http_req = http::Request::builder()
- .method(spin_req.method.clone())
- .uri(&spin_req.uri);
-
- append_request_headers(&mut http_req, &spin_req)?;
-
- let body = match spin_req.body {
- Some(b) => b.to_vec(),
- None => Vec::new(),
- };
-
- let body = Some(bytes::Bytes::from(body));
-
- Ok(http_req.body(body)?)
- }
- }
-
- impl From<spin_http_types::Method> for http::Method {
- fn from(spin_method: spin_http_types::Method) -> Self {
- match spin_method {
- spin_http_types::Method::Get => http::Method::GET,
- spin_http_types::Method::Post => http::Method::POST,
- spin_http_types::Method::Put => http::Method::PUT,
- spin_http_types::Method::Delete => http::Method::DELETE,
- spin_http_types::Method::Patch => http::Method::PATCH,
- spin_http_types::Method::Head => http::Method::HEAD,
- spin_http_types::Method::Options => http::Method::OPTIONS,
- }
- }
- }
-
- fn append_request_headers(
- http_req: &mut http::request::Builder,
- spin_req: &spin_http_types::Request,
- ) -> anyhow::Result<()> {
- let headers = http_req.headers_mut().unwrap();
- for (k, v) in &spin_req.headers {
- headers.append(
- <http::header::HeaderName as std::str::FromStr>::from_str(k)?,
- http::header::HeaderValue::from_str(v)?,
- );
- }
-
- Ok(())
- }
-
- impl TryFrom<spin_http_types::Response> for http::Response<Option<bytes::Bytes>> {
- type Error = anyhow::Error;
-
- fn try_from(spin_res: spin_http_types::Response) -> Result<Self, Self::Error> {
- let mut http_res = http::Response::builder().status(spin_res.status);
- append_response_headers(&mut http_res, spin_res.clone())?;
-
- let body = match spin_res.body {
- Some(b) => b.to_vec(),
- None => Vec::new(),
- };
- let body = Some(bytes::Bytes::from(body));
-
- Ok(http_res.body(body)?)
+ impl ::std::convert::From<self::fermyon::spin::http_types::Request> for ::spin_sdk::http::Request {
+ fn from(req: self::fermyon::spin::http_types::Request) -> Self {
+ Self {
+ method: ::std::convert::Into::into(req.method),
+ uri: req.uri,
+ params: req.params,
+ headers: req.headers,
+ body: req.body
}
}
+ }
- fn append_response_headers(
- http_res: &mut http::response::Builder,
- spin_res: spin_http_types::Response,
- ) -> anyhow::Result<()> {
- let headers = http_res.headers_mut().unwrap();
- for (k, v) in spin_res.headers.unwrap() {
- headers.append(
- <http::header::HeaderName as ::std::str::FromStr>::from_str(&k)?,
- http::header::HeaderValue::from_str(&v)?,
- );
+ impl ::std::convert::From<self::fermyon::spin::http_types::Method> for ::spin_sdk::http::Method {
+ fn from(method: self::fermyon::spin::http_types::Method) -> Self {
+ match method {
+ self::fermyon::spin::http_types::Method::Get => Self::Get,
+ self::fermyon::spin::http_types::Method::Post => Self::Post,
+ self::fermyon::spin::http_types::Method::Put => Self::Put,
+ self::fermyon::spin::http_types::Method::Patch => Self::Patch,
+ self::fermyon::spin::http_types::Method::Delete => Self::Delete,
+ self::fermyon::spin::http_types::Method::Head => Self::Head,
+ self::fermyon::spin::http_types::Method::Options => Self::Options,
}
-
- Ok(())
}
+ }
- impl TryFrom<http::Response<Option<bytes::Bytes>>> for spin_http_types::Response {
- type Error = anyhow::Error;
-
- fn try_from(
- http_res: http::Response<Option<bytes::Bytes>>,
- ) -> Result<Self, Self::Error> {
- let status = http_res.status().as_u16();
- let headers = Some(outbound_headers(http_res.headers())?);
- let body = http_res.body().as_ref().map(|b| b.to_vec());
-
- Ok(spin_http_types::Response {
- status,
- headers,
- body,
- })
+ impl ::std::convert::From<::spin_sdk::http::Response> for self::fermyon::spin::http_types::Response {
+ fn from(resp: ::spin_sdk::http::Response) -> Self {
+ Self {
+ status: resp.status,
+ headers: resp.headers,
+ body: resp.body,
}
}
-
- fn outbound_headers(hm: &http::HeaderMap) -> anyhow::Result<Vec<(String, String)>> {
- let mut res = Vec::new();
-
- for (k, v) in hm {
- res.push((
- k.as_str().to_string(),
- std::str::from_utf8(v.as_bytes())?.to_string(),
- ));
- }
-
- Ok(res)
- }
}
}
)
@@ -186,263 +93,103 @@ pub fn redis_component(_attr: TokenStream, item: TokenStream) -> TokenStream {
}
/// The entrypoint to a WASI HTTP component written in Rust.
+///
+/// Functions annotated with this attribute can be of two forms:
+/// * Request/Response
+/// * Input/Output Params
+///
+/// When in doubt prefer the Request/Response variant unless streaming response bodies is something you need.
+///
+/// ### Request/Response
+///
+/// This form has the same shape as the `http_component` handlers. The only difference is that the underlying handling
+/// happens through the `wasi-http` interface instead of the Spin specific `http` interface and thus requests are
+/// anything that implements `spin_sdk::wasi_http::conversions::TryFromIncomingRequest` and responses are anything that
+/// implements `spin_sdk::http::IntoResponse`.
+///
+/// For example:
+/// ```ignore
+/// #[wasi_http_component]
+/// async fn my_handler(request: IncomingRequest) -> anyhow::Result<impl IntoResponse> {
+/// // Your logic goes here
+/// }
+/// ```
+///
+/// ### Input/Output Params
+///
+/// Input/Output functions allow for streaming HTTP bodies. They are expected generally to be in the form:
+/// ```ignore
+/// #[wasi_http_component]
+/// async fn my_handler(request: IncomingRequest, response_out: ResponseOutparam) {
+/// // Your logic goes here
+/// }
+/// ```
+///
+/// The `request` param can be anything that implements `spin_sdk::wasi_http::conversions::TryFromIncomingRequest`.
+/// This includes all types that implement `spin_sdk::http::conversions::TryIntoRequest` (which may be more convenient to use
+/// when you don't need streaming request bodies).
#[proc_macro_attribute]
pub fn wasi_http_component(_attr: TokenStream, item: TokenStream) -> TokenStream {
let func = syn::parse_macro_input!(item as syn::ItemFn);
let func_name = &func.sig.ident;
let preamble = preamble(Export::WasiHttp);
+ let is_native_wasi_http_handler = func.sig.inputs.len() == 2;
+ let await_postfix = func.sig.asyncness.map(|_| quote!(.await));
+ let handler = if is_native_wasi_http_handler {
+ quote! { super::#func_name(req, response_out)#await_postfix }
+ } else {
+ quote! { handle_response(response_out, super::#func_name(req)#await_postfix).await }
+ };
quote!(
#func
- // We export wasi here since `wit-bindgen` currently has no way of using types
- // declared somewhere else as part of its generated code. If we want users to be able to
- // use `wasi-http` types, they have to be generated in this macro. This should be solved once
- // `with` is supported in wit-bindgen [ref: https://github.com/bytecodealliance/wit-bindgen/issues/694].
- use __spin_wasi_http::wasi;
mod __spin_wasi_http {
#preamble
- use exports::wasi::http::incoming_handler;
- use wasi::http::types::{IncomingRequest, ResponseOutparam};
-
- impl incoming_handler::Guest for Spin {
- fn handle(request: IncomingRequest, response_out: ResponseOutparam) {
- let future = async move {
- if let Err(e) = super::#func_name(request, response_out).await {
- eprintln!("Handler returned an error: {e}");
+ impl self::exports::wasi::http::incoming_handler::Guest for Spin {
+ fn handle(request: wasi::http::types::IncomingRequest, response_out: self::wasi::http::types::ResponseOutparam) {
+ let request: ::spin_sdk::wasi_http::IncomingRequest = ::std::convert::Into::into(request);
+ let response_out: ::spin_sdk::wasi_http::ResponseOutparam = ::std::convert::Into::into(response_out);
+ ::spin_sdk::wasi_http::run(async move {
+ match ::spin_sdk::wasi_http::conversions::TryFromIncomingRequest::try_from_incoming_request(request).await {
+ ::std::result::Result::Ok(req) => #handler,
+ ::std::result::Result::Err(e) => handle_response(response_out, e).await,
}
- };
- futures::pin_mut!(future);
- super::executor::run(future);
+ });
}
}
- }
-
- mod executor {
- use {
- super::wasi::{
- http::{
- outgoing_handler,
- types::{
- self, IncomingBody, IncomingRequest, IncomingResponse, OutgoingBody,
- OutgoingRequest, OutgoingResponse,
- },
- },
- io::{
- poll,
- streams::{InputStream, OutputStream, StreamError},
- },
- },
- anyhow::{anyhow, Error, Result},
- futures::{future, sink, stream, Sink, Stream},
- std::{
- cell::RefCell,
- future::Future,
- mem,
- pin::Pin,
- rc::Rc,
- sync::{Arc, Mutex},
- task::{Context, Poll, Wake, Waker},
- },
- };
-
- const READ_SIZE: u64 = 16 * 1024;
-
- static WAKERS: Mutex<Vec<(poll::Pollable, Waker)>> = Mutex::new(Vec::new());
-
- /// Run the specified future on an executor based on `wasi::io/poll/poll-list`, blocking until it
- /// yields a result.
- pub fn run<T>(mut future: Pin<&mut impl Future<Output = T>>) -> T {
- struct DummyWaker;
- impl Wake for DummyWaker {
- fn wake(self: Arc<Self>) {}
+ async fn handle_response<R: ::spin_sdk::http::IntoResponse>(response_out: ::spin_sdk::wasi_http::ResponseOutparam, resp: R) {
+ let mut response = ::spin_sdk::http::IntoResponse::into_response(resp);
+ let body = response.body.take().unwrap_or_default();
+ let response = ::std::convert::Into::into(response);
+ if let Err(e) = ::spin_sdk::wasi_http::ResponseOutparam::set_with_body(response_out, response, body).await {
+ eprintln!("Could not set `ResponseOutparam`: {e}");
}
-
- let waker = Arc::new(DummyWaker).into();
-
- loop {
- match future.as_mut().poll(&mut Context::from_waker(&waker)) {
- Poll::Pending => {
- let mut new_wakers = Vec::new();
-
- let wakers = mem::take::<Vec<_>>(&mut WAKERS.lock().unwrap());
-
- assert!(!wakers.is_empty());
-
- let pollables = wakers
- .iter()
- .map(|(pollable, _)| pollable)
- .collect::<Vec<_>>();
-
- let mut ready = vec![false; wakers.len()];
-
- for index in poll::poll_list(&pollables) {
- ready[usize::try_from(index).unwrap()] = true;
- }
-
- for (ready, (pollable, waker)) in ready.into_iter().zip(wakers) {
- if ready {
- waker.wake()
- } else {
- new_wakers.push((pollable, waker));
- }
- }
-
- *WAKERS.lock().unwrap() = new_wakers;
- }
- Poll::Ready(result) => break result,
- }
- }
- }
-
- /// Construct a `Sink` which writes chunks to the body of the specified response.
- pub fn outgoing_response_body(response: &OutgoingResponse) -> impl Sink<Vec<u8>, Error = Error> {
- outgoing_body(response.write().expect("response should be writable"))
}
- fn outgoing_body(body: OutgoingBody) -> impl Sink<Vec<u8>, Error = Error> {
- struct Outgoing(Option<(OutputStream, OutgoingBody)>);
-
- impl Drop for Outgoing {
- fn drop(&mut self) {
- if let Some((stream, body)) = self.0.take() {
- drop(stream);
- OutgoingBody::finish(body, None);
- }
- }
+ impl From<self::wasi::http::types::IncomingRequest> for ::spin_sdk::wasi_http::IncomingRequest {
+ fn from(req: self::wasi::http::types::IncomingRequest) -> Self {
+ let req = ::std::mem::ManuallyDrop::new(req);
+ unsafe { Self::from_handle(req.handle()) }
}
-
- let stream = body.write().expect("response body should be writable");
- let pair = Rc::new(RefCell::new(Outgoing(Some((stream, body)))));
-
- sink::unfold((), {
- move |(), chunk: Vec<u8>| {
- future::poll_fn({
- let mut offset = 0;
- let mut flushing = false;
- let pair = pair.clone();
-
- move |context| {
- let pair = pair.borrow();
- let (stream, _) = &pair.0.as_ref().unwrap();
-
- loop {
- match stream.check_write() {
- Ok(0) => {
- WAKERS
- .lock()
- .unwrap()
- .push((stream.subscribe(), context.waker().clone()));
-
- break Poll::Pending;
- }
- Ok(count) => {
- if offset == chunk.len() {
- if flushing {
- break Poll::Ready(Ok(()));
- } else {
- stream.flush().expect("stream should be flushable");
- flushing = true;
- }
- } else {
- let count =
- usize::try_from(count).unwrap().min(chunk.len() - offset);
-
- match stream.write(&chunk[offset..][..count]) {
- Ok(()) => {
- offset += count;
- }
- Err(_) => break Poll::Ready(Err(anyhow!("I/O error"))),
- }
- }
- }
- Err(_) => break Poll::Ready(Err(anyhow!("I/O error"))),
- }
- }
- }
- })
- }
- })
- }
-
- /// Send the specified request and return the response.
- pub fn outgoing_request_send(
- request: OutgoingRequest,
- ) -> impl Future<Output = Result<IncomingResponse, types::Error>> {
- future::poll_fn({
- let response = outgoing_handler::handle(request, None);
-
- move |context| match &response {
- Ok(response) => {
- if let Some(response) = response.get() {
- Poll::Ready(response.unwrap())
- } else {
- WAKERS
- .lock()
- .unwrap()
- .push((response.subscribe(), context.waker().clone()));
- Poll::Pending
- }
- }
- Err(error) => Poll::Ready(Err(error.clone())),
- }
- })
- }
-
- /// Return a `Stream` from which the body of the specified request may be read.
- pub fn incoming_request_body(request: IncomingRequest) -> impl Stream<Item = Result<Vec<u8>>> {
- incoming_body(request.consume().expect("request should be consumable"))
}
- /// Return a `Stream` from which the body of the specified response may be read.
- pub fn incoming_response_body(response: IncomingResponse) -> impl Stream<Item = Result<Vec<u8>>> {
- incoming_body(response.consume().expect("response should be consumable"))
+ impl From<::spin_sdk::wasi_http::OutgoingResponse> for self::wasi::http::types::OutgoingResponse {
+ fn from(resp: ::spin_sdk::wasi_http::OutgoingResponse) -> Self {
+ unsafe { Self::from_handle(resp.into_handle()) }
+ }
}
- fn incoming_body(body: IncomingBody) -> impl Stream<Item = Result<Vec<u8>>> {
- struct Incoming(Option<(InputStream, IncomingBody)>);
-
- impl Drop for Incoming {
- fn drop(&mut self) {
- if let Some((stream, body)) = self.0.take() {
- drop(stream);
- IncomingBody::finish(body);
- }
- }
+ impl From<self::wasi::http::types::ResponseOutparam> for ::spin_sdk::wasi_http::ResponseOutparam {
+ fn from(resp: self::wasi::http::types::ResponseOutparam) -> Self {
+ let resp = ::std::mem::ManuallyDrop::new(resp);
+ unsafe { Self::from_handle(resp.handle()) }
}
-
- stream::poll_fn({
- let stream = body.stream().expect("response body should be readable");
- let pair = Incoming(Some((stream, body)));
-
- move |context| {
- if let Some((stream, _)) = &pair.0 {
- match stream.read(READ_SIZE) {
- Ok(buffer) => {
- if buffer.is_empty() {
- WAKERS
- .lock()
- .unwrap()
- .push((stream.subscribe(), context.waker().clone()));
- Poll::Pending
- } else {
- Poll::Ready(Some(Ok(buffer)))
- }
- }
- Err(StreamError::Closed) => Poll::Ready(None),
- Err(StreamError::LastOperationFailed(error)) => {
- Poll::Ready(Some(Err(anyhow!("{}", error.to_debug_string()))))
- }
- }
- } else {
- Poll::Ready(None)
- }
- }
- })
}
}
+
)
- .into()
+ .into()
}
#[derive(Copy, Clone)]
diff --git a/sdk/rust/readme.md b/sdk/rust/readme.md
index 352efeb686..3702b5c5f5 100644
--- a/sdk/rust/readme.md
+++ b/sdk/rust/readme.md
@@ -18,11 +18,8 @@ use spin_sdk::{
/// A simple Spin HTTP component.
#[http_component]
fn hello_world(req: Request) -> Result<Response> {
- println!("{:?}", req.headers());
- Ok(http::Response::builder()
- .status(200)
- .header("foo", "bar")
- .body(Some("Hello, Fermyon!".into()))?)
+ println!("{:?}", req.headers);
+ Ok(Response::new_with_headers(200, &[] "Hello, Fermyon!"))
}
```
@@ -31,9 +28,10 @@ The important things to note in the function above:
- the `spin_sdk::http_component` macro — this marks the function as the
entrypoint for the Spin component
- the function signature — `fn hello_world(req: Request) -> Result<Response>` —
- the Spin HTTP component uses the HTTP objects from the popular Rust crate
- [`http`](https://crates.io/crates/http), and the request and response bodies
- are optionally using [`bytes::Bytes`](https://crates.io/crates/bytes)
+`req` can be any number of types including the built in `Request` type or
+the `http::Request` from the popular `http` crate. Likewise, the response type
+can be many things including the built in `Response` type or the `http::Response` type
+from the `http` crate.
### Making outbound HTTP requests
@@ -43,11 +41,11 @@ server, modifies the result, then returns it:
```rust
#[http_component]
fn hello_world(_req: Request) -> Result<Response> {
- let mut res = spin_sdk::http::send(
+ let mut res: http::Response<()> = spin_sdk::http::send(
http::Request::builder()
.method("GET")
.uri("https://fermyon.com")
- .body(None)?,
+ .body(())?,
)?;
res.headers_mut()
diff --git a/sdk/rust/src/http.rs b/sdk/rust/src/http.rs
new file mode 100644
index 0000000000..5ee37acfed
--- /dev/null
+++ b/sdk/rust/src/http.rs
@@ -0,0 +1,171 @@
+use std::fmt::Display;
+use std::hash::Hash;
+
+use crate::wit::v1::{http::send_request, http_types::HttpError};
+
+/// Traits for converting between the various types
+pub mod conversions;
+
+#[doc(inline)]
+pub use conversions::IntoResponse;
+
+#[doc(inline)]
+pub use crate::wit::v1::http_types::{Method, Request, Response};
+
+/// Perform an HTTP request getting back a response or an error
+pub fn send<I, O>(req: I) -> Result<O, SendError>
+where
+ I: TryInto<Request>,
+ I::Error: Into<Box<dyn std::error::Error + Send + Sync>> + 'static,
+ O: TryFrom<Response>,
+ O::Error: Into<Box<dyn std::error::Error + Send + Sync>> + 'static,
+{
+ let response = send_request(
+ &req.try_into()
+ .map_err(|e| SendError::RequestConversion(e.into()))?,
+ )
+ .map_err(SendError::Http)?;
+ response
+ .try_into()
+ .map_err(|e: O::Error| SendError::ResponseConversion(e.into()))
+}
+
+/// An error encountered when performing an HTTP request
+#[derive(thiserror::Error, Debug)]
+pub enum SendError {
+ /// Error converting to a request
+ #[error(transparent)]
+ RequestConversion(Box<dyn std::error::Error + Send + Sync>),
+ /// Error converting from a response
+ #[error(transparent)]
+ ResponseConversion(Box<dyn std::error::Error + Send + Sync>),
+ /// An HTTP error
+ #[error(transparent)]
+ Http(HttpError),
+}
+
+impl Display for Method {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(match self {
+ Method::Get => "GET",
+ Method::Post => "POST",
+ Method::Put => "PUT",
+ Method::Delete => "DELETE",
+ Method::Patch => "PATCH",
+ Method::Head => "HEAD",
+ Method::Options => "OPTIONS",
+ })
+ }
+}
+
+impl Hash for Method {
+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
+ core::mem::discriminant(self).hash(state);
+ }
+}
+
+impl Response {
+ /// Create a new response from a status and optional headers and body
+ pub fn new<S: conversions::IntoStatusCode, B: conversions::IntoBody>(
+ status: S,
+ body: B,
+ ) -> Self {
+ Self {
+ status: status.into_status_code(),
+ headers: None,
+ body: body.into_body(),
+ }
+ }
+
+ /// Create a new response from a status and optional headers and body
+ pub fn new_with_headers(
+ status: u16,
+ headers: Vec<(String, String)>,
+ body: Option<Vec<u8>>,
+ ) -> Self {
+ Self {
+ status,
+ headers: Some(headers),
+ body,
+ }
+ }
+}
+
+/// An error parsing a JSON body
+#[cfg(feature = "json")]
+#[derive(Debug)]
+pub struct JsonBodyError(serde_json::Error);
+
+#[cfg(feature = "json")]
+impl std::error::Error for JsonBodyError {}
+
+#[cfg(feature = "json")]
+impl Display for JsonBodyError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str("could not convert body to json")
+ }
+}
+
+/// An error when the body is not UTF-8
+#[derive(Debug)]
+pub struct NonUtf8BodyError;
+
+impl std::error::Error for NonUtf8BodyError {}
+
+impl Display for NonUtf8BodyError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str("body was expected to be utf8 but was not")
+ }
+}
+
+mod router;
+/// Exports HTTP Router items.
+pub use router::*;
+
+/// A Body extractor
+#[derive(Debug)]
+pub struct Body<T>(pub T);
+
+impl<T> std::ops::Deref for Body<T> {
+ type Target = T;
+
+ fn deref(&self) -> &Self::Target {
+ &self.0
+ }
+}
+
+/// A Json extractor
+#[derive(Debug)]
+pub struct Json<T>(pub T);
+
+impl<T> std::ops::Deref for Json<T> {
+ type Target = T;
+
+ fn deref(&self) -> &Self::Target {
+ &self.0
+ }
+}
+
+/// Helper functions for creating responses
+pub mod responses {
+ use super::Response;
+
+ /// Helper function to return a 404 Not Found response.
+ pub fn not_found() -> Response {
+ Response::new(404, "Not Found")
+ }
+
+ /// Helper function to return a 500 Internal Server Error response.
+ pub fn internal_server_error() -> Response {
+ Response::new(500, "Internal Server Error")
+ }
+
+ /// Helper function to return a 405 Method Not Allowed response.
+ pub fn method_not_allowed() -> Response {
+ Response::new(405, "Method Not Allowed")
+ }
+
+ pub(crate) fn bad_request(msg: Option<String>) -> Response {
+ Response::new(400, msg.map(|m| m.into_bytes()))
+ }
+}
diff --git a/sdk/rust/src/http/conversions.rs b/sdk/rust/src/http/conversions.rs
new file mode 100644
index 0000000000..631bc6549a
--- /dev/null
+++ b/sdk/rust/src/http/conversions.rs
@@ -0,0 +1,387 @@
+use crate::wit::v1::http::{Request, Response};
+
+use super::{responses, NonUtf8BodyError};
+
+/// A trait for any type that can be constructor from a `Request`
+pub trait TryFromRequest {
+ /// The error if the conversion fails
+ type Error;
+ /// Try to turn the request into the type
+ fn try_from_request(req: Request) -> Result<Self, Self::Error>
+ where
+ Self: Sized;
+}
+
+impl TryFromRequest for Request {
+ type Error = std::convert::Infallible;
+
+ fn try_from_request(req: Request) -> Result<Self, Self::Error>
+ where
+ Self: Sized,
+ {
+ Ok(req)
+ }
+}
+
+impl<R: TryNonRequestFromRequest> TryFromRequest for R {
+ type Error = R::Error;
+
+ fn try_from_request(req: Request) -> Result<Self, Self::Error>
+ where
+ Self: Sized,
+ {
+ TryNonRequestFromRequest::try_from_request(req)
+ }
+}
+
+/// A hack that allows us to do blanket impls for `T where T: TryFromRequest` for all types
+/// `T` *except* for `Request`.
+///
+/// This is useful in `wasi_http` where we want to implement `TryFromIncomingRequest` for all types that impl
+/// `TryFromRequest` with the exception of `Request` itself. This allows that implementation to first convert
+/// the `IncomingRequest` to a `Request` and then using this trait convert from `Request` to the given type.
+pub trait TryNonRequestFromRequest {
+ /// The error if the conversion fails
+ type Error;
+ /// Try to turn the request into the type
+ fn try_from_request(req: Request) -> Result<Self, Self::Error>
+ where
+ Self: Sized;
+}
+
+#[cfg(feature = "http")]
+impl<B: TryFromBody> TryNonRequestFromRequest for hyperium::Request<B> {
+ type Error = B::Error;
+ fn try_from_request(req: Request) -> Result<Self, Self::Error> {
+ let mut builder = hyperium::Request::builder().uri(req.uri).method(req.method);
+ for (n, v) in req.headers {
+ builder = builder.header(n, v);
+ }
+ Ok(builder.body(B::try_from_body(req.body)?).unwrap())
+ }
+}
+
+#[cfg(feature = "http")]
+impl From<super::Method> for hyperium::Method {
+ fn from(method: super::Method) -> Self {
+ match method {
+ super::Method::Get => hyperium::Method::GET,
+ super::Method::Post => hyperium::Method::POST,
+ super::Method::Put => hyperium::Method::PUT,
+ super::Method::Delete => hyperium::Method::DELETE,
+ super::Method::Patch => hyperium::Method::PATCH,
+ super::Method::Head => hyperium::Method::HEAD,
+ super::Method::Options => hyperium::Method::OPTIONS,
+ }
+ }
+}
+
+/// A trait for any type that can be turned into a `Response`
+pub trait IntoResponse {
+ /// Turn `self` into a `Response`
+ fn into_response(self) -> Response;
+}
+
+impl IntoResponse for Response {
+ fn into_response(self) -> Response {
+ self
+ }
+}
+
+#[cfg(feature = "http")]
+impl<B> IntoResponse for hyperium::Response<B>
+where
+ B: IntoBody,
+{
+ fn into_response(self) -> Response {
+ let headers = self
+ .headers()
+ .into_iter()
+ .map(|(n, v)| {
+ (
+ n.as_str().to_owned(),
+ String::from_utf8_lossy(v.as_bytes()).into_owned(),
+ )
+ })
+ .collect();
+ Response::new_with_headers(
+ self.status().as_u16(),
+ headers,
+ IntoBody::into_body(self.into_body()),
+ )
+ }
+}
+
+impl<R: IntoResponse, E: IntoResponse> IntoResponse for std::result::Result<R, E> {
+ fn into_response(self) -> Response {
+ match self {
+ Ok(r) => r.into_response(),
+ Err(e) => e.into_response(),
+ }
+ }
+}
+
+impl IntoResponse for anyhow::Error {
+ fn into_response(self) -> Response {
+ let body = self.to_string();
+ eprintln!("Handler returned an error: {}", body);
+ let mut source = self.source();
+ while let Some(s) = source {
+ eprintln!(" caused by: {}", s);
+ source = s.source();
+ }
+ Response {
+ status: 500,
+ headers: None,
+ body: Some(body.as_bytes().to_vec()),
+ }
+ }
+}
+
+impl IntoResponse for Box<dyn std::error::Error> {
+ fn into_response(self) -> Response {
+ let body = self.to_string();
+ eprintln!("Handler returned an error: {}", body);
+ let mut source = self.source();
+ while let Some(s) = source {
+ eprintln!(" caused by: {}", s);
+ source = s.source();
+ }
+ Response {
+ status: 500,
+ headers: None,
+ body: Some(body.as_bytes().to_vec()),
+ }
+ }
+}
+
+#[cfg(feature = "json")]
+impl IntoResponse for super::JsonBodyError {
+ fn into_response(self) -> Response {
+ responses::bad_request(Some(format!("failed to parse JSON body: {}", self.0)))
+ }
+}
+
+impl IntoResponse for NonUtf8BodyError {
+ fn into_response(self) -> Response {
+ responses::bad_request(Some(
+ "expected body to be a utf8 string but wasn't".to_owned(),
+ ))
+ }
+}
+
+impl IntoResponse for std::convert::Infallible {
+ fn into_response(self) -> Response {
+ unreachable!()
+ }
+}
+
+/// A trait for any type that can be turned into a `Response` status code
+pub trait IntoStatusCode {
+ /// Turn `self` into a status code
+ fn into_status_code(self) -> u16;
+}
+
+impl IntoStatusCode for u16 {
+ fn into_status_code(self) -> u16 {
+ self
+ }
+}
+
+#[cfg(feature = "http")]
+impl IntoStatusCode for hyperium::StatusCode {
+ fn into_status_code(self) -> u16 {
+ self.as_u16()
+ }
+}
+
+/// A trait for any type that can be turned into a `Response` body
+pub trait IntoBody {
+ /// Turn `self` into a `Response` body
+ fn into_body(self) -> Option<Vec<u8>>;
+}
+
+impl<T: IntoBody> IntoBody for Option<T> {
+ fn into_body(self) -> Option<Vec<u8>> {
+ self.and_then(|b| IntoBody::into_body(b))
+ }
+}
+
+impl IntoBody for Vec<u8> {
+ fn into_body(self) -> Option<Vec<u8>> {
+ Some(self)
+ }
+}
+
+#[cfg(feature = "http")]
+impl IntoBody for bytes::Bytes {
+ fn into_body(self) -> Option<Vec<u8>> {
+ Some(self.to_vec())
+ }
+}
+
+impl IntoBody for () {
+ fn into_body(self) -> Option<Vec<u8>> {
+ None
+ }
+}
+
+impl IntoBody for &str {
+ fn into_body(self) -> Option<Vec<u8>> {
+ Some(self.to_owned().into_bytes())
+ }
+}
+
+impl IntoBody for String {
+ fn into_body(self) -> Option<Vec<u8>> {
+ Some(self.to_owned().into_bytes())
+ }
+}
+
+/// A trait for converting from a body or failing
+pub trait TryFromBody {
+ /// The error encountered if conversion fails
+ type Error: IntoResponse;
+ /// Convert from a body to `Self` or fail
+ fn try_from_body(body: Option<Vec<u8>>) -> Result<Self, Self::Error>
+ where
+ Self: Sized;
+}
+
+impl<T: TryFromBody> TryFromBody for Option<T> {
+ type Error = T::Error;
+
+ fn try_from_body(body: Option<Vec<u8>>) -> Result<Self, Self::Error>
+ where
+ Self: Sized,
+ {
+ Ok(match body {
+ None => None,
+ Some(v) => Some(TryFromBody::try_from_body(Some(v))?),
+ })
+ }
+}
+
+impl<T: FromBody> TryFromBody for T {
+ type Error = std::convert::Infallible;
+
+ fn try_from_body(body: Option<Vec<u8>>) -> Result<Self, Self::Error>
+ where
+ Self: Sized,
+ {
+ Ok(FromBody::from_body(body))
+ }
+}
+
+impl TryFromBody for String {
+ type Error = NonUtf8BodyError;
+
+ fn try_from_body(body: Option<Vec<u8>>) -> Result<Self, Self::Error>
+ where
+ Self: Sized,
+ {
+ String::from_utf8(body.unwrap_or_default()).map_err(|_| NonUtf8BodyError)
+ }
+}
+
+#[cfg(feature = "json")]
+impl<T: serde::de::DeserializeOwned> TryFromBody for super::Json<T> {
+ type Error = super::JsonBodyError;
+ fn try_from_body(body: Option<Vec<u8>>) -> Result<Self, Self::Error> {
+ Ok(super::Json(
+ serde_json::from_slice(&body.unwrap_or_default()).map_err(super::JsonBodyError)?,
+ ))
+ }
+}
+
+/// A trait from converting from a body
+pub trait FromBody {
+ /// Convert from a body into the type
+ fn from_body(body: Option<Vec<u8>>) -> Self;
+}
+
+impl FromBody for Vec<u8> {
+ fn from_body(body: Option<Vec<u8>>) -> Self {
+ body.unwrap_or_default()
+ }
+}
+
+impl FromBody for () {
+ fn from_body(_body: Option<Vec<u8>>) -> Self {}
+}
+
+#[cfg(feature = "http")]
+impl FromBody for bytes::Bytes {
+ fn from_body(body: Option<Vec<u8>>) -> Self {
+ Into::into(body.unwrap_or_default())
+ }
+}
+
+/// A trait for any type that can be turned into a `Response` body or fail
+pub trait TryIntoBody {
+ /// The type of error if the conversion fails
+ type Error;
+ /// Turn `self` into an Error
+ fn try_into_body(self) -> Result<Option<Vec<u8>>, Self::Error>;
+}
+
+impl<B> TryIntoBody for B
+where
+ B: IntoBody,
+{
+ type Error = std::convert::Infallible;
+
+ fn try_into_body(self) -> Result<Option<Vec<u8>>, Self::Error> {
+ Ok(self.into_body())
+ }
+}
+
+#[cfg(feature = "http")]
+impl<B> TryFrom<hyperium::Request<B>> for Request
+where
+ B: TryIntoBody,
+ B::Error: std::error::Error + Send + Sync + 'static,
+{
+ type Error = anyhow::Error;
+ fn try_from(req: hyperium::Request<B>) -> Result<Self, Self::Error> {
+ let method = match req.method() {
+ &hyperium::Method::GET => super::Method::Get,
+ &hyperium::Method::POST => super::Method::Post,
+ &hyperium::Method::PUT => super::Method::Put,
+ &hyperium::Method::DELETE => super::Method::Delete,
+ &hyperium::Method::PATCH => super::Method::Patch,
+ &hyperium::Method::HEAD => super::Method::Head,
+ &hyperium::Method::OPTIONS => super::Method::Options,
+ m => anyhow::bail!("Unsupported method: {m}"),
+ };
+ let headers = req
+ .headers()
+ .into_iter()
+ .map(|(n, v)| {
+ (
+ n.as_str().to_owned(),
+ String::from_utf8_lossy(v.as_bytes()).into_owned(),
+ )
+ })
+ .collect();
+ Ok(Request {
+ method,
+ uri: req.uri().to_string(),
+ headers,
+ params: Vec::new(),
+ body: B::try_into_body(req.into_body())?,
+ })
+ }
+}
+
+#[cfg(feature = "http")]
+impl<B: TryFromBody> TryFrom<Response> for hyperium::Response<B> {
+ type Error = B::Error;
+ fn try_from(resp: Response) -> Result<Self, Self::Error> {
+ let mut builder = hyperium::Response::builder().status(resp.status);
+ for (n, v) in resp.headers.unwrap_or_default() {
+ builder = builder.header(n, v);
+ }
+ Ok(builder.body(B::try_from_body(resp.body)?).unwrap())
+ }
+}
diff --git a/sdk/rust/src/http/router.rs b/sdk/rust/src/http/router.rs
index 56b17b4812..cd5075090a 100644
--- a/sdk/rust/src/http/router.rs
+++ b/sdk/rust/src/http/router.rs
@@ -1,15 +1,16 @@
-use super::{Request, Response, Result};
+use super::conversions::{IntoResponse, TryFromRequest};
+use super::{responses, Method, Request, Response};
use routefinder::{Captures, Router as MethodRouter};
use std::{collections::HashMap, fmt::Display};
-type Handler = dyn Fn(Request, Params) -> Result<Response>;
+type Handler = dyn Fn(Request, Params) -> Response;
/// Route parameters extracted from a URI that match a route pattern.
pub type Params = Captures<'static, 'static>;
/// The Spin SDK HTTP router.
pub struct Router {
- methods_map: HashMap<http_types::Method, MethodRouter<Box<Handler>>>,
+ methods_map: HashMap<Method, MethodRouter<Box<Handler>>>,
any_methods: MethodRouter<Box<Handler>>,
}
@@ -38,14 +39,15 @@ struct RouteMatch<'a> {
impl Router {
/// Dispatches a request to the appropriate handler along with the URI parameters.
- pub fn handle(&self, request: Request) -> Result<Response> {
- let method = request.method().to_owned();
- let path = request.uri().path().to_owned();
- let RouteMatch { params, handler } = self.find(&path, method);
+ pub fn handle<R: Into<Request>>(&self, request: R) -> Response {
+ let request = request.into();
+ let method = request.method;
+ let path = &request.uri;
+ let RouteMatch { params, handler } = self.find(path, method);
handler(request, params)
}
- fn find(&self, path: &str, method: http_types::Method) -> RouteMatch<'_> {
+ fn find(&self, path: &str, method: Method) -> RouteMatch<'_> {
let best_match = self
.methods_map
.get(&method)
@@ -65,10 +67,10 @@ impl Router {
let handler = m.handler();
RouteMatch { handler, params }
}
- None if method == http_types::Method::HEAD => {
+ None if method == Method::Head => {
// If it is a HTTP HEAD request then check if there is a callback in the methods map
// if not then fallback to the behavior of HTTP GET else proceed as usual
- self.find(path, http_types::Method::GET)
+ self.find(path, Method::Get)
}
None => {
// Handle the failure case where no match could be resolved.
@@ -78,7 +80,7 @@ impl Router {
}
// Helper function to handle the case where a best match couldn't be resolved.
- fn fail(&self, path: &str, method: http_types::Method) -> RouteMatch<'_> {
+ fn fail(&self, path: &str, method: Method) -> RouteMatch<'_> {
// First, filter all routers to determine if the path can match but the provided method is not allowed.
let is_method_not_allowed = self
.methods_map
@@ -103,79 +105,124 @@ impl Router {
}
/// Register a handler at the path for all methods.
- pub fn any<F>(&mut self, path: &str, handler: F)
+ pub fn any<F, I, O>(&mut self, path: &str, handler: F)
where
- F: Fn(Request, Params) -> Result<Response> + 'static,
+ F: Fn(I, Params) -> O + 'static,
+ I: TryFromRequest,
+ I::Error: IntoResponse,
+ O: IntoResponse,
{
- self.any_methods.add(path, Box::new(handler)).unwrap();
+ self.any_methods
+ .add(
+ path,
+ Box::new(
+ move |req, params| match TryFromRequest::try_from_request(req) {
+ Ok(r) => handler(r, params).into_response(),
+ Err(e) => e.into_response(),
+ },
+ ),
+ )
+ .unwrap();
}
/// Register a handler at the path for the specified HTTP method.
- pub fn add<F>(&mut self, path: &str, method: http_types::Method, handler: F)
+ pub fn add<F, I, O>(&mut self, path: &str, method: Method, handler: F)
where
- F: Fn(Request, Params) -> Result<Response> + 'static,
+ F: Fn(I, Params) -> O + 'static,
+ I: TryFromRequest,
+ I::Error: IntoResponse,
+ O: IntoResponse,
{
self.methods_map
.entry(method)
.or_default()
- .add(path, Box::new(handler))
+ .add(
+ path,
+ Box::new(
+ move |req, params| match TryFromRequest::try_from_request(req) {
+ Ok(r) => handler(r, params).into_response(),
+ Err(e) => e.into_response(),
+ },
+ ),
+ )
.unwrap();
}
/// Register a handler at the path for the HTTP GET method.
- pub fn get<F>(&mut self, path: &str, handler: F)
+ pub fn get<F, Req, Resp>(&mut self, path: &str, handler: F)
where
- F: Fn(Request, Params) -> Result<Response> + 'static,
+ F: Fn(Req, Params) -> Resp + 'static,
+ Req: TryFromRequest,
+ Req::Error: IntoResponse,
+ Resp: IntoResponse,
{
- self.add(path, http_types::Method::GET, handler)
+ self.add(path, Method::Get, handler)
}
/// Register a handler at the path for the HTTP HEAD method.
- pub fn head<F>(&mut self, path: &str, handler: F)
+ pub fn head<F, Req, Resp>(&mut self, path: &str, handler: F)
where
- F: Fn(Request, Params) -> Result<Response> + 'static,
+ F: Fn(Req, Params) -> Resp + 'static,
+ Req: TryFromRequest,
+ Req::Error: IntoResponse,
+ Resp: IntoResponse,
{
- self.add(path, http_types::Method::HEAD, handler)
+ self.add(path, Method::Head, handler)
}
/// Register a handler at the path for the HTTP POST method.
- pub fn post<F>(&mut self, path: &str, handler: F)
+ pub fn post<F, Req, Resp>(&mut self, path: &str, handler: F)
where
- F: Fn(Request, Params) -> Result<Response> + 'static,
+ F: Fn(Req, Params) -> Resp + 'static,
+ Req: TryFromRequest,
+ Req::Error: IntoResponse,
+ Resp: IntoResponse,
{
- self.add(path, http_types::Method::POST, handler)
+ self.add(path, Method::Post, handler)
}
/// Register a handler at the path for the HTTP DELETE method.
- pub fn delete<F>(&mut self, path: &str, handler: F)
+ pub fn delete<F, Req, Resp>(&mut self, path: &str, handler: F)
where
- F: Fn(Request, Params) -> Result<Response> + 'static,
+ F: Fn(Req, Params) -> Resp + 'static,
+ Req: TryFromRequest,
+ Req::Error: IntoResponse,
+ Resp: IntoResponse,
{
- self.add(path, http_types::Method::DELETE, handler)
+ self.add(path, Method::Delete, handler)
}
/// Register a handler at the path for the HTTP PUT method.
- pub fn put<F>(&mut self, path: &str, handler: F)
+ pub fn put<F, Req, Resp>(&mut self, path: &str, handler: F)
where
- F: Fn(Request, Params) -> Result<Response> + 'static,
+ F: Fn(Req, Params) -> Resp + 'static,
+ Req: TryFromRequest,
+ Req::Error: IntoResponse,
+ Resp: IntoResponse,
{
- self.add(path, http_types::Method::PUT, handler)
+ self.add(path, Method::Put, handler)
}
/// Register a handler at the path for the HTTP PATCH method.
- pub fn patch<F>(&mut self, path: &str, handler: F)
+ pub fn patch<F, Req, Resp>(&mut self, path: &str, handler: F)
where
- F: Fn(Request, Params) -> Result<Response> + 'static,
+ F: Fn(Req, Params) -> Resp + 'static,
+ Req: TryFromRequest,
+ Req::Error: IntoResponse,
+ Resp: IntoResponse,
{
- self.add(path, http_types::Method::PATCH, handler)
+ self.add(path, Method::Patch, handler)
}
/// Register a handler at the path for the HTTP OPTIONS method.
- pub fn options<F>(&mut self, path: &str, handler: F)
+ pub fn options<F, Req, Resp>(&mut self, path: &str, handler: F)
where
- F: Fn(Request, Params) -> Result<Response> + 'static,
+ F: Fn(Req, Params) -> Resp + 'static,
+ Req: TryFromRequest,
+ Req::Error: IntoResponse,
+ Resp: IntoResponse,
{
- self.add(path, http_types::Method::OPTIONS, handler)
+ self.add(path, Method::Options, handler)
}
/// Construct a new Router.
@@ -187,18 +234,12 @@ impl Router {
}
}
-fn not_found(_req: Request, _params: Params) -> Result<Response> {
- Ok(http_types::Response::builder()
- .status(http_types::StatusCode::NOT_FOUND)
- .body(None)
- .unwrap())
+fn not_found(_req: Request, _params: Params) -> Response {
+ responses::not_found()
}
-fn method_not_allowed(_req: Request, _params: Params) -> Result<Response> {
- Ok(http_types::Response::builder()
- .status(http_types::StatusCode::METHOD_NOT_ALLOWED)
- .body(None)
- .unwrap())
+fn method_not_allowed(_req: Request, _params: Params) -> Response {
+ responses::method_not_allowed()
}
/// A macro to help with constructing a Router from a stream of tokens.
@@ -243,19 +284,19 @@ macro_rules! http_router {
mod tests {
use super::*;
- fn make_request(method: http_types::Method, path: &str) -> Request {
- http_types::Request::builder()
- .method(method)
- .uri(path)
- .body(None)
- .unwrap()
+ fn make_request(method: Method, path: &str) -> Request {
+ Request {
+ method,
+ uri: path.into(),
+ headers: Vec::new(),
+ params: Vec::new(),
+ body: None,
+ }
}
- fn echo_param(req: Request, params: Params) -> Result<Response> {
+ fn echo_param(req: Request, params: Params) -> Response {
match params.get("x") {
- Some(path) => Ok(http_types::Response::builder()
- .status(http_types::StatusCode::OK)
- .body(Some(path.to_string().into()))?),
+ Some(path) => Response::new(200, path),
None => not_found(req, params),
}
}
@@ -265,42 +306,40 @@ mod tests {
let mut router = Router::default();
router.get("/:x", echo_param);
- let req = make_request(http_types::Method::POST, "/foobar");
- let res = router.handle(req).unwrap();
- assert_eq!(res.status(), http_types::StatusCode::METHOD_NOT_ALLOWED);
+ let req = make_request(Method::Post, "/foobar");
+ let res = router.handle(req);
+ assert_eq!(res.status, hyperium::StatusCode::METHOD_NOT_ALLOWED);
}
#[test]
fn test_not_found() {
- fn h1(_req: Request, _params: Params) -> Result<Response> {
- Ok(http_types::Response::builder().status(200).body(None)?)
+ fn h1(_req: Request, _params: Params) -> anyhow::Result<Response> {
+ Ok(Response::new(200, ()))
}
let mut router = Router::default();
router.get("/h1/:param", h1);
- let req = make_request(http_types::Method::GET, "/h1/");
- let res = router.handle(req).unwrap();
- assert_eq!(res.status(), http_types::StatusCode::NOT_FOUND);
+ let req = make_request(Method::Get, "/h1/");
+ let res = router.handle(req);
+ assert_eq!(res.status, hyperium::StatusCode::NOT_FOUND);
}
#[test]
fn test_multi_param() {
- fn multiply(_req: Request, params: Params) -> Result<Response> {
+ fn multiply(_req: Request, params: Params) -> anyhow::Result<Response> {
let x: i64 = params.get("x").unwrap().parse()?;
let y: i64 = params.get("y").unwrap().parse()?;
- Ok(http_types::Response::builder()
- .status(http_types::StatusCode::OK)
- .body(Some(format!("{result}", result = x * y).into()))?)
+ Ok(Response::new(200, format!("{result}", result = x * y)))
}
let mut router = Router::default();
router.get("/multiply/:x/:y", multiply);
- let req = make_request(http_types::Method::GET, "/multiply/2/4");
- let res = router.handle(req).unwrap();
+ let req = make_request(Method::Get, "/multiply/2/4");
+ let res = router.handle(req);
- assert_eq!(res.into_body().unwrap(), "8".to_string());
+ assert_eq!(res.body.unwrap(), "8".to_owned().into_bytes());
}
#[test]
@@ -308,19 +347,17 @@ mod tests {
let mut router = Router::default();
router.get("/:x", echo_param);
- let req = make_request(http_types::Method::GET, "/y");
- let res = router.handle(req).unwrap();
+ let req = make_request(Method::Get, "/y");
+ let res = router.handle(req);
- assert_eq!(res.into_body().unwrap(), "y".to_string());
+ assert_eq!(res.body.unwrap(), "y".to_owned().into_bytes());
}
#[test]
fn test_wildcard() {
- fn echo_wildcard(req: Request, params: Params) -> Result<Response> {
+ fn echo_wildcard(req: Request, params: Params) -> Response {
match params.wildcard() {
- Some(path) => Ok(http_types::Response::builder()
- .status(http_types::StatusCode::OK)
- .body(Some(path.to_string().into()))?),
+ Some(path) => Response::new(200, path),
None => not_found(req, params),
}
}
@@ -328,10 +365,10 @@ mod tests {
let mut router = Router::default();
router.get("/*", echo_wildcard);
- let req = make_request(http_types::Method::GET, "/foo/bar");
- let res = router.handle(req).unwrap();
- assert_eq!(res.status(), http_types::StatusCode::OK);
- assert_eq!(res.into_body().unwrap(), "foo/bar".to_string());
+ let req = make_request(Method::Get, "/foo/bar");
+ let res = router.handle(req);
+ assert_eq!(res.status, hyperium::StatusCode::OK);
+ assert_eq!(res.body.unwrap(), "foo/bar".to_owned().into_bytes());
}
#[test]
@@ -339,9 +376,9 @@ mod tests {
let mut router = Router::default();
router.get("/:x/*", echo_param);
- let req = make_request(http_types::Method::GET, "/foo/bar");
- let res = router.handle(req).unwrap();
- assert_eq!(res.into_body().unwrap(), "foo".to_string());
+ let req = make_request(Method::Get, "/foo/bar");
+ let res = router.handle(req);
+ assert_eq!(res.body.unwrap(), "foo".to_owned().into_bytes());
}
#[test]
@@ -357,25 +394,21 @@ mod tests {
#[test]
fn test_ambiguous_wildcard_vs_star() {
- fn h1(_req: Request, _params: Params) -> Result<Response> {
- Ok(http_types::Response::builder()
- .status(http_types::StatusCode::OK)
- .body(Some("one/two".into()))?)
+ fn h1(_req: Request, _params: Params) -> anyhow::Result<Response> {
+ Ok(Response::new(200, "one/two"))
}
- fn h2(_req: Request, _params: Params) -> Result<Response> {
- Ok(http_types::Response::builder()
- .status(http_types::StatusCode::OK)
- .body(Some("posts/*".into()))?)
+ fn h2(_req: Request, _params: Params) -> anyhow::Result<Response> {
+ Ok(Response::new(200, "posts/*"))
}
let mut router = Router::default();
router.get("/:one/:two", h1);
router.get("/posts/*", h2);
- let req = make_request(http_types::Method::GET, "/posts/2");
- let res = router.handle(req).unwrap();
+ let req = make_request(Method::Get, "/posts/2");
+ let res = router.handle(req);
- assert_eq!(res.into_body().unwrap(), "posts/*".to_string());
+ assert_eq!(res.body.unwrap(), "posts/*".to_owned().into_bytes());
}
}
diff --git a/sdk/rust/src/key_value.rs b/sdk/rust/src/key_value.rs
index 23c69e7b2c..7a62a8f4f9 100644
--- a/sdk/rust/src/key_value.rs
+++ b/sdk/rust/src/key_value.rs
@@ -34,7 +34,13 @@ impl Store {
#[cfg(feature = "json")]
/// Deserialize an instance of type `T` from the value of `key`.
- pub fn get_json<T: DeserializeOwned>(&self, key: impl AsRef<str>) -> Result<T, anyhow::Error> {
- Ok(serde_json::from_slice(&self.get(key.as_ref())?)?)
+ pub fn get_json<T: DeserializeOwned>(
+ &self,
+ key: impl AsRef<str>,
+ ) -> Result<Option<T>, anyhow::Error> {
+ let Some(value) = self.get(key.as_ref())? else {
+ return Ok(None);
+ };
+ Ok(serde_json::from_slice(&value)?)
}
}
diff --git a/sdk/rust/src/lib.rs b/sdk/rust/src/lib.rs
index cbabf59e0c..c3d9edbf59 100644
--- a/sdk/rust/src/lib.rs
+++ b/sdk/rust/src/lib.rs
@@ -2,9 +2,6 @@
#![deny(missing_docs)]
-/// Outbound HTTP request functionality.
-pub mod outbound_http;
-
/// Key/Value storage.
pub mod key_value;
@@ -17,8 +14,6 @@ pub mod llm;
/// Exports the procedural macros for writing handlers for Spin components.
pub use spin_macro::*;
-pub use http_types;
-
#[doc(hidden)]
/// Module containing wit bindgen generated code.
///
@@ -52,37 +47,10 @@ extern "C" fn __spin_sdk_language() {}
extern "C" fn __spin_sdk_hash() {}
/// Helpers for building Spin HTTP components.
-/// These are convenience helpers, and the types in this module are
-/// based on the [`http`](https://crates.io/crates) crate.
-pub mod http {
- use anyhow::Result;
-
- /// The Spin HTTP request.
- pub type Request = http_types::Request<Option<bytes::Bytes>>;
-
- /// The Spin HTTP response.
- pub type Response = http_types::Response<Option<bytes::Bytes>>;
-
- pub use crate::outbound_http::send_request as send;
+pub mod http;
- /// Exports HTTP Router items.
- pub use router::*;
- mod router;
-
- /// Helper function to return a 404 Not Found response.
- pub fn not_found() -> Result<Response> {
- Ok(http_types::Response::builder()
- .status(404)
- .body(Some("Not Found".into()))?)
- }
-
- /// Helper function to return a 500 Internal Server Error response.
- pub fn internal_server_error() -> Result<Response> {
- Ok(http_types::Response::builder()
- .status(500)
- .body(Some("Internal Server Error".into()))?)
- }
-}
+/// Helpers for building Spin `wasi-http` components.
+pub mod wasi_http;
/// Implementation of the spin redis interface.
#[allow(missing_docs)]
diff --git a/sdk/rust/src/outbound_http.rs b/sdk/rust/src/outbound_http.rs
deleted file mode 100644
index 20abee92a8..0000000000
--- a/sdk/rust/src/outbound_http.rs
+++ /dev/null
@@ -1,84 +0,0 @@
-use http_types::{header::HeaderName, HeaderValue};
-
-use super::http::{Request, Response};
-
-use super::wit::v1::http::{self as spin_http};
-use super::wit::v1::http_types as spin_http_types;
-
-/// Error type returned by [`send_request`][crate::outbound_http::send_request]
-pub use spin_http_types::HttpError as OutboundHttpError;
-
-type Result<T> = std::result::Result<T, OutboundHttpError>;
-
-/// Send an HTTP request and get a fully formed HTTP response.
-pub fn send_request(req: Request) -> Result<Response> {
- let (req, body) = req.into_parts();
-
- let method = req.method.try_into()?;
-
- let uri = req.uri.to_string();
-
- let params = vec![];
-
- let headers = req
- .headers
- .iter()
- .map(try_header_to_strings)
- .collect::<Result<Vec<_>>>()?;
-
- let body = body.map(|bytes| bytes.to_vec());
-
- let out_req = spin_http_types::Request {
- method,
- uri,
- params,
- headers,
- body,
- };
-
- let spin_http_types::Response {
- status,
- headers,
- body,
- } = spin_http::send_request(&out_req)?;
-
- let resp_builder = http_types::response::Builder::new().status(status);
- let resp_builder = headers
- .into_iter()
- .flatten()
- .fold(resp_builder, |b, (k, v)| b.header(k, v));
- resp_builder
- .body(body.map(Into::into))
- .map_err(|_| OutboundHttpError::RuntimeError)
-}
-
-fn try_header_to_strings(
- (header_name, header_value): (&HeaderName, &HeaderValue),
-) -> Result<(String, String)> {
- Ok((
- header_name.to_string(),
- header_value
- .to_str()
- .map_err(|_| OutboundHttpError::InvalidUrl)?
- .to_owned(),
- ))
-}
-
-impl TryFrom<http_types::Method> for spin_http_types::Method {
- type Error = OutboundHttpError;
-
- fn try_from(method: http_types::Method) -> Result<Self> {
- use http_types::Method;
- use spin_http_types::Method::*;
- Ok(match method {
- Method::GET => Get,
- Method::POST => Post,
- Method::PUT => Put,
- Method::DELETE => Delete,
- Method::PATCH => Patch,
- Method::HEAD => Head,
- Method::OPTIONS => Options,
- _ => return Err(spin_http::HttpError::RequestError),
- })
- }
-}
diff --git a/sdk/rust/src/wasi_http.rs b/sdk/rust/src/wasi_http.rs
new file mode 100644
index 0000000000..9ad770eaa5
--- /dev/null
+++ b/sdk/rust/src/wasi_http.rs
@@ -0,0 +1,105 @@
+/// Traits for converting between the various types
+pub mod conversions;
+
+#[doc(inline)]
+pub use super::wit::wasi::http::types::*;
+
+impl IncomingRequest {
+ /// Return a `Stream` from which the body of the specified request may be read.
+ ///
+ /// # Panics
+ ///
+ /// Panics if the body was already consumed.
+ pub fn into_body_stream(self) -> impl futures::Stream<Item = anyhow::Result<Vec<u8>>> {
+ executor::incoming_body(self.consume().expect("request body was already consumed"))
+ }
+
+ /// Return a `Vec<u8>` of the body or fails
+ pub async fn into_body(self) -> anyhow::Result<Vec<u8>> {
+ use futures::TryStreamExt;
+ let mut stream = self.into_body_stream();
+ let mut body = Vec::new();
+ while let Some(chunk) = stream.try_next().await? {
+ body.extend(chunk);
+ }
+ Ok(body)
+ }
+}
+
+impl IncomingResponse {
+ /// Return a `Stream` from which the body of the specified response may be read.
+ ///
+ /// # Panics
+ ///
+ /// Panics if the body was already consumed.
+ pub fn into_body_stream(self) -> impl futures::Stream<Item = anyhow::Result<Vec<u8>>> {
+ executor::incoming_body(self.consume().expect("response body was already consumed"))
+ }
+}
+
+impl OutgoingResponse {
+ /// Construct a `Sink` which writes chunks to the body of the specified response.
+ ///
+ /// # Panics
+ ///
+ /// Panics if the body was already taken.
+ pub fn take_body(&self) -> impl futures::Sink<Vec<u8>, Error = anyhow::Error> {
+ executor::outgoing_body(self.write().expect("response body was already taken"))
+ }
+}
+
+impl ResponseOutparam {
+ /// Set with the outgoing response and the supplied buffer
+ ///
+ /// Will panic if response body has already been taken
+ pub async fn set_with_body(
+ self,
+ response: OutgoingResponse,
+ buffer: Vec<u8>,
+ ) -> anyhow::Result<()> {
+ use futures::SinkExt;
+ let mut body = response.take_body();
+ ResponseOutparam::set(self, Ok(response));
+ body.send(buffer).await
+ }
+}
+
+/// Send an outgoing request
+pub async fn send<I, O>(request: I) -> Result<O, SendError>
+where
+ I: TryInto<OutgoingRequest>,
+ I::Error: Into<Box<dyn std::error::Error + Send + Sync>> + 'static,
+ O: TryFrom<IncomingResponse>,
+ O::Error: Into<Box<dyn std::error::Error + Send + Sync>> + 'static,
+{
+ let response = executor::outgoing_request_send(
+ request
+ .try_into()
+ .map_err(|e| SendError::RequestConversion(e.into()))?,
+ )
+ .await
+ .map_err(SendError::Http)?;
+ response
+ .try_into()
+ .map_err(|e: O::Error| SendError::ResponseConversion(e.into()))
+}
+
+/// An error encountered when performing an HTTP request
+#[derive(thiserror::Error, Debug)]
+pub enum SendError {
+ /// Error converting to a request
+ #[error(transparent)]
+ RequestConversion(Box<dyn std::error::Error + Send + Sync>),
+ /// Error converting from a response
+ #[error(transparent)]
+ ResponseConversion(Box<dyn std::error::Error + Send + Sync>),
+ /// An HTTP error
+ #[error(transparent)]
+ Http(Error),
+}
+
+#[doc(hidden)]
+/// The executor for driving wasi-http futures to completion
+mod executor;
+#[doc(hidden)]
+pub use executor::run;
diff --git a/sdk/rust/src/wasi_http/conversions.rs b/sdk/rust/src/wasi_http/conversions.rs
new file mode 100644
index 0000000000..c83dfa982d
--- /dev/null
+++ b/sdk/rust/src/wasi_http/conversions.rs
@@ -0,0 +1,139 @@
+use async_trait::async_trait;
+
+use super::{Headers, IncomingRequest, Method, OutgoingResponse};
+use crate::http::conversions as http_conversions;
+
+impl From<crate::http::Response> for OutgoingResponse {
+ fn from(response: crate::http::Response) -> Self {
+ let headers = response
+ .headers
+ .unwrap_or_default()
+ .into_iter()
+ .map(|(k, v)| (k, v.into_bytes()))
+ .collect::<Vec<_>>();
+ OutgoingResponse::new(response.status, &Headers::new(&headers))
+ }
+}
+
+/// A trait for trying to convert from an `IncomingRequest` to the implementing type
+#[async_trait]
+pub trait TryFromIncomingRequest {
+ /// The error if conversion fails
+ type Error;
+
+ /// Try to turn the `IncomingRequest` into the implementing type
+ async fn try_from_incoming_request(value: IncomingRequest) -> Result<Self, Self::Error>
+ where
+ Self: Sized;
+}
+
+#[async_trait]
+impl TryFromIncomingRequest for IncomingRequest {
+ type Error = std::convert::Infallible;
+ async fn try_from_incoming_request(request: IncomingRequest) -> Result<Self, Self::Error> {
+ Ok(request)
+ }
+}
+
+#[async_trait]
+impl<R> TryFromIncomingRequest for R
+where
+ R: crate::http::conversions::TryNonRequestFromRequest,
+{
+ type Error = IncomingRequestError<R::Error>;
+
+ async fn try_from_incoming_request(request: IncomingRequest) -> Result<Self, Self::Error> {
+ let req = crate::http::Request::try_from_incoming_request(request)
+ .await
+ .map_err(convert_error)?;
+ R::try_from_request(req).map_err(IncomingRequestError::ConversionError)
+ }
+}
+
+#[async_trait]
+impl TryFromIncomingRequest for crate::http::Request {
+ type Error = IncomingRequestError;
+
+ async fn try_from_incoming_request(request: IncomingRequest) -> Result<Self, Self::Error> {
+ let headers = request
+ .headers()
+ .entries()
+ .iter()
+ .map(|(k, v)| (k.clone(), String::from_utf8_lossy(v).into_owned()))
+ .collect();
+ Ok(Self {
+ method: request
+ .method()
+ .try_into()
+ .map_err(|_| IncomingRequestError::UnexpectedMethod(request.method()))?,
+ uri: request
+ .path_with_query()
+ .unwrap_or_else(|| String::from("/")),
+ headers,
+ params: Vec::new(),
+ body: Some(
+ request
+ .into_body()
+ .await
+ .map_err(IncomingRequestError::BodyConversionError)?,
+ ),
+ })
+ }
+}
+
+#[derive(Debug, thiserror::Error)]
+/// An error converting an `IncomingRequest`
+pub enum IncomingRequestError<E = std::convert::Infallible> {
+ /// The `IncomingRequest` has a method not supported by `Request`
+ #[error("unexpected method: {0:?}")]
+ UnexpectedMethod(Method),
+ /// There was an error converting the body to an `Option<Vec<u8>>k`
+ #[error(transparent)]
+ BodyConversionError(anyhow::Error),
+ /// There was an error converting the `Request` into the requested type
+ #[error(transparent)]
+ ConversionError(E),
+}
+
+/// Helper for converting `IncomingRequestError`s that cannot fail due to conversion errors
+/// into ones that can.
+fn convert_error<E>(
+ error: IncomingRequestError<std::convert::Infallible>,
+) -> IncomingRequestError<E> {
+ match error {
+ IncomingRequestError::UnexpectedMethod(e) => IncomingRequestError::UnexpectedMethod(e),
+ IncomingRequestError::BodyConversionError(e) => {
+ IncomingRequestError::BodyConversionError(e)
+ }
+ IncomingRequestError::ConversionError(_) => unreachable!(),
+ }
+}
+
+impl<E: http_conversions::IntoResponse> http_conversions::IntoResponse for IncomingRequestError<E> {
+ fn into_response(self) -> crate::http::Response {
+ match self {
+ IncomingRequestError::UnexpectedMethod(_) => {
+ crate::http::responses::method_not_allowed()
+ }
+ IncomingRequestError::BodyConversionError(e) => e.into_response(),
+ IncomingRequestError::ConversionError(e) => e.into_response(),
+ }
+ }
+}
+
+impl TryFrom<Method> for crate::http::Method {
+ type Error = ();
+ fn try_from(method: Method) -> Result<Self, Self::Error> {
+ let method = match method {
+ Method::Get => Self::Get,
+ Method::Head => Self::Head,
+ Method::Post => Self::Post,
+ Method::Put => Self::Put,
+ Method::Patch => Self::Patch,
+ Method::Delete => Self::Delete,
+ Method::Options => Self::Options,
+ _ => return Err(()),
+ };
+ Ok(method)
+ }
+}
diff --git a/sdk/rust/src/wasi_http/executor.rs b/sdk/rust/src/wasi_http/executor.rs
new file mode 100644
index 0000000000..0dcefa5c10
--- /dev/null
+++ b/sdk/rust/src/wasi_http/executor.rs
@@ -0,0 +1,200 @@
+use crate::wit::wasi::http::outgoing_handler;
+use crate::wit::wasi::http::types::{
+ self, IncomingBody, IncomingResponse, OutgoingBody, OutgoingRequest,
+};
+use crate::wit::wasi::io;
+use crate::wit::wasi::io::streams::{InputStream, OutputStream, StreamError};
+
+use anyhow::{anyhow, Error, Result};
+use futures::{future, sink, stream, Sink, Stream};
+
+use std::cell::RefCell;
+use std::future::Future;
+use std::mem;
+use std::rc::Rc;
+use std::sync::{Arc, Mutex};
+use std::task::{Context, Poll, Wake, Waker};
+
+const READ_SIZE: u64 = 16 * 1024;
+
+static WAKERS: Mutex<Vec<(io::poll::Pollable, Waker)>> = Mutex::new(Vec::new());
+
+/// Run the specified future to completion blocking until it yields a result.
+///
+/// Based on an executor using `wasi::io/poll/poll-list`,
+pub fn run<T>(future: impl Future<Output = T>) -> T {
+ futures::pin_mut!(future);
+ struct DummyWaker;
+
+ impl Wake for DummyWaker {
+ fn wake(self: Arc<Self>) {}
+ }
+
+ let waker = Arc::new(DummyWaker).into();
+
+ loop {
+ match future.as_mut().poll(&mut Context::from_waker(&waker)) {
+ Poll::Pending => {
+ let mut new_wakers = Vec::new();
+
+ let wakers = mem::take::<Vec<_>>(&mut WAKERS.lock().unwrap());
+
+ assert!(!wakers.is_empty());
+
+ let pollables = wakers
+ .iter()
+ .map(|(pollable, _)| pollable)
+ .collect::<Vec<_>>();
+
+ let mut ready = vec![false; wakers.len()];
+
+ for index in io::poll::poll_list(&pollables) {
+ ready[usize::try_from(index).unwrap()] = true;
+ }
+
+ for (ready, (pollable, waker)) in ready.into_iter().zip(wakers) {
+ if ready {
+ waker.wake()
+ } else {
+ new_wakers.push((pollable, waker));
+ }
+ }
+
+ *WAKERS.lock().unwrap() = new_wakers;
+ }
+ Poll::Ready(result) => break result,
+ }
+ }
+}
+
+pub(crate) fn outgoing_body(body: OutgoingBody) -> impl Sink<Vec<u8>, Error = Error> {
+ struct Outgoing(Option<(OutputStream, OutgoingBody)>);
+
+ impl Drop for Outgoing {
+ fn drop(&mut self) {
+ if let Some((stream, body)) = self.0.take() {
+ drop(stream);
+ OutgoingBody::finish(body, None);
+ }
+ }
+ }
+
+ let stream = body.write().expect("response body should be writable");
+ let pair = Rc::new(RefCell::new(Outgoing(Some((stream, body)))));
+
+ sink::unfold((), {
+ move |(), chunk: Vec<u8>| {
+ future::poll_fn({
+ let mut offset = 0;
+ let mut flushing = false;
+ let pair = pair.clone();
+
+ move |context| {
+ let pair = pair.borrow();
+ let (stream, _) = &pair.0.as_ref().unwrap();
+
+ loop {
+ match stream.check_write() {
+ Ok(0) => {
+ WAKERS
+ .lock()
+ .unwrap()
+ .push((stream.subscribe(), context.waker().clone()));
+
+ break Poll::Pending;
+ }
+ Ok(count) => {
+ if offset == chunk.len() {
+ if flushing {
+ break Poll::Ready(Ok(()));
+ } else {
+ stream.flush().expect("stream should be flushable");
+ flushing = true;
+ }
+ } else {
+ let count =
+ usize::try_from(count).unwrap().min(chunk.len() - offset);
+
+ match stream.write(&chunk[offset..][..count]) {
+ Ok(()) => {
+ offset += count;
+ }
+ Err(_) => break Poll::Ready(Err(anyhow!("I/O error"))),
+ }
+ }
+ }
+ Err(_) => break Poll::Ready(Err(anyhow!("I/O error"))),
+ }
+ }
+ }
+ })
+ }
+ })
+}
+
+/// Send the specified request and return the response.
+pub(crate) fn outgoing_request_send(
+ request: OutgoingRequest,
+) -> impl Future<Output = Result<IncomingResponse, types::Error>> {
+ future::poll_fn({
+ let response = outgoing_handler::handle(request, None);
+
+ move |context| match &response {
+ Ok(response) => {
+ if let Some(response) = response.get() {
+ Poll::Ready(response.unwrap())
+ } else {
+ WAKERS
+ .lock()
+ .unwrap()
+ .push((response.subscribe(), context.waker().clone()));
+ Poll::Pending
+ }
+ }
+ Err(error) => Poll::Ready(Err(error.clone())),
+ }
+ })
+}
+
+#[doc(hidden)]
+pub fn incoming_body(body: IncomingBody) -> impl Stream<Item = Result<Vec<u8>>> {
+ struct Incoming(Option<(InputStream, IncomingBody)>);
+
+ impl Drop for Incoming {
+ fn drop(&mut self) {
+ if let Some((stream, body)) = self.0.take() {
+ drop(stream);
+ IncomingBody::finish(body);
+ }
+ }
+ }
+
+ stream::poll_fn({
+ let stream = body.stream().expect("response body should be readable");
+ let pair = Incoming(Some((stream, body)));
+
+ move |context| {
+ if let Some((stream, _)) = &pair.0 {
+ match stream.read(READ_SIZE) {
+ Ok(buffer) => {
+ if buffer.is_empty() {
+ WAKERS
+ .lock()
+ .unwrap()
+ .push((stream.subscribe(), context.waker().clone()));
+ Poll::Pending
+ } else {
+ Poll::Ready(Some(Ok(buffer)))
+ }
+ }
+ Err(StreamError::Closed) => Poll::Ready(None),
+ Err(StreamError::LastOperationFailed(error)) => {
+ Poll::Ready(Some(Err(anyhow!("{}", error.to_debug_string()))))
+ }
+ }
+ } else {
+ Poll::Ready(None)
+ }
+ }
+ })
+}
diff --git a/wit/preview2/deps/http/types.wit b/wit/preview2/deps/http/types.wit
index 2b64e40eb6..3ba1a71290 100644
--- a/wit/preview2/deps/http/types.wit
+++ b/wit/preview2/deps/http/types.wit
@@ -1,13 +1,13 @@
package wasi:http
-// The `wasi:http/types` interface is meant to be imported by components to
-// define the HTTP resource types and operations used by the component's
-// imported and exported interfaces.
+/// The `wasi:http/types` interface is meant to be imported by components to
+/// define the HTTP resource types and operations used by the component's
+/// imported and exported interfaces.
interface types {
use wasi:io/streams.{input-stream, output-stream}
use wasi:io/poll.{pollable}
- // This type corresponds to HTTP standard Methods.
+ /// This type corresponds to HTTP standard Methods.
variant method {
get,
head,
@@ -21,7 +21,7 @@ interface types {
other(string)
}
- // This type corresponds to HTTP standard Related Schemes.
+ /// This type corresponds to HTTP standard Related Schemes.
variant scheme {
HTTP,
HTTPS,
@@ -29,8 +29,8 @@ interface types {
}
// TODO: perhaps better align with HTTP semantics?
- // This type enumerates the different kinds of errors that may occur when
- // initially returning a response.
+ /// This type enumerates the different kinds of errors that may occur when
+ /// initially returning a response.
variant error {
invalid-url(string),
timeout-error(string),
@@ -38,10 +38,8 @@ interface types {
unexpected-error(string)
}
- // This following block defines the `fields` resource which corresponds to
- // HTTP standard Fields. Soon, when resource types are added, the `type
- // fields = u32` type alias can be replaced by a proper `resource fields`
- // definition containing all the functions using the method syntactic sugar.
+ /// This following block defines the `fields` resource which corresponds to
+ /// HTTP standard Fields.
resource fields {
// Multiple values for a header are multiple entries in the list with the
// same key.
@@ -68,14 +66,11 @@ interface types {
type headers = fields
type trailers = fields
- // The following block defines the `incoming-request` and `outgoing-request`
- // resource types that correspond to HTTP standard Requests. Soon, when
- // resource types are added, the `u32` type aliases can be replaced by
- // proper `resource` type definitions containing all the functions as
- // methods. Later, Preview2 will allow both types to be merged together into
- // a single `request` type (that uses the single `stream` type mentioned
- // above). The `consume` and `write` methods may only be called once (and
- // return failure thereafter).
+ /// The following block defines the `incoming-request` and `outgoing-request`
+ /// resource types that correspond to HTTP standard Requests.
+ ///
+ /// The `consume` and `write` methods may only be called once (and
+ /// return failure thereafter).
resource incoming-request {
method: func() -> method
@@ -86,9 +81,10 @@ interface types {
authority: func() -> option<string>
headers: func() -> /* child */ headers
- // Will return the input-stream child at most once. If called more than
- // once, subsequent calls will return error.
+ /// Returns the input-stream child at most once.
+ ///
+ /// If called more than once, subsequent calls return an error.
consume: func() -> result<incoming-body>
}
@@ -101,33 +97,34 @@ interface types {
headers: borrow<headers>
)
- // Will return the outgoing-body child at most once. If called more than
- // once, subsequent calls will return error.
+ /// Will return the outgoing-body child at most once.
+ ///
+ /// If called more than once, subsequent calls return an error.
write: func() -> result< /* child */ outgoing-body>
}
- // Additional optional parameters that can be set when making a request.
+ /// Additional optional parameters that can be set when making a request.
record request-options {
// The following timeouts are specific to the HTTP protocol and work
// independently of the overall timeouts passed to `io.poll.poll-list`.
- // The timeout for the initial connect.
+ /// The timeout for the initial connect.
connect-timeout-ms: option<u32>,
- // The timeout for receiving the first byte of the response body.
+ /// The timeout for receiving the first byte of the response body.
first-byte-timeout-ms: option<u32>,
- // The timeout for receiving the next chunk of bytes in the response body
- // stream.
+ /// The timeout for receiving the next chunk of bytes in the response body
+ /// stream.
between-bytes-timeout-ms: option<u32>
}
- // The following block defines a special resource type used by the
- // `wasi:http/incoming-handler` interface. When resource types are added, this
- // block can be replaced by a proper `resource response-outparam { ... }`
- // definition. Later, with Preview3, the need for an outparam goes away entirely
- // (the `wasi:http/handler` interface used for both incoming and outgoing can
- // simply return a `stream`).
+ /// The following block defines a special resource type used by the
+ /// `wasi:http/incoming-handler` interface. When resource types are added, this
+ /// block can be replaced by a proper `resource response-outparam { ... }`
+ /// definition. Later, with Preview3, the need for an outparam goes away entirely
+ /// (the `wasi:http/handler` interface used for both incoming and outgoing can
+ /// simply return a `stream`).
resource response-outparam {
set: static func(param: response-outparam, response: result<outgoing-response, error>)
}
@@ -135,13 +132,10 @@ interface types {
// This type corresponds to the HTTP standard Status Code.
type status-code = u16
- // The following block defines the `incoming-response` and `outgoing-response`
- // resource types that correspond to HTTP standard Responses. Soon, when
- // resource types are added, the `u32` type aliases can be replaced by proper
- // `resource` type definitions containing all the functions as methods. Later,
- // Preview2 will allow both types to be merged together into a single `response`
- // type (that uses the single `stream` type mentioned above). The `consume` and
- // `write` methods may only be called once (and return failure thereafter).
+ /// The following block defines the `incoming-response` and `outgoing-response`
+ /// resource types that correspond to HTTP standard Responses.
+ ///
+ /// The `consume` and `write` methods may only be called once (and return failure thereafter).
resource incoming-response {
status: func() -> status-code
diff --git a/wit/preview2/world.wit b/wit/preview2/world.wit
index 5aa0294754..4454459b78 100644
--- a/wit/preview2/world.wit
+++ b/wit/preview2/world.wit
@@ -20,6 +20,7 @@ world platform {
import fermyon:spin/http
import fermyon:spin/mysql
import fermyon:spin/llm
+ import wasi:http/outgoing-handler
import redis
import postgres
| 1,887
|
[
"1372"
] |
diff --git a/tests/http/headers-env-routes-test/Cargo.lock b/tests/http/headers-env-routes-test/Cargo.lock
index 40d01ab1bc..709cb10ba8 100644
--- a/tests/http/headers-env-routes-test/Cargo.lock
+++ b/tests/http/headers-env-routes-test/Cargo.lock
@@ -8,6 +8,17 @@ version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
+[[package]]
+name = "async-trait"
+version = "0.1.74"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.37",
+]
+
[[package]]
name = "autocfg"
version = "1.1.0"
@@ -50,9 +61,9 @@ checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "form_urlencoded"
-version = "1.1.0"
+version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a9c384f161156f5260c24a097c56119f9be8c798586aecc13afbcbe7b7e26bf8"
+checksum = "a62bc1cf6f830c2ec14a513a9fb124d0a213a629668a4186f329db21fe045652"
dependencies = [
"percent-encoding",
]
@@ -221,9 +232,9 @@ checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d"
[[package]]
name = "percent-encoding"
-version = "2.2.0"
+version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "478c572c3d73181ff3c2539045f6eb99e5491218eae919370993b890cdbdd98e"
+checksum = "9b2a4787296e9989611394c33f193f676704af1686e70b8f8033ab5ba9a35a94"
[[package]]
name = "pin-project-lite"
@@ -248,9 +259,9 @@ dependencies = [
[[package]]
name = "quote"
-version = "1.0.28"
+version = "1.0.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1b9ab9c7eadfd8df19006f1cf1a4aed13540ed5cbc047010ece5826e10825488"
+checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae"
dependencies = [
"proc-macro2",
]
@@ -369,12 +380,15 @@ name = "spin-sdk"
version = "2.0.0-pre0"
dependencies = [
"anyhow",
+ "async-trait",
"bytes",
"form_urlencoded",
"futures",
"http",
"once_cell",
"routefinder",
+ "serde",
+ "serde_json",
"spin-macro",
"thiserror",
"wit-bindgen",
diff --git a/tests/http/headers-env-routes-test/src/lib.rs b/tests/http/headers-env-routes-test/src/lib.rs
index 3cad5a7359..74d0b66633 100644
--- a/tests/http/headers-env-routes-test/src/lib.rs
+++ b/tests/http/headers-env-routes-test/src/lib.rs
@@ -1,23 +1,19 @@
use anyhow::Result;
-use spin_sdk::{
- http::{Request, Response},
- http_component
-};
+use spin_sdk::http_component;
// This handler does the following:
// - returns all environment variables as headers with an ENV_ prefix
// - returns all request headers as response headers.
#[http_component]
-fn handle_http_request(req: Request) -> Result<Response> {
- match append_headers(http::Response::builder(), &req) {
- Err(e) => anyhow::bail!("Unable to append headers to response: {}", e),
- Ok(resp) => Ok(resp
- .status(200)
- .body(Some("I'm a teapot".into()))?)
- }
+fn handle_http_request(req: http::Request<()>) -> Result<http::Response<&'static str>> {
+ let resp = append_headers(http::Response::builder(), &req);
+ Ok(resp.status(200).body("I'm a teapot")?)
}
-fn append_headers(mut resp: http::response::Builder, req: &Request) -> Result<http::response::Builder> {
+fn append_headers(
+ mut resp: http::response::Builder,
+ req: &http::Request<()>,
+) -> http::response::Builder {
for (k, v) in std::env::vars() {
resp = resp.header(format!("ENV_{}", k), v);
}
@@ -25,5 +21,5 @@ fn append_headers(mut resp: http::response::Builder, req: &Request) -> Result<ht
resp = resp.header(k, v);
}
- Ok(resp)
+ resp
}
diff --git a/tests/http/simple-spin-rust/Cargo.lock b/tests/http/simple-spin-rust/Cargo.lock
index 6a9cd3b5e3..ba49c38825 100644
--- a/tests/http/simple-spin-rust/Cargo.lock
+++ b/tests/http/simple-spin-rust/Cargo.lock
@@ -8,6 +8,17 @@ version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
+[[package]]
+name = "async-trait"
+version = "0.1.74"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.37",
+]
+
[[package]]
name = "autocfg"
version = "1.1.0"
@@ -40,11 +51,10 @@ checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "form_urlencoded"
-version = "1.0.1"
+version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5fc25a87fa4fd2094bffb06925852034d90a17f0d1e05197d4956d3555752191"
+checksum = "a62bc1cf6f830c2ec14a513a9fb124d0a213a629668a4186f329db21fe045652"
dependencies = [
- "matches",
"percent-encoding",
]
@@ -198,12 +208,6 @@ version = "0.4.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b06a4cde4c0f271a446782e3eff8de789548ce57dbc8eca9292c27f4a42004b4"
-[[package]]
-name = "matches"
-version = "0.1.9"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a3e378b66a060d48947b590737b30a1be76706c8dd7b8ba0f2fe3989c68a853f"
-
[[package]]
name = "memchr"
version = "2.6.3"
@@ -218,9 +222,9 @@ checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d"
[[package]]
name = "percent-encoding"
-version = "2.1.0"
+version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d4fd5641d01c8f18a23da7b6fe29298ff4b55afcccdf78973b24cf3175fee32e"
+checksum = "9b2a4787296e9989611394c33f193f676704af1686e70b8f8033ab5ba9a35a94"
[[package]]
name = "pin-project-lite"
@@ -245,9 +249,9 @@ dependencies = [
[[package]]
name = "quote"
-version = "1.0.28"
+version = "1.0.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1b9ab9c7eadfd8df19006f1cf1a4aed13540ed5cbc047010ece5826e10825488"
+checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae"
dependencies = [
"proc-macro2",
]
@@ -376,12 +380,15 @@ name = "spin-sdk"
version = "2.0.0-pre0"
dependencies = [
"anyhow",
+ "async-trait",
"bytes",
"form_urlencoded",
"futures",
"http",
"once_cell",
"routefinder",
+ "serde",
+ "serde_json",
"spin-macro",
"thiserror",
"wit-bindgen",
diff --git a/tests/http/simple-spin-rust/src/lib.rs b/tests/http/simple-spin-rust/src/lib.rs
index f40d5c2b14..ad7fa5b096 100644
--- a/tests/http/simple-spin-rust/src/lib.rs
+++ b/tests/http/simple-spin-rust/src/lib.rs
@@ -1,26 +1,18 @@
use anyhow::Result;
-use spin_sdk::{
- config,
- http::{Request, Response},
- http_component,
-};
+use spin_sdk::{config, http_component};
#[http_component]
-fn hello_world(req: Request) -> Result<Response> {
+fn hello_world(req: http::Request<()>) -> Result<http::Response<String>> {
let path = req.uri().path();
if path.contains("test-placement") {
match std::fs::read_to_string("/test.txt") {
- Ok(txt) => Ok(http::Response::builder()
- .status(200)
- .body(Some(txt.into()))?),
+ Ok(txt) => Ok(http::Response::builder().status(200).body(txt)?),
Err(e) => anyhow::bail!("Error, could not access test.txt: {}", e),
}
} else {
let msg = config::get("message").expect("Failed to acquire message from spin.toml");
- Ok(http::Response::builder()
- .status(200)
- .body(Some(msg.into()))?)
+ Ok(http::Response::builder().status(200).body(msg)?)
}
}
diff --git a/tests/http/vault-config-test/Cargo.lock b/tests/http/vault-config-test/Cargo.lock
index 447d6e6aa7..fcf5786ea2 100644
--- a/tests/http/vault-config-test/Cargo.lock
+++ b/tests/http/vault-config-test/Cargo.lock
@@ -8,6 +8,17 @@ version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
+[[package]]
+name = "async-trait"
+version = "0.1.74"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.38",
+]
+
[[package]]
name = "autocfg"
version = "1.1.0"
@@ -359,12 +370,15 @@ name = "spin-sdk"
version = "2.0.0-pre0"
dependencies = [
"anyhow",
+ "async-trait",
"bytes",
"form_urlencoded",
"futures",
"http",
"once_cell",
"routefinder",
+ "serde",
+ "serde_json",
"spin-macro",
"thiserror",
"wit-bindgen",
diff --git a/tests/http/vault-config-test/src/lib.rs b/tests/http/vault-config-test/src/lib.rs
index cf130e43b1..330397eab1 100644
--- a/tests/http/vault-config-test/src/lib.rs
+++ b/tests/http/vault-config-test/src/lib.rs
@@ -1,18 +1,14 @@
use anyhow::Result;
-use spin_sdk::{
- config,
- http::{Request, Response},
- http_component,
-};
+use spin_sdk::{config, http_component};
/// A simple Spin HTTP component.
#[http_component]
-fn config_test(_req: Request) -> Result<Response> {
+fn config_test(_req: http::Request<()>) -> Result<http::Response<String>> {
// Ensure we can get a value from Vault
let password = config::get("password").expect("Failed to acquire password from vault");
// Ensure we can get a defaulted value
let greeting = config::get("greeting").expect("Failed to acquire greeting from default");
Ok(http::Response::builder()
.status(200)
- .body(Some(format!("{} Got password {}", greeting, password).into()))?)
+ .body(format!("{} Got password {}", greeting, password))?)
}
diff --git a/tests/outbound-redis/http-rust-outbound-redis/Cargo.lock b/tests/outbound-redis/http-rust-outbound-redis/Cargo.lock
index 0dc8ed2983..9c9aceaa2d 100644
--- a/tests/outbound-redis/http-rust-outbound-redis/Cargo.lock
+++ b/tests/outbound-redis/http-rust-outbound-redis/Cargo.lock
@@ -8,6 +8,17 @@ version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
+[[package]]
+name = "async-trait"
+version = "0.1.74"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.37",
+]
+
[[package]]
name = "autocfg"
version = "1.1.0"
@@ -40,9 +51,9 @@ checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "form_urlencoded"
-version = "1.1.0"
+version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a9c384f161156f5260c24a097c56119f9be8c798586aecc13afbcbe7b7e26bf8"
+checksum = "a62bc1cf6f830c2ec14a513a9fb124d0a213a629668a4186f329db21fe045652"
dependencies = [
"percent-encoding",
]
@@ -221,9 +232,9 @@ checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d"
[[package]]
name = "percent-encoding"
-version = "2.2.0"
+version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "478c572c3d73181ff3c2539045f6eb99e5491218eae919370993b890cdbdd98e"
+checksum = "9b2a4787296e9989611394c33f193f676704af1686e70b8f8033ab5ba9a35a94"
[[package]]
name = "pin-project-lite"
@@ -369,12 +380,15 @@ name = "spin-sdk"
version = "2.0.0-pre0"
dependencies = [
"anyhow",
+ "async-trait",
"bytes",
"form_urlencoded",
"futures",
"http",
"once_cell",
"routefinder",
+ "serde",
+ "serde_json",
"spin-macro",
"thiserror",
"wit-bindgen",
diff --git a/tests/outbound-redis/http-rust-outbound-redis/src/lib.rs b/tests/outbound-redis/http-rust-outbound-redis/src/lib.rs
index fe42b6b4a4..45342f4ca7 100644
--- a/tests/outbound-redis/http-rust-outbound-redis/src/lib.rs
+++ b/tests/outbound-redis/http-rust-outbound-redis/src/lib.rs
@@ -1,6 +1,5 @@
use anyhow::{anyhow, Context, Result};
use spin_sdk::{
- http::{Request, Response},
http_component,
redis::{self, RedisParameter, RedisResult},
};
@@ -9,7 +8,7 @@ use std::collections::HashSet;
const REDIS_ADDRESS_ENV: &str = "REDIS_ADDRESS";
#[http_component]
-fn test(_req: Request) -> Result<Response> {
+fn test(_req: http::Request<()>) -> Result<http::Response<()>> {
let address = std::env::var(REDIS_ADDRESS_ENV)?;
let connection = redis::Connection::open(&address)?;
@@ -143,5 +142,5 @@ fn test(_req: Request) -> Result<Response> {
.collect::<HashSet<_>>()
);
- Ok(http::Response::builder().status(204).body(None)?)
+ Ok(http::Response::builder().status(204).body(())?)
}
diff --git a/tests/testcases/config-variables/Cargo.lock b/tests/testcases/config-variables/Cargo.lock
index 9ce48569a8..e8076ecda9 100644
--- a/tests/testcases/config-variables/Cargo.lock
+++ b/tests/testcases/config-variables/Cargo.lock
@@ -8,6 +8,17 @@ version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
+[[package]]
+name = "async-trait"
+version = "0.1.74"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.38",
+]
+
[[package]]
name = "autocfg"
version = "1.1.0"
@@ -381,12 +392,15 @@ name = "spin-sdk"
version = "2.0.0-pre0"
dependencies = [
"anyhow",
+ "async-trait",
"bytes",
"form_urlencoded",
"futures",
"http",
"once_cell",
"routefinder",
+ "serde",
+ "serde_json",
"spin-macro",
"thiserror",
"wit-bindgen",
diff --git a/tests/testcases/config-variables/src/lib.rs b/tests/testcases/config-variables/src/lib.rs
index f1e0d962db..6fe2a4d52a 100644
--- a/tests/testcases/config-variables/src/lib.rs
+++ b/tests/testcases/config-variables/src/lib.rs
@@ -1,12 +1,8 @@
use anyhow::{ensure, Result};
-use spin_sdk::{
- config,
- http::{Request, Response},
- http_component,
-};
+use spin_sdk::{config, http_component};
#[http_component]
-fn handle_request(req: Request) -> Result<Response> {
+fn handle_request(req: http::Request<()>) -> Result<http::Response<()>> {
let query = req
.uri()
.query()
@@ -24,5 +20,5 @@ fn handle_request(req: Request) -> Result<Response> {
expected_password_value
);
- Ok(http::Response::builder().status(200).body(None)?)
+ Ok(http::Response::builder().status(200).body(())?)
}
diff --git a/tests/testcases/head-rust-sdk-http/Cargo.lock b/tests/testcases/head-rust-sdk-http/Cargo.lock
index b5129c724c..35df45803c 100644
--- a/tests/testcases/head-rust-sdk-http/Cargo.lock
+++ b/tests/testcases/head-rust-sdk-http/Cargo.lock
@@ -8,6 +8,17 @@ version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
+[[package]]
+name = "async-trait"
+version = "0.1.74"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.38",
+]
+
[[package]]
name = "autocfg"
version = "1.1.0"
@@ -369,12 +380,15 @@ name = "spin-sdk"
version = "2.0.0-pre0"
dependencies = [
"anyhow",
+ "async-trait",
"bytes",
"form_urlencoded",
"futures",
"http",
"once_cell",
"routefinder",
+ "serde",
+ "serde_json",
"spin-macro",
"thiserror",
"wit-bindgen",
diff --git a/tests/testcases/head-rust-sdk-http/src/lib.rs b/tests/testcases/head-rust-sdk-http/src/lib.rs
index f40d5c2b14..ad7fa5b096 100644
--- a/tests/testcases/head-rust-sdk-http/src/lib.rs
+++ b/tests/testcases/head-rust-sdk-http/src/lib.rs
@@ -1,26 +1,18 @@
use anyhow::Result;
-use spin_sdk::{
- config,
- http::{Request, Response},
- http_component,
-};
+use spin_sdk::{config, http_component};
#[http_component]
-fn hello_world(req: Request) -> Result<Response> {
+fn hello_world(req: http::Request<()>) -> Result<http::Response<String>> {
let path = req.uri().path();
if path.contains("test-placement") {
match std::fs::read_to_string("/test.txt") {
- Ok(txt) => Ok(http::Response::builder()
- .status(200)
- .body(Some(txt.into()))?),
+ Ok(txt) => Ok(http::Response::builder().status(200).body(txt)?),
Err(e) => anyhow::bail!("Error, could not access test.txt: {}", e),
}
} else {
let msg = config::get("message").expect("Failed to acquire message from spin.toml");
- Ok(http::Response::builder()
- .status(200)
- .body(Some(msg.into()))?)
+ Ok(http::Response::builder().status(200).body(msg)?)
}
}
diff --git a/tests/testcases/head-rust-sdk-redis/Cargo.lock b/tests/testcases/head-rust-sdk-redis/Cargo.lock
index 81dd3dd1e2..4a5af01b89 100644
--- a/tests/testcases/head-rust-sdk-redis/Cargo.lock
+++ b/tests/testcases/head-rust-sdk-redis/Cargo.lock
@@ -8,6 +8,17 @@ version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
+[[package]]
+name = "async-trait"
+version = "0.1.74"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.38",
+]
+
[[package]]
name = "autocfg"
version = "1.1.0"
@@ -369,12 +380,15 @@ name = "spin-sdk"
version = "2.0.0-pre0"
dependencies = [
"anyhow",
+ "async-trait",
"bytes",
"form_urlencoded",
"futures",
"http",
"once_cell",
"routefinder",
+ "serde",
+ "serde_json",
"spin-macro",
"thiserror",
"wit-bindgen",
diff --git a/tests/testcases/headers-dynamic-env-test/Cargo.lock b/tests/testcases/headers-dynamic-env-test/Cargo.lock
index 79371656f1..a3c4d44d2a 100644
--- a/tests/testcases/headers-dynamic-env-test/Cargo.lock
+++ b/tests/testcases/headers-dynamic-env-test/Cargo.lock
@@ -8,6 +8,17 @@ version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
+[[package]]
+name = "async-trait"
+version = "0.1.74"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.38",
+]
+
[[package]]
name = "autocfg"
version = "1.1.0"
@@ -369,12 +380,15 @@ name = "spin-sdk"
version = "2.0.0-pre0"
dependencies = [
"anyhow",
+ "async-trait",
"bytes",
"form_urlencoded",
"futures",
"http",
"once_cell",
"routefinder",
+ "serde",
+ "serde_json",
"spin-macro",
"thiserror",
"wit-bindgen",
diff --git a/tests/testcases/headers-dynamic-env-test/src/lib.rs b/tests/testcases/headers-dynamic-env-test/src/lib.rs
index 5e83353404..94a46f6074 100644
--- a/tests/testcases/headers-dynamic-env-test/src/lib.rs
+++ b/tests/testcases/headers-dynamic-env-test/src/lib.rs
@@ -1,24 +1,19 @@
use anyhow::Result;
-use spin_sdk::{
- http::{Request, Response},
- http_component,
-};
+use spin_sdk::{http::IntoResponse, http_component};
// This handler does the following:
// - returns all environment variables as headers with an ENV_ prefix
// - returns all request headers as response headers.
#[http_component]
-fn handle_http_request(req: Request) -> Result<Response> {
- match append_headers(http::Response::builder(), &req) {
- Err(e) => anyhow::bail!("Unable to append headers to response: {}", e),
- Ok(resp) => Ok(resp.status(200).body(Some("I'm a teapot".into()))?),
- }
+fn handle_http_request(req: http::Request<()>) -> Result<impl IntoResponse> {
+ let resp = append_headers(http::Response::builder(), &req);
+ Ok(resp.status(200).body(Some("I'm a teapot"))?)
}
fn append_headers(
mut resp: http::response::Builder,
- req: &Request,
-) -> Result<http::response::Builder> {
+ req: &http::Request<()>,
+) -> http::response::Builder {
for (k, v) in std::env::vars() {
resp = resp.header(format!("ENV_{}", k), v);
}
@@ -26,5 +21,5 @@ fn append_headers(
resp = resp.header(k, v);
}
- Ok(resp)
+ resp
}
diff --git a/tests/testcases/headers-env-routes-test/Cargo.lock b/tests/testcases/headers-env-routes-test/Cargo.lock
index 1cf9f747ba..c6564a6182 100644
--- a/tests/testcases/headers-env-routes-test/Cargo.lock
+++ b/tests/testcases/headers-env-routes-test/Cargo.lock
@@ -8,6 +8,17 @@ version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
+[[package]]
+name = "async-trait"
+version = "0.1.74"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.38",
+]
+
[[package]]
name = "autocfg"
version = "1.1.0"
@@ -369,12 +380,15 @@ name = "spin-sdk"
version = "2.0.0-pre0"
dependencies = [
"anyhow",
+ "async-trait",
"bytes",
"form_urlencoded",
"futures",
"http",
"once_cell",
"routefinder",
+ "serde",
+ "serde_json",
"spin-macro",
"thiserror",
"wit-bindgen",
diff --git a/tests/testcases/headers-env-routes-test/src/lib.rs b/tests/testcases/headers-env-routes-test/src/lib.rs
index 5e83353404..94a46f6074 100644
--- a/tests/testcases/headers-env-routes-test/src/lib.rs
+++ b/tests/testcases/headers-env-routes-test/src/lib.rs
@@ -1,24 +1,19 @@
use anyhow::Result;
-use spin_sdk::{
- http::{Request, Response},
- http_component,
-};
+use spin_sdk::{http::IntoResponse, http_component};
// This handler does the following:
// - returns all environment variables as headers with an ENV_ prefix
// - returns all request headers as response headers.
#[http_component]
-fn handle_http_request(req: Request) -> Result<Response> {
- match append_headers(http::Response::builder(), &req) {
- Err(e) => anyhow::bail!("Unable to append headers to response: {}", e),
- Ok(resp) => Ok(resp.status(200).body(Some("I'm a teapot".into()))?),
- }
+fn handle_http_request(req: http::Request<()>) -> Result<impl IntoResponse> {
+ let resp = append_headers(http::Response::builder(), &req);
+ Ok(resp.status(200).body(Some("I'm a teapot"))?)
}
fn append_headers(
mut resp: http::response::Builder,
- req: &Request,
-) -> Result<http::response::Builder> {
+ req: &http::Request<()>,
+) -> http::response::Builder {
for (k, v) in std::env::vars() {
resp = resp.header(format!("ENV_{}", k), v);
}
@@ -26,5 +21,5 @@ fn append_headers(
resp = resp.header(k, v);
}
- Ok(resp)
+ resp
}
diff --git a/tests/testcases/http-rust-outbound-mysql/Cargo.lock b/tests/testcases/http-rust-outbound-mysql/Cargo.lock
index f9a1fb0cc9..1ccc331255 100644
--- a/tests/testcases/http-rust-outbound-mysql/Cargo.lock
+++ b/tests/testcases/http-rust-outbound-mysql/Cargo.lock
@@ -8,6 +8,17 @@ version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
+[[package]]
+name = "async-trait"
+version = "0.1.74"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.38",
+]
+
[[package]]
name = "autocfg"
version = "1.1.0"
@@ -369,12 +380,15 @@ name = "spin-sdk"
version = "2.0.0-pre0"
dependencies = [
"anyhow",
+ "async-trait",
"bytes",
"form_urlencoded",
"futures",
"http",
"once_cell",
"routefinder",
+ "serde",
+ "serde_json",
"spin-macro",
"thiserror",
"wit-bindgen",
diff --git a/tests/testcases/http-rust-outbound-mysql/src/lib.rs b/tests/testcases/http-rust-outbound-mysql/src/lib.rs
index 4745066897..abafc86588 100644
--- a/tests/testcases/http-rust-outbound-mysql/src/lib.rs
+++ b/tests/testcases/http-rust-outbound-mysql/src/lib.rs
@@ -1,7 +1,6 @@
#![allow(dead_code)]
use anyhow::{anyhow, Result};
use spin_sdk::{
- http::{Request, Response},
http_component,
mysql::{self, Decode},
};
@@ -39,17 +38,17 @@ struct CharacterRow {
}
#[http_component]
-fn process(req: Request) -> Result<Response> {
+fn process(req: http::Request<()>) -> Result<http::Response<String>> {
match req.uri().path() {
"/test_character_types" => test_character_types(req),
"/test_numeric_types" => test_numeric_types(req),
_ => Ok(http::Response::builder()
.status(404)
- .body(Some("Not found".into()))?),
+ .body("Not found".into())?),
}
}
-fn test_numeric_types(_req: Request) -> Result<Response> {
+fn test_numeric_types(_req: http::Request<()>) -> Result<http::Response<String>> {
let address = std::env::var(DB_URL_ENV)?;
let create_table_sql = r#"
@@ -155,12 +154,10 @@ fn test_numeric_types(_req: Request) -> Result<Response> {
column_summary,
);
- Ok(http::Response::builder()
- .status(200)
- .body(Some(response.into()))?)
+ Ok(http::Response::builder().status(200).body(response)?)
}
-fn test_character_types(_req: Request) -> Result<Response> {
+fn test_character_types(_req: http::Request<()>) -> Result<http::Response<String>> {
let address = std::env::var(DB_URL_ENV)?;
let create_table_sql = r#"
@@ -230,9 +227,7 @@ fn test_character_types(_req: Request) -> Result<Response> {
column_summary,
);
- Ok(http::Response::builder()
- .status(200)
- .body(Some(response.into()))?)
+ Ok(http::Response::builder().status(200).body(response)?)
}
fn format_col(column: &mysql::Column) -> String {
diff --git a/tests/testcases/http-rust-outbound-pg/Cargo.lock b/tests/testcases/http-rust-outbound-pg/Cargo.lock
index aba0fe9a80..3d972b6dfd 100644
--- a/tests/testcases/http-rust-outbound-pg/Cargo.lock
+++ b/tests/testcases/http-rust-outbound-pg/Cargo.lock
@@ -8,6 +8,17 @@ version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
+[[package]]
+name = "async-trait"
+version = "0.1.74"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.38",
+]
+
[[package]]
name = "autocfg"
version = "1.1.0"
@@ -369,12 +380,15 @@ name = "spin-sdk"
version = "2.0.0-pre0"
dependencies = [
"anyhow",
+ "async-trait",
"bytes",
"form_urlencoded",
"futures",
"http",
"once_cell",
"routefinder",
+ "serde",
+ "serde_json",
"spin-macro",
"thiserror",
"wit-bindgen",
diff --git a/tests/testcases/http-rust-outbound-pg/src/lib.rs b/tests/testcases/http-rust-outbound-pg/src/lib.rs
index 5c7faa396b..dd4fa5d324 100644
--- a/tests/testcases/http-rust-outbound-pg/src/lib.rs
+++ b/tests/testcases/http-rust-outbound-pg/src/lib.rs
@@ -1,7 +1,6 @@
#![allow(dead_code)]
use anyhow::Result;
use spin_sdk::{
- http::{Request, Response},
http_component,
pg::{self, Decode},
};
@@ -41,7 +40,7 @@ struct GeneralRow<'a> {
}
#[http_component]
-fn process(req: Request) -> Result<Response> {
+fn process(req: http::Request<()>) -> Result<http::Response<String>> {
match req.uri().path() {
"/test_character_types" => test_character_types(req),
"/test_numeric_types" => test_numeric_types(req),
@@ -49,11 +48,11 @@ fn process(req: Request) -> Result<Response> {
"/pg_backend_pid" => pg_backend_pid(req),
_ => Ok(http::Response::builder()
.status(404)
- .body(Some("Not found".into()))?),
+ .body("Not found".into())?),
}
}
-fn test_numeric_types(_req: Request) -> Result<Response> {
+fn test_numeric_types(_req: http::Request<()>) -> Result<http::Response<String>> {
let address = std::env::var(DB_URL_ENV)?;
let conn = pg::Connection::open(&address)?;
@@ -152,12 +151,10 @@ fn test_numeric_types(_req: Request) -> Result<Response> {
column_summary,
);
- Ok(http::Response::builder()
- .status(200)
- .body(Some(response.into()))?)
+ Ok(http::Response::builder().status(200).body(response)?)
}
-fn test_character_types(_req: Request) -> Result<Response> {
+fn test_character_types(_req: http::Request<()>) -> Result<http::Response<String>> {
let address = std::env::var(DB_URL_ENV)?;
let conn = pg::Connection::open(&address)?;
@@ -218,12 +215,10 @@ fn test_character_types(_req: Request) -> Result<Response> {
column_summary,
);
- Ok(http::Response::builder()
- .status(200)
- .body(Some(response.into()))?)
+ Ok(http::Response::builder().status(200).body(response)?)
}
-fn test_general_types(_req: Request) -> Result<Response> {
+fn test_general_types(_req: http::Request<()>) -> Result<http::Response<String>> {
let address = std::env::var(DB_URL_ENV)?;
let conn = pg::Connection::open(&address)?;
@@ -284,12 +279,10 @@ fn test_general_types(_req: Request) -> Result<Response> {
column_summary,
);
- Ok(http::Response::builder()
- .status(200)
- .body(Some(response.into()))?)
+ Ok(http::Response::builder().status(200).body(response)?)
}
-fn pg_backend_pid(_req: Request) -> Result<Response> {
+fn pg_backend_pid(_req: http::Request<()>) -> Result<http::Response<String>> {
let address = std::env::var(DB_URL_ENV)?;
let conn = pg::Connection::open(&address)?;
let sql = "SELECT pg_backend_pid()";
@@ -305,9 +298,7 @@ fn pg_backend_pid(_req: Request) -> Result<Response> {
let response = format!("pg_backend_pid: {}\n", get_pid()?);
- Ok(http::Response::builder()
- .status(200)
- .body(Some(response.into()))?)
+ Ok(http::Response::builder().status(200).body(response)?)
}
fn format_col(column: &pg::Column) -> String {
diff --git a/tests/testcases/key-value-undefined-store/Cargo.lock b/tests/testcases/key-value-undefined-store/Cargo.lock
index 2af1efbb4f..2c5526f118 100644
--- a/tests/testcases/key-value-undefined-store/Cargo.lock
+++ b/tests/testcases/key-value-undefined-store/Cargo.lock
@@ -8,6 +8,17 @@ version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
+[[package]]
+name = "async-trait"
+version = "0.1.74"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.38",
+]
+
[[package]]
name = "autocfg"
version = "1.1.0"
@@ -398,12 +409,15 @@ name = "spin-sdk"
version = "2.0.0-pre0"
dependencies = [
"anyhow",
+ "async-trait",
"bytes",
"form_urlencoded",
"futures",
"http",
"once_cell",
"routefinder",
+ "serde",
+ "serde_json",
"spin-macro",
"thiserror",
"wit-bindgen",
diff --git a/tests/testcases/key-value-undefined-store/src/lib.rs b/tests/testcases/key-value-undefined-store/src/lib.rs
index 4e2739d5b5..e1a6c3b8f9 100644
--- a/tests/testcases/key-value-undefined-store/src/lib.rs
+++ b/tests/testcases/key-value-undefined-store/src/lib.rs
@@ -1,12 +1,9 @@
use anyhow::Result;
-use spin_sdk::{
- http::{Request, Response},
- http_component,
-};
+use spin_sdk::http_component;
#[http_component]
-fn handle_request(_req: Request) -> Result<Response> {
+fn handle_request(_req: http::Request<()>) -> Result<http::Response<()>> {
// We don't need to do anything here: it should never get called because
// spin up should fail at K/V validation.
- Ok(http::Response::builder().status(200).body(None)?)
+ Ok(http::Response::builder().status(200).body(())?)
}
diff --git a/tests/testcases/key-value/Cargo.lock b/tests/testcases/key-value/Cargo.lock
index 03d4e1de9a..2430ae8401 100644
--- a/tests/testcases/key-value/Cargo.lock
+++ b/tests/testcases/key-value/Cargo.lock
@@ -8,6 +8,17 @@ version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
+[[package]]
+name = "async-trait"
+version = "0.1.74"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.38",
+]
+
[[package]]
name = "autocfg"
version = "1.1.0"
@@ -398,12 +409,15 @@ name = "spin-sdk"
version = "2.0.0-pre0"
dependencies = [
"anyhow",
+ "async-trait",
"bytes",
"form_urlencoded",
"futures",
"http",
"once_cell",
"routefinder",
+ "serde",
+ "serde_json",
"spin-macro",
"thiserror",
"wit-bindgen",
diff --git a/tests/testcases/key-value/src/lib.rs b/tests/testcases/key-value/src/lib.rs
index aecb6a911c..8d4a4ff56e 100644
--- a/tests/testcases/key-value/src/lib.rs
+++ b/tests/testcases/key-value/src/lib.rs
@@ -1,13 +1,12 @@
use anyhow::{ensure, Result};
use itertools::sorted;
use spin_sdk::{
- http::{Request, Response},
http_component,
key_value::{Error, Store},
};
#[http_component]
-fn handle_request(req: Request) -> Result<Response> {
+fn handle_request(req: http::Request<()>) -> Result<http::Response<()>> {
// TODO: once we allow users to pass non-default stores, test that opening
// an allowed-but-non-existent one returns Error::NoSuchStore
ensure!(matches!(Store::open("forbidden"), Err(Error::AccessDenied)));
@@ -66,5 +65,5 @@ fn handle_request(req: Request) -> Result<Response> {
ensure!(matches!(store.get("bar"), Ok(None)));
- Ok(http::Response::builder().status(200).body(None)?)
+ Ok(http::Response::builder().status(200).body(())?)
}
diff --git a/tests/testcases/outbound-http-to-same-app/http-component/Cargo.lock b/tests/testcases/outbound-http-to-same-app/http-component/Cargo.lock
index d33c39eed1..763d8ead6d 100644
--- a/tests/testcases/outbound-http-to-same-app/http-component/Cargo.lock
+++ b/tests/testcases/outbound-http-to-same-app/http-component/Cargo.lock
@@ -8,6 +8,17 @@ version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
+[[package]]
+name = "async-trait"
+version = "0.1.74"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.37",
+]
+
[[package]]
name = "autocfg"
version = "1.1.0"
@@ -369,12 +380,15 @@ name = "spin-sdk"
version = "2.0.0-pre0"
dependencies = [
"anyhow",
+ "async-trait",
"bytes",
"form_urlencoded",
"futures",
"http",
"once_cell",
"routefinder",
+ "serde",
+ "serde_json",
"spin-macro",
"thiserror",
"wit-bindgen",
diff --git a/tests/testcases/outbound-http-to-same-app/http-component/src/lib.rs b/tests/testcases/outbound-http-to-same-app/http-component/src/lib.rs
index fe34f4338c..6deca439de 100644
--- a/tests/testcases/outbound-http-to-same-app/http-component/src/lib.rs
+++ b/tests/testcases/outbound-http-to-same-app/http-component/src/lib.rs
@@ -1,15 +1,12 @@
use anyhow::Result;
-use spin_sdk::{
- http::{Request, Response},
- http_component,
-};
+use spin_sdk::http_component;
/// A simple Spin HTTP component.
#[http_component]
-fn hello_world(req: Request) -> Result<Response> {
+fn hello_world(req: http::Request<()>) -> Result<http::Response<&'static str>> {
println!("{:?}", req.headers());
Ok(http::Response::builder()
.status(200)
.header("foo", "bar")
- .body(Some("Hello, Fermyon!\n".into()))?)
+ .body("Hello, Fermyon!\n")?)
}
diff --git a/tests/testcases/outbound-http-to-same-app/outbound-http-component/Cargo.lock b/tests/testcases/outbound-http-to-same-app/outbound-http-component/Cargo.lock
index b37d357d8d..5e1a580f77 100644
--- a/tests/testcases/outbound-http-to-same-app/outbound-http-component/Cargo.lock
+++ b/tests/testcases/outbound-http-to-same-app/outbound-http-component/Cargo.lock
@@ -8,6 +8,17 @@ version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
+[[package]]
+name = "async-trait"
+version = "0.1.74"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.37",
+]
+
[[package]]
name = "autocfg"
version = "1.1.0"
@@ -369,12 +380,15 @@ name = "spin-sdk"
version = "2.0.0-pre0"
dependencies = [
"anyhow",
+ "async-trait",
"bytes",
"form_urlencoded",
"futures",
"http",
"once_cell",
"routefinder",
+ "serde",
+ "serde_json",
"spin-macro",
"thiserror",
"wit-bindgen",
diff --git a/tests/testcases/outbound-http-to-same-app/outbound-http-component/src/lib.rs b/tests/testcases/outbound-http-to-same-app/outbound-http-component/src/lib.rs
index 30eaf71375..5acd429cbb 100644
--- a/tests/testcases/outbound-http-to-same-app/outbound-http-component/src/lib.rs
+++ b/tests/testcases/outbound-http-to-same-app/outbound-http-component/src/lib.rs
@@ -1,17 +1,17 @@
use anyhow::Result;
use spin_sdk::{
- http::{Request, Response},
+ http::{IntoResponse, Request},
http_component,
};
/// Send an HTTP request and return the response.
#[http_component]
-fn send_outbound(_req: Request) -> Result<Response> {
- let mut res = spin_sdk::outbound_http::send_request(
+fn send_outbound(_req: Request) -> Result<impl IntoResponse> {
+ let mut res: http::Response<String> = spin_sdk::http::send(
http::Request::builder()
.method("GET")
.uri("/test/hello")
- .body(None)?,
+ .body(())?,
)?;
res.headers_mut()
.insert("spin-component", "outbound-http-component".try_into()?);
diff --git a/tests/testcases/sqlite-undefined-db/Cargo.lock b/tests/testcases/sqlite-undefined-db/Cargo.lock
index 416e98896b..dfee9d97e0 100644
--- a/tests/testcases/sqlite-undefined-db/Cargo.lock
+++ b/tests/testcases/sqlite-undefined-db/Cargo.lock
@@ -8,6 +8,17 @@ version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
+[[package]]
+name = "async-trait"
+version = "0.1.74"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.38",
+]
+
[[package]]
name = "autocfg"
version = "1.1.0"
@@ -385,12 +396,15 @@ name = "spin-sdk"
version = "2.0.0-pre0"
dependencies = [
"anyhow",
+ "async-trait",
"bytes",
"form_urlencoded",
"futures",
"http",
"once_cell",
"routefinder",
+ "serde",
+ "serde_json",
"spin-macro",
"thiserror",
"wit-bindgen",
diff --git a/tests/testcases/sqlite-undefined-db/src/lib.rs b/tests/testcases/sqlite-undefined-db/src/lib.rs
index 52e87d8359..863b1a3637 100644
--- a/tests/testcases/sqlite-undefined-db/src/lib.rs
+++ b/tests/testcases/sqlite-undefined-db/src/lib.rs
@@ -1,12 +1,9 @@
use anyhow::Result;
-use spin_sdk::{
- http::{Request, Response},
- http_component,
-};
+use spin_sdk::http_component;
#[http_component]
-fn handle_request(_req: Request) -> Result<Response> {
+fn handle_request(_req: http::Request<()>) -> Result<http::Response<()>> {
// We don't need to do anything here: it should never get called because
// spin up should fail at SQLite validation.
- Ok(http::Response::builder().status(200).body(None)?)
+ Ok(http::Response::builder().status(200).body(())?)
}
diff --git a/tests/testcases/sqlite/Cargo.lock b/tests/testcases/sqlite/Cargo.lock
index 78ebfc2962..3fd991c0b2 100644
--- a/tests/testcases/sqlite/Cargo.lock
+++ b/tests/testcases/sqlite/Cargo.lock
@@ -8,6 +8,17 @@ version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
+[[package]]
+name = "async-trait"
+version = "0.1.74"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.38",
+]
+
[[package]]
name = "autocfg"
version = "1.1.0"
@@ -385,12 +396,15 @@ name = "spin-sdk"
version = "2.0.0-pre0"
dependencies = [
"anyhow",
+ "async-trait",
"bytes",
"form_urlencoded",
"futures",
"http",
"once_cell",
"routefinder",
+ "serde",
+ "serde_json",
"spin-macro",
"thiserror",
"wit-bindgen",
diff --git a/tests/testcases/sqlite/src/lib.rs b/tests/testcases/sqlite/src/lib.rs
index 6224beffb5..ef8de79214 100644
--- a/tests/testcases/sqlite/src/lib.rs
+++ b/tests/testcases/sqlite/src/lib.rs
@@ -1,12 +1,11 @@
use anyhow::{ensure, Result};
use spin_sdk::{
- http::{Request, Response},
http_component,
sqlite::{Connection, Error, Value},
};
#[http_component]
-fn handle_request(req: Request) -> Result<Response> {
+fn handle_request(req: http::Request<()>) -> Result<http::Response<()>> {
ensure!(matches!(
Connection::open("forbidden"),
Err(Error::AccessDenied)
@@ -43,5 +42,5 @@ fn handle_request(req: Request) -> Result<Response> {
assert_eq!(init_key, fetched_key);
assert_eq!(init_val, fetched_value);
- Ok(http::Response::builder().status(200).body(None)?)
+ Ok(http::Response::builder().status(200).body(())?)
}
|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
2a0205608ff47e9fd42c5056abc79715c9138032
|
`spin new`: provide application name without providing template
When creating a Spin application, I usually know the name I want to give the application, but I often cannot remember the template name I'd like to use (is it `http-rust`, `rust-http`, or something else?). I really wish I could `spin new $SOME_NAME` and then be presented with a picker for the template.
This might not be possible to add though given that `spin new` first expects a template *then* a name.
|
Yeah we should maybe have done this the other way round...
The only things I can think of are:
1. Allow the name as a named parameter as well as a positional one (clap permitting). So your command would become `spin new --name myapp`.
2. Have a magic syntax for "prompt me for the template ID" e.g. `spin new * myapp`.
3. Not quite what you asked for, but allow partial/tag matches in the template ID, so you could write `spin new rust myapp` and it would go "here are all your Rust templates."
Of these, the last feels most comfortable but I don't know if would meet what you want to write.
The PR you opened seems reasonable. I current ordering is a bit unfortunate, but alas, perhaps this is the best we can do.
We _could_ have a rule that if there is one positional arg and it _doesn't_ match a template (possibly within some fancy distance metric), we prompt for the template, and prompt for the name but default it to the positional arg. It feels a bit hairy but would probably work in the 90% case.
More generally we could try harder to make sense of "incorrect" user input e.g. if first arg does not match a template but second one does then quietly swap them. I am slightly wary of teaching people the "wrong" thing, though, because things where we can resolve the ambiguities in interactive mode today may not be resolvable in CI environments tomorrow.
This has been marked as a "must have" (release blocker) for Spin 2. I believe the only proposal for implementing it is to reorder the arguments from `spin new [<template>] [<name>]` to `spin new [<name>] [<template>]`? This would allow users to omit the template. Is that correct?
If this is the proposal, it's an easy change in the code! However, anyone with muscle memory of the existing order would experience a jarring transition (and any scripts that use the existing order will break in non-obvious ways). Are we agreed that the joy it will bring over time is worth the short-term pain? (I'm guessing I'm one of the only people on the planet to actually have that muscle memory, so if it brings two people joy then that's probably a net win!) If so, are there ways we can cushion the change?
Or are there other proposals? We also have #16 in the frame which asks for a specific "empty application" experience., so it would be good to get a comprehensive sense of what we want the app scaffolding experience to look like across the various asks.
(For example someone made mention of wanting to be able to create an application in the current directory. This can be done without a breaking change, but if it's a requirement/want then it would be good to have it in mind during any rethink.)
Can we get a decision on required behaviour please. It's marked as a release blocker for 2.0 but without some agreement on the desired outcome there's no point starting to code. cc @melissaklein24
I'd enjoy `spin new [app_name] -t <template>`.
`spin new [app_name] -t` where `<template>` is omitted gives you all the templates available to choose from.
`spin new [app_name]` with no flags gives you just a spin.toml file in a directory called [app_name]
wdyt?
> spin new [app_name] with no flags gives you just a spin.toml file in a directory called [app_name]
This seems to also solve #16
+1 to what Michelle said. The only other request I would like to see is a `--init` that initializes the current directory rather than creating a new directory.
I guess that would address this as well https://github.com/fermyon/spin/issues/1075 - which might be a dup of #16
Thanks all, appreciate getting some definition on this.
I don't quite get the "a spin.toml file in a directory." What is the spin.toml file? Is it the same as the current http-empty template? Is that the experience people want as the default, rather than the current "prompt for a template"? So if someone did a `spin new myapp` it would succeed but the created app would not yet be runnable?
Ah right, good catch. Personally, I don't see much value in `spin new <appname>` just generating a component/trigger-less `spin.toml`. I would think in this situation the user would be prompted for the template to select. In other words, in Michelle's above the `-t` flag requires an argument.
@fibonacci1729 In that case, could/should the template name be positional, or is it better to put it behind the `-t` flag? (I'm not trying to argue for a specific outcome here, just figuring out the design space.)
Also I know @michelleN has been arguing for the "just create a spin.toml file" for a _looong_ time and I do want to understand the intended experience because I am sure I am missing something.
IIRC the rationale for the `-t` flag was because we may want to allow application scaffolding from artefacts other than a template in the near future. E.g. `spin new myapp -w component.wasm` or `spin new myapp --openapi path/to/my/spec`.
@fibonacci1729 Interesting! I wonder if we should use the `--from` trick we do on `spin up` so the user could write `spin new myapp -f http-go` or `spin new myapp -f component.wasm` or `spin new myapp -f path/to/spec` interchangeably, and we figure out which case it is. (With `--from-template/--from-component/--from-openapi` longopts if disambiguation is needed.)
I guess some flags might need extra args like an OpenAPI spec in Git might need a branch/rev option.
> @fibonacci1729 Interesting! I wonder if we should use the `--from` trick we do on `spin up` so the user could write `spin new myapp -f http-go` or `spin new myapp -f component.wasm` or `spin new myapp -f path/to/spec` interchangeably, and we figure out which case it is. (With `--from-template/--from-component/--from-openapi` longopts if disambiguation is needed.)
That sounds like the best experience!
Boo, we already use `-f` for the manifest to add to in `spin add`.
> Also I know @michelleN has been arguing for the "just create a spin.toml file" for a looong time and I do want to understand the intended experience because I am sure I am missing something.
I am envisioning a skeleton Spin.toml file for an http Spin app that contains some comments on how to fill in the fields.
```
spin_manifest_version = "1"
authors = ["Michelle Dhanani <michelle@fermyon.com>"]
# add a description here
description = ""
name = "some-app"
# the trigger field is used to specify how components are invoked. the http trigger type is the most common # # Spin trigger. This allows components to be invoked via HTTP requests. There are other trigger types.. please see docs.
trigger = { type = "http" }
version = "0.1.0"
# Spin apps can consist of multiple [[component]] sections.
[[component]]
# id is a unique identifier for the component in this spin app, you can specify some alphanumeric string here <add constraints>
id = "component1"
# source is the path to the wasm file that will be executed when this component is invoked
source = ""
# allowed_http_hosts represents what hosts this component can make outbound http requests to
allowed_http_hosts = []
[component.trigger]
# route description here
route = "/..."
[component.build]
# command to build the component, will be used by Spin build
command = ""
```
Thanks for clarifying @michelleN. If we do this I think we're going to need a significant amount of supporting infra to provide:
* Good error messages for when a beginner does `spin build / spin up` on one of these. At the moment I think you'd get some nasty parsing errors, when what it would need to do is recognise the "blank" manifest and say "hey you need to go back and fill out all those fields that spin new created for you."
* Improvements to `spin add` so that when a user added a component to one of these, it replaces the "blank" component instead of adding. (Because it's significantly easier to `spin add` than to write out all those commands and paths by hand.)
The challenge is that, unlike the empty scaffold, this _looks_ like it has a component, so it requires more smarts to determine that actually there _isn't_ a component, it's still waiting to be filled in. I worry that this leaves new users going "but how do I make it work" rather than having a working "hello world" starting point.
We can of course do this if people want it, but I'm wondering if there are other ways to accomplish the goal that this is aiming at. @michelleN is the motive here the doc comments, the "bring your own language", the not needing to install a template. something else?
|
2023-10-10T21:38:13Z
|
fermyon__spin-1872
|
fermyon/spin
|
3.2
|
diff --git a/crates/templates/src/interaction.rs b/crates/templates/src/interaction.rs
index 5a02c31278..a8d36abaec 100644
--- a/crates/templates/src/interaction.rs
+++ b/crates/templates/src/interaction.rs
@@ -42,7 +42,7 @@ impl InteractionStrategy for Interactive {
fn allow_generate_into(&self, target_dir: &Path) -> Cancellable<(), anyhow::Error> {
if !is_directory_empty(target_dir) {
let prompt = format!(
- "{} already contains other files. Generate into it anyway?",
+ "Directory '{}' already contains other files. Generate into it anyway?",
target_dir.display()
);
match crate::interaction::confirm(&prompt) {
diff --git a/src/commands/new.rs b/src/commands/new.rs
index 1d058a5ed8..1a57b4c247 100644
--- a/src/commands/new.rs
+++ b/src/commands/new.rs
@@ -17,13 +17,14 @@ use crate::opts::{APP_MANIFEST_FILE_OPT, DEFAULT_MANIFEST_FILE};
/// Scaffold a new application based on a template.
#[derive(Parser, Debug)]
pub struct TemplateNewCommandCore {
- /// The template from which to create the new application or component. Run `spin templates list` to see available options.
- pub template_id: Option<String>,
-
/// The name of the new application or component.
#[clap(value_parser = validate_name)]
pub name: Option<String>,
+ /// The template from which to create the new application or component. Run `spin templates list` to see available options.
+ #[clap(short = 't', long = "template")]
+ pub template_id: Option<String>,
+
/// Filter templates to select by tags.
#[clap(
long = "tag",
@@ -34,9 +35,13 @@ pub struct TemplateNewCommandCore {
/// The directory in which to create the new application or component.
/// The default is the name argument.
- #[clap(short = 'o', long = "output")]
+ #[clap(short = 'o', long = "output", group = "location")]
pub output_path: Option<PathBuf>,
+ /// Create the new application or component in the current directory.
+ #[clap(long = "init", takes_value = false, group = "location")]
+ pub init: bool,
+
/// Parameter values to be passed to the template (in name=value format).
#[clap(short = 'v', long = "value", multiple_occurrences = true)]
pub values: Vec<ParameterValue>,
@@ -113,6 +118,17 @@ impl TemplateNewCommandCore {
let template_manager = TemplateManager::try_default()
.context("Failed to construct template directory path")?;
+ // If a user types `spin new http-rust` etc. then it's *probably* Spin 1.x muscle memory;
+ // try to be helpful without getting in the way.
+ if let Some(name) = &self.name {
+ if self.template_id.is_none() && matches!(template_manager.get(name), Ok(Some(_))) {
+ terminal::einfo!(
+ "This will create an app called {name}.",
+ "If you meant to use the {name} template, write '-t {name}'."
+ )
+ }
+ }
+
let template = match &self.template_id {
Some(template_id) => match template_manager
.get(template_id)
@@ -146,7 +162,12 @@ impl TemplateNewCommandCore {
None => prompt_name(&variant).await?,
};
- let output_path = self.output_path.clone().unwrap_or_else(|| path_safe(&name));
+ let output_path = if self.init {
+ PathBuf::from(".")
+ } else {
+ self.output_path.clone().unwrap_or_else(|| path_safe(&name))
+ };
+
let values = {
let mut values = match self.values_file.as_ref() {
Some(file) => values_from_file(file.as_path()).await?,
| 1,872
|
[
"1525"
] |
diff --git a/crates/e2e-testing/src/spin.rs b/crates/e2e-testing/src/spin.rs
index 4772f65673..e735b16b97 100644
--- a/crates/e2e-testing/src/spin.rs
+++ b/crates/e2e-testing/src/spin.rs
@@ -30,7 +30,14 @@ pub fn new_app<'a>(
mut args: Vec<&'a str>,
) -> Result<Output> {
let basedir = utils::testcases_base_dir();
- let mut cmd = vec!["spin", "new", template_name, app_name, "--accept-defaults"];
+ let mut cmd = vec![
+ "spin",
+ "new",
+ app_name,
+ "-t",
+ template_name,
+ "--accept-defaults",
+ ];
if !args.is_empty() {
cmd.append(&mut args);
}
|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
78e0f7f09f2eb8d89786a739e399456ba7a252fb
|
templates: redirect support for 'spin new'
The [redirect template](https://github.com/fermyon/spin/tree/main/templates/redirect) doesn't currently support use with `spin new`:
```
$ spin new redirect redirect
Template redirect doesn't support the 'new application' operation
```
There've been cases of [pure redirect apps](https://github.com/fermyon/spin/blob/main/docs/spin.toml), so perhaps we consider adding support?
|
I think my thinking was that if you didn't have any components yet then there was nothing to redirect _to_. You're right that there could be redirects to external URLs though; and although it's unlikely that anyone is going to start a Spin app from scratch _just_ to do redirects, there's probably no reason to actually _forbid_ this usage.
The current template has a pattern for `redirect-to` which is a local HTTP route (begins with `/`), not a full URL. If we want to a meaningful `spin new` then we need to remove this constraint. Are we okay with that?
|
2023-10-09T03:40:00Z
|
fermyon__spin-1865
|
fermyon/spin
|
3.2
|
diff --git a/crates/templates/src/manager.rs b/crates/templates/src/manager.rs
index 677ca7e7cd..82c0479753 100644
--- a/crates/templates/src/manager.rs
+++ b/crates/templates/src/manager.rs
@@ -1033,10 +1033,15 @@ mod tests {
let temp_dir = tempdir().unwrap();
let store = TemplateStore::new(temp_dir.path());
let manager = TemplateManager { store };
- let source = TemplateSource::File(project_root());
+ let source1 = TemplateSource::File(test_data_root());
+ let source2 = TemplateSource::File(project_root());
manager
- .install(&source, &InstallOptions::default(), &DiscardingReporter)
+ .install(&source1, &InstallOptions::default(), &DiscardingReporter)
+ .await
+ .unwrap();
+ manager
+ .install(&source2, &InstallOptions::default(), &DiscardingReporter)
.await
.unwrap();
@@ -1044,7 +1049,7 @@ mod tests {
let manifest_path = dummy_dir.join("ignored_spin.toml");
let add_component = TemplateVariantInfo::AddComponent { manifest_path };
- let redirect = manager.get("redirect").unwrap().unwrap();
+ let redirect = manager.get("add-only-redirect").unwrap().unwrap();
assert!(!redirect.supports_variant(&TemplateVariantInfo::NewApplication));
assert!(redirect.supports_variant(&add_component));
diff --git a/templates/redirect/content/.gitignore b/templates/redirect/content/.gitignore
new file mode 100644
index 0000000000..0688291f15
--- /dev/null
+++ b/templates/redirect/content/.gitignore
@@ -0,0 +1,1 @@
+.spin/
diff --git a/templates/redirect/content/spin.toml b/templates/redirect/content/spin.toml
new file mode 100644
index 0000000000..8e9195f0cc
--- /dev/null
+++ b/templates/redirect/content/spin.toml
@@ -0,0 +1,13 @@
+spin_manifest_version = "1"
+authors = ["{{authors}}"]
+description = "{{project-description}}"
+name = "{{project-name}}"
+trigger = { type = "http", base = "{{http-base}}" }
+version = "0.1.0"
+
+[[component]]
+source = { url = "https://github.com/fermyon/spin-redirect/releases/download/v0.1.0/redirect.wasm", digest = "sha256:8bee959843f28fef2a02164f5840477db81d350877e1c22cb524f41363468e52" }
+id = "{{ project-name | kebab_case }}"
+environment = { DESTINATION = "{{ redirect-to }}" }
+[component.trigger]
+route = "{{ redirect-from }}"
diff --git a/templates/redirect/metadata/snippets/component.txt b/templates/redirect/metadata/snippets/component.txt
index a91e1a8a32..5ae6628514 100644
--- a/templates/redirect/metadata/snippets/component.txt
+++ b/templates/redirect/metadata/snippets/component.txt
@@ -1,6 +1,6 @@
[[component]]
source = { url = "https://github.com/fermyon/spin-redirect/releases/download/v0.1.0/redirect.wasm", digest = "sha256:8bee959843f28fef2a02164f5840477db81d350877e1c22cb524f41363468e52" }
-id = "{{ project-name }}"
+id = "{{ project-name | kebab_case }}"
environment = { DESTINATION = "{{ redirect-to }}" }
[component.trigger]
route = "{{ redirect-from }}"
diff --git a/templates/redirect/metadata/spin-template.toml b/templates/redirect/metadata/spin-template.toml
index 98d14097b8..7681441047 100644
--- a/templates/redirect/metadata/spin-template.toml
+++ b/templates/redirect/metadata/spin-template.toml
@@ -4,13 +4,14 @@ description = "Redirects a HTTP route"
trigger_type = "http"
tags = ["redirect"]
-[new_application]
-supported = false
-
[add_component]
+skip_files = ["spin.toml"]
+skip_parameters = ["project-description", "http-base"]
[add_component.snippets]
component = "component.txt"
[parameters]
+project-description = { type = "string", prompt = "Description", default = "" }
+http-base = { type = "string", prompt = "HTTP base", default = "/", pattern = "^/\\S*$" }
redirect-from = { type = "string", prompt = "Redirect from", pattern = "^/\\S*$" }
-redirect-to = { type = "string", prompt = "Redirect to", pattern = "^/\\S*$" }
+redirect-to = { type = "string", prompt = "Redirect to" }
| 1,865
|
[
"1860"
] |
diff --git a/crates/templates/tests/templates/add-only-redirect/metadata/snippets/component.txt b/crates/templates/tests/templates/add-only-redirect/metadata/snippets/component.txt
new file mode 100644
index 0000000000..5ae6628514
--- /dev/null
+++ b/crates/templates/tests/templates/add-only-redirect/metadata/snippets/component.txt
@@ -0,0 +1,6 @@
+[[component]]
+source = { url = "https://github.com/fermyon/spin-redirect/releases/download/v0.1.0/redirect.wasm", digest = "sha256:8bee959843f28fef2a02164f5840477db81d350877e1c22cb524f41363468e52" }
+id = "{{ project-name | kebab_case }}"
+environment = { DESTINATION = "{{ redirect-to }}" }
+[component.trigger]
+route = "{{ redirect-from }}"
diff --git a/crates/templates/tests/templates/add-only-redirect/metadata/spin-template.toml b/crates/templates/tests/templates/add-only-redirect/metadata/spin-template.toml
new file mode 100644
index 0000000000..52d41a4915
--- /dev/null
+++ b/crates/templates/tests/templates/add-only-redirect/metadata/spin-template.toml
@@ -0,0 +1,16 @@
+manifest_version = "1"
+id = "add-only-redirect"
+description = "Redirects a HTTP route"
+trigger_type = "http"
+tags = ["redirect"]
+
+[new_application]
+supported = false
+
+[add_component]
+[add_component.snippets]
+component = "component.txt"
+
+[parameters]
+redirect-from = { type = "string", prompt = "Redirect from", pattern = "^/\\S*$" }
+redirect-to = { type = "string", prompt = "Redirect to", pattern = "^/\\S*$" }
|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
268883366d57712de1a9cc33135238b46013fe86
|
templates: Remove wit-bindgen-backport dependency
This is the last vestage of "old" wit-bindgen in spin; app usage of the old ABI is now handled by the spin-componentize adaptation.
After some discussion, I think one of the following should be done:
- Remove the custom filters feature; the only known usage of it is [this simple filter](https://github.com/fermyon/spin-dotnet-sdk/tree/main/tools/dotted-pascal-case-filter) which could be moved into a regular filter impl in spin-templates.
- Commit the wit-bindgen-generated source for the `custom-filter.wit` rather than using the wit-bindgen macro. Breaking changes in the wasmtime APIs that this generated code uses should be rare but would require manual fixes to that code. Guest code would be stuck with old wit-bindgen versions, but that isn't necessarily a major problem for this use.
- Convert custom filters to use the component model. I think as long as the custom filter "world" doesn't include WASI this might be fine.
|
I think we've settled on the breaking change of removing the functionality for 2.0.
|
2023-09-28T01:54:29Z
|
fermyon__spin-1822
|
fermyon/spin
|
3.2
|
diff --git a/Cargo.lock b/Cargo.lock
index 162179a8fb..cb017d81f7 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6166,9 +6166,6 @@ dependencies = [
"toml 0.5.11",
"url",
"walkdir",
- "wasmtime",
- "wasmtime-wasi",
- "wit-bindgen-wasmtime",
]
[[package]]
@@ -8161,34 +8158,6 @@ dependencies = [
"wit-parser 0.8.0",
]
-[[package]]
-name = "wit-bindgen-gen-core"
-version = "0.2.0"
-source = "git+https://github.com/fermyon/wit-bindgen-backport?rev=598cd229bb43baceff9616d16930b8a5a3e79d79#598cd229bb43baceff9616d16930b8a5a3e79d79"
-dependencies = [
- "anyhow",
- "wit-parser 0.2.0",
-]
-
-[[package]]
-name = "wit-bindgen-gen-rust"
-version = "0.2.0"
-source = "git+https://github.com/fermyon/wit-bindgen-backport?rev=598cd229bb43baceff9616d16930b8a5a3e79d79#598cd229bb43baceff9616d16930b8a5a3e79d79"
-dependencies = [
- "heck 0.3.3",
- "wit-bindgen-gen-core",
-]
-
-[[package]]
-name = "wit-bindgen-gen-wasmtime"
-version = "0.2.0"
-source = "git+https://github.com/fermyon/wit-bindgen-backport?rev=598cd229bb43baceff9616d16930b8a5a3e79d79#598cd229bb43baceff9616d16930b8a5a3e79d79"
-dependencies = [
- "heck 0.3.3",
- "wit-bindgen-gen-core",
- "wit-bindgen-gen-rust",
-]
-
[[package]]
name = "wit-bindgen-rust"
version = "0.8.0"
@@ -8226,30 +8195,6 @@ dependencies = [
"wit-component 0.11.0",
]
-[[package]]
-name = "wit-bindgen-wasmtime"
-version = "0.2.0"
-source = "git+https://github.com/fermyon/wit-bindgen-backport?rev=598cd229bb43baceff9616d16930b8a5a3e79d79#598cd229bb43baceff9616d16930b8a5a3e79d79"
-dependencies = [
- "anyhow",
- "async-trait",
- "bitflags 1.3.2",
- "thiserror",
- "wasmtime",
- "wit-bindgen-wasmtime-impl",
-]
-
-[[package]]
-name = "wit-bindgen-wasmtime-impl"
-version = "0.2.0"
-source = "git+https://github.com/fermyon/wit-bindgen-backport?rev=598cd229bb43baceff9616d16930b8a5a3e79d79#598cd229bb43baceff9616d16930b8a5a3e79d79"
-dependencies = [
- "proc-macro2",
- "syn 1.0.109",
- "wit-bindgen-gen-core",
- "wit-bindgen-gen-wasmtime",
-]
-
[[package]]
name = "wit-component"
version = "0.11.0"
@@ -8284,18 +8229,6 @@ dependencies = [
"wit-parser 0.11.0",
]
-[[package]]
-name = "wit-parser"
-version = "0.2.0"
-source = "git+https://github.com/fermyon/wit-bindgen-backport?rev=598cd229bb43baceff9616d16930b8a5a3e79d79#598cd229bb43baceff9616d16930b8a5a3e79d79"
-dependencies = [
- "anyhow",
- "id-arena",
- "pulldown-cmark 0.8.0",
- "unicode-normalization",
- "unicode-xid",
-]
-
[[package]]
name = "wit-parser"
version = "0.8.0"
diff --git a/crates/templates/Cargo.toml b/crates/templates/Cargo.toml
index d64cb14cce..9a9e8b5a94 100644
--- a/crates/templates/Cargo.toml
+++ b/crates/templates/Cargo.toml
@@ -32,10 +32,3 @@ tokio = { version = "1.23", features = ["fs", "process", "rt", "macros"] }
toml = "0.5"
url = "2.2.2"
walkdir = "2"
-wasmtime = { workspace = true }
-wasmtime-wasi = { workspace = true }
-
-[dependencies.wit-bindgen-wasmtime]
-git = "https://github.com/fermyon/wit-bindgen-backport"
-rev = "598cd229bb43baceff9616d16930b8a5a3e79d79"
-features = ["async"]
diff --git a/crates/templates/src/custom_filters.rs b/crates/templates/src/custom_filters.rs
deleted file mode 100644
index 2ed0a911ee..0000000000
--- a/crates/templates/src/custom_filters.rs
+++ /dev/null
@@ -1,166 +0,0 @@
-use std::{
- fmt::{Debug, Display},
- path::Path,
- sync::{Arc, RwLock},
-};
-
-use anyhow::Context;
-use liquid_core::{Filter, ParseFilter, Runtime, ValueView};
-use wasmtime::{Engine, Linker, Module, Store};
-use wasmtime_wasi::{WasiCtx, WasiCtxBuilder};
-
-wit_bindgen_wasmtime::import!({paths: ["./wit/custom-filter.wit"]});
-
-struct CustomFilterContext {
- wasi: WasiCtx,
- data: custom_filter::CustomFilterData,
-}
-
-impl CustomFilterContext {
- fn new() -> Self {
- Self {
- wasi: WasiCtxBuilder::new().build(),
- data: custom_filter::CustomFilterData {},
- }
- }
-}
-
-#[derive(Clone)]
-pub(crate) struct CustomFilterParser {
- name: String,
- wasm_store: Arc<RwLock<Store<CustomFilterContext>>>,
- exec: Arc<custom_filter::CustomFilter<CustomFilterContext>>,
-}
-
-impl CustomFilterParser {
- pub(crate) fn load(name: &str, wasm_path: &Path) -> anyhow::Result<Self> {
- let wasm = std::fs::read(wasm_path).with_context(|| {
- format!("Failed loading custom filter from {}", wasm_path.display())
- })?;
-
- let ctx = CustomFilterContext::new();
- let engine = Engine::default();
- let mut store = Store::new(&engine, ctx);
- let mut linker = Linker::new(&engine);
- wasmtime_wasi::add_to_linker(&mut linker, |ctx: &mut CustomFilterContext| &mut ctx.wasi)
- .with_context(|| format!("Setting up WASI for custom filter {}", name))?;
- let module = Module::new(&engine, wasm)
- .with_context(|| format!("Creating Wasm module for custom filter {}", name))?;
- let instance = linker
- .instantiate(&mut store, &module)
- .with_context(|| format!("Instantiating Wasm module for custom filter {}", name))?;
- let filter_exec =
- custom_filter::CustomFilter::new(&mut store, &instance, |ctx| &mut ctx.data)
- .with_context(|| format!("Loading Wasm executor for custom filer {}", name))?;
-
- Ok(Self {
- name: name.to_owned(),
- wasm_store: Arc::new(RwLock::new(store)),
- exec: Arc::new(filter_exec),
- })
- }
-}
-
-impl Debug for CustomFilterParser {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- f.debug_struct("CustomFilterParser")
- .field("name", &self.name)
- .finish()
- }
-}
-
-impl ParseFilter for CustomFilterParser {
- fn parse(
- &self,
- _arguments: liquid_core::parser::FilterArguments,
- ) -> liquid_core::Result<Box<dyn Filter>> {
- Ok(Box::new(CustomFilter {
- name: self.name.to_owned(),
- wasm_store: self.wasm_store.clone(),
- exec: self.exec.clone(),
- }))
- }
-
- fn reflection(&self) -> &dyn liquid_core::FilterReflection {
- self
- }
-}
-
-const EMPTY: [liquid_core::parser::ParameterReflection; 0] = [];
-
-impl liquid_core::FilterReflection for CustomFilterParser {
- fn name(&self) -> &str {
- &self.name
- }
-
- fn description(&self) -> &str {
- ""
- }
-
- fn positional_parameters(&self) -> &'static [liquid_core::parser::ParameterReflection] {
- &EMPTY
- }
-
- fn keyword_parameters(&self) -> &'static [liquid_core::parser::ParameterReflection] {
- &EMPTY
- }
-}
-
-struct CustomFilter {
- name: String,
- wasm_store: Arc<RwLock<Store<CustomFilterContext>>>,
- exec: Arc<custom_filter::CustomFilter<CustomFilterContext>>,
-}
-
-impl Debug for CustomFilter {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- f.debug_struct("CustomFilter")
- .field("name", &self.name)
- .finish()
- }
-}
-
-impl Display for CustomFilter {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- f.write_str(&self.name)
- }
-}
-
-impl Filter for CustomFilter {
- fn evaluate(
- &self,
- input: &dyn ValueView,
- _runtime: &dyn Runtime,
- ) -> Result<liquid::model::Value, liquid_core::error::Error> {
- let mut store = self
- .wasm_store
- .write()
- .map_err(|e| liquid_err(format!("Failed to get custom filter Wasm store: {}", e)))?;
- let input_str = self.liquid_value_as_string(input)?;
- match self.exec.exec(&mut *store, &input_str) {
- Ok(Ok(text)) => Ok(to_liquid_value(text)),
- Ok(Err(s)) => Err(liquid_err(s)),
- Err(trap) => Err(liquid_err(format!("{:?}", trap))),
- }
- }
-}
-
-impl CustomFilter {
- fn liquid_value_as_string(&self, input: &dyn ValueView) -> Result<String, liquid::Error> {
- let str = input.as_scalar().map(|s| s.into_cow_str()).ok_or_else(|| {
- liquid_err(format!(
- "Filter '{}': no input or input is not a string",
- self.name
- ))
- })?;
- Ok(str.to_string())
- }
-}
-
-fn to_liquid_value(value: String) -> liquid::model::Value {
- liquid::model::Value::Scalar(liquid::model::Scalar::from(value))
-}
-
-fn liquid_err(text: String) -> liquid_core::error::Error {
- liquid_core::error::Error::with_msg(text)
-}
diff --git a/crates/templates/src/lib.rs b/crates/templates/src/lib.rs
index e4b18216d9..c0b0181458 100644
--- a/crates/templates/src/lib.rs
+++ b/crates/templates/src/lib.rs
@@ -5,7 +5,6 @@
mod app_info;
mod cancellable;
mod constraints;
-mod custom_filters;
mod directory;
mod environment;
mod filters;
diff --git a/crates/templates/src/manager.rs b/crates/templates/src/manager.rs
index 2ca605c1a2..677ca7e7cd 100644
--- a/crates/templates/src/manager.rs
+++ b/crates/templates/src/manager.rs
@@ -56,6 +56,7 @@ enum ExistsBehaviour {
Update,
}
+#[allow(clippy::large_enum_variant)] // it's not worth it
enum InstallationResult {
Installed(Template),
Skipped(String, SkippedReason),
@@ -828,43 +829,26 @@ mod tests {
}
#[tokio::test]
- async fn can_use_custom_filter_in_template() {
+ async fn cannot_use_custom_filter_in_template() {
let temp_dir = tempdir().unwrap();
let store = TemplateStore::new(temp_dir.path());
let manager = TemplateManager { store };
let source = TemplateSource::File(test_data_root());
- manager
+ let install_results = manager
.install(&source, &InstallOptions::default(), &DiscardingReporter)
.await
.unwrap();
- let template = manager.get("testing-custom-filter").unwrap().unwrap();
+ assert_eq!(1, install_results.skipped.len());
- let dest_temp_dir = tempdir().unwrap();
- let output_dir = dest_temp_dir.path().join("myproj");
- let values = [
- ("p1".to_owned(), "biscuits".to_owned()),
- ("p2".to_owned(), "nomnomnom".to_owned()),
- ]
- .into_iter()
- .collect();
- let options = RunOptions {
- variant: crate::template::TemplateVariantInfo::NewApplication,
- output_path: output_dir.clone(),
- name: "custom-filter-test".to_owned(),
- values,
- accept_defaults: false,
+ let (id, reason) = &install_results.skipped[0];
+ assert_eq!("testing-custom-filter", id);
+ let SkippedReason::InvalidManifest(message) = reason else {
+ panic!("skip reason should be InvalidManifest"); // clippy dislikes assert!(false...)
};
-
- template.run(options).silent().await.unwrap();
-
- let message = tokio::fs::read_to_string(output_dir.join("test.txt"))
- .await
- .unwrap();
- assert!(message.contains("p1/studly = bIsCuItS"));
- assert!(message.contains("p2/studly = nOmNoMnOm"));
- assert!(message.contains("p1/clappy = b👏i👏s👏c👏u👏i👏t👏s"));
+ assert_contains(message, "filters");
+ assert_contains(message, "not supported");
}
#[tokio::test]
diff --git a/crates/templates/src/reader.rs b/crates/templates/src/reader.rs
index b3859a26c6..9006c8a065 100644
--- a/crates/templates/src/reader.rs
+++ b/crates/templates/src/reader.rs
@@ -22,7 +22,7 @@ pub(crate) struct RawTemplateManifestV1 {
pub new_application: Option<RawTemplateVariant>,
pub add_component: Option<RawTemplateVariant>,
pub parameters: Option<IndexMap<String, RawParameter>>,
- pub custom_filters: Option<Vec<RawCustomFilter>>,
+ pub custom_filters: Option<serde::de::IgnoredAny>, // kept for error messaging
}
#[derive(Debug, Deserialize)]
@@ -45,13 +45,6 @@ pub(crate) struct RawParameter {
pub pattern: Option<String>,
}
-#[derive(Debug, Deserialize)]
-#[serde(deny_unknown_fields, rename_all = "snake_case")]
-pub(crate) struct RawCustomFilter {
- pub name: String,
- pub wasm: String,
-}
-
pub(crate) fn parse_manifest_toml(text: impl AsRef<str>) -> anyhow::Result<RawTemplateManifest> {
toml::from_str(text.as_ref()).context("Failed to parse template manifest TOML")
}
diff --git a/crates/templates/src/run.rs b/crates/templates/src/run.rs
index 3c53eb8cb6..8413b0e2c5 100644
--- a/crates/templates/src/run.rs
+++ b/crates/templates/src/run.rs
@@ -308,14 +308,11 @@ impl Run {
}
fn template_parser(&self) -> liquid::Parser {
- let mut builder = liquid::ParserBuilder::with_stdlib()
+ let builder = liquid::ParserBuilder::with_stdlib()
.filter(crate::filters::KebabCaseFilterParser)
.filter(crate::filters::PascalCaseFilterParser)
.filter(crate::filters::SnakeCaseFilterParser)
.filter(crate::filters::HttpWildcardFilterParser);
- for filter in self.template.custom_filters() {
- builder = builder.filter(filter);
- }
builder
.build()
.expect("can't fail due to no partials support")
diff --git a/crates/templates/src/store.rs b/crates/templates/src/store.rs
index 7d432405cf..b484af30b2 100644
--- a/crates/templates/src/store.rs
+++ b/crates/templates/src/store.rs
@@ -66,7 +66,6 @@ pub(crate) struct TemplateLayout {
}
const METADATA_DIR_NAME: &str = "metadata";
-const FILTERS_DIR_NAME: &str = "filters";
const CONTENT_DIR_NAME: &str = "content";
const SNIPPETS_DIR_NAME: &str = "snippets";
@@ -85,14 +84,6 @@ impl TemplateLayout {
self.template_dir.join(METADATA_DIR_NAME)
}
- pub fn filters_dir(&self) -> PathBuf {
- self.metadata_dir().join(FILTERS_DIR_NAME)
- }
-
- pub fn filter_path(&self, filename: &str) -> PathBuf {
- self.filters_dir().join(filename)
- }
-
pub fn manifest_path(&self) -> PathBuf {
self.metadata_dir().join(MANIFEST_FILE_NAME)
}
diff --git a/crates/templates/src/template.rs b/crates/templates/src/template.rs
index 417254def6..5c78a2858d 100644
--- a/crates/templates/src/template.rs
+++ b/crates/templates/src/template.rs
@@ -9,8 +9,7 @@ use regex::Regex;
use crate::{
constraints::StringConstraints,
- custom_filters::CustomFilterParser,
- reader::{RawCustomFilter, RawParameter, RawTemplateManifest, RawTemplateVariant},
+ reader::{RawParameter, RawTemplateManifest, RawTemplateManifestV1, RawTemplateVariant},
run::{Run, RunOptions},
store::TemplateLayout,
};
@@ -25,7 +24,6 @@ pub struct Template {
trigger: TemplateTriggerCompatibility,
variants: HashMap<TemplateVariantKind, TemplateVariant>,
parameters: Vec<TemplateParameter>,
- custom_filters: Vec<CustomFilterParser>,
snippets_dir: Option<PathBuf>,
content_dir: Option<PathBuf>, // TODO: maybe always need a spin.toml file in there?
}
@@ -123,6 +121,8 @@ impl Template {
)
})?;
+ validate_manifest(&raw)?;
+
let content_dir = if layout.content_dir().exists() {
Some(layout.content_dir())
} else {
@@ -146,7 +146,6 @@ impl Template {
trigger: Self::parse_trigger_type(raw.trigger_type, layout),
variants: Self::parse_template_variants(raw.new_application, raw.add_component),
parameters: Self::parse_parameters(&raw.parameters)?,
- custom_filters: Self::load_custom_filters(layout, &raw.custom_filters)?,
snippets_dir,
content_dir,
},
@@ -229,10 +228,6 @@ impl Template {
self.parameters.iter().find(|p| p.id == name.as_ref())
}
- pub(crate) fn custom_filters(&self) -> Vec<CustomFilterParser> {
- self.custom_filters.clone()
- }
-
pub(crate) fn content_dir(&self) -> &Option<PathBuf> {
&self.content_dir
}
@@ -338,27 +333,6 @@ impl Template {
}
}
- fn load_custom_filters(
- layout: &TemplateLayout,
- raw: &Option<Vec<RawCustomFilter>>,
- ) -> anyhow::Result<Vec<CustomFilterParser>> {
- match raw {
- None => Ok(vec![]),
- Some(filters) => filters
- .iter()
- .map(|f| Self::load_custom_filter(layout, f))
- .collect(),
- }
- }
-
- fn load_custom_filter(
- layout: &TemplateLayout,
- raw: &RawCustomFilter,
- ) -> anyhow::Result<CustomFilterParser> {
- let wasm_path = layout.filter_path(&raw.wasm);
- CustomFilterParser::load(&raw.name, &wasm_path)
- }
-
pub(crate) fn included_files(
&self,
base: &std::path::Path,
@@ -463,3 +437,16 @@ fn read_install_record(layout: &TemplateLayout) -> InstalledFrom {
None => InstalledFrom::Unknown,
}
}
+
+fn validate_manifest(raw: &RawTemplateManifest) -> anyhow::Result<()> {
+ match raw {
+ RawTemplateManifest::V1(raw) => validate_v1_manifest(raw),
+ }
+}
+
+fn validate_v1_manifest(raw: &RawTemplateManifestV1) -> anyhow::Result<()> {
+ if raw.custom_filters.is_some() {
+ anyhow::bail!("Custom filters are not supported in this version of Spin. Please update your template.");
+ }
+ Ok(())
+}
diff --git a/crates/templates/wit/custom-filter.wit b/crates/templates/wit/custom-filter.wit
deleted file mode 100644
index 53d371492c..0000000000
--- a/crates/templates/wit/custom-filter.wit
+++ /dev/null
@@ -1,1 +0,0 @@
-exec: func(source: string) -> expected<string, string>
| 1,822
|
[
"1581"
] |
diff --git a/crates/templates/tests/filters/clappy/Cargo.toml b/crates/templates/tests/filters/clappy/Cargo.toml
deleted file mode 100644
index a30d5ce910..0000000000
--- a/crates/templates/tests/filters/clappy/Cargo.toml
+++ /dev/null
@@ -1,12 +0,0 @@
-[package]
-name = "clappy"
-version = "0.1.0"
-edition = "2021"
-
-[lib]
-crate-type = [ "cdylib" ]
-
-[dependencies]
-wit-bindgen-rust = { git = "https://github.com/bytecodealliance/wit-bindgen", rev = "cb871cfa1ee460b51eb1d144b175b9aab9c50aba" }
-
-[workspace]
diff --git a/crates/templates/tests/filters/clappy/src/lib.rs b/crates/templates/tests/filters/clappy/src/lib.rs
deleted file mode 100644
index 8e83f18909..0000000000
--- a/crates/templates/tests/filters/clappy/src/lib.rs
+++ /dev/null
@@ -1,17 +0,0 @@
-wit_bindgen_rust::export!("../../../wit/custom-filter.wit");
-
-const CLAP: char = '👏';
-
-struct CustomFilter;
-
-impl custom_filter::CustomFilter for CustomFilter {
- fn exec(source: String) -> Result<String, String> {
- let mut builder = String::with_capacity(source.len() * 2);
- for c in source.chars() {
- builder.push(c);
- builder.push(CLAP);
- }
- let result = builder.trim_end_matches(CLAP);
- Ok(result.to_owned())
- }
-}
diff --git a/crates/templates/tests/filters/studly-caps/Cargo.toml b/crates/templates/tests/filters/studly-caps/Cargo.toml
deleted file mode 100644
index fe179c2d16..0000000000
--- a/crates/templates/tests/filters/studly-caps/Cargo.toml
+++ /dev/null
@@ -1,12 +0,0 @@
-[package]
-name = "studly-caps"
-version = "0.1.0"
-edition = "2021"
-
-[lib]
-crate-type = [ "cdylib" ]
-
-[dependencies]
-wit-bindgen-rust = { git = "https://github.com/bytecodealliance/wit-bindgen", rev = "cb871cfa1ee460b51eb1d144b175b9aab9c50aba" }
-
-[workspace]
diff --git a/crates/templates/tests/filters/studly-caps/src/lib.rs b/crates/templates/tests/filters/studly-caps/src/lib.rs
deleted file mode 100644
index 22a0a59886..0000000000
--- a/crates/templates/tests/filters/studly-caps/src/lib.rs
+++ /dev/null
@@ -1,20 +0,0 @@
-wit_bindgen_rust::export!("../../../wit/custom-filter.wit");
-
-struct CustomFilter;
-
-impl custom_filter::CustomFilter for CustomFilter {
- fn exec(source: String) -> Result<String, String> {
- let mapped: String = (0..).zip(source.chars()).map(|(index, c)|
- if c.is_ascii_alphabetic() {
- if index % 2 == 0 {
- c.to_ascii_lowercase()
- } else {
- c.to_ascii_uppercase()
- }
- } else {
- c
- }
- ).collect();
- Ok(mapped)
- }
-}
diff --git a/crates/templates/tests/templates/testing-custom-filter/metadata/filters/clappy.wasm b/crates/templates/tests/templates/testing-custom-filter/metadata/filters/clappy.wasm
deleted file mode 100755
index e8126ead78..0000000000
Binary files a/crates/templates/tests/templates/testing-custom-filter/metadata/filters/clappy.wasm and /dev/null differ
diff --git a/crates/templates/tests/templates/testing-custom-filter/metadata/filters/studly_caps.wasm b/crates/templates/tests/templates/testing-custom-filter/metadata/filters/studly_caps.wasm
deleted file mode 100755
index d01943f455..0000000000
Binary files a/crates/templates/tests/templates/testing-custom-filter/metadata/filters/studly_caps.wasm and /dev/null differ
|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
35dcc921cee8a48d727e9036490da3e63d8dfcab
|
Timer trigger sample fails to resolve import
As part of ongoing component and Wasmtime infrastructure improvements, the `examples/spin-timer` trigger sample was updated in #1615 to refer to the Spin `config` API in a new way. Unfortunately, although both the trigger and example guest build okay, the example guest fails at `spin up` with:
```
$ spin up
Error: Failed to instantiate component 'three'
Caused by:
0: Failed to instantiate component 'three'
1: import `fermyon:example/config` has the wrong type
2: instance export `get-config` has the wrong type
3: expected func found nothing
```
I am not sure how to go about fixing this. @rylev @dicej do you have any ideas please? I'm not sure how to share the diff in a text format so here's ye olde GitHub screenshot:

The workaround is to revert the sample to an earlier commit (Spin itself doesn't need to be reverted as the trigger is an independent process).
Incidentally, this highlights a gap in CI - it tests that the sample _builds_, but doesn't test that it loads and runs - it would be good to improve our coverage here.
|
2023-08-30T19:03:51Z
|
fermyon__spin-1719
|
fermyon/spin
|
1.4
|
diff --git a/.github/actions/spin-ci-dependencies/action.yml b/.github/actions/spin-ci-dependencies/action.yml
index 8552ec3ed8..0be6c8ecf2 100644
--- a/.github/actions/spin-ci-dependencies/action.yml
+++ b/.github/actions/spin-ci-dependencies/action.yml
@@ -93,12 +93,11 @@ runs:
using: "composite"
steps:
- name: Install latest Rust stable toolchain
- uses: actions-rs/toolchain@v1
+ shell: bash
if: ${{ inputs.rust == 'true' }}
- with:
- toolchain: ${{ inputs.rust-version }}
- default: true
- components: clippy, rustfmt
+ run: |
+ rustup toolchain install ${{ inputs.rust-version }} --component clippy --component rustfmt
+ rustup default ${{ inputs.rust-version }}
- name: "Install Wasm Rust target"
run: rustup target add wasm32-wasi && rustup target add wasm32-unknown-unknown
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 95ec5ee3cb..4da4de0d4b 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -13,6 +13,12 @@ on:
- "README.md"
- "tests/README.md"
+# Serialize workflow runs per ref
+# Cancel any outdated, in-flight runs for refs other than 'main'
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
+
env:
CARGO_TERM_COLOR: always
jobs:
@@ -150,7 +156,8 @@ jobs:
run: make test-sdk-go
e2e-tests:
- runs-on: ubuntu-22.04
+ # run on a larger runner for more SSD/resource access
+ runs-on: ubuntu-22.04-4core-spin
needs: build-rust-ubuntu
steps:
- uses: actions/checkout@v3
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 92e4c0019c..d440945915 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -6,6 +6,12 @@ on:
tags:
- "v*"
+# Serialize workflow runs
+concurrency: ${{ github.workflow }}-${{ github.ref }}
+
+env:
+ RUST_VERSION: 1.68
+
jobs:
build-and-sign:
name: build and sign release assets
@@ -29,7 +35,7 @@ jobs:
targetDir: "target/release",
}
- {
- os: "ubuntu-latest",
+ os: "ubuntu-20.04",
arch: "aarch64",
extension: "",
extraArgs: "--features openssl/vendored --target aarch64-unknown-linux-gnu",
@@ -85,14 +91,18 @@ jobs:
cosign-release: v2.0.0
- name: Install Rust toolchain
- uses: actions-rs/toolchain@v1
- with:
- toolchain: 1.68
- default: true
- target: ${{ matrix.config.target }}
+ shell: bash
+ run: |
+ rustup toolchain install ${{ env.RUST_VERSION }}
+ rustup default ${{ env.RUST_VERSION }}
+
+ - name: Install target
+ if: matrix.config.target != ''
+ shell: bash
+ run: rustup target add --toolchain ${{ env.RUST_VERSION }} ${{ matrix.config.target }}
- name: "Install Wasm Rust target"
- run: rustup target add wasm32-wasi --toolchain 1.68 && rustup target add wasm32-unknown-unknown --toolchain 1.68
+ run: rustup target add wasm32-wasi --toolchain ${{ env.RUST_VERSION }} && rustup target add wasm32-unknown-unknown --toolchain ${{ env.RUST_VERSION }}
- name: setup for cross-compiled linux aarch64 build
if: matrix.config.target == 'aarch64-unknown-linux-gnu'
@@ -103,10 +113,8 @@ jobs:
echo 'linker = "aarch64-linux-gnu-gcc"' >> ${HOME}/.cargo/config.toml
- name: build release
- uses: actions-rs/cargo@v1
- with:
- command: build
- args: "--all-features --release ${{ matrix.config.extraArgs }}"
+ shell: bash
+ run: cargo build --all-features --release ${{ matrix.config.extraArgs }}
- name: Sign the binary with GitHub OIDC token
shell: bash
diff --git a/Cargo.lock b/Cargo.lock
index 0b8539e670..81a868082e 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -356,9 +356,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "bitflags"
-version = "2.2.1"
+version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "24a6904aef64d73cf10ab17ebace7befb918b82164785cb89907993be7f83813"
+checksum = "b4682ae6287fcf752ecaabbfcc7b6f9b72aa33933dc23a554d853aea8eea8635"
[[package]]
name = "bitvec"
@@ -1518,6 +1518,12 @@ dependencies = [
"instant",
]
+[[package]]
+name = "fastrand"
+version = "2.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6999dc1837253364c2ebb0704ba97994bd874e8f195d665c50b7548f6ea92764"
+
[[package]]
name = "fd-lock"
version = "3.0.12"
@@ -1688,7 +1694,7 @@ version = "1.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49a9d51ce47660b1e808d3c990b4709f2f415d928835a17dfd16991515c46bce"
dependencies = [
- "fastrand",
+ "fastrand 1.9.0",
"futures-core",
"futures-io",
"memchr",
@@ -1753,7 +1759,7 @@ version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27d12c0aed7f1e24276a241aadc4cb8ea9f83000f34bc062b7cc2d51e3b0fabd"
dependencies = [
- "bitflags 2.2.1",
+ "bitflags 2.4.0",
"debugid",
"fxhash",
"serde",
@@ -1903,7 +1909,7 @@ version = "5.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41b80172055c5d8017a48ddac5cc7a95421c00211047db0165c97853c4f05194"
dependencies = [
- "fastrand",
+ "fastrand 1.9.0",
"gix-tempfile",
"thiserror",
]
@@ -2773,6 +2779,12 @@ version = "0.3.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b64f40e5e03e0d54f03845c8197d0291253cdbedfb1cb46b13c2c117554a9f4c"
+[[package]]
+name = "linux-raw-sys"
+version = "0.4.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "57bcfdad1b858c2db7c38303a6d2ad4dfaf5eb53dfeb0910128b2c26d6158503"
+
[[package]]
name = "liquid"
version = "0.23.1"
@@ -3322,9 +3334,9 @@ checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5"
[[package]]
name = "openssl"
-version = "0.10.48"
+version = "0.10.55"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "518915b97df115dd36109bfa429a48b8f737bd05508cf9588977b599648926d2"
+checksum = "345df152bc43501c5eb9e4654ff05f794effb78d4efe3d53abc158baddc0703d"
dependencies = [
"bitflags 1.3.2",
"cfg-if",
@@ -3354,11 +3366,10 @@ checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf"
[[package]]
name = "openssl-sys"
-version = "0.9.83"
+version = "0.9.90"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "666416d899cf077260dac8698d60a60b435a46d57e82acb1be3d0dad87284e5b"
+checksum = "374533b0e45f3a7ced10fcaeccca020e66656bc03dac384f852e4e5a7a8104a6"
dependencies = [
- "autocfg",
"cc",
"libc",
"pkg-config",
@@ -4166,7 +4177,7 @@ version = "0.29.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "549b9d036d571d42e6e85d1c1425e2ac83491075078ca9a15be021c56b1641f2"
dependencies = [
- "bitflags 2.2.1",
+ "bitflags 2.4.0",
"fallible-iterator",
"fallible-streaming-iterator",
"hashlink",
@@ -4259,6 +4270,19 @@ dependencies = [
"windows-sys 0.48.0",
]
+[[package]]
+name = "rustix"
+version = "0.38.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac5ffa1efe7548069688cd7028f32591853cd7b5b756d41bcffd2353e4fc75b4"
+dependencies = [
+ "bitflags 2.4.0",
+ "errno 0.3.1",
+ "libc",
+ "linux-raw-sys 0.4.5",
+ "windows-sys 0.48.0",
+]
+
[[package]]
name = "rustls"
version = "0.20.8"
@@ -5467,15 +5491,15 @@ checksum = "8ae9980cab1db3fceee2f6c6f643d5d8de2997c58ee8d25fb0cc8a9e9e7348e5"
[[package]]
name = "tempfile"
-version = "3.5.0"
+version = "3.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b9fbec84f381d5795b08656e4912bec604d162bff9291d6189a78f4c8ab87998"
+checksum = "cb94d2f3cc536af71caac6b6fcebf65860b347e7ce0cc9ebe8f70d3e521054ef"
dependencies = [
"cfg-if",
- "fastrand",
+ "fastrand 2.0.0",
"redox_syscall 0.3.5",
- "rustix 0.37.20",
- "windows-sys 0.45.0",
+ "rustix 0.38.3",
+ "windows-sys 0.48.0",
]
[[package]]
@@ -7013,7 +7037,7 @@ version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "392d16e9e46cc7ca98125bc288dd5e4db469efe8323d3e0dac815ca7f2398522"
dependencies = [
- "bitflags 2.2.1",
+ "bitflags 2.4.0",
"wit-bindgen-rust-macro",
]
diff --git a/Cargo.toml b/Cargo.toml
index 3989944471..56cca0b188 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -61,7 +61,7 @@ spin-plugins = { path = "crates/plugins" }
spin-redis-engine = { path = "crates/redis" }
spin-templates = { path = "crates/templates" }
spin-trigger = { path = "crates/trigger" }
-tempfile = "3.3.0"
+tempfile = "3.8.0"
tokio = { version = "1.23", features = ["full"] }
toml = "0.6"
tracing = { workspace = true }
diff --git a/build.rs b/build.rs
index ee7b8c5789..bf24ade502 100644
--- a/build.rs
+++ b/build.rs
@@ -115,7 +115,17 @@ fn has_wasm32_wasi_target() -> bool {
fn cargo_build(dir: &str) {
run(
- vec!["cargo", "build", "--target", "wasm32-wasi", "--release"],
+ vec![
+ "cargo",
+ "build",
+ "--target",
+ "wasm32-wasi",
+ "--release",
+ // Ensure that even if `CARGO_TARGET_DIR` is set
+ // that we're still building into the right dir.
+ "--target-dir",
+ "./target",
+ ],
Some(dir),
None,
);
@@ -130,8 +140,9 @@ fn run<S: Into<String> + AsRef<std::ffi::OsStr>>(
cmd.stdout(process::Stdio::piped());
cmd.stderr(process::Stdio::piped());
- if let Some(dir) = dir {
- cmd.current_dir(dir.into());
+ let dir = dir.map(Into::into);
+ if let Some(dir) = &dir {
+ cmd.current_dir(dir);
};
if let Some(env) = env {
@@ -141,20 +152,20 @@ fn run<S: Into<String> + AsRef<std::ffi::OsStr>>(
};
cmd.arg("-c");
- cmd.arg(
- args.into_iter()
- .map(Into::into)
- .collect::<Vec<String>>()
- .join(" "),
- );
+ let c = args
+ .into_iter()
+ .map(Into::into)
+ .collect::<Vec<String>>()
+ .join(" ");
+ cmd.arg(&c);
let output = cmd.output().unwrap();
- let code = output.status.code().unwrap();
- if code != 0 {
- println!("{:#?}", std::str::from_utf8(&output.stderr).unwrap());
- println!("{:#?}", std::str::from_utf8(&output.stdout).unwrap());
- // just fail
- assert_eq!(0, code);
+ let exit = output.status;
+ if !exit.success() {
+ println!("{}", std::str::from_utf8(&output.stderr).unwrap());
+ println!("{}", std::str::from_utf8(&output.stdout).unwrap());
+ let dir = dir.unwrap_or_else(current_dir);
+ panic!("while running the build script, the command '{c}' failed to run in '{dir}'")
}
output
@@ -167,3 +178,9 @@ fn get_os_process() -> String {
String::from("bash")
}
}
+
+fn current_dir() -> String {
+ std::env::current_dir()
+ .map(|d| d.display().to_string())
+ .unwrap_or_else(|_| String::from("<CURRENT DIR>"))
+}
diff --git a/crates/app/src/lib.rs b/crates/app/src/lib.rs
index 3f874917f4..3299ff9f14 100644
--- a/crates/app/src/lib.rs
+++ b/crates/app/src/lib.rs
@@ -174,7 +174,7 @@ impl<'a, L: MaybeLoader> App<'a, L> {
&'this self,
key: MetadataKey<T>,
) -> Result<Option<T>> {
- self.locked.metadata.get_typed(key)
+ self.locked.get_metadata(key)
}
/// Deserializes typed metadata for this app.
@@ -185,7 +185,7 @@ impl<'a, L: MaybeLoader> App<'a, L> {
&'this self,
key: MetadataKey<T>,
) -> Result<T> {
- self.locked.metadata.require_typed(key)
+ self.locked.require_metadata(key)
}
/// Returns an iterator of custom config [`Variable`]s defined for this app.
diff --git a/crates/app/src/locked.rs b/crates/app/src/locked.rs
index 7cb8326db0..bf5895eaa1 100644
--- a/crates/app/src/locked.rs
+++ b/crates/app/src/locked.rs
@@ -5,7 +5,7 @@ use std::path::PathBuf;
use serde::{Deserialize, Serialize};
use serde_json::Value;
-use crate::values::ValuesMap;
+use crate::{metadata::MetadataExt, values::ValuesMap};
/// A String-keyed map with deterministic serialization order.
pub type LockedMap<T> = std::collections::BTreeMap<String, T>;
@@ -37,6 +37,29 @@ impl LockedApp {
pub fn to_json(&self) -> serde_json::Result<Vec<u8>> {
serde_json::to_vec_pretty(&self)
}
+
+ /// Deserializes typed metadata for this app.
+ ///
+ /// Returns `Ok(None)` if there is no metadata for the given `key` and an
+ /// `Err` only if there _is_ a value for the `key` but the typed
+ /// deserialization failed.
+ pub fn get_metadata<'this, T: Deserialize<'this>>(
+ &'this self,
+ key: crate::MetadataKey<T>,
+ ) -> crate::Result<Option<T>> {
+ self.metadata.get_typed(key)
+ }
+
+ /// Deserializes typed metadata for this app.
+ ///
+ /// Like [`LockedApp::get_metadata`], but returns an error if there is
+ /// no metadata for the given `key`.
+ pub fn require_metadata<'this, T: Deserialize<'this>>(
+ &'this self,
+ key: crate::MetadataKey<T>,
+ ) -> crate::Result<T> {
+ self.metadata.require_typed(key)
+ }
}
/// A LockedComponent represents a "fully resolved" Spin component.
diff --git a/crates/http/src/lib.rs b/crates/http/src/lib.rs
index 15eccbe069..c0fb1cb288 100644
--- a/crates/http/src/lib.rs
+++ b/crates/http/src/lib.rs
@@ -1,6 +1,7 @@
pub mod app_info;
pub mod config;
pub mod routes;
+pub mod trigger;
pub mod wagi;
pub const WELL_KNOWN_PREFIX: &str = "/.well-known/spin/";
diff --git a/crates/http/src/trigger.rs b/crates/http/src/trigger.rs
new file mode 100644
index 0000000000..a567dce36b
--- /dev/null
+++ b/crates/http/src/trigger.rs
@@ -0,0 +1,14 @@
+use serde::{Deserialize, Serialize};
+use spin_app::MetadataKey;
+
+/// Http trigger metadata key
+pub const METADATA_KEY: MetadataKey<Metadata> = MetadataKey::new("trigger");
+
+#[derive(Clone, Debug, Default, Deserialize, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct Metadata {
+ // The type of trigger which should always been "http" in this case
+ pub r#type: String,
+ // The based url
+ pub base: String,
+}
diff --git a/crates/loader/src/common.rs b/crates/loader/src/common.rs
index ef33717b31..6744609024 100644
--- a/crates/loader/src/common.rs
+++ b/crates/loader/src/common.rs
@@ -23,7 +23,7 @@ impl TryFrom<RawVariable> for Variable {
fn try_from(var: RawVariable) -> Result<Self, Self::Error> {
ensure!(
var.required ^ var.default.is_some(),
- "variable has both `required` and `default` set"
+ "variable should either have `required` set to true OR have a non-empty default value"
);
Ok(Variable {
default: var.default,
diff --git a/crates/loader/src/local/mod.rs b/crates/loader/src/local/mod.rs
index 03c747d391..a1cb60b090 100644
--- a/crates/loader/src/local/mod.rs
+++ b/crates/loader/src/local/mod.rs
@@ -167,7 +167,13 @@ async fn prepare(
let variables = raw
.variables
.into_iter()
- .map(|(key, var)| Ok((key, var.try_into()?)))
+ .map(|(key, var)| {
+ Ok((
+ key.clone(),
+ var.try_into()
+ .map_err(|err| anyhow!("variable '{}': {}", key, err))?,
+ ))
+ })
.collect::<Result<_>>()?;
Ok(Application {
diff --git a/crates/plugins/Cargo.toml b/crates/plugins/Cargo.toml
index 5ce5c631d6..0816ef3d64 100644
--- a/crates/plugins/Cargo.toml
+++ b/crates/plugins/Cargo.toml
@@ -7,14 +7,14 @@ edition = { workspace = true }
[dependencies]
anyhow = "1.0"
bytes = "1.1"
-chrono = "0.4"
+chrono = { version = "0.4", features = ["serde"] }
dirs = "4.0"
fd-lock = "3.0.12"
flate2 = { version = "1.0.17", features = ["zlib-ng"], default-features = false }
is-terminal = "0.4"
path-absolutize = "3.0.11"
reqwest = { version = "0.11", features = ["json"] }
-semver = "1.0"
+semver = { version = "1.0", features = ["serde"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
spin-common = { path = "../common" }
@@ -24,4 +24,4 @@ terminal = { path = "../terminal" }
thiserror = "1"
tokio = { version = "1.23", features = [ "fs", "process", "rt", "macros" ] }
tracing = { workspace = true }
-url = "2.2.2"
+url = { version = "2.2.2", features = ["serde"] }
diff --git a/crates/plugins/src/badger/mod.rs b/crates/plugins/src/badger/mod.rs
index fe5ffaf94c..b4ee7d74d3 100644
--- a/crates/plugins/src/badger/mod.rs
+++ b/crates/plugins/src/badger/mod.rs
@@ -170,7 +170,7 @@ impl BadgerEvaluator {
let latest_version = {
let latest_lookup = crate::lookup::PluginLookup::new(&self.plugin_name, None);
let latest_manifest = latest_lookup
- .get_manifest_from_repository(store.get_plugins_directory())
+ .resolve_manifest_exact(store.get_plugins_directory())
.await
.ok();
latest_manifest.and_then(|m| semver::Version::parse(m.version()).ok())
diff --git a/crates/plugins/src/error.rs b/crates/plugins/src/error.rs
index c784b7dac4..a8d2c148da 100644
--- a/crates/plugins/src/error.rs
+++ b/crates/plugins/src/error.rs
@@ -14,6 +14,9 @@ pub enum Error {
#[error("URL parse error {0}")]
UrlParseError(#[from] url::ParseError),
+
+ #[error("{0}")]
+ Other(#[from] anyhow::Error),
}
/// Contains error details for when a plugin resource cannot be found at expected location
diff --git a/crates/plugins/src/lookup.rs b/crates/plugins/src/lookup.rs
index 9c50da7503..f3c71c3347 100644
--- a/crates/plugins/src/lookup.rs
+++ b/crates/plugins/src/lookup.rs
@@ -30,7 +30,34 @@ impl PluginLookup {
}
}
- pub async fn get_manifest_from_repository(
+ pub async fn resolve_manifest(
+ &self,
+ plugins_dir: &Path,
+ skip_compatibility_check: bool,
+ spin_version: &str,
+ ) -> PluginLookupResult<PluginManifest> {
+ let exact = self.resolve_manifest_exact(plugins_dir).await?;
+ if skip_compatibility_check
+ || self.version.is_some()
+ || exact.is_compatible_spin_version(spin_version)
+ {
+ return Ok(exact);
+ }
+
+ let store = crate::store::PluginStore::new(plugins_dir.to_owned());
+
+ // TODO: This is very similar to some logic in the badger module - look for consolidation opportunities.
+ let manifests = store.catalogue_manifests()?;
+ let relevant_manifests = manifests.into_iter().filter(|m| m.name() == self.name);
+ let compatible_manifests = relevant_manifests
+ .filter(|m| m.has_compatible_package() && m.is_compatible_spin_version(spin_version));
+ let highest_compatible_manifest =
+ compatible_manifests.max_by_key(|m| m.try_version().unwrap_or_else(|_| null_version()));
+
+ Ok(highest_compatible_manifest.unwrap_or(exact))
+ }
+
+ pub async fn resolve_manifest_exact(
&self,
plugins_dir: &Path,
) -> PluginLookupResult<PluginManifest> {
@@ -41,22 +68,48 @@ impl PluginLookup {
.map_err(|e| {
Error::ConnectionFailed(ConnectionFailedError::new(url.to_string(), e.to_string()))
})?;
+
+ self.resolve_manifest_exact_from_good_repo(plugins_dir)
+ }
+
+ // This is split from resolve_manifest_exact because it may recurse (once) and that makes
+ // Rust async sad. So we move the potential recursion to a sync helper.
+ #[allow(clippy::let_and_return)]
+ pub fn resolve_manifest_exact_from_good_repo(
+ &self,
+ plugins_dir: &Path,
+ ) -> PluginLookupResult<PluginManifest> {
let expected_path = spin_plugins_repo_manifest_path(&self.name, &self.version, plugins_dir);
- let file = File::open(&expected_path).map_err(|e| {
- Error::NotFound(NotFoundError::new(
- Some(self.name.clone()),
- expected_path.display().to_string(),
- e.to_string(),
- ))
- })?;
- let manifest: PluginManifest = serde_json::from_reader(file).map_err(|e| {
- Error::InvalidManifest(InvalidManifestError::new(
+
+ let not_found = |e: std::io::Error| {
+ Err(Error::NotFound(NotFoundError::new(
Some(self.name.clone()),
expected_path.display().to_string(),
e.to_string(),
- ))
- })?;
- Ok(manifest)
+ )))
+ };
+
+ let manifest = match File::open(&expected_path) {
+ Ok(file) => serde_json::from_reader(file).map_err(|e| {
+ Error::InvalidManifest(InvalidManifestError::new(
+ Some(self.name.clone()),
+ expected_path.display().to_string(),
+ e.to_string(),
+ ))
+ }),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound && self.version.is_some() => {
+ // If a user has asked for a version by number, and the path doesn't exist,
+ // it _might_ be because it's the latest version. This checks for that case.
+ let latest = Self::new(&self.name, None);
+ match latest.resolve_manifest_exact_from_good_repo(plugins_dir) {
+ Ok(manifest) if manifest.try_version().ok() == self.version => Ok(manifest),
+ _ => not_found(e),
+ }
+ }
+ Err(e) => not_found(e),
+ };
+
+ manifest
}
}
@@ -64,6 +117,16 @@ pub fn plugins_repo_url() -> Result<Url, url::ParseError> {
Url::parse(SPIN_PLUGINS_REPO)
}
+#[cfg(not(test))]
+fn accept_as_repo(git_root: &Path) -> bool {
+ git_root.join(".git").exists()
+}
+
+#[cfg(test)]
+fn accept_as_repo(git_root: &Path) -> bool {
+ git_root.join(".git").exists() || git_root.join("_spin_test_dot_git").exists()
+}
+
pub async fn fetch_plugins_repo(
repo_url: &Url,
plugins_dir: &Path,
@@ -71,7 +134,7 @@ pub async fn fetch_plugins_repo(
) -> anyhow::Result<()> {
let git_root = plugin_manifests_repo_path(plugins_dir);
let git_source = GitSource::new(repo_url, None, &git_root);
- if git_root.join(".git").exists() {
+ if accept_as_repo(&git_root) {
if update {
git_source.pull().await?;
}
@@ -110,3 +173,83 @@ pub fn spin_plugins_repo_manifest_dir(plugins_dir: &Path) -> PathBuf {
.join(PLUGINS_REPO_LOCAL_DIRECTORY)
.join(PLUGINS_REPO_MANIFESTS_DIRECTORY)
}
+
+fn null_version() -> semver::Version {
+ semver::Version::new(0, 0, 0)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const TEST_NAME: &str = "some-spin-ver-some-not";
+ const TESTS_STORE_DIR: &str = "tests";
+
+ fn tests_store_dir() -> PathBuf {
+ PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(TESTS_STORE_DIR)
+ }
+
+ #[tokio::test]
+ async fn if_no_version_given_and_latest_is_compatible_then_latest() -> PluginLookupResult<()> {
+ let lookup = PluginLookup::new(TEST_NAME, None);
+ let resolved = lookup
+ .resolve_manifest(&tests_store_dir(), false, "99.0.0")
+ .await?;
+ assert_eq!("99.0.1", resolved.version);
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn if_no_version_given_and_latest_is_not_compatible_then_highest_compatible(
+ ) -> PluginLookupResult<()> {
+ // NOTE: The setup assumes you are NOT running Windows on aarch64, so as to check 98.1.0 is not
+ // offered. If that assumption fails then this test will fail with actual version being 98.1.0.
+ // (We use this combination because the OS and architecture enums don't allow for fake operating systems!)
+ let lookup = PluginLookup::new(TEST_NAME, None);
+ let resolved = lookup
+ .resolve_manifest(&tests_store_dir(), false, "98.0.0")
+ .await?;
+ assert_eq!("98.0.0", resolved.version);
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn if_version_given_it_gets_used_regardless() -> PluginLookupResult<()> {
+ let lookup = PluginLookup::new(TEST_NAME, Some(semver::Version::parse("99.0.0").unwrap()));
+ let resolved = lookup
+ .resolve_manifest(&tests_store_dir(), false, "98.0.0")
+ .await?;
+ assert_eq!("99.0.0", resolved.version);
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn if_latest_version_given_it_gets_used_regardless() -> PluginLookupResult<()> {
+ let lookup = PluginLookup::new(TEST_NAME, Some(semver::Version::parse("99.0.1").unwrap()));
+ let resolved = lookup
+ .resolve_manifest(&tests_store_dir(), false, "98.0.0")
+ .await?;
+ assert_eq!("99.0.1", resolved.version);
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn if_no_version_given_but_skip_compat_then_highest() -> PluginLookupResult<()> {
+ let lookup = PluginLookup::new(TEST_NAME, None);
+ let resolved = lookup
+ .resolve_manifest(&tests_store_dir(), true, "98.0.0")
+ .await?;
+ assert_eq!("99.0.1", resolved.version);
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn if_non_existent_version_given_then_error() -> PluginLookupResult<()> {
+ let lookup = PluginLookup::new(TEST_NAME, Some(semver::Version::parse("177.7.7").unwrap()));
+ lookup
+ .resolve_manifest(&tests_store_dir(), true, "99.0.0")
+ .await
+ .expect_err("Should have errored because plugin v177.7.7 does not exist");
+ Ok(())
+ }
+}
diff --git a/crates/plugins/src/manager.rs b/crates/plugins/src/manager.rs
index 53c290577b..2d6a81d241 100644
--- a/crates/plugins/src/manager.rs
+++ b/crates/plugins/src/manager.rs
@@ -6,7 +6,7 @@ use crate::{
SPIN_INTERNAL_COMMANDS,
};
-use anyhow::{anyhow, bail, Result};
+use anyhow::{anyhow, bail, Context, Result};
use path_absolutize::Absolutize;
use serde::Serialize;
use spin_common::sha256;
@@ -93,15 +93,26 @@ impl PluginManager {
let target_url = Url::parse(&target)?;
let temp_dir = tempdir()?;
let plugin_tarball_path = match target_url.scheme() {
- URL_FILE_SCHEME => target_url
- .to_file_path()
- .map_err(|_| anyhow!("Invalid file URL: {target_url:?}"))?,
+ URL_FILE_SCHEME => {
+ let path = target_url
+ .to_file_path()
+ .map_err(|_| anyhow!("Invalid file URL: {target_url:?}"))?;
+ if path.is_file() {
+ path
+ } else {
+ bail!(
+ "Package path {} does not exist or is not a file",
+ path.display()
+ );
+ }
+ }
_ => download_plugin(&plugin_manifest.name(), &temp_dir, &target).await?,
};
verify_checksum(&plugin_tarball_path, &plugin_package.sha256)?;
self.store
- .untar_plugin(&plugin_tarball_path, &plugin_manifest.name())?;
+ .untar_plugin(&plugin_tarball_path, &plugin_manifest.name())
+ .with_context(|| format!("Failed to untar {}", plugin_tarball_path.display()))?;
// Save manifest to installed plugins directory
self.store.add_manifest(plugin_manifest)?;
@@ -173,6 +184,8 @@ impl PluginManager {
pub async fn get_manifest(
&self,
manifest_location: &ManifestLocation,
+ skip_compatibility_check: bool,
+ spin_version: &str,
) -> PluginLookupResult<PluginManifest> {
let plugin_manifest = match manifest_location {
ManifestLocation::Remote(url) => {
@@ -221,7 +234,11 @@ impl PluginManager {
}
ManifestLocation::PluginsRepository(lookup) => {
lookup
- .get_manifest_from_repository(self.store().get_plugins_directory())
+ .resolve_manifest(
+ self.store().get_plugins_directory(),
+ skip_compatibility_check,
+ spin_version,
+ )
.await?
}
};
@@ -338,7 +355,8 @@ async fn download_plugin(name: &str, temp_dir: &TempDir, target_url: &str) -> Re
}
fn verify_checksum(plugin_file: &Path, expected_sha256: &str) -> Result<()> {
- let actual_sha256 = sha256::hex_digest_from_file(plugin_file)?;
+ let actual_sha256 = sha256::hex_digest_from_file(plugin_file)
+ .with_context(|| format!("Cannot get digest for {}", plugin_file.display()))?;
if actual_sha256 == expected_sha256 {
log::info!("Package checksum verified successfully");
Ok(())
diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs
index b7f7c21b87..9a0fe43d84 100644
--- a/crates/plugins/src/manifest.rs
+++ b/crates/plugins/src/manifest.rs
@@ -64,6 +64,10 @@ impl PluginManifest {
Err(_) => false,
}
}
+
+ pub fn try_version(&self) -> Result<semver::Version, semver::Error> {
+ semver::Version::parse(&self.version)
+ }
}
/// Describes compatibility and location of a plugin source.
diff --git a/crates/templates/src/lib.rs b/crates/templates/src/lib.rs
index 1aa344acd0..e4b18216d9 100644
--- a/crates/templates/src/lib.rs
+++ b/crates/templates/src/lib.rs
@@ -24,3 +24,6 @@ pub use manager::*;
pub use run::{Run, RunOptions};
pub use source::TemplateSource;
pub use template::{Template, TemplateVariantInfo};
+
+#[cfg(test)]
+mod test_built_ins;
diff --git a/crates/templates/src/manager.rs b/crates/templates/src/manager.rs
index 8f8eb23e69..2ca605c1a2 100644
--- a/crates/templates/src/manager.rs
+++ b/crates/templates/src/manager.rs
@@ -107,7 +107,11 @@ impl TemplateManager {
/// Creates a `TemplateManager` for the default install location.
pub fn try_default() -> anyhow::Result<Self> {
let store = TemplateStore::try_default()?;
- Ok(Self { store })
+ Ok(Self::new(store))
+ }
+
+ pub(crate) fn new(store: TemplateStore) -> Self {
+ Self { store }
}
/// Installs templates from the specified source.
diff --git a/crates/terminal/src/lib.rs b/crates/terminal/src/lib.rs
index 22fe9fdc46..dd7f151d40 100644
--- a/crates/terminal/src/lib.rs
+++ b/crates/terminal/src/lib.rs
@@ -75,7 +75,6 @@ fn color_choice(stream: atty::Stream) -> termcolor::ColorChoice {
#[macro_export]
macro_rules! step {
($step:expr, $($arg:tt)*) => {{
-
$crate::cprint!($crate::colors::bold_green(), $step);
print!(" ");
println!($($arg)*);
diff --git a/crates/trigger-http/src/lib.rs b/crates/trigger-http/src/lib.rs
index 26194ba832..e5778610a6 100644
--- a/crates/trigger-http/src/lib.rs
+++ b/crates/trigger-http/src/lib.rs
@@ -23,8 +23,7 @@ use hyper::{
service::{make_service_fn, service_fn},
Body, Request, Response, Server,
};
-use serde::{Deserialize, Serialize};
-use spin_app::{AppComponent, MetadataKey};
+use spin_app::AppComponent;
use spin_core::Engine;
use spin_http::{
app_info::AppInfo,
@@ -44,8 +43,6 @@ pub use tls::TlsConfig;
pub(crate) type RuntimeData = ();
pub(crate) type Store = spin_core::Store<RuntimeData>;
-const TRIGGER_METADATA_KEY: MetadataKey<TriggerMetadata> = MetadataKey::new("trigger");
-
/// The Spin HTTP trigger.
pub struct HttpTrigger {
engine: TriggerAppEngine<Self>,
@@ -84,13 +81,6 @@ impl CliArgs {
}
}
-#[derive(Clone, Debug, Default, Deserialize, Serialize)]
-#[serde(deny_unknown_fields)]
-struct TriggerMetadata {
- r#type: String,
- base: String,
-}
-
#[async_trait]
impl TriggerExecutor for HttpTrigger {
const TRIGGER_TYPE: &'static str = "http";
@@ -99,7 +89,10 @@ impl TriggerExecutor for HttpTrigger {
type RunConfig = CliArgs;
async fn new(engine: TriggerAppEngine<Self>) -> Result<Self> {
- let base = engine.app().require_metadata(TRIGGER_METADATA_KEY)?.base;
+ let base = engine
+ .app()
+ .require_metadata(spin_http::trigger::METADATA_KEY)?
+ .base;
let component_routes = engine
.trigger_configs()
@@ -174,17 +167,11 @@ impl TriggerExecutor for HttpTrigger {
if let Some(HttpExecutorType::Wagi(_)) = &config.executor {
let module = component.load_module(engine).await?;
Ok(EitherInstancePre::Module(
- engine
- .module_instantiate_pre(&module)
- .map_err(spin_trigger::decode_preinstantiation_error)?,
+ engine.module_instantiate_pre(&module)?,
))
} else {
let comp = component.load_component(engine).await?;
- Ok(EitherInstancePre::Component(
- engine
- .instantiate_pre(&comp)
- .map_err(spin_trigger::decode_preinstantiation_error)?,
- ))
+ Ok(EitherInstancePre::Component(engine.instantiate_pre(&comp)?))
}
}
}
@@ -465,6 +452,7 @@ mod tests {
use std::collections::BTreeMap;
use anyhow::Result;
+ use serde::Deserialize;
use spin_testing::test_socket_addr;
use super::*;
diff --git a/crates/trigger/src/cli.rs b/crates/trigger/src/cli.rs
index 31bb76c0c7..006c7013a2 100644
--- a/crates/trigger/src/cli.rs
+++ b/crates/trigger/src/cli.rs
@@ -28,7 +28,10 @@ pub const SPIN_WORKING_DIR: &str = "SPIN_WORKING_DIR";
/// A command that runs a TriggerExecutor.
#[derive(Parser, Debug)]
-#[clap(next_help_heading = "TRIGGER OPTIONS")]
+#[clap(
+ usage = "spin [COMMAND] [OPTIONS]",
+ next_help_heading = "TRIGGER OPTIONS"
+)]
pub struct TriggerExecutorCommand<Executor: TriggerExecutor>
where
Executor::RunConfig: Args,
diff --git a/crates/trigger/src/lib.rs b/crates/trigger/src/lib.rs
index 5a9f9a6ba5..6c1d1a2e5e 100644
--- a/crates/trigger/src/lib.rs
+++ b/crates/trigger/src/lib.rs
@@ -56,7 +56,6 @@ pub trait TriggerExecutor: Sized + Send + Sync {
Ok(EitherInstancePre::Component(
engine
.instantiate_pre(&comp)
- .map_err(decode_preinstantiation_error)
.with_context(|| format!("Failed to instantiate component '{}'", component.id()))?,
))
}
@@ -354,32 +353,3 @@ pub fn parse_file_url(url: &str) -> Result<PathBuf> {
.to_file_path()
.map_err(|_| anyhow!("Invalid file URL path: {url:?}"))
}
-
-pub fn decode_preinstantiation_error(e: anyhow::Error) -> anyhow::Error {
- let err_text = e.to_string();
-
- if err_text.contains("unknown import") && err_text.contains("has not been defined") {
- // TODO: how to maintain this list?
- let sdk_imported_interfaces = &[
- "config",
- "http",
- "key-value",
- "mysql",
- "postgres",
- "redis",
- "sqlite",
- ];
-
- if sdk_imported_interfaces
- .iter()
- .map(|s| format!("{s}::"))
- .any(|s| err_text.contains(&s))
- {
- return anyhow!(
- "{e}. Check that the component uses a SDK or plugin version that matches the Spin runtime."
- );
- }
- }
-
- e
-}
diff --git a/docs/content/release-process.md b/docs/content/release-process.md
index 38aa153a76..8ee7d76572 100644
--- a/docs/content/release-process.md
+++ b/docs/content/release-process.md
@@ -80,6 +80,10 @@ To cut a release of Spin, you will need to do the following:
`--certificate-identity` value should match this release, e.g.
`https://github.com/fermyon/spin/.github/workflows/release.yml@refs/tags/v1.1.0`.
+1. Create a Pull Request into Fermyon's Hombrew tap repository updating the [Spin
+ formula](https://github.com/fermyon/homebrew-tap/blob/main/Formula/spin.rb). In the formula,
+ update the version, point to the latest release artifacts, and set their correct sha256 digests.
+
The release is now complete!
[release action]: https://github.com/fermyon/spin/actions/workflows/release.yml
diff --git a/docs/content/triage-guide.md b/docs/content/triage-guide.md
new file mode 100644
index 0000000000..243eec970a
--- /dev/null
+++ b/docs/content/triage-guide.md
@@ -0,0 +1,41 @@
+# Triage Duty Guide
+
+This guide explains the goals of triage duty and outlines the triage process.
+
+## Goals
+
+1. Identify and properly manage critical issues in a timely manner.
+2. Label and prioritize incoming issues.
+3. Help move along conversations in issues until they are scoped for the backlog and ready for someone to pick up, closed or resolved.
+
+## Steps
+
+1. Add all new issues to the [`Spin Triage` project board](https://github.com/orgs/fermyon/projects/7/) under the `Triage Needed` column.
+
+To do this:
+
+- Go to the [project board](https://github.com/orgs/fermyon/projects/7/) and select `+ Add Item` at the bottom of the `Triage Needed` column.
+- Select `+`
+- Select `Add items to project`
+- In the search bar, filter issues by `is:issue is:open`
+- Select all and push the button `add selected items`
+
+2. For each issue in the `Triage Needed` column, add appropriate labels and move the issue to another column if the issue is ready for a different column (`Investigating / Open for Comment`, `Backlog`, `In progress`) or close.
+
+To do this:
+
+- Determine if the issue is a `bug`, `enhancement`, or `question` and label as such.
+ - If the issue does not clearly fall into one of these buckets, please ask more questions to determine what labels make sense.
+ - Please bubble up and help resolve any critical bugs as you come across them.
+ - If a `question` exposes a need for an improvement in the docs, please open up an issue in the [developer docs repo](https://github.com/fermyon/developer/issues).
+- If the issue is being currently investigated, move the issue to the `Investigating / Open for Comment` column and assign the issue an owner (the person who is investigating).
+- If the issue is an enhancement and we do not know yet whether we want to address it or it needs more input and discussion, move the issue to the `Investigating / Open for Comment` column. Please also bring this up in the next Spin maintainer or community meeting.
+- If the issue is well scoped, we want to resolve it, and it is ready to be picked up, move it to the `Backlog` column.
+- If the issue is being actively worked on, please ensure there is an owner and move it to the `In Progress` column.
+- If the issue requires no further action or it is a suggestion we don't plan on working on, add an explanation, link to other relevant issues/comments, add the appropriate labels (`duplicate`, `wontfix`) and then close the issue.
+
+3. Visit the [Security Vulnerability tab](https://github.com/fermyon/spin/security/dependabot) to see if there are any outstanding dependabot PRs to review or if any vulnerabilities need to be addressed.
+
+If merging a dependabot PR turns out to be a complicated endevaor and there are reasons for not being able to merge it immediately, leave a comment explaining the situation and where application, link to relevant upstream issues/PRs to watch for progress.
+
+4. Time permitting, review and help move along issues in the `Investigating / Open for Comment` column.
diff --git a/examples/http-rust/Cargo.lock b/examples/http-rust/Cargo.lock
index b589a47418..7b32b6a66c 100644
--- a/examples/http-rust/Cargo.lock
+++ b/examples/http-rust/Cargo.lock
@@ -14,12 +14,6 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
-[[package]]
-name = "autocfg"
-version = "1.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
-
[[package]]
name = "bitflags"
version = "1.3.2"
@@ -28,15 +22,15 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "bitflags"
-version = "2.3.2"
+version = "2.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6dbe3c979c178231552ecba20214a8272df4e09f232a87aef4320cf06539aded"
+checksum = "630be753d4e58660abd17930c71b647fe46c27ea6b63cc59e1e3851406972e42"
[[package]]
name = "bytes"
-version = "1.1.0"
+version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c4872d67bab6358e59559027aa3b9157c53d9358c51423c17554809a8858e0f8"
+checksum = "89b2fd2a0dcf38d7971e2194b6b6eebab45ae01067456a7fd93d5547a61b70be"
[[package]]
name = "fnv"
@@ -46,11 +40,10 @@ checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "form_urlencoded"
-version = "1.0.1"
+version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5fc25a87fa4fd2094bffb06925852034d90a17f0d1e05197d4956d3555752191"
+checksum = "a62bc1cf6f830c2ec14a513a9fb124d0a213a629668a4186f329db21fe045652"
dependencies = [
- "matches",
"percent-encoding",
]
@@ -71,9 +64,9 @@ dependencies = [
[[package]]
name = "http"
-version = "0.2.6"
+version = "0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "31f4c6746584866f0feabcc69893c5b51beef3831656a968ed7ae254cdc4fd03"
+checksum = "bd6effc99afb63425aff9b05836f029929e345a6148a14b7ecd5ab67af944482"
dependencies = [
"bytes",
"fnv",
@@ -98,11 +91,10 @@ checksum = "25a2bc672d1148e28034f176e01fffebb08b35768468cc954630da77a1449005"
[[package]]
name = "idna"
-version = "0.2.3"
+version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "418a0a6fab821475f634efe3ccc45c013f742efe03d853e8d3355d5cb850ecf8"
+checksum = "7d20d6b07bfbc108882d88ed8e37d39636dcc260e15e30c45e6ba089610b917c"
dependencies = [
- "matches",
"unicode-bidi",
"unicode-normalization",
]
@@ -120,9 +112,9 @@ dependencies = [
[[package]]
name = "itoa"
-version = "1.0.1"
+version = "1.0.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1aab8fc367588b89dcee83ab0fd66b72b50b72fa1904d7095045ace2b0c81c35"
+checksum = "62b02a5381cc465bd3041d84623d0fa3b66738b52b8e2fc3bab8ad63ab032f4a"
[[package]]
name = "leb128"
@@ -136,29 +128,23 @@ version = "0.4.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b06a4cde4c0f271a446782e3eff8de789548ce57dbc8eca9292c27f4a42004b4"
-[[package]]
-name = "matches"
-version = "0.1.9"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a3e378b66a060d48947b590737b30a1be76706c8dd7b8ba0f2fe3989c68a853f"
-
[[package]]
name = "memchr"
-version = "2.4.1"
+version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "308cc39be01b73d0d18f82a0e7b2a3df85245f84af96fdddc5d202d27e47b86a"
+checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d"
[[package]]
name = "percent-encoding"
-version = "2.1.0"
+version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d4fd5641d01c8f18a23da7b6fe29298ff4b55afcccdf78973b24cf3175fee32e"
+checksum = "9b2a4787296e9989611394c33f193f676704af1686e70b8f8033ab5ba9a35a94"
[[package]]
name = "proc-macro2"
-version = "1.0.60"
+version = "1.0.64"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dec2b086b7a862cf4de201096214fa870344cf922b2b30c167badb3af3195406"
+checksum = "78803b62cbf1f46fde80d7c0e803111524b9877184cfe7c3033659490ac7a7da"
dependencies = [
"unicode-ident",
]
@@ -176,9 +162,9 @@ dependencies = [
[[package]]
name = "quote"
-version = "1.0.28"
+version = "1.0.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1b9ab9c7eadfd8df19006f1cf1a4aed13540ed5cbc047010ece5826e10825488"
+checksum = "573015e8ab27661678357f27dc26460738fd2b6c86e46f386fde94cb5d913105"
dependencies = [
"proc-macro2",
]
@@ -193,6 +179,32 @@ dependencies = [
"smartstring",
]
+[[package]]
+name = "semver"
+version = "1.0.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bebd363326d05ec3e2f532ab7660680f3b02130d780c299bca73469d521bc0ed"
+
+[[package]]
+name = "serde"
+version = "1.0.171"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "30e27d1e4fd7659406c492fd6cfaf2066ba8773de45ca75e855590f856dc34a9"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.171"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "389894603bd18c46fa56231694f8d827779c0951a667087194cf9de94ed24682"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.25",
+]
+
[[package]]
name = "smartcow"
version = "0.2.1"
@@ -222,12 +234,12 @@ dependencies = [
"http",
"proc-macro2",
"quote",
- "syn",
+ "syn 1.0.109",
]
[[package]]
name = "spin-sdk"
-version = "1.4.0-pre0"
+version = "1.5.0-pre0"
dependencies = [
"anyhow",
"bytes",
@@ -247,20 +259,20 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
[[package]]
name = "syn"
-version = "1.0.85"
+version = "1.0.109"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a684ac3dcd8913827e18cd09a68384ee66c1de24157e3c556c9ab16d85695fb7"
+checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
dependencies = [
"proc-macro2",
"quote",
- "unicode-xid",
+ "unicode-ident",
]
[[package]]
name = "syn"
-version = "2.0.18"
+version = "2.0.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "32d41677bcbe24c20c52e7c70b0d8db04134c5d1066bf98662e2871ad200ea3e"
+checksum = "15e3fc8c0c74267e2df136e5e5fb656a464158aa57624053375eb9c8c6e25ae2"
dependencies = [
"proc-macro2",
"quote",
@@ -269,38 +281,38 @@ dependencies = [
[[package]]
name = "thiserror"
-version = "1.0.37"
+version = "1.0.43"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "10deb33631e3c9018b9baf9dcbbc4f737320d2b576bac10f6aefa048fa407e3e"
+checksum = "a35fc5b8971143ca348fa6df4f024d4d55264f3468c71ad1c2f365b0a4d58c42"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
-version = "1.0.37"
+version = "1.0.43"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "982d17546b47146b28f7c22e3d08465f6b8903d0ea13c1660d9d84a6e7adcdbb"
+checksum = "463fe12d7993d3b327787537ce8dd4dfa058de32fc2b195ef3cde03dc4771e8f"
dependencies = [
"proc-macro2",
"quote",
- "syn 1.0.85",
+ "syn 2.0.25",
]
[[package]]
name = "tinyvec"
-version = "1.5.1"
+version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2c1c1d5a42b6245520c249549ec267180beaffcc0615401ac8e31853d4b6d8d2"
+checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50"
dependencies = [
"tinyvec_macros",
]
[[package]]
name = "tinyvec_macros"
-version = "0.1.0"
+version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c"
+checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]]
name = "unicase"
@@ -319,36 +331,36 @@ checksum = "92888ba5573ff080736b3648696b70cafad7d250551175acbaa4e0385b3e1460"
[[package]]
name = "unicode-ident"
-version = "1.0.9"
+version = "1.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b15811caf2415fb889178633e7724bad2509101cde276048e013b9def5e51fa0"
+checksum = "22049a19f4a68748a168c0fc439f9516686aa045927ff767eca0a85101fb6e73"
[[package]]
name = "unicode-normalization"
-version = "0.1.19"
+version = "0.1.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d54590932941a9e9266f0832deed84ebe1bf2e4c9e4a3554d393d18f5e854bf9"
+checksum = "5c5713f0fc4b5db668a2ac63cdb7bb4469d8c9fed047b1d0292cc7b0ce2ba921"
dependencies = [
"tinyvec",
]
[[package]]
name = "unicode-segmentation"
-version = "1.8.0"
+version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8895849a949e7845e06bd6dc1aa51731a103c42707010a5b591c0038fb73385b"
+checksum = "1dd624098567895118886609431a7c3b8f516e41d30e0643f03d94592a147e36"
[[package]]
name = "unicode-xid"
-version = "0.2.2"
+version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3"
+checksum = "f962df74c8c05a667b5ee8bcf162993134c104e96440b663c8daa176dc772d8c"
[[package]]
name = "url"
-version = "2.3.0"
+version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "22fe195a4f217c25b25cb5058ced57059824a678474874038dc88d211bf508d3"
+checksum = "50bff7831e19200a85b17131d085c25d7811bc4e186efdaf54bbd132994a88cb"
dependencies = [
"form_urlencoded",
"idna",
@@ -399,7 +411,7 @@ version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "392d16e9e46cc7ca98125bc288dd5e4db469efe8323d3e0dac815ca7f2398522"
dependencies = [
- "bitflags 2.3.2",
+ "bitflags 2.3.3",
"wit-bindgen-rust-macro",
]
@@ -445,7 +457,7 @@ checksum = "ced38a5e174940c6a41ae587babeadfd2e2c2dc32f3b6488bcdca0e8922cf3f3"
dependencies = [
"anyhow",
"proc-macro2",
- "syn 2.0.18",
+ "syn 2.0.25",
"wit-bindgen-core",
"wit-bindgen-rust",
"wit-component",
diff --git a/examples/spin-timer/Cargo.lock b/examples/spin-timer/Cargo.lock
index a2d48839bb..9802ee8be6 100644
--- a/examples/spin-timer/Cargo.lock
+++ b/examples/spin-timer/Cargo.lock
@@ -87,12 +87,6 @@ version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2d098ff73c1ca148721f37baad5ea6a465a13f9573aba8641fbbbae8164a54e"
-[[package]]
-name = "arrayvec"
-version = "0.7.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8da52d66c7071e2e3fa2a1e5c6d088fec47b593032b254f5e980de8ea54454d6"
-
[[package]]
name = "async-channel"
version = "1.8.0"
@@ -215,17 +209,6 @@ dependencies = [
"getrandom 0.2.8",
]
-[[package]]
-name = "bigdecimal"
-version = "0.3.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6aaf33151a6429fe9211d1b276eafdf70cdff28b071e76c0b0e1503221ea3744"
-dependencies = [
- "num-bigint",
- "num-integer",
- "num-traits",
-]
-
[[package]]
name = "bincode"
version = "1.3.3"
@@ -349,78 +332,12 @@ dependencies = [
"opaque-debug",
]
-[[package]]
-name = "borsh"
-version = "0.9.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "15bf3650200d8bffa99015595e10f1fbd17de07abbc25bb067da79e769939bfa"
-dependencies = [
- "borsh-derive",
- "hashbrown 0.11.2",
-]
-
-[[package]]
-name = "borsh-derive"
-version = "0.9.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6441c552f230375d18e3cc377677914d2ca2b0d36e52129fe15450a2dce46775"
-dependencies = [
- "borsh-derive-internal",
- "borsh-schema-derive-internal",
- "proc-macro-crate",
- "proc-macro2",
- "syn 1.0.107",
-]
-
-[[package]]
-name = "borsh-derive-internal"
-version = "0.9.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5449c28a7b352f2d1e592a8a28bf139bc71afb0764a14f3c02500935d8c44065"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 1.0.107",
-]
-
-[[package]]
-name = "borsh-schema-derive-internal"
-version = "0.9.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cdbd5696d8bfa21d53d9fe39a714a18538bad11492a42d066dbbc395fb1951c0"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 1.0.107",
-]
-
[[package]]
name = "bumpalo"
version = "3.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d261e256854913907f67ed06efbc3338dfe6179796deefc1ff763fc1aee5535"
-[[package]]
-name = "bytecheck"
-version = "0.6.9"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d11cac2c12b5adc6570dad2ee1b87eff4955dac476fe12d81e5fdd352e52406f"
-dependencies = [
- "bytecheck_derive",
- "ptr_meta",
-]
-
-[[package]]
-name = "bytecheck_derive"
-version = "0.6.9"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "13e576ebe98e605500b3c8041bb888e966653577172df6dd97398714eb30b9bf"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 1.0.107",
-]
-
[[package]]
name = "byteorder"
version = "1.4.3"
@@ -1233,7 +1150,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a8a2db397cb1c8772f31494cb8917e48cd1e64f0fa7efac59fbd741a0a8ce841"
dependencies = [
"crc32fast",
- "libz-sys",
+ "libz-ng-sys",
"miniz_oxide",
]
@@ -1267,70 +1184,6 @@ dependencies = [
"percent-encoding",
]
-[[package]]
-name = "frunk"
-version = "0.4.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a89c703bf50009f383a0873845357cc400a95fc535f836feddfe015d7df6e1e0"
-dependencies = [
- "frunk_core",
- "frunk_derives",
- "frunk_proc_macros",
-]
-
-[[package]]
-name = "frunk_core"
-version = "0.4.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2a446d01a558301dca28ef43222864a9fa2bd9a2e71370f769d5d5d5ec9f3537"
-
-[[package]]
-name = "frunk_derives"
-version = "0.4.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b83164912bb4c97cfe0772913c7af7387ee2e00cb6d4636fb65a35b3d0c8f173"
-dependencies = [
- "frunk_proc_macro_helpers",
- "quote",
- "syn 1.0.107",
-]
-
-[[package]]
-name = "frunk_proc_macro_helpers"
-version = "0.1.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "015425591bbeb0f5b8a75593340f1789af428e9f887a4f1e36c0c471f067ef50"
-dependencies = [
- "frunk_core",
- "proc-macro2",
- "quote",
- "syn 1.0.107",
-]
-
-[[package]]
-name = "frunk_proc_macros"
-version = "0.1.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ea01524f285deab48affffb342b97f186e657b119c3f1821ac531780e0fbfae0"
-dependencies = [
- "frunk_core",
- "frunk_proc_macros_impl",
- "proc-macro-hack",
-]
-
-[[package]]
-name = "frunk_proc_macros_impl"
-version = "0.1.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0a802d974cc18ee7fe1a7868fc9ce31086294fd96ba62f8da64ecb44e92a2653"
-dependencies = [
- "frunk_core",
- "frunk_proc_macro_helpers",
- "proc-macro-hack",
- "quote",
- "syn 1.0.107",
-]
-
[[package]]
name = "fs-set-times"
version = "0.19.1"
@@ -1560,15 +1413,6 @@ version = "1.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eabb4a44450da02c90444cf74558da904edde8fb4e9035a9a6a4e15445af0bd7"
-[[package]]
-name = "hashbrown"
-version = "0.11.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e"
-dependencies = [
- "ahash 0.7.6",
-]
-
[[package]]
name = "hashbrown"
version = "0.12.3"
@@ -1637,9 +1481,9 @@ dependencies = [
[[package]]
name = "hrana-client-proto"
-version = "0.1.2"
+version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "26f15d50a607f7f2cb8cb97cad7ae746f861139e8ebc425a8545195a556d6102"
+checksum = "f16b4e41e289da3fd60e64f245246a97e78fab7b3788c6d8147b3ae7d9f5e533"
dependencies = [
"anyhow",
"base64 0.21.0",
@@ -2044,18 +1888,20 @@ dependencies = [
[[package]]
name = "libsql-client"
-version = "0.24.5"
+version = "0.31.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8861153820a4228a1261ee92138345f7e08c71e64a75c95217247427172f2ce8"
+checksum = "e119ff2e259fe776a1340d2cb40baf4d44c32e5a9fd2755e756fc46802c79c70"
dependencies = [
"anyhow",
- "async-trait",
"base64 0.21.0",
+ "fallible-iterator",
+ "futures",
"hrana-client-proto",
"num-traits",
"reqwest",
"serde",
"serde_json",
+ "sqlite3-parser",
"tracing",
"url",
]
@@ -2072,14 +1918,13 @@ dependencies = [
]
[[package]]
-name = "libz-sys"
-version = "1.1.8"
+name = "libz-ng-sys"
+version = "1.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9702761c3935f8cc2f101793272e202c72b99da8f4224a19ddcf1279a6450bbf"
+checksum = "2468756f34903b582fe7154dc1ffdebd89d0562c4a43b53c621bb0f1b1043ccb"
dependencies = [
- "cc",
- "pkg-config",
- "vcpkg",
+ "cmake",
+ "libc",
]
[[package]]
@@ -2279,7 +2124,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9006c95034ccf7b903d955f210469119f6c3477fc9c9e7a7845ce38a3e665c2a"
dependencies = [
"base64 0.13.1",
- "bigdecimal",
"bindgen",
"bitflags 1.3.2",
"bitvec",
@@ -2289,14 +2133,12 @@ dependencies = [
"cmake",
"crc32fast",
"flate2",
- "frunk",
"lazy_static",
"lexical",
"num-bigint",
"num-traits",
"rand 0.8.5",
"regex",
- "rust_decimal",
"saturating",
"serde",
"serde_json",
@@ -2305,8 +2147,6 @@ dependencies = [
"smallvec",
"subprocess",
"thiserror",
- "time",
- "uuid",
]
[[package]]
@@ -2518,7 +2358,7 @@ dependencies = [
[[package]]
name = "outbound-http"
-version = "1.4.0-pre0"
+version = "1.5.0-pre0"
dependencies = [
"anyhow",
"http",
@@ -2532,9 +2372,10 @@ dependencies = [
[[package]]
name = "outbound-mysql"
-version = "1.4.0-pre0"
+version = "1.5.0-pre0"
dependencies = [
"anyhow",
+ "flate2",
"mysql_async",
"mysql_common",
"spin-core",
@@ -2546,7 +2387,7 @@ dependencies = [
[[package]]
name = "outbound-pg"
-version = "1.4.0-pre0"
+version = "1.5.0-pre0"
dependencies = [
"anyhow",
"native-tls",
@@ -2560,7 +2401,7 @@ dependencies = [
[[package]]
name = "outbound-redis"
-version = "1.4.0-pre0"
+version = "1.5.0-pre0"
dependencies = [
"anyhow",
"redis",
@@ -2678,6 +2519,26 @@ dependencies = [
"phf_shared",
]
+[[package]]
+name = "phf_codegen"
+version = "0.11.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e8d39688d359e6b34654d328e262234662d16cc0f60ec8dcbe5e718709342a5a"
+dependencies = [
+ "phf_generator",
+ "phf_shared",
+]
+
+[[package]]
+name = "phf_generator"
+version = "0.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b1181c94580fa345f50f19d738aaa39c0ed30a600d95cb2d3e23f94266f14fbf"
+dependencies = [
+ "phf_shared",
+ "rand 0.8.5",
+]
+
[[package]]
name = "phf_shared"
version = "0.11.1"
@@ -2685,6 +2546,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1fb5f6f826b772a8d4c0394209441e7d37cbbb967ae9c7e0e8134365c9ee676"
dependencies = [
"siphasher",
+ "uncased",
]
[[package]]
@@ -2773,15 +2635,6 @@ version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de"
-[[package]]
-name = "proc-macro-crate"
-version = "0.1.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1d6ea3c4595b96363c13943497db34af4460fb474a95c43f4446ad341b8c9785"
-dependencies = [
- "toml",
-]
-
[[package]]
name = "proc-macro-error"
version = "1.0.4"
@@ -2806,12 +2659,6 @@ dependencies = [
"version_check",
]
-[[package]]
-name = "proc-macro-hack"
-version = "0.5.20+deprecated"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068"
-
[[package]]
name = "proc-macro2"
version = "1.0.54"
@@ -2830,26 +2677,6 @@ dependencies = [
"cc",
]
-[[package]]
-name = "ptr_meta"
-version = "0.1.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0738ccf7ea06b608c10564b31debd4f5bc5e197fc8bfe088f68ae5ce81e7a4f1"
-dependencies = [
- "ptr_meta_derive",
-]
-
-[[package]]
-name = "ptr_meta_derive"
-version = "0.1.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "16b845dbfca988fa33db069c0e230574d15a3088f147a87b64c7589eb662c9ac"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 1.0.107",
-]
-
[[package]]
name = "pulldown-cmark"
version = "0.8.0"
@@ -3050,15 +2877,6 @@ dependencies = [
"winapi",
]
-[[package]]
-name = "rend"
-version = "0.3.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "79af64b4b6362ffba04eef3a4e10829718a4896dac19daa741851c86781edf95"
-dependencies = [
- "bytecheck",
-]
-
[[package]]
name = "reqwest"
version = "0.11.14"
@@ -3119,31 +2937,6 @@ dependencies = [
"winapi",
]
-[[package]]
-name = "rkyv"
-version = "0.7.39"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cec2b3485b07d96ddfd3134767b8a447b45ea4eb91448d0a35180ec0ffd5ed15"
-dependencies = [
- "bytecheck",
- "hashbrown 0.12.3",
- "ptr_meta",
- "rend",
- "rkyv_derive",
- "seahash",
-]
-
-[[package]]
-name = "rkyv_derive"
-version = "0.7.39"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6eaedadc88b53e36dd32d940ed21ae4d850d5916f2581526921f553a72ac34c4"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 1.0.107",
-]
-
[[package]]
name = "rusqlite"
version = "0.29.0"
@@ -3158,24 +2951,6 @@ dependencies = [
"smallvec",
]
-[[package]]
-name = "rust_decimal"
-version = "1.28.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7fe32e8c89834541077a5c5bbe5691aa69324361e27e6aeb3552a737db4a70c8"
-dependencies = [
- "arrayvec",
- "borsh",
- "bytecheck",
- "byteorder",
- "bytes",
- "num-traits",
- "rand 0.8.5",
- "rkyv",
- "serde",
- "serde_json",
-]
-
[[package]]
name = "rustc-demangle"
version = "0.1.21"
@@ -3344,12 +3119,6 @@ dependencies = [
"untrusted",
]
-[[package]]
-name = "seahash"
-version = "4.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b"
-
[[package]]
name = "security-framework"
version = "2.8.0"
@@ -3617,7 +3386,7 @@ checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d"
[[package]]
name = "spin-app"
-version = "1.4.0-pre0"
+version = "1.5.0-pre0"
dependencies = [
"anyhow",
"async-trait",
@@ -3630,7 +3399,7 @@ dependencies = [
[[package]]
name = "spin-common"
-version = "1.4.0-pre0"
+version = "1.5.0-pre0"
dependencies = [
"anyhow",
"dirs",
@@ -3652,7 +3421,7 @@ dependencies = [
[[package]]
name = "spin-config"
-version = "1.4.0-pre0"
+version = "1.5.0-pre0"
dependencies = [
"anyhow",
"async-trait",
@@ -3669,7 +3438,7 @@ dependencies = [
[[package]]
name = "spin-core"
-version = "1.4.0-pre0"
+version = "1.5.0-pre0"
dependencies = [
"anyhow",
"async-trait",
@@ -3686,7 +3455,7 @@ dependencies = [
[[package]]
name = "spin-key-value"
-version = "1.4.0-pre0"
+version = "1.5.0-pre0"
dependencies = [
"anyhow",
"lru 0.9.0",
@@ -3739,7 +3508,7 @@ dependencies = [
[[package]]
name = "spin-loader"
-version = "1.4.0-pre0"
+version = "1.5.0-pre0"
dependencies = [
"anyhow",
"async-trait",
@@ -3761,6 +3530,7 @@ dependencies = [
"serde_json",
"shellexpand 3.1.0",
"spin-common",
+ "spin-config",
"spin-manifest",
"tempfile",
"terminal",
@@ -3773,7 +3543,7 @@ dependencies = [
[[package]]
name = "spin-manifest"
-version = "1.4.0-pre0"
+version = "1.5.0-pre0"
dependencies = [
"indexmap",
"serde",
@@ -3783,9 +3553,10 @@ dependencies = [
[[package]]
name = "spin-sqlite"
-version = "1.4.0-pre0"
+version = "1.5.0-pre0"
dependencies = [
"anyhow",
+ "async-trait",
"spin-app",
"spin-core",
"spin-key-value",
@@ -3795,9 +3566,10 @@ dependencies = [
[[package]]
name = "spin-sqlite-inproc"
-version = "1.4.0-pre0"
+version = "1.5.0-pre0"
dependencies = [
"anyhow",
+ "async-trait",
"once_cell",
"rand 0.8.5",
"rusqlite",
@@ -3808,9 +3580,10 @@ dependencies = [
[[package]]
name = "spin-sqlite-libsql"
-version = "1.4.0-pre0"
+version = "1.5.0-pre0"
dependencies = [
"anyhow",
+ "async-trait",
"libsql-client",
"spin-sqlite",
"spin-world",
@@ -3820,7 +3593,7 @@ dependencies = [
[[package]]
name = "spin-trigger"
-version = "1.4.0-pre0"
+version = "1.5.0-pre0"
dependencies = [
"anyhow",
"async-trait",
@@ -3861,7 +3634,7 @@ dependencies = [
[[package]]
name = "spin-world"
-version = "1.4.0-pre0"
+version = "1.5.0-pre0"
dependencies = [
"wasmtime",
]
@@ -3872,6 +3645,25 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b9b39299b249ad65f3b7e96443bad61c02ca5cd3589f46cb6d610a0fd6c0d6a"
+[[package]]
+name = "sqlite3-parser"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3995a6daa13c113217b6ad22154865fb06f9cb939bef398fd04f4a7aaaf5bd7"
+dependencies = [
+ "bitflags 2.2.1",
+ "cc",
+ "fallible-iterator",
+ "indexmap",
+ "log",
+ "memchr",
+ "phf",
+ "phf_codegen",
+ "phf_shared",
+ "smallvec",
+ "uncased",
+]
+
[[package]]
name = "sqlparser"
version = "0.34.0"
@@ -4326,6 +4118,15 @@ version = "1.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "497961ef93d974e23eb6f433eb5fe1b7930b659f06d12dec6fc44a8f554c0bba"
+[[package]]
+name = "uncased"
+version = "0.9.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b9bc53168a4be7402ab86c3aad243a84dd7381d09be0eddc81280c1da95ca68"
+dependencies = [
+ "version_check",
+]
+
[[package]]
name = "unicase"
version = "2.6.0"
diff --git a/examples/spin-timer/app-example/src/lib.rs b/examples/spin-timer/app-example/src/lib.rs
index 1a115d8692..7485a60657 100644
--- a/examples/spin-timer/app-example/src/lib.rs
+++ b/examples/spin-timer/app-example/src/lib.rs
@@ -1,9 +1,9 @@
wit_bindgen::generate!({
world: "spin-timer",
- path: "../spin-timer.wit"
+ path: ".."
});
-use fermyon::example::config;
+use fermyon::spin::config;
struct MySpinTimer;
diff --git a/examples/spin-timer/deps/spin/config.wit b/examples/spin-timer/deps/spin/config.wit
new file mode 100644
index 0000000000..bdf478ce73
--- /dev/null
+++ b/examples/spin-timer/deps/spin/config.wit
@@ -0,0 +1,14 @@
+package fermyon:spin
+
+interface config {
+ // Get a configuration value for the current component.
+ // The config key must match one defined in in the component manifest.
+ get-config: func(key: string) -> result<string, error>
+
+ variant error {
+ provider(string),
+ invalid-key(string),
+ invalid-schema(string),
+ other(string),
+ }
+}
diff --git a/examples/spin-timer/spin-timer.wit b/examples/spin-timer/spin-timer.wit
index 9744d1f333..2d476dcc2b 100644
--- a/examples/spin-timer/spin-timer.wit
+++ b/examples/spin-timer/spin-timer.wit
@@ -1,19 +1,6 @@
package fermyon:example
-interface config {
- // Get a configuration value for the current component.
- // The config key must match one defined in in the component manifest.
- get-config: func(key: string) -> result<string, error>
-
- variant error {
- provider(string),
- invalid-key(string),
- invalid-schema(string),
- other(string),
- }
-}
-
world spin-timer {
- import config
+ import fermyon:spin/config
export handle-timer-request: func()
}
diff --git a/examples/spin-timer/src/main.rs b/examples/spin-timer/src/main.rs
index 6db0107f73..55ba0348f0 100644
--- a/examples/spin-timer/src/main.rs
+++ b/examples/spin-timer/src/main.rs
@@ -10,7 +10,7 @@ use spin_trigger::{
};
wasmtime::component::bindgen!({
- path: "spin-timer.wit",
+ path: ".",
world: "spin-timer",
async: true
});
diff --git a/sdk/go/Makefile b/sdk/go/Makefile
index 5772752817..b2463c97ba 100644
--- a/sdk/go/Makefile
+++ b/sdk/go/Makefile
@@ -47,6 +47,10 @@ SDK_VERSION_SOURCE_FILE = sdk_version/sdk-version-go-template.c
SDK_VERSION_DEST_FILES = config/sdk-version-go.c http/sdk-version-go.c \
key_value/sdk-version-go.c redis/sdk-version-go.c
+# NOTE: To generate the C bindings you need to install a forked version of wit-bindgen.
+#
+# cargo install wit-bindgen-cli --git https://github.com/fermyon/wit-bindgen-backport --rev "b89d5079ba5b07b319631a1b191d2139f126c976"
+#
.PHONY: generate
generate: $(GENERATED_OUTBOUND_HTTP) $(GENERATED_SPIN_HTTP)
generate: $(GENERATED_OUTBOUND_REDIS) $(GENERATED_SPIN_REDIS)
diff --git a/sdk/go/key_value/key-value.go b/sdk/go/key_value/key-value.go
index a5141256f8..b0e8485ea4 100644
--- a/sdk/go/key_value/key-value.go
+++ b/sdk/go/key_value/key-value.go
@@ -10,7 +10,7 @@ import (
"unsafe"
)
-type Store C.key_value_store_t
+type Store uint32
const (
errorKindStoreTableFull = iota
diff --git a/sdk/go/redis/internals.go b/sdk/go/redis/internals.go
index fa32f7d782..57c4993d3c 100644
--- a/sdk/go/redis/internals.go
+++ b/sdk/go/redis/internals.go
@@ -100,7 +100,7 @@ func srem(addr string, key string, values []string) (int64, error) {
return int64(cpayload), toErr(err)
}
-type RedisParameterKind C.uint8_t
+type RedisParameterKind uint8
const (
RedisParameterKindInt64 = iota
@@ -112,7 +112,7 @@ type RedisParameter struct {
Val interface{}
}
-type RedisResultKind C.uint8_t
+type RedisResultKind uint8
const (
RedisResultKindNil = iota
diff --git a/src/bin/spin.rs b/src/bin/spin.rs
index ee2988a2f3..a8a8a96f0e 100644
--- a/src/bin/spin.rs
+++ b/src/bin/spin.rs
@@ -2,7 +2,6 @@ use anyhow::Error;
use clap::{CommandFactory, FromArgMatches, Parser, Subcommand};
use is_terminal::IsTerminal;
use lazy_static::lazy_static;
-use spin_cli::build_info::*;
use spin_cli::commands::external::predefined_externals;
use spin_cli::commands::{
build::BuildCommand,
@@ -16,6 +15,7 @@ use spin_cli::commands::{
up::UpCommand,
watch::WatchCommand,
};
+use spin_cli::{build_info::*, subprocess::ExitStatusError};
use spin_redis_engine::RedisTrigger;
use spin_trigger::cli::help::HelpArgsOnlyTrigger;
use spin_trigger::cli::TriggerExecutorCommand;
@@ -24,9 +24,20 @@ use spin_trigger_http::HttpTrigger;
#[tokio::main]
async fn main() {
if let Err(err) = _main().await {
- terminal::error!("{err}");
- print_error_chain(err);
- std::process::exit(1)
+ let code = match err.downcast_ref::<ExitStatusError>() {
+ // If we encounter an `ExitStatusError` it means a subprocess has already
+ // exited unsuccessfully and thus already printed error messages. No need
+ // to print anything additional.
+ Some(e) => e.code(),
+ // Otherwise we print the error chain.
+ None => {
+ terminal::error!("{err}");
+ print_error_chain(err);
+ 1
+ }
+ };
+
+ std::process::exit(code)
}
}
diff --git a/src/commands/plugins.rs b/src/commands/plugins.rs
index a5dbe5619a..31ca9f8b58 100644
--- a/src/commands/plugins.rs
+++ b/src/commands/plugins.rs
@@ -114,7 +114,13 @@ impl Install {
let manager = PluginManager::try_default()?;
// Downgrades are only allowed via the `upgrade` subcommand
let downgrade = false;
- let manifest = manager.get_manifest(&manifest_location).await?;
+ let manifest = manager
+ .get_manifest(
+ &manifest_location,
+ self.override_compatibility_check,
+ SPIN_VERSION,
+ )
+ .await?;
try_install(
&manifest,
&manager,
@@ -250,7 +256,14 @@ impl Upgrade {
.to_string();
let manifest_location =
ManifestLocation::PluginsRepository(PluginLookup::new(&name, None));
- let manifest = match manager.get_manifest(&manifest_location).await {
+ let manifest = match manager
+ .get_manifest(
+ &manifest_location,
+ self.override_compatibility_check,
+ SPIN_VERSION,
+ )
+ .await
+ {
Err(Error::NotFound(e)) => {
log::info!("Could not upgrade plugin '{name}': {e:?}");
continue;
@@ -283,7 +296,13 @@ impl Upgrade {
self.version,
)),
};
- let manifest = manager.get_manifest(&manifest_location).await?;
+ let manifest = manager
+ .get_manifest(
+ &manifest_location,
+ self.override_compatibility_check,
+ SPIN_VERSION,
+ )
+ .await?;
try_install(
&manifest,
&manager,
diff --git a/src/commands/up.rs b/src/commands/up.rs
index 0460f2c787..1e337cae35 100644
--- a/src/commands/up.rs
+++ b/src/commands/up.rs
@@ -126,7 +126,7 @@ impl UpCommand {
}
let working_dir_holder = match &self.tmp {
- None => WorkingDirectory::Temporary(tempfile::tempdir()?),
+ None => WorkingDirectory::Temporary(TempDir::with_prefix("spinup-")?),
Some(d) => WorkingDirectory::Given(d.to_owned()),
};
let working_dir = working_dir_holder.path().canonicalize()?;
@@ -206,7 +206,7 @@ impl UpCommand {
if status.success() {
Ok(())
} else {
- bail!(status);
+ Err(crate::subprocess::ExitStatusError::new(status).into())
}
}
diff --git a/src/lib.rs b/src/lib.rs
index c5284f7f6a..f2becb44a1 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,7 +1,8 @@
pub mod build_info;
pub mod commands;
pub(crate) mod opts;
+pub mod subprocess;
mod watch_filter;
mod watch_state;
-pub use crate::opts::HELP_ARGS_ONLY_TRIGGER_TYPE;
+pub use opts::HELP_ARGS_ONLY_TRIGGER_TYPE;
diff --git a/src/subprocess.rs b/src/subprocess.rs
new file mode 100644
index 0000000000..cc6b4d93c2
--- /dev/null
+++ b/src/subprocess.rs
@@ -0,0 +1,34 @@
+/// An error representing a subprocess that errored
+///
+/// This can be used to propogate a subprocesses exit status.
+/// When this error is encountered the cli will exit with the status code
+/// instead of printing an error,
+#[derive(Debug)]
+pub struct ExitStatusError {
+ status: Option<i32>,
+}
+
+impl ExitStatusError {
+ pub(crate) fn new(status: std::process::ExitStatus) -> Self {
+ Self {
+ status: status.code(),
+ }
+ }
+
+ pub fn code(&self) -> i32 {
+ self.status.unwrap_or(1)
+ }
+}
+
+impl std::error::Error for ExitStatusError {}
+
+impl std::fmt::Display for ExitStatusError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let _ = write!(f, "subprocess exited with status: ");
+ if let Some(status) = self.status {
+ writeln!(f, "{}", status)
+ } else {
+ writeln!(f, "unknown")
+ }
+ }
+}
diff --git a/templates/static-fileserver/content/spin.toml b/templates/static-fileserver/content/spin.toml
index 67aae1f339..8e2883777f 100644
--- a/templates/static-fileserver/content/spin.toml
+++ b/templates/static-fileserver/content/spin.toml
@@ -6,8 +6,8 @@ trigger = { type = "http", base = "{{http-base}}" }
version = "0.1.0"
[[component]]
-source = { url = "https://github.com/fermyon/spin-fileserver/releases/download/v0.0.2/spin_static_fs.wasm", digest = "sha256:65456bf4e84cf81b62075e761b2b0afaffaef2d0aeda521b245150f76b96421b" }
+source = { url = "https://github.com/fermyon/spin-fileserver/releases/download/v0.0.3/spin_static_fs.wasm", digest = "sha256:38bf971900228222f7f6b2ccee5051f399adca58d71692cdfdea98997965fd0d" }
id = "{{ project-name }}"
-files = [ { source = "{{ files-path }}", destination = "/" } ]
+files = [{ source = "{{ files-path }}", destination = "/" }]
[component.trigger]
route = "{{ http-path | http_wildcard }}"
diff --git a/templates/static-fileserver/metadata/snippets/component.txt b/templates/static-fileserver/metadata/snippets/component.txt
index 39eaf20313..683a2f2c91 100644
--- a/templates/static-fileserver/metadata/snippets/component.txt
+++ b/templates/static-fileserver/metadata/snippets/component.txt
@@ -1,5 +1,5 @@
[[component]]
-source = { url = "https://github.com/fermyon/spin-fileserver/releases/download/v0.0.2/spin_static_fs.wasm", digest = "sha256:65456bf4e84cf81b62075e761b2b0afaffaef2d0aeda521b245150f76b96421b" }
+source = { url = "https://github.com/fermyon/spin-fileserver/releases/download/v0.0.3/spin_static_fs.wasm", digest = "sha256:38bf971900228222f7f6b2ccee5051f399adca58d71692cdfdea98997965fd0d" }
id = "{{ project-name }}"
files = [ { source = "{{ files-path }}", destination = "/" } ]
[component.trigger]
diff --git a/templates/static-fileserver/metadata/spin-template.toml b/templates/static-fileserver/metadata/spin-template.toml
index dbdebe8735..9399a04dad 100644
--- a/templates/static-fileserver/metadata/spin-template.toml
+++ b/templates/static-fileserver/metadata/spin-template.toml
@@ -5,7 +5,7 @@ trigger_type = "http"
tags = ["http", "file", "static", "asset"]
[add_component]
-skip_files = ["spin.toml"]
+skip_files = ["spin.toml", ".gitignore"]
skip_parameters = ["http-base", "project-description"]
[add_component.snippets]
component = "component.txt"
| 1,719
|
[
"1662"
] |
diff --git a/crates/e2e-testing/src/testcase.rs b/crates/e2e-testing/src/testcase.rs
index 8d940f0c61..383cde239f 100644
--- a/crates/e2e-testing/src/testcase.rs
+++ b/crates/e2e-testing/src/testcase.rs
@@ -153,7 +153,9 @@ impl TestCase {
}
// run spin build
- let build_output = controller.build_app(&appname).context("building app")?;
+ let build_output = controller
+ .build_app(&appname)
+ .context("failed building app")?;
if bail_on_run_failure {
utils::assert_success(&build_output);
}
diff --git a/crates/plugins/tests/.spin-plugins/_spin_test_dot_git b/crates/plugins/tests/.spin-plugins/_spin_test_dot_git
new file mode 100644
index 0000000000..a60a97e033
--- /dev/null
+++ b/crates/plugins/tests/.spin-plugins/_spin_test_dot_git
@@ -0,0 +1,1 @@
+Fake file for preventing the plugin system from pulling from the production repo into this directory during tests
diff --git a/crates/plugins/tests/.spin-plugins/manifests/some-spin-ver-some-not/some-spin-ver-some-not.json b/crates/plugins/tests/.spin-plugins/manifests/some-spin-ver-some-not/some-spin-ver-some-not.json
new file mode 100644
index 0000000000..d325dc8ec1
--- /dev/null
+++ b/crates/plugins/tests/.spin-plugins/manifests/some-spin-ver-some-not/some-spin-ver-some-not.json
@@ -0,0 +1,27 @@
+{
+ "name": "some-spin-ver-some-not",
+ "description": "A plugin where only some versions work with the test harness version of Spin.",
+ "version": "99.0.1",
+ "spinCompatibility": ">=99.0",
+ "license": "Apache-2.0",
+ "packages": [
+ {
+ "os": "linux",
+ "arch": "amd64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ },
+ {
+ "os": "macos",
+ "arch": "aarch64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ },
+ {
+ "os": "macos",
+ "arch": "amd64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ }
+ ]
+}
diff --git a/crates/plugins/tests/.spin-plugins/manifests/some-spin-ver-some-not/some-spin-ver-some-not@98.0.0.json b/crates/plugins/tests/.spin-plugins/manifests/some-spin-ver-some-not/some-spin-ver-some-not@98.0.0.json
new file mode 100644
index 0000000000..e3db68191a
--- /dev/null
+++ b/crates/plugins/tests/.spin-plugins/manifests/some-spin-ver-some-not/some-spin-ver-some-not@98.0.0.json
@@ -0,0 +1,27 @@
+{
+ "name": "some-spin-ver-some-not",
+ "description": "A plugin where only some versions work with the test harness version of Spin.",
+ "version": "98.0.0",
+ "spinCompatibility": ">=98.0",
+ "license": "Apache-2.0",
+ "packages": [
+ {
+ "os": "linux",
+ "arch": "amd64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ },
+ {
+ "os": "macos",
+ "arch": "aarch64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ },
+ {
+ "os": "macos",
+ "arch": "amd64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ }
+ ]
+}
diff --git a/crates/plugins/tests/.spin-plugins/manifests/some-spin-ver-some-not/some-spin-ver-some-not@98.1.0.json b/crates/plugins/tests/.spin-plugins/manifests/some-spin-ver-some-not/some-spin-ver-some-not@98.1.0.json
new file mode 100644
index 0000000000..1db8f90143
--- /dev/null
+++ b/crates/plugins/tests/.spin-plugins/manifests/some-spin-ver-some-not/some-spin-ver-some-not@98.1.0.json
@@ -0,0 +1,15 @@
+{
+ "name": "some-spin-ver-some-not",
+ "description": "A plugin where only some versions work with the test harness version of Spin.",
+ "version": "98.1.0",
+ "spinCompatibility": ">=98.0",
+ "license": "Apache-2.0",
+ "packages": [
+ {
+ "os": "windows",
+ "arch": "aarch64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ }
+ ]
+}
diff --git a/crates/plugins/tests/.spin-plugins/manifests/some-spin-ver-some-not/some-spin-ver-some-not@99.0.0.json b/crates/plugins/tests/.spin-plugins/manifests/some-spin-ver-some-not/some-spin-ver-some-not@99.0.0.json
new file mode 100644
index 0000000000..bf255be664
--- /dev/null
+++ b/crates/plugins/tests/.spin-plugins/manifests/some-spin-ver-some-not/some-spin-ver-some-not@99.0.0.json
@@ -0,0 +1,27 @@
+{
+ "name": "some-spin-ver-some-not",
+ "description": "A plugin where only some versions work with the test harness version of Spin.",
+ "version": "99.0.0",
+ "spinCompatibility": ">=99.0",
+ "license": "Apache-2.0",
+ "packages": [
+ {
+ "os": "linux",
+ "arch": "amd64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ },
+ {
+ "os": "macos",
+ "arch": "aarch64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ },
+ {
+ "os": "macos",
+ "arch": "amd64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ }
+ ]
+}
diff --git a/crates/plugins/tests/some-spin-ver-some-not/some-spin-ver-some-not.json b/crates/plugins/tests/some-spin-ver-some-not/some-spin-ver-some-not.json
new file mode 100644
index 0000000000..eafeb34c08
--- /dev/null
+++ b/crates/plugins/tests/some-spin-ver-some-not/some-spin-ver-some-not.json
@@ -0,0 +1,21 @@
+{
+ "name": "some-spin-ver-some-not",
+ "description": "A plugin where only some versions work with the test harness version of Spin.",
+ "version": "99.0.1",
+ "spinCompatibility": ">=99.0",
+ "license": "Apache-2.0",
+ "packages": [
+ {
+ "os": "linux",
+ "arch": "amd64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ },
+ {
+ "os": "macos",
+ "arch": "aarch64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ }
+ ]
+}
diff --git a/crates/plugins/tests/some-spin-ver-some-not/some-spin-ver-some-not@98.0.0.json b/crates/plugins/tests/some-spin-ver-some-not/some-spin-ver-some-not@98.0.0.json
new file mode 100644
index 0000000000..fb313522c9
--- /dev/null
+++ b/crates/plugins/tests/some-spin-ver-some-not/some-spin-ver-some-not@98.0.0.json
@@ -0,0 +1,21 @@
+{
+ "name": "some-spin-ver-some-not",
+ "description": "A plugin where only some versions work with the test harness version of Spin.",
+ "version": "98.0.0",
+ "spinCompatibility": ">=98.0",
+ "license": "Apache-2.0",
+ "packages": [
+ {
+ "os": "linux",
+ "arch": "amd64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ },
+ {
+ "os": "macos",
+ "arch": "aarch64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ }
+ ]
+}
diff --git a/crates/plugins/tests/some-spin-ver-some-not/some-spin-ver-some-not@98.1.0.json b/crates/plugins/tests/some-spin-ver-some-not/some-spin-ver-some-not@98.1.0.json
new file mode 100644
index 0000000000..1db8f90143
--- /dev/null
+++ b/crates/plugins/tests/some-spin-ver-some-not/some-spin-ver-some-not@98.1.0.json
@@ -0,0 +1,15 @@
+{
+ "name": "some-spin-ver-some-not",
+ "description": "A plugin where only some versions work with the test harness version of Spin.",
+ "version": "98.1.0",
+ "spinCompatibility": ">=98.0",
+ "license": "Apache-2.0",
+ "packages": [
+ {
+ "os": "windows",
+ "arch": "aarch64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ }
+ ]
+}
diff --git a/crates/plugins/tests/some-spin-ver-some-not/some-spin-ver-some-not@99.0.0.json b/crates/plugins/tests/some-spin-ver-some-not/some-spin-ver-some-not@99.0.0.json
new file mode 100644
index 0000000000..cf2bd99f90
--- /dev/null
+++ b/crates/plugins/tests/some-spin-ver-some-not/some-spin-ver-some-not@99.0.0.json
@@ -0,0 +1,21 @@
+{
+ "name": "some-spin-ver-some-not",
+ "description": "A plugin where only some versions work with the test harness version of Spin.",
+ "version": "99.0.0",
+ "spinCompatibility": ">=99.0",
+ "license": "Apache-2.0",
+ "packages": [
+ {
+ "os": "linux",
+ "arch": "amd64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ },
+ {
+ "os": "macos",
+ "arch": "aarch64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ }
+ ]
+}
diff --git a/crates/templates/src/test_built_ins/mod.rs b/crates/templates/src/test_built_ins/mod.rs
new file mode 100644
index 0000000000..8df9710678
--- /dev/null
+++ b/crates/templates/src/test_built_ins/mod.rs
@@ -0,0 +1,73 @@
+#![cfg(test)]
+
+// Module for unit-testing the built-in templates when a full e2e test would be overkill.
+// If your test involves invoking the Spin CLI, or builds or runs an application, use
+// an e2e test.
+
+use std::{collections::HashMap, path::PathBuf};
+
+use super::*;
+
+struct DiscardingReporter;
+
+impl ProgressReporter for DiscardingReporter {
+ fn report(&self, _: impl AsRef<str>) {}
+}
+
+#[tokio::test]
+async fn add_fileserver_does_not_create_dir() -> anyhow::Result<()> {
+ let built_ins_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..");
+ let built_ins_src = TemplateSource::File(built_ins_dir);
+
+ let store_dir = tempfile::tempdir()?;
+ let store = store::TemplateStore::new(store_dir.path());
+ let manager = TemplateManager::new(store);
+
+ manager
+ .install(
+ &built_ins_src,
+ &InstallOptions::default(),
+ &DiscardingReporter,
+ )
+ .await?;
+
+ let app_dir = tempfile::tempdir()?;
+
+ // Create an app to add the fileserver into
+ let new_empty_options = RunOptions {
+ variant: TemplateVariantInfo::NewApplication,
+ name: "add-fs-dir-test".to_owned(),
+ output_path: app_dir.path().to_owned(),
+ values: HashMap::new(),
+ accept_defaults: true,
+ };
+ manager
+ .get("http-empty")?
+ .expect("http-empty template should exist")
+ .run(new_empty_options)
+ .silent()
+ .await?;
+
+ // Add the fileserver to that app
+ let manifest_path = app_dir.path().join("spin.toml");
+ let add_fs_options = RunOptions {
+ variant: TemplateVariantInfo::AddComponent { manifest_path },
+ name: "fs".to_owned(),
+ output_path: app_dir.path().join("fs"),
+ values: HashMap::new(),
+ accept_defaults: true,
+ };
+ manager
+ .get("static-fileserver")?
+ .expect("static-fileserver template should exist")
+ .run(add_fs_options)
+ .silent()
+ .await?;
+
+ // Finally!
+ assert!(
+ !app_dir.path().join("fs").exists(),
+ "<app_dir>/fs should not have been created"
+ );
+ Ok(())
+}
diff --git a/sdk/go/integration_test.go b/sdk/go/integration_test.go
index 2ac2d2d36c..8887715917 100644
--- a/sdk/go/integration_test.go
+++ b/sdk/go/integration_test.go
@@ -17,14 +17,18 @@ const spinBinary = "../../target/debug/spin"
func retryGet(t *testing.T, url string) *http.Response {
t.Helper()
- const maxTries = 120 // (10min/5sec)
+ const maxTries = 600 // (10min)
for i := 1; i < maxTries; i++ {
+ // Catch call to `Fail` in other goroutine
+ if t.Failed() {
+ t.FailNow()
+ }
if res, err := http.Get(url); err != nil {
t.Log(err)
} else {
return res
}
- time.Sleep(5 * time.Second)
+ time.Sleep(1 * time.Second)
}
t.Fatal("Get request timeout: ", url)
return nil
@@ -50,6 +54,15 @@ func startSpin(t *testing.T, spinfile string) *testSpin {
t.Fatal(err)
}
+ go func() {
+ cmd.Wait()
+ if ctx.Err() == nil {
+ t.Log("spin exited before the test finished:", cmd.ProcessState)
+ t.Log("stderr:\n", stderr.String())
+ t.Fail()
+ }
+ }()
+
return &testSpin{
cancel: cancel,
url: fmt.Sprintf("http://%s", url),
diff --git a/tests/spinup_tests.rs b/tests/spinup_tests.rs
index f2920b8ab6..0cfa3121ea 100644
--- a/tests/spinup_tests.rs
+++ b/tests/spinup_tests.rs
@@ -89,8 +89,13 @@ mod spinup_tests {
}
#[tokio::test]
- async fn simple_spin_rust_works() {
- testcases::simple_spin_rust_works(CONTROLLER).await
+ async fn head_rust_sdk_http() {
+ testcases::head_rust_sdk_http(CONTROLLER).await
+ }
+
+ #[tokio::test]
+ async fn head_rust_sdk_redis() {
+ testcases::head_rust_sdk_redis(CONTROLLER).await
}
#[tokio::test]
diff --git a/tests/testcases/simple-spin-rust-test/.cargo/config.toml b/tests/testcases/head-rust-sdk-http/.cargo/config.toml
similarity index 100%
rename from tests/testcases/simple-spin-rust-test/.cargo/config.toml
rename to tests/testcases/head-rust-sdk-http/.cargo/config.toml
diff --git a/tests/testcases/simple-spin-rust-test/Cargo.toml b/tests/testcases/head-rust-sdk-http/Cargo.toml
similarity index 72%
rename from tests/testcases/simple-spin-rust-test/Cargo.toml
rename to tests/testcases/head-rust-sdk-http/Cargo.toml
index 10fa6db8ee..8f109a0041 100644
--- a/tests/testcases/simple-spin-rust-test/Cargo.toml
+++ b/tests/testcases/head-rust-sdk-http/Cargo.toml
@@ -1,5 +1,5 @@
[package]
-name = "simple-spin-rust-test"
+name = "head-rust-sdk-http"
version = "0.1.0"
edition = "2021"
@@ -17,7 +17,3 @@ http = "0.2"
spin-sdk = { path = "../../../sdk/rust" }
[workspace]
-
-# Metadata about this component.
-[package.metadata.component]
-name = "spinhelloworld"
diff --git a/tests/testcases/simple-spin-rust-test/assets/test.txt b/tests/testcases/head-rust-sdk-http/assets/test.txt
similarity index 100%
rename from tests/testcases/simple-spin-rust-test/assets/test.txt
rename to tests/testcases/head-rust-sdk-http/assets/test.txt
diff --git a/tests/testcases/simple-spin-rust-test/spin.toml b/tests/testcases/head-rust-sdk-http/spin.toml
similarity index 83%
rename from tests/testcases/simple-spin-rust-test/spin.toml
rename to tests/testcases/head-rust-sdk-http/spin.toml
index e8c070bc8a..f7de55301d 100644
--- a/tests/testcases/simple-spin-rust-test/spin.toml
+++ b/tests/testcases/head-rust-sdk-http/spin.toml
@@ -1,7 +1,7 @@
spin_version = "1"
authors = ["Fermyon Engineering <engineering@fermyon.com>"]
description = "A simple application that returns hello and goodbye."
-name = "simple-spin-rust-test"
+name = "head-rust-sdk-http"
trigger = {type = "http", base = "/test"}
version = "1.0.0"
@@ -10,7 +10,7 @@ object = { default = "teapot" }
[[component]]
id = "hello"
-source = "target/wasm32-wasi/release/simple_spin_rust_test.wasm"
+source = "target/wasm32-wasi/release/head_rust_sdk_http.wasm"
files = [ { source = "assets", destination = "/" } ]
[component.trigger]
route = "/hello/..."
diff --git a/tests/testcases/simple-spin-rust-test/src/lib.rs b/tests/testcases/head-rust-sdk-http/src/lib.rs
similarity index 100%
rename from tests/testcases/simple-spin-rust-test/src/lib.rs
rename to tests/testcases/head-rust-sdk-http/src/lib.rs
diff --git a/tests/testcases/head-rust-sdk-redis/.cargo/config.toml b/tests/testcases/head-rust-sdk-redis/.cargo/config.toml
new file mode 100644
index 0000000000..6b77899cb3
--- /dev/null
+++ b/tests/testcases/head-rust-sdk-redis/.cargo/config.toml
@@ -0,0 +1,2 @@
+[build]
+target = "wasm32-wasi"
diff --git a/tests/testcases/head-rust-sdk-redis/Cargo.toml b/tests/testcases/head-rust-sdk-redis/Cargo.toml
new file mode 100644
index 0000000000..3de29bf0e3
--- /dev/null
+++ b/tests/testcases/head-rust-sdk-redis/Cargo.toml
@@ -0,0 +1,15 @@
+[package]
+name = "head-rust-sdk-redis"
+version = "0.1.0"
+edition = "2021"
+
+[lib]
+crate-type = [ "cdylib" ]
+
+[dependencies]
+anyhow = "1"
+bytes = "1"
+http = "0.2"
+spin-sdk = { path = "../../../sdk/rust"}
+
+[workspace]
diff --git a/tests/testcases/head-rust-sdk-redis/spin.toml b/tests/testcases/head-rust-sdk-redis/spin.toml
new file mode 100644
index 0000000000..7a5a8bf1f3
--- /dev/null
+++ b/tests/testcases/head-rust-sdk-redis/spin.toml
@@ -0,0 +1,14 @@
+spin_version = "1"
+authors = ["Fermyon Engineering <engineering@fermyon.com>"]
+description = "A simple redis application that exercises the Rust SDK in the current branch"
+name = "head-rust-sdk-redis"
+trigger = {type = "redis", address = "redis://redis:6379"}
+version = "1.0.0"
+
+[[component]]
+id = "hello"
+source = "target/wasm32-wasi/release/head_rust_sdk_redis.wasm"
+[component.trigger]
+channel = "my-channel"
+[component.build]
+command = "cargo build --target wasm32-wasi --release"
diff --git a/tests/testcases/head-rust-sdk-redis/src/lib.rs b/tests/testcases/head-rust-sdk-redis/src/lib.rs
new file mode 100644
index 0000000000..f42dfc3fa7
--- /dev/null
+++ b/tests/testcases/head-rust-sdk-redis/src/lib.rs
@@ -0,0 +1,10 @@
+use spin_sdk::redis_component;
+
+#[redis_component]
+fn on_message(message: bytes::Bytes) -> anyhow::Result<()> {
+ println!(
+ "Got message: '{}'",
+ std::str::from_utf8(&*message).unwrap_or("<MESSAGE NOT UTF8>")
+ );
+ Ok(())
+}
diff --git a/tests/testcases/mod.rs b/tests/testcases/mod.rs
index dec01a4f96..b027192e25 100644
--- a/tests/testcases/mod.rs
+++ b/tests/testcases/mod.rs
@@ -665,7 +665,8 @@ pub async fn assets_routing_works(controller: &dyn Controller) {
tc.run(controller).await.unwrap()
}
-pub async fn simple_spin_rust_works(controller: &dyn Controller) {
+/// Test an http app using the current branch's version of the Rust SDK
+pub async fn head_rust_sdk_http(controller: &dyn Controller) {
async fn checks(
metadata: AppMetadata,
_: Option<Pin<Box<dyn AsyncBufRead>>>,
@@ -719,8 +720,42 @@ pub async fn simple_spin_rust_works(controller: &dyn Controller) {
}
let tc = TestCaseBuilder::default()
- .name("simple-spin-rust-test".to_string())
- .appname(Some("simple-spin-rust-test".to_string()))
+ .name("head-rust-sdk-http".to_string())
+ .appname(Some("head-rust-sdk-http".to_string()))
+ .assertions(
+ |metadata: AppMetadata,
+ stdout_stream: Option<Pin<Box<dyn AsyncBufRead>>>,
+ stderr_stream: Option<Pin<Box<dyn AsyncBufRead>>>| {
+ Box::pin(checks(metadata, stdout_stream, stderr_stream))
+ },
+ )
+ .build()
+ .unwrap();
+
+ tc.run(controller).await.unwrap()
+}
+
+/// Test a redis app using the current branch's version of the Rust SDK
+pub async fn head_rust_sdk_redis(controller: &dyn Controller) {
+ async fn checks(
+ _: AppMetadata,
+ _: Option<Pin<Box<dyn AsyncBufRead>>>,
+ stderr_stream: Option<Pin<Box<dyn AsyncBufRead>>>,
+ ) -> Result<()> {
+ wait_for_spin().await;
+ let stderr = get_output_stream(stderr_stream).await?;
+ anyhow::ensure!(
+ stderr.is_empty(),
+ "expected stderr to be empty, but it was not: {}",
+ stderr.join("\n")
+ );
+ Ok(())
+ }
+
+ let tc = TestCaseBuilder::default()
+ .name("head-rust-sdk-redis".to_string())
+ .appname(Some("head-rust-sdk-redis".to_string()))
+ .trigger_type("redis".to_string())
.assertions(
|metadata: AppMetadata,
stdout_stream: Option<Pin<Box<dyn AsyncBufRead>>>,
@@ -877,8 +912,7 @@ pub async fn redis_go_works(controller: &dyn Controller) {
_: Option<Pin<Box<dyn AsyncBufRead>>>,
stderr_stream: Option<Pin<Box<dyn AsyncBufRead>>>,
) -> Result<()> {
- //TODO: wait for spin up to be ready dynamically
- sleep(Duration::from_secs(10)).await;
+ wait_for_spin().await;
let output = utils::run(
&[
@@ -894,12 +928,13 @@ pub async fn redis_go_works(controller: &dyn Controller) {
)?;
utils::assert_success(&output);
- let stderr = utils::get_output_stream(stderr_stream, Duration::from_secs(5)).await?;
+ let stderr = get_output_stream(stderr_stream).await?;
let expected_logs = vec!["Payload::::", "msg-from-go-channel"];
assert!(expected_logs
.iter()
- .all(|item| stderr.contains(&item.to_string())));
+ .all(|item| stderr.contains(&item.to_string())),
+ "Expected log lines to contain all of {expected_logs:?} but actual lines were '{stderr:?}'");
Ok(())
}
@@ -933,8 +968,7 @@ pub async fn redis_rust_works(controller: &dyn Controller) {
_: Option<Pin<Box<dyn AsyncBufRead>>>,
stderr_stream: Option<Pin<Box<dyn AsyncBufRead>>>,
) -> Result<()> {
- //TODO: wait for spin up to be ready dynamically
- sleep(Duration::from_secs(20)).await;
+ wait_for_spin().await;
utils::run(
&[
@@ -949,13 +983,14 @@ pub async fn redis_rust_works(controller: &dyn Controller) {
None,
)?;
- let stderr = utils::get_output_stream(stderr_stream, Duration::from_secs(5)).await?;
+ let stderr = get_output_stream(stderr_stream).await?;
let expected_logs = vec!["msg-from-rust-channel"];
assert!(expected_logs
.iter()
- .all(|item| stderr.contains(&item.to_string())));
+ .all(|item| stderr.contains(&item.to_string())),
+ "Expected log lines to contain all of {expected_logs:?} but actual lines were '{stderr:?}'");
Ok(())
}
@@ -1205,3 +1240,14 @@ pub async fn error_messages(controller: &dyn Controller) {
tc.try_run(controller).await.unwrap();
}
+
+async fn get_output_stream(
+ stream: Option<Pin<Box<dyn AsyncBufRead>>>,
+) -> anyhow::Result<Vec<String>> {
+ utils::get_output_stream(stream, Duration::from_secs(5)).await
+}
+
+async fn wait_for_spin() {
+ //TODO: wait for spin up to be ready dynamically
+ sleep(Duration::from_secs(10)).await;
+}
|
35dcc921cee8a48d727e9036490da3e63d8dfcab
|
|
7f84a95bc842d8a23410c2b381594d7218f76f8f
|
outbound-http: Support "relative" URIs to current app
This has been requested a couple of times and should be _relatively_ straightforward:
- Add a field to `OutboundHttp` e.g. `origin: Uri` which gets updated from each inbound request
- If an outbound request starts with a `/` (has no scheme or authority), join with the origin
|
If the application has a `base`, should "relative" URLs be relativised to that base, or to the host? (The reference to "current app" makes me assume this is relative to the app base but I want to check!)
First, I'd like to get rid of `base` :sweat_smile:.
I'm not sure which would be less confusing. Magically prepending things to `/path` seems like it _might_ be more surprising, even if it is logical from "inside the app".
ref #957
|
2023-08-26T04:15:06Z
|
fermyon__spin-1710
|
fermyon/spin
|
3.2
|
diff --git a/Cargo.lock b/Cargo.lock
index 4ac146655d..a6584ae786 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5311,6 +5311,7 @@ dependencies = [
"hyper",
"indexmap",
"num_cpus",
+ "outbound-http",
"percent-encoding",
"rustls-pemfile 0.3.0",
"serde",
diff --git a/crates/outbound-http/src/allowed_http_hosts.rs b/crates/outbound-http/src/allowed_http_hosts.rs
index 4378ac1cdd..18604190d1 100644
--- a/crates/outbound-http/src/allowed_http_hosts.rs
+++ b/crates/outbound-http/src/allowed_http_hosts.rs
@@ -26,6 +26,13 @@ impl AllowedHttpHosts {
Self::AllowSpecific(hosts) => hosts.iter().any(|h| h.allow(url)),
}
}
+
+ pub fn allow_relative_url(&self) -> bool {
+ match self {
+ Self::AllowAll => true,
+ Self::AllowSpecific(hosts) => hosts.contains(&AllowedHttpHost::host("self")),
+ }
+ }
}
/// An HTTP host allow-list entry.
@@ -214,6 +221,14 @@ mod test {
);
}
+ #[test]
+ fn test_allowed_hosts_accepts_self() {
+ assert_eq!(
+ AllowedHttpHost::host("self"),
+ parse_allowed_http_host("self").unwrap()
+ );
+ }
+
#[test]
fn test_allowed_hosts_accepts_localhost_addresses() {
assert_eq!(
@@ -303,4 +318,18 @@ mod test {
assert!(!allowed.allow(&Url::parse("http://example.com/").unwrap()));
assert!(!allowed.allow(&Url::parse("http://google.com/").unwrap()));
}
+
+ #[test]
+ fn test_allowed_hosts_allow_relative_url() {
+ let allowed =
+ parse_allowed_http_hosts(&to_vec_owned(&["self", "http://example.com:8383"])).unwrap();
+ assert!(allowed.allow_relative_url());
+
+ let not_allowed =
+ parse_allowed_http_hosts(&to_vec_owned(&["http://example.com:8383"])).unwrap();
+ assert!(!not_allowed.allow_relative_url());
+
+ let allow_all = parse_allowed_http_hosts(&to_vec_owned(&["insecure:allow-all"])).unwrap();
+ assert!(allow_all.allow_relative_url());
+ }
}
diff --git a/crates/outbound-http/src/lib.rs b/crates/outbound-http/src/lib.rs
index cafde2c310..f24e2a27f9 100644
--- a/crates/outbound-http/src/lib.rs
+++ b/crates/outbound-http/src/lib.rs
@@ -21,15 +21,23 @@ pub const ALLOWED_HTTP_HOSTS_KEY: MetadataKey<Vec<String>> = MetadataKey::new("a
pub struct OutboundHttp {
/// List of hosts guest modules are allowed to make requests to.
pub allowed_hosts: AllowedHttpHosts,
+ /// During an incoming HTTP request, origin is set to the host of that incoming HTTP request.
+ /// This is used to direct outbound requests to the same host when allowed.
+ pub origin: String,
client: Option<Client>,
}
impl OutboundHttp {
/// Check if guest module is allowed to send request to URL, based on the list of
- /// allowed hosts defined by the runtime. If the list of allowed hosts contains
+ /// allowed hosts defined by the runtime. If the url passed in is a relative path,
+ /// only allow if allowed_hosts contains `self`. If the list of allowed hosts contains
/// `insecure:allow-all`, then all hosts are allowed.
/// If `None` is passed, the guest module is not allowed to send the request.
- fn is_allowed(&self, url: &str) -> Result<bool, HttpError> {
+ fn is_allowed(&mut self, url: &str) -> Result<bool, HttpError> {
+ if url.starts_with('/') {
+ return Ok(self.allowed_hosts.allow_relative_url());
+ }
+
let url = Url::parse(url).map_err(|_| HttpError::InvalidUrl)?;
Ok(self.allowed_hosts.allow(&url))
}
@@ -49,7 +57,15 @@ impl outbound_http::Host for OutboundHttp {
}
let method = method_from(req.method);
- let url = Url::parse(&req.uri).map_err(|_| HttpError::InvalidUrl)?;
+
+ let abs_url = if req.uri.starts_with('/') {
+ format!("{}{}", self.origin, req.uri)
+ } else {
+ req.uri.clone()
+ };
+
+ let req_url = Url::parse(&abs_url).map_err(|_| HttpError::InvalidUrl)?;
+
let headers = request_headers(req.headers).map_err(|_| HttpError::RuntimeError)?;
let body = req.body.unwrap_or_default().to_vec();
@@ -62,7 +78,7 @@ impl outbound_http::Host for OutboundHttp {
let client = self.client.get_or_insert_with(Default::default);
let resp = client
- .request(method, url)
+ .request(method, req_url)
.headers(headers)
.body(body)
.send()
diff --git a/crates/trigger-http/Cargo.toml b/crates/trigger-http/Cargo.toml
index 4e9c450338..0d3342f248 100644
--- a/crates/trigger-http/Cargo.toml
+++ b/crates/trigger-http/Cargo.toml
@@ -16,6 +16,7 @@ futures-util = "0.3.8"
http = "0.2"
hyper = { version = "0.14", features = ["full"] }
indexmap = "1"
+outbound-http = { path = "../outbound-http" }
percent-encoding = "2"
rustls-pemfile = "0.3.0"
serde = { version = "1.0", features = ["derive"] }
diff --git a/crates/trigger-http/src/spin.rs b/crates/trigger-http/src/spin.rs
index 598cf4540b..a3d9054480 100644
--- a/crates/trigger-http/src/spin.rs
+++ b/crates/trigger-http/src/spin.rs
@@ -4,9 +4,11 @@ use crate::{HttpExecutor, HttpTrigger, Store};
use anyhow::{anyhow, Result};
use async_trait::async_trait;
use hyper::{Body, Request, Response};
+use outbound_http::OutboundHttpComponent;
use spin_core::Instance;
use spin_trigger::{EitherInstance, TriggerAppEngine};
use spin_world::http_types;
+use std::sync::Arc;
#[derive(Clone)]
pub struct SpinHttpExecutor;
@@ -27,11 +29,13 @@ impl HttpExecutor for SpinHttpExecutor {
component_id
);
- let (instance, store) = engine.prepare_instance(component_id).await?;
+ let (instance, mut store) = engine.prepare_instance(component_id).await?;
let EitherInstance::Component(instance) = instance else {
unreachable!()
};
+ set_http_origin_from_request(&mut store, engine, &req);
+
let resp = Self::execute_impl(store, instance, base, raw_route, req, client_addr)
.await
.map_err(contextualise_err)?;
@@ -182,6 +186,27 @@ impl SpinHttpExecutor {
}
}
+fn set_http_origin_from_request(
+ store: &mut Store,
+ engine: &TriggerAppEngine<HttpTrigger>,
+ req: &Request<Body>,
+) {
+ if let Some(authority) = req.uri().authority() {
+ if let Some(scheme) = req.uri().scheme_str() {
+ if let Some(outbound_http_handle) = engine
+ .engine
+ .find_host_component_handle::<Arc<OutboundHttpComponent>>()
+ {
+ let mut outbound_http_data = store
+ .host_components_data()
+ .get_or_insert(outbound_http_handle);
+
+ outbound_http_data.origin = format!("{}://{}", scheme, authority);
+ }
+ }
+ }
+}
+
fn contextualise_err(e: anyhow::Error) -> anyhow::Error {
if e.to_string()
.contains("failed to find function export `canonical_abi_free`")
diff --git a/examples/http-rust-outbound-http/Cargo.lock b/examples/http-rust-outbound-http/Cargo.lock
deleted file mode 100644
index ad74e02424..0000000000
--- a/examples/http-rust-outbound-http/Cargo.lock
+++ /dev/null
@@ -1,504 +0,0 @@
-# This file is automatically @generated by Cargo.
-# It is not intended for manual editing.
-version = 3
-
-[[package]]
-name = "anyhow"
-version = "1.0.71"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9c7d0618f0e0b7e8ff11427422b64564d5fb0be1940354bfe2e0529b18a9d9b8"
-
-[[package]]
-name = "autocfg"
-version = "1.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
-
-[[package]]
-name = "bitflags"
-version = "1.3.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
-
-[[package]]
-name = "bitflags"
-version = "2.3.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6dbe3c979c178231552ecba20214a8272df4e09f232a87aef4320cf06539aded"
-
-[[package]]
-name = "bytes"
-version = "1.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c4872d67bab6358e59559027aa3b9157c53d9358c51423c17554809a8858e0f8"
-
-[[package]]
-name = "fnv"
-version = "1.0.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
-
-[[package]]
-name = "form_urlencoded"
-version = "1.0.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5fc25a87fa4fd2094bffb06925852034d90a17f0d1e05197d4956d3555752191"
-dependencies = [
- "matches",
- "percent-encoding",
-]
-
-[[package]]
-name = "hashbrown"
-version = "0.12.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
-
-[[package]]
-name = "heck"
-version = "0.4.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
-dependencies = [
- "unicode-segmentation",
-]
-
-[[package]]
-name = "http"
-version = "0.2.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ff8670570af52249509a86f5e3e18a08c60b177071826898fde8997cf5f6bfbb"
-dependencies = [
- "bytes",
- "fnv",
- "itoa",
-]
-
-[[package]]
-name = "http-rust-outbound-http"
-version = "0.1.0"
-dependencies = [
- "anyhow",
- "bytes",
- "http",
- "spin-sdk",
-]
-
-[[package]]
-name = "id-arena"
-version = "2.2.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "25a2bc672d1148e28034f176e01fffebb08b35768468cc954630da77a1449005"
-
-[[package]]
-name = "idna"
-version = "0.2.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "418a0a6fab821475f634efe3ccc45c013f742efe03d853e8d3355d5cb850ecf8"
-dependencies = [
- "matches",
- "unicode-bidi",
- "unicode-normalization",
-]
-
-[[package]]
-name = "indexmap"
-version = "1.9.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99"
-dependencies = [
- "autocfg",
- "hashbrown",
- "serde",
-]
-
-[[package]]
-name = "itoa"
-version = "1.0.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1aab8fc367588b89dcee83ab0fd66b72b50b72fa1904d7095045ace2b0c81c35"
-
-[[package]]
-name = "leb128"
-version = "0.2.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "884e2677b40cc8c339eaefcb701c32ef1fd2493d71118dc0ca4b6a736c93bd67"
-
-[[package]]
-name = "log"
-version = "0.4.19"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b06a4cde4c0f271a446782e3eff8de789548ce57dbc8eca9292c27f4a42004b4"
-
-[[package]]
-name = "matches"
-version = "0.1.9"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a3e378b66a060d48947b590737b30a1be76706c8dd7b8ba0f2fe3989c68a853f"
-
-[[package]]
-name = "memchr"
-version = "2.5.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d"
-
-[[package]]
-name = "percent-encoding"
-version = "2.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d4fd5641d01c8f18a23da7b6fe29298ff4b55afcccdf78973b24cf3175fee32e"
-
-[[package]]
-name = "proc-macro2"
-version = "1.0.60"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dec2b086b7a862cf4de201096214fa870344cf922b2b30c167badb3af3195406"
-dependencies = [
- "unicode-ident",
-]
-
-[[package]]
-name = "pulldown-cmark"
-version = "0.8.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ffade02495f22453cd593159ea2f59827aae7f53fa8323f756799b670881dcf8"
-dependencies = [
- "bitflags 1.3.2",
- "memchr",
- "unicase",
-]
-
-[[package]]
-name = "quote"
-version = "1.0.28"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1b9ab9c7eadfd8df19006f1cf1a4aed13540ed5cbc047010ece5826e10825488"
-dependencies = [
- "proc-macro2",
-]
-
-[[package]]
-name = "routefinder"
-version = "0.5.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "94f8f99b10dedd317514253dda1fa7c14e344aac96e1f78149a64879ce282aca"
-dependencies = [
- "smartcow",
- "smartstring",
-]
-
-[[package]]
-name = "semver"
-version = "1.0.17"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bebd363326d05ec3e2f532ab7660680f3b02130d780c299bca73469d521bc0ed"
-
-[[package]]
-name = "serde"
-version = "1.0.164"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9e8c8cf938e98f769bc164923b06dce91cea1751522f46f8466461af04c9027d"
-dependencies = [
- "serde_derive",
-]
-
-[[package]]
-name = "serde_derive"
-version = "1.0.164"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d9735b638ccc51c28bf6914d90a2e9725b377144fc612c49a611fddd1b631d68"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 2.0.18",
-]
-
-[[package]]
-name = "smartcow"
-version = "0.2.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "656fcb1c1fca8c4655372134ce87d8afdf5ec5949ebabe8d314be0141d8b5da2"
-dependencies = [
- "smartstring",
-]
-
-[[package]]
-name = "smartstring"
-version = "1.0.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3fb72c633efbaa2dd666986505016c32c3044395ceaf881518399d2f4127ee29"
-dependencies = [
- "autocfg",
- "static_assertions",
- "version_check",
-]
-
-[[package]]
-name = "spin-macro"
-version = "0.1.0"
-dependencies = [
- "anyhow",
- "bytes",
- "http",
- "proc-macro2",
- "quote",
- "syn 1.0.92",
-]
-
-[[package]]
-name = "spin-sdk"
-version = "1.4.0-pre0"
-dependencies = [
- "anyhow",
- "bytes",
- "form_urlencoded",
- "http",
- "routefinder",
- "spin-macro",
- "thiserror",
- "wit-bindgen",
-]
-
-[[package]]
-name = "static_assertions"
-version = "1.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
-
-[[package]]
-name = "syn"
-version = "1.0.92"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7ff7c592601f11445996a06f8ad0c27f094a58857c2f89e97974ab9235b92c52"
-dependencies = [
- "proc-macro2",
- "quote",
- "unicode-xid",
-]
-
-[[package]]
-name = "syn"
-version = "2.0.18"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "32d41677bcbe24c20c52e7c70b0d8db04134c5d1066bf98662e2871ad200ea3e"
-dependencies = [
- "proc-macro2",
- "quote",
- "unicode-ident",
-]
-
-[[package]]
-name = "thiserror"
-version = "1.0.37"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "10deb33631e3c9018b9baf9dcbbc4f737320d2b576bac10f6aefa048fa407e3e"
-dependencies = [
- "thiserror-impl",
-]
-
-[[package]]
-name = "thiserror-impl"
-version = "1.0.37"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "982d17546b47146b28f7c22e3d08465f6b8903d0ea13c1660d9d84a6e7adcdbb"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 1.0.92",
-]
-
-[[package]]
-name = "tinyvec"
-version = "1.6.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50"
-dependencies = [
- "tinyvec_macros",
-]
-
-[[package]]
-name = "tinyvec_macros"
-version = "0.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c"
-
-[[package]]
-name = "unicase"
-version = "2.6.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "50f37be617794602aabbeee0be4f259dc1778fabe05e2d67ee8f79326d5cb4f6"
-dependencies = [
- "version_check",
-]
-
-[[package]]
-name = "unicode-bidi"
-version = "0.3.13"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "92888ba5573ff080736b3648696b70cafad7d250551175acbaa4e0385b3e1460"
-
-[[package]]
-name = "unicode-ident"
-version = "1.0.9"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b15811caf2415fb889178633e7724bad2509101cde276048e013b9def5e51fa0"
-
-[[package]]
-name = "unicode-normalization"
-version = "0.1.19"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d54590932941a9e9266f0832deed84ebe1bf2e4c9e4a3554d393d18f5e854bf9"
-dependencies = [
- "tinyvec",
-]
-
-[[package]]
-name = "unicode-segmentation"
-version = "1.9.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7e8820f5d777f6224dc4be3632222971ac30164d4a258d595640799554ebfd99"
-
-[[package]]
-name = "unicode-xid"
-version = "0.2.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3"
-
-[[package]]
-name = "url"
-version = "2.3.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "22fe195a4f217c25b25cb5058ced57059824a678474874038dc88d211bf508d3"
-dependencies = [
- "form_urlencoded",
- "idna",
- "percent-encoding",
-]
-
-[[package]]
-name = "version_check"
-version = "0.9.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
-
-[[package]]
-name = "wasm-encoder"
-version = "0.29.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "18c41dbd92eaebf3612a39be316540b8377c871cb9bde6b064af962984912881"
-dependencies = [
- "leb128",
-]
-
-[[package]]
-name = "wasm-metadata"
-version = "0.8.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "36e5156581ff4a302405c44ca7c85347563ca431d15f1a773f12c9c7b9a6cdc9"
-dependencies = [
- "anyhow",
- "indexmap",
- "serde",
- "wasm-encoder",
- "wasmparser",
-]
-
-[[package]]
-name = "wasmparser"
-version = "0.107.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "29e3ac9b780c7dda0cac7a52a5d6d2d6707cc6e3451c9db209b6c758f40d7acb"
-dependencies = [
- "indexmap",
- "semver",
-]
-
-[[package]]
-name = "wit-bindgen"
-version = "0.8.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "392d16e9e46cc7ca98125bc288dd5e4db469efe8323d3e0dac815ca7f2398522"
-dependencies = [
- "bitflags 2.3.2",
- "wit-bindgen-rust-macro",
-]
-
-[[package]]
-name = "wit-bindgen-core"
-version = "0.8.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d422d36cbd78caa0e18c3371628447807c66ee72466b69865ea7e33682598158"
-dependencies = [
- "anyhow",
- "wit-component",
- "wit-parser",
-]
-
-[[package]]
-name = "wit-bindgen-rust"
-version = "0.8.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9b76db68264f5d2089dc4652581236d8e75c5b89338de6187716215fd0e68ba3"
-dependencies = [
- "heck",
- "wasm-metadata",
- "wit-bindgen-core",
- "wit-bindgen-rust-lib",
- "wit-component",
-]
-
-[[package]]
-name = "wit-bindgen-rust-lib"
-version = "0.8.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1c50f334bc08b0903a43387f6eea6ef6aa9eb2a085729f1677b29992ecef20ba"
-dependencies = [
- "heck",
- "wit-bindgen-core",
-]
-
-[[package]]
-name = "wit-bindgen-rust-macro"
-version = "0.8.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ced38a5e174940c6a41ae587babeadfd2e2c2dc32f3b6488bcdca0e8922cf3f3"
-dependencies = [
- "anyhow",
- "proc-macro2",
- "syn 2.0.18",
- "wit-bindgen-core",
- "wit-bindgen-rust",
- "wit-component",
-]
-
-[[package]]
-name = "wit-component"
-version = "0.11.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7cbd4c7f8f400327c482c88571f373844b7889e61460650d650fc5881bb3575c"
-dependencies = [
- "anyhow",
- "bitflags 1.3.2",
- "indexmap",
- "log",
- "wasm-encoder",
- "wasm-metadata",
- "wasmparser",
- "wit-parser",
-]
-
-[[package]]
-name = "wit-parser"
-version = "0.8.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6daec9f093dbaea0e94043eeb92ece327bbbe70c86b1f41aca9bbfefd7f050f0"
-dependencies = [
- "anyhow",
- "id-arena",
- "indexmap",
- "log",
- "pulldown-cmark",
- "semver",
- "unicode-xid",
- "url",
-]
diff --git a/examples/http-rust-outbound-http/http-hello/.cargo/config.toml b/examples/http-rust-outbound-http/http-hello/.cargo/config.toml
new file mode 100644
index 0000000000..6b77899cb3
--- /dev/null
+++ b/examples/http-rust-outbound-http/http-hello/.cargo/config.toml
@@ -0,0 +1,2 @@
+[build]
+target = "wasm32-wasi"
diff --git a/examples/http-rust-outbound-http/http-hello/.gitignore b/examples/http-rust-outbound-http/http-hello/.gitignore
new file mode 100644
index 0000000000..2f7896d1d1
--- /dev/null
+++ b/examples/http-rust-outbound-http/http-hello/.gitignore
@@ -0,0 +1,1 @@
+target/
diff --git a/examples/http-rust-outbound-http/http-hello/Cargo.toml b/examples/http-rust-outbound-http/http-hello/Cargo.toml
new file mode 100644
index 0000000000..7db45bda22
--- /dev/null
+++ b/examples/http-rust-outbound-http/http-hello/Cargo.toml
@@ -0,0 +1,18 @@
+[package]
+name = "http-hello"
+version = "0.1.0"
+edition = "2021"
+
+[lib]
+crate-type = ["cdylib"]
+
+[dependencies]
+# Useful crate to handle errors.
+anyhow = "1"
+# Crate to simplify working with bytes.
+bytes = "1"
+# General-purpose crate with common HTTP types.
+http = "0.2"
+# The Spin SDK.
+spin-sdk = { path = "../../../sdk/rust" }
+[workspace]
diff --git a/examples/http-rust-outbound-http/http-hello/src/lib.rs b/examples/http-rust-outbound-http/http-hello/src/lib.rs
new file mode 100644
index 0000000000..ff2cc7c880
--- /dev/null
+++ b/examples/http-rust-outbound-http/http-hello/src/lib.rs
@@ -0,0 +1,14 @@
+use anyhow::Result;
+use spin_sdk::{
+ http::{Request, Response},
+ http_component,
+};
+
+/// A simple Spin HTTP component.
+#[http_component]
+fn hello_world(_req: Request) -> Result<Response> {
+ Ok(http::Response::builder()
+ .status(200)
+ .header("foo", "bar")
+ .body(Some("Hello, Fermyon!\n".into()))?)
+}
diff --git a/examples/http-rust-outbound-http/.cargo/config.toml b/examples/http-rust-outbound-http/outbound-http-to-same-app/.cargo/config.toml
similarity index 100%
rename from examples/http-rust-outbound-http/.cargo/config.toml
rename to examples/http-rust-outbound-http/outbound-http-to-same-app/.cargo/config.toml
diff --git a/examples/http-rust-outbound-http/outbound-http-to-same-app/Cargo.toml b/examples/http-rust-outbound-http/outbound-http-to-same-app/Cargo.toml
new file mode 100644
index 0000000000..665de8b45c
--- /dev/null
+++ b/examples/http-rust-outbound-http/outbound-http-to-same-app/Cargo.toml
@@ -0,0 +1,19 @@
+[package]
+name = "outbound-http-to-same-app"
+version = "0.1.0"
+edition = "2021"
+
+[lib]
+crate-type = ["cdylib"]
+
+[dependencies]
+# Useful crate to handle errors.
+anyhow = "1"
+# Crate to simplify working with bytes.
+bytes = "1"
+# General-purpose crate with common HTTP types.
+http = "0.2"
+# The Spin SDK.
+spin-sdk = { path = "../../../sdk/rust" }
+url = "2"
+[workspace]
diff --git a/examples/http-rust-outbound-http/outbound-http-to-same-app/src/lib.rs b/examples/http-rust-outbound-http/outbound-http-to-same-app/src/lib.rs
new file mode 100644
index 0000000000..2a809a3ccc
--- /dev/null
+++ b/examples/http-rust-outbound-http/outbound-http-to-same-app/src/lib.rs
@@ -0,0 +1,21 @@
+use anyhow::Result;
+use spin_sdk::{
+ http::{Request, Response},
+ http_component,
+};
+
+/// Send an HTTP request and return the response.
+#[http_component]
+fn send_outbound(_req: Request) -> Result<Response> {
+ let mut res = spin_sdk::outbound_http::send_request(
+ http::Request::builder()
+ .method("GET")
+ .uri("/hello") // relative routes are not yet supported in cloud
+ .body(None)
+ .unwrap(),
+ )?;
+ res.headers_mut()
+ .insert("spin-component", "rust-outbound-http".try_into()?);
+ println!("{:?}", res);
+ Ok(res)
+}
diff --git a/examples/http-rust-outbound-http/outbound-http/.cargo/config.toml b/examples/http-rust-outbound-http/outbound-http/.cargo/config.toml
new file mode 100644
index 0000000000..6b77899cb3
--- /dev/null
+++ b/examples/http-rust-outbound-http/outbound-http/.cargo/config.toml
@@ -0,0 +1,2 @@
+[build]
+target = "wasm32-wasi"
diff --git a/examples/http-rust-outbound-http/Cargo.toml b/examples/http-rust-outbound-http/outbound-http/Cargo.toml
similarity index 77%
rename from examples/http-rust-outbound-http/Cargo.toml
rename to examples/http-rust-outbound-http/outbound-http/Cargo.toml
index 5e29a4f20c..28a9232eb5 100644
--- a/examples/http-rust-outbound-http/Cargo.toml
+++ b/examples/http-rust-outbound-http/outbound-http/Cargo.toml
@@ -4,7 +4,7 @@ version = "0.1.0"
edition = "2021"
[lib]
-crate-type = [ "cdylib" ]
+crate-type = ["cdylib"]
[dependencies]
# Useful crate to handle errors.
@@ -14,5 +14,6 @@ bytes = "1"
# General-purpose crate with common HTTP types.
http = "0.2"
# The Spin SDK.
-spin-sdk = { path = "../../sdk/rust" }
-[workspace]
\ No newline at end of file
+spin-sdk = { path = "../../../sdk/rust" }
+
+[workspace]
diff --git a/examples/http-rust-outbound-http/src/lib.rs b/examples/http-rust-outbound-http/outbound-http/src/lib.rs
similarity index 100%
rename from examples/http-rust-outbound-http/src/lib.rs
rename to examples/http-rust-outbound-http/outbound-http/src/lib.rs
diff --git a/examples/http-rust-outbound-http/spin.toml b/examples/http-rust-outbound-http/spin.toml
index 67c0c4e975..efa11da228 100644
--- a/examples/http-rust-outbound-http/spin.toml
+++ b/examples/http-rust-outbound-http/spin.toml
@@ -1,24 +1,48 @@
spin_manifest_version = "1"
authors = ["Fermyon Engineering <engineering@fermyon.com>"]
-description = "A simple application that makes an outbound http call."
+description = "Demonstrates outbound HTTP calls"
name = "spin-outbound-http"
trigger = { type = "http", base = "/" }
version = "1.0.0"
[[component]]
-id = "rust-outbound-http"
-source = "target/wasm32-wasi/release/http_rust_outbound_http.wasm"
+id = "outbound-http"
+source = "outbound-http/target/wasm32-wasi/release/http_rust_outbound_http.wasm"
allowed_http_hosts = ["https://random-data-api.fermyon.app"]
[component.trigger]
route = "/outbound"
[component.build]
+workdir = "outbound-http"
command = "cargo build --target wasm32-wasi --release"
[[component]]
-id = "rust-outbound-http-wildcard"
-source = "target/wasm32-wasi/release/http_rust_outbound_http.wasm"
+id = "outbound-http-wildcard"
+source = "outbound-http/target/wasm32-wasi/release/http_rust_outbound_http.wasm"
allowed_http_hosts = ["insecure:allow-all"]
[component.trigger]
route = "/wildcard"
[component.build]
+workdir = "outbound-http"
+command = "cargo build --target wasm32-wasi --release"
+
+[[component]]
+id = "outbound-http-to-same-app"
+source = "outbound-http-to-same-app/target/wasm32-wasi/release/outbound_http_to_same_app.wasm"
+# To make outbound calls to components in the same Spin app, use the special value self.
+# This is not yet supported in cloud.
+allowed_http_hosts = ["self"]
+[component.trigger]
+route = "/outbound-to-hello-component"
+[component.build]
+workdir = "outbound-http-to-same-app"
+command = "cargo build --target wasm32-wasi --release"
+
+[[component]]
+id = "hello-component"
+source = "http-hello/target/wasm32-wasi/release/http_hello.wasm"
+description = "A simple component that returns hello."
+[component.trigger]
+route = "/hello"
+[component.build]
+workdir = "http-hello"
command = "cargo build --target wasm32-wasi --release"
diff --git a/examples/http-tinygo-outbound-http/outbound-http-to-same-app/go.mod b/examples/http-tinygo-outbound-http/outbound-http-to-same-app/go.mod
new file mode 100644
index 0000000000..296ca67dbe
--- /dev/null
+++ b/examples/http-tinygo-outbound-http/outbound-http-to-same-app/go.mod
@@ -0,0 +1,9 @@
+module outbound-http-to-same-app
+
+go 1.17
+
+require github.com/fermyon/spin/sdk/go v0.0.0
+
+require github.com/julienschmidt/httprouter v1.3.0 // indirect
+
+replace github.com/fermyon/spin/sdk/go v0.0.0 => ../../../sdk/go/
diff --git a/examples/http-tinygo-outbound-http/go.sum b/examples/http-tinygo-outbound-http/outbound-http-to-same-app/go.sum
similarity index 100%
rename from examples/http-tinygo-outbound-http/go.sum
rename to examples/http-tinygo-outbound-http/outbound-http-to-same-app/go.sum
diff --git a/examples/http-tinygo-outbound-http/outbound-http-to-same-app/main.go b/examples/http-tinygo-outbound-http/outbound-http-to-same-app/main.go
new file mode 100644
index 0000000000..009df6921a
--- /dev/null
+++ b/examples/http-tinygo-outbound-http/outbound-http-to-same-app/main.go
@@ -0,0 +1,26 @@
+package main
+
+import (
+ "fmt"
+ "net/http"
+
+ spinhttp "github.com/fermyon/spin/sdk/go/http"
+)
+
+func init() {
+ spinhttp.Handle(func(w http.ResponseWriter, r *http.Request) {
+ // Because we included self in `allowed_http_hosts`, we can make outbound
+ // HTTP requests to our own app using a relative path.
+ // This is not yet supported in cloud.
+ resp, err := spinhttp.Get("/hello")
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ fmt.Fprintln(w, resp.Body)
+ fmt.Fprintln(w, resp.Header.Get("content-type"))
+ })
+}
+
+func main() {}
diff --git a/examples/http-tinygo-outbound-http/spin.toml b/examples/http-tinygo-outbound-http/spin.toml
index d8a37a9461..ab01306c22 100644
--- a/examples/http-tinygo-outbound-http/spin.toml
+++ b/examples/http-tinygo-outbound-http/spin.toml
@@ -7,9 +7,25 @@ version = "1.0.0"
[[component]]
id = "tinygo-hello"
-source = "main.wasm"
-allowed_http_hosts = ["https://random-data-api.fermyon.app", "https://postman-echo.com"]
+source = "tinygo-hello/main.wasm"
+allowed_http_hosts = [
+ "https://random-data-api.fermyon.app",
+ "https://postman-echo.com",
+]
[component.trigger]
route = "/hello"
[component.build]
+workdir = "tinygo-hello"
+command = "tinygo build -target=wasi -gc=leaking -no-debug -o main.wasm main.go"
+
+[[component]]
+id = "outbound-http-to-same-app"
+source = "outbound-http-to-same-app/main.wasm"
+# Use self to make outbound requests to components in the same Spin application.
+# `self` is not yet supported in cloud
+allowed_http_hosts = ["self"]
+[component.trigger]
+route = "/outbound-http-to-same-app"
+[component.build]
+workdir = "outbound-http-to-same-app"
command = "tinygo build -target=wasi -gc=leaking -no-debug -o main.wasm main.go"
diff --git a/examples/http-tinygo-outbound-http/go.mod b/examples/http-tinygo-outbound-http/tinygo-hello/go.mod
similarity index 74%
rename from examples/http-tinygo-outbound-http/go.mod
rename to examples/http-tinygo-outbound-http/tinygo-hello/go.mod
index 2c1b9e24bf..92fbf0342d 100644
--- a/examples/http-tinygo-outbound-http/go.mod
+++ b/examples/http-tinygo-outbound-http/tinygo-hello/go.mod
@@ -6,4 +6,4 @@ require github.com/fermyon/spin/sdk/go v0.0.0
require github.com/julienschmidt/httprouter v1.3.0 // indirect
-replace github.com/fermyon/spin/sdk/go v0.0.0 => ../../sdk/go/
+replace github.com/fermyon/spin/sdk/go v0.0.0 => ../../../sdk/go/
diff --git a/examples/http-tinygo-outbound-http/tinygo-hello/go.sum b/examples/http-tinygo-outbound-http/tinygo-hello/go.sum
new file mode 100644
index 0000000000..096c54e630
--- /dev/null
+++ b/examples/http-tinygo-outbound-http/tinygo-hello/go.sum
@@ -0,0 +1,2 @@
+github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U=
+github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
diff --git a/examples/http-tinygo-outbound-http/main.go b/examples/http-tinygo-outbound-http/tinygo-hello/main.go
similarity index 100%
rename from examples/http-tinygo-outbound-http/main.go
rename to examples/http-tinygo-outbound-http/tinygo-hello/main.go
| 1,710
|
[
"1533"
] |
diff --git a/tests/spinup_tests.rs b/tests/spinup_tests.rs
index 0cfa3121ea..5de715d3d0 100644
--- a/tests/spinup_tests.rs
+++ b/tests/spinup_tests.rs
@@ -7,6 +7,11 @@ mod spinup_tests {
use {e2e_testing::controller::Controller, e2e_testing::spin_controller::SpinUp};
const CONTROLLER: &dyn Controller = &SpinUp {};
+ #[tokio::test]
+ async fn component_outbound_http_works() {
+ testcases::component_outbound_http_works(CONTROLLER).await
+ }
+
#[tokio::test]
async fn config_variables_default_works() {
testcases::config_variables_default_works(CONTROLLER).await
diff --git a/tests/testcases/mod.rs b/tests/testcases/mod.rs
index b027192e25..7cd663e841 100644
--- a/tests/testcases/mod.rs
+++ b/tests/testcases/mod.rs
@@ -14,6 +14,53 @@ fn get_url(base: &str, path: &str) -> String {
format!("{}{}", base, path)
}
+pub async fn component_outbound_http_works(controller: &dyn Controller) {
+ async fn checks(
+ metadata: AppMetadata,
+ _: Option<Pin<Box<dyn AsyncBufRead>>>,
+ _: Option<Pin<Box<dyn AsyncBufRead>>>,
+ ) -> Result<()> {
+ assert_http_response(
+ get_url(metadata.base.as_str(), "/test/outbound-allowed").as_str(),
+ Method::GET,
+ "",
+ 200,
+ &[],
+ Some("Hello, Fermyon!\n"),
+ )
+ .await?;
+
+ assert_http_response(
+ get_url(metadata.base.as_str(), "/test/outbound-not-allowed").as_str(),
+ Method::GET,
+ "",
+ 500,
+ &[],
+ Some("destination-not-allowed (error 1)"),
+ )
+ .await?;
+
+ Ok(())
+ }
+
+ let tc = TestCaseBuilder::default()
+ .name("outbound-http-to-same-app".to_string())
+ //the appname should be same as dir where this app exists
+ .appname(Some("outbound-http-to-same-app".to_string()))
+ .template(None)
+ .assertions(
+ |metadata: AppMetadata,
+ stdout_stream: Option<Pin<Box<dyn AsyncBufRead>>>,
+ stderr_stream: Option<Pin<Box<dyn AsyncBufRead>>>| {
+ Box::pin(checks(metadata, stdout_stream, stderr_stream))
+ },
+ )
+ .build()
+ .unwrap();
+
+ tc.run(controller).await.unwrap()
+}
+
pub async fn config_variables_default_works(controller: &dyn Controller) {
async fn checks(
metadata: AppMetadata,
diff --git a/tests/testcases/outbound-http-to-same-app/http-component/.cargo/config.toml b/tests/testcases/outbound-http-to-same-app/http-component/.cargo/config.toml
new file mode 100644
index 0000000000..6b77899cb3
--- /dev/null
+++ b/tests/testcases/outbound-http-to-same-app/http-component/.cargo/config.toml
@@ -0,0 +1,2 @@
+[build]
+target = "wasm32-wasi"
diff --git a/tests/testcases/outbound-http-to-same-app/http-component/Cargo.toml b/tests/testcases/outbound-http-to-same-app/http-component/Cargo.toml
new file mode 100644
index 0000000000..2d778a64c0
--- /dev/null
+++ b/tests/testcases/outbound-http-to-same-app/http-component/Cargo.toml
@@ -0,0 +1,19 @@
+[package]
+name = "http-component"
+version = "0.1.0"
+edition = "2021"
+
+[lib]
+crate-type = ["cdylib"]
+
+[dependencies]
+# Useful crate to handle errors.
+anyhow = "1"
+# Crate to simplify working with bytes.
+bytes = "1"
+# General-purpose crate with common HTTP types.
+http = "0.2"
+# The Spin SDK.
+spin-sdk = { path = "../../../../sdk/rust" }
+
+[workspace]
diff --git a/tests/testcases/outbound-http-to-same-app/http-component/src/lib.rs b/tests/testcases/outbound-http-to-same-app/http-component/src/lib.rs
new file mode 100644
index 0000000000..fe34f4338c
--- /dev/null
+++ b/tests/testcases/outbound-http-to-same-app/http-component/src/lib.rs
@@ -0,0 +1,15 @@
+use anyhow::Result;
+use spin_sdk::{
+ http::{Request, Response},
+ http_component,
+};
+
+/// A simple Spin HTTP component.
+#[http_component]
+fn hello_world(req: Request) -> Result<Response> {
+ println!("{:?}", req.headers());
+ Ok(http::Response::builder()
+ .status(200)
+ .header("foo", "bar")
+ .body(Some("Hello, Fermyon!\n".into()))?)
+}
diff --git a/tests/testcases/outbound-http-to-same-app/outbound-http-component/.cargo/config.toml b/tests/testcases/outbound-http-to-same-app/outbound-http-component/.cargo/config.toml
new file mode 100644
index 0000000000..6b77899cb3
--- /dev/null
+++ b/tests/testcases/outbound-http-to-same-app/outbound-http-component/.cargo/config.toml
@@ -0,0 +1,2 @@
+[build]
+target = "wasm32-wasi"
diff --git a/tests/testcases/outbound-http-to-same-app/outbound-http-component/Cargo.toml b/tests/testcases/outbound-http-to-same-app/outbound-http-component/Cargo.toml
new file mode 100644
index 0000000000..5e13e10410
--- /dev/null
+++ b/tests/testcases/outbound-http-to-same-app/outbound-http-component/Cargo.toml
@@ -0,0 +1,19 @@
+[package]
+name = "outbound-http-component"
+version = "0.1.0"
+edition = "2021"
+
+[lib]
+crate-type = ["cdylib"]
+
+[dependencies]
+# Useful crate to handle errors.
+anyhow = "1"
+# Crate to simplify working with bytes.
+bytes = "1"
+# General-purpose crate with common HTTP types.
+http = "0.2"
+# The Spin SDK.
+spin-sdk = { path = "../../../../sdk/rust" }
+
+[workspace]
diff --git a/tests/testcases/outbound-http-to-same-app/outbound-http-component/src/lib.rs b/tests/testcases/outbound-http-to-same-app/outbound-http-component/src/lib.rs
new file mode 100644
index 0000000000..30eaf71375
--- /dev/null
+++ b/tests/testcases/outbound-http-to-same-app/outbound-http-component/src/lib.rs
@@ -0,0 +1,20 @@
+use anyhow::Result;
+use spin_sdk::{
+ http::{Request, Response},
+ http_component,
+};
+
+/// Send an HTTP request and return the response.
+#[http_component]
+fn send_outbound(_req: Request) -> Result<Response> {
+ let mut res = spin_sdk::outbound_http::send_request(
+ http::Request::builder()
+ .method("GET")
+ .uri("/test/hello")
+ .body(None)?,
+ )?;
+ res.headers_mut()
+ .insert("spin-component", "outbound-http-component".try_into()?);
+ println!("{:?}", res);
+ Ok(res)
+}
diff --git a/tests/testcases/outbound-http-to-same-app/spin.toml b/tests/testcases/outbound-http-to-same-app/spin.toml
new file mode 100644
index 0000000000..1b9dea8466
--- /dev/null
+++ b/tests/testcases/outbound-http-to-same-app/spin.toml
@@ -0,0 +1,34 @@
+spin_version = "1"
+authors = ["Fermyon Engineering <engineering@fermyon.com>"]
+description = "An application that demonstates a component making an outbound http request to another component in the same application."
+name = "local-outbound-http"
+trigger = { type = "http", base = "/test" }
+version = "1.0.0"
+
+[[component]]
+id = "hello"
+source = "http-component/target/wasm32-wasi/release/http_component.wasm"
+[component.trigger]
+route = "/hello/..."
+[component.build]
+workdir = "http-component"
+command = "cargo build --target wasm32-wasi --release"
+
+[[component]]
+id = "outbound-http-allowed"
+source = "outbound-http-component/target/wasm32-wasi/release/outbound_http_component.wasm"
+allowed_http_hosts = ["self"]
+[component.trigger]
+route = "/outbound-allowed/..."
+[component.build]
+workdir = "outbound-http-component"
+command = "cargo build --target wasm32-wasi --release"
+
+[[component]]
+id = "outbound-http-not-allowed"
+source = "outbound-http-component/target/wasm32-wasi/release/outbound_http_component.wasm"
+[component.trigger]
+route = "/outbound-not-allowed/..."
+[component.build]
+workdir = "outbound-http-component"
+command = "cargo build --target wasm32-wasi --release"
|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
ced6f0e9a04631de351e0d137873be301d7e08bb
|
`spin add static-fileserver` creates folder based on component name (still have to create `assets` dir manually)
Version:
`spin 1.4.0 (7aab1fe 2023-07-11)`
Issue:
When adding a `static-fileserver` component to an application, Spin creates a new directory based on the component name which the user provides. For example:
```console
$ spin add static-fileserver
Enter a name for your new component: component-name
HTTP path: /static/...
Directory containing the files to serve: assets
```
If a user only provides a name `component-name` and then presses inter twice (accepting the defaults) Spin creates the following application structure. The component name directory is empty by default:
```console
$ tree .
.
├── Cargo.toml
├── component-name
├── spin.toml
└── src
└── lib.rs
```
If the application is built and run as is, the following error message is returned:
```console
$ spin build --up
// --snip--
Finished building all Spin components
Error: Failed to collect file mounts for assets
Caused by:
Cannot place ~/http-rust-app/assets: source must be a directory
```
If the user creates a new assets directory manually, the build works:
```console
$ mkdir assets
$ spin build --up
// --snip--
Available Routes:
http-rust-app: http://127.0.0.1:3000 (wildcard)
component-name: http://127.0.0.1:3000/static (wildcard)
```
Problem is that we a) had to manually create the `assets` directory and b) the application has an empty directory called `component-name`.
```console
.
├── Cargo.lock
├── Cargo.toml
├── assets
├── component-name
├── spin.toml
└── src
└── lib.rs
```
Related:
- [Create directory for static-fileserver template ](https://github.com/fermyon/spin/issues/1022)
|
I was going to claim that this would require some changes because the template system _always_ created the new directory... but the `redirect` template doesn't. Time to do some figuring!
|
2023-07-19T03:25:57Z
|
fermyon__spin-1670
|
fermyon/spin
|
3.2
|
diff --git a/crates/templates/src/lib.rs b/crates/templates/src/lib.rs
index 1aa344acd0..e4b18216d9 100644
--- a/crates/templates/src/lib.rs
+++ b/crates/templates/src/lib.rs
@@ -24,3 +24,6 @@ pub use manager::*;
pub use run::{Run, RunOptions};
pub use source::TemplateSource;
pub use template::{Template, TemplateVariantInfo};
+
+#[cfg(test)]
+mod test_built_ins;
diff --git a/crates/templates/src/manager.rs b/crates/templates/src/manager.rs
index 8f8eb23e69..2ca605c1a2 100644
--- a/crates/templates/src/manager.rs
+++ b/crates/templates/src/manager.rs
@@ -107,7 +107,11 @@ impl TemplateManager {
/// Creates a `TemplateManager` for the default install location.
pub fn try_default() -> anyhow::Result<Self> {
let store = TemplateStore::try_default()?;
- Ok(Self { store })
+ Ok(Self::new(store))
+ }
+
+ pub(crate) fn new(store: TemplateStore) -> Self {
+ Self { store }
}
/// Installs templates from the specified source.
diff --git a/templates/static-fileserver/metadata/spin-template.toml b/templates/static-fileserver/metadata/spin-template.toml
index dbdebe8735..9399a04dad 100644
--- a/templates/static-fileserver/metadata/spin-template.toml
+++ b/templates/static-fileserver/metadata/spin-template.toml
@@ -5,7 +5,7 @@ trigger_type = "http"
tags = ["http", "file", "static", "asset"]
[add_component]
-skip_files = ["spin.toml"]
+skip_files = ["spin.toml", ".gitignore"]
skip_parameters = ["http-base", "project-description"]
[add_component.snippets]
component = "component.txt"
| 1,670
|
[
"1669"
] |
diff --git a/crates/templates/src/test_built_ins/mod.rs b/crates/templates/src/test_built_ins/mod.rs
new file mode 100644
index 0000000000..8df9710678
--- /dev/null
+++ b/crates/templates/src/test_built_ins/mod.rs
@@ -0,0 +1,73 @@
+#![cfg(test)]
+
+// Module for unit-testing the built-in templates when a full e2e test would be overkill.
+// If your test involves invoking the Spin CLI, or builds or runs an application, use
+// an e2e test.
+
+use std::{collections::HashMap, path::PathBuf};
+
+use super::*;
+
+struct DiscardingReporter;
+
+impl ProgressReporter for DiscardingReporter {
+ fn report(&self, _: impl AsRef<str>) {}
+}
+
+#[tokio::test]
+async fn add_fileserver_does_not_create_dir() -> anyhow::Result<()> {
+ let built_ins_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..");
+ let built_ins_src = TemplateSource::File(built_ins_dir);
+
+ let store_dir = tempfile::tempdir()?;
+ let store = store::TemplateStore::new(store_dir.path());
+ let manager = TemplateManager::new(store);
+
+ manager
+ .install(
+ &built_ins_src,
+ &InstallOptions::default(),
+ &DiscardingReporter,
+ )
+ .await?;
+
+ let app_dir = tempfile::tempdir()?;
+
+ // Create an app to add the fileserver into
+ let new_empty_options = RunOptions {
+ variant: TemplateVariantInfo::NewApplication,
+ name: "add-fs-dir-test".to_owned(),
+ output_path: app_dir.path().to_owned(),
+ values: HashMap::new(),
+ accept_defaults: true,
+ };
+ manager
+ .get("http-empty")?
+ .expect("http-empty template should exist")
+ .run(new_empty_options)
+ .silent()
+ .await?;
+
+ // Add the fileserver to that app
+ let manifest_path = app_dir.path().join("spin.toml");
+ let add_fs_options = RunOptions {
+ variant: TemplateVariantInfo::AddComponent { manifest_path },
+ name: "fs".to_owned(),
+ output_path: app_dir.path().join("fs"),
+ values: HashMap::new(),
+ accept_defaults: true,
+ };
+ manager
+ .get("static-fileserver")?
+ .expect("static-fileserver template should exist")
+ .run(add_fs_options)
+ .silent()
+ .await?;
+
+ // Finally!
+ assert!(
+ !app_dir.path().join("fs").exists(),
+ "<app_dir>/fs should not have been created"
+ );
+ Ok(())
+}
|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
ced6f0e9a04631de351e0d137873be301d7e08bb
|
`spin plugin install` fails if latest plugin version doesn't support current Spin version
on trying to install the plugins with spin 1.3, we get following error:
```
$) spin --version
spin 1.3.0 (9fb8256 2023-06-12)
$) spin plugin install js2wasm --yes
Error: Plugin is not compatible with this version of Spin (supported: >=1.4, actual: 1.3.0). Try running `spin plugins update && spin plugins upgrade --all` to install latest or override with `--override-compatibility-check`.
```
It seems because the latest release of js2wasm plugin has compatibility with spin version `>=1.4` only.
It might be useful to identify and install the `latest compatible` version automatically rather than failing the installation.
|
one more thing I noticed is that you can't install the latest version by using a `--version` flag:
```
$) spin plugin install js2wasm -v 0.5.0
Error: plugin 'js2wasm' not found at expected location /Users/rajatjindal/Library/Application Support/spin/plugins/.spin-plugins/manifests/js2wasm/js2wasm@0.5.0.json: No such file or directory (os error 2)
```
@rajatjindal #1548 tracks the second issue
I have a candidate fix for this, but I'm having trouble wrangling it into a test harness - either my fix is in the wrong place or I need to also tweak some layering.
|
2023-07-18T03:42:05Z
|
fermyon__spin-1668
|
fermyon/spin
|
3.2
|
diff --git a/crates/plugins/Cargo.toml b/crates/plugins/Cargo.toml
index 5ce5c631d6..0816ef3d64 100644
--- a/crates/plugins/Cargo.toml
+++ b/crates/plugins/Cargo.toml
@@ -7,14 +7,14 @@ edition = { workspace = true }
[dependencies]
anyhow = "1.0"
bytes = "1.1"
-chrono = "0.4"
+chrono = { version = "0.4", features = ["serde"] }
dirs = "4.0"
fd-lock = "3.0.12"
flate2 = { version = "1.0.17", features = ["zlib-ng"], default-features = false }
is-terminal = "0.4"
path-absolutize = "3.0.11"
reqwest = { version = "0.11", features = ["json"] }
-semver = "1.0"
+semver = { version = "1.0", features = ["serde"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
spin-common = { path = "../common" }
@@ -24,4 +24,4 @@ terminal = { path = "../terminal" }
thiserror = "1"
tokio = { version = "1.23", features = [ "fs", "process", "rt", "macros" ] }
tracing = { workspace = true }
-url = "2.2.2"
+url = { version = "2.2.2", features = ["serde"] }
diff --git a/crates/plugins/src/badger/mod.rs b/crates/plugins/src/badger/mod.rs
index fe5ffaf94c..b4ee7d74d3 100644
--- a/crates/plugins/src/badger/mod.rs
+++ b/crates/plugins/src/badger/mod.rs
@@ -170,7 +170,7 @@ impl BadgerEvaluator {
let latest_version = {
let latest_lookup = crate::lookup::PluginLookup::new(&self.plugin_name, None);
let latest_manifest = latest_lookup
- .get_manifest_from_repository(store.get_plugins_directory())
+ .resolve_manifest_exact(store.get_plugins_directory())
.await
.ok();
latest_manifest.and_then(|m| semver::Version::parse(m.version()).ok())
diff --git a/crates/plugins/src/error.rs b/crates/plugins/src/error.rs
index c784b7dac4..a8d2c148da 100644
--- a/crates/plugins/src/error.rs
+++ b/crates/plugins/src/error.rs
@@ -14,6 +14,9 @@ pub enum Error {
#[error("URL parse error {0}")]
UrlParseError(#[from] url::ParseError),
+
+ #[error("{0}")]
+ Other(#[from] anyhow::Error),
}
/// Contains error details for when a plugin resource cannot be found at expected location
diff --git a/crates/plugins/src/lookup.rs b/crates/plugins/src/lookup.rs
index 9c50da7503..f3c71c3347 100644
--- a/crates/plugins/src/lookup.rs
+++ b/crates/plugins/src/lookup.rs
@@ -30,7 +30,34 @@ impl PluginLookup {
}
}
- pub async fn get_manifest_from_repository(
+ pub async fn resolve_manifest(
+ &self,
+ plugins_dir: &Path,
+ skip_compatibility_check: bool,
+ spin_version: &str,
+ ) -> PluginLookupResult<PluginManifest> {
+ let exact = self.resolve_manifest_exact(plugins_dir).await?;
+ if skip_compatibility_check
+ || self.version.is_some()
+ || exact.is_compatible_spin_version(spin_version)
+ {
+ return Ok(exact);
+ }
+
+ let store = crate::store::PluginStore::new(plugins_dir.to_owned());
+
+ // TODO: This is very similar to some logic in the badger module - look for consolidation opportunities.
+ let manifests = store.catalogue_manifests()?;
+ let relevant_manifests = manifests.into_iter().filter(|m| m.name() == self.name);
+ let compatible_manifests = relevant_manifests
+ .filter(|m| m.has_compatible_package() && m.is_compatible_spin_version(spin_version));
+ let highest_compatible_manifest =
+ compatible_manifests.max_by_key(|m| m.try_version().unwrap_or_else(|_| null_version()));
+
+ Ok(highest_compatible_manifest.unwrap_or(exact))
+ }
+
+ pub async fn resolve_manifest_exact(
&self,
plugins_dir: &Path,
) -> PluginLookupResult<PluginManifest> {
@@ -41,22 +68,48 @@ impl PluginLookup {
.map_err(|e| {
Error::ConnectionFailed(ConnectionFailedError::new(url.to_string(), e.to_string()))
})?;
+
+ self.resolve_manifest_exact_from_good_repo(plugins_dir)
+ }
+
+ // This is split from resolve_manifest_exact because it may recurse (once) and that makes
+ // Rust async sad. So we move the potential recursion to a sync helper.
+ #[allow(clippy::let_and_return)]
+ pub fn resolve_manifest_exact_from_good_repo(
+ &self,
+ plugins_dir: &Path,
+ ) -> PluginLookupResult<PluginManifest> {
let expected_path = spin_plugins_repo_manifest_path(&self.name, &self.version, plugins_dir);
- let file = File::open(&expected_path).map_err(|e| {
- Error::NotFound(NotFoundError::new(
- Some(self.name.clone()),
- expected_path.display().to_string(),
- e.to_string(),
- ))
- })?;
- let manifest: PluginManifest = serde_json::from_reader(file).map_err(|e| {
- Error::InvalidManifest(InvalidManifestError::new(
+
+ let not_found = |e: std::io::Error| {
+ Err(Error::NotFound(NotFoundError::new(
Some(self.name.clone()),
expected_path.display().to_string(),
e.to_string(),
- ))
- })?;
- Ok(manifest)
+ )))
+ };
+
+ let manifest = match File::open(&expected_path) {
+ Ok(file) => serde_json::from_reader(file).map_err(|e| {
+ Error::InvalidManifest(InvalidManifestError::new(
+ Some(self.name.clone()),
+ expected_path.display().to_string(),
+ e.to_string(),
+ ))
+ }),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound && self.version.is_some() => {
+ // If a user has asked for a version by number, and the path doesn't exist,
+ // it _might_ be because it's the latest version. This checks for that case.
+ let latest = Self::new(&self.name, None);
+ match latest.resolve_manifest_exact_from_good_repo(plugins_dir) {
+ Ok(manifest) if manifest.try_version().ok() == self.version => Ok(manifest),
+ _ => not_found(e),
+ }
+ }
+ Err(e) => not_found(e),
+ };
+
+ manifest
}
}
@@ -64,6 +117,16 @@ pub fn plugins_repo_url() -> Result<Url, url::ParseError> {
Url::parse(SPIN_PLUGINS_REPO)
}
+#[cfg(not(test))]
+fn accept_as_repo(git_root: &Path) -> bool {
+ git_root.join(".git").exists()
+}
+
+#[cfg(test)]
+fn accept_as_repo(git_root: &Path) -> bool {
+ git_root.join(".git").exists() || git_root.join("_spin_test_dot_git").exists()
+}
+
pub async fn fetch_plugins_repo(
repo_url: &Url,
plugins_dir: &Path,
@@ -71,7 +134,7 @@ pub async fn fetch_plugins_repo(
) -> anyhow::Result<()> {
let git_root = plugin_manifests_repo_path(plugins_dir);
let git_source = GitSource::new(repo_url, None, &git_root);
- if git_root.join(".git").exists() {
+ if accept_as_repo(&git_root) {
if update {
git_source.pull().await?;
}
@@ -110,3 +173,83 @@ pub fn spin_plugins_repo_manifest_dir(plugins_dir: &Path) -> PathBuf {
.join(PLUGINS_REPO_LOCAL_DIRECTORY)
.join(PLUGINS_REPO_MANIFESTS_DIRECTORY)
}
+
+fn null_version() -> semver::Version {
+ semver::Version::new(0, 0, 0)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const TEST_NAME: &str = "some-spin-ver-some-not";
+ const TESTS_STORE_DIR: &str = "tests";
+
+ fn tests_store_dir() -> PathBuf {
+ PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(TESTS_STORE_DIR)
+ }
+
+ #[tokio::test]
+ async fn if_no_version_given_and_latest_is_compatible_then_latest() -> PluginLookupResult<()> {
+ let lookup = PluginLookup::new(TEST_NAME, None);
+ let resolved = lookup
+ .resolve_manifest(&tests_store_dir(), false, "99.0.0")
+ .await?;
+ assert_eq!("99.0.1", resolved.version);
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn if_no_version_given_and_latest_is_not_compatible_then_highest_compatible(
+ ) -> PluginLookupResult<()> {
+ // NOTE: The setup assumes you are NOT running Windows on aarch64, so as to check 98.1.0 is not
+ // offered. If that assumption fails then this test will fail with actual version being 98.1.0.
+ // (We use this combination because the OS and architecture enums don't allow for fake operating systems!)
+ let lookup = PluginLookup::new(TEST_NAME, None);
+ let resolved = lookup
+ .resolve_manifest(&tests_store_dir(), false, "98.0.0")
+ .await?;
+ assert_eq!("98.0.0", resolved.version);
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn if_version_given_it_gets_used_regardless() -> PluginLookupResult<()> {
+ let lookup = PluginLookup::new(TEST_NAME, Some(semver::Version::parse("99.0.0").unwrap()));
+ let resolved = lookup
+ .resolve_manifest(&tests_store_dir(), false, "98.0.0")
+ .await?;
+ assert_eq!("99.0.0", resolved.version);
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn if_latest_version_given_it_gets_used_regardless() -> PluginLookupResult<()> {
+ let lookup = PluginLookup::new(TEST_NAME, Some(semver::Version::parse("99.0.1").unwrap()));
+ let resolved = lookup
+ .resolve_manifest(&tests_store_dir(), false, "98.0.0")
+ .await?;
+ assert_eq!("99.0.1", resolved.version);
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn if_no_version_given_but_skip_compat_then_highest() -> PluginLookupResult<()> {
+ let lookup = PluginLookup::new(TEST_NAME, None);
+ let resolved = lookup
+ .resolve_manifest(&tests_store_dir(), true, "98.0.0")
+ .await?;
+ assert_eq!("99.0.1", resolved.version);
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn if_non_existent_version_given_then_error() -> PluginLookupResult<()> {
+ let lookup = PluginLookup::new(TEST_NAME, Some(semver::Version::parse("177.7.7").unwrap()));
+ lookup
+ .resolve_manifest(&tests_store_dir(), true, "99.0.0")
+ .await
+ .expect_err("Should have errored because plugin v177.7.7 does not exist");
+ Ok(())
+ }
+}
diff --git a/crates/plugins/src/manager.rs b/crates/plugins/src/manager.rs
index 13c68e882b..2d6a81d241 100644
--- a/crates/plugins/src/manager.rs
+++ b/crates/plugins/src/manager.rs
@@ -184,6 +184,8 @@ impl PluginManager {
pub async fn get_manifest(
&self,
manifest_location: &ManifestLocation,
+ skip_compatibility_check: bool,
+ spin_version: &str,
) -> PluginLookupResult<PluginManifest> {
let plugin_manifest = match manifest_location {
ManifestLocation::Remote(url) => {
@@ -232,7 +234,11 @@ impl PluginManager {
}
ManifestLocation::PluginsRepository(lookup) => {
lookup
- .get_manifest_from_repository(self.store().get_plugins_directory())
+ .resolve_manifest(
+ self.store().get_plugins_directory(),
+ skip_compatibility_check,
+ spin_version,
+ )
.await?
}
};
diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs
index b7f7c21b87..9a0fe43d84 100644
--- a/crates/plugins/src/manifest.rs
+++ b/crates/plugins/src/manifest.rs
@@ -64,6 +64,10 @@ impl PluginManifest {
Err(_) => false,
}
}
+
+ pub fn try_version(&self) -> Result<semver::Version, semver::Error> {
+ semver::Version::parse(&self.version)
+ }
}
/// Describes compatibility and location of a plugin source.
diff --git a/src/commands/plugins.rs b/src/commands/plugins.rs
index a5dbe5619a..31ca9f8b58 100644
--- a/src/commands/plugins.rs
+++ b/src/commands/plugins.rs
@@ -114,7 +114,13 @@ impl Install {
let manager = PluginManager::try_default()?;
// Downgrades are only allowed via the `upgrade` subcommand
let downgrade = false;
- let manifest = manager.get_manifest(&manifest_location).await?;
+ let manifest = manager
+ .get_manifest(
+ &manifest_location,
+ self.override_compatibility_check,
+ SPIN_VERSION,
+ )
+ .await?;
try_install(
&manifest,
&manager,
@@ -250,7 +256,14 @@ impl Upgrade {
.to_string();
let manifest_location =
ManifestLocation::PluginsRepository(PluginLookup::new(&name, None));
- let manifest = match manager.get_manifest(&manifest_location).await {
+ let manifest = match manager
+ .get_manifest(
+ &manifest_location,
+ self.override_compatibility_check,
+ SPIN_VERSION,
+ )
+ .await
+ {
Err(Error::NotFound(e)) => {
log::info!("Could not upgrade plugin '{name}': {e:?}");
continue;
@@ -283,7 +296,13 @@ impl Upgrade {
self.version,
)),
};
- let manifest = manager.get_manifest(&manifest_location).await?;
+ let manifest = manager
+ .get_manifest(
+ &manifest_location,
+ self.override_compatibility_check,
+ SPIN_VERSION,
+ )
+ .await?;
try_install(
&manifest,
&manager,
| 1,668
|
[
"1661"
] |
diff --git a/crates/plugins/tests/.spin-plugins/_spin_test_dot_git b/crates/plugins/tests/.spin-plugins/_spin_test_dot_git
new file mode 100644
index 0000000000..a60a97e033
--- /dev/null
+++ b/crates/plugins/tests/.spin-plugins/_spin_test_dot_git
@@ -0,0 +1,1 @@
+Fake file for preventing the plugin system from pulling from the production repo into this directory during tests
diff --git a/crates/plugins/tests/.spin-plugins/manifests/some-spin-ver-some-not/some-spin-ver-some-not.json b/crates/plugins/tests/.spin-plugins/manifests/some-spin-ver-some-not/some-spin-ver-some-not.json
new file mode 100644
index 0000000000..d325dc8ec1
--- /dev/null
+++ b/crates/plugins/tests/.spin-plugins/manifests/some-spin-ver-some-not/some-spin-ver-some-not.json
@@ -0,0 +1,27 @@
+{
+ "name": "some-spin-ver-some-not",
+ "description": "A plugin where only some versions work with the test harness version of Spin.",
+ "version": "99.0.1",
+ "spinCompatibility": ">=99.0",
+ "license": "Apache-2.0",
+ "packages": [
+ {
+ "os": "linux",
+ "arch": "amd64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ },
+ {
+ "os": "macos",
+ "arch": "aarch64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ },
+ {
+ "os": "macos",
+ "arch": "amd64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ }
+ ]
+}
diff --git a/crates/plugins/tests/.spin-plugins/manifests/some-spin-ver-some-not/some-spin-ver-some-not@98.0.0.json b/crates/plugins/tests/.spin-plugins/manifests/some-spin-ver-some-not/some-spin-ver-some-not@98.0.0.json
new file mode 100644
index 0000000000..e3db68191a
--- /dev/null
+++ b/crates/plugins/tests/.spin-plugins/manifests/some-spin-ver-some-not/some-spin-ver-some-not@98.0.0.json
@@ -0,0 +1,27 @@
+{
+ "name": "some-spin-ver-some-not",
+ "description": "A plugin where only some versions work with the test harness version of Spin.",
+ "version": "98.0.0",
+ "spinCompatibility": ">=98.0",
+ "license": "Apache-2.0",
+ "packages": [
+ {
+ "os": "linux",
+ "arch": "amd64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ },
+ {
+ "os": "macos",
+ "arch": "aarch64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ },
+ {
+ "os": "macos",
+ "arch": "amd64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ }
+ ]
+}
diff --git a/crates/plugins/tests/.spin-plugins/manifests/some-spin-ver-some-not/some-spin-ver-some-not@98.1.0.json b/crates/plugins/tests/.spin-plugins/manifests/some-spin-ver-some-not/some-spin-ver-some-not@98.1.0.json
new file mode 100644
index 0000000000..1db8f90143
--- /dev/null
+++ b/crates/plugins/tests/.spin-plugins/manifests/some-spin-ver-some-not/some-spin-ver-some-not@98.1.0.json
@@ -0,0 +1,15 @@
+{
+ "name": "some-spin-ver-some-not",
+ "description": "A plugin where only some versions work with the test harness version of Spin.",
+ "version": "98.1.0",
+ "spinCompatibility": ">=98.0",
+ "license": "Apache-2.0",
+ "packages": [
+ {
+ "os": "windows",
+ "arch": "aarch64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ }
+ ]
+}
diff --git a/crates/plugins/tests/.spin-plugins/manifests/some-spin-ver-some-not/some-spin-ver-some-not@99.0.0.json b/crates/plugins/tests/.spin-plugins/manifests/some-spin-ver-some-not/some-spin-ver-some-not@99.0.0.json
new file mode 100644
index 0000000000..bf255be664
--- /dev/null
+++ b/crates/plugins/tests/.spin-plugins/manifests/some-spin-ver-some-not/some-spin-ver-some-not@99.0.0.json
@@ -0,0 +1,27 @@
+{
+ "name": "some-spin-ver-some-not",
+ "description": "A plugin where only some versions work with the test harness version of Spin.",
+ "version": "99.0.0",
+ "spinCompatibility": ">=99.0",
+ "license": "Apache-2.0",
+ "packages": [
+ {
+ "os": "linux",
+ "arch": "amd64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ },
+ {
+ "os": "macos",
+ "arch": "aarch64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ },
+ {
+ "os": "macos",
+ "arch": "amd64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ }
+ ]
+}
diff --git a/crates/plugins/tests/some-spin-ver-some-not/some-spin-ver-some-not.json b/crates/plugins/tests/some-spin-ver-some-not/some-spin-ver-some-not.json
new file mode 100644
index 0000000000..eafeb34c08
--- /dev/null
+++ b/crates/plugins/tests/some-spin-ver-some-not/some-spin-ver-some-not.json
@@ -0,0 +1,21 @@
+{
+ "name": "some-spin-ver-some-not",
+ "description": "A plugin where only some versions work with the test harness version of Spin.",
+ "version": "99.0.1",
+ "spinCompatibility": ">=99.0",
+ "license": "Apache-2.0",
+ "packages": [
+ {
+ "os": "linux",
+ "arch": "amd64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ },
+ {
+ "os": "macos",
+ "arch": "aarch64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ }
+ ]
+}
diff --git a/crates/plugins/tests/some-spin-ver-some-not/some-spin-ver-some-not@98.0.0.json b/crates/plugins/tests/some-spin-ver-some-not/some-spin-ver-some-not@98.0.0.json
new file mode 100644
index 0000000000..fb313522c9
--- /dev/null
+++ b/crates/plugins/tests/some-spin-ver-some-not/some-spin-ver-some-not@98.0.0.json
@@ -0,0 +1,21 @@
+{
+ "name": "some-spin-ver-some-not",
+ "description": "A plugin where only some versions work with the test harness version of Spin.",
+ "version": "98.0.0",
+ "spinCompatibility": ">=98.0",
+ "license": "Apache-2.0",
+ "packages": [
+ {
+ "os": "linux",
+ "arch": "amd64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ },
+ {
+ "os": "macos",
+ "arch": "aarch64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ }
+ ]
+}
diff --git a/crates/plugins/tests/some-spin-ver-some-not/some-spin-ver-some-not@98.1.0.json b/crates/plugins/tests/some-spin-ver-some-not/some-spin-ver-some-not@98.1.0.json
new file mode 100644
index 0000000000..1db8f90143
--- /dev/null
+++ b/crates/plugins/tests/some-spin-ver-some-not/some-spin-ver-some-not@98.1.0.json
@@ -0,0 +1,15 @@
+{
+ "name": "some-spin-ver-some-not",
+ "description": "A plugin where only some versions work with the test harness version of Spin.",
+ "version": "98.1.0",
+ "spinCompatibility": ">=98.0",
+ "license": "Apache-2.0",
+ "packages": [
+ {
+ "os": "windows",
+ "arch": "aarch64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ }
+ ]
+}
diff --git a/crates/plugins/tests/some-spin-ver-some-not/some-spin-ver-some-not@99.0.0.json b/crates/plugins/tests/some-spin-ver-some-not/some-spin-ver-some-not@99.0.0.json
new file mode 100644
index 0000000000..cf2bd99f90
--- /dev/null
+++ b/crates/plugins/tests/some-spin-ver-some-not/some-spin-ver-some-not@99.0.0.json
@@ -0,0 +1,21 @@
+{
+ "name": "some-spin-ver-some-not",
+ "description": "A plugin where only some versions work with the test harness version of Spin.",
+ "version": "99.0.0",
+ "spinCompatibility": ">=99.0",
+ "license": "Apache-2.0",
+ "packages": [
+ {
+ "os": "linux",
+ "arch": "amd64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ },
+ {
+ "os": "macos",
+ "arch": "aarch64",
+ "url": "https://example.com/doesnt-exist",
+ "sha256": "11111111"
+ }
+ ]
+}
|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
75b3474dfa96d5ba93f931f2625e2829f57422ac
|
Unhide planned Spin 1.4 features
* CLI: Unhide `spin up --sqlite` flag
* Rust SDK: Move `sqlite` out of `experimental` feature
* CLI: Unhide `spin doctor` command
|
2023-06-26T22:13:01Z
|
fermyon__spin-1617
|
fermyon/spin
|
3.2
|
diff --git a/crates/trigger/src/cli.rs b/crates/trigger/src/cli.rs
index 5e23eb04c9..31bb76c0c7 100644
--- a/crates/trigger/src/cli.rs
+++ b/crates/trigger/src/cli.rs
@@ -107,8 +107,9 @@ where
#[clap(long = "key-value", parse(try_from_str = parse_kv))]
key_values: Vec<(String, String)>,
- /// Run a sqlite migration against the default database
- #[clap(long = "sqlite", hide = true)]
+ /// Run a SQLite statement such as a migration against the default database.
+ /// To run from a file, prefix the filename with @ e.g. spin up --sqlite @migration.sql
+ #[clap(long = "sqlite")]
sqlite_statements: Vec<String>,
#[clap(long = "help-args-only", hide = true)]
diff --git a/sdk/rust/src/lib.rs b/sdk/rust/src/lib.rs
index 225135e7fd..5b0caf25ce 100644
--- a/sdk/rust/src/lib.rs
+++ b/sdk/rust/src/lib.rs
@@ -8,8 +8,7 @@ pub mod outbound_http;
/// Key/Value storage.
pub mod key_value;
-/// Sqlite
-#[cfg(feature = "experimental")]
+/// SQLite storage.
pub mod sqlite;
/// Exports the procedural macros for writing handlers for Spin components.
diff --git a/src/commands/doctor.rs b/src/commands/doctor.rs
index aec3711c4e..2fb5fe7559 100644
--- a/src/commands/doctor.rs
+++ b/src/commands/doctor.rs
@@ -9,7 +9,7 @@ use spin_doctor::{Diagnosis, DryRunNotSupported};
use crate::opts::{APP_MANIFEST_FILE_OPT, DEFAULT_MANIFEST_FILE};
#[derive(Parser, Debug)]
-#[clap(hide = true, about = "Detect and fix problems with Spin applications")]
+#[clap(about = "Detect and fix problems with Spin applications")]
pub struct DoctorCommand {
/// The application to check. This may be a manifest (spin.toml) file, or a
/// directory containing a spin.toml file.
| 1,617
|
[
"1616"
] |
diff --git a/tests/testcases/sqlite-undefined-db/Cargo.toml b/tests/testcases/sqlite-undefined-db/Cargo.toml
index b1373a5f16..fd3944394a 100644
--- a/tests/testcases/sqlite-undefined-db/Cargo.toml
+++ b/tests/testcases/sqlite-undefined-db/Cargo.toml
@@ -16,7 +16,7 @@ http = "0.2"
itertools = "0.10"
serde = { version = "1.0", features = ["derive"] }
serde_qs = "0.12"
-spin-sdk = { path = "../../../sdk/rust", features = ["experimental"] }
+spin-sdk = { path = "../../../sdk/rust" }
# The wit-bindgen-rust dependency generates bindings for interfaces.
wit-bindgen-rust = { git = "https://github.com/bytecodealliance/wit-bindgen", rev = "cb871cfa1ee460b51eb1d144b175b9aab9c50aba" }
diff --git a/tests/testcases/sqlite/Cargo.toml b/tests/testcases/sqlite/Cargo.toml
index 771e8fdcc5..186518d391 100644
--- a/tests/testcases/sqlite/Cargo.toml
+++ b/tests/testcases/sqlite/Cargo.toml
@@ -16,7 +16,7 @@ http = "0.2"
itertools = "0.10"
serde = { version = "1.0", features = ["derive"] }
serde_qs = "0.12"
-spin-sdk = { path = "../../../sdk/rust", features = ["experimental"] }
+spin-sdk = { path = "../../../sdk/rust" }
# The wit-bindgen-rust dependency generates bindings for interfaces.
wit-bindgen-rust = { git = "https://github.com/bytecodealliance/wit-bindgen", rev = "cb871cfa1ee460b51eb1d144b175b9aab9c50aba" }
|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
|
9aa23cf51d3e625392182f18ec48ffec10543884
|
Run local integration tests with clean or predictable starting state
Per #1448, I got a failure in `make-kv` which neither @rajatjindal nor @lann could reproduce. It turned out this was because I had previously tried to adapt the test to include the new `spin up --key-value` option; apparently that worked, because it left turds in the store. So when I re-ran `make-kv`, even on main, an assertion about the set of keys in the store misfired.
Our local integration tests should either:
* Clear each test's local state before running it (e.g. delete `.spin` directory);
* Run each test with its own randomly generated state directoryl; or
* Reset local state to a known state before running.
I'm not sure of a good approach to the third option; I'd say consider it only if we have tests we want to run with a non-empty initial state.
NOTE: We should tackle this at the per-test level, not the per-session level, because otherwise we could get nasty heisentests where a failure only happens if tests run in a specific order (if two tests drive the same application but do not clean up between themselves). If we want tests to run in parallel then the second option is probably safest.
cc @rajatjindal
|
2023-05-08T06:58:24Z
|
fermyon__spin-1461
|
fermyon/spin
|
3.2
|
diff --git a/Cargo.lock b/Cargo.lock
index 4642285a74..97077bdf31 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1438,6 +1438,7 @@ dependencies = [
"nix 0.26.2",
"regex",
"reqwest",
+ "tempfile",
"tokio",
"url",
]
| 1,461
|
[
"1458"
] |
diff --git a/crates/e2e-testing/Cargo.toml b/crates/e2e-testing/Cargo.toml
index 03294f4bd9..7fbd464ec6 100644
--- a/crates/e2e-testing/Cargo.toml
+++ b/crates/e2e-testing/Cargo.toml
@@ -17,4 +17,5 @@ reqwest = { version = "0.11", features = ["blocking"] }
nix = "0.26.1"
url = "2.2.2"
derive_builder = "0.12.0"
-hyper-tls = "0.5.0"
\ No newline at end of file
+hyper-tls = "0.5.0"
+tempfile = "3.3.0"
\ No newline at end of file
diff --git a/crates/e2e-testing/src/controller.rs b/crates/e2e-testing/src/controller.rs
index 7bd411f554..48d30024cb 100644
--- a/crates/e2e-testing/src/controller.rs
+++ b/crates/e2e-testing/src/controller.rs
@@ -21,6 +21,7 @@ pub trait Controller {
app_name: &str,
trigger_type: &str,
mut args: Vec<&str>,
+ state_dir: &str,
) -> Result<AppInstance>;
async fn stop_app(
&self,
@@ -28,6 +29,7 @@ pub trait Controller {
process: Option<tokio::process::Child>,
) -> Result<()>;
}
+
/// This represents a running spin app.
/// If it is running using `spin up`, it also has `process` field populated
/// with handle to the `spin up` process
diff --git a/crates/e2e-testing/src/spin_controller.rs b/crates/e2e-testing/src/spin_controller.rs
index ff6ee48aab..dd3055ea76 100644
--- a/crates/e2e-testing/src/spin_controller.rs
+++ b/crates/e2e-testing/src/spin_controller.rs
@@ -43,6 +43,7 @@ impl Controller for SpinUp {
app_name: &str,
trigger_type: &str,
mut xargs: Vec<&str>,
+ state_dir: &str,
) -> Result<AppInstance> {
let appdir = spin::appdir(app_name);
@@ -51,6 +52,11 @@ impl Controller for SpinUp {
cmd.append(&mut xargs);
}
+ if !xargs.contains(&"--state_dir") {
+ cmd.push("--state-dir");
+ cmd.push(state_dir);
+ }
+
let mut address = "".to_string();
if trigger_type == "http" {
let port = utils::get_random_port()?;
diff --git a/crates/e2e-testing/src/testcase.rs b/crates/e2e-testing/src/testcase.rs
index 00c8deade7..754f8a3693 100644
--- a/crates/e2e-testing/src/testcase.rs
+++ b/crates/e2e-testing/src/testcase.rs
@@ -7,6 +7,7 @@ use core::pin::Pin;
use derive_builder::Builder;
use std::fs;
use std::future::Future;
+use tempfile::TempDir;
use tokio::io::BufReader;
use tokio::process::{ChildStderr, ChildStdout};
@@ -146,11 +147,25 @@ impl TestCase {
spin::registry_push(&appname, registry_app_url.as_str())?;
}
+ // create temp dir as state dir
+ let tempdir = TempDir::new()?;
+ let state_dir: String = tempdir
+ .path()
+ .join(".spin")
+ .into_os_string()
+ .into_string()
+ .unwrap();
+
// run `spin up` (or `spin deploy` for cloud).
// `AppInstance` has some basic info about the running app like base url, routes (only for cloud) etc.
let deploy_args = self.deploy_args.iter().map(|s| s as &str).collect();
let app = controller
- .run_app(&appname, &self.trigger_type, deploy_args)
+ .run_app(
+ &appname,
+ &self.trigger_type,
+ deploy_args,
+ state_dir.as_str(),
+ )
.await
.context("running app")?;
@@ -173,6 +188,9 @@ impl TestCase {
),
}
+ // this ensure tempdir cleans up after running test
+ drop(tempdir);
+
assertions_result
}
}
|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
|
033c3d1d6de26bfa3441aa38e5b44d077457321d
|
Add support for `spin up --key-value KEY,VALUE`
It would be nice to have parity between `spin up` and `spin cloud deploy` for the pre-seed key value feature. Today only `spin cloud deploy --key-value KEY,VALUE` works. This issue will track the work to add support for `spin up --key-value KEY,VALUE`. That way, Spin & Fermyon Cloud users who have a dependency on this feature can move their applications between environments easily.
|
nit so we don't accidentally end up with different syntaxes: the `deploy` syntax is `KEY=VALUE`, i.e. equals sign not a comma.
The existing `cloud deploy` syntax allows setting K/V pairs only in the app's default store (because cloud only has the default store).
1. For the local case, is it necessary to set pairs in non-default stores?
2. If so, what do we like as a syntax to do it?
The syntax needs to be unambiguous. For example, anything along the lines of `store:key=value` runs into the problem that a key could contain the separator character, and using quotes to avoid the ambiguity could get messy because a K/V pair with spaces in it would need to be quoted already, I think, which could get messy...
|
2023-05-02T00:57:31Z
|
fermyon__spin-1442
|
fermyon/spin
|
3.2
|
diff --git a/Cargo.lock b/Cargo.lock
index de376a04cc..dcc8f03c1e 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4976,6 +4976,7 @@ dependencies = [
"spin-app",
"spin-bindle",
"spin-build",
+ "spin-common",
"spin-config",
"spin-key-value",
"spin-key-value-sqlite",
@@ -5005,6 +5006,7 @@ dependencies = [
name = "spin-common"
version = "1.2.0-pre0"
dependencies = [
+ "anyhow",
"sha2 0.10.6",
"tempfile",
]
@@ -5314,6 +5316,7 @@ dependencies = [
"serde",
"serde_json",
"spin-app",
+ "spin-common",
"spin-componentize",
"spin-config",
"spin-core",
diff --git a/Cargo.toml b/Cargo.toml
index 6ae48bb3a6..777920b3ec 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -49,6 +49,7 @@ sha2 = "0.10.2"
spin-app = { path = "crates/app" }
spin-bindle = { path = "crates/bindle" }
spin-build = { path = "crates/build" }
+spin-common = { path = "crates/common" }
spin-config = { path = "crates/config" }
spin-trigger-http = { path = "crates/trigger-http" }
spin-loader = { path = "crates/loader" }
diff --git a/crates/common/Cargo.toml b/crates/common/Cargo.toml
index 5a84686bea..6f4320bfd1 100644
--- a/crates/common/Cargo.toml
+++ b/crates/common/Cargo.toml
@@ -5,6 +5,7 @@ authors = { workspace = true }
edition = { workspace = true }
[dependencies]
+anyhow = "1.0"
sha2 = "0.10"
[dev-dependencies]
diff --git a/crates/common/src/arg_parser.rs b/crates/common/src/arg_parser.rs
new file mode 100644
index 0000000000..361a679d41
--- /dev/null
+++ b/crates/common/src/arg_parser.rs
@@ -0,0 +1,17 @@
+//! Command line argument parsers
+
+use anyhow::bail;
+
+/// Parse an argument in the form `key=value` into a pair of strings.
+/// The error message is specific to key-value arguments.
+pub fn parse_kv(s: &str) -> anyhow::Result<(String, String)> {
+ parse_eq_pair(s, "Key/Values must be of the form `key=value`")
+}
+
+fn parse_eq_pair(s: &str, err_msg: &str) -> anyhow::Result<(String, String)> {
+ if let Some((key, value)) = s.split_once('=') {
+ Ok((key.to_owned(), value.to_owned()))
+ } else {
+ bail!("{err_msg}");
+ }
+}
diff --git a/crates/common/src/lib.rs b/crates/common/src/lib.rs
index c128c4c7cc..def2bcca02 100644
--- a/crates/common/src/lib.rs
+++ b/crates/common/src/lib.rs
@@ -8,4 +8,5 @@
// - No dependencies on other Spin crates
// - Code should have at least 2 dependents
+pub mod arg_parser;
pub mod sha256;
diff --git a/crates/trigger/Cargo.toml b/crates/trigger/Cargo.toml
index 164c74cb46..e2d391c82a 100644
--- a/crates/trigger/Cargo.toml
+++ b/crates/trigger/Cargo.toml
@@ -15,6 +15,7 @@ outbound-http = { path = "../outbound-http" }
outbound-redis = { path = "../outbound-redis" }
outbound-pg = { path = "../outbound-pg" }
outbound-mysql = { path = "../outbound-mysql" }
+spin-common = { path = "../common" }
spin-key-value = { path = "../key-value" }
spin-key-value-redis = { path = "../key-value-redis" }
spin-key-value-sqlite = { path = "../key-value-sqlite" }
diff --git a/crates/trigger/src/cli.rs b/crates/trigger/src/cli.rs
index 71884718ed..428c001c2a 100644
--- a/crates/trigger/src/cli.rs
+++ b/crates/trigger/src/cli.rs
@@ -9,6 +9,7 @@ use tokio::{
};
use spin_app::Loader;
+use spin_common::arg_parser::parse_kv;
use crate::stdio::StdioLoggingTriggerHooks;
use crate::{
@@ -104,6 +105,12 @@ where
#[clap(flatten)]
pub run_config: Executor::RunConfig,
+ /// Set a key/value pair (key=value) in the application's
+ /// default store. Any existing value will be overwritten.
+ /// Can be used multiple times.
+ #[clap(long = "key-value", parse(try_from_str = parse_kv))]
+ key_values: Vec<(String, String)>,
+
#[clap(long = "help-args-only", hide = true)]
pub help_args_only: bool,
}
@@ -132,8 +139,12 @@ where
let working_dir = std::env::var(SPIN_WORKING_DIR).context(SPIN_WORKING_DIR)?;
let locked_url = std::env::var(SPIN_LOCKED_URL).context(SPIN_LOCKED_URL)?;
+ let init_data = crate::HostComponentInitData {
+ kv: self.key_values.clone(),
+ };
+
let loader = TriggerLoader::new(working_dir, self.allow_transient_write);
- let executor = self.build_executor(loader, locked_url).await?;
+ let executor = self.build_executor(loader, locked_url, init_data).await?;
let run_fut = executor.run(self.run_config);
@@ -159,6 +170,7 @@ where
&self,
loader: impl Loader + Send + Sync + 'static,
locked_url: String,
+ init_data: crate::HostComponentInitData,
) -> Result<Executor> {
let runtime_config = self.build_runtime_config()?;
@@ -170,7 +182,7 @@ where
builder.hooks(StdioLoggingTriggerHooks::new(self.follow_components()));
builder.hooks(KeyValuePersistenceMessageHook);
- builder.build(locked_url, runtime_config).await
+ builder.build(locked_url, runtime_config, init_data).await
}
fn build_runtime_config(&self) -> Result<RuntimeConfig> {
diff --git a/crates/trigger/src/lib.rs b/crates/trigger/src/lib.rs
index 0d789a327a..175d6f95c1 100644
--- a/crates/trigger/src/lib.rs
+++ b/crates/trigger/src/lib.rs
@@ -102,6 +102,7 @@ impl<Executor: TriggerExecutor> TriggerExecutorBuilder<Executor> {
mut self,
app_uri: String,
runtime_config: runtime_config::RuntimeConfig,
+ init_data: HostComponentInitData,
) -> Result<Executor>
where
Executor::TriggerConfig: DeserializeOwned,
@@ -115,7 +116,11 @@ impl<Executor: TriggerExecutor> TriggerExecutorBuilder<Executor> {
builder.add_host_component(outbound_mysql::OutboundMysql::default())?;
self.loader.add_dynamic_host_component(
&mut builder,
- runtime_config::key_value::build_key_value_component(&runtime_config)?,
+ runtime_config::key_value::build_key_value_component(
+ &runtime_config,
+ &init_data.kv,
+ )
+ .await?,
)?;
self.loader.add_dynamic_host_component(
&mut builder,
@@ -144,6 +149,12 @@ impl<Executor: TriggerExecutor> TriggerExecutorBuilder<Executor> {
}
}
+/// Initialisation data for host components.
+#[derive(Default)] // TODO: this is only for tests, would like to get rid of
+pub struct HostComponentInitData {
+ kv: Vec<(String, String)>,
+}
+
/// Execution context for a TriggerExecutor executing a particular App.
pub struct TriggerAppEngine<Executor: TriggerExecutor> {
/// Engine to be used with this executor.
diff --git a/crates/trigger/src/runtime_config/key_value.rs b/crates/trigger/src/runtime_config/key_value.rs
index 4c2340065c..341ae4828c 100644
--- a/crates/trigger/src/runtime_config/key_value.rs
+++ b/crates/trigger/src/runtime_config/key_value.rs
@@ -1,7 +1,7 @@
-use std::{fs, path::PathBuf, sync::Arc};
+use std::{collections::HashMap, fs, path::PathBuf, sync::Arc};
use crate::{runtime_config::RuntimeConfig, TriggerHooks};
-use anyhow::{Context, Result};
+use anyhow::{bail, Context, Result};
use serde::Deserialize;
use spin_key_value::{
CachingStoreManager, DelegatingStoreManager, KeyValueComponent, StoreManager,
@@ -16,10 +16,36 @@ const DEFAULT_SPIN_STORE_FILENAME: &str = "sqlite_key_value.db";
pub type KeyValueStore = Arc<dyn StoreManager>;
/// Builds a [`KeyValueComponent`] from the given [`RuntimeConfig`].
-pub fn build_key_value_component(runtime_config: &RuntimeConfig) -> Result<KeyValueComponent> {
- let stores = runtime_config
+pub async fn build_key_value_component(
+ runtime_config: &RuntimeConfig,
+ init_data: &[(String, String)],
+) -> Result<KeyValueComponent> {
+ let stores: HashMap<_, _> = runtime_config
.key_value_stores()
- .context("Failed to build key-value component")?;
+ .context("Failed to build key-value component")?
+ .into_iter()
+ .collect();
+
+ // Avoid creating a database as a side-effect if one is not needed.
+ if !init_data.is_empty() {
+ if let Some(manager) = stores.get("default") {
+ let default_store = manager
+ .get("default")
+ .await
+ .context("Failed to access key-value store to set requested entries")?;
+ for (key, value) in init_data {
+ default_store
+ .set(key, value.as_bytes())
+ .await
+ .with_context(|| {
+ format!("Failed to set requested entry {key} in key-value store")
+ })?;
+ }
+ } else {
+ bail!("Failed to access key-value store to set requested entries");
+ }
+ }
+
let delegating_manager = DelegatingStoreManager::new(stores);
let caching_manager = Arc::new(CachingStoreManager::new(delegating_manager));
Ok(KeyValueComponent::new(spin_key_value::manager(move |_| {
diff --git a/src/commands/deploy.rs b/src/commands/deploy.rs
index 75c62b840a..31b8e9340f 100644
--- a/src/commands/deploy.rs
+++ b/src/commands/deploy.rs
@@ -10,6 +10,7 @@ use hippo_openapi::models::ChannelRevisionSelectionStrategy;
use rand::Rng;
use semver::BuildMetadata;
use sha2::{Digest, Sha256};
+use spin_common::arg_parser::parse_kv;
use spin_loader::bindle::BindleConnectionInfo;
use spin_loader::local::config::RawAppManifest;
use spin_loader::local::{assets, config, parent_dir};
@@ -94,7 +95,8 @@ pub struct DeployCommand {
)]
pub deployment_env_id: Option<String>,
- /// Pass a key/value (key=value) to all components of the application.
+ /// Set a key/value pair (key=value) in the deployed application's
+ /// default store. Any existing value will be overwritten.
/// Can be used multiple times.
#[clap(long = "key-value", parse(try_from_str = parse_kv))]
pub key_values: Vec<(String, String)>,
@@ -871,12 +873,3 @@ fn has_expired(login_connection: &LoginConnection) -> Result<bool> {
None => Ok(false),
}
}
-
-// Parse the key/values passed in as `key=value` pairs.
-fn parse_kv(s: &str) -> Result<(String, String)> {
- let parts: Vec<_> = s.splitn(2, '=').collect();
- if parts.len() != 2 {
- bail!("Key/Values must be of the form `key=value`");
- }
- Ok((parts[0].to_owned(), parts[1].to_owned()))
-}
| 1,442
|
[
"1404"
] |
diff --git a/crates/testing/src/lib.rs b/crates/testing/src/lib.rs
index 3f2aef347b..3c9df07c7d 100644
--- a/crates/testing/src/lib.rs
+++ b/crates/testing/src/lib.rs
@@ -17,7 +17,7 @@ use spin_app::{
AppComponent, Loader,
};
use spin_core::{Component, StoreBuilder};
-use spin_trigger::{RuntimeConfig, TriggerExecutor, TriggerExecutorBuilder};
+use spin_trigger::{HostComponentInitData, RuntimeConfig, TriggerExecutor, TriggerExecutorBuilder};
use spin_trigger_http::{HttpExecutorType, HttpTriggerConfig, WagiTriggerConfig};
use tokio::fs;
@@ -105,7 +105,11 @@ impl HttpTestConfig {
Executor::TriggerConfig: DeserializeOwned,
{
TriggerExecutorBuilder::new(self.build_loader())
- .build(TEST_APP_URI.to_string(), RuntimeConfig::default())
+ .build(
+ TEST_APP_URI.to_string(),
+ RuntimeConfig::default(),
+ HostComponentInitData::default(),
+ )
.await
.unwrap()
}
@@ -141,7 +145,11 @@ impl RedisTestConfig {
self.redis_channel = channel.into();
TriggerExecutorBuilder::new(self.build_loader())
- .build(TEST_APP_URI.to_string(), RuntimeConfig::default())
+ .build(
+ TEST_APP_URI.to_string(),
+ RuntimeConfig::default(),
+ HostComponentInitData::default(),
+ )
.await
.unwrap()
}
|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
40d50862f1d917bf1907081e1f925e84e29d2215
|
Misleading `spin plugin install` error
When the URL to the tarball in a plugin manifest is wrong, the error returned is the following
```
$ spin plugin install -u https://github.com/karthik2804/spin-js-sdk/releases/download/canary/js2wasm.json
Are you sure you want to install plugin 'js2wasm' with license Apache-2.0 from https://github.com/fermyon/spin-js-sdk/releases/download/canary/js2wasm-canary-maAre you sure you want to install plugin 'js2wasm' with license Apache-2.0 from https://github.com/fermyon/spin-js-sdk/releases/download/canary/js2wasm-canary-macos-aarch64.tar.gz? yes
Error: Checksum did not match, aborting installation.
```
The URL is actually wrong and returns a 404.
```
$ curl https://github.com/fermyon/spin-js-sdk/releases/download/canary/js2wasm-canary-macos-aarch64.tar.gz
Not Found%
```
The correct URL is supposed to be
```
https://github.com/karthik2804/spin-js-sdk/releases/download/canary/js2wasm-canary-macos-aarch64.tar.gz
```
|
2023-04-30T22:42:12Z
|
fermyon__spin-1441
|
fermyon/spin
|
3.2
|
diff --git a/crates/plugins/src/manager.rs b/crates/plugins/src/manager.rs
index 10f82660e1..f886e64441 100644
--- a/crates/plugins/src/manager.rs
+++ b/crates/plugins/src/manager.rs
@@ -219,6 +219,13 @@ pub fn get_package(plugin_manifest: &PluginManifest) -> Result<&PluginPackage> {
async fn download_plugin(name: &str, temp_dir: &TempDir, target_url: &str) -> Result<PathBuf> {
log::trace!("Trying to get tar file for plugin '{name}' from {target_url}");
let plugin_bin = reqwest::get(target_url).await?;
+ if !plugin_bin.status().is_success() {
+ match plugin_bin.status() {
+ reqwest::StatusCode::NOT_FOUND => bail!("The download URL specified in the plugin manifest was not found ({target_url} returned HTTP error 404). Please contact the plugin author."),
+ _ => bail!("HTTP error {} when downloading plugin from {target_url}", plugin_bin.status()),
+ }
+ }
+
let mut content = Cursor::new(plugin_bin.bytes().await?);
let dir = temp_dir.path();
let mut plugin_file = dir.join(name);
@@ -247,3 +254,31 @@ fn file_digest_string(path: &Path) -> Result<String> {
let digest_string = format!("{:x}", digest_value);
Ok(digest_string)
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[tokio::test]
+ async fn good_error_when_tarball_404s() -> anyhow::Result<()> {
+ let temp_dir = tempdir()?;
+ let store = PluginStore::new(temp_dir.path());
+ let manager = PluginManager { store };
+
+ let bad_manifest: PluginManifest = serde_json::from_str(include_str!(
+ "../tests/nonexistent-url/nonexistent-url.json"
+ ))?;
+
+ let install_result = manager
+ .install(&bad_manifest, &bad_manifest.packages[0])
+ .await;
+
+ let err = format!("{:#}", install_result.unwrap_err());
+ assert!(
+ err.contains("not found"),
+ "Expected error to contain 'not found' but was '{err}'"
+ );
+
+ Ok(())
+ }
+}
| 1,441
|
[
"1436"
] |
diff --git a/crates/plugins/tests/nonexistent-url/nonexistent-url.json b/crates/plugins/tests/nonexistent-url/nonexistent-url.json
new file mode 100644
index 0000000000..9733792ec3
--- /dev/null
+++ b/crates/plugins/tests/nonexistent-url/nonexistent-url.json
@@ -0,0 +1,14 @@
+{
+ "name": "nonexistent-url",
+ "version": "1.0.0",
+ "spinCompatibility": ">=1.0",
+ "license": "lol snort",
+ "packages": [
+ {
+ "os": "linux",
+ "arch": "amd64",
+ "url": "http://example.com/402f926a-44e3-4d62-93c1-ecc39761afbe",
+ "sha256": "ho ho ho"
+ }
+ ]
+}
|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
|
40d50862f1d917bf1907081e1f925e84e29d2215
|
"No built-in trigger named 'http'" if `trigger.base` is missing
If `base` is missing:
```console
$ spin up
Error: No built-in trigger named 'http', and no plugin named 'trigger-http' was found
```
|
@itowlson Is this a regression from the original external trigger impl?
@lann Could be - I will have a look.
|
2023-04-30T21:40:56Z
|
fermyon__spin-1440
|
fermyon/spin
|
3.2
|
diff --git a/crates/manifest/src/lib.rs b/crates/manifest/src/lib.rs
index 9d7a580c42..a099051e71 100644
--- a/crates/manifest/src/lib.rs
+++ b/crates/manifest/src/lib.rs
@@ -20,6 +20,9 @@ pub enum Error {
/// No 'type' key in trigger declaration.
#[error("the application did not specify a trigger type")]
MissingTriggerType,
+ /// No 'type' key in trigger declaration.
+ #[error("could not load application trigger parameters: {0}")]
+ InvalidTriggerTypeParameters(String),
/// Non-string 'type' key in trigger declaration.
#[error("the trigger type must be a string")]
NonStringTriggerType,
@@ -116,7 +119,7 @@ pub enum ApplicationOrigin {
#[serde(
deny_unknown_fields,
rename_all = "camelCase",
- try_from = "ApplicationTriggerSerialised",
+ try_from = "ApplicationTriggerDeserialised",
into = "ApplicationTriggerSerialised"
)]
pub enum ApplicationTrigger {
@@ -128,12 +131,7 @@ pub enum ApplicationTrigger {
External(ExternalTriggerConfiguration),
}
-/// Serialisation helper - we need all unmatched `trigger.type` values to
-/// map to `ApplicationTrigger::External`, but `#[serde(other)]` can
-/// only be applied to unit types. The following types cause recognised
-/// tags to map to the Internal case and unrecognised ones to the
-/// External case.
-#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
+#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase", untagged)]
enum ApplicationTriggerSerialised {
Internal(InternalApplicationTriggerSerialised),
@@ -141,6 +139,19 @@ enum ApplicationTriggerSerialised {
External(HashMap<String, toml::Value>),
}
+/// Deserialisation helper - we need all unmatched `trigger.type` values to
+/// map to `ApplicationTrigger::External`, but `#[serde(other)]` can
+/// only be applied to unit types. The following types cause recognised
+/// tags to map to the Internal case and unrecognised ones to the
+/// External case.
+#[derive(Deserialize)]
+struct ApplicationTriggerDeserialised {
+ #[serde(rename = "type")]
+ trigger_type: String,
+ #[serde(flatten)]
+ parameters: toml::Value,
+}
+
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, Eq)]
#[serde(deny_unknown_fields, rename_all = "camelCase", tag = "type")]
enum InternalApplicationTriggerSerialised {
@@ -150,29 +161,26 @@ enum InternalApplicationTriggerSerialised {
Redis(RedisTriggerConfiguration),
}
-impl TryFrom<ApplicationTriggerSerialised> for ApplicationTrigger {
+impl TryFrom<ApplicationTriggerDeserialised> for ApplicationTrigger {
type Error = Error;
- fn try_from(value: ApplicationTriggerSerialised) -> Result<Self, Self::Error> {
- match value {
- ApplicationTriggerSerialised::Internal(InternalApplicationTriggerSerialised::Http(
- h,
- )) => Ok(Self::Http(h)),
- ApplicationTriggerSerialised::Internal(
- InternalApplicationTriggerSerialised::Redis(r),
- ) => Ok(Self::Redis(r)),
- ApplicationTriggerSerialised::External(mut map) => match map.remove("type") {
- Some(toml::Value::String(ty)) => {
- let ext_config = ExternalTriggerConfiguration {
- trigger_type: ty,
- parameters: map,
- };
- Ok(Self::External(ext_config))
- }
- Some(_) => Err(Error::NonStringTriggerType),
- None => Err(Error::MissingTriggerType),
- },
- }
+ fn try_from(value: ApplicationTriggerDeserialised) -> Result<Self, Self::Error> {
+ let trigger = match value.trigger_type.as_str() {
+ "http" => ApplicationTrigger::Http(
+ HttpTriggerConfiguration::deserialize(value.parameters)
+ .map_err(|e| Error::InvalidTriggerTypeParameters(e.to_string()))?,
+ ),
+ "redis" => ApplicationTrigger::Redis(
+ RedisTriggerConfiguration::deserialize(value.parameters)
+ .map_err(|e| Error::InvalidTriggerTypeParameters(e.to_string()))?,
+ ),
+ _ => ApplicationTrigger::External(ExternalTriggerConfiguration {
+ trigger_type: value.trigger_type,
+ parameters: HashMap::deserialize(value.parameters)
+ .map_err(|e| Error::InvalidTriggerTypeParameters(e.to_string()))?,
+ }),
+ };
+ Ok(trigger)
}
}
| 1,440
|
[
"1434"
] |
diff --git a/crates/loader/src/local/tests.rs b/crates/loader/src/local/tests.rs
index 2f3446d267..c79f16e829 100644
--- a/crates/loader/src/local/tests.rs
+++ b/crates/loader/src/local/tests.rs
@@ -201,6 +201,21 @@ fn test_unknown_version_is_rejected() {
);
}
+#[tokio::test]
+async fn gives_correct_error_when_missing_app_trigger_field() -> Result<()> {
+ const MANIFEST: &str = "tests/missing-http-base.toml";
+
+ let app = raw_manifest_from_file(&PathBuf::from(MANIFEST)).await;
+
+ let e = format!("{:#}", app.unwrap_err());
+ assert!(
+ e.contains("missing field `base`"),
+ "Expected error to contain trigger field information but was '{e}'"
+ );
+
+ Ok(())
+}
+
#[test]
fn test_wagi_executor_with_custom_entrypoint() -> Result<()> {
const MANIFEST: &str = include_str!("../../tests/wagi-custom-entrypoint.toml");
diff --git a/crates/loader/tests/missing-http-base.toml b/crates/loader/tests/missing-http-base.toml
new file mode 100644
index 0000000000..2d11da7867
--- /dev/null
+++ b/crates/loader/tests/missing-http-base.toml
@@ -0,0 +1,12 @@
+spin_version = "1"
+authors = ["Gul Madred", "Edward Jellico", "JL"]
+description = "A HTTP application without a base"
+name = "missing-http-base"
+trigger = {type = "http"}
+version = "6.11.2"
+
+[[component]]
+id = "test"
+source = "nope/nope/nope"
+[component.trigger]
+route = "/test"
|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
40d50862f1d917bf1907081e1f925e84e29d2215
|
Embedding spin v1.1.0 does not built
## TL;DR
spin `v1.1.0` depends on wasmtime `v7.0.0`, but also depends on `spin-componentize` which depends on wasmtime `v8.0.1`. This makes using spin v1.1.0 as a library unable to built correctly.
## How to repro
Create an empty rust project and add `spin-app = { git = "https://github.com/fermyon/spin", tag = "v1.1.0" }` to `Cargo.toml` and then hit `cargo run`.
## Error message
```shell
(base) ➜ rust-dep git:(main) ✗ cargo build
Updating git repository `https://github.com/fermyon/spin`
Updating crates.io index
Updating git repository `https://github.com/fermyon/spin-componentize`
Updating git submodule `https://github.com/dicej/preview1.wasm`
Updating git submodule `https://github.com/bytecodealliance/preview2-prototyping`
error: failed to select a version for `wasmtime-fiber`.
... required by package `wasmtime v7.0.0`
... which satisfies dependency `wasmtime = "^7.0.0"` of package `spin-core v1.1.0 (https://github.com/fermyon/spin?tag=v1.1.0#28655d57)`
... which satisfies git dependency `spin-core` of package `spin-app v1.1.0 (https://github.com/fermyon/spin?tag=v1.1.0#28655d57)`
... which satisfies git dependency `spin-app` of package `rust-dep v0.1.0 (/Users/mossaka/Developer/rust-playground/rust-dep)`
versions that meet the requirements `=7.0.0` are: 7.0.0
the package `wasmtime-fiber` links to the native library `wasmtime-fiber-shims`, but it conflicts with a previous package which links to `wasmtime-fiber-shims` as well:
package `wasmtime-fiber v8.0.1`
... which satisfies dependency `wasmtime-fiber = "=8.0.1"` of package `wasmtime v8.0.1`
... which satisfies dependency `wasmtime = "^8.0.1"` of package `host v0.0.0 (https://github.com/fermyon/spin-componentize#51c3fade)`
... which satisfies git dependency `wasi-host` of package `spin-core v1.1.0 (https://github.com/fermyon/spin?tag=v1.1.0#28655d57)`
... which satisfies git dependency `spin-core` of package `spin-app v1.1.0 (https://github.com/fermyon/spin?tag=v1.1.0#28655d57)`
... which satisfies git dependency `spin-app` of package `rust-dep v0.1.0 (/Users/mossaka/Developer/rust-playground/rust-dep)`
Only one package in the dependency graph may specify the same links value. This helps ensure that only one copy of a native library is linked in the final binary. Try to adjust your dependencies so that only one package uses the links ='wasmtime-fiber' value. For more information, see https://doc.rust-lang.org/cargo/reference/resolver.html#links.
failed to select a version for `wasmtime-fiber` which could resolve this conflict
```
|
I guess to resolve this issue in the future is to pin `spin-componentize` to a specific rev in spin's `Cargo.toml`
|
2023-04-29T16:50:15Z
|
fermyon__spin-1439
|
fermyon/spin
|
3.2
|
diff --git a/Cargo.lock b/Cargo.lock
index a47fe64565..2b0b26fed4 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -845,18 +845,18 @@ dependencies = [
[[package]]
name = "cranelift-bforest"
-version = "0.94.1"
+version = "0.95.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0853f4732d9557cc1f3b4a97112bd5f00a7c619c9828edb45d0a2389ce2913f9"
+checksum = "1277fbfa94bc82c8ec4af2ded3e639d49ca5f7f3c7eeab2c66accd135ece4e70"
dependencies = [
"cranelift-entity",
]
[[package]]
name = "cranelift-codegen"
-version = "0.94.1"
+version = "0.95.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ed06a9dd2e065be7c1f89cdc820c8c328d2cb69b2be0ba6338fe4050b30bf510"
+checksum = "c6e8c31ad3b2270e9aeec38723888fe1b0ace3bea2b06b3f749ccf46661d3220"
dependencies = [
"bumpalo",
"cranelift-bforest",
@@ -874,33 +874,33 @@ dependencies = [
[[package]]
name = "cranelift-codegen-meta"
-version = "0.94.1"
+version = "0.95.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "416f0e0e34689be78c2689b31374404d21f1c7667431fd7cd29bed0fa8a67ce8"
+checksum = "c8ac5ac30d62b2d66f12651f6b606dbdfd9c2cfd0908de6b387560a277c5c9da"
dependencies = [
"cranelift-codegen-shared",
]
[[package]]
name = "cranelift-codegen-shared"
-version = "0.94.1"
+version = "0.95.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a05c0a89f82c5731ccad8795cd91cc3c771295aa42c268c7f81607388495d374"
+checksum = "dd82b8b376247834b59ed9bdc0ddeb50f517452827d4a11bccf5937b213748b8"
[[package]]
name = "cranelift-entity"
-version = "0.94.1"
+version = "0.95.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f184fc14ff49b119760e5f96d1c836d89ee0f5d1b94073ebe88f45b745a9c7a5"
+checksum = "40099d38061b37e505e63f89bab52199037a72b931ad4868d9089ff7268660b0"
dependencies = [
"serde",
]
[[package]]
name = "cranelift-frontend"
-version = "0.94.1"
+version = "0.95.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1990b107c505d3bb0e9fe7ee9a4180912c924c12da1ebed68230393789387858"
+checksum = "64a25d9d0a0ae3079c463c34115ec59507b4707175454f0eee0891e83e30e82d"
dependencies = [
"cranelift-codegen",
"log",
@@ -910,15 +910,15 @@ dependencies = [
[[package]]
name = "cranelift-isle"
-version = "0.94.1"
+version = "0.95.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e47d398114545d4de2b152c28b1428c840e55764a6b58eea2a0e5c661d9a382a"
+checksum = "80de6a7d0486e4acbd5f9f87ec49912bf4c8fb6aea00087b989685460d4469ba"
[[package]]
name = "cranelift-native"
-version = "0.94.1"
+version = "0.95.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9c769285ed99f5791ca04d9716b3ca3508ec4e7b959759409fddf51ad0481f51"
+checksum = "bb6b03e0e03801c4b3fd8ce0758a94750c07a44e7944cc0ffbf0d3f2e7c79b00"
dependencies = [
"cranelift-codegen",
"libc",
@@ -927,9 +927,9 @@ dependencies = [
[[package]]
name = "cranelift-wasm"
-version = "0.94.1"
+version = "0.95.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e0cbcdec1d7b678919910d213b9e98d5d4c65eeb2153ac042535b00931f093d3"
+checksum = "ff3220489a3d928ad91e59dd7aeaa8b3de18afb554a6211213673a71c90737ac"
dependencies = [
"cranelift-codegen",
"cranelift-entity",
@@ -937,7 +937,7 @@ dependencies = [
"itertools",
"log",
"smallvec",
- "wasmparser 0.100.0",
+ "wasmparser 0.102.0",
"wasmtime-types",
]
@@ -2286,7 +2286,7 @@ dependencies = [
[[package]]
name = "host"
version = "0.0.0"
-source = "git+https://github.com/fermyon/spin-componentize#9e7ec95ccaf490c9b96c03af1c818e8197ccf855"
+source = "git+https://github.com/fermyon/spin-componentize?rev=51c3fade751c4e364142719e42130943fd8b0a76#51c3fade751c4e364142719e42130943fd8b0a76"
dependencies = [
"anyhow",
"async-trait",
@@ -4960,11 +4960,11 @@ dependencies = [
[[package]]
name = "spin-componentize"
version = "0.1.0"
-source = "git+https://github.com/fermyon/spin-componentize#9e7ec95ccaf490c9b96c03af1c818e8197ccf855"
+source = "git+https://github.com/fermyon/spin-componentize?rev=51c3fade751c4e364142719e42130943fd8b0a76#51c3fade751c4e364142719e42130943fd8b0a76"
dependencies = [
"anyhow",
- "wasm-encoder 0.25.0 (registry+https://github.com/rust-lang/crates.io-index)",
- "wasmparser 0.102.0",
+ "wasm-encoder 0.26.0",
+ "wasmparser 0.104.0",
"wit-component",
]
@@ -5002,7 +5002,7 @@ dependencies = [
"tracing",
"wasi-cap-std-sync 0.0.0",
"wasi-common 0.0.0",
- "wasi-common 7.0.0",
+ "wasi-common 8.0.1",
"wasmtime",
"wasmtime-wasi",
]
@@ -5304,7 +5304,7 @@ dependencies = [
"tokio",
"tokio-rustls",
"tracing",
- "wasi-common 7.0.0",
+ "wasi-common 8.0.1",
"wasmtime",
"wasmtime-wasi",
"wit-bindgen-wasmtime",
@@ -6063,7 +6063,7 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]]
name = "wasi-cap-std-sync"
version = "0.0.0"
-source = "git+https://github.com/fermyon/spin-componentize#9e7ec95ccaf490c9b96c03af1c818e8197ccf855"
+source = "git+https://github.com/fermyon/spin-componentize?rev=51c3fade751c4e364142719e42130943fd8b0a76#51c3fade751c4e364142719e42130943fd8b0a76"
dependencies = [
"anyhow",
"async-trait",
@@ -6086,9 +6086,9 @@ dependencies = [
[[package]]
name = "wasi-cap-std-sync"
-version = "7.0.0"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "39c029a2dfc62195f26612e1f9de4c4207e4088ce48f84861229fa268021d1d0"
+checksum = "612510e6c7b6681f7d29ce70ef26e18349c26acd39b7d89f1727d90b7f58b20e"
dependencies = [
"anyhow",
"async-trait",
@@ -6104,14 +6104,14 @@ dependencies = [
"rustix",
"system-interface",
"tracing",
- "wasi-common 7.0.0",
+ "wasi-common 8.0.1",
"windows-sys 0.45.0",
]
[[package]]
name = "wasi-common"
version = "0.0.0"
-source = "git+https://github.com/fermyon/spin-componentize#9e7ec95ccaf490c9b96c03af1c818e8197ccf855"
+source = "git+https://github.com/fermyon/spin-componentize?rev=51c3fade751c4e364142719e42130943fd8b0a76#51c3fade751c4e364142719e42130943fd8b0a76"
dependencies = [
"anyhow",
"async-trait",
@@ -6130,9 +6130,9 @@ dependencies = [
[[package]]
name = "wasi-common"
-version = "7.0.0"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "be54f652e97bf4ffd98368386785ef80a70daf045ee307ec321be51b3ad7370c"
+checksum = "008136464e438c5049a614b6ea1bae9f6c4d354ce9ee2b4d9a1ac6e73f31aafc"
dependencies = [
"anyhow",
"bitflags 1.3.2",
@@ -6150,9 +6150,9 @@ dependencies = [
[[package]]
name = "wasi-tokio"
-version = "7.0.0"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c1ae40212ea8d8f80a7b09abcb5b736fdcc605b1d4394f896eaf592ac9444aef"
+checksum = "c24672bbdac9b6ccd6f19e846bef945f63729abcea4c1c3f0ba725faad055e9d"
dependencies = [
"anyhow",
"cap-std",
@@ -6160,8 +6160,8 @@ dependencies = [
"io-lifetimes",
"rustix",
"tokio",
- "wasi-cap-std-sync 7.0.0",
- "wasi-common 7.0.0",
+ "wasi-cap-std-sync 8.0.1",
+ "wasi-common 8.0.1",
"wiggle",
]
@@ -6231,15 +6231,6 @@ version = "0.2.84"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0046fef7e28c3804e5e38bfa31ea2a0f73905319b677e57ebe37e49358989b5d"
-[[package]]
-name = "wasm-encoder"
-version = "0.23.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1c3e4bc09095436c8e7584d86d33e6c3ee67045af8fb262cbb9cc321de553428"
-dependencies = [
- "leb128",
-]
-
[[package]]
name = "wasm-encoder"
version = "0.25.0"
@@ -6251,22 +6242,24 @@ dependencies = [
[[package]]
name = "wasm-encoder"
-version = "0.25.0"
-source = "git+https://github.com/bytecodealliance/wasm-tools?rev=016838279808be4d257f1b58b9942420f0a09855#016838279808be4d257f1b58b9942420f0a09855"
+version = "0.26.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d05d0b6fcd0aeb98adf16e7975331b3c17222aa815148f5b976370ce589d80ef"
dependencies = [
"leb128",
]
[[package]]
name = "wasm-metadata"
-version = "0.4.0"
-source = "git+https://github.com/bytecodealliance/wasm-tools?rev=016838279808be4d257f1b58b9942420f0a09855#016838279808be4d257f1b58b9942420f0a09855"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dbdef99fafff010c57fabb7bc703f0903ec16fcee49207a22dcc4f78ea44562f"
dependencies = [
"anyhow",
"indexmap",
"serde",
- "wasm-encoder 0.25.0 (git+https://github.com/bytecodealliance/wasm-tools?rev=016838279808be4d257f1b58b9942420f0a09855)",
- "wasmparser 0.103.0",
+ "wasm-encoder 0.26.0",
+ "wasmparser 0.104.0",
]
[[package]]
@@ -6282,16 +6275,6 @@ dependencies = [
"web-sys",
]
-[[package]]
-name = "wasmparser"
-version = "0.100.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "64b20236ab624147dfbb62cf12a19aaf66af0e41b8398838b66e997d07d269d4"
-dependencies = [
- "indexmap",
- "url",
-]
-
[[package]]
name = "wasmparser"
version = "0.102.0"
@@ -6304,8 +6287,9 @@ dependencies = [
[[package]]
name = "wasmparser"
-version = "0.103.0"
-source = "git+https://github.com/bytecodealliance/wasm-tools?rev=016838279808be4d257f1b58b9942420f0a09855#016838279808be4d257f1b58b9942420f0a09855"
+version = "0.104.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6a396af81a7c56ad976131d6a35e4b693b78a1ea0357843bd436b4577e254a7d"
dependencies = [
"indexmap",
"url",
@@ -6323,9 +6307,9 @@ dependencies = [
[[package]]
name = "wasmtime"
-version = "7.0.1"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a15ac4b4bee3bcf3750911c7104cf50f12c6b1055cc491254c508294b019fd79"
+checksum = "f907fdead3153cb9bfb7a93bbd5b62629472dc06dee83605358c64c52ed3dda9"
dependencies = [
"anyhow",
"async-trait",
@@ -6342,7 +6326,7 @@ dependencies = [
"rayon",
"serde",
"target-lexicon",
- "wasmparser 0.100.0",
+ "wasmparser 0.102.0",
"wasmtime-cache",
"wasmtime-component-macro",
"wasmtime-component-util",
@@ -6357,18 +6341,18 @@ dependencies = [
[[package]]
name = "wasmtime-asm-macros"
-version = "7.0.1"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "06f9859a704f6b807a3e2e3466ab727f3f748134a96712d0d27c48ba32b32992"
+checksum = "d3b9daa7c14cd4fa3edbf69de994408d5f4b7b0959ac13fa69d465f6597f810d"
dependencies = [
"cfg-if",
]
[[package]]
name = "wasmtime-cache"
-version = "7.0.1"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a66f6967ff6d89a4aa0abe11a145c7a2538f10d9dca6a0718dba6470166c8182"
+checksum = "c86437fa68626fe896e5afc69234bb2b5894949083586535f200385adfd71213"
dependencies = [
"anyhow",
"base64 0.21.0",
@@ -6386,9 +6370,9 @@ dependencies = [
[[package]]
name = "wasmtime-component-macro"
-version = "7.0.1"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0f851a08ee7b76f74a51d1fd1ce22b139a40beb1792b4f903279c46b568eb1ec"
+checksum = "267096ed7cc93b4ab15d3daa4f195e04dbb7e71c7e5c6457ae7d52e9dd9c3607"
dependencies = [
"anyhow",
"proc-macro2",
@@ -6401,15 +6385,15 @@ dependencies = [
[[package]]
name = "wasmtime-component-util"
-version = "7.0.1"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ddc0e0e733a8d097a137e05d5e7f62376600d32bd89bdc22c002d1826ae5af2e"
+checksum = "74e02ca7a4a3c69d72b88f26f0192e333958df6892415ac9ab84dcc42c9000c2"
[[package]]
name = "wasmtime-cranelift"
-version = "7.0.1"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5f5ce3bc589c19cd055cc5210daaf77288563010f45cce40c58b57182b9b5bdd"
+checksum = "b1cefde0cce8cb700b1b21b6298a3837dba46521affd7b8c38a9ee2c869eee04"
dependencies = [
"anyhow",
"cranelift-codegen",
@@ -6422,15 +6406,31 @@ dependencies = [
"object",
"target-lexicon",
"thiserror",
- "wasmparser 0.100.0",
+ "wasmparser 0.102.0",
+ "wasmtime-cranelift-shared",
+ "wasmtime-environ",
+]
+
+[[package]]
+name = "wasmtime-cranelift-shared"
+version = "8.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cd041e382ef5aea1b9fc78442394f1a4f6d676ce457e7076ca4cb3f397882f8b"
+dependencies = [
+ "anyhow",
+ "cranelift-codegen",
+ "cranelift-native",
+ "gimli",
+ "object",
+ "target-lexicon",
"wasmtime-environ",
]
[[package]]
name = "wasmtime-environ"
-version = "7.0.1"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "78a205f0f0ea33bcb56756718a9a9ca1042614237d6258893c519f6fed593325"
+checksum = "a990198cee4197423045235bf89d3359e69bd2ea031005f4c2d901125955c949"
dependencies = [
"anyhow",
"cranelift-entity",
@@ -6441,8 +6441,8 @@ dependencies = [
"serde",
"target-lexicon",
"thiserror",
- "wasm-encoder 0.23.0",
- "wasmparser 0.100.0",
+ "wasm-encoder 0.25.0",
+ "wasmparser 0.102.0",
"wasmprinter",
"wasmtime-component-util",
"wasmtime-types",
@@ -6450,9 +6450,9 @@ dependencies = [
[[package]]
name = "wasmtime-fiber"
-version = "7.0.1"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d55f4f52b3f26b03e6774f2e6c41c72d4106175c58ddd0b74b4b4a81c1ba702c"
+checksum = "7ab182d5ab6273a133ab88db94d8ca86dc3e57e43d70baaa4d98f94ddbd7d10a"
dependencies = [
"cc",
"cfg-if",
@@ -6463,9 +6463,9 @@ dependencies = [
[[package]]
name = "wasmtime-jit"
-version = "7.0.1"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2b111d642a32c858096a57456e503f6b72abdbd04d15b44e12f329c238802f66"
+checksum = "0de48df552cfca1c9b750002d3e07b45772dd033b0b206d5c0968496abf31244"
dependencies = [
"addr2line",
"anyhow",
@@ -6488,9 +6488,9 @@ dependencies = [
[[package]]
name = "wasmtime-jit-debug"
-version = "7.0.1"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e7da0f3ae2e2cefa9d28f3f11bcf7d956433a60ccb34f359cd8c930e2bf1cf5a"
+checksum = "6e0554b84c15a27d76281d06838aed94e13a77d7bf604bbbaf548aa20eb93846"
dependencies = [
"object",
"once_cell",
@@ -6499,9 +6499,9 @@ dependencies = [
[[package]]
name = "wasmtime-jit-icache-coherence"
-version = "7.0.1"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "52aab5839634bd3b158757b52bb689e04815023f2a83b281d657b3a0f061f7a0"
+checksum = "aecae978b13f7f67efb23bd827373ace4578f2137ec110bbf6a4a7cde4121bbd"
dependencies = [
"cfg-if",
"libc",
@@ -6510,9 +6510,9 @@ dependencies = [
[[package]]
name = "wasmtime-runtime"
-version = "7.0.1"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b738633d1c81b5df6f959757ac529b5c0f69ca917c1cfefac2e114af5c397014"
+checksum = "658cf6f325232b6760e202e5255d823da5e348fdea827eff0a2a22319000b441"
dependencies = [
"anyhow",
"cc",
@@ -6536,26 +6536,26 @@ dependencies = [
[[package]]
name = "wasmtime-types"
-version = "7.0.1"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dc565951214d0707de731561b84457e1200c545437a167f232e150c496295c6e"
+checksum = "a4f6fffd2a1011887d57f07654dd112791e872e3ff4a2e626aee8059ee17f06f"
dependencies = [
"cranelift-entity",
"serde",
"thiserror",
- "wasmparser 0.100.0",
+ "wasmparser 0.102.0",
]
[[package]]
name = "wasmtime-wasi"
-version = "7.0.0"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dc41b56ec1c032e4bb67cf0fe0b36443f7a8be341abce2e5ec9cc8ac6ef4bee0"
+checksum = "4a3b5cb7606625ec229f0e33394a1637b34a58ad438526eba859b5fdb422ac1e"
dependencies = [
"anyhow",
"libc",
- "wasi-cap-std-sync 7.0.0",
- "wasi-common 7.0.0",
+ "wasi-cap-std-sync 8.0.1",
+ "wasi-common 8.0.1",
"wasi-tokio",
"wasmtime",
"wiggle",
@@ -6563,9 +6563,9 @@ dependencies = [
[[package]]
name = "wasmtime-wit-bindgen"
-version = "7.0.1"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0e1f2a35ff0a64ae07d4fcfd7c9b745e517be00ddb9991f8e2ad2c913cc11094"
+checksum = "983db9cc294d1adaa892a53ff6a0dc6605fc0ab1a4da5d8a2d2d4bde871ff7dd"
dependencies = [
"anyhow",
"heck 0.4.1",
@@ -6590,7 +6590,7 @@ dependencies = [
"leb128",
"memchr",
"unicode-width",
- "wasm-encoder 0.25.0 (registry+https://github.com/rust-lang/crates.io-index)",
+ "wasm-encoder 0.25.0",
]
[[package]]
@@ -6689,9 +6689,9 @@ dependencies = [
[[package]]
name = "wiggle"
-version = "7.0.0"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "43991a6d0a435642831e40de3e412eb96950f1c9c72289e486db469ff7c4e53c"
+checksum = "6b16a7462893c46c6d3dd2a1f99925953bdbb921080606e1a4c9344864492fa4"
dependencies = [
"anyhow",
"async-trait",
@@ -6704,9 +6704,9 @@ dependencies = [
[[package]]
name = "wiggle-generate"
-version = "7.0.0"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "424062dad40b2020239ae2de27c962b5dfa6f36b9fe4ddfc3bcff3d5917d078f"
+checksum = "489499e186ab24c8ac6d89e9934c54ced6f19bd473730e6a74f533bd67ecd905"
dependencies = [
"anyhow",
"heck 0.4.1",
@@ -6719,9 +6719,9 @@ dependencies = [
[[package]]
name = "wiggle-macro"
-version = "7.0.0"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7dc0c6a4cbe4f073e7e24c0452fc58c2775574f3b8c89703148d6308d2531b16"
+checksum = "e9142e7fce24a4344c85a43c8b719ef434fc6155223bade553e186cb4183b6cc"
dependencies = [
"proc-macro2",
"quote",
@@ -6879,37 +6879,37 @@ dependencies = [
[[package]]
name = "wit-bindgen-gen-core"
version = "0.2.0"
-source = "git+https://github.com/bytecodealliance/wit-bindgen?rev=cb871cfa1ee460b51eb1d144b175b9aab9c50aba#cb871cfa1ee460b51eb1d144b175b9aab9c50aba"
+source = "git+https://github.com/fermyon/wit-bindgen-backport?rev=ba1636af0338623b54db84e2224be9a124e231f6#ba1636af0338623b54db84e2224be9a124e231f6"
dependencies = [
"anyhow",
- "wit-parser 0.2.0 (git+https://github.com/bytecodealliance/wit-bindgen?rev=cb871cfa1ee460b51eb1d144b175b9aab9c50aba)",
+ "wit-parser 0.2.0 (git+https://github.com/fermyon/wit-bindgen-backport?rev=ba1636af0338623b54db84e2224be9a124e231f6)",
]
[[package]]
name = "wit-bindgen-gen-core"
version = "0.2.0"
-source = "git+https://github.com/fermyon/wit-bindgen-backport?rev=e1e2525bbbc8430c4ebe57e9f4b3f63b6facff98#e1e2525bbbc8430c4ebe57e9f4b3f63b6facff98"
+source = "git+https://github.com/bytecodealliance/wit-bindgen?rev=cb871cfa1ee460b51eb1d144b175b9aab9c50aba#cb871cfa1ee460b51eb1d144b175b9aab9c50aba"
dependencies = [
"anyhow",
- "wit-parser 0.2.0 (git+https://github.com/fermyon/wit-bindgen-backport?rev=e1e2525bbbc8430c4ebe57e9f4b3f63b6facff98)",
+ "wit-parser 0.2.0 (git+https://github.com/bytecodealliance/wit-bindgen?rev=cb871cfa1ee460b51eb1d144b175b9aab9c50aba)",
]
[[package]]
name = "wit-bindgen-gen-rust"
version = "0.2.0"
-source = "git+https://github.com/bytecodealliance/wit-bindgen?rev=cb871cfa1ee460b51eb1d144b175b9aab9c50aba#cb871cfa1ee460b51eb1d144b175b9aab9c50aba"
+source = "git+https://github.com/fermyon/wit-bindgen-backport?rev=ba1636af0338623b54db84e2224be9a124e231f6#ba1636af0338623b54db84e2224be9a124e231f6"
dependencies = [
"heck 0.3.3",
- "wit-bindgen-gen-core 0.2.0 (git+https://github.com/bytecodealliance/wit-bindgen?rev=cb871cfa1ee460b51eb1d144b175b9aab9c50aba)",
+ "wit-bindgen-gen-core 0.2.0 (git+https://github.com/fermyon/wit-bindgen-backport?rev=ba1636af0338623b54db84e2224be9a124e231f6)",
]
[[package]]
name = "wit-bindgen-gen-rust"
version = "0.2.0"
-source = "git+https://github.com/fermyon/wit-bindgen-backport?rev=e1e2525bbbc8430c4ebe57e9f4b3f63b6facff98#e1e2525bbbc8430c4ebe57e9f4b3f63b6facff98"
+source = "git+https://github.com/bytecodealliance/wit-bindgen?rev=cb871cfa1ee460b51eb1d144b175b9aab9c50aba#cb871cfa1ee460b51eb1d144b175b9aab9c50aba"
dependencies = [
"heck 0.3.3",
- "wit-bindgen-gen-core 0.2.0 (git+https://github.com/fermyon/wit-bindgen-backport?rev=e1e2525bbbc8430c4ebe57e9f4b3f63b6facff98)",
+ "wit-bindgen-gen-core 0.2.0 (git+https://github.com/bytecodealliance/wit-bindgen?rev=cb871cfa1ee460b51eb1d144b175b9aab9c50aba)",
]
[[package]]
@@ -6925,11 +6925,11 @@ dependencies = [
[[package]]
name = "wit-bindgen-gen-wasmtime"
version = "0.2.0"
-source = "git+https://github.com/fermyon/wit-bindgen-backport?rev=e1e2525bbbc8430c4ebe57e9f4b3f63b6facff98#e1e2525bbbc8430c4ebe57e9f4b3f63b6facff98"
+source = "git+https://github.com/fermyon/wit-bindgen-backport?rev=ba1636af0338623b54db84e2224be9a124e231f6#ba1636af0338623b54db84e2224be9a124e231f6"
dependencies = [
"heck 0.3.3",
- "wit-bindgen-gen-core 0.2.0 (git+https://github.com/fermyon/wit-bindgen-backport?rev=e1e2525bbbc8430c4ebe57e9f4b3f63b6facff98)",
- "wit-bindgen-gen-rust 0.2.0 (git+https://github.com/fermyon/wit-bindgen-backport?rev=e1e2525bbbc8430c4ebe57e9f4b3f63b6facff98)",
+ "wit-bindgen-gen-core 0.2.0 (git+https://github.com/fermyon/wit-bindgen-backport?rev=ba1636af0338623b54db84e2224be9a124e231f6)",
+ "wit-bindgen-gen-rust 0.2.0 (git+https://github.com/fermyon/wit-bindgen-backport?rev=ba1636af0338623b54db84e2224be9a124e231f6)",
]
[[package]]
@@ -6956,7 +6956,7 @@ dependencies = [
[[package]]
name = "wit-bindgen-wasmtime"
version = "0.2.0"
-source = "git+https://github.com/fermyon/wit-bindgen-backport?rev=e1e2525bbbc8430c4ebe57e9f4b3f63b6facff98#e1e2525bbbc8430c4ebe57e9f4b3f63b6facff98"
+source = "git+https://github.com/fermyon/wit-bindgen-backport?rev=ba1636af0338623b54db84e2224be9a124e231f6#ba1636af0338623b54db84e2224be9a124e231f6"
dependencies = [
"anyhow",
"async-trait",
@@ -6969,34 +6969,35 @@ dependencies = [
[[package]]
name = "wit-bindgen-wasmtime-impl"
version = "0.2.0"
-source = "git+https://github.com/fermyon/wit-bindgen-backport?rev=e1e2525bbbc8430c4ebe57e9f4b3f63b6facff98#e1e2525bbbc8430c4ebe57e9f4b3f63b6facff98"
+source = "git+https://github.com/fermyon/wit-bindgen-backport?rev=ba1636af0338623b54db84e2224be9a124e231f6#ba1636af0338623b54db84e2224be9a124e231f6"
dependencies = [
"proc-macro2",
"syn 1.0.109",
- "wit-bindgen-gen-core 0.2.0 (git+https://github.com/fermyon/wit-bindgen-backport?rev=e1e2525bbbc8430c4ebe57e9f4b3f63b6facff98)",
+ "wit-bindgen-gen-core 0.2.0 (git+https://github.com/fermyon/wit-bindgen-backport?rev=ba1636af0338623b54db84e2224be9a124e231f6)",
"wit-bindgen-gen-wasmtime",
]
[[package]]
name = "wit-component"
-version = "0.8.1"
-source = "git+https://github.com/bytecodealliance/wasm-tools?rev=016838279808be4d257f1b58b9942420f0a09855#016838279808be4d257f1b58b9942420f0a09855"
+version = "0.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e291ff83cb9c8e59963cc6922bdda77ed8f5517d6835f0c98070c4e7f1ae4996"
dependencies = [
"anyhow",
"bitflags 1.3.2",
"indexmap",
"log",
"url",
- "wasm-encoder 0.25.0 (git+https://github.com/bytecodealliance/wasm-tools?rev=016838279808be4d257f1b58b9942420f0a09855)",
+ "wasm-encoder 0.26.0",
"wasm-metadata",
- "wasmparser 0.103.0",
- "wit-parser 0.7.0",
+ "wasmparser 0.104.0",
+ "wit-parser 0.7.1",
]
[[package]]
name = "wit-parser"
version = "0.2.0"
-source = "git+https://github.com/bytecodealliance/wit-bindgen?rev=cb871cfa1ee460b51eb1d144b175b9aab9c50aba#cb871cfa1ee460b51eb1d144b175b9aab9c50aba"
+source = "git+https://github.com/fermyon/wit-bindgen-backport?rev=ba1636af0338623b54db84e2224be9a124e231f6#ba1636af0338623b54db84e2224be9a124e231f6"
dependencies = [
"anyhow",
"id-arena",
@@ -7008,7 +7009,7 @@ dependencies = [
[[package]]
name = "wit-parser"
version = "0.2.0"
-source = "git+https://github.com/fermyon/wit-bindgen-backport?rev=e1e2525bbbc8430c4ebe57e9f4b3f63b6facff98#e1e2525bbbc8430c4ebe57e9f4b3f63b6facff98"
+source = "git+https://github.com/bytecodealliance/wit-bindgen?rev=cb871cfa1ee460b51eb1d144b175b9aab9c50aba#cb871cfa1ee460b51eb1d144b175b9aab9c50aba"
dependencies = [
"anyhow",
"id-arena",
@@ -7034,8 +7035,9 @@ dependencies = [
[[package]]
name = "wit-parser"
-version = "0.7.0"
-source = "git+https://github.com/bytecodealliance/wasm-tools?rev=016838279808be4d257f1b58b9942420f0a09855#016838279808be4d257f1b58b9942420f0a09855"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5ca2581061573ef6d1754983d7a9b3ed5871ef859d52708ea9a0f5af32919172"
dependencies = [
"anyhow",
"id-arena",
diff --git a/Cargo.toml b/Cargo.toml
index ec87ef0dd4..e62c48d951 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -125,13 +125,13 @@ members = [
[workspace.dependencies]
tracing = { version = "0.1", features = ["log"] }
-wasmtime-wasi = { version = "7.0.0", features = ["tokio"] }
-wasi-common-preview1 = { package = "wasi-common", version = "7.0.0" }
-wasmtime = { version = "7.0.1", features = ["component-model"] }
-spin-componentize = { git = "https://github.com/fermyon/spin-componentize" }
-wasi-host = { package = "host", git = "https://github.com/fermyon/spin-componentize" }
-wasi-common = { git = "https://github.com/fermyon/spin-componentize" }
-wasi-cap-std-sync = { git = "https://github.com/fermyon/spin-componentize" }
+wasmtime-wasi = { version = "8.0.1", features = ["tokio"] }
+wasi-common-preview1 = { package = "wasi-common", version = "8.0.1" }
+wasmtime = { version = "8.0.1", features = ["component-model"] }
+spin-componentize = { git = "https://github.com/fermyon/spin-componentize", rev = "51c3fade751c4e364142719e42130943fd8b0a76" }
+wasi-host = { package = "host", git = "https://github.com/fermyon/spin-componentize", rev = "51c3fade751c4e364142719e42130943fd8b0a76" }
+wasi-common = { git = "https://github.com/fermyon/spin-componentize", rev = "51c3fade751c4e364142719e42130943fd8b0a76" }
+wasi-cap-std-sync = { git = "https://github.com/fermyon/spin-componentize", rev = "51c3fade751c4e364142719e42130943fd8b0a76" }
[workspace.dependencies.bindle]
git = "https://github.com/fermyon/bindle"
@@ -141,7 +141,7 @@ features = ["client"]
[workspace.dependencies.wit-bindgen-wasmtime]
git = "https://github.com/fermyon/wit-bindgen-backport"
-rev = "e1e2525bbbc8430c4ebe57e9f4b3f63b6facff98"
+rev = "ba1636af0338623b54db84e2224be9a124e231f6"
features = ["async"]
[[bin]]
diff --git a/examples/spin-timer/Cargo.lock b/examples/spin-timer/Cargo.lock
index e6bdc83d5a..17b78a74aa 100644
--- a/examples/spin-timer/Cargo.lock
+++ b/examples/spin-timer/Cargo.lock
@@ -640,18 +640,18 @@ dependencies = [
[[package]]
name = "cranelift-bforest"
-version = "0.94.0"
+version = "0.95.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "862eb053fc21f991db27c73bc51494fe77aadfa09ea257cb43b62a2656fd4cc1"
+checksum = "1277fbfa94bc82c8ec4af2ded3e639d49ca5f7f3c7eeab2c66accd135ece4e70"
dependencies = [
"cranelift-entity",
]
[[package]]
name = "cranelift-codegen"
-version = "0.94.0"
+version = "0.95.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "038a74bc85da2f6f9e237c51b7998b47229c0f9da69b4c6b0590cf6621c45d46"
+checksum = "c6e8c31ad3b2270e9aeec38723888fe1b0ace3bea2b06b3f749ccf46661d3220"
dependencies = [
"bumpalo",
"cranelift-bforest",
@@ -669,33 +669,33 @@ dependencies = [
[[package]]
name = "cranelift-codegen-meta"
-version = "0.94.0"
+version = "0.95.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c7fb720a7955cf7cc92c58f3896952589062e6f12d8eb35ef4337e708ed2e738"
+checksum = "c8ac5ac30d62b2d66f12651f6b606dbdfd9c2cfd0908de6b387560a277c5c9da"
dependencies = [
"cranelift-codegen-shared",
]
[[package]]
name = "cranelift-codegen-shared"
-version = "0.94.0"
+version = "0.95.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c0954f9426cf0fa7ad57910ea5822a09c5da590222a767a6c38080a8534a0af8"
+checksum = "dd82b8b376247834b59ed9bdc0ddeb50f517452827d4a11bccf5937b213748b8"
[[package]]
name = "cranelift-entity"
-version = "0.94.0"
+version = "0.95.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "68c7096c1a66cfa73899645f0a46a6f5c91641e678eeafb0fc47a19ab34069ca"
+checksum = "40099d38061b37e505e63f89bab52199037a72b931ad4868d9089ff7268660b0"
dependencies = [
"serde",
]
[[package]]
name = "cranelift-frontend"
-version = "0.94.0"
+version = "0.95.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "697f2fdaceb228fea413ea91baa7c6b8533fc2e61ac5a08db7acc1b31e673a2a"
+checksum = "64a25d9d0a0ae3079c463c34115ec59507b4707175454f0eee0891e83e30e82d"
dependencies = [
"cranelift-codegen",
"log",
@@ -705,15 +705,15 @@ dependencies = [
[[package]]
name = "cranelift-isle"
-version = "0.94.0"
+version = "0.95.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f41037f4863e0c6716dbe60e551d501f4197383cb43d75038c0170159fc8fb5b"
+checksum = "80de6a7d0486e4acbd5f9f87ec49912bf4c8fb6aea00087b989685460d4469ba"
[[package]]
name = "cranelift-native"
-version = "0.94.0"
+version = "0.95.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "797c6e5643eb654bb7bf496f1f03518323a89b937b84020b786620f910364a52"
+checksum = "bb6b03e0e03801c4b3fd8ce0758a94750c07a44e7944cc0ffbf0d3f2e7c79b00"
dependencies = [
"cranelift-codegen",
"libc",
@@ -722,9 +722,9 @@ dependencies = [
[[package]]
name = "cranelift-wasm"
-version = "0.94.0"
+version = "0.95.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "69b5fae12cefda3a2c43837e562dd525ab1d75b27989eece66de5b2c8fe120f9"
+checksum = "ff3220489a3d928ad91e59dd7aeaa8b3de18afb554a6211213673a71c90737ac"
dependencies = [
"cranelift-codegen",
"cranelift-entity",
@@ -732,7 +732,7 @@ dependencies = [
"itertools",
"log",
"smallvec",
- "wasmparser 0.100.0",
+ "wasmparser 0.102.0",
"wasmtime-types",
]
@@ -1541,7 +1541,7 @@ dependencies = [
[[package]]
name = "host"
version = "0.0.0"
-source = "git+https://github.com/fermyon/spin-componentize#df2c3ef7dc518cae7d0daedc2037aebf7ee718cb"
+source = "git+https://github.com/fermyon/spin-componentize?rev=51c3fade751c4e364142719e42130943fd8b0a76#51c3fade751c4e364142719e42130943fd8b0a76"
dependencies = [
"anyhow",
"async-trait",
@@ -3430,11 +3430,11 @@ dependencies = [
[[package]]
name = "spin-componentize"
version = "0.1.0"
-source = "git+https://github.com/fermyon/spin-componentize#df2c3ef7dc518cae7d0daedc2037aebf7ee718cb"
+source = "git+https://github.com/fermyon/spin-componentize?rev=51c3fade751c4e364142719e42130943fd8b0a76#51c3fade751c4e364142719e42130943fd8b0a76"
dependencies = [
"anyhow",
- "wasm-encoder 0.25.0 (registry+https://github.com/rust-lang/crates.io-index)",
- "wasmparser 0.102.0 (registry+https://github.com/rust-lang/crates.io-index)",
+ "wasm-encoder 0.26.0",
+ "wasmparser 0.104.0",
"wit-component",
]
@@ -3468,7 +3468,7 @@ dependencies = [
"tracing",
"wasi-cap-std-sync 0.0.0",
"wasi-common 0.0.0",
- "wasi-common 7.0.0",
+ "wasi-common 8.0.1",
"wasmtime",
"wasmtime-wasi",
]
@@ -4159,7 +4159,7 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]]
name = "wasi-cap-std-sync"
version = "0.0.0"
-source = "git+https://github.com/fermyon/spin-componentize#df2c3ef7dc518cae7d0daedc2037aebf7ee718cb"
+source = "git+https://github.com/fermyon/spin-componentize?rev=51c3fade751c4e364142719e42130943fd8b0a76#51c3fade751c4e364142719e42130943fd8b0a76"
dependencies = [
"anyhow",
"async-trait",
@@ -4182,9 +4182,9 @@ dependencies = [
[[package]]
name = "wasi-cap-std-sync"
-version = "7.0.0"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "39c029a2dfc62195f26612e1f9de4c4207e4088ce48f84861229fa268021d1d0"
+checksum = "612510e6c7b6681f7d29ce70ef26e18349c26acd39b7d89f1727d90b7f58b20e"
dependencies = [
"anyhow",
"async-trait",
@@ -4200,14 +4200,14 @@ dependencies = [
"rustix",
"system-interface",
"tracing",
- "wasi-common 7.0.0",
+ "wasi-common 8.0.1",
"windows-sys 0.45.0",
]
[[package]]
name = "wasi-common"
version = "0.0.0"
-source = "git+https://github.com/fermyon/spin-componentize#df2c3ef7dc518cae7d0daedc2037aebf7ee718cb"
+source = "git+https://github.com/fermyon/spin-componentize?rev=51c3fade751c4e364142719e42130943fd8b0a76#51c3fade751c4e364142719e42130943fd8b0a76"
dependencies = [
"anyhow",
"async-trait",
@@ -4226,9 +4226,9 @@ dependencies = [
[[package]]
name = "wasi-common"
-version = "7.0.0"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "be54f652e97bf4ffd98368386785ef80a70daf045ee307ec321be51b3ad7370c"
+checksum = "008136464e438c5049a614b6ea1bae9f6c4d354ce9ee2b4d9a1ac6e73f31aafc"
dependencies = [
"anyhow",
"bitflags 1.3.2",
@@ -4246,9 +4246,9 @@ dependencies = [
[[package]]
name = "wasi-tokio"
-version = "7.0.0"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c1ae40212ea8d8f80a7b09abcb5b736fdcc605b1d4394f896eaf592ac9444aef"
+checksum = "c24672bbdac9b6ccd6f19e846bef945f63729abcea4c1c3f0ba725faad055e9d"
dependencies = [
"anyhow",
"cap-std",
@@ -4256,8 +4256,8 @@ dependencies = [
"io-lifetimes",
"rustix",
"tokio",
- "wasi-cap-std-sync 7.0.0",
- "wasi-common 7.0.0",
+ "wasi-cap-std-sync 8.0.1",
+ "wasi-common 8.0.1",
"wiggle",
]
@@ -4327,15 +4327,6 @@ version = "0.2.83"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c38c045535d93ec4f0b4defec448e4291638ee608530863b1e2ba115d4fff7f"
-[[package]]
-name = "wasm-encoder"
-version = "0.23.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1c3e4bc09095436c8e7584d86d33e6c3ee67045af8fb262cbb9cc321de553428"
-dependencies = [
- "leb128",
-]
-
[[package]]
name = "wasm-encoder"
version = "0.25.0"
@@ -4347,22 +4338,24 @@ dependencies = [
[[package]]
name = "wasm-encoder"
-version = "0.25.0"
-source = "git+https://github.com/bytecodealliance/wasm-tools?rev=1e0052974277b3cce6c3703386e4e90291da2b24#1e0052974277b3cce6c3703386e4e90291da2b24"
+version = "0.26.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d05d0b6fcd0aeb98adf16e7975331b3c17222aa815148f5b976370ce589d80ef"
dependencies = [
"leb128",
]
[[package]]
name = "wasm-metadata"
-version = "0.3.1"
-source = "git+https://github.com/bytecodealliance/wasm-tools?rev=1e0052974277b3cce6c3703386e4e90291da2b24#1e0052974277b3cce6c3703386e4e90291da2b24"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dbdef99fafff010c57fabb7bc703f0903ec16fcee49207a22dcc4f78ea44562f"
dependencies = [
"anyhow",
"indexmap",
"serde",
- "wasm-encoder 0.25.0 (git+https://github.com/bytecodealliance/wasm-tools?rev=1e0052974277b3cce6c3703386e4e90291da2b24)",
- "wasmparser 0.102.0 (git+https://github.com/bytecodealliance/wasm-tools?rev=1e0052974277b3cce6c3703386e4e90291da2b24)",
+ "wasm-encoder 0.26.0",
+ "wasmparser 0.104.0",
]
[[package]]
@@ -4378,16 +4371,6 @@ dependencies = [
"web-sys",
]
-[[package]]
-name = "wasmparser"
-version = "0.100.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "64b20236ab624147dfbb62cf12a19aaf66af0e41b8398838b66e997d07d269d4"
-dependencies = [
- "indexmap",
- "url",
-]
-
[[package]]
name = "wasmparser"
version = "0.102.0"
@@ -4400,8 +4383,9 @@ dependencies = [
[[package]]
name = "wasmparser"
-version = "0.102.0"
-source = "git+https://github.com/bytecodealliance/wasm-tools?rev=1e0052974277b3cce6c3703386e4e90291da2b24#1e0052974277b3cce6c3703386e4e90291da2b24"
+version = "0.104.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6a396af81a7c56ad976131d6a35e4b693b78a1ea0357843bd436b4577e254a7d"
dependencies = [
"indexmap",
"url",
@@ -4414,14 +4398,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2dc17ae63836d010a2bf001c26a5fedbb9a05e5f71117fb63e0ab878bfbe1ca3"
dependencies = [
"anyhow",
- "wasmparser 0.102.0 (registry+https://github.com/rust-lang/crates.io-index)",
+ "wasmparser 0.102.0",
]
[[package]]
name = "wasmtime"
-version = "7.0.0"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d137f87df6e037b2bcb960c2db7ea174e04fb897051380c14b5e5475a870669e"
+checksum = "f907fdead3153cb9bfb7a93bbd5b62629472dc06dee83605358c64c52ed3dda9"
dependencies = [
"anyhow",
"async-trait",
@@ -4438,7 +4422,7 @@ dependencies = [
"rayon",
"serde",
"target-lexicon",
- "wasmparser 0.100.0",
+ "wasmparser 0.102.0",
"wasmtime-cache",
"wasmtime-component-macro",
"wasmtime-component-util",
@@ -4453,18 +4437,18 @@ dependencies = [
[[package]]
name = "wasmtime-asm-macros"
-version = "7.0.0"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ad63d4175d6af44af2046186c87deae4e9a8150b92de2d4809c6f745d5ee9b38"
+checksum = "d3b9daa7c14cd4fa3edbf69de994408d5f4b7b0959ac13fa69d465f6597f810d"
dependencies = [
"cfg-if",
]
[[package]]
name = "wasmtime-cache"
-version = "7.0.0"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f3055fb327f795b4639f47b9dadad9d3d9b185fd3001adf8db08f5fa06d07032"
+checksum = "c86437fa68626fe896e5afc69234bb2b5894949083586535f200385adfd71213"
dependencies = [
"anyhow",
"base64 0.21.0",
@@ -4482,9 +4466,9 @@ dependencies = [
[[package]]
name = "wasmtime-component-macro"
-version = "7.0.0"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "64cf4906f990d6ab3065d042cf5a15eb7a2a5406d1c001a45ab9615de876458a"
+checksum = "267096ed7cc93b4ab15d3daa4f195e04dbb7e71c7e5c6457ae7d52e9dd9c3607"
dependencies = [
"anyhow",
"proc-macro2",
@@ -4492,20 +4476,20 @@ dependencies = [
"syn 1.0.107",
"wasmtime-component-util",
"wasmtime-wit-bindgen",
- "wit-parser 0.6.4 (registry+https://github.com/rust-lang/crates.io-index)",
+ "wit-parser 0.6.4",
]
[[package]]
name = "wasmtime-component-util"
-version = "7.0.0"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "22ccf49c18c1ce3f682310e642dcdc00ffc67f1ce0767c89a16fc8fcf5eaeb97"
+checksum = "74e02ca7a4a3c69d72b88f26f0192e333958df6892415ac9ab84dcc42c9000c2"
[[package]]
name = "wasmtime-cranelift"
-version = "7.0.0"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "274590ecbb1179d45a5c8d9f54b9d236e9414d9ca3b861cd8956cec085508eb0"
+checksum = "b1cefde0cce8cb700b1b21b6298a3837dba46521affd7b8c38a9ee2c869eee04"
dependencies = [
"anyhow",
"cranelift-codegen",
@@ -4518,15 +4502,31 @@ dependencies = [
"object",
"target-lexicon",
"thiserror",
- "wasmparser 0.100.0",
+ "wasmparser 0.102.0",
+ "wasmtime-cranelift-shared",
+ "wasmtime-environ",
+]
+
+[[package]]
+name = "wasmtime-cranelift-shared"
+version = "8.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cd041e382ef5aea1b9fc78442394f1a4f6d676ce457e7076ca4cb3f397882f8b"
+dependencies = [
+ "anyhow",
+ "cranelift-codegen",
+ "cranelift-native",
+ "gimli",
+ "object",
+ "target-lexicon",
"wasmtime-environ",
]
[[package]]
name = "wasmtime-environ"
-version = "7.0.0"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "05b4a897e6ce1f2567ba98e7b1948c0e12cae1202fd88e7639f901b8ce9203f7"
+checksum = "a990198cee4197423045235bf89d3359e69bd2ea031005f4c2d901125955c949"
dependencies = [
"anyhow",
"cranelift-entity",
@@ -4537,8 +4537,8 @@ dependencies = [
"serde",
"target-lexicon",
"thiserror",
- "wasm-encoder 0.23.0",
- "wasmparser 0.100.0",
+ "wasm-encoder 0.25.0",
+ "wasmparser 0.102.0",
"wasmprinter",
"wasmtime-component-util",
"wasmtime-types",
@@ -4546,9 +4546,9 @@ dependencies = [
[[package]]
name = "wasmtime-fiber"
-version = "7.0.0"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "01b1192624694399f601de28db78975ed20fa859da8e048bf8250bd3b38d302b"
+checksum = "7ab182d5ab6273a133ab88db94d8ca86dc3e57e43d70baaa4d98f94ddbd7d10a"
dependencies = [
"cc",
"cfg-if",
@@ -4559,9 +4559,9 @@ dependencies = [
[[package]]
name = "wasmtime-jit"
-version = "7.0.0"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f3f035bfe27ce5129c9d081d6288480f2e6ae9d16d0eb035a5d9e3b5b6c36658"
+checksum = "0de48df552cfca1c9b750002d3e07b45772dd033b0b206d5c0968496abf31244"
dependencies = [
"addr2line",
"anyhow",
@@ -4584,9 +4584,9 @@ dependencies = [
[[package]]
name = "wasmtime-jit-debug"
-version = "7.0.0"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "17e35d335dd2461c631ba24d2326d993bd3a4bdb4b0217e5bda4f518ba0e29f3"
+checksum = "6e0554b84c15a27d76281d06838aed94e13a77d7bf604bbbaf548aa20eb93846"
dependencies = [
"object",
"once_cell",
@@ -4595,9 +4595,9 @@ dependencies = [
[[package]]
name = "wasmtime-jit-icache-coherence"
-version = "7.0.0"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4c8c01a070f55343f7afd309a9609c12378548b26c3f53c599bc711bb1ce42ee"
+checksum = "aecae978b13f7f67efb23bd827373ace4578f2137ec110bbf6a4a7cde4121bbd"
dependencies = [
"cfg-if",
"libc",
@@ -4606,9 +4606,9 @@ dependencies = [
[[package]]
name = "wasmtime-runtime"
-version = "7.0.0"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1ac02cc14c8247f6e4e48c7653a79c226babac8f2cacdd933d3f15ca2a6ab20b"
+checksum = "658cf6f325232b6760e202e5255d823da5e348fdea827eff0a2a22319000b441"
dependencies = [
"anyhow",
"cc",
@@ -4632,26 +4632,26 @@ dependencies = [
[[package]]
name = "wasmtime-types"
-version = "7.0.0"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c8dc0062ab053e1aa22d2355a2de4df482a0007fecae82ea02cc596c2329971d"
+checksum = "a4f6fffd2a1011887d57f07654dd112791e872e3ff4a2e626aee8059ee17f06f"
dependencies = [
"cranelift-entity",
"serde",
"thiserror",
- "wasmparser 0.100.0",
+ "wasmparser 0.102.0",
]
[[package]]
name = "wasmtime-wasi"
-version = "7.0.0"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dc41b56ec1c032e4bb67cf0fe0b36443f7a8be341abce2e5ec9cc8ac6ef4bee0"
+checksum = "4a3b5cb7606625ec229f0e33394a1637b34a58ad438526eba859b5fdb422ac1e"
dependencies = [
"anyhow",
"libc",
- "wasi-cap-std-sync 7.0.0",
- "wasi-common 7.0.0",
+ "wasi-cap-std-sync 8.0.1",
+ "wasi-common 8.0.1",
"wasi-tokio",
"wasmtime",
"wiggle",
@@ -4659,13 +4659,13 @@ dependencies = [
[[package]]
name = "wasmtime-wit-bindgen"
-version = "7.0.0"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fd2cf93f3c8a6f443d8a9098fddc5fd887783c0fe725dc10c54ca9280546421d"
+checksum = "983db9cc294d1adaa892a53ff6a0dc6605fc0ab1a4da5d8a2d2d4bde871ff7dd"
dependencies = [
"anyhow",
"heck 0.4.0",
- "wit-parser 0.6.4 (registry+https://github.com/rust-lang/crates.io-index)",
+ "wit-parser 0.6.4",
]
[[package]]
@@ -4686,7 +4686,7 @@ dependencies = [
"leb128",
"memchr",
"unicode-width",
- "wasm-encoder 0.25.0 (registry+https://github.com/rust-lang/crates.io-index)",
+ "wasm-encoder 0.25.0",
]
[[package]]
@@ -4729,9 +4729,9 @@ dependencies = [
[[package]]
name = "wiggle"
-version = "7.0.0"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "43991a6d0a435642831e40de3e412eb96950f1c9c72289e486db469ff7c4e53c"
+checksum = "6b16a7462893c46c6d3dd2a1f99925953bdbb921080606e1a4c9344864492fa4"
dependencies = [
"anyhow",
"async-trait",
@@ -4744,9 +4744,9 @@ dependencies = [
[[package]]
name = "wiggle-generate"
-version = "7.0.0"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "424062dad40b2020239ae2de27c962b5dfa6f36b9fe4ddfc3bcff3d5917d078f"
+checksum = "489499e186ab24c8ac6d89e9934c54ced6f19bd473730e6a74f533bd67ecd905"
dependencies = [
"anyhow",
"heck 0.4.0",
@@ -4759,9 +4759,9 @@ dependencies = [
[[package]]
name = "wiggle-macro"
-version = "7.0.0"
+version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7dc0c6a4cbe4f073e7e24c0452fc58c2775574f3b8c89703148d6308d2531b16"
+checksum = "e9142e7fce24a4344c85a43c8b719ef434fc6155223bade553e186cb4183b6cc"
dependencies = [
"proc-macro2",
"quote",
@@ -4904,7 +4904,7 @@ dependencies = [
[[package]]
name = "wit-bindgen-gen-core"
version = "0.2.0"
-source = "git+https://github.com/fermyon/wit-bindgen-backport?rev=e1e2525bbbc8430c4ebe57e9f4b3f63b6facff98#e1e2525bbbc8430c4ebe57e9f4b3f63b6facff98"
+source = "git+https://github.com/fermyon/wit-bindgen-backport?rev=ba1636af0338623b54db84e2224be9a124e231f6#ba1636af0338623b54db84e2224be9a124e231f6"
dependencies = [
"anyhow",
"wit-parser 0.2.0",
@@ -4913,7 +4913,7 @@ dependencies = [
[[package]]
name = "wit-bindgen-gen-rust"
version = "0.2.0"
-source = "git+https://github.com/fermyon/wit-bindgen-backport?rev=e1e2525bbbc8430c4ebe57e9f4b3f63b6facff98#e1e2525bbbc8430c4ebe57e9f4b3f63b6facff98"
+source = "git+https://github.com/fermyon/wit-bindgen-backport?rev=ba1636af0338623b54db84e2224be9a124e231f6#ba1636af0338623b54db84e2224be9a124e231f6"
dependencies = [
"heck 0.3.3",
"wit-bindgen-gen-core",
@@ -4922,7 +4922,7 @@ dependencies = [
[[package]]
name = "wit-bindgen-gen-wasmtime"
version = "0.2.0"
-source = "git+https://github.com/fermyon/wit-bindgen-backport?rev=e1e2525bbbc8430c4ebe57e9f4b3f63b6facff98#e1e2525bbbc8430c4ebe57e9f4b3f63b6facff98"
+source = "git+https://github.com/fermyon/wit-bindgen-backport?rev=ba1636af0338623b54db84e2224be9a124e231f6#ba1636af0338623b54db84e2224be9a124e231f6"
dependencies = [
"heck 0.3.3",
"wit-bindgen-gen-core",
@@ -4932,7 +4932,7 @@ dependencies = [
[[package]]
name = "wit-bindgen-wasmtime"
version = "0.2.0"
-source = "git+https://github.com/fermyon/wit-bindgen-backport?rev=e1e2525bbbc8430c4ebe57e9f4b3f63b6facff98#e1e2525bbbc8430c4ebe57e9f4b3f63b6facff98"
+source = "git+https://github.com/fermyon/wit-bindgen-backport?rev=ba1636af0338623b54db84e2224be9a124e231f6#ba1636af0338623b54db84e2224be9a124e231f6"
dependencies = [
"anyhow",
"async-trait",
@@ -4945,7 +4945,7 @@ dependencies = [
[[package]]
name = "wit-bindgen-wasmtime-impl"
version = "0.2.0"
-source = "git+https://github.com/fermyon/wit-bindgen-backport?rev=e1e2525bbbc8430c4ebe57e9f4b3f63b6facff98#e1e2525bbbc8430c4ebe57e9f4b3f63b6facff98"
+source = "git+https://github.com/fermyon/wit-bindgen-backport?rev=ba1636af0338623b54db84e2224be9a124e231f6#ba1636af0338623b54db84e2224be9a124e231f6"
dependencies = [
"proc-macro2",
"syn 1.0.107",
@@ -4955,24 +4955,25 @@ dependencies = [
[[package]]
name = "wit-component"
-version = "0.7.4"
-source = "git+https://github.com/bytecodealliance/wasm-tools?rev=1e0052974277b3cce6c3703386e4e90291da2b24#1e0052974277b3cce6c3703386e4e90291da2b24"
+version = "0.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e291ff83cb9c8e59963cc6922bdda77ed8f5517d6835f0c98070c4e7f1ae4996"
dependencies = [
"anyhow",
"bitflags 1.3.2",
"indexmap",
"log",
"url",
- "wasm-encoder 0.25.0 (git+https://github.com/bytecodealliance/wasm-tools?rev=1e0052974277b3cce6c3703386e4e90291da2b24)",
+ "wasm-encoder 0.26.0",
"wasm-metadata",
- "wasmparser 0.102.0 (git+https://github.com/bytecodealliance/wasm-tools?rev=1e0052974277b3cce6c3703386e4e90291da2b24)",
- "wit-parser 0.6.4 (git+https://github.com/bytecodealliance/wasm-tools?rev=1e0052974277b3cce6c3703386e4e90291da2b24)",
+ "wasmparser 0.104.0",
+ "wit-parser 0.7.1",
]
[[package]]
name = "wit-parser"
version = "0.2.0"
-source = "git+https://github.com/fermyon/wit-bindgen-backport?rev=e1e2525bbbc8430c4ebe57e9f4b3f63b6facff98#e1e2525bbbc8430c4ebe57e9f4b3f63b6facff98"
+source = "git+https://github.com/fermyon/wit-bindgen-backport?rev=ba1636af0338623b54db84e2224be9a124e231f6#ba1636af0338623b54db84e2224be9a124e231f6"
dependencies = [
"anyhow",
"id-arena",
@@ -4998,8 +4999,9 @@ dependencies = [
[[package]]
name = "wit-parser"
-version = "0.6.4"
-source = "git+https://github.com/bytecodealliance/wasm-tools?rev=1e0052974277b3cce6c3703386e4e90291da2b24#1e0052974277b3cce6c3703386e4e90291da2b24"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5ca2581061573ef6d1754983d7a9b3ed5871ef859d52708ea9a0f5af32919172"
dependencies = [
"anyhow",
"id-arena",
diff --git a/examples/spin-timer/Cargo.toml b/examples/spin-timer/Cargo.toml
index 3121dd5a7a..53b66819f2 100644
--- a/examples/spin-timer/Cargo.toml
+++ b/examples/spin-timer/Cargo.toml
@@ -14,6 +14,6 @@ spin-core = { path = "../../crates/core" }
spin-trigger = { path = "../../crates/trigger" }
tokio = { version = "1.11", features = [ "full" ] }
tokio-scoped = "0.2.0"
-wasmtime = { version = "7.0.0", features = ["component-model"] }
+wasmtime = { version = "8.0.1", features = ["component-model"] }
[workspace]
diff --git a/examples/spin-timer/app-example/Cargo.lock b/examples/spin-timer/app-example/Cargo.lock
index ca09492517..9d5e1e556f 100644
--- a/examples/spin-timer/app-example/Cargo.lock
+++ b/examples/spin-timer/app-example/Cargo.lock
@@ -4,20 +4,9 @@ version = 3
[[package]]
name = "anyhow"
-version = "1.0.66"
+version = "1.0.71"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "216261ddc8289130e551ddcd5ce8a064710c0d064a4d2895c67151c92b5443f6"
-
-[[package]]
-name = "async-trait"
-version = "0.1.58"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1e805d94e6b5001b651426cf4cd446b1ab5f319d27bab5c644f61de0a804360c"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn",
-]
+checksum = "9c7d0618f0e0b7e8ff11427422b64564d5fb0be1940354bfe2e0529b18a9d9b8"
[[package]]
name = "autocfg"
@@ -32,10 +21,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
-name = "bytes"
-version = "1.2.1"
+name = "bitflags"
+version = "2.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ec8a7b6a70fde80372154c65702f00a0f56f3e1c36abbc6c440484be248856db"
+checksum = "24a6904aef64d73cf10ab17ebace7befb918b82164785cb89907993be7f83813"
[[package]]
name = "cfg-if"
@@ -43,12 +32,6 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
-[[package]]
-name = "fnv"
-version = "1.0.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
-
[[package]]
name = "form_urlencoded"
version = "1.1.0"
@@ -64,15 +47,6 @@ version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
-[[package]]
-name = "heck"
-version = "0.3.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6d621efb26863f0e9924c6ac577e8275e5e6b77455db64ffa6c65c904e9e132c"
-dependencies = [
- "unicode-segmentation",
-]
-
[[package]]
name = "heck"
version = "0.4.1"
@@ -82,17 +56,6 @@ dependencies = [
"unicode-segmentation",
]
-[[package]]
-name = "http"
-version = "0.2.8"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "75f43d41e26995c17e71ee126451dd3941010b0514a81a9d11f3b341debc2399"
-dependencies = [
- "bytes",
- "fnv",
- "itoa",
-]
-
[[package]]
name = "id-arena"
version = "2.2.1"
@@ -120,12 +83,6 @@ dependencies = [
"serde",
]
-[[package]]
-name = "itoa"
-version = "1.0.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fad582f4b9e86b6caa621cabeb0963332d92eea04729ab12892c2533951e6440"
-
[[package]]
name = "leb128"
version = "0.2.5"
@@ -155,9 +112,9 @@ checksum = "478c572c3d73181ff3c2539045f6eb99e5491218eae919370993b890cdbdd98e"
[[package]]
name = "proc-macro2"
-version = "1.0.47"
+version = "1.0.56"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5ea3d908b0e36316caf9e9e2c4625cdde190a7e6f440d794667ed17a1855e725"
+checksum = "2b63bdb0cd06f1f4dedf69b254734f9b45af66e4a031e42a7480257d9898b435"
dependencies = [
"unicode-ident",
]
@@ -168,16 +125,16 @@ version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ffade02495f22453cd593159ea2f59827aae7f53fa8323f756799b670881dcf8"
dependencies = [
- "bitflags",
+ "bitflags 1.3.2",
"memchr",
"unicase",
]
[[package]]
name = "quote"
-version = "1.0.21"
+version = "1.0.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179"
+checksum = "4424af4bf778aae2051a77b60283332f386554255d722233d09fbfc7e30da2fc"
dependencies = [
"proc-macro2",
]
@@ -199,37 +156,7 @@ checksum = "4f1d362ca8fc9c3e3a7484440752472d68a6caa98f1ab81d99b5dfe517cec852"
dependencies = [
"proc-macro2",
"quote",
- "syn",
-]
-
-[[package]]
-name = "spin-macro"
-version = "0.1.0"
-source = "git+https://github.com/fermyon/spin?tag=v0.7.0#73d315f2ab914cbbb69310af123c5d67d659f0e3"
-dependencies = [
- "anyhow",
- "bytes",
- "http",
- "proc-macro2",
- "quote",
- "syn",
- "wit-bindgen-gen-core",
- "wit-bindgen-gen-rust-wasm",
- "wit-bindgen-rust 0.2.0",
-]
-
-[[package]]
-name = "spin-sdk"
-version = "0.7.0"
-source = "git+https://github.com/fermyon/spin?tag=v0.7.0#73d315f2ab914cbbb69310af123c5d67d659f0e3"
-dependencies = [
- "anyhow",
- "bytes",
- "form_urlencoded",
- "http",
- "spin-macro",
- "thiserror",
- "wit-bindgen-rust 0.2.0",
+ "syn 1.0.103",
]
[[package]]
@@ -244,32 +171,20 @@ dependencies = [
]
[[package]]
-name = "thiserror"
-version = "1.0.38"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6a9cd18aa97d5c45c6603caea1da6628790b37f7a34b6ca89522331c5180fed0"
-dependencies = [
- "thiserror-impl",
-]
-
-[[package]]
-name = "thiserror-impl"
-version = "1.0.38"
+name = "syn"
+version = "2.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1fb327af4685e4d03fa8cbcf1716380da910eeb2bb8be417e7f9fd3fb164f36f"
+checksum = "a34fcf3e8b60f57e6a14301a2e916d323af98b0ea63c599441eec8558660c822"
dependencies = [
"proc-macro2",
"quote",
- "syn",
+ "unicode-ident",
]
[[package]]
name = "timer-app-example"
version = "0.1.0"
dependencies = [
- "anyhow",
- "bytes",
- "spin-sdk",
"wit-bindgen",
]
@@ -349,18 +264,18 @@ checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
[[package]]
name = "wasm-encoder"
-version = "0.25.0"
+version = "0.26.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4eff853c4f09eec94d76af527eddad4e9de13b11d6286a1ef7134bc30135a2b7"
+checksum = "d05d0b6fcd0aeb98adf16e7975331b3c17222aa815148f5b976370ce589d80ef"
dependencies = [
"leb128",
]
[[package]]
name = "wasm-metadata"
-version = "0.3.1"
+version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fd6956efd8a1a2c48a707e9a1b2da729834a0f8e4c58117493b0d9d089cee468"
+checksum = "dbdef99fafff010c57fabb7bc703f0903ec16fcee49207a22dcc4f78ea44562f"
dependencies = [
"anyhow",
"indexmap",
@@ -371,9 +286,9 @@ dependencies = [
[[package]]
name = "wasmparser"
-version = "0.102.0"
+version = "0.104.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "48134de3d7598219ab9eaf6b91b15d8e50d31da76b8519fe4ecfcec2cf35104b"
+checksum = "6a396af81a7c56ad976131d6a35e4b693b78a1ea0357843bd436b4577e254a7d"
dependencies = [
"indexmap",
"url",
@@ -381,145 +296,84 @@ dependencies = [
[[package]]
name = "wit-bindgen"
-version = "0.4.0"
+version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4e7cf57f8786216c5652e1228b25203af2ff523808b5e9d3671894eee2bf7264"
+checksum = "ad22d93d3f55847ac4b3df31607a26f35231754ef472382319de032770d8b5bf"
dependencies = [
- "bitflags",
+ "bitflags 2.2.1",
"wit-bindgen-rust-macro",
]
[[package]]
name = "wit-bindgen-core"
-version = "0.4.0"
+version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ef177b73007d86c720931d0e2ea7e30eb8c9776e58361717743fc1e83cfacfe5"
+checksum = "5bc1b5a6e87f16491f2297f75312dc0fb354f8c88c8bece53ea0d3167fc98867"
dependencies = [
"anyhow",
"wit-component",
- "wit-parser 0.6.4",
-]
-
-[[package]]
-name = "wit-bindgen-gen-core"
-version = "0.2.0"
-source = "git+https://github.com/bytecodealliance/wit-bindgen?rev=cb871cfa1ee460b51eb1d144b175b9aab9c50aba#cb871cfa1ee460b51eb1d144b175b9aab9c50aba"
-dependencies = [
- "anyhow",
- "wit-parser 0.2.0",
-]
-
-[[package]]
-name = "wit-bindgen-gen-rust"
-version = "0.2.0"
-source = "git+https://github.com/bytecodealliance/wit-bindgen?rev=cb871cfa1ee460b51eb1d144b175b9aab9c50aba#cb871cfa1ee460b51eb1d144b175b9aab9c50aba"
-dependencies = [
- "heck 0.3.3",
- "wit-bindgen-gen-core",
-]
-
-[[package]]
-name = "wit-bindgen-gen-rust-wasm"
-version = "0.2.0"
-source = "git+https://github.com/bytecodealliance/wit-bindgen?rev=cb871cfa1ee460b51eb1d144b175b9aab9c50aba#cb871cfa1ee460b51eb1d144b175b9aab9c50aba"
-dependencies = [
- "heck 0.3.3",
- "wit-bindgen-gen-core",
- "wit-bindgen-gen-rust",
+ "wit-parser",
]
[[package]]
name = "wit-bindgen-rust"
-version = "0.2.0"
-source = "git+https://github.com/bytecodealliance/wit-bindgen?rev=cb871cfa1ee460b51eb1d144b175b9aab9c50aba#cb871cfa1ee460b51eb1d144b175b9aab9c50aba"
-dependencies = [
- "async-trait",
- "bitflags",
- "wit-bindgen-rust-impl",
-]
-
-[[package]]
-name = "wit-bindgen-rust"
-version = "0.4.0"
+version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "efdf5b00935b7b52d0e56cae1960f8ac13019a285f5aa762ff6bd7139a5c28a2"
+checksum = "7946a66f1132d3322c29de9d28097bd263f67e1e0909054f91253aa103cdf8be"
dependencies = [
- "heck 0.4.1",
+ "heck",
"wasm-metadata",
"wit-bindgen-core",
"wit-bindgen-rust-lib",
"wit-component",
]
-[[package]]
-name = "wit-bindgen-rust-impl"
-version = "0.2.0"
-source = "git+https://github.com/bytecodealliance/wit-bindgen?rev=cb871cfa1ee460b51eb1d144b175b9aab9c50aba#cb871cfa1ee460b51eb1d144b175b9aab9c50aba"
-dependencies = [
- "proc-macro2",
- "syn",
- "wit-bindgen-gen-core",
- "wit-bindgen-gen-rust-wasm",
-]
-
[[package]]
name = "wit-bindgen-rust-lib"
-version = "0.4.0"
+version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ab0a8f4b5fb1820b9d232beb122936425f72ec8fe6acb56e5d8782cfe55083da"
+checksum = "0baf7325748c5d363ab6ed3ddbd155c241cfe385410c61f2505ec978a61a2d2c"
dependencies = [
- "heck 0.4.1",
+ "heck",
"wit-bindgen-core",
]
[[package]]
name = "wit-bindgen-rust-macro"
-version = "0.4.0"
+version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cadf1adf12ed25629b06272c16b335ef8c5a240d0ca64ab508a955ac3b46172c"
+checksum = "42c131da5d2ba7746908e1401d474640371c31ad05281528c2a9e945a87d19be"
dependencies = [
"anyhow",
"proc-macro2",
- "syn",
+ "syn 2.0.15",
"wit-bindgen-core",
- "wit-bindgen-rust 0.4.0",
+ "wit-bindgen-rust",
"wit-component",
]
[[package]]
name = "wit-component"
-version = "0.7.4"
+version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ed04310239706efc71cc8b995cb0226089c5b5fd260c3bd800a71486bd3cec97"
+checksum = "e291ff83cb9c8e59963cc6922bdda77ed8f5517d6835f0c98070c4e7f1ae4996"
dependencies = [
"anyhow",
- "bitflags",
+ "bitflags 1.3.2",
"indexmap",
"log",
"url",
"wasm-encoder",
"wasm-metadata",
"wasmparser",
- "wit-parser 0.6.4",
-]
-
-[[package]]
-name = "wit-parser"
-version = "0.2.0"
-source = "git+https://github.com/bytecodealliance/wit-bindgen?rev=cb871cfa1ee460b51eb1d144b175b9aab9c50aba#cb871cfa1ee460b51eb1d144b175b9aab9c50aba"
-dependencies = [
- "anyhow",
- "id-arena",
- "pulldown-cmark",
- "unicode-normalization",
- "unicode-xid",
+ "wit-parser",
]
[[package]]
name = "wit-parser"
-version = "0.6.4"
+version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f887c3da527a51b321076ebe6a7513026a4757b6d4d144259946552d6fc728b3"
+checksum = "5ca2581061573ef6d1754983d7a9b3ed5871ef859d52708ea9a0f5af32919172"
dependencies = [
"anyhow",
"id-arena",
diff --git a/examples/spin-timer/app-example/Cargo.toml b/examples/spin-timer/app-example/Cargo.toml
index c475ea4a4b..8b7579b5e7 100644
--- a/examples/spin-timer/app-example/Cargo.toml
+++ b/examples/spin-timer/app-example/Cargo.toml
@@ -9,9 +9,6 @@ edition = "2021"
crate-type = [ "cdylib" ]
[dependencies]
-anyhow = "1"
-bytes = "1"
-spin-sdk = { git = "https://github.com/fermyon/spin", tag = "v0.7.0" }
-wit-bindgen = "0.4.0"
+wit-bindgen = "0.6.0"
[workspace]
diff --git a/examples/spin-timer/app-example/src/lib.rs b/examples/spin-timer/app-example/src/lib.rs
index 49a8fe2d64..a2cc0cac2c 100644
--- a/examples/spin-timer/app-example/src/lib.rs
+++ b/examples/spin-timer/app-example/src/lib.rs
@@ -7,7 +7,7 @@ struct MySpinTimer;
impl SpinTimer for MySpinTimer {
fn handle_timer_request() {
- let text = spin_sdk::config::get("message").unwrap();
+ let text = config::get_config("message").unwrap();
println!("{text}");
}
}
diff --git a/examples/spin-timer/spin-timer.wit b/examples/spin-timer/spin-timer.wit
index 9d5fa73cce..d4ff107908 100644
--- a/examples/spin-timer/spin-timer.wit
+++ b/examples/spin-timer/spin-timer.wit
@@ -1,3 +1,17 @@
+interface config {
+ // Get a configuration value for the current component.
+ // The config key must match one defined in in the component manifest.
+ get-config: func(key: string) -> result<string, error>
+
+ variant error {
+ provider(string),
+ invalid-key(string),
+ invalid-schema(string),
+ other(string),
+ }
+}
+
default world spin-timer {
+ import config: self.config
export handle-timer-request: func()
}
| 1,439
|
[
"1437"
] |
diff --git a/crates/core/tests/core-wasi-test/Cargo.toml b/crates/core/tests/core-wasi-test/Cargo.toml
index d388b0233a..9de6561859 100644
--- a/crates/core/tests/core-wasi-test/Cargo.toml
+++ b/crates/core/tests/core-wasi-test/Cargo.toml
@@ -7,6 +7,6 @@ edition = "2021"
debug = true
[dependencies]
-wit-bindgen = "0.4.0"
+wit-bindgen = "0.6.0"
[workspace]
|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
0b683a9bf9750723aa7a65a390d76fc1f7a6ae05
|
Dev Loop Test Failure
When running `make test` spin is not present in dev container/system path which results in the following error:
---
running 1 test
**"/bin/bash: line 1: spin: command not found\n"**
""
thread 'spinup_tests::key_value_works' panicked at 'command `cd "/workspaces/spin/crates/e2e-testing/../../tests/testcases/key-value" && "/bin/bash" "-c" "spin build"` exited with code 127', crates/e2e-testing/src/utils.rs:50:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
test spinup_tests::key_value_works ... FAILED
failures:
failures:
spinup_tests::key_value_works
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 20 filtered out; finished in 0.00s
error: test failed, to rerun pass `--test spinup_tests`
error: 1 target failed:
`--test spinup_tests`
make: *** [Makefile:64: test-kv] Error 101
|
Hi @suneetnangia
thank you for reporting this issue. Could you please confirm if you have Spin in `target/{release,debug}` directory? I think we should add those dir to PATH before running the tests.
Hi @rajatjindal
Confirmed, spin binary does get created in `./target/release` dir, I had to manually copy it to /usr/local/bin/ to make the tests run. Agreed, adding the above release/debug dirs to PATH should fix this.
|
2023-04-25T05:39:06Z
|
fermyon__spin-1422
|
fermyon/spin
|
3.2
|
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 2bd46125d8..67cc4d3299 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -174,8 +174,8 @@ jobs:
export E2E_FETCH_SPIN=false
make build-test-spin-up
- - name: Run e2e tests image
+ - name: Run e2e tests
run: |
chmod +x `pwd`/target/release/spin
export E2E_VOLUME_MOUNT="-v `pwd`/target/release/spin:/usr/local/bin/spin"
- make run-test-spin-up
\ No newline at end of file
+ make run-test-spin-up
diff --git a/Makefile b/Makefile
index 62dccffcbe..d9cfaf82fd 100644
--- a/Makefile
+++ b/Makefile
@@ -1,26 +1,44 @@
LOG_LEVEL ?= spin=trace
CERT_NAME ?= local
SPIN_DOC_NAME ?= new-doc.md
+export PATH := target/debug:target/release:$(HOME)/.cargo/bin:$(PATH)
ARCH = $(shell uname -p)
## dependencies for e2e-tests
-E2E_VOLUME_MOUNT ?=
-E2E_BUILD_SPIN ?= false
-E2E_FETCH_SPIN ?= true
-E2E_TESTS_DOCKERFILE ?= e2e-tests.Dockerfile
-MYSQL_IMAGE ?= mysql:8.0.22
-REDIS_IMAGE ?= redis:7.0.8-alpine3.17
-POSTGRES_IMAGE ?= postgres:14.7-alpine
-REGISTRY_IMAGE ?= registry:2
+E2E_BUILD_SPIN ?= false
+E2E_FETCH_SPIN ?= true
+E2E_TESTS_DOCKERFILE ?= e2e-tests.Dockerfile
+MYSQL_IMAGE ?= mysql:8.0.22
+REDIS_IMAGE ?= redis:7.0.8-alpine3.17
+POSTGRES_IMAGE ?= postgres:14.7-alpine
+REGISTRY_IMAGE ?= registry:2
+E2E_SPIN_RELEASE_VOLUME_MOUNT ?=
+E2E_SPIN_DEBUG_VOLUME_MOUNT ?=
## overrides for aarch64
ifneq ($(ARCH),x86_64)
- MYSQL_IMAGE = arm64v8/mysql:8.0.32
- REDIS_IMAGE = arm64v8/redis:6.0-alpine3.17
- POSTGRES_IMAGE = arm64v8/postgres:14.7
- REGISTRY_IMAGE = arm64v8/registry:2
- E2E_TESTS_DOCKERFILE = e2e-tests-aarch64.Dockerfile
+ MYSQL_IMAGE = arm64v8/mysql:8.0.32
+ REDIS_IMAGE = arm64v8/redis:6.0-alpine3.17
+ POSTGRES_IMAGE = arm64v8/postgres:14.7
+ REGISTRY_IMAGE = arm64v8/registry:2
+ E2E_TESTS_DOCKERFILE = e2e-tests-aarch64.Dockerfile
+endif
+
+ifneq (,$(wildcard $(shell pwd)/target/release/spin))
+ E2E_SPIN_RELEASE_VOLUME_MOUNT = -v $(shell pwd)/target/release/spin:/from-host/target/release/spin
+endif
+
+ifneq (,$(wildcard $(shell pwd)/target/debug/spin))
+ E2E_SPIN_DEBUG_VOLUME_MOUNT = -v $(shell pwd)/target/debug/spin:/from-host/target/debug/spin
+endif
+
+## Reset volume mounts for e2e-tests if Darwin because the
+## spin binaries built on macOS won't run in the docker container
+ifeq ($(shell uname -s),Darwin)
+ E2E_SPIN_RELEASE_VOLUME_MOUNT =
+ E2E_SPIN_DEBUG_VOLUME_MOUNT =
+ E2E_BUILD_SPIN = true
endif
.PHONY: build
@@ -54,7 +72,7 @@ test-integration: test-kv
RUST_LOG=$(LOG_LEVEL) cargo test --test integration --no-fail-fast -- --skip spinup_tests --skip cloud_tests --nocapture
.PHONY: test-spin-up
-test-spin-up: build-test-spin-up-docker run-test-spin-up-docker
+test-spin-up: build-test-spin-up run-test-spin-up
.PHONY: build-test-spin-up
build-test-spin-up:
@@ -63,7 +81,8 @@ build-test-spin-up:
.PHONY: run-test-spin-up
run-test-spin-up:
REDIS_IMAGE=$(REDIS_IMAGE) MYSQL_IMAGE=$(MYSQL_IMAGE) POSTGRES_IMAGE=$(POSTGRES_IMAGE) \
- docker compose -f e2e-tests-docker-compose.yml run $(E2E_VOLUME_MOUNT) e2e-tests
+ BUILD_SPIN=$(E2E_BUILD_SPIN) \
+ docker compose -f e2e-tests-docker-compose.yml run $(E2E_SPIN_RELEASE_VOLUME_MOUNT) $(E2E_SPIN_DEBUG_VOLUME_MOUNT) e2e-tests
.PHONY: test-kv
test-kv:
| 1,422
|
[
"1385"
] |
diff --git a/crates/e2e-testing/src/spin.rs b/crates/e2e-testing/src/spin.rs
index dc848c54f1..4772f65673 100644
--- a/crates/e2e-testing/src/spin.rs
+++ b/crates/e2e-testing/src/spin.rs
@@ -117,5 +117,11 @@ pub fn registry_login(registry_url: &str, username: &str, password: &str) -> Res
pub fn version() -> Result<String> {
let output = utils::run(&["spin", "--version"], None, None)?;
utils::assert_success(&output);
- Ok(format!("{:#?}", std::str::from_utf8(&output.stdout)?))
+ Ok(std::str::from_utf8(&output.stdout)?.trim().to_string())
+}
+
+pub fn which_spin() -> Result<String> {
+ let output = utils::run(&["which", "spin"], None, None)?;
+ utils::assert_success(&output);
+ Ok(std::str::from_utf8(&output.stdout)?.trim().to_string())
}
diff --git a/crates/e2e-testing/src/testcase.rs b/crates/e2e-testing/src/testcase.rs
index 383cde239f..776ed3b9b9 100644
--- a/crates/e2e-testing/src/testcase.rs
+++ b/crates/e2e-testing/src/testcase.rs
@@ -109,6 +109,8 @@ impl TestCase {
///
/// The output from running `spin build` is returned.
async fn do_run(&self, controller: &dyn Controller, bail_on_run_failure: bool) -> Result<()> {
+ print_version_info(&self.name);
+
// install spin plugins if requested in testcase config
if let Some(plugins) = &self.plugins {
controller
@@ -218,3 +220,14 @@ impl TestCase {
}
}
}
+
+fn print_version_info(testcase_name: &str) {
+ let version = spin::version();
+ let which_spin = spin::which_spin();
+ println!(
+ r###"[testcase::run] Running testcase "{}" using spin ({}) with version {}"###,
+ testcase_name,
+ which_spin.as_deref().unwrap_or("unknown"),
+ version.as_deref().unwrap_or("unknown")
+ );
+}
diff --git a/e2e-tests-aarch64.Dockerfile b/e2e-tests-aarch64.Dockerfile
index 044185872c..c59946f40e 100644
--- a/e2e-tests-aarch64.Dockerfile
+++ b/e2e-tests-aarch64.Dockerfile
@@ -67,11 +67,16 @@ RUN wget https://github.com/fermyon/spin/releases/download/${SPIN_VERSION}/spin-
WORKDIR /e2e-tests
COPY . .
-RUN if [ "${BUILD_SPIN}" == "true" ]; then \
- cargo build --release && \
- cp target/release/spin /usr/local/bin/spin; \
- fi
+RUN printf '#!/bin/bash \n \
+ if [[ "$BUILD_SPIN" == "true" ]]; then \n \
+ echo "BUILD_SPIN is true. compiling spin" \n \
+ cargo build --release \n \
+ fi \n\n \
+ cargo test spinup_tests --features e2e-tests --no-fail-fast -- --nocapture \n \
+ ' > /usr/local/bin/entrypoint.sh
-RUN spin --version
+RUN chmod +x /usr/local/bin/entrypoint.sh
-CMD cargo test spinup_tests --features e2e-tests --no-fail-fast -- --nocapture
+RUN spin --version
+ENV PATH=/from-host/target/debug:/from-host/target/release:$HOME/.cargo/bin:$PATH
+CMD /usr/local/bin/entrypoint.sh
diff --git a/e2e-tests-docker-compose.yml b/e2e-tests-docker-compose.yml
index ef884bc68e..b553891a34 100644
--- a/e2e-tests-docker-compose.yml
+++ b/e2e-tests-docker-compose.yml
@@ -47,7 +47,7 @@ services:
- postgres
- registry
image: spin-e2e-tests
- entrypoint: cargo test spinup_tests --features e2e-tests --no-fail-fast -- --nocapture
+ entrypoint: /usr/local/bin/entrypoint.sh
volumes:
- target_cache:/e2e-tests/target
- cargo_registry_cache:/usr/local/cargo/registry
@@ -58,4 +58,4 @@ volumes:
postgres_data: {}
cargo_registry_cache: {}
cargo_git_cache: {}
- target_cache: {}
\ No newline at end of file
+ target_cache: {}
diff --git a/e2e-tests.Dockerfile b/e2e-tests.Dockerfile
index b1dfaa1c8d..c6e1058db3 100644
--- a/e2e-tests.Dockerfile
+++ b/e2e-tests.Dockerfile
@@ -70,13 +70,19 @@ RUN if [ "${FETCH_SPIN}" = "true" ]; then
WORKDIR /e2e-tests
COPY . .
-RUN if [ "${BUILD_SPIN}" = "true" ]; then \
- cargo build --release && \
- cp target/release/spin /usr/local/bin/spin; \
- fi
+RUN printf '#!/bin/bash \n \
+ if [[ "$BUILD_SPIN" == "true" ]]; then \n \
+ echo "BUILD_SPIN is true. compiling spin" \n \
+ cargo build --release \n \
+ fi \n\n \
+ cargo test spinup_tests --features e2e-tests --no-fail-fast -- --nocapture \n \
+ ' > /usr/local/bin/entrypoint.sh
+
+RUN chmod +x /usr/local/bin/entrypoint.sh
RUN if [ "${FETCH_SPIN}" = "true" ] || [ "${BUILD_SPIN}" = "true" ]; then \
spin --version; \
fi
-CMD cargo test spinup_tests --features e2e-tests --no-fail-fast -- --nocapture
+ENV PATH=/from-host/target/debug:/from-host/target/release:$HOME/.cargo/bin:$PATH
+CMD /usr/local/bin/entrypoint.sh
diff --git a/tests/README.md b/tests/README.md
index 51890ee1d2..478abed392 100644
--- a/tests/README.md
+++ b/tests/README.md
@@ -13,6 +13,13 @@ The goal of these tests is to ensure that spin continues to work with existing a
make test-spin-up
```
+The e2e-tests looks for `spin` binary in following folders (in that order):
+
+- target/debug
+- target/release
+- $HOME/.cargo/bin
+- $PATH
+
## How to use `spin` binary with your local changes
By default, tests use the canary build of `spin` downloaded at the docker image creation time. If you want to test it with your changes, you can use the environment variable E2E_BUILD_SPIN=true
|
c02196882a336d46c3dd5fcfafeed45ef0a4490e
|
7f0d5460125dbff96b4bba1a32ca8750d17b0bd0
|
`spin watch` configuration handles multi-component applications poorly
Imagine a Spin application that has two components. Here is its `spin.toml`:
```toml
[[component]]
id = "web"
source = "modules/spin_static_fs.wasm"
environment = { FALLBACK_PATH = "index.html" }
# [[component.files]]
# source = "web/dist"
# destination = "/"
[component.trigger]
route = "/..."
[component.build]
workdir = "web"
command = "npm run build"
watch = ["src/**/*.tsx", "src/**/*.css", "package.json"]
[[component]]
id = "api"
source = "api/target/wasm32-wasi/release/api.wasm"
[component.trigger]
route = "/api/..."
[component.build]
workdir = "api"
command = "cargo build --target wasm32-wasi --release"
watch = ["src/**/*.rs", "Cargo.toml"]
```
Here is its directory structure:
```text
.
├── api
│ ├── Cargo.toml
│ ├── src
│ │ ├── lib.rs
├── modules
│ └── spin_static_fs.wasm
├── spin.toml
└── web
├── dist
│ ├── index.html
├── package.json
├── src
│ ├── app
│ └── components
```
If we run `spin watch` from the root directory it will not properly watch all the files that the user specified in their `component.build.watch`. This is because it takes the globs in that configuration and appends them to the directory the manifest file is in. In practice this means `spin watch` is going to watch `manifest/dir/src/**/*.rs` instead of the correct `manifest/dir/api/src/**/*.rs`.
There are two possible solutions I see:
1. Automatically infer this subdirectory structure from the `component.workdir` configuration.
2. Require users to include this subdirectory structure in their `component.build.watch` configuration e.g. `["api/src/**/*.rs", "api/Cargo.toml"]`
The advantage of 1 is that it is simpler but I'm also worried about scenarios where the assumption of the workdir and subdirectory being the same aren't true.
The advantage of 2 is that it will always work but this comes at the cost of extra overhead for the user. In particular we should update the `spin add` templates to handle configuring the subdirectory for the watch config.
CC @itowlson I'd love to hear your thoughts here.
|
I like the idea that `build.watch` sees the world in the same way as `build.command`, which is your option 1.
Could you elaborate on scenarios where a source to be watched-built is _not_ under the `workdir`? That would help establish how important it is to address this case and whether there are satisfactory workarounds if we do adopt option 1.
I can't come up with a concrete/real-world language or development pattern where a source to be watched-built is not under the `workdir`. So maybe that answers your question.
But, what I was imagining was something like:
- User puts source code under `src/`.
- User has a directory `tmp/` where they want to run their tool from because it produces lots of random extra files they don't want polluting their source.
- Now `workdir` is different then the prefix that watch would need.
- We would have to expose a flag to handle this use case which clutters up the watch UI.
Tools that can't run in the directory where the source code lives are, I suspect, vanishingly thin on the ground. _grin_ But even in that scenario, I think you'd want watch and build to have the same view of the world, something like:
```
workdir = "tmp"
# The ill-behaved compiler would still need some way to know where the source files were...
command = "filthylang ../src/filth.json"
# ...and watch would just employ that same "../src" pattern
watch = ["../src/**/*"]
```
I would say don't worry about this case unless we know of a concrete example, and we will cross that bridge if we come to it.
I agree and will proceed with option #1.
Unrelated, now I'm really tempted to build `filthylang`.
|
2023-04-18T17:30:40Z
|
fermyon__spin-1409
|
fermyon/spin
|
3.1
|
diff --git a/src/commands/watch.rs b/src/commands/watch.rs
index 41df859904..0a8a7418f0 100644
--- a/src/commands/watch.rs
+++ b/src/commands/watch.rs
@@ -188,11 +188,26 @@ impl WatchCommand {
.iter()
.filter_map(|c| {
if let Some(build) = c.build.as_ref() {
- if build.watch.is_none() {
- // TODO: Make sure that documentation link is pointing specifically to spin watch docs
- eprintln!("You haven't configured what to watch for the component: '{}'. Learn how to configure Spin watch at https://developer.fermyon.com", c.id);
+ match build.watch.clone() {
+ Some(watch) => {
+ let Some(workdir) = build.workdir.clone() else {
+ return Some(watch);
+ };
+ Some(
+ watch
+ .iter()
+ .filter_map(|ws| workdir.join(ws).to_str().map(String::from))
+ .collect::<Vec<String>>(),
+ )
+ }
+ None => {
+ eprintln!(
+ "You haven't configured what to watch for the component: '{}'. Learn how to configure Spin watch at https://developer.fermyon.com/common/cli-reference#watch",
+ c.id
+ );
+ None
+ }
}
- build.watch.clone()
} else {
// No build config for this component so lets watch the source instead
if let RawModuleSource::FileReference(path) = &c.source {
@@ -286,11 +301,19 @@ mod tests {
up_args: vec![],
};
let path_patterns = watch_command.generate_path_patterns().await.unwrap();
- assert_eq!(path_patterns.len(), 3);
+ assert_eq!(path_patterns.len(), 5);
assert_eq!(path_patterns.get(0), Some(&String::from("src/**/*.rs")));
assert_eq!(path_patterns.get(1), Some(&String::from("Cargo.toml")));
assert_eq!(
path_patterns.get(2),
+ Some(&String::from("subcomponent/**/*.go"))
+ );
+ assert_eq!(
+ path_patterns.get(3),
+ Some(&String::from("subcomponent/go.mod"))
+ );
+ assert_eq!(
+ path_patterns.get(4),
Some(&String::from("tests/watch/http-rust/spin.toml"))
);
}
@@ -306,13 +329,17 @@ mod tests {
up_args: vec![],
};
let path_patterns = watch_command.generate_path_patterns().await.unwrap();
- assert_eq!(path_patterns.len(), 2);
+ assert_eq!(path_patterns.len(), 3);
assert_eq!(
path_patterns.get(0),
Some(&String::from("target/wasm32-wasi/release/http_rust.wasm"))
);
assert_eq!(
path_patterns.get(1),
+ Some(&String::from("subcomponent/main.wasm"))
+ );
+ assert_eq!(
+ path_patterns.get(2),
Some(&String::from("tests/watch/http-rust/spin.toml"))
);
}
| 1,409
|
[
"1402"
] |
diff --git a/tests/watch/http-rust/spin.toml b/tests/watch/http-rust/spin.toml
index 10854dc585..c6ab91fafa 100644
--- a/tests/watch/http-rust/spin.toml
+++ b/tests/watch/http-rust/spin.toml
@@ -14,3 +14,14 @@ route = "/hello"
[component.build]
command = "cargo build --target wasm32-wasi --release"
watch = ["src/**/*.rs", "Cargo.toml"]
+
+[[component]]
+id = "subcomponent"
+source = "subcomponent/main.wasm"
+allowed_http_hosts = []
+[component.trigger]
+route = "/..."
+[component.build]
+command = "tinygo build -target=wasi -gc=leaking -no-debug -o main.wasm main.go"
+workdir = "subcomponent"
+watch = ["**/*.go", "go.mod"]
diff --git a/tests/watch/http-rust/subcomponent/.gitignore b/tests/watch/http-rust/subcomponent/.gitignore
new file mode 100644
index 0000000000..b565010470
--- /dev/null
+++ b/tests/watch/http-rust/subcomponent/.gitignore
@@ -0,0 +1,2 @@
+main.wasm
+.spin/
diff --git a/tests/watch/http-rust/subcomponent/go.mod b/tests/watch/http-rust/subcomponent/go.mod
new file mode 100644
index 0000000000..5686fd3c62
--- /dev/null
+++ b/tests/watch/http-rust/subcomponent/go.mod
@@ -0,0 +1,5 @@
+module github.com/subcomponent
+
+go 1.17
+
+require github.com/fermyon/spin/sdk/go v1.0.0
diff --git a/tests/watch/http-rust/subcomponent/main.go b/tests/watch/http-rust/subcomponent/main.go
new file mode 100644
index 0000000000..c18f862304
--- /dev/null
+++ b/tests/watch/http-rust/subcomponent/main.go
@@ -0,0 +1,17 @@
+package main
+
+import (
+ "fmt"
+ "net/http"
+
+ spinhttp "github.com/fermyon/spin/sdk/go/http"
+)
+
+func init() {
+ spinhttp.Handle(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "text/plain")
+ fmt.Fprintln(w, "Hello Fermyon!")
+ })
+}
+
+func main() {}
|
7f0d5460125dbff96b4bba1a32ca8750d17b0bd0
|
88c7dbe987af72be7faf950df9af3a40fca02a72
|
Add `spin up --app-state-dir`
We're starting to move some per-app local state (logs, default KV store) into a `.spin` dir adjacent to the `spin.toml` file, which we'll start calling the "app state" directory. This should be configurable, with different defaults between "local" (`spin.toml`) and "remote" (Bindle, OCI) apps:
- Add a `--app-state-dir` flag to `spin up`
- Local apps: defaults to `.spin/` relative to the local `spin.toml`
- Remote apps: defaults to being unset
The value of the app state dir will impact a couple of existing features:
- If `--app-state-dir` is set (local default):
- App logs (stdout/err) will be written to `<app-state-dir>/logs/...` (when #1111 is done)
- Default KV store will be `<app-state-dir>/sqlite_key_value.db`
- If `--app-state-dir` is unset (remote default):
- App logs will not be written to disk (still written to stdio by default)
- Default KV store will be in-memory (not persisted)
|
For the local case, it seems like there would be no way to unset `--app-state-dir` - is that correct? (I don't see a lot of value to doing so, but just want to be sure that we're making that decision intentionally.)
> way to unset `--app-state-dir`
We can probably safely interpret `--app-state-dir ''` as "unset" which would at least be useful for testing this code.
Rethinking my own name suggestion, I'm not sure "state" really captures what we want to use this for (logs aren't really "state"). Maybe `--app-data-dir`? Just `--data-dir`?
|
2023-03-08T22:50:45Z
|
fermyon__spin-1245
|
fermyon/spin
|
3.1
|
diff --git a/Cargo.lock b/Cargo.lock
index 7183b512b7..68eead556d 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4724,7 +4724,6 @@ dependencies = [
"ctrlc",
"dirs 4.0.0",
"futures",
- "once_cell",
"outbound-http",
"outbound-mysql",
"outbound-pg",
diff --git a/crates/config/src/provider/vault.rs b/crates/config/src/provider/vault.rs
index afc8c08b2d..a0f901bde8 100644
--- a/crates/config/src/provider/vault.rs
+++ b/crates/config/src/provider/vault.rs
@@ -23,13 +23,13 @@ impl VaultProvider {
url: impl Into<String>,
token: impl Into<String>,
mount: impl Into<String>,
- prefix: Option<String>,
+ prefix: Option<impl Into<String>>,
) -> Self {
Self {
url: url.into(),
token: token.into(),
mount: mount.into(),
- prefix,
+ prefix: prefix.map(Into::into),
}
}
}
diff --git a/crates/http/src/lib.rs b/crates/http/src/lib.rs
index e1c4794237..fe731567eb 100644
--- a/crates/http/src/lib.rs
+++ b/crates/http/src/lib.rs
@@ -176,7 +176,7 @@ impl TriggerExecutor for HttpTrigger {
// Print startup messages
let scheme = if tls.is_some() { "https" } else { "http" };
let base_url = format!("{}://{:?}", scheme, listen_addr);
- println!("Serving {}", base_url);
+ println!("\nServing {}", base_url);
log::info!("Serving {}", base_url);
println!("Available Routes:");
diff --git a/crates/key-value-sqlite/src/lib.rs b/crates/key-value-sqlite/src/lib.rs
index 8900dc6ce9..9f7290b7e6 100644
--- a/crates/key-value-sqlite/src/lib.rs
+++ b/crates/key-value-sqlite/src/lib.rs
@@ -34,14 +34,8 @@ impl StoreManager for KeyValueSqlite {
let connection = task::block_in_place(|| {
self.connection.get_or_try_init(|| {
let connection = match &self.location {
- DatabaseLocation::InMemory => {
- println!("Using in-memory key-value store");
- Connection::open_in_memory()
- }
- DatabaseLocation::Path(path) => {
- println!("Using {} for key-value store", path.display());
- Connection::open(path)
- }
+ DatabaseLocation::InMemory => Connection::open_in_memory(),
+ DatabaseLocation::Path(path) => Connection::open(path),
}
.map_err(log_error)?;
@@ -156,15 +150,10 @@ mod test {
.into_iter()
.map(ToOwned::to_owned)
.collect(),
- Arc::new(DelegatingStoreManager::new(
- [(
- "default".to_owned(),
- Arc::new(KeyValueSqlite::new(DatabaseLocation::InMemory))
- as Arc<dyn StoreManager>,
- )]
- .into_iter()
- .collect(),
- )),
+ Arc::new(DelegatingStoreManager::new([(
+ "default".to_owned(),
+ Arc::new(KeyValueSqlite::new(DatabaseLocation::InMemory)) as _,
+ )])),
);
assert!(matches!(
diff --git a/crates/key-value/src/host_component.rs b/crates/key-value/src/host_component.rs
index aaa023fe25..1d81ff17be 100644
--- a/crates/key-value/src/host_component.rs
+++ b/crates/key-value/src/host_component.rs
@@ -58,15 +58,18 @@ impl HostComponent for KeyValueComponent {
impl DynamicHostComponent for KeyValueComponent {
fn update_data(&self, data: &mut Self::Data, component: &AppComponent) -> anyhow::Result<()> {
+ let key_value_stores = component_key_value_stores(component)?;
data.init(
- component
- .get_metadata::<Vec<String>>(KEY_VALUE_STORES_METADATA_KEY)?
- .unwrap_or_default()
- .into_iter()
- .collect(),
+ key_value_stores.into_iter().collect(),
self.manager.get(component),
);
Ok(())
}
}
+
+pub fn component_key_value_stores(component: &AppComponent) -> anyhow::Result<Vec<String>> {
+ Ok(component
+ .get_metadata(KEY_VALUE_STORES_METADATA_KEY)?
+ .unwrap_or_default())
+}
diff --git a/crates/key-value/src/lib.rs b/crates/key-value/src/lib.rs
index 91fd61a77b..d17f5db39d 100644
--- a/crates/key-value/src/lib.rs
+++ b/crates/key-value/src/lib.rs
@@ -7,7 +7,7 @@ mod host_component;
mod table;
mod util;
-pub use host_component::{manager, KeyValueComponent};
+pub use host_component::{component_key_value_stores, manager, KeyValueComponent};
pub use util::{CachingStoreManager, DelegatingStoreManager, EmptyStoreManager};
const DEFAULT_STORE_TABLE_CAPACITY: u32 = 256;
diff --git a/crates/key-value/src/util.rs b/crates/key-value/src/util.rs
index e97a9cde17..5c5bc3eb6f 100644
--- a/crates/key-value/src/util.rs
+++ b/crates/key-value/src/util.rs
@@ -28,7 +28,8 @@ pub struct DelegatingStoreManager {
}
impl DelegatingStoreManager {
- pub fn new(delegates: HashMap<String, Arc<dyn StoreManager>>) -> Self {
+ pub fn new(delegates: impl IntoIterator<Item = (String, Arc<dyn StoreManager>)>) -> Self {
+ let delegates = delegates.into_iter().collect();
Self { delegates }
}
}
diff --git a/crates/trigger/Cargo.toml b/crates/trigger/Cargo.toml
index 3dd8538034..671f10c18c 100644
--- a/crates/trigger/Cargo.toml
+++ b/crates/trigger/Cargo.toml
@@ -11,7 +11,6 @@ clap = { version = "3.1.15", features = ["derive", "env"] }
ctrlc = { version = "3.2", features = ["termination"] }
dirs = "4"
futures = "0.3"
-once_cell = "1.0"
outbound-http = { path = "../outbound-http" }
outbound-redis = { path = "../outbound-redis" }
outbound-pg = { path = "../outbound-pg" }
diff --git a/crates/trigger/src/cli.rs b/crates/trigger/src/cli.rs
index a690b3111b..4b4221debf 100644
--- a/crates/trigger/src/cli.rs
+++ b/crates/trigger/src/cli.rs
@@ -11,7 +11,10 @@ use tokio::{
use spin_app::Loader;
use crate::stdio::StdioLoggingTriggerHooks;
-use crate::{config::TriggerExecutorBuilderConfig, loader::TriggerLoader, stdio::FollowComponents};
+use crate::{
+ key_value::KeyValuePersistenceMessageHook, loader::TriggerLoader,
+ runtime_config::RuntimeConfig, stdio::FollowComponents,
+};
use crate::{TriggerExecutor, TriggerExecutorBuilder};
pub const APP_LOG_DIR: &str = "APP_LOG_DIR";
@@ -22,8 +25,8 @@ pub const RUNTIME_CONFIG_FILE: &str = "RUNTIME_CONFIG_FILE";
// Set by `spin up`
pub const SPIN_LOCKED_URL: &str = "SPIN_LOCKED_URL";
+pub const SPIN_LOCAL_APP_DIR: &str = "SPIN_LOCAL_APP_DIR";
pub const SPIN_WORKING_DIR: &str = "SPIN_WORKING_DIR";
-pub const SPIN_STATE_DIR: &str = "SPIN_STATE_DIR";
/// A command that runs a TriggerExecutor.
#[derive(Parser, Debug)]
@@ -88,6 +91,15 @@ where
)]
pub runtime_config_file: Option<PathBuf>,
+ /// Set the application state directory path. This is used in the default
+ /// locations for logs, key value stores, etc.
+ ///
+ /// For local apps, this defaults to `.spin/` relative to the `spin.toml` file.
+ /// For remote apps, this has no default (unset).
+ /// Passing an empty value forces the value to be unset.
+ #[clap(long)]
+ pub state_dir: Option<String>,
+
#[clap(flatten)]
pub run_config: Executor::RunConfig,
@@ -147,29 +159,35 @@ where
loader: impl Loader + Send + Sync + 'static,
locked_url: String,
) -> Result<Executor> {
- let trigger_config =
- TriggerExecutorBuilderConfig::load_from_file(self.runtime_config_file.clone())?;
+ let runtime_config = self.build_runtime_config()?;
let _sloth_warning = warn_if_wasm_build_slothful();
let mut builder = TriggerExecutorBuilder::new(loader);
self.update_wasmtime_config(builder.wasmtime_config_mut())?;
- let logging_hooks = StdioLoggingTriggerHooks::new(self.follow_components(), self.log_dir());
- builder.hooks(logging_hooks);
+ builder.hooks(StdioLoggingTriggerHooks::new(self.follow_components()));
+ builder.hooks(KeyValuePersistenceMessageHook);
- builder.build(locked_url, trigger_config).await
+ builder.build(locked_url, runtime_config).await
}
- pub fn log_dir(&self) -> Option<PathBuf> {
- self.log.clone().or_else(|| {
- std::env::var(SPIN_STATE_DIR)
- .ok()
- .map(|dir| PathBuf::from(dir).join("logs"))
- })
+ fn build_runtime_config(&self) -> Result<RuntimeConfig> {
+ let local_app_dir = std::env::var_os(SPIN_LOCAL_APP_DIR);
+ let mut config = RuntimeConfig::new(local_app_dir.map(Into::into));
+ if let Some(state_dir) = &self.state_dir {
+ config.set_state_dir(state_dir);
+ }
+ if let Some(log_dir) = &self.log {
+ config.set_log_dir(log_dir);
+ }
+ if let Some(config_file) = &self.runtime_config_file {
+ config.merge_config_from(config_file)?;
+ }
+ Ok(config)
}
- pub fn follow_components(&self) -> FollowComponents {
+ fn follow_components(&self) -> FollowComponents {
if self.silence_component_logs {
FollowComponents::None
} else if self.follow_components.is_empty() {
diff --git a/crates/trigger/src/config.rs b/crates/trigger/src/config.rs
deleted file mode 100644
index 46818359ad..0000000000
--- a/crates/trigger/src/config.rs
+++ /dev/null
@@ -1,41 +0,0 @@
-use std::path::PathBuf;
-
-use anyhow::Result;
-use serde::Deserialize;
-use toml;
-
-// Config for config providers and wasmtime config
-#[derive(Debug, Default, Deserialize)]
-pub struct TriggerExecutorBuilderConfig {
- #[serde(rename = "config_provider", default)]
- pub config_providers: Vec<ConfigProvider>,
-}
-
-#[derive(Debug, Deserialize)]
-#[serde(rename_all = "snake_case", tag = "type")]
-pub enum ConfigProvider {
- Vault(VaultConfig),
-}
-
-// Vault config to initialize vault provider
-#[derive(Debug, Default, Deserialize)]
-pub struct VaultConfig {
- pub url: String,
- pub token: String,
- pub mount: String,
- pub prefix: Option<String>,
-}
-
-impl TriggerExecutorBuilderConfig {
- pub fn load_from_file(config_file: Option<PathBuf>) -> Result<Self> {
- let config_file = match config_file {
- Some(p) => p,
- None => {
- return Ok(Self::default());
- }
- };
- let content = std::fs::read_to_string(config_file)?;
- let config: TriggerExecutorBuilderConfig = toml::from_str(&content)?;
- Ok(config)
- }
-}
diff --git a/crates/trigger/src/key_value.rs b/crates/trigger/src/key_value.rs
new file mode 100644
index 0000000000..5ad047b8bf
--- /dev/null
+++ b/crates/trigger/src/key_value.rs
@@ -0,0 +1,64 @@
+use std::{path::Path, sync::Arc};
+
+use anyhow::{Context, Result};
+use spin_key_value::{
+ component_key_value_stores, CachingStoreManager, DelegatingStoreManager, KeyValueComponent,
+};
+use spin_key_value_sqlite::{DatabaseLocation, KeyValueSqlite};
+
+use crate::{runtime_config::RuntimeConfig, TriggerHooks};
+
+// TODO: Once we have runtime configuration for key-value stores, the user will be able
+// to both change the default store configuration (e.g. use Redis, or an SQLite
+// in-memory database, or use a different path) and add other named stores with their
+// own configurations.
+
+pub(crate) fn build_key_value_component(
+ runtime_config: &RuntimeConfig,
+) -> Result<KeyValueComponent> {
+ let location = match runtime_config.sqlite_db_path() {
+ Some(path) => {
+ // Create the store's parent directory if necessary
+ create_parent_dir(&path).context("Failed to create key value store")?;
+ DatabaseLocation::Path(path)
+ }
+ None => DatabaseLocation::InMemory,
+ };
+
+ let manager = Arc::new(CachingStoreManager::new(DelegatingStoreManager::new([(
+ "default".to_owned(),
+ Arc::new(KeyValueSqlite::new(location)) as _,
+ )])));
+
+ Ok(KeyValueComponent::new(spin_key_value::manager(move |_| {
+ manager.clone()
+ })))
+}
+
+fn create_parent_dir(path: &Path) -> Result<()> {
+ let dir = path
+ .parent()
+ .with_context(|| format!("{path:?} missing parent dir"))?;
+ std::fs::create_dir_all(dir).with_context(|| format!("Failed to create parent dir {dir:?}"))
+}
+
+pub struct KeyValuePersistenceMessageHook;
+
+impl TriggerHooks for KeyValuePersistenceMessageHook {
+ fn app_loaded(&mut self, app: &spin_app::App, runtime_config: &RuntimeConfig) -> Result<()> {
+ // Don't print anything if the app doesn't use KV
+ if app.components().all(|c| {
+ component_key_value_stores(&c)
+ .unwrap_or_default()
+ .is_empty()
+ }) {
+ return Ok(());
+ }
+ if let Some(path) = runtime_config.sqlite_db_path() {
+ println!("Storing key-value data to {path:?}");
+ } else {
+ println!("Using in-memory key-value store; data will not be saved!");
+ }
+ Ok(())
+ }
+}
diff --git a/crates/trigger/src/lib.rs b/crates/trigger/src/lib.rs
index 3adf531706..de9fa64539 100644
--- a/crates/trigger/src/lib.rs
+++ b/crates/trigger/src/lib.rs
@@ -1,34 +1,20 @@
pub mod cli;
-pub mod config;
+mod key_value;
pub mod loader;
pub mod locked;
+pub mod runtime_config;
mod stdio;
-use std::{
- collections::HashMap,
- fs,
- marker::PhantomData,
- path::{Path, PathBuf},
- sync::Arc,
-};
+use std::{collections::HashMap, marker::PhantomData, path::PathBuf};
use anyhow::{anyhow, Context, Result};
pub use async_trait::async_trait;
-use once_cell::sync::OnceCell;
+use runtime_config::RuntimeConfig;
use serde::de::DeserializeOwned;
-use url::Url;
use spin_app::{App, AppComponent, AppLoader, AppTrigger, Loader, OwnedApp};
-use spin_config::{
- provider::{env::EnvProvider, vault::VaultProvider},
- Provider,
-};
use spin_core::{Config, Engine, EngineBuilder, Instance, InstancePre, Store, StoreBuilder};
-const SPIN_CONFIG_ENV_PREFIX: &str = "SPIN_CONFIG";
-const DEFAULT_SQLITE_DB_DIRECTORY: &str = ".spin";
-const DEFAULT_SQLITE_DB_FILENAME: &str = "sqlite_key_value.db";
-
#[async_trait]
pub trait TriggerExecutor: Sized {
const TRIGGER_TYPE: &'static str;
@@ -51,7 +37,7 @@ pub trait TriggerExecutor: Sized {
pub struct TriggerExecutorBuilder<Executor: TriggerExecutor> {
loader: AppLoader,
config: Config,
- hooks: Box<dyn TriggerHooks>,
+ hooks: Vec<Box<dyn TriggerHooks>>,
disable_default_host_components: bool,
_phantom: PhantomData<Executor>,
}
@@ -62,7 +48,7 @@ impl<Executor: TriggerExecutor> TriggerExecutorBuilder<Executor> {
Self {
loader: AppLoader::new(loader),
config: Default::default(),
- hooks: Box::new(()),
+ hooks: Default::default(),
disable_default_host_components: false,
_phantom: PhantomData,
}
@@ -76,7 +62,7 @@ impl<Executor: TriggerExecutor> TriggerExecutorBuilder<Executor> {
}
pub fn hooks(&mut self, hooks: impl TriggerHooks + 'static) -> &mut Self {
- self.hooks = Box::new(hooks);
+ self.hooks.push(Box::new(hooks));
self
}
@@ -88,7 +74,7 @@ impl<Executor: TriggerExecutor> TriggerExecutorBuilder<Executor> {
pub async fn build(
mut self,
app_uri: String,
- builder_config: config::TriggerExecutorBuilderConfig,
+ runtime_config: runtime_config::RuntimeConfig,
) -> Result<Executor>
where
Executor::TriggerConfig: DeserializeOwned,
@@ -100,18 +86,9 @@ impl<Executor: TriggerExecutor> TriggerExecutorBuilder<Executor> {
builder.add_host_component(outbound_redis::OutboundRedisComponent)?;
builder.add_host_component(outbound_pg::OutboundPg::default())?;
builder.add_host_component(outbound_mysql::OutboundMysql::default())?;
-
- let manager = OnceCell::new();
-
self.loader.add_dynamic_host_component(
&mut builder,
- spin_key_value::KeyValueComponent::new(spin_key_value::manager(
- move |component| {
- manager
- .get_or_init(|| make_store_manager(component))
- .clone()
- },
- )),
+ crate::key_value::build_key_value_component(&runtime_config)?,
)?;
self.loader.add_dynamic_host_component(
&mut builder,
@@ -119,9 +96,7 @@ impl<Executor: TriggerExecutor> TriggerExecutorBuilder<Executor> {
)?;
self.loader.add_dynamic_host_component(
&mut builder,
- spin_config::ConfigHostComponent::new(
- self.get_config_providers(&app_uri, &builder_config),
- ),
+ spin_config::ConfigHostComponent::new(runtime_config.config_providers()),
)?;
}
@@ -133,46 +108,13 @@ impl<Executor: TriggerExecutor> TriggerExecutorBuilder<Executor> {
let app_name = app.borrowed().require_metadata("name")?;
- self.hooks.app_loaded(app.borrowed())?;
+ self.hooks
+ .iter_mut()
+ .try_for_each(|h| h.app_loaded(app.borrowed(), &runtime_config))?;
// Run trigger executor
Executor::new(TriggerAppEngine::new(engine, app_name, app, self.hooks).await?)
}
-
- pub fn get_config_providers(
- &self,
- app_uri: &str,
- builder_config: &config::TriggerExecutorBuilderConfig,
- ) -> Vec<Box<dyn Provider>> {
- let mut providers = self.default_config_providers(app_uri);
- for config_provider in &builder_config.config_providers {
- let provider = match config_provider {
- config::ConfigProvider::Vault(vault_config) => VaultProvider::new(
- &vault_config.url,
- &vault_config.token,
- &vault_config.mount,
- vault_config.prefix.clone(),
- ),
- };
- providers.push(Box::new(provider));
- }
- providers
- }
-
- pub fn default_config_providers(&self, app_uri: &str) -> Vec<Box<dyn Provider>> {
- // EnvProvider
- // Look for a .env file in either the manifest parent directory for local apps
- // or the current directory for remote (e.g. bindle) apps.
- let dotenv_path = parse_file_url(app_uri)
- .as_deref()
- .ok()
- .unwrap_or_else(|| Path::new("."))
- .join(".env");
- vec![Box::new(EnvProvider::new(
- SPIN_CONFIG_ENV_PREFIX,
- Some(dotenv_path),
- ))]
- }
}
/// Execution context for a TriggerExecutor executing a particular App.
@@ -184,7 +126,7 @@ pub struct TriggerAppEngine<Executor: TriggerExecutor> {
// An owned wrapper of the App.
app: OwnedApp,
// Trigger hooks
- hooks: Box<dyn TriggerHooks>,
+ hooks: Vec<Box<dyn TriggerHooks>>,
// Trigger configs for this trigger type, with order matching `app.triggers_with_type(Executor::TRIGGER_TYPE)`
trigger_configs: Vec<Executor::TriggerConfig>,
// Map of {Component ID -> InstancePre} for each component.
@@ -198,7 +140,7 @@ impl<Executor: TriggerExecutor> TriggerAppEngine<Executor> {
engine: Engine<Executor::RuntimeData>,
app_name: String,
app: OwnedApp,
- hooks: Box<dyn TriggerHooks>,
+ hooks: Vec<Box<dyn TriggerHooks>>,
) -> Result<Self>
where
<Executor as TriggerExecutor>::TriggerConfig: DeserializeOwned,
@@ -250,7 +192,8 @@ impl<Executor: TriggerExecutor> TriggerAppEngine<Executor> {
let mut builder = self.engine.store_builder();
let component = self.get_component(component_id)?;
self.hooks
- .component_store_builder(component, &mut builder)?;
+ .iter()
+ .try_for_each(|h| h.component_store_builder(&component, &mut builder))?;
Ok(builder)
}
@@ -309,7 +252,7 @@ pub trait TriggerHooks: Send + Sync {
#![allow(unused_variables)]
/// Called once, immediately after an App is loaded.
- fn app_loaded(&mut self, app: &App) -> Result<()> {
+ fn app_loaded(&mut self, app: &App, runtime_config: &RuntimeConfig) -> Result<()> {
Ok(())
}
@@ -318,7 +261,7 @@ pub trait TriggerHooks: Send + Sync {
/// environment of the instance to be executed.
fn component_store_builder(
&self,
- component: AppComponent,
+ component: &AppComponent,
store_builder: &mut StoreBuilder,
) -> Result<()> {
Ok(())
@@ -360,47 +303,3 @@ fn decode_preinstantiation_error(e: anyhow::Error) -> anyhow::Error {
e
}
-
-fn key_value_file_location(app: &App) -> Option<PathBuf> {
- let url = Url::parse(&app.get_metadata::<String>("origin").ok()??).ok()?;
- let local_spin_toml = if url.scheme() == "file" {
- url.path()
- } else {
- // Use in-memory store for remote apps.
- return None;
- };
-
- // Attempt to create or reuse a database file inside the app directory. If that's not successful, we'll use an
- // in-memory database.
- let directory = Path::new(&local_spin_toml)
- .parent()?
- .join(DEFAULT_SQLITE_DB_DIRECTORY);
-
- fs::create_dir_all(&directory).ok()?;
-
- Some(directory.join(DEFAULT_SQLITE_DB_FILENAME))
-}
-
-fn make_store_manager(component: &AppComponent) -> Arc<dyn spin_key_value::StoreManager> {
- // TODO: Once we have runtime configuration for key-value stores, the user will be able
- // to both change the default store configuration (e.g. use Redis, or an SQLite
- // in-memory database, or use a different path) and add other named stores with their
- // own configurations.
-
- Arc::new(spin_key_value::CachingStoreManager::new(
- spin_key_value::DelegatingStoreManager::new(
- [(
- "default".to_owned(),
- Arc::new(spin_key_value_sqlite::KeyValueSqlite::new(
- if let Some(key_value_file) = key_value_file_location(component.app) {
- spin_key_value_sqlite::DatabaseLocation::Path(key_value_file)
- } else {
- spin_key_value_sqlite::DatabaseLocation::InMemory
- },
- )) as Arc<dyn spin_key_value::StoreManager>,
- )]
- .into_iter()
- .collect(),
- ),
- ))
-}
diff --git a/crates/trigger/src/runtime_config.rs b/crates/trigger/src/runtime_config.rs
new file mode 100644
index 0000000000..f0f606a650
--- /dev/null
+++ b/crates/trigger/src/runtime_config.rs
@@ -0,0 +1,265 @@
+use std::path::{Path, PathBuf};
+
+use anyhow::{Context, Result};
+use serde::Deserialize;
+use spin_config::provider::{env::EnvProvider, vault::VaultProvider};
+use toml;
+
+pub const DEFAULT_STATE_DIR: &str = ".spin";
+const DEFAULT_LOGS_DIR: &str = "logs";
+
+const SPIN_CONFIG_ENV_PREFIX: &str = "SPIN_CONFIG";
+
+const DEFAULT_SQLITE_DB_FILENAME: &str = "sqlite_key_value.db";
+
+/// RuntimeConfig allows multiple sources of runtime configuration to be
+/// queried uniformly.
+#[derive(Debug, Default)]
+pub struct RuntimeConfig {
+ local_app_dir: Option<PathBuf>,
+ files: Vec<RuntimeConfigOpts>,
+ overrides: RuntimeConfigOpts,
+}
+
+impl RuntimeConfig {
+ // Gives more consistent conditional branches
+ #![allow(clippy::manual_map)]
+
+ pub fn new(local_app_dir: Option<PathBuf>) -> Self {
+ Self {
+ local_app_dir: local_app_dir.map(Into::into),
+ ..Default::default()
+ }
+ }
+
+ /// Load a runtime config file from the given path. Options specified in a
+ /// later-loaded file take precedence over any earlier-loaded files.
+ pub fn merge_config_from(&mut self, path: impl AsRef<Path>) -> Result<()> {
+ let path = path.as_ref();
+ let bytes = std::fs::read(path)
+ .with_context(|| format!("Failed to load runtime config file {path:?}"))?;
+ let opts = toml::from_slice(&bytes)
+ .with_context(|| format!("Failed to parse runtime config file {path:?}"))?;
+ self.files.push(opts);
+ Ok(())
+ }
+
+ /// Return an iterator of configured spin_config::Providers.
+ pub fn config_providers(&self) -> Vec<BoxedConfigProvider> {
+ // Default EnvProvider
+ let dotenv_path = self.local_app_dir.as_deref().map(|path| path.join(".env"));
+ let env_provider = EnvProvider::new(SPIN_CONFIG_ENV_PREFIX, dotenv_path);
+
+ let mut providers: Vec<BoxedConfigProvider> = vec![Box::new(env_provider)];
+ providers.extend(self.opts_layers().flat_map(|opts| {
+ opts.config_providers
+ .iter()
+ .map(Self::build_config_provider)
+ }));
+ providers
+ }
+
+ fn build_config_provider(provider_config: &ConfigProvider) -> BoxedConfigProvider {
+ match provider_config {
+ ConfigProvider::Vault(VaultConfig {
+ url,
+ token,
+ mount,
+ prefix,
+ }) => Box::new(VaultProvider::new(url, token, mount, prefix.as_deref())),
+ }
+ }
+
+ /// Set the state dir, overriding any other runtime config source.
+ pub fn set_state_dir(&mut self, state_dir: impl Into<String>) {
+ self.overrides.state_dir = Some(state_dir.into());
+ }
+
+ /// Return the state dir if set.
+ pub fn state_dir(&self) -> Option<PathBuf> {
+ if let Some(path_str) = self.find_opt(|opts| &opts.state_dir) {
+ if path_str.is_empty() {
+ None // An empty string forces the state dir to be unset
+ } else {
+ Some(path_str.into())
+ }
+ } else if let Some(app_dir) = &self.local_app_dir {
+ // If we're running a local app, return the default state dir
+ Some(app_dir.join(DEFAULT_STATE_DIR))
+ } else {
+ None
+ }
+ }
+
+ /// Set the log dir, overriding any other runtime config source.
+ pub fn set_log_dir(&mut self, log_dir: impl Into<PathBuf>) {
+ self.overrides.log_dir = Some(log_dir.into());
+ }
+
+ /// Return the log dir if set.
+ pub fn log_dir(&self) -> Option<PathBuf> {
+ if let Some(path) = self.find_opt(|opts| &opts.log_dir) {
+ // If there is an explicit log dir set, return it
+ Some(path.into())
+ } else if let Some(state_dir) = self.state_dir() {
+ // If the state dir is set, build the default path
+ Some(state_dir.join(DEFAULT_LOGS_DIR))
+ } else {
+ None
+ }
+ }
+
+ /// Return a path to the sqlite DB if set.
+ pub fn sqlite_db_path(&self) -> Option<PathBuf> {
+ if let Some(state_dir) = self.state_dir() {
+ // If the state dir is set, build the default path
+ Some(state_dir.join(DEFAULT_SQLITE_DB_FILENAME))
+ } else {
+ None
+ }
+ }
+
+ /// Returns an iterator of RuntimeConfigOpts in order of decreasing precedence
+ fn opts_layers(&self) -> impl Iterator<Item = &RuntimeConfigOpts> {
+ std::iter::once(&self.overrides).chain(self.files.iter().rev())
+ }
+
+ /// Returns the highest precedence RuntimeConfigOpts Option that is set
+ fn find_opt<T>(&self, mut f: impl FnMut(&RuntimeConfigOpts) -> &Option<T>) -> Option<&T> {
+ self.opts_layers().find_map(|opts| f(opts).as_ref())
+ }
+}
+
+#[derive(Debug, Default, Deserialize)]
+#[serde(deny_unknown_fields)]
+struct RuntimeConfigOpts {
+ #[serde(default)]
+ pub state_dir: Option<String>,
+
+ #[serde(default)]
+ pub log_dir: Option<PathBuf>,
+
+ #[serde(rename = "config_provider", default)]
+ pub config_providers: Vec<ConfigProvider>,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "snake_case", tag = "type")]
+pub enum ConfigProvider {
+ Vault(VaultConfig),
+}
+
+// Vault config to initialize vault provider
+#[derive(Debug, Default, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct VaultConfig {
+ pub url: String,
+ pub token: String,
+ pub mount: String,
+ pub prefix: Option<String>,
+}
+
+type BoxedConfigProvider = Box<dyn spin_config::Provider>;
+
+#[cfg(test)]
+mod tests {
+ use std::io::Write;
+
+ use tempfile::NamedTempFile;
+ use toml::toml;
+
+ use super::*;
+
+ #[test]
+ fn defaults_without_local_app_dir() -> Result<()> {
+ let config = RuntimeConfig::new(None);
+
+ assert_eq!(config.state_dir(), None);
+ assert_eq!(config.log_dir(), None);
+ assert_eq!(config.sqlite_db_path(), None);
+
+ Ok(())
+ }
+
+ #[test]
+ fn defaults_with_local_app_dir() -> Result<()> {
+ let app_dir = tempfile::tempdir()?;
+ let config = RuntimeConfig::new(Some(app_dir.path().into()));
+
+ let state_dir = config.state_dir().unwrap();
+ assert!(state_dir.starts_with(&app_dir));
+
+ let log_dir = config.log_dir().unwrap();
+ assert!(log_dir.starts_with(&state_dir));
+
+ let sqlite_db_path = config.sqlite_db_path().unwrap();
+ assert!(sqlite_db_path.starts_with(&state_dir));
+
+ Ok(())
+ }
+
+ #[test]
+ fn state_dir_force_unset() -> Result<()> {
+ let app_dir = tempfile::tempdir()?;
+ let mut config = RuntimeConfig::new(Some(app_dir.path().into()));
+ assert!(config.state_dir().is_some());
+
+ config.set_state_dir("");
+ assert!(config.state_dir().is_none());
+
+ Ok(())
+ }
+
+ #[test]
+ fn opts_layers_precedence() -> Result<()> {
+ let mut config = RuntimeConfig::new(None);
+
+ config.merge_config_from(toml_tempfile(toml! {
+ state_dir = "file-state-dir"
+ log_dir = "file-log-dir"
+ })?)?;
+
+ let state_dir = config.state_dir().unwrap();
+ assert_eq!(state_dir.as_os_str(), "file-state-dir");
+
+ let log_dir = config.log_dir().unwrap();
+ assert_eq!(log_dir.as_os_str(), "file-log-dir");
+
+ config.set_state_dir("override-state-dir");
+ config.set_log_dir("override-log-dir");
+
+ let state_dir = config.state_dir().unwrap();
+ assert_eq!(state_dir.as_os_str(), "override-state-dir");
+
+ let log_dir = config.log_dir().unwrap();
+ assert_eq!(log_dir.as_os_str(), "override-log-dir");
+
+ Ok(())
+ }
+
+ #[test]
+ fn config_providers_from_file() -> Result<()> {
+ let mut config = RuntimeConfig::new(None);
+
+ // One default provider
+ assert_eq!(config.config_providers().len(), 1);
+
+ config.merge_config_from(toml_tempfile(toml! {
+ [[config_provider]]
+ type = "vault"
+ url = "http://vault"
+ token = "secret"
+ mount = "root"
+ })?)?;
+ assert_eq!(config.config_providers().len(), 2);
+
+ Ok(())
+ }
+
+ fn toml_tempfile(value: toml::Value) -> Result<NamedTempFile> {
+ let data = toml::to_vec(&value)?;
+ let mut file = NamedTempFile::new()?;
+ file.write_all(&data)?;
+ Ok(file)
+ }
+}
diff --git a/crates/trigger/src/stdio.rs b/crates/trigger/src/stdio.rs
index ca6c6d66e6..147fcc07f9 100644
--- a/crates/trigger/src/stdio.rs
+++ b/crates/trigger/src/stdio.rs
@@ -6,7 +6,7 @@ use std::{
use anyhow::{Context, Result};
-use crate::TriggerHooks;
+use crate::{runtime_config::RuntimeConfig, TriggerHooks};
/// Which components should have their logs followed on stdout/stderr.
#[derive(Clone, Debug)]
@@ -43,10 +43,10 @@ pub struct StdioLoggingTriggerHooks {
}
impl StdioLoggingTriggerHooks {
- pub fn new(follow_components: FollowComponents, log_dir: Option<PathBuf>) -> Self {
+ pub fn new(follow_components: FollowComponents) -> Self {
Self {
follow_components,
- log_dir,
+ log_dir: None,
}
}
@@ -84,13 +84,21 @@ impl StdioLoggingTriggerHooks {
}
impl TriggerHooks for StdioLoggingTriggerHooks {
- fn app_loaded(&mut self, app: &spin_app::App) -> anyhow::Result<()> {
+ fn app_loaded(
+ &mut self,
+ app: &spin_app::App,
+ runtime_config: &RuntimeConfig,
+ ) -> anyhow::Result<()> {
+ self.log_dir = runtime_config.log_dir();
+
self.validate_follows(app)?;
- // Ensure log dir exists if set
- if let Some(l) = &self.log_dir {
- std::fs::create_dir_all(l)
- .with_context(|| format!("Failed to create log dir {l:?}"))?;
+ if let Some(dir) = &self.log_dir {
+ // Ensure log dir exists if set
+ std::fs::create_dir_all(dir)
+ .with_context(|| format!("Failed to create log dir {dir:?}"))?;
+
+ println!("Logging component stdio to {:?}", dir.join(""))
}
Ok(())
@@ -98,7 +106,7 @@ impl TriggerHooks for StdioLoggingTriggerHooks {
fn component_store_builder(
&self,
- component: spin_app::AppComponent,
+ component: &spin_app::AppComponent,
builder: &mut spin_core::StoreBuilder,
) -> anyhow::Result<()> {
match &self.log_dir {
diff --git a/src/commands/up.rs b/src/commands/up.rs
index 400a8fc79e..a88b442ff9 100644
--- a/src/commands/up.rs
+++ b/src/commands/up.rs
@@ -11,7 +11,7 @@ use spin_app::locked::LockedApp;
use spin_loader::bindle::{deprecation::print_bindle_deprecation, BindleConnectionInfo};
use spin_manifest::ApplicationTrigger;
use spin_oci::OciLoader;
-use spin_trigger::cli::{SPIN_LOCKED_URL, SPIN_STATE_DIR, SPIN_WORKING_DIR};
+use spin_trigger::cli::{SPIN_LOCAL_APP_DIR, SPIN_LOCKED_URL, SPIN_WORKING_DIR};
use tempfile::TempDir;
use crate::opts::*;
@@ -186,12 +186,12 @@ impl UpCommand {
self.update_locked_app(&mut locked_app);
- let state_dir = self.prepare_state_dir(&app_source);
+ let local_app_dir = app_source.local_app_dir().map(Into::into);
let run_opts = RunTriggerOpts {
locked_app,
working_dir,
- state_dir,
+ local_app_dir,
};
self.run_trigger(trigger_cmd, Some(run_opts)).await
@@ -210,7 +210,7 @@ impl UpCommand {
if let Some(RunTriggerOpts {
locked_app,
working_dir,
- state_dir,
+ local_app_dir,
}) = opts
{
let locked_url = self.write_locked_app(&locked_app, &working_dir).await?;
@@ -219,8 +219,8 @@ impl UpCommand {
.env(SPIN_WORKING_DIR, &working_dir)
.args(&self.trigger_args);
- if let Some(state_dir) = state_dir {
- cmd.env(SPIN_STATE_DIR, state_dir);
+ if let Some(local_app_dir) = local_app_dir {
+ cmd.env(SPIN_LOCAL_APP_DIR, local_app_dir);
}
} else {
cmd.arg("--help-args-only");
@@ -395,13 +395,6 @@ impl UpCommand {
spin_trigger::locked::build_locked_app(app, working_dir)
}
- fn prepare_state_dir(&self, source: &AppSource) -> Option<PathBuf> {
- match source {
- AppSource::File(path) => Some(path.parent().unwrap().join(".spin")),
- _ => None,
- }
- }
-
fn update_locked_app(&self, locked_app: &mut LockedApp) {
// Apply --env to component environments
if !self.env.is_empty() {
@@ -415,7 +408,7 @@ impl UpCommand {
struct RunTriggerOpts {
locked_app: LockedApp,
working_dir: PathBuf,
- state_dir: Option<PathBuf>,
+ local_app_dir: Option<PathBuf>,
}
enum WorkingDirectory {
@@ -510,6 +503,16 @@ impl AppSource {
fn unresolvable(message: impl Into<String>) -> Self {
Self::Unresolvable(message.into())
}
+
+ fn local_app_dir(&self) -> Option<&Path> {
+ match self {
+ Self::File(path) => path.parent().or_else(|| {
+ tracing::warn!("Error finding local app dir from source {path:?}");
+ None
+ }),
+ _ => None,
+ }
+ }
}
#[cfg(test)]
| 1,245
|
[
"1175"
] |
diff --git a/crates/testing/src/lib.rs b/crates/testing/src/lib.rs
index 7bf3f9c097..f2abf4234e 100644
--- a/crates/testing/src/lib.rs
+++ b/crates/testing/src/lib.rs
@@ -18,7 +18,7 @@ use spin_app::{
};
use spin_core::{Module, StoreBuilder};
use spin_http::{HttpExecutorType, HttpTriggerConfig, WagiTriggerConfig};
-use spin_trigger::{config::TriggerExecutorBuilderConfig, TriggerExecutor, TriggerExecutorBuilder};
+use spin_trigger::{runtime_config::RuntimeConfig, TriggerExecutor, TriggerExecutorBuilder};
pub use tokio;
@@ -100,10 +100,7 @@ impl HttpTestConfig {
Executor::TriggerConfig: DeserializeOwned,
{
TriggerExecutorBuilder::new(self.build_loader())
- .build(
- TEST_APP_URI.to_string(),
- TriggerExecutorBuilderConfig::default(),
- )
+ .build(TEST_APP_URI.to_string(), RuntimeConfig::default())
.await
.unwrap()
}
@@ -139,10 +136,7 @@ impl RedisTestConfig {
self.redis_channel = channel.into();
TriggerExecutorBuilder::new(self.build_loader())
- .build(
- TEST_APP_URI.to_string(),
- TriggerExecutorBuilderConfig::default(),
- )
+ .build(TEST_APP_URI.to_string(), RuntimeConfig::default())
.await
.unwrap()
}
|
7f0d5460125dbff96b4bba1a32ca8750d17b0bd0
|
8f33ca92dd863fa935f60c0a4ef393de4c464cad
|
Catch invalid key/value store at build time
Currently, Spin's SQLite key value feature only supports a single `"default"` store per application. The implementation [hard codes only supporting this store](https://github.com/fermyon/spin/blob/665d3a023d2a192b12f32dedec9d89b8fd9f9e7e/crates/trigger/src/lib.rs#L393). Access to this store is granted by the user on the component level in a `Spin.toml`, so to grant my `hello` component access to the store I do the following:
```toml
[[component]]
id = "hello"
source = "target/wasm32-wasi/release/rust_key_value.wasm"
key_value_stores = ["default"]
```
However, currently I can do the following and build and run an application without an error on `spin build --up`. Only when my app tries `Store::open("foo")` during runtime is a `NoSuchStore` error returned. Which as a user may not make sense since I added it to the component:
```
[[component]]
id = "hello"
source = "target/wasm32-wasi/release/rust_key_value.wasm"
key_value_stores = ["default", "foo"]
# OR the following
# key_value_stores = ["foo"]
```
Clear documentation on default store only may suffice, but catching during build time may be better.
|
Just to clarify: this would happen at `spin up` time (which would include `spin build --up`). We don't know what stores are available at build time (or won't, once multiple stores are available).
I hadn't realised this. This has docs impact too.
I'd argue this shouldn't prevent build:
* I want to be able to check that my code compiles without needing to sort out my `spin.toml`
* I can build my code without going through `spin build`
My suggestion would be to put this check next to `allowed_http_hosts` validation in the various `validate_raw_app_manifest` functions. (I did notice that OCI manifests are validated on _upload_ not download, which is fine today but could cause a problem if a future version of Spin allowed alternative stores, and uploaded an OCI manifest that was then downloaded by an earlier version of Spin that didn't.)
|
2023-03-07T02:57:30Z
|
fermyon__spin-1235
|
fermyon/spin
|
3.1
|
diff --git a/crates/loader/src/lib.rs b/crates/loader/src/lib.rs
index 0eb307f33c..7ce84abf43 100644
--- a/crates/loader/src/lib.rs
+++ b/crates/loader/src/lib.rs
@@ -16,6 +16,7 @@ pub mod cache;
mod common;
pub mod digest;
pub mod local;
+mod validation;
/// Load a Spin application configuration from a spin.toml manifest file.
pub use local::from_file;
diff --git a/crates/loader/src/local/mod.rs b/crates/loader/src/local/mod.rs
index 73426f915e..7745c551f4 100644
--- a/crates/loader/src/local/mod.rs
+++ b/crates/loader/src/local/mod.rs
@@ -28,7 +28,10 @@ use spin_manifest::{
};
use tokio::{fs::File, io::AsyncReadExt};
-use crate::{bindle::BindleConnectionInfo, cache::Cache, digest::bytes_sha256_string};
+use crate::{
+ bindle::BindleConnectionInfo, cache::Cache, digest::bytes_sha256_string,
+ validation::validate_key_value_stores,
+};
use config::{
FileComponentUrlSource, RawAppInformation, RawAppManifest, RawAppManifestAnyVersion,
RawAppManifestAnyVersionPartial, RawComponentManifest, RawComponentManifestPartial,
@@ -126,6 +129,10 @@ pub fn validate_raw_app_manifest(raw: &RawAppManifestAnyVersion) -> Result<()> {
.components
.iter()
.try_for_each(|c| validate_allowed_http_hosts(&c.wasm.allowed_http_hosts))?;
+ manifest
+ .components
+ .iter()
+ .try_for_each(|c| validate_key_value_stores(&c.wasm.key_value_stores))?;
if raw
.as_v1()
diff --git a/crates/loader/src/validation.rs b/crates/loader/src/validation.rs
new file mode 100644
index 0000000000..64eba82e5c
--- /dev/null
+++ b/crates/loader/src/validation.rs
@@ -0,0 +1,48 @@
+use anyhow::{anyhow, Result};
+
+const ONLY_ALLOWED_KV_STORE: &str = "default";
+
+pub(crate) fn validate_key_value_stores(key_value_stores: &Option<Vec<String>>) -> Result<()> {
+ match key_value_stores
+ .iter()
+ .flatten()
+ .find(|id| *id != ONLY_ALLOWED_KV_STORE)
+ {
+ None => Ok(()),
+ Some(invalid) => {
+ let err = anyhow!("Invalid key-value store '{invalid}'. This version of Spin supports only the '{ONLY_ALLOWED_KV_STORE}' store.");
+ Err(err)
+ }
+ }
+}
+
+#[cfg(test)]
+mod test {
+ use super::*;
+
+ #[test]
+ fn kv_empty_list_is_allowed() {
+ validate_key_value_stores(&None).expect("None should be valid");
+ validate_key_value_stores(&Some(vec![])).expect("Empty vector should be valid");
+ }
+
+ #[test]
+ fn default_store_is_allowed() {
+ validate_key_value_stores(&Some(vec!["default".to_owned()]))
+ .expect("Default store should be valid");
+ validate_key_value_stores(&Some(vec!["default".to_owned(), "default".to_owned()]))
+ .expect("Default store twice should be valid");
+ }
+
+ #[test]
+ fn non_default_store_is_not_allowed() {
+ validate_key_value_stores(&Some(vec!["hello".to_owned()]))
+ .expect_err("'hello' store should be invalid");
+ }
+
+ #[test]
+ fn no_sneaky_hiding_non_default_store_behind_default_one() {
+ validate_key_value_stores(&Some(vec!["default".to_owned(), "hello".to_owned()]))
+ .expect_err("'hello' store should be invalid");
+ }
+}
| 1,235
|
[
"1232"
] |
diff --git a/tests/testcases/key-value/spin.toml b/tests/testcases/key-value/spin.toml
index 764ebdaad0..7891c0bca1 100644
--- a/tests/testcases/key-value/spin.toml
+++ b/tests/testcases/key-value/spin.toml
@@ -7,7 +7,7 @@ version = "1.0.0"
[[component]]
id = "hello"
-key_value_stores = ["default", "foo"]
+key_value_stores = ["default"]
source = "target/wasm32-wasi/release/key_value.wasm"
[component.trigger]
route = "/..."
diff --git a/tests/testcases/key-value/src/lib.rs b/tests/testcases/key-value/src/lib.rs
index d257879ccc..a6886e12c0 100644
--- a/tests/testcases/key-value/src/lib.rs
+++ b/tests/testcases/key-value/src/lib.rs
@@ -7,7 +7,8 @@ use spin_sdk::{
#[http_component]
fn handle_request(_req: Request) -> Result<Response> {
- ensure!(matches!(Store::open("foo"), Err(Error::NoSuchStore)));
+ // TODO: once we allow users to pass non-default stores, test that opening
+ // an allowed-but-non-existent one returns Error::NoSuchStore
ensure!(matches!(Store::open("forbidden"), Err(Error::AccessDenied)));
let store = Store::open_default()?;
|
7f0d5460125dbff96b4bba1a32ca8750d17b0bd0
|
3da388c68704a21fd6292987b4e9ddb1079d2984
|
Warnings on clean build of new Rust app
We had this before, I think, and got rid of it, but I can't remember how, sorry.

|
Previous occurrence was #793 which was fixed in #862. Looks like the fix is to rename the example and test crates?
Is this worth having an integration/SDK test to detect?
|
2023-02-22T21:35:06Z
|
fermyon__spin-1192
|
fermyon/spin
|
0.9
|
diff --git a/examples/rust-key-value/Cargo.toml b/examples/rust-key-value/Cargo.toml
index 55b8526fd4..186ac88ea8 100644
--- a/examples/rust-key-value/Cargo.toml
+++ b/examples/rust-key-value/Cargo.toml
@@ -1,5 +1,5 @@
[package]
-name = "spin-key-value"
+name = "rust-key-value"
version = "0.1.0"
edition = "2021"
diff --git a/examples/rust-key-value/spin.toml b/examples/rust-key-value/spin.toml
index e1d8cee847..81ab76be6c 100644
--- a/examples/rust-key-value/spin.toml
+++ b/examples/rust-key-value/spin.toml
@@ -7,7 +7,7 @@ version = "1.0.0"
[[component]]
id = "hello"
-source = "target/wasm32-wasi/release/spin_key_value.wasm"
+source = "target/wasm32-wasi/release/rust_key_value.wasm"
key_value_stores = ["default"]
[component.trigger]
route = "/..."
| 1,192
|
[
"1186"
] |
diff --git a/tests/testcases/headers-dynamic-env-test/Cargo.toml b/tests/testcases/headers-dynamic-env-test/Cargo.toml
index b38cc622cb..7da7cec6e7 100644
--- a/tests/testcases/headers-dynamic-env-test/Cargo.toml
+++ b/tests/testcases/headers-dynamic-env-test/Cargo.toml
@@ -1,5 +1,5 @@
[package]
-name = "env"
+name = "headers-dynamic-env-test"
version = "0.1.0"
edition = "2021"
diff --git a/tests/testcases/headers-dynamic-env-test/spin.toml b/tests/testcases/headers-dynamic-env-test/spin.toml
index 2446972447..09392d4b02 100644
--- a/tests/testcases/headers-dynamic-env-test/spin.toml
+++ b/tests/testcases/headers-dynamic-env-test/spin.toml
@@ -7,7 +7,7 @@ trigger = {type = "http", base = "/"}
[[component]]
id = "env"
-source = "target/wasm32-wasi/release/env.wasm"
+source = "target/wasm32-wasi/release/headers_dynamic_env_test.wasm"
environment = { some_key = "some_value" }
[component.build]
command = "cargo build --target wasm32-wasi --release"
diff --git a/tests/testcases/headers-env-routes-test/Cargo.toml b/tests/testcases/headers-env-routes-test/Cargo.toml
index b38cc622cb..4009dc8b59 100644
--- a/tests/testcases/headers-env-routes-test/Cargo.toml
+++ b/tests/testcases/headers-env-routes-test/Cargo.toml
@@ -1,5 +1,5 @@
[package]
-name = "env"
+name = "headers-env-routes-test"
version = "0.1.0"
edition = "2021"
diff --git a/tests/testcases/headers-env-routes-test/spin.toml b/tests/testcases/headers-env-routes-test/spin.toml
index 919027b84e..b6aff444ac 100644
--- a/tests/testcases/headers-env-routes-test/spin.toml
+++ b/tests/testcases/headers-env-routes-test/spin.toml
@@ -7,7 +7,7 @@ trigger = {type = "http", base = "/"}
[[component]]
id = "env"
-source = "target/wasm32-wasi/release/env.wasm"
+source = "target/wasm32-wasi/release/headers_env_routes_test.wasm"
environment = { some_key = "some_value" }
[component.trigger]
route = "/env/..."
diff --git a/tests/testcases/http-rust-outbound-mysql/Cargo.toml b/tests/testcases/http-rust-outbound-mysql/Cargo.toml
index cd56000c5c..56c2cc04dd 100644
--- a/tests/testcases/http-rust-outbound-mysql/Cargo.toml
+++ b/tests/testcases/http-rust-outbound-mysql/Cargo.toml
@@ -1,5 +1,5 @@
[package]
-name = "http-rust-outbound-mysql"
+name = "http-rust-outbound-mysql-test"
version = "0.1.0"
edition = "2021"
diff --git a/tests/testcases/http-rust-outbound-mysql/spin.toml b/tests/testcases/http-rust-outbound-mysql/spin.toml
index 08df23e2bc..4d6a2b4b27 100644
--- a/tests/testcases/http-rust-outbound-mysql/spin.toml
+++ b/tests/testcases/http-rust-outbound-mysql/spin.toml
@@ -7,7 +7,7 @@ version = "0.1.0"
[[component]]
environment = { DB_URL = "mysql://spin:spin@mysql/spin_dev" }
id = "outbound-mysql"
-source = "target/wasm32-wasi/release/http_rust_outbound_mysql.wasm"
+source = "target/wasm32-wasi/release/http_rust_outbound_mysql_test.wasm"
[component.trigger]
route = "/..."
[component.build]
diff --git a/tests/testcases/simple-spin-rust-test/Cargo.toml b/tests/testcases/simple-spin-rust-test/Cargo.toml
index 9b78c752cd..05cfb75003 100644
--- a/tests/testcases/simple-spin-rust-test/Cargo.toml
+++ b/tests/testcases/simple-spin-rust-test/Cargo.toml
@@ -1,5 +1,5 @@
[package]
-name = "simple-spin-rust"
+name = "simple-spin-rust-test"
version = "0.1.0"
edition = "2021"
diff --git a/tests/testcases/simple-spin-rust-test/spin.toml b/tests/testcases/simple-spin-rust-test/spin.toml
index 730dd809c2..e8c070bc8a 100644
--- a/tests/testcases/simple-spin-rust-test/spin.toml
+++ b/tests/testcases/simple-spin-rust-test/spin.toml
@@ -10,7 +10,7 @@ object = { default = "teapot" }
[[component]]
id = "hello"
-source = "target/wasm32-wasi/release/simple_spin_rust.wasm"
+source = "target/wasm32-wasi/release/simple_spin_rust_test.wasm"
files = [ { source = "assets", destination = "/" } ]
[component.trigger]
route = "/hello/..."
|
3da388c68704a21fd6292987b4e9ddb1079d2984
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.