Skip to main content

reddb_grpc_proto/
client.rs

1use std::error::Error;
2
3use reddb_wire::auth::{bearer_authorization_value, login_payload_json, AUTHORIZATION_HEADER};
4use tonic::transport::Channel;
5use tonic::Request;
6
7use crate::red_db_client::RedDbClient;
8use crate::{
9    BulkEntityReply, DeleteEntityRequest, Empty, EntityReply, HealthReply, JsonBulkCreateRequest,
10    JsonCreateRequest, JsonPayloadRequest, MutationField, OperationReply, PayloadReply, QueryReply,
11    QueryRequest, QueryValue, ScanReply, ScanRequest, StatsReply, TopologyRequest,
12    TypedCreateRowRequest,
13};
14
15/// Thin authenticated client over the generated tonic stub.
16#[derive(Clone)]
17pub struct RedDBClient {
18    inner: RedDbClient<Channel>,
19    token: Option<String>,
20    pub addr: String,
21}
22
23impl RedDBClient {
24    pub async fn connect(addr: &str, token: Option<String>) -> Result<Self, Box<dyn Error>> {
25        let endpoint = if addr.starts_with("http") {
26            addr.to_string()
27        } else {
28            format!("http://{addr}")
29        };
30        let inner = RedDbClient::connect(endpoint.clone()).await?;
31        Ok(Self {
32            inner,
33            token,
34            addr: endpoint,
35        })
36    }
37
38    /// Build on a caller-configured channel without enabling TLS in the
39    /// generated-protocol crate's otherwise transport-neutral feature set.
40    pub fn from_channel(addr: String, token: Option<String>, channel: Channel) -> Self {
41        Self {
42            inner: RedDbClient::new(channel),
43            token,
44            addr,
45        }
46    }
47
48    fn auth_request<T>(&self, inner: T) -> Request<T> {
49        let mut request = Request::new(inner);
50        if let Some(token) = &self.token {
51            if let Ok(value) = bearer_authorization_value(token).parse() {
52                request.metadata_mut().insert(AUTHORIZATION_HEADER, value);
53            }
54        }
55        request
56    }
57
58    /// Update the bearer token, for example after a successful login.
59    pub fn set_token(&mut self, token: String) {
60        self.token = Some(token);
61    }
62
63    pub async fn health_status(&mut self) -> Result<HealthReply, Box<dyn Error>> {
64        let request = self.auth_request(Empty {});
65        Ok(self.inner.health(request).await?.into_inner())
66    }
67
68    pub async fn query_reply(&mut self, sql: &str) -> Result<QueryReply, Box<dyn Error>> {
69        self.query_reply_with_params(sql, Vec::new()).await
70    }
71
72    pub async fn query_reply_with_params(
73        &mut self,
74        sql: &str,
75        params: Vec<QueryValue>,
76    ) -> Result<QueryReply, Box<dyn Error>> {
77        let request = self.auth_request(QueryRequest {
78            query: sql.to_string(),
79            entity_types: vec![],
80            capabilities: vec![],
81            params,
82        });
83        Ok(self.inner.query(request).await?.into_inner())
84    }
85
86    pub async fn query(&mut self, sql: &str) -> Result<String, Box<dyn Error>> {
87        Ok(self.query_reply(sql).await?.result_json)
88    }
89
90    pub async fn collections(&mut self) -> Result<Vec<String>, Box<dyn Error>> {
91        let request = self.auth_request(Empty {});
92        Ok(self
93            .inner
94            .collections(request)
95            .await?
96            .into_inner()
97            .collections)
98    }
99
100    pub async fn scan(
101        &mut self,
102        collection: &str,
103        limit: u64,
104    ) -> Result<ScanReply, Box<dyn Error>> {
105        let request = self.auth_request(ScanRequest {
106            collection: collection.to_string(),
107            offset: 0,
108            limit,
109        });
110        Ok(self.inner.scan(request).await?.into_inner())
111    }
112
113    pub async fn stats(&mut self) -> Result<StatsReply, Box<dyn Error>> {
114        let request = self.auth_request(Empty {});
115        Ok(self.inner.stats(request).await?.into_inner())
116    }
117
118    pub async fn create_row_entity(
119        &mut self,
120        collection: &str,
121        json: &str,
122    ) -> Result<EntityReply, Box<dyn Error>> {
123        let request = self.auth_request(JsonCreateRequest {
124            collection: collection.to_string(),
125            payload_json: json.to_string(),
126        });
127        Ok(self.inner.create_row(request).await?.into_inner())
128    }
129
130    pub async fn create_row_typed(
131        &mut self,
132        collection: &str,
133        fields: Vec<MutationField>,
134    ) -> Result<EntityReply, Box<dyn Error>> {
135        let request = self.auth_request(TypedCreateRowRequest {
136            collection: collection.to_string(),
137            fields,
138        });
139        Ok(self.inner.create_row_typed(request).await?.into_inner())
140    }
141
142    pub async fn bulk_create_rows(
143        &mut self,
144        collection: &str,
145        payload_json: Vec<String>,
146    ) -> Result<BulkEntityReply, Box<dyn Error>> {
147        let request = self.auth_request(JsonBulkCreateRequest {
148            collection: collection.to_string(),
149            payload_json,
150        });
151        Ok(self.inner.bulk_create_rows(request).await?.into_inner())
152    }
153
154    pub async fn explain(&mut self, sql: &str) -> Result<String, Box<dyn Error>> {
155        let request = self.auth_request(QueryRequest {
156            query: sql.to_string(),
157            entity_types: vec![],
158            capabilities: vec![],
159            params: vec![],
160        });
161        Ok(self
162            .inner
163            .explain_query(request)
164            .await?
165            .into_inner()
166            .payload)
167    }
168
169    pub async fn login(
170        &mut self,
171        username: &str,
172        password: &str,
173    ) -> Result<String, Box<dyn Error>> {
174        let request = self.auth_request(JsonPayloadRequest {
175            payload_json: login_payload_json(username, password),
176        });
177        let reply: PayloadReply = self.inner.auth_login(request).await?.into_inner();
178        Ok(reply.payload)
179    }
180
181    pub async fn replication_status(&mut self) -> Result<String, Box<dyn Error>> {
182        let request = self.auth_request(Empty {});
183        Ok(self
184            .inner
185            .replication_status(request)
186            .await?
187            .into_inner()
188            .payload)
189    }
190
191    /// Fetch the canonical topology envelope bytes.
192    pub async fn topology(&mut self) -> Result<Vec<u8>, Box<dyn Error>> {
193        let request = self.auth_request(TopologyRequest {});
194        Ok(self
195            .inner
196            .topology(request)
197            .await?
198            .into_inner()
199            .topology_bytes)
200    }
201
202    pub async fn topology_for_transport(
203        &mut self,
204        protocol: &str,
205    ) -> Result<Vec<u8>, Box<dyn Error>> {
206        let mut request = self.auth_request(TopologyRequest {});
207        request.metadata_mut().insert(
208            reddb_wire::routing::TOPOLOGY_TRANSPORT_METADATA_KEY,
209            protocol.parse()?,
210        );
211        Ok(self
212            .inner
213            .topology(request)
214            .await?
215            .into_inner()
216            .topology_bytes)
217    }
218
219    pub async fn delete_entity(
220        &mut self,
221        collection: &str,
222        id: u64,
223    ) -> Result<OperationReply, Box<dyn Error>> {
224        let request = self.auth_request(DeleteEntityRequest {
225            collection: collection.to_string(),
226            id,
227        });
228        Ok(self.inner.delete_entity(request).await?.into_inner())
229    }
230}