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
use std::sync::Arc;
use super::{KalamLinkClient, KalamLinkClientBuilder, QueryUploadFile};
#[cfg(feature = "consumer")]
use crate::consumer::ConsumerBuilder;
use crate::{
auth::{AuthProvider, ResolvedAuth},
error::{KalamLinkError, Result},
event_handlers::EventHandlers,
models::{LoginResponse, QueryResponse, SubscriptionConfig, SubscriptionInfo},
query::UploadProgressCallback,
subscription::{LiveRowsConfig, LiveRowsSubscription, SubscriptionManager},
timeouts::KalamLinkTimeouts,
};
impl KalamLinkClient {
/// Create a new builder for configuring the client
pub fn builder() -> KalamLinkClientBuilder {
KalamLinkClientBuilder::new()
}
/// Execute a SQL query with optional files, parameters, and namespace context
///
/// # Arguments
/// * `sql` - The SQL query string
/// * `files` - Optional file uploads for FILE("name") placeholders
/// * `params` - Optional query parameters for $1, $2, ... placeholders
/// * `namespace_id` - Optional namespace for unqualified table names
///
/// # Example
/// ```rust,no_run
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = kalam_client::KalamLinkClient::builder().base_url("http://localhost:3000").build()?;
/// // Simple query
/// let result = client.execute_query("SELECT * FROM users", None, None, None).await?;
///
/// // Query with parameters
/// let params = vec![serde_json::json!(42)];
/// let result = client.execute_query("SELECT * FROM users WHERE id = $1", None, Some(params), None).await?;
///
/// // Query in specific namespace
/// let result = client.execute_query("SELECT * FROM messages", None, None, Some("chat")).await?;
/// # Ok(())
/// # }
/// ```
pub async fn execute_query(
&self,
sql: &str,
files: Option<Vec<QueryUploadFile<'_>>>,
params: Option<Vec<serde_json::Value>>,
namespace_id: Option<&str>,
) -> Result<QueryResponse> {
self.execute_query_with_progress(sql, files, params, namespace_id, None).await
}
/// Execute a SQL query with optional files and a progress callback for uploads.
pub async fn execute_query_with_progress(
&self,
sql: &str,
files: Option<Vec<QueryUploadFile<'_>>>,
params: Option<Vec<serde_json::Value>>,
namespace_id: Option<&str>,
progress: Option<UploadProgressCallback>,
) -> Result<QueryResponse> {
let files_owned = files.map(|items| {
items
.into_iter()
.map(|(placeholder, filename, data, mime)| {
(
placeholder.to_string(),
filename.to_string(),
data,
mime.map(|m| m.to_string()),
)
})
.collect()
});
self.query_executor
.execute_with_progress_ref(sql, files_owned, params, namespace_id, progress)
.await
}
/// Execute a SQL query with file uploads (FILE datatype support).
///
/// This method allows inserting/updating rows that contain FILE columns.
/// Use FILE("name") placeholders in SQL that reference uploaded files.
#[cfg(feature = "file-uploads")]
pub async fn execute_with_files(
&self,
sql: &str,
files: Vec<QueryUploadFile<'_>>,
params: Option<Vec<serde_json::Value>>,
namespace_id: Option<&str>,
) -> Result<QueryResponse> {
self.execute_query(sql, Some(files), params, namespace_id).await
}
/// Execute a SQL query with file uploads and a progress callback.
#[cfg(feature = "file-uploads")]
pub async fn execute_with_files_with_progress(
&self,
sql: &str,
files: Vec<QueryUploadFile<'_>>,
params: Option<Vec<serde_json::Value>>,
namespace_id: Option<&str>,
progress: Option<UploadProgressCallback>,
) -> Result<QueryResponse> {
self.execute_query_with_progress(sql, Some(files), params, namespace_id, progress)
.await
}
/// Open a low-level live event stream.
///
/// Live streams are multiplexed over the shared WebSocket connection.
pub async fn live_events(&self, query: &str) -> Result<SubscriptionManager> {
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_nanos();
let subscription_id = format!("sub_{}", nanos);
self.live_events_with_config(SubscriptionConfig::new(subscription_id, query))
.await
}
/// Open a low-level live event stream with advanced configuration.
///
/// When [`ConnectionOptions::ws_lazy_connect`] is `true` (the default)
/// and no shared connection exists yet, `connect()` is called
/// automatically before opening the stream.
pub async fn live_events_with_config(
&self,
config: SubscriptionConfig,
) -> Result<SubscriptionManager> {
if self.connection_options.ws_lazy_connect {
let conn_guard = self.connection.lock().await;
if conn_guard.is_none() {
drop(conn_guard);
self.connect().await?;
}
}
let conn = {
let conn_guard = self.connection.lock().await;
conn_guard.clone()
};
if let Some(conn) = conn {
// Send the protocol subscribe command without holding the client
// connection mutex. The command channel is bounded and can apply
// backpressure, so awaiting it while locked would serialize or
// stall unrelated connection operations.
let (event_rx, result_rx) =
conn.subscribe_send(config.id.clone(), config.sql, config.options).await?;
let shared_control = conn.subscription_control();
// Wait for the server ack without the lock held. Initial snapshot
// batches continue through the returned subscription stream.
let (generation, resume_from) = result_rx.await.map_err(|_| {
KalamLinkError::WebSocketError(
"Connection task died before confirming subscribe".to_string(),
)
})??;
return Ok(SubscriptionManager::from_shared(
config.id,
event_rx,
shared_control,
generation,
resume_from,
&self.timeouts,
));
}
Err(KalamLinkError::WebSocketError(
"Not connected. Call connect() before opening live streams.".to_string(),
))
}
/// Open a SQL query and receive materialized row snapshots.
pub async fn live(&self, query: &str) -> Result<LiveRowsSubscription> {
self.live_with_config(
SubscriptionConfig::new(
format!(
"live_rows_{}",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_nanos()
),
query,
),
LiveRowsConfig::default(),
)
.await
}
/// Open materialized live rows with advanced low-level and materialization configuration.
pub async fn live_with_config(
&self,
config: SubscriptionConfig,
live_rows_config: LiveRowsConfig,
) -> Result<LiveRowsSubscription> {
let subscription = self.live_events_with_config(config).await?;
Ok(LiveRowsSubscription::new(subscription, live_rows_config))
}
/// Establish a shared WebSocket connection.
///
/// After calling this, all subsequent [`live_events()`](Self::live_events)
/// and [`live()`](Self::live) calls will multiplex over the single connection.
pub async fn connect(&self) -> Result<()> {
{
let conn_guard = self.connection.lock().await;
if conn_guard.is_some() {
return Ok(());
}
}
let resolved_auth = match self.fresh_auth().await? {
AuthProvider::BasicAuth(user, password) => {
let login_response = self.exchange_login_credentials(&user, &password).await?;
AuthProvider::jwt_token(login_response.access_token)
},
auth => auth,
};
self.update_shared_auth(resolved_auth);
let conn = Arc::new(
crate::connection::SharedConnection::connect(
self.base_url.clone(),
self.shared_resolved_auth.clone(),
self.timeouts.clone(),
self.connection_options.clone(),
self.event_handlers.clone(),
)
.await?,
);
let mut conn_guard = self.connection.lock().await;
if conn_guard.is_none() {
*conn_guard = Some(conn);
} else {
drop(conn_guard);
conn.disconnect().await;
}
Ok(())
}
/// Disconnect the shared WebSocket connection.
pub async fn disconnect(&self) {
let conn = {
let mut guard = self.connection.lock().await;
guard.take()
};
if let Some(conn) = conn {
conn.disconnect().await;
}
}
/// Cancel / unsubscribe a subscription by ID on the shared connection.
pub async fn cancel_subscription(&self, id: &str) -> Result<()> {
let conn = {
let guard = self.connection.lock().await;
guard.clone()
};
if let Some(conn) = conn {
conn.unsubscribe(id).await?;
}
Ok(())
}
/// Whether the shared connection is currently ready.
///
/// During reconnect with active subscriptions, this stays false until the
/// subscription set has recovered, not merely until the socket handshake
/// succeeds.
pub async fn is_connected(&self) -> bool {
let guard = self.connection.lock().await;
guard.as_ref().is_some_and(|conn| conn.is_connected())
}
/// List all active subscriptions on the shared connection.
pub async fn subscriptions(&self) -> Vec<SubscriptionInfo> {
let conn = {
let guard = self.connection.lock().await;
guard.clone()
};
match conn.as_ref() {
Some(conn) => conn.list_subscriptions().await,
None => Vec::new(),
}
}
/// Get the current event handlers
pub fn event_handlers(&self) -> &EventHandlers {
&self.event_handlers
}
/// Get the configured timeouts
pub fn timeouts(&self) -> &KalamLinkTimeouts {
&self.timeouts
}
/// Create a topic consumer builder bound to this client
#[cfg(feature = "consumer")]
pub fn consumer(&self) -> ConsumerBuilder {
ConsumerBuilder::from_client(self.clone())
}
#[cfg(feature = "consumer")]
pub(crate) fn base_url(&self) -> &str {
&self.base_url
}
#[cfg(feature = "consumer")]
pub(crate) fn http_client(&self) -> reqwest::Client {
self.http_client.clone()
}
#[cfg(feature = "consumer")]
pub(crate) fn auth(&self) -> &AuthProvider {
&self.auth
}
/// Return the resolved auth source (static or dynamic).
pub fn resolved_auth(&self) -> &ResolvedAuth {
&self.resolved_auth
}
/// Replace the static authentication credentials at runtime.
pub fn set_auth(&mut self, auth: AuthProvider) {
self.auth = auth.clone();
self.query_executor.set_auth(auth.clone());
let resolved = ResolvedAuth::Static(auth);
self.resolved_auth = resolved.clone();
*self.shared_resolved_auth.write().unwrap() = resolved;
}
/// Update the shared authentication source without requiring `&mut self`.
pub fn update_shared_auth(&self, auth: AuthProvider) {
self.query_executor.set_auth(auth.clone());
let resolved = ResolvedAuth::Static(auth);
*self.shared_resolved_auth.write().unwrap() = resolved;
}
/// Resolve fresh credentials from the auth source.
pub async fn fresh_auth(&self) -> Result<AuthProvider> {
self.resolved_auth.resolve().await
}
async fn exchange_login_credentials(
&self,
user: &str,
password: &str,
) -> Result<LoginResponse> {
let url = format!("{}/v1/api/auth/login", self.base_url);
let body = serde_json::json!({
"user": user,
"password": password,
});
let response = self.http_client.post(&url).json(&body).send().await?;
let status = response.status();
if !status.is_success() {
let error_text = response.text().await.unwrap_or_else(|_| "Unknown error".to_string());
return Err(KalamLinkError::AuthenticationError(format!(
"Login failed during auth exchange ({}): {}",
status, error_text
)));
}
Ok(response.json::<LoginResponse>().await?)
}
}