reifydb-client 0.10.3

Official Rust client library for ReifyDB
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 ReifyDB
use std::collections::HashMap;

use reifydb_codec::{
	frame::decode::decode_frames,
	json::{excerpt, types::ResponseFrame},
};
use reifydb_value::{
	error::{Diagnostic, Error},
	fragment::Fragment,
	params::Params,
	value::{duration::Duration, frame::frame::Frame, temporal::parse::duration::parse_duration},
};
use reqwest::{Client as ReqwestClient, Error as ReqwestError, header::HeaderMap};
use serde::{Deserialize, Serialize};
use serde_json::{from_str, json};

use crate::{
	AdminRequest, AdminResponse, AdminResult, CommandRequest, CommandResponse, CommandResult, ErrResponse,
	LoginResult, QueryRequest, QueryResponse, QueryResult, QueueClaimRequest, Response, ResponseMeta,
	ResponsePayload, WireFormat,
	error::ClientError,
	params_to_wire,
	session::{parse_admin_response, parse_command_response, parse_query_response},
};

#[derive(Debug, Deserialize)]
struct HttpFrameResponse {
	frames: Vec<ResponseFrame>,
}

impl HttpFrameResponse {
	fn into_admin(self, meta: Option<ResponseMeta>) -> AdminResponse {
		AdminResponse {
			content_type: "application/vnd.reifydb.frames".to_string(),
			body: json!({ "frames": self.frames }),
			meta,
		}
	}

	fn into_command(self, meta: Option<ResponseMeta>) -> CommandResponse {
		CommandResponse {
			content_type: "application/vnd.reifydb.frames".to_string(),
			body: json!({ "frames": self.frames }),
			meta,
		}
	}

	fn into_query(self, meta: Option<ResponseMeta>) -> QueryResponse {
		QueryResponse {
			content_type: "application/vnd.reifydb.frames".to_string(),
			body: json!({ "frames": self.frames }),
			meta,
		}
	}
}

fn extract_meta(headers: &HeaderMap) -> Option<ResponseMeta> {
	let fingerprint = headers.get("x-fingerprint").and_then(|v| v.to_str().ok())?;
	let duration = headers.get("x-duration").and_then(|v| v.to_str().ok())?;
	Some(ResponseMeta {
		fingerprint: fingerprint.to_string(),
		duration: duration.to_string(),
	})
}

#[derive(Debug, Deserialize)]
struct HttpErrorResponse {
	code: String,
	error: String,
	#[serde(default)]
	diagnostic: Option<Diagnostic>,
}

#[derive(Debug, Deserialize)]
struct HttpAuthenticateResponse {
	status: String,
	token: Option<String>,
	identity: Option<String>,
	reason: Option<String>,
}

#[derive(Clone)]
pub struct HttpClient {
	inner: ReqwestClient,
	base_url: String,
	token: Option<String>,
	format: WireFormat,
}

impl HttpClient {
	pub async fn connect(url: &str, format: WireFormat) -> Result<Self, Error> {
		let inner =
			ReqwestClient::builder().timeout(Duration::from_seconds(30).unwrap().to_std()).build().unwrap(); // FIXME better error handling

		let base_url = url.trim_end_matches('/').to_string();

		Ok(Self {
			inner,
			base_url,
			token: None,
			format,
		})
	}

	pub fn with_client(client: ReqwestClient, url: &str, format: WireFormat) -> Result<Self, Error> {
		let base_url = url.trim_end_matches('/').to_string();
		Ok(Self {
			inner: client,
			base_url,
			token: None,
			format,
		})
	}

	pub fn authenticate(&mut self, token: &str) {
		self.token = Some(token.to_string());
	}

	pub async fn login_with_password(&mut self, identifier: &str, password: &str) -> Result<LoginResult, Error> {
		let mut credentials = HashMap::new();
		credentials.insert("identifier".to_string(), identifier.to_string());
		credentials.insert("password".to_string(), password.to_string());
		self.login("password", credentials).await
	}

	pub async fn login_with_token(&mut self, token: &str) -> Result<LoginResult, Error> {
		let mut credentials = HashMap::new();
		credentials.insert("token".to_string(), token.to_string());
		self.login("token", credentials).await
	}

