Skip to main content

reifydb_sub_server/
remote.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2025 ReifyDB
3
4//! Shared remote subscription support.
5//!
6//! Provides connection and proxy logic for remote subscriptions,
7//! used by both gRPC and WebSocket server subsystems.
8
9use 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/// Error returned when connecting to a remote subscription fails.
19#[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
34/// An active remote subscription, wrapping the underlying gRPC connection.
35pub struct RemoteSubscription {
36	inner: GrpcSubscription,
37	subscription_id: String,
38}
39
40impl RemoteSubscription {
41	/// The subscription ID assigned by the remote node.
42	pub fn subscription_id(&self) -> &str {
43		&self.subscription_id
44	}
45}
46
47/// Connect to a remote node and create a subscription.
48pub 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
60/// Proxy frames from a remote subscription to a local channel.
61///
62/// Receives frames from the remote subscription and converts them using the
63/// provided closure before sending through the local channel. Exits when:
64/// - The remote stream ends
65/// - The local channel closes (receiver dropped)
66/// - A shutdown signal is received
67pub 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}