Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add general-purpose execute function to outbound-redis #1134

Merged
merged 5 commits into from Feb 14, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
104 changes: 73 additions & 31 deletions crates/abi-conformance/src/outbound_redis.rs
@@ -1,5 +1,6 @@
use super::Context;
use anyhow::{ensure, Result};
use outbound_redis::{Error, ValueParam, ValueResult};
use serde::Serialize;
use std::collections::{HashMap, HashSet};
use wasmtime::{InstancePre, Store};
Expand Down Expand Up @@ -76,6 +77,15 @@ pub struct RedisReport {
/// "baz"))` as the result. The host will assert that said function is called exactly once with the specified
/// arguments.
pub smembers: Result<(), String>,

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As a total aside, it would be interesting to run these conformance tests under tarpaulin.

/// Result of the Redis `execute` test
///
/// The guest module should expect a call according to [`super::InvocationStyle`] with
/// \["outbound-redis-execute", "127.0.0.1", "append", "foo", "baz"\] as arguments. The module should call the
/// host-implemented `outbound-redis::execute` function with the arguments \["127.0.0.1", "append", "foo",
/// "baz"\] and expect `ok(list(value::int(3)))` as the result. The host will assert that said function is
/// called exactly once with the specified arguments.
pub execute: Result<(), String>,
}

wit_bindgen_wasmtime::export!("../../wit/ephemeral/outbound-redis.wit");
Expand All @@ -90,92 +100,93 @@ pub(super) struct OutboundRedis {
sadd_map: HashMap<(String, String, Vec<String>), i64>,
srem_map: HashMap<(String, String, Vec<String>), i64>,
smembers_map: HashMap<(String, String), Vec<String>>,
execute_map: HashMap<(String, String, Vec<String>), Vec<ValueResult>>,
}