	pub async fn login(
		&mut self,
		method: &str,
		credentials: HashMap<String, String>,
	) -> Result<LoginResult, Error> {
		let body = json!({
			"method": method,
			"credentials": credentials
		});

		let url = format!("{}/v1/authenticate", self.base_url);
		let mut request = self.inner.post(&url).json(&body);
		if let Some(token) = &self.token {
			request = request.bearer_auth(token);
		}
		let response = request.send().await.map_err(transport)?;
		let response_body = response.text().await.map_err(transport)?;

		let auth: HttpAuthenticateResponse =
			from_str(&response_body).map_err(|_| self.parse_error_response(&response_body))?;

		if auth.status == "authenticated" {
			let token = auth.token.unwrap_or_default();
			let identity = auth.identity.unwrap_or_default();
			self.token = Some(token.clone());
			Ok(LoginResult {
				token,
				identity,
			})
		} else {
			let reason = auth.reason.unwrap_or_else(|| "Authentication failed".to_string());
			Err(ClientError::NotAuthenticated(reason).into())
		}
	}

	pub async fn logout(&mut self) -> Result<(), Error> {
		let token = match self.token.as_ref() {
			Some(t) => t.clone(),
			None => return Ok(()),
		};

		let url = format!("{}/v1/logout", self.base_url);
		let response = self.inner.post(&url).bearer_auth(&token).send().await.map_err(transport)?;

		let status = response.status();
		if status.is_success() {
			self.token = None;
			Ok(())
		} else {
			let body = response.text().await.map_err(transport)?;
			Err(self.parse_error_response(&body))
		}
	}

	pub async fn admin(&self, rql: &str, params: Option<Params>) -> Result<Vec<Frame>, Error> {
		Ok(self.admin_with_meta(rql, params).await?.frames)
	}

	pub async fn admin_with_meta(&self, rql: &str, params: Option<Params>) -> Result<AdminResult, Error> {
		let request = AdminRequest {
			rql: rql.to_string(),
			params: params.and_then(params_to_wire),
			format: None,
		};

		if self.format == WireFormat::Rbcf {
			let (frames, meta) = self.send_rbcf("/v1/admin", &request).await?;
			return Ok(AdminResult {
				frames,
				meta,
			});
		}

		let response = self.send_admin(&request).await?;
		let ws_response = Response {
			id: String::new(),
			payload: ResponsePayload::Admin(response),
		};
		parse_admin_response(ws_response)
	}

	pub async fn command(&self, rql: &str, params: Option<Params>) -> Result<Vec<Frame>, Error> {
		Ok(self.command_with_meta(rql, params).await?.frames)
	}

	pub async fn command_with_meta(&self, rql: &str, params: Option<Params>) -> Result<CommandResult, Error> {
		let request = CommandRequest {
			rql: rql.to_string(),
			params: params.and_then(params_to_wire),
			format: None,
		};

		if self.format == WireFormat::Rbcf {
			let (frames, meta) = self.send_rbcf("/v1/command", &request).await?;
			return Ok(CommandResult {
				frames,
				meta,
			});
		}

		let response = self.send_command(&request).await?;
		let ws_response = Response {
			id: String::new(),
			payload: ResponsePayload::Command(response),
		};
		parse_command_response(ws_response)
	}

	pub async fn query(&self, rql: &str, params: Option<Params>) -> Result<Vec<Frame>, Error> {
		Ok(self.query_with_meta(rql, params).await?.frames)
	}

	pub async fn query_with_meta(&self, rql: &str, params: Option<Params>) -> Result<QueryResult, Error> {
		let request = QueryRequest {
			rql: rql.to_string(),
			params: params.and_then(params_to_wire),
			format: None,
		};

		if self.format == WireFormat::Rbcf {
			let (frames, meta) = self.send_rbcf("/v1/query", &request).await?;
			return Ok(QueryResult {
				frames,
				meta,
			});
		}

		let response = self.send_query(&request).await?;
		let ws_response = Response {
			id: String::new(),
			payload: ResponsePayload::Query(response),
		};
		parse_query_response(ws_response)
	}

	async fn send_admin(&self, request: &AdminRequest) -> Result<AdminResponse, Error> {
		let url = format!("{}/v1/admin?format=frames", self.base_url);
		let (response_body, meta) = self.send_request(&url, request).await?;

		match from_str::<HttpFrameResponse>(&response_body) {
			Ok(response) => Ok(response.into_admin(meta)),
			Err(_) => Err(self.parse_error_response(&response_body)),
		}
	}

	async fn send_command(&self, request: &CommandRequest) -> Result<CommandResponse, Error> {
		let url = format!("{}/v1/command?format=frames", self.base_url);
		let (response_body, meta) = self.send_request(&url, request).await?;

		match from_str::<HttpFrameResponse>(&response_body) {
			Ok(response) => Ok(response.into_command(meta)),
			Err(_) => Err(self.parse_error_response(&response_body)),
		}
	}

	async fn send_query(&self, request: &QueryRequest) -> Result<QueryResponse, Error> {
		let url = format!("{}/v1/query?format=frames", self.base_url);
		let (response_body, meta) = self.send_request(&url, request).await?;

		match from_str::<HttpFrameResponse>(&response_body) {
			Ok(response) => Ok(response.into_query(meta)),
			Err(_) => Err(self.parse_error_response(&response_body)),
		}
	}

