Skip to main content

rtdb_rs/
lib.rs

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// ── Auth ──────────────────────────────────────────────────────────────────────
13
14#[derive(Serialize)]
15struct Claims {
16    iss: String,
17    scope: String,
18    aud: String,
19    exp: i64,
20    iat: i64,
21}
22
23/// Generate a signed JWT for Firebase service account authentication.
24/// Pass the RSA private key PEM string and the service account client email.
25pub 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
57/// Exchange a signed JWT for a Firebase OAuth2 access token.
58pub 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(&params)
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// ── Errors ────────────────────────────────────────────────────────────────────
91
92#[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// ── SSE Event ─────────────────────────────────────────────────────────────────
117
118/// An event received from a Firebase RTDB SSE stream.
119///
120/// Firebase streams four event types over an open HTTP connection.
121/// The first event after connecting is always a `Put` containing the full
122/// current value of the node. Subsequent events reflect changes as they happen.
123///
124/// # Example
125/// ```no_run
126/// # use rtdb_rs::{RtdbClient, RtdbEvent, RtdbError};
127/// # use futures_util::StreamExt;
128/// # async fn example() -> Result<(), RtdbError> {
129/// # let client = RtdbClient::new("https://my-project.firebaseio.com", "token");
130/// let mut stream = client.stream("users/alice").await?;
131/// tokio::pin!(stream);
132/// while let Some(event) = stream.next().await {
133///     match event? {
134///         RtdbEvent::Put { path, data }   => println!("put at {}: {}", path, data),
135///         RtdbEvent::Patch { path, data } => println!("patch at {}: {}", path, data),
136///         RtdbEvent::KeepAlive            => {}
137///         RtdbEvent::Cancel               => break,
138///     }
139/// }
140/// # Ok(()) }
141/// ```
142#[derive(Debug, Clone)]
143pub enum RtdbEvent {
144    /// Full node replaced. Fired once on connect with the current value,
145    /// then again whenever the node is overwritten via PUT.
146    Put { path: String, data: Value },
147
148    /// Specific fields updated. `data` contains only the changed fields,
149    /// not the full node. Fired when a PATCH is applied to the node.
150    Patch { path: String, data: Value },
151
152    /// Heartbeat sent by Firebase to keep the connection alive. Safe to ignore.
153    KeepAlive,
154
155    /// Stream cancelled — usually means the auth token was revoked or expired.
156    /// Stop listening and re-authenticate before reconnecting.
157    Cancel,
158}
159
160fn auth_query_name(token: &str) -> &'static str {
161    // Google OAuth2 access tokens usually start with "ya29".
162    // Firebase ID tokens are JWTs and should continue using "auth".
163    if token.starts_with("ya29.") || token.starts_with("ya29_") || token.starts_with("ya29-") {
164        "access_token"
165    } else {
166        "auth"
167    }
168}
169
170// ── SSE Parser ────────────────────────────────────────────────────────────────
171
172/// Parse a Firebase SSE `data:` payload into `(path, data)`.
173/// Firebase always sends `{"path": "...", "data": ...}`.
174fn 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// ── Query Builder Types ───────────────────────────────────────────────────────
189
190/// Controls how results are ordered.
191///
192/// Firebase requires `orderBy` to be set before using `limit_to_first`,
193/// `limit_to_last`, `start_at`, `end_at`, or `equal_to`.
194#[derive(Debug, Clone)]
195pub enum OrderBy {
196    /// Sort by Firebase push key. Equivalent to `orderBy="$key"`.
197    Key,
198    /// Sort by node value. Equivalent to `orderBy="$value"`.
199    /// Useful when nodes are primitives rather than objects.
200    Value,
201    /// Sort by Firebase priority. Equivalent to `orderBy="$priority"`.
202    Priority,
203    /// Sort by a child field. Equivalent to `orderBy="fieldName"`.
204    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/// A value used with `start_at`, `end_at`, and `equal_to` filters.
219///
220/// Firebase encodes filter values differently based on type:
221/// strings are JSON-quoted, numbers and booleans are bare.
222#[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
253// ── GetBuilder ────────────────────────────────────────────────────────────────
254
255/// A builder for filtered GET and SSE stream requests against the Firebase RTDB REST API.
256///
257/// Created via [`RtdbClient::query`]. Chain filter methods and call
258/// `.send().await` for a one-shot read or `.stream().await` for real-time events.
259///
260/// # Example
261/// ```no_run
262/// # use rtdb_rs::{RtdbClient, FilterValue, RtdbError};
263/// # async fn example() -> Result<(), RtdbError> {
264/// # let client = RtdbClient::new("https://my-project.firebaseio.com", "token");
265/// let results = client
266///     .query("orders")
267///     .order_by_child("status")
268///     .equal_to(FilterValue::string("pending"))
269///     .limit_to_first(25)
270///     .send()
271///     .await?;
272/// # Ok(()) }
273/// ```
274pub 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    /// Order results by a child field.
321    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    /// Order results by Firebase push key (`$key`).
327    pub fn order_by_key(mut self) -> Self {
328        self.order_by = Some(OrderBy::Key);
329        self
330    }
331
332    /// Order results by node value (`$value`).
333    pub fn order_by_value(mut self) -> Self {
334        self.order_by = Some(OrderBy::Value);
335        self
336    }
337
338    /// Set ordering explicitly via [`OrderBy`].
339    pub fn order_by(mut self, order: OrderBy) -> Self {
340        self.order_by = Some(order);
341        self
342    }
343
344    /// Return only the first `n` results (requires `order_by`).
345    /// Mutually exclusive with `limit_to_last`.
346    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    /// Return only the last `n` results (requires `order_by`).
353    /// Mutually exclusive with `limit_to_first`.
354    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    /// Filter to results where the ordered field is >= this value.
361    pub fn start_at(mut self, val: FilterValue) -> Self {
362        self.start_at = Some(val);
363        self
364    }
365
366    /// Filter to results where the ordered field is <= this value.
367    pub fn end_at(mut self, val: FilterValue) -> Self {
368        self.end_at = Some(val);
369        self
370    }
371
372    /// Filter to results where the ordered field exactly equals this value.
373    pub fn equal_to(mut self, val: FilterValue) -> Self {
374        self.equal_to = Some(val);
375        self
376    }
377
378    /// Return only keys, not values. Cannot be combined with other query params
379    /// or with `.stream()`.
380    pub fn shallow(mut self) -> Self {
381        self.shallow = true;
382        self
383    }
384
385    /// Build the request URL. Public for debugging — inspect this if a query
386    /// is not returning what you expect before calling `.send()` or `.stream()`.
387    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    /// Execute the query and return the matched data as a [`serde_json::Value`].
503    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    /// Open a real-time SSE stream at `path` and return an async `Stream` of
521    /// [`RtdbEvent`]s. The first event is always a `Put` containing the full
522    /// current value. Subsequent events reflect changes as they occur.
523    ///
524    /// All query params (`order_by_child`, `limit_to_last`, etc.) are supported
525    /// — Firebase will filter the stream to only push matching events.
526    /// `shallow` is not supported with streaming.
527    ///
528    /// The stream ends when dropped. Firebase may send a `Cancel` event if
529    /// the auth token expires — handle it by re-authenticating and reconnecting.
530    ///
531    /// # Example
532    /// ```no_run
533    /// # use rtdb_rs::{RtdbClient, RtdbEvent, FilterValue, RtdbError};
534    /// # use futures_util::StreamExt;
535    /// # async fn example() -> Result<(), RtdbError> {
536    /// # let client = RtdbClient::new("https://my-project.firebaseio.com", "token");
537    /// let mut stream = client
538    ///     .query("orders")
539    ///     .order_by_child("status")
540    ///     .equal_to(FilterValue::string("pending"))
541    ///     .stream()
542    ///     .await?;
543    /// tokio::pin!(stream);
544    /// while let Some(event) = stream.next().await {
545    ///     match event? {
546    ///         RtdbEvent::Put { path, data }   => println!("put at {}: {}", path, data),
547    ///         RtdbEvent::Patch { path, data } => println!("patch at {}: {}", path, data),
548    ///         RtdbEvent::KeepAlive            => {}
549    ///         RtdbEvent::Cancel               => break,
550    ///     }
551    /// }
552    /// # Ok(()) }
553    /// ```
554    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                // Process all complete lines in the buffer
614                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                        // Blank line = end of event block, dispatch
620                        if !current_event.is_empty() {
621                            match current_event.as_str() {
622                                "put" => {
623                                    match parse_sse_data(&current_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(&current_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                                    // Unknown event type — ignore rather than error
645                                    // Firebase may add new event types in future
646                                    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                    // Lines starting with ':' are SSE comments — ignore
658                }
659            }
660        };
661
662        Ok(s)
663    }
664}
665
666// ── RtdbClient ────────────────────────────────────────────────────────────────
667
668/// A reusable Firebase RTDB client.
669///
670/// Prefer this over the free functions — it reuses the underlying HTTP client
671/// and avoids passing `base_url` and `token` on every call.
672///
673/// # Example
674/// ```no_run
675/// # use rtdb_rs::{RtdbClient, RtdbError};
676/// # async fn example() -> Result<(), RtdbError> {
677/// let client = RtdbClient::new(
678///     "https://my-project.firebaseio.com",
679///     "your-oauth2-token",
680/// );
681///
682/// // Simple read
683/// let user = client.get("users/alice").await?;
684///
685/// // Filtered query
686/// let recent = client
687///     .query("logs")
688///     .order_by_child("timestamp")
689///     .limit_to_last(50)
690///     .send()
691///     .await?;
692/// # Ok(()) }
693/// ```
694pub 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    /// Create a new client. `base_url` is your project URL,
704    /// e.g. `https://my-project-default-rtdb.firebaseio.com`.
705    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    /// Replace the auth token. Call this when the OAuth2 token is refreshed.
716    /// Tokens expire after 1 hour.
717    pub fn with_token(mut self, token: impl Into<String>) -> Self {
718        self.token = token.into();
719        self
720    }
721
722    /// Set a persistent Firebase database namespace, such as the project ID
723    /// required by the local Realtime Database emulator.
724    pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
725        self.namespace = Some(namespace.into());
726        self
727    }
728
729    /// Add a persistent query parameter to every REST and SSE request.
730    ///
731    /// The name and value are URL-encoded. This is useful for Firebase
732    /// emulator parameters such as `auth_variable_override`, while remaining
733    /// general enough for other Firebase REST options.
734    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    /// Read a value at `path`. Returns `Value::Null` if the node is empty —
768    /// Firebase does not return HTTP 404 for missing nodes.
769    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    /// Start a filtered query at `path`. Chain filter methods, then call
800    /// `.send().await` for a one-shot read or `.stream().await` for real-time events.
801    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    /// Open a real-time SSE stream at `path`. Shorthand for `client.query(path).stream()`.
813    ///
814    /// Use `client.query(path).order_by_child(...).stream()` if you need filtering.
815    ///
816    /// # Example
817    /// ```no_run
818    /// # use rtdb_rs::{RtdbClient, RtdbEvent, RtdbError};
819    /// # use futures_util::StreamExt;
820    /// # async fn example() -> Result<(), RtdbError> {
821    /// # let client = RtdbClient::new("https://my-project.firebaseio.com", "token");
822    /// let mut stream = client.stream("users/alice").await?;
823    /// tokio::pin!(stream);
824    /// while let Some(event) = stream.next().await {
825    ///     match event? {
826    ///         RtdbEvent::Put { path, data }   => println!("put at {}: {}", path, data),
827    ///         RtdbEvent::Patch { path, data } => println!("patch at {}: {}", path, data),
828    ///         RtdbEvent::KeepAlive            => {}
829    ///         RtdbEvent::Cancel               => break,
830    ///     }
831    /// }
832    /// # Ok(()) }
833    /// ```
834    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    /// Overwrite the value at `path` (HTTP PUT).
842    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    /// Update specific fields at `path` without overwriting siblings (HTTP PATCH).
856    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    /// Append a new child node at `path` with a Firebase-generated push key (HTTP POST).
870    /// Returns the generated key as `{ "name": "-NxPushKey..." }`.
871    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    /// Delete the node at `path` (HTTP DELETE).
885    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// ── Types (optional helpers) ──────────────────────────────────────────────────
897
898/// A document returned by the Firebase RTDB REST API.
899///
900/// Note: these field types mirror a Firestore-style wire format and are
901/// provided as optional helpers. Firebase RTDB natively returns plain JSON —
902/// using [`serde_json::Value`] directly is often simpler.
903#[derive(Serialize, Deserialize, Debug, Clone)]
904pub struct RtdbDocument {
905    pub name: String,
906    pub fields: HashMap<String, RtdbFieldValue>,
907}
908
909/// A single field value in a structured document.
910#[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/// An array value in the RTDB REST wire format.
952#[derive(Serialize, Deserialize, Debug, Clone)]
953pub struct RtdbArrayValue {
954    pub values: Vec<RtdbFieldValue>,
955}
956
957// ── Free functions (backward compat) ─────────────────────────────────────────
958
959/// Read a value from Firebase RTDB at `path`.
960/// Consider using [`RtdbClient`] instead — it reuses the HTTP client.
961pub async fn get(base_url: &str, path: &str, token: &str) -> Result<Value, RtdbError> {
962    RtdbClient::new(base_url, token).get(path).await
963}
964
965/// Write (overwrite) a value at `path` using HTTP PUT.
966/// Consider using [`RtdbClient`] instead — it reuses the HTTP client.
967pub 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
976/// Update specific fields at `path` using HTTP PATCH.
977/// Consider using [`RtdbClient`] instead — it reuses the HTTP client.
978pub 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
987/// Delete the value at `path`.
988/// Consider using [`RtdbClient`] instead — it reuses the HTTP client.
989pub async fn delete(base_url: &str, path: &str, token: &str) -> Result<(), RtdbError> {
990    RtdbClient::new(base_url, token).delete(path).await
991}
992
993// ── Tests ─────────────────────────────────────────────────────────────────────
994
995#[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    // — RtdbFieldValue constructors —
1006
1007    #[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    // — OrderBy —
1030
1031    #[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    // — FilterValue —
1050
1051    #[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    // — GetBuilder URL construction —
1070
1071    #[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    // — SSE parser —
1156
1157    #[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        // Firebase sends null data when a node is deleted
1177        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        // shallow + stream() should return InvalidQuery
1199        // We test build_url here since stream() is async
1200        let result = make_builder("users").shallow().build_url();
1201        // shallow alone is valid for GET...
1202        assert!(result.is_ok());
1203        // ...but shallow + any filter is not
1204        let result2 = make_builder("users").shallow().order_by_key().build_url();
1205        assert!(matches!(result2, Err(RtdbError::InvalidQuery(_))));
1206    }
1207}