Dataset Viewer
Auto-converted to Parquet Duplicate
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
sequencelengths
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\nCurrently, the route matching in spin can be of two(...TRUNCATED)
"I'm not necessarily opposed to this but just want to note that V2 manifests help with a workaround (...TRUNCATED)
2024-04-22T03:53:13Z
fermyon__spin-2464
fermyon/spin
3.2
"diff --git a/Cargo.lock b/Cargo.lock\nindex 3242c114aa..d8b01f0cf2 100644\n--- a/Cargo.lock\n+++ b/(...TRUNCATED)
2,464
[ "1923" ]
"diff --git a/tests/integration.rs b/tests/integration.rs\nindex 9e30952a35..1a4fe2acbe 100644\n--- (...TRUNCATED)
c02196882a336d46c3dd5fcfafeed45ef0a4490e
d6b9713c311208a250185f326987f3dcf651517c
"In `component.files`, mapping a single file to `/` gives an unhelpful error\nThe `component.files` (...TRUNCATED)
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\nindex f9d019c737..c6e122ab94 (...TRUNCATED)
2,460
[ "2361" ]
"diff --git a/crates/loader/tests/file-errors/bad.toml b/crates/loader/tests/file-errors/bad.toml\nn(...TRUNCATED)
c02196882a336d46c3dd5fcfafeed45ef0a4490e
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
1