Skip to main content

spin_factor_outbound_redis/
host.rs

1use std::net::SocketAddr;
2
3use anyhow::Result;
4use opentelemetry_semantic_conventions::attribute as otel_attribute;
5use redis::AsyncConnectionConfig;
6use redis::io::AsyncDNSResolver;
7use redis::{AsyncCommands, FromRedisValue, Value, aio::MultiplexedConnection};
8use spin_core::wasmtime::component::{Accessor, Resource};
9use spin_factor_otel::OtelFactorState;
10use spin_factor_outbound_networking::ConnectionSemaphore;
11use spin_factor_outbound_networking::config::blocked_networks::BlockedNetworks;
12use spin_world::MAX_HOST_BUFFERED_BYTES;
13use spin_world::spin::redis::redis as v3;
14use spin_world::v1::{redis as v1, redis_types};
15use spin_world::v2::redis as v2;
16use tracing::field::Empty;
17use tracing::{Level, instrument};
18
19use crate::allowed_hosts::AllowedHostChecker;
20
21const REDIS_CONNECTION_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
22
23pub struct InstanceState {
24    pub(crate) allowed_host_checker: AllowedHostChecker,
25    pub blocked_networks: BlockedNetworks,
26    pub connections: spin_resource_table::Table<(
27        MultiplexedConnection,
28        spin_factor_outbound_networking::ConnectionPermit,
29    )>,
30    pub semaphore: ConnectionSemaphore,
31    pub otel: OtelFactorState,
32}
33
34impl InstanceState {
35    async fn is_address_allowed(&self, address: &str) -> Result<bool> {
36        self.allowed_host_checker.is_address_allowed(address).await
37    }
38
39    async fn establish_connection(
40        &mut self,
41        address: String,
42    ) -> Result<Resource<v2::Connection>, v2::Error> {
43        let permit = self
44            .semaphore
45            .acquire()
46            .await
47            .map_err(|_| v2::Error::TooManyConnections)?;
48        let config = AsyncConnectionConfig::new()
49            .set_dns_resolver(SpinDnsResolver(self.blocked_networks.clone()))
50            .set_connection_timeout(REDIS_CONNECTION_TIMEOUT);
51        let conn = redis::Client::open(address.as_str())
52            .map_err(|_| v2::Error::InvalidAddress)?
53            .get_multiplexed_async_connection_with_config(&config)
54            .await
55            .map_err(other_error_v2)?;
56        self.connections
57            .push((conn, permit))
58            .map(Resource::new_own)
59            .map_err(|_| v2::Error::TooManyConnections)
60    }
61
62    async fn get_conn(
63        &mut self,
64        connection: Resource<v2::Connection>,
65    ) -> Result<&mut MultiplexedConnection, v2::Error> {
66        self.connections
67            .get_mut(connection.rep())
68            .map(|(conn, _permit)| conn)
69            .ok_or(v2::Error::Other(
70                "could not find connection for resource".into(),
71            ))
72    }
73
74    fn get_conn_v3(
75        &mut self,
76        connection: Resource<v3::Connection>,
77    ) -> Result<MultiplexedConnection, v3::Error> {
78        self.connections
79            .get(connection.rep())
80            .map(|(conn, _permit)| conn.clone())
81            .ok_or(v3::Error::Other(
82                "could not find connection for resource".into(),
83            ))
84    }
85}
86
87mod operations {
88    use super::*;
89
90    pub async fn publish(
91        conn: &mut MultiplexedConnection,
92        channel: String,
93        payload: v3::Payload,
94    ) -> Result<(), v3::Error> {
95        // The `let () =` syntax is needed to suppress a warning when the result type is inferred.
96        // You can read more about the issue here: <https://github.com/redis-rs/redis-rs/issues/1228>
97        let () = conn
98            .publish(&channel, &payload)
99            .await
100            .map_err(other_error_v3)?;
101        Ok(())
102    }
103
104    pub async fn get(
105        conn: &mut MultiplexedConnection,
106        key: String,
107    ) -> Result<Option<Vec<u8>>, v3::Error> {
108        let value = conn
109            .get::<_, Option<Vec<u8>>>(&key)
110            .await
111            .map_err(other_error_v3)?;
112
113        // Currently there's no way to stream a `GET` result using the `redis`
114        // crate without buffering, so the damage (in terms of host memory
115        // usage) is already done, but we can still enforce the limit:
116        if std::mem::size_of::<Option<Vec<u8>>>() + value.as_ref().map(|v| v.len()).unwrap_or(0)
117            > MAX_HOST_BUFFERED_BYTES
118        {
119            Err(v3::Error::Other(format!(
120                "query result exceeds limit of {MAX_HOST_BUFFERED_BYTES} bytes"
121            )))
122        } else {
123            Ok(value)
124        }
125    }
126
127    pub async fn set(
128        conn: &mut MultiplexedConnection,
129        key: String,
130        value: Vec<u8>,
131    ) -> Result<(), v3::Error> {
132        // The `let () =` syntax is needed to suppress a warning when the result type is inferred.
133        // You can read more about the issue here: <https://github.com/redis-rs/redis-rs/issues/1228>
134        let () = conn.set(&key, &value).await.map_err(other_error_v3)?;
135        Ok(())
136    }
137
138    pub async fn incr(conn: &mut MultiplexedConnection, key: String) -> Result<i64, v3::Error> {
139        conn.incr(&key, 1).await.map_err(other_error_v3)
140    }
141
142    pub async fn del(
143        conn: &mut MultiplexedConnection,
144        keys: Vec<String>,
145    ) -> Result<u32, v3::Error> {
146        conn.del(&keys).await.map_err(other_error_v3)
147    }
148
149    pub async fn sadd(
150        conn: &mut MultiplexedConnection,
151        key: String,
152        values: Vec<String>,
153    ) -> Result<u32, v3::Error> {
154        let value = conn.sadd(&key, &values).await.map_err(|e| {
155            if e.kind() == redis::ErrorKind::TypeError {
156                v3::Error::TypeError
157            } else {
158                v3::Error::Other(e.to_string())
159            }
160        })?;
161        Ok(value)
162    }
163
164    pub async fn smembers(
165        conn: &mut MultiplexedConnection,
166        key: String,
167    ) -> Result<Vec<String>, v3::Error> {
168        conn.smembers(&key).await.map_err(other_error_v3)
169    }
170
171    pub async fn srem(
172        conn: &mut MultiplexedConnection,
173        key: String,
174        values: Vec<String>,
175    ) -> Result<u32, v3::Error> {
176        conn.srem(&key, &values).await.map_err(other_error_v3)
177    }
178
179    pub async fn execute(
180        conn: &mut MultiplexedConnection,
181        command: String,
182        arguments: impl IntoIterator<Item = v3::RedisParameter>,
183    ) -> Result<RedisResults, v3::Error> {
184        let mut cmd = redis::cmd(&command);
185        arguments.into_iter().for_each(|value| match value {
186            v3::RedisParameter::Int64(v) => {
187                cmd.arg(v);
188            }
189            v3::RedisParameter::Binary(v) => {
190                cmd.arg(v);
191            }
192        });
193
194        let results = cmd
195            .query_async::<RedisResults>(conn)
196            .await
197            .map_err(other_error_v3)?;
198
199        // Currently there's no way to stream results using the `redis`
200        // crate without buffering, so the damage (in terms of host memory
201        // usage) is already done, but we can still enforce the limit:
202        if std::mem::size_of::<Vec<v3::RedisResult>>()
203            + results.0.iter().map(memory_size).sum::<usize>()
204            > MAX_HOST_BUFFERED_BYTES
205        {
206            Err(v3::Error::Other(format!(
207                "query result exceeds limit of {MAX_HOST_BUFFERED_BYTES} bytes"
208            )))
209        } else {
210            Ok(results)
211        }
212    }
213}
214
215impl v3::Host for crate::InstanceState {
216    fn convert_error(&mut self, error: v3::Error) -> anyhow::Result<v3::Error> {
217        Ok(error)
218    }
219}
220
221impl v3::HostConnection for crate::InstanceState {
222    async fn drop(&mut self, connection: Resource<v3::Connection>) -> anyhow::Result<()> {
223        self.connections.remove(connection.rep());
224        Ok(())
225    }
226}
227
228impl crate::RedisFactorData {
229    fn get_conn<T: Send>(
230        accessor: &Accessor<T, Self>,
231        connection: Resource<v3::Connection>,
232    ) -> Result<MultiplexedConnection, v3::Error> {
233        accessor.with(|mut access| {
234            let host = access.get();
235            host.otel.reparent_tracing_span();
236            host.get_conn_v3(connection)
237        })
238    }
239}
240
241impl<T: Send> v3::HostConnectionWithStore<T> for crate::RedisFactorData {
242    #[instrument(name = "spin_outbound_redis.open_connection", skip(accessor, address), err(level = Level::INFO),
243        fields(otel.kind = "client", {otel_attribute::DB_SYSTEM_NAME} = "redis", {otel_attribute::SERVER_ADDRESS} = Empty, {otel_attribute::SERVER_PORT} = Empty, {otel_attribute::DB_NAMESPACE} = Empty))]
244    async fn open(
245        accessor: &Accessor<T, Self>,
246        address: String,
247    ) -> Result<Resource<v3::Connection>, v3::Error> {
248        let (allowed_host_checker, blocked_networks, semaphore) = accessor.with(|mut access| {
249            let host = access.get();
250            host.otel.reparent_tracing_span();
251            (
252                host.allowed_host_checker.clone(),
253                host.blocked_networks.clone(),
254                host.semaphore.clone(),
255            )
256        });
257
258        if !allowed_host_checker
259            .is_address_allowed(&address)
260            .await
261            .map_err(|e| v3::Error::Other(e.to_string()))?
262        {
263            return Err(v3::Error::InvalidAddress);
264        }
265
266        let permit = semaphore
267            .acquire()
268            .await
269            .map_err(|_| v3::Error::TooManyConnections)?;
270
271        let config =
272            AsyncConnectionConfig::new().set_dns_resolver(SpinDnsResolver(blocked_networks));
273        let conn = redis::Client::open(address.as_str())
274            .map_err(|_| v3::Error::InvalidAddress)?
275            .get_multiplexed_async_connection_with_config(&config)
276            .await
277            .map_err(other_error_v3)?;
278
279        accessor.with(|mut access| {
280            let host = access.get();
281            host.connections
282                .push((conn, permit))
283                .map(Resource::new_own)
284                .map_err(|_| v3::Error::TooManyConnections)
285        })
286    }
287
288    #[instrument(name = "spin_outbound_redis.publish", skip(accessor, connection, payload), err(level = Level::INFO),
289        fields(otel.kind = "client", {otel_attribute::DB_SYSTEM_NAME} = "redis", otel.name = "PUBLISH"))]
290    async fn publish(
291        accessor: &Accessor<T, Self>,
292        connection: Resource<v3::Connection>,
293        channel: String,
294        payload: v3::Payload,
295    ) -> Result<(), v3::Error> {
296        let mut conn = Self::get_conn(accessor, connection)?;
297        operations::publish(&mut conn, channel, payload).await
298    }
299
300    #[instrument(name = "spin_outbound_redis.get", skip(accessor, connection), err(level = Level::INFO),
301        fields(otel.kind = "client", {otel_attribute::DB_SYSTEM_NAME} = "redis", otel.name = "GET"))]
302    async fn get(
303        accessor: &Accessor<T, Self>,
304        connection: Resource<v3::Connection>,
305        key: String,
306    ) -> Result<Option<v3::Payload>, v3::Error> {
307        let mut conn = Self::get_conn(accessor, connection)?;
308        operations::get(&mut conn, key).await
309    }
310
311    #[instrument(name = "spin_outbound_redis.set", skip(accessor, connection, value), err(level = Level::INFO),
312        fields(otel.kind = "client", {otel_attribute::DB_SYSTEM_NAME} = "redis", otel.name = "SET"))]
313    async fn set(
314        accessor: &Accessor<T, Self>,
315        connection: Resource<v3::Connection>,
316        key: String,
317        value: v3::Payload,
318    ) -> Result<(), v3::Error> {
319        let mut conn = Self::get_conn(accessor, connection)?;
320        operations::set(&mut conn, key, value).await
321    }
322
323    #[instrument(name = "spin_outbound_redis.incr", skip(accessor, connection), err(level = Level::INFO),
324        fields(otel.kind = "client", {otel_attribute::DB_SYSTEM_NAME} = "redis", otel.name = "INCRBY"))]
325    async fn incr(
326        accessor: &Accessor<T, Self>,
327        connection: Resource<v3::Connection>,
328        key: String,
329    ) -> Result<i64, v3::Error> {
330        let mut conn = Self::get_conn(accessor, connection)?;
331        operations::incr(&mut conn, key).await
332    }
333
334    #[instrument(name = "spin_outbound_redis.del", skip(accessor, connection), err(level = Level::INFO),
335        fields(otel.kind = "client", {otel_attribute::DB_SYSTEM_NAME} = "redis", otel.name = "DEL"))]
336    async fn del(
337        accessor: &Accessor<T, Self>,
338        connection: Resource<v3::Connection>,
339        keys: Vec<String>,
340    ) -> Result<u32, v3::Error> {
341        let mut conn = Self::get_conn(accessor, connection)?;
342        operations::del(&mut conn, keys).await
343    }
344
345    #[instrument(name = "spin_outbound_redis.sadd", skip(accessor, connection, values), err(level = Level::INFO),
346        fields(otel.kind = "client", {otel_attribute::DB_SYSTEM_NAME} = "redis", otel.name = "SADD"))]
347    async fn sadd(
348        accessor: &Accessor<T, Self>,
349        connection: Resource<v3::Connection>,
350        key: String,
351        values: Vec<String>,
352    ) -> Result<u32, v3::Error> {
353        let mut conn = Self::get_conn(accessor, connection)?;
354        operations::sadd(&mut conn, key, values).await
355    }
356
357    #[instrument(name = "spin_outbound_redis.smembers", skip(accessor, connection), err(level = Level::INFO),
358        fields(otel.kind = "client", {otel_attribute::DB_SYSTEM_NAME} = "redis", otel.name = "SMEMBERS"))]
359    async fn smembers(
360        accessor: &Accessor<T, Self>,
361        connection: Resource<v3::Connection>,
362        key: String,
363    ) -> Result<Vec<String>, v3::Error> {
364        let mut conn = Self::get_conn(accessor, connection)?;
365        operations::smembers(&mut conn, key).await
366    }
367
368    #[instrument(name = "spin_outbound_redis.srem", skip(accessor, connection, values), err(level = Level::INFO),
369        fields(otel.kind = "client", {otel_attribute::DB_SYSTEM_NAME} = "redis", otel.name = "SREM"))]
370    async fn srem(
371        accessor: &Accessor<T, Self>,
372        connection: Resource<v3::Connection>,
373        key: String,
374        values: Vec<String>,
375    ) -> Result<u32, v3::Error> {
376        let mut conn = Self::get_conn(accessor, connection)?;
377        operations::srem(&mut conn, key, values).await
378    }
379
380    #[instrument(name = "spin_outbound_redis.execute", skip(accessor, connection), err(level = Level::INFO),
381        fields(otel.kind = "client", {otel_attribute::DB_SYSTEM_NAME} = "redis", otel.name = command.clone()))]
382    async fn execute(
383        accessor: &Accessor<T, Self>,
384        connection: Resource<v3::Connection>,
385        command: String,
386        arguments: Vec<v3::RedisParameter>,
387    ) -> Result<Vec<v3::RedisResult>, v3::Error> {
388        let mut conn = Self::get_conn(accessor, connection)?;
389        Ok(operations::execute(&mut conn, command, arguments)
390            .await?
391            .into_v3())
392    }
393}
394
395impl v2::Host for crate::InstanceState {
396    fn convert_error(&mut self, error: v2::Error) -> Result<v2::Error> {
397        Ok(error)
398    }
399}
400
401impl v2::HostConnection for crate::InstanceState {
402    #[instrument(name = "spin_outbound_redis.open_connection", skip(self, address), err(level = Level::INFO),
403        fields(otel.kind = "client", {otel_attribute::DB_SYSTEM_NAME} = "redis", {otel_attribute::SERVER_ADDRESS} = Empty, {otel_attribute::SERVER_PORT} = Empty, {otel_attribute::DB_NAMESPACE} = Empty))]
404    async fn open(&mut self, address: String) -> Result<Resource<v2::Connection>, v2::Error> {
405        self.otel.reparent_tracing_span();
406        if !self
407            .is_address_allowed(&address)
408            .await
409            .map_err(|e| v2::Error::Other(e.to_string()))?
410        {
411            return Err(v2::Error::InvalidAddress);
412        }
413
414        self.establish_connection(address).await
415    }
416
417    #[instrument(name = "spin_outbound_redis.publish", skip(self, connection, payload), err(level = Level::INFO),
418        fields(otel.kind = "client", {otel_attribute::DB_SYSTEM_NAME} = "redis", otel.name = "PUBLISH"))]
419    async fn publish(
420        &mut self,
421        connection: Resource<v2::Connection>,
422        channel: String,
423        payload: Vec<u8>,
424    ) -> Result<(), v2::Error> {
425        self.otel.reparent_tracing_span();
426
427        let conn = self.get_conn(connection).await.map_err(other_error_v2)?;
428
429        Ok(operations::publish(conn, channel, payload).await?)
430    }
431
432    #[instrument(name = "spin_outbound_redis.get", skip(self, connection), err(level = Level::INFO),
433        fields(otel.kind = "client", {otel_attribute::DB_SYSTEM_NAME} = "redis", otel.name = "GET"))]
434    async fn get(
435        &mut self,
436        connection: Resource<v2::Connection>,
437        key: String,
438    ) -> Result<Option<Vec<u8>>, v2::Error> {
439        self.otel.reparent_tracing_span();
440
441        let conn = self.get_conn(connection).await.map_err(other_error_v2)?;
442
443        Ok(operations::get(conn, key).await?)
444    }
445
446    #[instrument(name = "spin_outbound_redis.set", skip(self, connection, value), err(level = Level::INFO),
447        fields(otel.kind = "client", {otel_attribute::DB_SYSTEM_NAME} = "redis", otel.name = "SET"))]
448    async fn set(
449        &mut self,
450        connection: Resource<v2::Connection>,
451        key: String,
452        value: Vec<u8>,
453    ) -> Result<(), v2::Error> {
454        self.otel.reparent_tracing_span();
455
456        let conn = self.get_conn(connection).await.map_err(other_error_v2)?;
457        Ok(operations::set(conn, key, value).await?)
458    }
459
460    #[instrument(name = "spin_outbound_redis.incr", skip(self, connection), err(level = Level::INFO),
461        fields(otel.kind = "client", {otel_attribute::DB_SYSTEM_NAME} = "redis", otel.name = "INCRBY"))]
462    async fn incr(
463        &mut self,
464        connection: Resource<v2::Connection>,
465        key: String,
466    ) -> Result<i64, v2::Error> {
467        self.otel.reparent_tracing_span();
468
469        let conn = self.get_conn(connection).await.map_err(other_error_v2)?;
470        Ok(operations::incr(conn, key).await?)
471    }
472
473    #[instrument(name = "spin_outbound_redis.del", skip(self, connection), err(level = Level::INFO),
474        fields(otel.kind = "client", {otel_attribute::DB_SYSTEM_NAME} = "redis", otel.name = "DEL"))]
475    async fn del(
476        &mut self,
477        connection: Resource<v2::Connection>,
478        keys: Vec<String>,
479    ) -> Result<u32, v2::Error> {
480        self.otel.reparent_tracing_span();
481
482        let conn = self.get_conn(connection).await.map_err(other_error_v2)?;
483        Ok(operations::del(conn, keys).await?)
484    }
485
486    #[instrument(name = "spin_outbound_redis.sadd", skip(self, connection, values), err(level = Level::INFO),
487        fields(otel.kind = "client", {otel_attribute::DB_SYSTEM_NAME} = "redis", otel.name = "SADD"))]
488    async fn sadd(
489        &mut self,
490        connection: Resource<v2::Connection>,
491        key: String,
492        values: Vec<String>,
493    ) -> Result<u32, v2::Error> {
494        self.otel.reparent_tracing_span();
495
496        let conn = self.get_conn(connection).await.map_err(other_error_v2)?;
497        Ok(operations::sadd(conn, key, values).await?)
498    }
499
500    #[instrument(name = "spin_outbound_redis.smembers", skip(self, connection), err(level = Level::INFO),
501        fields(otel.kind = "client", {otel_attribute::DB_SYSTEM_NAME} = "redis", otel.name = "SMEMBERS"))]
502    async fn smembers(
503        &mut self,
504        connection: Resource<v2::Connection>,
505        key: String,
506    ) -> Result<Vec<String>, v2::Error> {
507        self.otel.reparent_tracing_span();
508
509        let conn = self.get_conn(connection).await.map_err(other_error_v2)?;
510        Ok(operations::smembers(conn, key).await?)
511    }
512
513    #[instrument(name = "spin_outbound_redis.srem", skip(self, connection, values), err(level = Level::INFO),
514        fields(otel.kind = "client", {otel_attribute::DB_SYSTEM_NAME} = "redis", otel.name = "SREM"))]
515    async fn srem(
516        &mut self,
517        connection: Resource<v2::Connection>,
518        key: String,
519        values: Vec<String>,
520    ) -> Result<u32, v2::Error> {
521        self.otel.reparent_tracing_span();
522
523        let conn = self.get_conn(connection).await.map_err(other_error_v2)?;
524        Ok(operations::srem(conn, key, values).await?)
525    }
526
527    #[instrument(name = "spin_outbound_redis.execute", skip(self, connection, arguments), err(level = Level::INFO),
528        fields(otel.kind = "client", {otel_attribute::DB_SYSTEM_NAME} = "redis", otel.name = command))]
529    async fn execute(
530        &mut self,
531        connection: Resource<v2::Connection>,
532        command: String,
533        arguments: Vec<v2::RedisParameter>,
534    ) -> Result<Vec<v2::RedisResult>, v2::Error> {
535        fn to_v3_param(value: v2::RedisParameter) -> v3::RedisParameter {
536            match value {
537                v2::RedisParameter::Int64(v) => v3::RedisParameter::Int64(v),
538                v2::RedisParameter::Binary(v) => v3::RedisParameter::Binary(v),
539            }
540        }
541
542        self.otel.reparent_tracing_span();
543
544        let conn = self.get_conn(connection).await?;
545
546        let arguments = arguments.into_iter().map(to_v3_param);
547        Ok(operations::execute(conn, command, arguments)
548            .await?
549            .into_v2())
550    }
551
552    async fn drop(&mut self, connection: Resource<v2::Connection>) -> anyhow::Result<()> {
553        self.connections.remove(connection.rep());
554        Ok(())
555    }
556}
557
558fn other_error_v2(e: impl std::fmt::Display) -> v2::Error {
559    v2::Error::Other(e.to_string())
560}
561
562fn other_error_v3(e: impl std::fmt::Display) -> v3::Error {
563    v3::Error::Other(e.to_string())
564}
565
566/// Delegate a function call to the v2::HostConnection implementation
567macro_rules! delegate {
568    ($self:ident.$name:ident($address:expr, $($arg:expr),*)) => {{
569        if !$self.is_address_allowed(&$address).await.map_err(|_| v1::Error::Error)?  {
570            return Err(v1::Error::Error);
571        }
572        let connection = match $self.establish_connection($address).await {
573            Ok(c) => c,
574            Err(_) => return Err(v1::Error::Error),
575        };
576        // v1 has no persistent connections, so remove the table entry immediately
577        // after the call to release the semaphore permit.
578        let rep = connection.rep();
579        let result = <Self as v2::HostConnection>::$name($self, connection, $($arg),*)
580            .await
581            .map_err(|_| v1::Error::Error);
582        $self.connections.remove(rep);
583        result
584    }};
585}
586
587impl v1::Host for crate::InstanceState {
588    async fn publish(
589        &mut self,
590        address: String,
591        channel: String,
592        payload: Vec<u8>,
593    ) -> Result<(), v1::Error> {
594        delegate!(self.publish(address, channel, payload))
595    }
596
597    async fn get(&mut self, address: String, key: String) -> Result<Vec<u8>, v1::Error> {
598        delegate!(self.get(address, key)).map(|v| v.unwrap_or_default())
599    }
600
601    async fn set(&mut self, address: String, key: String, value: Vec<u8>) -> Result<(), v1::Error> {
602        delegate!(self.set(address, key, value))
603    }
604
605    async fn incr(&mut self, address: String, key: String) -> Result<i64, v1::Error> {
606        delegate!(self.incr(address, key))
607    }
608
609    async fn del(&mut self, address: String, keys: Vec<String>) -> Result<i64, v1::Error> {
610        delegate!(self.del(address, keys)).map(|v| v as i64)
611    }
612
613    async fn sadd(
614        &mut self,
615        address: String,
616        key: String,
617        values: Vec<String>,
618    ) -> Result<i64, v1::Error> {
619        delegate!(self.sadd(address, key, values)).map(|v| v as i64)
620    }
621
622    async fn smembers(&mut self, address: String, key: String) -> Result<Vec<String>, v1::Error> {
623        delegate!(self.smembers(address, key))
624    }
625
626    async fn srem(
627        &mut self,
628        address: String,
629        key: String,
630        values: Vec<String>,
631    ) -> Result<i64, v1::Error> {
632        delegate!(self.srem(address, key, values)).map(|v| v as i64)
633    }
634
635    async fn execute(
636        &mut self,
637        address: String,
638        command: String,
639        arguments: Vec<v1::RedisParameter>,
640    ) -> Result<Vec<v1::RedisResult>, v1::Error> {
641        delegate!(self.execute(
642            address,
643            command,
644            arguments.into_iter().map(Into::into).collect()
645        ))
646        .map(|v| v.into_iter().map(Into::into).collect())
647    }
648}
649
650impl redis_types::Host for crate::InstanceState {
651    fn convert_error(&mut self, error: redis_types::Error) -> Result<redis_types::Error> {
652        Ok(error)
653    }
654}
655
656struct RedisResults(Vec<v3::RedisResult>);
657
658impl RedisResults {
659    fn into_v2(self) -> Vec<v2::RedisResult> {
660        fn into_v2(value: v3::RedisResult) -> v2::RedisResult {
661            match value {
662                v3::RedisResult::Nil => v2::RedisResult::Nil,
663                v3::RedisResult::Status(v) => v2::RedisResult::Status(v),
664                v3::RedisResult::Int64(v) => v2::RedisResult::Int64(v),
665                v3::RedisResult::Binary(v) => v2::RedisResult::Binary(v),
666            }
667        }
668
669        self.0.into_iter().map(into_v2).collect()
670    }
671
672    fn into_v3(self) -> Vec<v3::RedisResult> {
673        self.0
674    }
675}
676
677impl FromRedisValue for RedisResults {
678    fn from_redis_value(value: &Value) -> redis::RedisResult<Self> {
679        fn append(values: &mut Vec<v3::RedisResult>, value: &Value) -> redis::RedisResult<()> {
680            match value {
681                Value::Nil => {
682                    values.push(v3::RedisResult::Nil);
683                    Ok(())
684                }
685                Value::Int(v) => {
686                    values.push(v3::RedisResult::Int64(*v));
687                    Ok(())
688                }
689                Value::BulkString(bytes) => {
690                    values.push(v3::RedisResult::Binary(bytes.to_owned()));
691                    Ok(())
692                }
693                Value::SimpleString(s) => {
694                    values.push(v3::RedisResult::Status(s.to_owned()));
695                    Ok(())
696                }
697                Value::Okay => {
698                    values.push(v3::RedisResult::Status("OK".to_string()));
699                    Ok(())
700                }
701                Value::Map(_) => Err(redis::RedisError::from((
702                    redis::ErrorKind::TypeError,
703                    "Could not convert Redis response",
704                    "Redis Map type is not supported".to_string(),
705                ))),
706                Value::Attribute { .. } => Err(redis::RedisError::from((
707                    redis::ErrorKind::TypeError,
708                    "Could not convert Redis response",
709                    "Redis Attribute type is not supported".to_string(),
710                ))),
711                Value::Array(arr) | Value::Set(arr) => {
712                    arr.iter().try_for_each(|value| append(values, value))
713                }
714                Value::Double(v) => {
715                    values.push(v3::RedisResult::Binary(v.to_string().into_bytes()));
716                    Ok(())
717                }
718                Value::VerbatimString { .. } => Err(redis::RedisError::from((
719                    redis::ErrorKind::TypeError,
720                    "Could not convert Redis response",
721                    "Redis string with format attribute is not supported".to_string(),
722                ))),
723                Value::Boolean(v) => {
724                    values.push(v3::RedisResult::Int64(if *v { 1 } else { 0 }));
725                    Ok(())
726                }
727                Value::BigNumber(v) => {
728                    values.push(v3::RedisResult::Binary(v.to_string().as_bytes().to_owned()));
729                    Ok(())
730                }
731                Value::Push { .. } => Err(redis::RedisError::from((
732                    redis::ErrorKind::TypeError,
733                    "Could not convert Redis response",
734                    "Redis Pub/Sub types are not supported".to_string(),
735                ))),
736                Value::ServerError(err) => Err(redis::RedisError::from((
737                    redis::ErrorKind::ResponseError,
738                    "Server error",
739                    format!("{err:?}"),
740                ))),
741            }
742        }
743        let mut values = Vec::new();
744        append(&mut values, value)?;
745        Ok(RedisResults(values))
746    }
747}
748
749fn memory_size(value: &v3::RedisResult) -> usize {
750    match value {
751        v3::RedisResult::Nil | v3::RedisResult::Int64(_) => std::mem::size_of::<v3::RedisResult>(),
752        v3::RedisResult::Binary(b) => std::mem::size_of::<v3::RedisResult>() + b.len(),
753        v3::RedisResult::Status(s) => std::mem::size_of::<v3::RedisResult>() + s.len(),
754    }
755}
756
757/// Resolves DNS using Tokio's resolver, filtering out blocked IPs.
758struct SpinDnsResolver(BlockedNetworks);
759
760impl AsyncDNSResolver for SpinDnsResolver {
761    fn resolve<'a, 'b: 'a>(
762        &'a self,
763        host: &'b str,
764        port: u16,
765    ) -> redis::RedisFuture<'a, Box<dyn Iterator<Item = std::net::SocketAddr> + Send + 'a>> {
766        Box::pin(async move {
767            let mut addrs = tokio::net::lookup_host((host, port))
768                .await?
769                .collect::<Vec<_>>();
770            // Remove blocked IPs
771            let blocked_addrs = self.0.remove_blocked(&mut addrs);
772            if addrs.is_empty() && !blocked_addrs.is_empty() {
773                tracing::error!(
774                    "error.type" = "destination_ip_prohibited",
775                    ?blocked_addrs,
776                    "all destination IP(s) prohibited by runtime config"
777                );
778            }
779            Ok(Box::new(addrs.into_iter()) as Box<dyn Iterator<Item = SocketAddr> + Send>)
780        })
781    }
782}