impl outbound_redis::OutboundRedis for OutboundRedis {
fn publish(
&mut self,
address: &str,
channel: &str,
payload: &[u8],
) -> Result<(), outbound_redis::Error> {
fn publish(&mut self, address: &str, channel: &str, payload: &[u8]) -> Result<(), Error> {
if self
.publish_set
.remove(&(address.to_owned(), channel.to_owned(), payload.to_vec()))
{
Ok(())
} else {
Err(outbound_redis::Error::Error)
Err(Error::Error)
}
}

fn get(&mut self, address: &str, key: &str) -> Result<Vec<u8>, outbound_redis::Error> {
fn get(&mut self, address: &str, key: &str) -> Result<Vec<u8>, Error> {
self.get_map
.remove(&(address.to_owned(), key.to_owned()))
.ok_or(outbound_redis::Error::Error)
.ok_or(Error::Error)
}

fn set(&mut self, address: &str, key: &str, value: &[u8]) -> Result<(), outbound_redis::Error> {
fn set(&mut self, address: &str, key: &str, value: &[u8]) -> Result<(), Error> {
if self
.set_set
.remove(&(address.to_owned(), key.to_owned(), value.to_vec()))
{
Ok(())
} else {
Err(outbound_redis::Error::Error)
Err(Error::Error)
}
}

fn incr(&mut self, address: &str, key: &str) -> Result<i64, outbound_redis::Error> {
fn incr(&mut self, address: &str, key: &str) -> Result<i64, Error> {
self.incr_map
.remove(&(address.to_owned(), key.to_owned()))
.map(|value| value + 1)
.ok_or(outbound_redis::Error::Error)
.ok_or(Error::Error)
}

fn del(&mut self, address: &str, keys: Vec<&str>) -> Result<i64, outbound_redis::Error> {
fn del(&mut self, address: &str, keys: Vec<&str>) -> Result<i64, Error> {
self.del_map
.remove(&(
address.into(),
keys.into_iter().map(|s| s.to_owned()).collect(),
))
.ok_or(outbound_redis::Error::Error)
.ok_or(Error::Error)
}

fn sadd(
&mut self,
address: &str,
key: &str,
values: Vec<&str>,
) -> Result<i64, outbound_redis::Error> {
fn sadd(&mut self, address: &str, key: &str, values: Vec<&str>) -> Result<i64, Error> {
self.sadd_map
.remove(&(
address.into(),
key.to_owned(),
values.into_iter().map(|s| s.to_owned()).collect(),
))
.ok_or(outbound_redis::Error::Error)
.ok_or(Error::Error)
}

fn srem(
&mut self,
address: &str,
key: &str,
values: Vec<&str>,
) -> Result<i64, outbound_redis::Error> {
fn srem(&mut self, address: &str, key: &str, values: Vec<&str>) -> Result<i64, Error> {
self.srem_map
.remove(&(
address.into(),
key.to_owned(),
values.into_iter().map(|s| s.to_owned()).collect(),
))
.ok_or(outbound_redis::Error::Error)
.ok_or(Error::Error)
}

fn smembers(&mut self, address: &str, key: &str) -> Result<Vec<String>, outbound_redis::Error> {
fn smembers(&mut self, address: &str, key: &str) -> Result<Vec<String>, Error> {
self.smembers_map
.remove(&(address.into(), key.to_owned()))
.ok_or(outbound_redis::Error::Error)
.ok_or(Error::Error)
}

fn execute(
&mut self,
address: &str,
command: &str,
arguments: Vec<ValueParam<'_>>,
) -> Result<Vec<ValueResult>, Error> {
self.execute_map
.remove(&(
address.into(),
command.to_owned(),
arguments.iter().map(|v| format!("{v:?}")).collect(),
))
.ok_or(Error::Error)
}
}

Expand Down Expand Up @@ -360,5 +371,36 @@ pub(super) fn test(store: &mut Store<Context>, pre: &InstancePre<Context>) -> Re
},
)
},

execute: {
store.data_mut().outbound_redis.execute_map.insert(
(
"127.0.0.1".into(),
"append".to_owned(),
vec!["foo".to_owned(), "baz".to_owned()],
),
vec![ValueResult::Int(3)],
);

super::run_command(
store,
pre,
&[
"outbound-redis-execute",
"127.0.0.1",
"append",
"foo",
"baz",
],
|store| {
ensure!(
store.data().outbound_redis.execute_map.is_empty(),
"expected module to call `outbound-redis::execute` exactly once"
);

Ok(())
},
)
},
})
}
51 changes: 49 additions & 2 deletions crates/outbound-redis/src/lib.rs
Expand Up @@ -3,13 +3,33 @@ mod host_component;
use std::collections::{hash_map::Entry, HashMap};

use anyhow::Result;
use redis::{aio::Connection, AsyncCommands};
use redis::{aio::Connection, AsyncCommands, FromRedisValue, RedisResult, Value};
use wit_bindgen_wasmtime::async_trait;

pub use host_component::OutboundRedisComponent;

wit_bindgen_wasmtime::export!({paths: ["../../wit/ephemeral/outbound-redis.wit"], async: *});
use outbound_redis::Error;
use outbound_redis::{Error, ValueParam, ValueResult};

struct Values(Vec<ValueResult>);

impl FromRedisValue for Values {
fn from_redis_value(value: &Value) -> RedisResult<Self> {
fn append(values: &mut Vec<ValueResult>, value: &Value) {
match value {
Value::Nil | Value::Okay => (),
Value::Int(v) => values.push(ValueResult::Int(*v)),
Value::Data(bytes) => values.push(ValueResult::Data(bytes.to_owned())),
Value::Bulk(bulk) => bulk.iter().for_each(|value| append(values, value)),
Value::Status(message) => values.push(ValueResult::String(message.to_owned())),
dicej marked this conversation as resolved.
Show resolved Hide resolved
}
}

let mut values = Vec::new();
append(&mut values, value);
Ok(Values(values))
}
}

#[derive(Default)]
pub struct OutboundRedis {
Expand Down Expand Up @@ -65,6 +85,33 @@ impl outbound_redis::OutboundRedis for OutboundRedis {
let value = conn.srem(key, values).await.map_err(log_error)?;
Ok(value)
}

async fn execute(
&mut self,
address: &str,
command: &str,
arguments: Vec<ValueParam<'_>>,
) -> Result<Vec<ValueResult>, Error> {
let conn = self.get_conn(address).await.map_err(log_error)?;
let mut cmd = redis::cmd(command);
arguments.iter().for_each(|value| match value {
ValueParam::Nil => (),
dicej marked this conversation as resolved.
Show resolved Hide resolved
ValueParam::String(s) => {
cmd.arg(s);
}
ValueParam::Int(v) => {
cmd.arg(v);
}
ValueParam::Data(v) => {
cmd.arg(v);
}
});

cmd.query_async::<_, Values>(conn)
.await
.map(|values| values.0)
.map_err(log_error)
}
}

impl OutboundRedis {
Expand Down
2 changes: 1 addition & 1 deletion examples/rust-outbound-redis/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

31 changes: 31 additions & 0 deletions sdk/rust/src/lib.rs
Expand Up @@ -43,8 +43,39 @@ pub mod http {
/// Implementation of the spin redis interface.
#[allow(missing_docs)]
pub mod redis {
use std::hash::{Hash, Hasher};

wit_bindgen_rust::import!("../../wit/ephemeral/outbound-redis.wit");

impl PartialEq for outbound_redis::ValueResult {
fn eq(&self, other: &Self) -> bool {
use outbound_redis::ValueResult::*;

match (self, other) {
(Nil, Nil) => true,
(String(a), String(b)) => a == b,
(Int(a), Int(b)) => a == b,
(Data(a), Data(b)) => a == b,
_ => false,
}
}
}

impl Eq for outbound_redis::ValueResult {}

impl Hash for outbound_redis::ValueResult {
fn hash<H: Hasher>(&self, state: &mut H) {
use outbound_redis::ValueResult::*;

match self {
Nil => (),
String(s) => s.hash(state),
Int(v) => v.hash(state),
Data(v) => v.hash(state),
}
}
}

/// Exports the generated outbound Redis items.
pub use outbound_redis::*;
}
Expand Down
7 changes: 3 additions & 4 deletions tests/integration.rs
Expand Up @@ -9,7 +9,6 @@ mod integration_tests {
use std::{
collections::HashMap,
ffi::OsStr,
fs,
net::{Ipv4Addr, SocketAddrV4, TcpListener},
path::Path,
process::{self, Child, Command, Output},
Expand Down Expand Up @@ -1133,7 +1132,7 @@ route = "/..."
]
});
let manifest_file_path = dir.join("example-plugin-manifest.json");
fs::write(
std::fs::write(
&manifest_file_path,
serde_json::to_string(&plugin_manifest_json).unwrap(),
)?;
Expand Down Expand Up @@ -1161,7 +1160,7 @@ route = "/..."

// Upgrade plugin to newer version
*plugin_manifest_json.get_mut("version").unwrap() = serde_json::json!("0.2.1");
fs::write(
std::fs::write(
dir.join("example-plugin-manifest.json"),
serde_json::to_string(&plugin_manifest_json).unwrap(),
)?;
Expand All @@ -1184,7 +1183,7 @@ route = "/..."
.join("plugins")
.join("manifests")
.join("example.json");
let manifest = fs::read_to_string(installed_manifest)?;
let manifest = std::fs::read_to_string(installed_manifest)?;
assert!(manifest.contains("0.2.1"));

// Uninstall plugin
Expand Down