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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
use futures_core::stream::Stream;
use futures_util::stream::StreamExt;
use reqwest::ClientBuilder;
use serde::de::DeserializeOwned;
use serde_json::json;
use std::collections::HashMap;
use super::client::USER_AGENT;
use super::{Error, KsqlDB, Result};
#[cfg(feature = "http2")]
pub use http2::*;
#[cfg(not(feature = "http2"))]
#[cfg(feature = "http1")]
pub use http1::*;
#[cfg(feature = "http2")]
mod http2 {
use bytes::Bytes;
use pin_project_lite::pin_project;
use reqwest::header::CONTENT_TYPE;
use serde_json::Value;
use std::marker::PhantomData;
use std::pin::Pin;
use std::task::{Context, Poll};
use super::*;
impl KsqlDB {
/// Initialises the KSQL DB Client with the provided `request::ClientBuilder`.
///
/// Any authentication or common headers should be attached to the client prior to
/// calling this method.
pub fn new(url: String, mut builder: ClientBuilder, https_only: bool) -> Result<Self> {
builder = builder
.user_agent(USER_AGENT)
.http2_prior_knowledge()
.https_only(https_only);
Ok(Self {
client: builder.build()?,
root_url: url,
https_only,
})
}
/// This method lets you stream the output records of a `SELECT` statement
/// via HTTP/2 streams. The response is streamed back until the
/// `LIMIT` specified in the statement is reached, or the client closes the connection.
///
/// If no `LIMIT` is specified in the statement, then the response is streamed until the client closes the connection.
///
/// This method requires the `http2` feature be enabled.
///
/// This crate also offers a HTTP/1 compatible approach to streaming results via
/// `Transfer-Encoding: chunked`. To enable this turn off default features and enable the
/// `http1` feature.
///
/// ## Notes
///
/// - The `T` provided, must be able to directly [`serde::Deserialize`] the response, it will
/// error if there are missing mandatory fields
/// - In the example below, if you were to change the query to be `SELECT ID FROM
/// EVENT_REPLAY_STREAM EMIT CHANGES`, the query would error, because all of the other fields
/// within the struct are mandatory fields.
///
/// ## Example
///
/// ```no_run
/// use futures_util::StreamExt;
/// use reqwest::Client;
/// use serde::Deserialize;
///
/// use ksqldb::KsqlDB;
///
/// #[derive(Debug, Deserialize)]
/// struct Response {
/// id: String,
/// is_keyframe: bool,
/// sequence_number: u32,
/// events_since_keyframe: u32,
/// event_data: String,
/// }
///
/// #[tokio::main]
/// async fn main() {
/// let ksql = KsqlDB::new("localhost:8080".into(), Client::builder(), false).unwrap();
/// let query = "SELECT * FROM EVENT_REPLAY_STREAM EMIT CHANGES;";
///
/// let mut stream = ksql
/// .query::<Response>(&query, &Default::default())
/// .await
/// .unwrap();
/// while let Some(r) = stream.next().await {
/// match r {
/// Ok(data) => {
/// println!("{:#?}", data);
/// }
/// Err(e) => {
/// eprintln!("Found Error {}", e);
/// }
/// }
/// }
/// }
/// ```
///
/// [API Docs](https://docs.ksqldb.io/en/0.13.0-ksqldb/developer-guide/ksqldb-rest-api/streaming-endpoint/)
pub async fn query<T>(
&self,
statement: &str,
properties: &HashMap<String, String>,
) -> Result<impl Stream<Item = Result<T>>>
where
T: DeserializeOwned,
{
let url = format!("{}{}/query-stream", self.url_prefix(), self.root_url);
let payload = json!({
"sql": statement,
"properties": properties
});
let mut response = self
.client
.post(&url)
.header(CONTENT_TYPE, "application/vnd.ksqlapi.delimited.v1")
.json(&payload)
.send()
.await?
.bytes_stream();
let columns = match response.next().await {
Some(data) => Ok(data?),
None => Err(Error::KSQLStream(
"Expected to receive data about the schema".to_string(),
)),
}?;
let mut json = serde_json::from_slice::<Value>(&columns)?;
if let Some(error_code) = json.get("error_code") {
if let Some(error) = json.get("message") {
return Err(Error::KSQLStream(format!(
"Error code: {}, message: {}",
error_code, error
)));
}
}
let schema = json["columnNames"].take();
let columns: Vec<String> = serde_json::from_value::<Vec<String>>(schema)?
.into_iter()
.map(|c| c.to_lowercase())
.collect();
let stream: QueryStream<T, _> = QueryStream::new(response, columns);
Ok(stream)
}
}
pin_project! {
#[derive(Default)]
struct QueryStream<T, S>
where
S: Stream,
T: DeserializeOwned,
{
columns: Vec<String>,
#[pin]
stream: S,
_marker: PhantomData<T>,
}
}
impl<T, S> QueryStream<T, S>
where
T: DeserializeOwned,
S: Stream<Item = std::result::Result<Bytes, reqwest::Error>>,
{
pub fn new(stream: S, columns: Vec<String>) -> Self {
Self {
columns,
stream,
_marker: PhantomData::default(),
}
}
}
impl<T, S> Stream for QueryStream<T, S>
where
T: DeserializeOwned,
S: Stream<Item = std::result::Result<Bytes, reqwest::Error>>,
{
type Item = Result<T>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let mut this = self.project();
Pin::new(&mut this.stream).poll_next(cx).map(|data| {
let data = data?;
let data = match data {
Ok(data) => data,
Err(e) => return Some(Err(Error::from(e))),
};
let json = match serde_json::from_slice::<Value>(&*data) {
Ok(data) => data,
Err(e) => return Some(Err(Error::from(e))),
};
if json.get("error_code").is_some() {
if let Some(error) = json.get("message") {
return Some(Err(Error::KSQLStream(error.to_string())));
}
}
let arr = match json.as_array() {
Some(data) => data.to_owned(),
None => {
return Some(Err(Error::KSQLStream(
"Expected an array of column data".to_string(),
)))
}
};
let resp =
this.columns
.iter()
.zip(arr.into_iter())
.fold(json!({}), |mut acc, (k, v)| {
acc[k] = v;
acc
});
let resp = match serde_json::from_value::<T>(resp) {
Ok(data) => data,
Err(e) => return Some(Err(Error::from(e))),
};
Some(Ok(resp))
})
}
}
}
#[cfg(feature = "http1")]
#[cfg(not(feature = "http2"))]
mod http1 {
use bytes::Bytes;
use futures_core::Stream;
use futures_util::future;
use lazy_static::lazy_static;
use pin_project_lite::pin_project;
use regex::Regex;
use serde::Deserialize;
use serde_json::Value;
use std::marker::PhantomData;
use std::pin::Pin;
use std::task::{Context, Poll};
use super::*;
lazy_static! {
static ref COLUMN_REGEX: Regex =
Regex::new(r#"`(?P<column>[a-zA-Z0-9_]+)`\w?"#).expect("failed to create column regex");
}
const NEW_LINE_DELIM: [u8; 1] = *b"\n";
const NEW_LINE_COMMA_DELIM: [u8; 2] = *b",\n";
impl KsqlDB {
/// Initialises the KSQL DB Client with the provided `request::ClientBuilder`.
///
/// Any authentication or common headers should be attached to the client prior to
/// calling this method.
pub fn new(url: String, mut builder: ClientBuilder, https_only: bool) -> Result<Self> {
builder = builder.user_agent(USER_AGENT).https_only(https_only);
Ok(Self {
client: builder.build()?,
root_url: url,
https_only,
})
}
/// This method lets you stream the output records of a `SELECT` statement
/// via a chunked transfer encoding. The response is streamed back until the
/// `LIMIT` specified in the statement is reached, or the client closes the connection.
///
/// If no `LIMIT` is specified in the statement, then the response is streamed until the client closes the connection.
///
/// This method requires the `http1` feature is enabled.
///
/// This crate also offers a HTTP/2 compatible approach to streaming results. To enable this
/// ensure the `http2` feature is being used.
///
/// ## Notes
///
/// - The `T` provided, must be able to directly [`Deserialize`] the response, it will
/// error if there are missing mandatory fields
/// - In the example below, if you were to change the query to be `SELECT ID FROM
/// EVENT_REPLAY_STREAM EMIT CHANGES`, the query would error, because all of the other fields
/// within the struct are mandatory fields.
///
/// ## Example
///
/// ```no_run
/// use futures_util::StreamExt;
/// use reqwest::Client;
/// use serde::Deserialize;
///
/// use ksqldb::KsqlDB;
///
/// #[derive(Debug, Deserialize)]
/// struct Response {
/// id: String,
/// is_keyframe: bool,
/// sequence_number: u32,
/// events_since_keyframe: u32,
/// event_data: String,
/// }
///
/// #[tokio::main]
/// async fn main() {
/// let ksql = KsqlDB::new("localhost:8080".into(), Client::builder(), false).unwrap();
/// let query = "SELECT * FROM EVENT_REPLAY_STREAM EMIT CHANGES;";
///
/// let mut stream = ksql
/// .query::<Response>(&query, &Default::default())
/// .await
/// .unwrap();
/// while let Some(r) = stream.next().await {
/// match r {
/// Ok(data) => {
/// println!("{:#?}", data);
/// }
/// Err(e) => {
/// eprintln!("Found Error {}", e);
/// }
/// }
/// }
/// }
/// ```
///
/// [API Docs](https://docs.ksqldb.io/en/0.13.0-ksqldb/developer-guide/ksqldb-rest-api/query-endpoint/)
pub async fn query<T>(
&self,
query: &str,
stream_properties: &HashMap<String, String>,
) -> Result<impl Stream<Item = Result<T>>>
where
T: DeserializeOwned,
{
let url = format!("{}{}/query", self.url_prefix(), self.root_url);
let payload = json!({
"ksql": query,
"streamProperties": stream_properties
});
let mut stream = self
.client
.post(&url)
.json(&payload)
.send()
.await?
.bytes_stream();
let columns = match stream.next().await {
Some(data) => Ok(data?),
None => Err(Error::KSQLStream(
"Expected to receive data about the schema".to_string(),
)),
}?;
let stream = stream.filter(|x| {
if let Ok(data) = x {
future::ready(**data != NEW_LINE_DELIM && **data != NEW_LINE_COMMA_DELIM)
} else {
future::ready(true)
}
});
// This should be the `header` for the events
// This will contain the column information
let mut json = serde_json::from_slice::<Value>(&columns[1..])?;
let schema = json["header"]["schema"].take();
let schema_str = serde_json::to_string(&schema)?;
let captures = COLUMN_REGEX.captures_iter(&schema_str);
let columns = captures
.into_iter()
.map(|c| c["column"].to_lowercase())
.collect::<Vec<String>>();
let stream: TransferEncodedStream<T, _> = TransferEncodedStream::new(stream, columns);
Ok(stream)
}
}
pin_project! {
#[derive(Default)]
struct TransferEncodedStream<T, S> where S: Stream, T: DeserializeOwned {
columns: Vec<String>,
#[pin]
stream: S,
_marker: PhantomData<T>
}
}
impl<T, S> TransferEncodedStream<T, S>
where
T: DeserializeOwned,
S: Stream<Item = std::result::Result<Bytes, reqwest::Error>>,
{
pub fn new(stream: S, columns: Vec<String>) -> Self {
Self {
columns,
stream,
_marker: PhantomData::default(),
}
}
}
impl<T, S> Stream for TransferEncodedStream<T, S>
where
T: DeserializeOwned,
S: Stream<Item = std::result::Result<Bytes, reqwest::Error>>,
{
type Item = Result<T>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let mut this = self.project();
Pin::new(&mut this.stream).poll_next(cx).map(|data| {
let data = match data? {
Ok(data) => data,
Err(e) => return Some(Err(Error::from(e))),
};
let json = match serde_json::from_slice::<QueryResponse>(&*data) {
Ok(data) => data,
Err(e) => return Some(Err(Error::from(e))),
};
// Check to see if the stream is about to close
if let Some(error) = json.error_message {
return Some(Err(Error::KSQLStream(error)));
}
if let Some(message) = json.final_message {
return Some(Err(Error::FinalMessage(message)));
}
// Actually process the raw data
if let Some(data) = json.row {
let columns = data.columns;
let resp = this.columns.iter().zip(columns.into_iter()).fold(
json!({}),
|mut acc, (k, v)| {
acc[k] = v;
acc
},
);
let resp = match serde_json::from_value::<T>(resp) {
Ok(data) => data,
Err(e) => return Some(Err(Error::from(e))),
};
Some(Ok::<_, Error>(resp))
} else {
Some(Err(Error::KSQLStream(
"Expected to find a row of data, however found nothing".to_string(),
)))
}
})
}
}
#[derive(Deserialize)]
#[serde(rename_all(serialize = "snake_case", deserialize = "camelCase"))]
pub(crate) struct QueryResponse {
pub(crate) row: Option<Column>,
pub(crate) error_message: Option<String>,
pub(crate) final_message: Option<String>,
}
#[derive(Deserialize)]
pub(crate) struct Column {
pub(crate) columns: Vec<Value>,
}
}