Skip to main content

reifydb_client/
lib.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2025 ReifyDB
3#![cfg_attr(not(debug_assertions), deny(clippy::disallowed_methods))]
4#![cfg_attr(debug_assertions, warn(clippy::disallowed_methods))]
5#![allow(clippy::tabs_in_doc_comments)]
6
7/// Wire format for client-server communication.
8#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
9pub enum WireFormat {
10	#[default]
11	Json,
12	Proto,
13	Rbcf,
14}
15
16#[cfg(all(feature = "dst", reifydb_single_threaded))]
17pub mod dst;
18#[cfg(feature = "grpc")]
19pub mod grpc;
20#[cfg(feature = "http")]
21pub mod http;
22#[cfg(any(feature = "http", feature = "ws"))]
23mod session;
24#[cfg(feature = "ws")]
25mod utils;
26#[cfg(feature = "ws")]
27pub mod ws;
28
29// Re-export client types
30#[cfg(any(feature = "http", feature = "ws"))]
31use std::collections::HashMap;
32#[cfg(any(feature = "http", feature = "ws"))]
33use std::sync::Arc;
34
35#[cfg(all(feature = "dst", reifydb_single_threaded))]
36pub use dst::DstClient;
37#[cfg(feature = "grpc")]
38pub use grpc::{
39	BatchFramesEnvelope, BatchGrpcSubscription, BatchMemberHandle, BatchStreamEvent, GrpcClient, GrpcSubscription,
40	RawChangePayload,
41};
42#[cfg(feature = "http")]
43pub use http::HttpClient;
44// Re-export derive macro
45pub use reifydb_client_derive::FromFrame;
46// Re-export commonly used types from reifydb-type
47pub use reifydb_type as r#type;
48pub use reifydb_type::{
49	params::Params,
50	value::{
51		Value,
52		frame::{
53			column::FrameColumn,
54			data::FrameColumnData,
55			extract::FrameError,
56			frame::Frame,
57			from_frame::FromFrameError,
58			row::{FrameRow, FrameRows},
59		},
60		ordered_f32::OrderedF32,
61		ordered_f64::OrderedF64,
62		try_from::{FromValueError, TryFromValue, TryFromValueCoerce},
63		r#type::Type,
64	},
65};
66#[cfg(any(feature = "http", feature = "ws"))]
67use serde::{Deserialize, Serialize};
68#[cfg(any(feature = "http", feature = "ws"))]
69use serde_json::Value as JsonValue;
70#[cfg(feature = "ws")]
71pub use ws::{BatchPushEvent, WsBatchSubscription, WsClient};
72
73/// Server-reported metadata about a single executed request.
74#[cfg_attr(any(feature = "http", feature = "ws"), derive(Serialize, Deserialize))]
75#[derive(Debug, Clone)]
76pub struct ResponseMeta {
77	pub fingerprint: String,
78	pub duration: String,
79}
80
81/// Result type for admin operations
82#[derive(Debug)]
83pub struct AdminResult {
84	pub frames: Vec<Frame>,
85	pub meta: Option<ResponseMeta>,
86}
87
88/// Result type for command operations
89#[derive(Debug)]
90pub struct CommandResult {
91	pub frames: Vec<Frame>,
92	pub meta: Option<ResponseMeta>,
93}
94
95/// Result type for query operations
96#[derive(Debug)]
97pub struct QueryResult {
98	pub frames: Vec<Frame>,
99	pub meta: Option<ResponseMeta>,
100}
101
102/// Result type for authentication login operations
103#[derive(Debug, Clone)]
104pub struct LoginResult {
105	/// Session token for subsequent requests
106	pub token: String,
107	/// Identity UUID of the authenticated user
108	pub identity: String,
109}
110
111#[cfg(any(feature = "http", feature = "ws"))]
112/// Wire format for a single typed value: `{"type": "Int2", "value": "1234"}`.
113#[derive(Debug, Serialize, Deserialize)]
114pub struct WireValue {
115	#[serde(rename = "type")]
116	pub type_name: String,
117	pub value: String,
118}
119
120#[cfg(any(feature = "http", feature = "ws"))]
121/// Wire format for query parameters.
122///
123/// Either positional or named:
124/// - Positional: `[{"type":"Int2","value":"1234"}, ...]`
125/// - Named: `{"key": {"type":"Int2","value":"1234"}, ...}`
126#[derive(Debug, Serialize, Deserialize)]
127#[serde(untagged)]
128pub enum WireParams {
129	Positional(Vec<WireValue>),
130	Named(HashMap<String, WireValue>),
131}
132
133#[cfg(any(feature = "http", feature = "ws"))]
134fn value_to_wire(value: Value) -> WireValue {
135	let (type_name, value_str): (&str, String) = match &value {
136		Value::None {
137			..
138		} => ("None", "\u{27EA}none\u{27EB}".to_string()),
139		Value::Boolean(b) => ("Boolean", b.to_string()),
140		Value::Float4(f) => ("Float4", f.to_string()),
141		Value::Float8(f) => ("Float8", f.to_string()),
142		Value::Int1(i) => ("Int1", i.to_string()),
143		Value::Int2(i) => ("Int2", i.to_string()),
144		Value::Int4(i) => ("Int4", i.to_string()),
145		Value::Int8(i) => ("Int8", i.to_string()),
146		Value::Int16(i) => ("Int16", i.to_string()),
147		Value::Utf8(s) => ("Utf8", s.clone()),
148		Value::Uint1(u) => ("Uint1", u.to_string()),
149		Value::Uint2(u) => ("Uint2", u.to_string()),
150		Value::Uint4(u) => ("Uint4", u.to_string()),
151		Value::Uint8(u) => ("Uint8", u.to_string()),
152		Value::Uint16(u) => ("Uint16", u.to_string()),
153		Value::Uuid4(u) => ("Uuid4", u.to_string()),
154		Value::Uuid7(u) => ("Uuid7", u.to_string()),
155		Value::Date(d) => ("Date", d.to_string()),
156		Value::DateTime(dt) => ("DateTime", dt.to_string()),
157		Value::Time(t) => ("Time", t.to_string()),
158		Value::Duration(d) => ("Duration", d.to_iso_string()),
159		Value::Blob(b) => ("Blob", b.to_hex()),
160		Value::IdentityId(id) => ("IdentityId", id.to_string()),
161		Value::Int(i) => ("Int", i.to_string()),
162		Value::Uint(u) => ("Uint", u.to_string()),
163		Value::Decimal(d) => ("Decimal", d.to_string()),
164		Value::Any(v) => return value_to_wire(*v.clone()),
165		Value::DictionaryId(id) => ("DictionaryId", id.to_string()),
166		Value::Type(t) => ("Type", t.to_string()),
167		Value::List(items) => ("List", format!("{}", Value::List(items.clone()))),
168		Value::Record(fields) => ("Record", format!("{}", Value::Record(fields.clone()))),
169		Value::Tuple(items) => ("Tuple", format!("{}", Value::Tuple(items.clone()))),
170	};
171	WireValue {
172		type_name: type_name.to_string(),
173		value: value_str,
174	}
175}
176
177#[cfg(any(feature = "http", feature = "ws"))]
178pub fn params_to_wire(params: Params) -> Option<WireParams> {
179	match params {
180		Params::None => None,
181		Params::Positional(values) => Some(WireParams::Positional(
182			Arc::unwrap_or_clone(values).into_iter().map(value_to_wire).collect(),
183		)),
184		Params::Named(map) => Some(WireParams::Named(
185			Arc::unwrap_or_clone(map).into_iter().map(|(k, v)| (k, value_to_wire(v))).collect(),
186		)),
187	}
188}
189
190#[cfg(any(feature = "http", feature = "ws"))]
191#[derive(Debug, Serialize, Deserialize)]
192pub struct Request {
193	pub id: String,
194	#[serde(flatten)]
195	pub payload: RequestPayload,
196}
197
198#[cfg(any(feature = "http", feature = "ws"))]
199#[derive(Debug, Serialize, Deserialize)]
200#[serde(tag = "type", content = "payload")]
201pub enum RequestPayload {
202	Auth(AuthRequest),
203	Admin(AdminRequest),
204	Command(CommandRequest),
205	Query(QueryRequest),
206	Subscribe(SubscribeRequest),
207	Unsubscribe(UnsubscribeRequest),
208	BatchSubscribe(BatchSubscribeRequest),
209	BatchUnsubscribe(BatchUnsubscribeRequest),
210	Logout,
211}
212
213#[cfg(any(feature = "http", feature = "ws"))]
214#[derive(Debug, Serialize, Deserialize)]
215pub struct AdminRequest {
216	pub rql: String,
217	pub params: Option<WireParams>,
218	#[serde(skip_serializing_if = "Option::is_none")]
219	pub format: Option<String>,
220}
221
222#[cfg(any(feature = "http", feature = "ws"))]
223#[derive(Debug, Serialize, Deserialize)]
224pub struct AuthRequest {
225	#[serde(skip_serializing_if = "Option::is_none")]
226	pub token: Option<String>,
227	#[serde(skip_serializing_if = "Option::is_none")]
228	pub method: Option<String>,
229	#[serde(skip_serializing_if = "Option::is_none")]
230	pub credentials: Option<HashMap<String, String>>,
231}
232
233#[cfg(any(feature = "http", feature = "ws"))]
234#[derive(Debug, Serialize, Deserialize)]
235pub struct CommandRequest {
236	pub rql: String,
237	pub params: Option<WireParams>,
238	#[serde(skip_serializing_if = "Option::is_none")]
239	pub format: Option<String>,
240}
241
242#[cfg(any(feature = "http", feature = "ws"))]
243#[derive(Debug, Serialize, Deserialize)]
244pub struct QueryRequest {
245	pub rql: String,
246	pub params: Option<WireParams>,
247	#[serde(skip_serializing_if = "Option::is_none")]
248	pub format: Option<String>,
249}
250
251#[cfg(any(feature = "http", feature = "ws"))]
252#[derive(Debug, Serialize, Deserialize)]
253pub struct SubscribeRequest {
254	pub rql: String,
255	#[serde(skip_serializing_if = "Option::is_none")]
256	pub format: Option<String>,
257}
258
259#[cfg(any(feature = "http", feature = "ws"))]
260#[derive(Debug, Serialize, Deserialize)]
261pub struct UnsubscribeRequest {
262	pub subscription_id: String,
263}
264
265#[cfg(any(feature = "http", feature = "ws"))]
266#[derive(Debug, Serialize, Deserialize)]
267pub struct BatchSubscribeRequest {
268	pub queries: Vec<String>,
269	#[serde(skip_serializing_if = "Option::is_none")]
270	pub format: Option<String>,
271}
272
273#[cfg(any(feature = "http", feature = "ws"))]
274#[derive(Debug, Serialize, Deserialize)]
275pub struct BatchUnsubscribeRequest {
276	pub batch_id: String,
277}
278
279#[cfg(any(feature = "http", feature = "ws"))]
280#[derive(Debug, Serialize, Deserialize)]
281pub struct Response {
282	pub id: String,
283	#[serde(flatten)]
284	pub payload: ResponsePayload,
285}
286
287#[cfg(any(feature = "http", feature = "ws"))]
288#[derive(Debug, Serialize, Deserialize)]
289#[serde(tag = "type", content = "payload")]
290pub enum ResponsePayload {
291	Auth(AuthResponse),
292	Err(ErrResponse),
293	Admin(AdminResponse),
294	Command(CommandResponse),
295	Query(QueryResponse),
296	Subscribed(SubscribedResponse),
297	Unsubscribed(UnsubscribedResponse),
298	BatchSubscribed(BatchSubscribedResponse),
299	BatchUnsubscribed(BatchUnsubscribedResponse),
300	Logout(LogoutResponsePayload),
301}
302
303#[cfg(any(feature = "http", feature = "ws"))]
304#[derive(Debug, Serialize, Deserialize)]
305pub struct AdminResponse {
306	pub content_type: String,
307	pub body: JsonValue,
308	#[serde(default)]
309	pub meta: Option<ResponseMeta>,
310}
311
312#[cfg(any(feature = "http", feature = "ws"))]
313use reifydb_type::error::Diagnostic;
314
315#[cfg(any(feature = "http", feature = "ws"))]
316#[derive(Debug, Serialize, Deserialize)]
317pub struct AuthResponse {
318	#[serde(skip_serializing_if = "Option::is_none")]
319	pub status: Option<String>,
320	#[serde(skip_serializing_if = "Option::is_none")]
321	pub token: Option<String>,
322	#[serde(skip_serializing_if = "Option::is_none")]
323	pub identity: Option<String>,
324}
325
326#[cfg(any(feature = "http", feature = "ws"))]
327#[derive(Debug, Serialize, Deserialize)]
328pub struct ErrResponse {
329	pub diagnostic: Diagnostic,
330}
331
332#[cfg(any(feature = "http", feature = "ws"))]
333#[derive(Debug, Serialize, Deserialize)]
334pub struct CommandResponse {
335	pub content_type: String,
336	pub body: JsonValue,
337	#[serde(default)]
338	pub meta: Option<ResponseMeta>,
339}
340
341#[cfg(any(feature = "http", feature = "ws"))]
342#[derive(Debug, Serialize, Deserialize)]
343pub struct QueryResponse {
344	pub content_type: String,
345	pub body: JsonValue,
346	#[serde(default)]
347	pub meta: Option<ResponseMeta>,
348}
349
350#[cfg(any(feature = "http", feature = "ws"))]
351#[derive(Debug, Serialize, Deserialize)]
352pub struct SubscribedResponse {
353	pub subscription_id: String,
354}
355
356#[cfg(any(feature = "http", feature = "ws"))]
357#[derive(Debug, Serialize, Deserialize)]
358pub struct UnsubscribedResponse {
359	pub subscription_id: String,
360}
361
362#[cfg(any(feature = "http", feature = "ws"))]
363#[derive(Debug, Serialize, Deserialize)]
364pub struct BatchSubscribedResponse {
365	pub batch_id: String,
366	pub members: Vec<BatchMemberInfo>,
367}
368
369#[cfg(any(feature = "http", feature = "ws"))]
370#[derive(Debug, Clone, Serialize, Deserialize)]
371pub struct BatchMemberInfo {
372	pub index: usize,
373	pub subscription_id: String,
374}
375
376#[cfg(any(feature = "http", feature = "ws"))]
377#[derive(Debug, Serialize, Deserialize)]
378pub struct BatchUnsubscribedResponse {
379	pub batch_id: String,
380}
381
382#[cfg(any(feature = "http", feature = "ws"))]
383#[derive(Debug, Serialize, Deserialize)]
384pub struct LogoutResponsePayload {
385	pub status: String,
386}
387
388#[cfg(any(feature = "http", feature = "ws"))]
389/// Server-initiated push message (no request id).
390#[derive(Debug, Serialize, Deserialize)]
391#[serde(tag = "type", content = "payload")]
392pub enum ServerPush {
393	Change(ChangePayload),
394	BatchChange(BatchChangePayload),
395	BatchMemberClosed(BatchMemberClosedPayload),
396	BatchClosed(BatchClosedPayload),
397}
398
399#[cfg(any(feature = "http", feature = "ws"))]
400/// Payload for subscription change notifications.
401///
402/// For JSON pushes, `body` holds the JSON frames body and `frames` is `None`.
403/// For RBCF pushes, the client decodes the binary envelope and populates
404/// `frames` directly; `body` is empty and `content_type` is `application/vnd.reifydb.rbcf`.
405#[derive(Debug, Clone, Serialize, Deserialize)]
406pub struct ChangePayload {
407	pub subscription_id: String,
408	pub content_type: String,
409	pub body: JsonValue,
410	#[serde(skip, default)]
411	pub frames: Option<Vec<Frame>>,
412}
413
414#[cfg(any(feature = "http", feature = "ws"))]
415#[derive(Debug, Clone, Serialize, Deserialize)]
416pub struct BatchChangePayload {
417	pub batch_id: String,
418	pub entries: Vec<BatchChangeEntry>,
419}
420
421#[cfg(any(feature = "http", feature = "ws"))]
422#[derive(Debug, Clone, Serialize, Deserialize)]
423pub struct BatchChangeEntry {
424	pub subscription_id: String,
425	pub content_type: String,
426	pub body: JsonValue,
427	#[serde(skip, default)]
428	pub frames: Option<Vec<Frame>>,
429	#[serde(skip, default)]
430	pub decode_error: Option<String>,
431}
432
433#[cfg(any(feature = "http", feature = "ws"))]
434#[derive(Debug, Clone, Serialize, Deserialize)]
435pub struct BatchMemberClosedPayload {
436	pub batch_id: String,
437	pub subscription_id: String,
438}
439
440#[cfg(any(feature = "http", feature = "ws"))]
441#[derive(Debug, Clone, Serialize, Deserialize)]
442pub struct BatchClosedPayload {
443	pub batch_id: String,
444}