channel_session/
channel_ws.rs

1// Copyright (c) reifydb.com 2025
2// This file is licensed under the MIT
3
4use std::time::Duration;
5
6use reifydb_client::{ChannelResponse, Client};
7
8fn main() -> Result<(), Box<dyn std::error::Error>> {
9	// Connect to ReifyDB server
10	let client = Client::ws(("127.0.0.1", 8090))?;
11
12	// Create a channel session with authentication
13	let (session, receiver) = client.channel_session(Some("mysecrettoken".to_string()))?;
14
15	// Consume authentication response
16	if let Ok(msg) = receiver.recv_timeout(Duration::from_millis(100)) {
17		if let Ok(ChannelResponse::Auth {
18			request_id,
19		}) = msg.response
20		{
21			println!("Authenticated with ID: {}", request_id);
22		}
23	}
24
25	// Execute a command to create a table
26	let command_id =
27		session.command("CREATE NAMESPACE test; CREATE TABLE test.users { id: INT4, name: UTF8 }", None)?;
28	println!("Command sent with ID: {}", command_id);
29
30	// Execute a query
31	let query_id = session.query("MAP { x: 42, y: 'hello' }", None)?;
32	println!("Query sent with ID: {}", query_id);
33
34	// Receive responses
35	let mut received = 0;
36	while received < 2 {
37		match receiver.recv_timeout(Duration::from_secs(1)) {
38			Ok(msg) => {
39				match msg.response {
40					Ok(ChannelResponse::Command {
41						request_id,
42						result,
43					}) => {
44						println!(
45							"Command {} executed: {} frames returned",
46							request_id,
47							result.frames.len()
48						);
49						received += 1;
50					}
51					Ok(ChannelResponse::Query {
52						request_id,
53						result,
54					}) => {
55						println!(
56							"Query {} executed: {} frames returned",
57							request_id,
58							result.frames.len()
59						);
60						// Print first frame if
61						// available
62						if let Some(frame) = result.frames.first() {
63							println!("First frame:\n{}", frame);
64						}
65						received += 1;
66					}
67					Ok(ChannelResponse::Auth {
68						..
69					}) => {
70						// Already handled above
71					}
72					Err(e) => {
73						println!("Request {} failed: {}", msg.request_id, e);
74						received += 1;
75					}
76				}
77			}
78			Err(_) => {
79				println!("Timeout waiting for responses");
80				break;
81			}
82		}
83	}
84
85	Ok(())
86}