	pub async fn queue_claim(&self, request: QueueClaimRequest) -> Result<Vec<Frame>, Error> {
		let budget = request.wait_for.as_deref().and_then(|raw| parse_duration(Fragment::internal(raw)).ok());
		let timeout = budget.unwrap_or(Duration::zero()).try_add(Duration::from_seconds(30).unwrap())?;

		let url = format!("{}/v1/queue/claim?format=rbcf", self.base_url);
		let (bytes, _) = self.send_request_bytes_with_timeout(&url, &request, timeout).await?;
		decode_frames(&bytes)
			.map_err(|e| ClientError::Decode(format!("Failed to decode RBCF response: {}", e)).into())
	}

	async fn send_request_bytes_with_timeout<T: Serialize>(
		&self,
		url: &str,
		body: &T,
		timeout: Duration,
	) -> Result<(Vec<u8>, Option<ResponseMeta>), Error> {
		let mut request = self.inner.post(url).timeout(timeout.to_std()).json(body);

		if let Some(ref token) = self.token {
			request = request.bearer_auth(token);
		}

		let response = request.send().await.map_err(transport)?;

		if !response.status().is_success() {
			let body = response.text().await.map_err(transport)?;
			return Err(self.parse_error_response(&body));
		}

		let meta = extract_meta(response.headers());
		Ok((response.bytes().await.map_err(transport)?.to_vec(), meta))
	}

	async fn send_rbcf<T: Serialize>(
		&self,
		path: &str,
		body: &T,
	) -> Result<(Vec<Frame>, Option<ResponseMeta>), Error> {
		let url = format!("{}{}?format=rbcf", self.base_url, path);
		let (bytes, meta) = self.send_request_bytes(&url, body).await?;
		let frames = decode_frames(&bytes)
			.map_err(|e| ClientError::Decode(format!("Failed to decode RBCF response: {}", e)))?;
		Ok((frames, meta))
	}

	async fn send_request<T: Serialize>(
		&self,
		url: &str,
		body: &T,
	) -> Result<(String, Option<ResponseMeta>), Error> {
		let mut request = self.inner.post(url).json(body);

		if let Some(ref token) = self.token {
			request = request.bearer_auth(token);
		}

		let response = request.send().await.map_err(transport)?;
		let meta = extract_meta(response.headers());
		Ok((response.text().await.map_err(transport)?, meta))
	}

	async fn send_request_bytes<T: Serialize>(
		&self,
		url: &str,
		body: &T,
	) -> Result<(Vec<u8>, Option<ResponseMeta>), Error> {
		let mut request = self.inner.post(url).json(body);

		if let Some(ref token) = self.token {
			request = request.bearer_auth(token);
		}

		let response = request.send().await.map_err(transport)?;

		if !response.status().is_success() {
			let body = response.text().await.map_err(transport)?;
			return Err(self.parse_error_response(&body));
		}

		let meta = extract_meta(response.headers());
		Ok((response.bytes().await.map_err(transport)?.to_vec(), meta))
	}

	fn parse_error_response(&self, body: &str) -> Error {
		if let Ok(http_err) = from_str::<HttpErrorResponse>(body) {
			let diag = http_err.diagnostic.unwrap_or_else(|| Diagnostic {
				code: http_err.code,
				message: http_err.error,
				..Default::default()
			});
			return Error(Box::new(diag));
		}

		if let Ok(err_response) = from_str::<ErrResponse>(body) {
			return Error(Box::new(err_response.diagnostic));
		}

		ClientError::Decode(format!("failed to parse response: {}", excerpt(body))).into()
	}
}

fn transport(error: ReqwestError) -> Error {
	ClientError::Transport(error.to_string()).into()
}

#[cfg(test)]
mod tests {
	use reqwest::Client as ReqwestClient;
	use rustls::crypto::ring::default_provider;

	use super::HttpClient;
	use crate::WireFormat;

	#[test]
	fn an_unparsable_response_body_is_a_decode_error_not_a_panic() {
		// A frames body that fails to decode lands here, so it must fail the request, never the process.
		let _ = default_provider().install_default();
		let client =
			HttpClient::with_client(ReqwestClient::new(), "http://localhost", WireFormat::Frames).unwrap();
		let body = format!(r#"{{"frames":[{{"columns":"{}"}}]}}"#, "x".repeat(10_000));

		let error = client.parse_error_response(&body);

		assert_eq!(error.0.code, "DECODE");
		assert!(error.0.message.len() < 400, "body not truncated, {} bytes", error.0.message.len());
	}
}