reifydb_sub_server/
remote.rs1use std::fmt;
10
11use reifydb_client::{GrpcClient, GrpcSubscription};
12use reifydb_type::value::frame::frame::Frame;
13use tokio::{
14 select,
15 sync::{mpsc, watch},
16};
17
18#[derive(Debug)]
20pub enum RemoteSubscriptionError {
21 Connect(String),
22 Subscribe(String),
23}
24
25impl fmt::Display for RemoteSubscriptionError {
26 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27 match self {
28 Self::Connect(e) => write!(f, "Failed to connect to remote: {}", e),
29 Self::Subscribe(e) => write!(f, "Remote subscribe failed: {}", e),
30 }
31 }
32}
33
34pub struct RemoteSubscription {
36 inner: GrpcSubscription,
37 subscription_id: String,
38}
39
40impl RemoteSubscription {
41 pub fn subscription_id(&self) -> &str {
43 &self.subscription_id
44 }
45}
46
47pub async fn connect_remote(address: &str, query: &str) -> Result<RemoteSubscription, RemoteSubscriptionError> {
49 let mut client =
50 GrpcClient::connect(address).await.map_err(|e| RemoteSubscriptionError::Connect(e.to_string()))?;
51 client.authenticate("service-token");
52 let sub = client.subscribe(query).await.map_err(|e| RemoteSubscriptionError::Subscribe(e.to_string()))?;
53 let subscription_id = sub.subscription_id().to_string();
54 Ok(RemoteSubscription {
55 inner: sub,
56 subscription_id,
57 })
58}
59
60pub async fn proxy_remote<T, F>(
68 mut remote_sub: RemoteSubscription,
69 sender: mpsc::Sender<T>,
70 mut shutdown: watch::Receiver<bool>,
71 convert: F,
72) where
73 T: Send + 'static,
74 F: Fn(Vec<Frame>) -> T,
75{
76 loop {
77 select! {
78 frames = remote_sub.inner.recv() => {
79 match frames {
80 Some(frames) => {
81 if sender.send(convert(frames)).await.is_err() {
82 break;
83 }
84 }
85 None => break,
86 }
87 }
88 _ = sender.closed() => break,
89 _ = shutdown.changed() => break,
90 }
91 }
92}