1use async_stream::stream;
2use chrono::{Duration, Utc};
3use futures_core::Stream;
4use futures_util::StreamExt;
5use jsonwebtoken::{encode, EncodingKey, Header};
6use reqwest::Client;
7use serde::{Deserialize, Serialize};
8use serde_json::Value;
9use std::collections::HashMap;
10use thiserror::Error;
11
12#[derive(Serialize)]
15struct Claims {
16 iss: String,
17 scope: String,
18 aud: String,
19 exp: i64,
20 iat: i64,
21}
22
23pub async fn generate_jwt(private_key: &str, client_email: &str) -> Result<String, RtdbError> {
26 let now = Utc::now();
27 let exp = now
28 .checked_add_signed(Duration::seconds(3600))
29 .expect("valid timestamp")
30 .timestamp();
31
32 let claims = Claims {
33 iss: client_email.to_string(),
34 scope: "https://www.googleapis.com/auth/firebase.database \
35 https://www.googleapis.com/auth/userinfo.email"
36 .to_string(),
37 aud: "https://oauth2.googleapis.com/token".to_string(),
38 exp,
39 iat: now.timestamp(),
40 };
41
42 let key = EncodingKey::from_rsa_pem(private_key.as_bytes())
43 .map_err(|e| RtdbError::Auth(e.to_string()))?;
44 let header = Header::new(jsonwebtoken::Algorithm::RS256);
45 let token = encode(&header, &claims, &key).map_err(|e| RtdbError::Auth(e.to_string()))?;
46
47 Ok(token)
48}
49
50#[derive(Deserialize)]
51struct AccessTokenResponse {
52 access_token: Option<String>,
53 error: Option<String>,
54 error_description: Option<String>,
55}
56
57pub async fn exchange_jwt_for_access_token(jwt: &str) -> Result<String, RtdbError> {
59 let client = Client::new();
60 let params = [
61 ("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"),
62 ("assertion", jwt),
63 ];
64
65 let response = client
66 .post("https://oauth2.googleapis.com/token")
67 .form(¶ms)
68 .send()
69 .await
70 .map_err(RtdbError::Request)?
71 .json::<AccessTokenResponse>()
72 .await
73 .map_err(RtdbError::Request)?;
74
75 if let Some(token) = response.access_token {
76 Ok(token)
77 } else if let Some(error) = response.error {
78 Err(RtdbError::Auth(format!(
79 "{}: {}",
80 error,
81 response.error_description.unwrap_or_default()
82 )))
83 } else {
84 Err(RtdbError::Auth(
85 "No access token or error in response".to_string(),
86 ))
87 }
88}
89
90#[derive(Debug, Error)]
93pub enum RtdbError {
94 #[error("HTTP request failed: {0}")]
95 Request(#[from] reqwest::Error),
96
97 #[error("HTTP status error {status}: {body}")]
98 Status {
99 status: reqwest::StatusCode,
100 body: String,
101 },
102
103 #[error("Authentication error: {0}")]
104 Auth(String),
105
106 #[error("Not found: {0}")]
107 NotFound(String),
108
109 #[error("Parse error: {0}")]
110 Parse(String),
111
112 #[error("Invalid query: {0}")]
113 InvalidQuery(String),
114}
115
116#[derive(Debug, Clone)]
143pub enum RtdbEvent {
144 Put { path: String, data: Value },
147
148 Patch { path: String, data: Value },
151
152 KeepAlive,
154
155 Cancel,
158}
159
160fn auth_query_name(token: &str) -> &'static str {
161 if token.starts_with("ya29.") || token.starts_with("ya29_") || token.starts_with("ya29-") {
164 "access_token"
165 } else {
166 "auth"
167 }
168}
169
170fn parse_sse_data(raw: &str) -> Result<(String, Value), RtdbError> {
175 let v: Value = serde_json::from_str(raw)
176 .map_err(|e| RtdbError::Parse(format!("invalid SSE payload: {}", e)))?;
177
178 let path = v["path"]
179 .as_str()
180 .ok_or_else(|| RtdbError::Parse("SSE payload missing 'path' field".to_string()))?
181 .to_string();
182
183 let data = v["data"].clone();
184
185 Ok((path, data))
186}
187
188#[derive(Debug, Clone)]
195pub enum OrderBy {
196 Key,
198 Value,
201 Priority,
203 Child(String),
205}
206
207impl OrderBy {
208 fn as_query_param(&self) -> String {
209 match self {
210 OrderBy::Key => "\"$key\"".to_string(),
211 OrderBy::Value => "\"$value\"".to_string(),
212 OrderBy::Priority => "\"$priority\"".to_string(),
213 OrderBy::Child(field) => format!("\"{}\"", field),
214 }
215 }
216}
217
218#[derive(Debug, Clone)]
223pub enum FilterValue {
224 String(String),
225 Number(f64),
226 Bool(bool),
227 Null,
228}
229
230impl FilterValue {
231 pub fn string(s: impl Into<String>) -> Self {
232 FilterValue::String(s.into())
233 }
234
235 pub fn number(n: f64) -> Self {
236 FilterValue::Number(n)
237 }
238
239 pub fn boolean(b: bool) -> Self {
240 FilterValue::Bool(b)
241 }
242
243 fn as_query_param(&self) -> String {
244 match self {
245 FilterValue::String(s) => format!("\"{}\"", s),
246 FilterValue::Number(n) => n.to_string(),
247 FilterValue::Bool(b) => b.to_string(),
248 FilterValue::Null => "null".to_string(),
249 }
250 }
251}
252
253pub struct GetBuilder<'a> {
275 client: &'a Client,
276 base_url: &'a str,
277 path: String,
278 token: &'a str,
279 namespace: Option<String>,
280 query_params: Vec<(String, String)>,
281 order_by: Option<OrderBy>,
282 limit_to_first: Option<u32>,
283 limit_to_last: Option<u32>,
284 start_at: Option<FilterValue>,
285 end_at: Option<FilterValue>,
286 equal_to: Option<FilterValue>,
287 shallow: bool,
288}
289
290impl<'a> GetBuilder<'a> {
291 pub fn new(client: &'a Client, base_url: &'a str, path: &str, token: &'a str) -> Self {
292 Self::new_with_options(client, base_url, path, token, None, &[])
293 }
294
295 fn new_with_options(
296 client: &'a Client,
297 base_url: &'a str,
298 path: &str,
299 token: &'a str,
300 namespace: Option<&str>,
301 query_params: &[(String, String)],
302 ) -> Self {
303 Self {
304 client,
305 base_url,
306 path: path.trim_matches('/').to_string(),
307 token,
308 namespace: namespace.map(str::to_owned),
309 query_params: query_params.to_vec(),
310 order_by: None,
311 limit_to_first: None,
312 limit_to_last: None,
313 start_at: None,
314 end_at: None,
315 equal_to: None,
316 shallow: false,
317 }
318 }
319
320 pub fn order_by_child(mut self, field: &str) -> Self {
322 self.order_by = Some(OrderBy::Child(field.to_string()));
323 self
324 }
325
326 pub fn order_by_key(mut self) -> Self {
328 self.order_by = Some(OrderBy::Key);
329 self
330 }
331
332 pub fn order_by_value(mut self) -> Self {
334 self.order_by = Some(OrderBy::Value);
335 self
336 }
337
338 pub fn order_by(mut self, order: OrderBy) -> Self {
340 self.order_by = Some(order);
341 self
342 }
343
344 pub fn limit_to_first(mut self, n: u32) -> Self {
347 self.limit_to_first = Some(n);
348 self.limit_to_last = None;
349 self
350 }
351
352 pub fn limit_to_last(mut self, n: u32) -> Self {
355 self.limit_to_last = Some(n);
356 self.limit_to_first = None;
357 self
358 }
359
360 pub fn start_at(mut self, val: FilterValue) -> Self {
362 self.start_at = Some(val);
363 self
364 }
365
366 pub fn end_at(mut self, val: FilterValue) -> Self {
368 self.end_at = Some(val);
369 self
370 }
371
372 pub fn equal_to(mut self, val: FilterValue) -> Self {
374 self.equal_to = Some(val);
375 self
376 }
377
378 pub fn shallow(mut self) -> Self {
381 self.shallow = true;
382 self
383 }
384
385 pub fn build_url(&self) -> Result<String, RtdbError> {
388 if self.shallow {
389 let has_filters = self.order_by.is_some()
390 || self.limit_to_first.is_some()
391 || self.limit_to_last.is_some()
392 || self.start_at.is_some()
393 || self.end_at.is_some()
394 || self.equal_to.is_some();
395
396 if has_filters {
397 return Err(RtdbError::InvalidQuery(
398 "shallow=true cannot be combined with orderBy, limit, or filter params"
399 .to_string(),
400 ));
401 }
402
403 let auth_name = auth_query_name(self.token);
404
405 let mut params = Vec::new();
406 if let Some(namespace) = &self.namespace {
407 params.push(format!("ns={}", urlencoding::encode(namespace)));
408 }
409 params.extend(self.query_params.iter().map(|(name, value)| {
410 format!(
411 "{}={}",
412 urlencoding::encode(name),
413 urlencoding::encode(value)
414 )
415 }));
416 if !self.token.is_empty() {
417 params.push(format!("{}={}", auth_name, urlencoding::encode(self.token)));
418 }
419 params.push("shallow=true".to_string());
420 return Ok(format!(
421 "{}/{}.json?{}",
422 self.base_url,
423 self.path,
424 params.join("&")
425 ));
426 }
427
428 let needs_order = self.limit_to_first.is_some()
429 || self.limit_to_last.is_some()
430 || self.start_at.is_some()
431 || self.end_at.is_some()
432 || self.equal_to.is_some();
433
434 if needs_order && self.order_by.is_none() {
435 return Err(RtdbError::InvalidQuery(
436 "limit_to_first, limit_to_last, start_at, end_at, and equal_to all require order_by"
437 .to_string(),
438 ));
439 }
440
441 let auth_name = auth_query_name(self.token);
442
443 let mut params = Vec::new();
444 if let Some(namespace) = &self.namespace {
445 params.push(format!("ns={}", urlencoding::encode(namespace)));
446 }
447 params.extend(self.query_params.iter().map(|(name, value)| {
448 format!(
449 "{}={}",
450 urlencoding::encode(name),
451 urlencoding::encode(value)
452 )
453 }));
454 if !self.token.is_empty() {
455 params.push(format!("{}={}", auth_name, urlencoding::encode(self.token)));
456 }
457
458 if let Some(ref order) = self.order_by {
459 params.push(format!(
460 "orderBy={}",
461 urlencoding::encode(&order.as_query_param())
462 ));
463 }
464
465 if let Some(n) = self.limit_to_first {
466 params.push(format!("limitToFirst={}", n));
467 }
468
469 if let Some(n) = self.limit_to_last {
470 params.push(format!("limitToLast={}", n));
471 }
472
473 if let Some(ref val) = self.start_at {
474 params.push(format!(
475 "startAt={}",
476 urlencoding::encode(&val.as_query_param())
477 ));
478 }
479
480 if let Some(ref val) = self.end_at {
481 params.push(format!(
482 "endAt={}",
483 urlencoding::encode(&val.as_query_param())
484 ));
485 }
486
487 if let Some(ref val) = self.equal_to {
488 params.push(format!(
489 "equalTo={}",
490 urlencoding::encode(&val.as_query_param())
491 ));
492 }
493
494 Ok(format!(
495 "{}/{}.json?{}",
496 self.base_url,
497 self.path,
498 params.join("&")
499 ))
500 }
501
502 pub async fn send(self) -> Result<Value, RtdbError> {
504 let url = self.build_url()?;
505
506 let response = self
507 .client
508 .get(&url)
509 .send()
510 .await
511 .map_err(RtdbError::Request)?;
512
513 if response.status() == reqwest::StatusCode::NOT_FOUND {
514 return Err(RtdbError::NotFound(self.path));
515 }
516
517 response.json::<Value>().await.map_err(RtdbError::Request)
518 }
519
520 pub async fn stream(
555 self,
556 ) -> Result<impl Stream<Item = Result<RtdbEvent, RtdbError>>, RtdbError> {
557 if self.shallow {
558 return Err(RtdbError::InvalidQuery(
559 "shallow cannot be used with stream() — streaming requires full node data"
560 .to_string(),
561 ));
562 }
563
564 let url = self.build_url()?;
565 let path = self.path.clone();
566
567 let response = self
568 .client
569 .get(&url)
570 .header("Accept", "text/event-stream")
571 .header("Cache-Control", "no-cache")
572 .send()
573 .await
574 .map_err(RtdbError::Request)?;
575
576 if response.status() == reqwest::StatusCode::NOT_FOUND {
577 return Err(RtdbError::NotFound(path));
578 }
579
580 if response.status() == reqwest::StatusCode::UNAUTHORIZED {
581 return Err(RtdbError::Auth(
582 "unauthorized — check your token".to_string(),
583 ));
584 }
585
586 let s = stream! {
587 let mut bytes_stream = response.bytes_stream();
588 let mut buffer = String::new();
589 let mut current_event = String::new();
590 let mut current_data = String::new();
591
592 while let Some(chunk) = bytes_stream.next().await {
593 let chunk = match chunk {
594 Ok(c) => c,
595 Err(e) => {
596 yield Err(RtdbError::Request(e));
597 return;
598 }
599 };
600
601 let text = match std::str::from_utf8(&chunk) {
602 Ok(t) => t.to_string(),
603 Err(_) => {
604 yield Err(RtdbError::Parse(
605 "invalid UTF-8 in SSE stream".to_string(),
606 ));
607 return;
608 }
609 };
610
611 buffer.push_str(&text);
612
613 while let Some(pos) = buffer.find('\n') {
615 let line = buffer[..pos].trim_end_matches('\r').to_string();
616 buffer = buffer[pos + 1..].to_string();
617
618 if line.is_empty() {
619 if !current_event.is_empty() {
621 match current_event.as_str() {
622 "put" => {
623 match parse_sse_data(¤t_data) {
624 Ok((path, data)) => {
625 yield Ok(RtdbEvent::Put { path, data })
626 }
627 Err(e) => yield Err(e),
628 }
629 }
630 "patch" => {
631 match parse_sse_data(¤t_data) {
632 Ok((path, data)) => {
633 yield Ok(RtdbEvent::Patch { path, data })
634 }
635 Err(e) => yield Err(e),
636 }
637 }
638 "keep-alive" => yield Ok(RtdbEvent::KeepAlive),
639 "cancel" => {
640 yield Ok(RtdbEvent::Cancel);
641 return;
642 }
643 other => {
644 let _ = other;
647 }
648 }
649 }
650 current_event.clear();
651 current_data.clear();
652 } else if let Some(rest) = line.strip_prefix("event:") {
653 current_event = rest.trim().to_string();
654 } else if let Some(rest) = line.strip_prefix("data:") {
655 current_data = rest.trim().to_string();
656 }
657 }
659 }
660 };
661
662 Ok(s)
663 }
664}
665
666pub struct RtdbClient {
695 base_url: String,
696 token: String,
697 namespace: Option<String>,
698 query_params: Vec<(String, String)>,
699 client: Client,
700}
701
702impl RtdbClient {
703 pub fn new(base_url: impl Into<String>, token: impl Into<String>) -> Self {
706 Self {
707 base_url: base_url.into().trim_end_matches('/').to_string(),
708 token: token.into(),
709 namespace: None,
710 query_params: Vec::new(),
711 client: Client::new(),
712 }
713 }
714
715 pub fn with_token(mut self, token: impl Into<String>) -> Self {
718 self.token = token.into();
719 self
720 }
721
722 pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
725 self.namespace = Some(namespace.into());
726 self
727 }
728
729 pub fn with_query_param(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
735 self.query_params.push((name.into(), value.into()));
736 self
737 }
738
739 fn url(&self, path: &str) -> String {
740 let auth_name = auth_query_name(&self.token);
741 let mut params = Vec::new();
742 if let Some(namespace) = &self.namespace {
743 params.push(format!("ns={}", urlencoding::encode(namespace)));
744 }
745 params.extend(self.query_params.iter().map(|(name, value)| {
746 format!(
747 "{}={}",
748 urlencoding::encode(name),
749 urlencoding::encode(value)
750 )
751 }));
752 if !self.token.is_empty() {
753 params.push(format!(
754 "{}={}",
755 auth_name,
756 urlencoding::encode(&self.token)
757 ));
758 }
759 format!(
760 "{}/{}.json?{}",
761 self.base_url,
762 path.trim_matches('/'),
763 params.join("&")
764 )
765 }
766
767 pub async fn get(&self, path: &str) -> Result<Value, RtdbError> {
770 let url = self.url(path);
771
772 let response = self
773 .client
774 .get(&url)
775 .send()
776 .await
777 .map_err(RtdbError::Request)?;
778
779 if response.status() == reqwest::StatusCode::NOT_FOUND {
780 return Err(RtdbError::NotFound(path.to_string()));
781 }
782
783 if response.status() == reqwest::StatusCode::UNAUTHORIZED {
784 return Err(RtdbError::Auth(
785 "unauthorized — check your token".to_string(),
786 ));
787 }
788
789 if !response.status().is_success() {
790 let status = response.status();
791 let body = response.text().await.unwrap_or_default();
792
793 return Err(RtdbError::Status { status, body });
794 }
795
796 response.json::<Value>().await.map_err(RtdbError::Request)
797 }
798
799 pub fn query(&self, path: &str) -> GetBuilder<'_> {
802 GetBuilder::new_with_options(
803 &self.client,
804 &self.base_url,
805 path,
806 &self.token,
807 self.namespace.as_deref(),
808 &self.query_params,
809 )
810 }
811
812 pub async fn stream(
835 &self,
836 path: &str,
837 ) -> Result<impl Stream<Item = Result<RtdbEvent, RtdbError>>, RtdbError> {
838 self.query(path).stream().await
839 }
840
841 pub async fn put(&self, path: &str, body: &Value) -> Result<Value, RtdbError> {
843 let url = self.url(path);
844 self.client
845 .put(&url)
846 .json(body)
847 .send()
848 .await
849 .map_err(RtdbError::Request)?
850 .json::<Value>()
851 .await
852 .map_err(RtdbError::Request)
853 }
854
855 pub async fn patch(&self, path: &str, body: &Value) -> Result<Value, RtdbError> {
857 let url = self.url(path);
858 self.client
859 .patch(&url)
860 .json(body)
861 .send()
862 .await
863 .map_err(RtdbError::Request)?
864 .json::<Value>()
865 .await
866 .map_err(RtdbError::Request)
867 }
868
869 pub async fn post(&self, path: &str, body: &Value) -> Result<Value, RtdbError> {
872 let url = self.url(path);
873 self.client
874 .post(&url)
875 .json(body)
876 .send()
877 .await
878 .map_err(RtdbError::Request)?
879 .json::<Value>()
880 .await
881 .map_err(RtdbError::Request)
882 }
883
884 pub async fn delete(&self, path: &str) -> Result<(), RtdbError> {
886 let url = self.url(path);
887 self.client
888 .delete(&url)
889 .send()
890 .await
891 .map_err(RtdbError::Request)?;
892 Ok(())
893 }
894}
895
896#[derive(Serialize, Deserialize, Debug, Clone)]
904pub struct RtdbDocument {
905 pub name: String,
906 pub fields: HashMap<String, RtdbFieldValue>,
907}
908
909#[derive(Serialize, Deserialize, Debug, Clone)]
911pub struct RtdbFieldValue {
912 pub string_value: Option<String>,
913 pub integer_value: Option<i64>,
914 pub boolean_value: Option<bool>,
915 pub array_value: Option<RtdbArrayValue>,
916 pub map_value: Option<HashMap<String, RtdbFieldValue>>,
917}
918
919impl RtdbFieldValue {
920 pub fn string(value: impl Into<String>) -> Self {
921 Self {
922 string_value: Some(value.into()),
923 integer_value: None,
924 boolean_value: None,
925 array_value: None,
926 map_value: None,
927 }
928 }
929
930 pub fn integer(value: i64) -> Self {
931 Self {
932 string_value: None,
933 integer_value: Some(value),
934 boolean_value: None,
935 array_value: None,
936 map_value: None,
937 }
938 }
939
940 pub fn boolean(value: bool) -> Self {
941 Self {
942 string_value: None,
943 integer_value: None,
944 boolean_value: Some(value),
945 array_value: None,
946 map_value: None,
947 }
948 }
949}
950
951#[derive(Serialize, Deserialize, Debug, Clone)]
953pub struct RtdbArrayValue {
954 pub values: Vec<RtdbFieldValue>,
955}
956
957pub async fn get(base_url: &str, path: &str, token: &str) -> Result<Value, RtdbError> {
962 RtdbClient::new(base_url, token).get(path).await
963}
964
965pub async fn put(
968 base_url: &str,
969 path: &str,
970 token: &str,
971 body: &Value,
972) -> Result<Value, RtdbError> {
973 RtdbClient::new(base_url, token).put(path, body).await
974}
975
976pub async fn patch(
979 base_url: &str,
980 path: &str,
981 token: &str,
982 body: &Value,
983) -> Result<Value, RtdbError> {
984 RtdbClient::new(base_url, token).patch(path, body).await
985}
986
987pub async fn delete(base_url: &str, path: &str, token: &str) -> Result<(), RtdbError> {
990 RtdbClient::new(base_url, token).delete(path).await
991}
992
993#[cfg(test)]
996mod tests {
997 use super::*;
998
999 fn make_builder(path: &str) -> GetBuilder<'static> {
1000 static CLIENT: std::sync::OnceLock<Client> = std::sync::OnceLock::new();
1001 let client = CLIENT.get_or_init(Client::new);
1002 GetBuilder::new(client, "https://test.firebaseio.com", path, "test-token")
1003 }
1004
1005 #[test]
1008 fn string_field_value() {
1009 let v = RtdbFieldValue::string("hello");
1010 assert_eq!(v.string_value, Some("hello".to_string()));
1011 assert!(v.integer_value.is_none());
1012 assert!(v.boolean_value.is_none());
1013 }
1014
1015 #[test]
1016 fn integer_field_value() {
1017 let v = RtdbFieldValue::integer(42);
1018 assert_eq!(v.integer_value, Some(42));
1019 assert!(v.string_value.is_none());
1020 }
1021
1022 #[test]
1023 fn boolean_field_value() {
1024 let v = RtdbFieldValue::boolean(true);
1025 assert_eq!(v.boolean_value, Some(true));
1026 assert!(v.string_value.is_none());
1027 }
1028
1029 #[test]
1032 fn order_by_key_param() {
1033 assert_eq!(OrderBy::Key.as_query_param(), "\"$key\"");
1034 }
1035
1036 #[test]
1037 fn order_by_value_param() {
1038 assert_eq!(OrderBy::Value.as_query_param(), "\"$value\"");
1039 }
1040
1041 #[test]
1042 fn order_by_child_param() {
1043 assert_eq!(
1044 OrderBy::Child("created_at".to_string()).as_query_param(),
1045 "\"created_at\""
1046 );
1047 }
1048
1049 #[test]
1052 fn filter_value_string_is_quoted() {
1053 let v = FilterValue::string("pending");
1054 assert_eq!(v.as_query_param(), "\"pending\"");
1055 }
1056
1057 #[test]
1058 fn filter_value_number_is_bare() {
1059 let v = FilterValue::number(42.0);
1060 assert_eq!(v.as_query_param(), "42");
1061 }
1062
1063 #[test]
1064 fn filter_value_bool_is_bare() {
1065 let v = FilterValue::boolean(true);
1066 assert_eq!(v.as_query_param(), "true");
1067 }
1068
1069 #[test]
1072 fn url_simple_get() {
1073 let url = make_builder("users/alice").build_url().unwrap();
1074 assert_eq!(
1075 url,
1076 "https://test.firebaseio.com/users/alice.json?auth=test-token"
1077 );
1078 }
1079
1080 #[test]
1081 fn empty_auth_is_omitted_and_extra_params_are_encoded() {
1082 let client = RtdbClient::new("http://127.0.0.1:9000", "")
1083 .with_namespace("demo-rtdb-typed")
1084 .with_query_param("print", "hello world");
1085 let url = client.query("users").build_url().unwrap();
1086 assert_eq!(
1087 url,
1088 "http://127.0.0.1:9000/users.json?ns=demo-rtdb-typed&print=hello%20world"
1089 );
1090 }
1091
1092 #[test]
1093 fn url_with_order_and_limit() {
1094 let url = make_builder("orders")
1095 .order_by_child("status")
1096 .limit_to_last(10)
1097 .build_url()
1098 .unwrap();
1099
1100 assert!(url.contains("orderBy=%22status%22"));
1101 assert!(url.contains("limitToLast=10"));
1102 assert!(!url.contains("limitToFirst"));
1103 }
1104
1105 #[test]
1106 fn url_limit_to_first_clears_limit_to_last() {
1107 let url = make_builder("orders")
1108 .order_by_key()
1109 .limit_to_last(5)
1110 .limit_to_first(10)
1111 .build_url()
1112 .unwrap();
1113 assert!(url.contains("limitToFirst=10"));
1114 assert!(!url.contains("limitToLast"));
1115 }
1116
1117 #[test]
1118 fn url_equal_to_string_is_quoted() {
1119 let url = make_builder("jobs")
1120 .order_by_child("status")
1121 .equal_to(FilterValue::string("active"))
1122 .build_url()
1123 .unwrap();
1124
1125 assert!(url.contains("equalTo=%22active%22"));
1126 }
1127
1128 #[test]
1129 fn url_shallow() {
1130 let url = make_builder("users").shallow().build_url().unwrap();
1131 assert!(url.contains("shallow=true"));
1132 assert!(!url.contains("orderBy"));
1133 }
1134
1135 #[test]
1136 fn shallow_with_order_by_is_error() {
1137 let result = make_builder("users").order_by_key().shallow().build_url();
1138 assert!(matches!(result, Err(RtdbError::InvalidQuery(_))));
1139 }
1140
1141 #[test]
1142 fn limit_without_order_by_is_error() {
1143 let result = make_builder("users").limit_to_first(10).build_url();
1144 assert!(matches!(result, Err(RtdbError::InvalidQuery(_))));
1145 }
1146
1147 #[test]
1148 fn start_at_without_order_by_is_error() {
1149 let result = make_builder("users")
1150 .start_at(FilterValue::string("alice"))
1151 .build_url();
1152 assert!(matches!(result, Err(RtdbError::InvalidQuery(_))));
1153 }
1154
1155 #[test]
1158 fn parse_sse_data_valid() {
1159 let raw = r#"{"path":"/users/alice","data":{"name":"Alice","score":95}}"#;
1160 let (path, data) = parse_sse_data(raw).unwrap();
1161 assert_eq!(path, "/users/alice");
1162 assert_eq!(data["name"], "Alice");
1163 assert_eq!(data["score"], 95);
1164 }
1165
1166 #[test]
1167 fn parse_sse_data_root_path() {
1168 let raw = r#"{"path":"/","data":{"a":1,"b":2}}"#;
1169 let (path, data) = parse_sse_data(raw).unwrap();
1170 assert_eq!(path, "/");
1171 assert_eq!(data["a"], 1);
1172 }
1173
1174 #[test]
1175 fn parse_sse_data_null_data() {
1176 let raw = r#"{"path":"/users/alice","data":null}"#;
1178 let (path, data) = parse_sse_data(raw).unwrap();
1179 assert_eq!(path, "/users/alice");
1180 assert!(data.is_null());
1181 }
1182
1183 #[test]
1184 fn parse_sse_data_missing_path_is_error() {
1185 let raw = r#"{"data":{"name":"Alice"}}"#;
1186 let result = parse_sse_data(raw);
1187 assert!(matches!(result, Err(RtdbError::Parse(_))));
1188 }
1189
1190 #[test]
1191 fn parse_sse_data_invalid_json_is_error() {
1192 let result = parse_sse_data("not json at all");
1193 assert!(matches!(result, Err(RtdbError::Parse(_))));
1194 }
1195
1196 #[test]
1197 fn shallow_stream_is_error() {
1198 let result = make_builder("users").shallow().build_url();
1201 assert!(result.is_ok());
1203 let result2 = make_builder("users").shallow().order_by_key().build_url();
1205 assert!(matches!(result2, Err(RtdbError::InvalidQuery(_))));
1206 }
1207}