openrtc 0.2.1

OpenRTC: a Rust-first P2P runtime for device discovery, signaling, and iroh/QUIC networking.
Documentation
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
//! WebChannel protocol client for Firestore Listen.
//!
//! Implements Google's WebChannel framing protocol to stream real-time document
//! changes from Firestore. Works on both native (reqwest) and WASM (web-sys fetch).

use crate::logging::log_warn;
use anyhow::{Context, Result};
use std::sync::{Arc, Mutex};

/// Percent-encode a string for use in URL query parameters.
fn url_encode(s: &str) -> String {
    s.bytes()
        .flat_map(|b| match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                vec![b as char]
            }
            _ => format!("%{:02X}", b).chars().collect::<Vec<_>>(),
        })
        .collect()
}

/// Percent-encode for form body values (space → +, others → %XX).
fn form_encode(s: &str) -> String {
    s.bytes()
        .flat_map(|b| match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'*' => {
                vec![b as char]
            }
            b' ' => vec!['+'],
            _ => format!("%{:02X}", b).chars().collect::<Vec<_>>(),
        })
        .collect()
}

const WEBCHANNEL_BASE_PROD: &str =
    "https://firestore.googleapis.com/google.firestore.v1.Firestore/Listen/channel";

#[cfg(target_arch = "wasm32")]
fn wasm_global_string(key: &str) -> Option<String> {
    let global = js_sys::global();
    js_sys::Reflect::get(&global, &wasm_bindgen::JsValue::from_str(key))
        .ok()
        .and_then(|v| v.as_string())
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
}

fn webchannel_base() -> String {
    #[cfg(target_arch = "wasm32")]
    {
        if let Some(host) = wasm_global_string("__OPENRTC_FIRESTORE_EMULATOR_HOST__") {
            return format!(
                "http://{}/google.firestore.v1.Firestore/Listen/channel",
                host
            );
        }
    }
    if let Ok(host) = std::env::var("OPENRTC_FIRESTORE_EMULATOR_HOST") {
        let host = host.trim();
        if !host.is_empty() {
            return format!(
                "http://{}/google.firestore.v1.Firestore/Listen/channel",
                host
            );
        }
    }
    WEBCHANNEL_BASE_PROD.to_string()
}
const WEBCHANNEL_VERSION: u8 = 8;
const WEBCHANNEL_CVER: u8 = 22;

/// Events emitted by the Firestore Listen stream.
#[derive(Debug, Clone)]
pub(crate) enum ListenEvent {
    DocumentChange {
        document: serde_json::Value,
        /// Required by the WebChannel wire format even though the current device
        /// listener only tracks a single target and does not read per-target IDs.
        #[allow(dead_code)]
        target_ids: Vec<i32>,
    },
    DocumentDelete {
        document_path: String,
        /// Required by the WebChannel wire format even though remove handling
        /// only needs the document path for the current listener implementation.
        #[allow(dead_code)]
        target_ids: Vec<i32>,
    },
    DocumentRemove {
        document_path: String,
        /// Required by the WebChannel wire format even though remove handling
        /// only needs the document path for the current listener implementation.
        #[allow(dead_code)]
        target_ids: Vec<i32>,
    },
    TargetChange {
        target_change_type: String,
        target_ids: Vec<i32>,
        resume_token: Option<String>,
        cause: Option<ListenError>,
    },
    Filter {
        /// Required by the WebChannel wire format; retained so filter frames can
        /// be decoded without losing protocol fidelity.
        #[allow(dead_code)]
        target_id: i32,
        /// Required by the WebChannel wire format; retained so filter frames can
        /// be decoded without losing protocol fidelity.
        #[allow(dead_code)]
        count: i32,
    },
}

#[derive(Debug, Clone)]
pub(crate) struct ListenError {
    pub code: i32,
    pub message: String,
}

/// Active WebChannel session state.
pub(crate) struct WebChannelSession {
    sid: String,
    gsession_id: String,
    next_rid: u32,
    last_aid: i64,
    backward_channel_counter: u32,
}

impl WebChannelSession {
    pub(crate) fn short_sid(&self) -> String {
        format!(
            "{}...{}",
            &self.sid[..self.sid.len().min(4)],
            &self.sid[self.sid.len().saturating_sub(4)..]
        )
    }
}

/// WebChannel client for Firestore Listen.
pub(crate) struct WebChannelClient {
    project_id: String,
    database_path: String,
    token_provider: Arc<Mutex<Box<dyn Fn() -> Option<String> + Send + Sync>>>,
    #[cfg(not(target_arch = "wasm32"))]
    http: reqwest::Client,
}

impl WebChannelClient {
    pub fn new(
        project_id: String,
        token_provider: Arc<Mutex<Box<dyn Fn() -> Option<String> + Send + Sync>>>,
    ) -> Self {
        let database_path = format!("projects/{}/databases/(default)", project_id);
        Self {
            project_id,
            database_path,
            token_provider,
            #[cfg(not(target_arch = "wasm32"))]
            http: reqwest::Client::new(),
        }
    }

    fn get_token(&self) -> Option<String> {
        match self.token_provider.lock() {
            Ok(provider) => (provider)(),
            Err(poisoned) => {
                log_warn("[WebChannel] token provider mutex poisoned; recovering inner provider");
                (poisoned.into_inner())()
            }
        }
    }

    fn encoded_database(&self) -> String {
        url_encode(&self.database_path)
    }

    /// Create a new WebChannel session (handshake).
    pub async fn create_session(&self) -> Result<WebChannelSession> {
        let url = format!(
            "{}?VER={}&database={}&RID=0&CVER={}&X-HTTP-Session-Id=gsessionid",
            &webchannel_base(),
            WEBCHANNEL_VERSION,
            self.encoded_database(),
            WEBCHANNEL_CVER,
        );

        let body = "count=0";
        let (response_text, gsession_id) = self.post_form(&url, body).await?;

        // Parse: [[0,["c","<SID>","",8,14,30000]]]
        let parsed: serde_json::Value = serde_json::from_str(&response_text)
            .with_context(|| format!("Failed to parse handshake response: {}", response_text))?;

        let sid = parsed
            .as_array()
            .and_then(|arr| arr.first())
            .and_then(|item| item.as_array())
            .and_then(|pair| pair.get(1))
            .and_then(|data| data.as_array())
            .and_then(|data| data.get(1))
            .and_then(|sid| sid.as_str())
            .context("Missing SID in handshake response")?
            .to_string();

        Ok(WebChannelSession {
            sid,
            gsession_id,
            next_rid: 1,
            last_aid: 0,
            backward_channel_counter: 0,
        })
    }

    /// Send an addTarget request through the forward channel.
    pub async fn add_target(
        &self,
        session: &mut WebChannelSession,
        target_id: i32,
        parent_path: &str,
        collection_id: &str,
        resume_token: Option<&str>,
    ) -> Result<()> {
        let mut listen_req = serde_json::json!({
            "database": self.database_path,
            "addTarget": {
                "query": {
                    "parent": format!(
                        "projects/{}/databases/(default)/documents/{}",
                        self.project_id, parent_path
                    ),
                    "structuredQuery": {
                        "from": [{"collectionId": collection_id}]
                    }
                },
                "targetId": target_id
            }
        });

        if let Some(token) = resume_token {
            listen_req["addTarget"]["resumeToken"] = serde_json::Value::String(token.to_string());
        }

        self.send_forward(session, &listen_req).await
    }

    /// Send a removeTarget request through the forward channel.
    /// Required for full WebChannel protocol coverage even though the current
    /// listener lifecycle relies on session teardown instead of explicit removal.
    #[allow(dead_code)]
    pub async fn remove_target(
        &self,
        session: &mut WebChannelSession,
        target_id: i32,
    ) -> Result<()> {
        let listen_req = serde_json::json!({
            "database": self.database_path,
            "removeTarget": target_id
        });

        self.send_forward(session, &listen_req).await
    }

    /// Poll the backward channel for events. Blocks until events arrive or timeout.
    pub async fn poll_backward(&self, session: &mut WebChannelSession) -> Result<Vec<ListenEvent>> {
        let url = format!(
            "{}?VER={}&database={}&gsessionid={}&SID={}&RID=rpc&AID={}&CI=0&TYPE=xmlhttp&t={}",
            &webchannel_base(),
            WEBCHANNEL_VERSION,
            self.encoded_database(),
            url_encode(&session.gsession_id),
            url_encode(&session.sid),
            session.last_aid,
            session.backward_channel_counter,
        );
        session.backward_channel_counter += 1;

        #[cfg(not(target_arch = "wasm32"))]
        let frames = {
            let response_text = self.get_with_auth(&url).await?;
            parse_framed_response(&response_text)?
        };

        #[cfg(target_arch = "wasm32")]
        let frames = self.get_streaming_frames_with_auth(&url).await?;

        let mut events = Vec::new();

        for (aid, messages) in frames {
            if aid > session.last_aid {
                session.last_aid = aid;
            }
            for msg in messages {
                if let Some(event) = parse_listen_event(&msg) {
                    events.push(event);
                }
            }
        }

        Ok(events)
    }

    /// Send a message through the forward channel.
    async fn send_forward(
        &self,
        session: &mut WebChannelSession,
        data: &serde_json::Value,
    ) -> Result<()> {
        let url = format!(
            "{}?VER={}&database={}&gsessionid={}&SID={}&RID={}&AID={}&CI=0",
            &webchannel_base(),
            WEBCHANNEL_VERSION,
            self.encoded_database(),
            url_encode(&session.gsession_id),
            url_encode(&session.sid),
            session.next_rid,
            session.last_aid,
        );
        session.next_rid += 1;

        let data_str = serde_json::to_string(data)?;
        let body = format!("count=1&ofs=0&req0___data__={}", form_encode(&data_str));

        let (response_text, _) = self.post_form(&url, &body).await?;
        if let Ok(frames) = parse_framed_response(&response_text) {
            for (aid, _) in frames {
                if aid > session.last_aid {
                    session.last_aid = aid;
                }
            }
        }
        Ok(())
    }

    // ── Platform-specific HTTP methods ──────────────────────────────────

    #[cfg(not(target_arch = "wasm32"))]
    async fn post_form(&self, url: &str, body: &str) -> Result<(String, String)> {
        let mut req = self
            .http
            .post(url)
            .header("Content-Type", "application/x-www-form-urlencoded")
            .body(body.to_string());

        if let Some(token) = self.get_token() {
            req = req.header("Authorization", format!("Bearer {}", token));
        }

        let res = req.send().await.context("WebChannel POST failed")?;

        let gsession_id = res
            .headers()
            .get("x-http-session-id")
            .and_then(|v| v.to_str().ok())
            .unwrap_or("")
            .to_string();

        if !res.status().is_success() {
            let status = res.status();
            let text = res.text().await.unwrap_or_default();
            anyhow::bail!("WebChannel POST {} returned {}: {}", url, status, text);
        }

        let text = res.text().await.context("Failed to read POST response")?;
        // Strip length prefix if present
        let stripped = strip_length_prefix(&text);
        Ok((stripped.to_string(), gsession_id))
    }

    #[cfg(target_arch = "wasm32")]
    async fn post_form(&self, url: &str, body: &str) -> Result<(String, String)> {
        use wasm_bindgen::JsCast;
        use wasm_bindgen_futures::JsFuture;

        let opts = web_sys::RequestInit::new();
        opts.set_method("POST");
        opts.set_body(&wasm_bindgen::JsValue::from_str(body));

        let headers =
            web_sys::Headers::new().map_err(|e| anyhow::anyhow!("Headers::new failed: {:?}", e))?;
        headers
            .set("Content-Type", "application/x-www-form-urlencoded")
            .map_err(|e| anyhow::anyhow!("headers.set failed: {:?}", e))?;

        if let Some(token) = self.get_token() {
            headers
                .set("Authorization", &format!("Bearer {}", token))
                .map_err(|e| anyhow::anyhow!("headers.set auth failed: {:?}", e))?;
        }

        opts.set_headers(&headers);

        let request = web_sys::Request::new_with_str_and_init(url, &opts)
            .map_err(|e| anyhow::anyhow!("Request::new failed: {:?}", e))?;

        let window = web_sys::window().context("no window")?;
        let resp_value = JsFuture::from(window.fetch_with_request(&request))
            .await
            .map_err(|e| anyhow::anyhow!("fetch failed: {:?}", e))?;

        let resp: web_sys::Response = resp_value
            .dyn_into()
            .map_err(|_| anyhow::anyhow!("response is not a Response"))?;

        let gsession_id = resp
            .headers()
            .get("x-http-session-id")
            .ok()
            .flatten()
            .unwrap_or_default();

        if !resp.ok() {
            let text = JsFuture::from(
                resp.text()
                    .map_err(|e| anyhow::anyhow!("text() failed: {:?}", e))?,
            )
            .await
            .map_err(|e| anyhow::anyhow!("text await failed: {:?}", e))?
            .as_string()
            .unwrap_or_default();
            anyhow::bail!("WebChannel POST returned {}: {}", resp.status(), text);
        }

        let text = JsFuture::from(
            resp.text()
                .map_err(|e| anyhow::anyhow!("text() failed: {:?}", e))?,
        )
        .await
        .map_err(|e| anyhow::anyhow!("text await failed: {:?}", e))?
        .as_string()
        .unwrap_or_default();

        let stripped = strip_length_prefix(&text);
        Ok((stripped.to_string(), gsession_id))
    }

    /// Native GET fallback retained for parity with the WASM implementation and
    /// targeted diagnostics, even though the streaming path is preferred today.
    #[cfg(not(target_arch = "wasm32"))]
    #[allow(dead_code)]
    async fn get_with_auth(&self, url: &str) -> Result<String> {
        let mut req = self.http.get(url);

        if let Some(token) = self.get_token() {
            req = req.header("Authorization", format!("Bearer {}", token));
        }

        let res = req.send().await.context("WebChannel GET failed")?;

        if res.status() == reqwest::StatusCode::UNAUTHORIZED {
            anyhow::bail!("WebChannel: unauthorized (401)");
        }

        if !res.status().is_success() {
            let status = res.status();
            let text = res.text().await.unwrap_or_default();
            anyhow::bail!("WebChannel GET returned {}: {}", status, text);
        }

        res.text().await.context("Failed to read GET response")
    }

    /// WASM GET fallback retained for parity with the native implementation and
    /// targeted diagnostics, even though the streaming path is preferred today.
    #[cfg(target_arch = "wasm32")]
    #[allow(dead_code)]
    async fn get_with_auth(&self, url: &str) -> Result<String> {
        use wasm_bindgen::JsCast;
        use wasm_bindgen_futures::JsFuture;

        let opts = web_sys::RequestInit::new();
        opts.set_method("GET");

        let headers =
            web_sys::Headers::new().map_err(|e| anyhow::anyhow!("Headers::new failed: {:?}", e))?;

        if let Some(token) = self.get_token() {
            headers
                .set("Authorization", &format!("Bearer {}", token))
                .map_err(|e| anyhow::anyhow!("headers.set auth failed: {:?}", e))?;
        }

        opts.set_headers(&headers);

        let request = web_sys::Request::new_with_str_and_init(url, &opts)
            .map_err(|e| anyhow::anyhow!("Request::new failed: {:?}", e))?;

        let window = web_sys::window().context("no window")?;
        let resp_value = JsFuture::from(window.fetch_with_request(&request))
            .await
            .map_err(|e| anyhow::anyhow!("fetch failed: {:?}", e))?;

        let resp: web_sys::Response = resp_value
            .dyn_into()
            .map_err(|_| anyhow::anyhow!("response is not a Response"))?;

        if resp.status() == 401 {
            anyhow::bail!("WebChannel: unauthorized (401)");
        }

        if !resp.ok() {
            let text = JsFuture::from(
                resp.text()
                    .map_err(|e| anyhow::anyhow!("text() failed: {:?}", e))?,
            )
            .await
            .map_err(|e| anyhow::anyhow!("text await failed: {:?}", e))?
            .as_string()
            .unwrap_or_default();
            anyhow::bail!("WebChannel GET returned {}: {}", resp.status(), text);
        }

        let text = JsFuture::from(
            resp.text()
                .map_err(|e| anyhow::anyhow!("text() failed: {:?}", e))?,
        )
        .await
        .map_err(|e| anyhow::anyhow!("text await failed: {:?}", e))?
        .as_string()
        .unwrap_or_default();

        Ok(text)
    }

    #[cfg(target_arch = "wasm32")]
    async fn get_streaming_frames_with_auth(
        &self,
        url: &str,
    ) -> Result<Vec<(i64, Vec<serde_json::Value>)>> {
        use wasm_bindgen::JsCast;
        use wasm_bindgen_futures::JsFuture;

        let opts = web_sys::RequestInit::new();
        opts.set_method("GET");

        let headers =
            web_sys::Headers::new().map_err(|e| anyhow::anyhow!("Headers::new failed: {:?}", e))?;

        if let Some(token) = self.get_token() {
            headers
                .set("Authorization", &format!("Bearer {}", token))
                .map_err(|e| anyhow::anyhow!("headers.set auth failed: {:?}", e))?;
        }

        opts.set_headers(&headers);

        let request = web_sys::Request::new_with_str_and_init(url, &opts)
            .map_err(|e| anyhow::anyhow!("Request::new failed: {:?}", e))?;

        let window = web_sys::window().context("no window")?;
        let resp_value = JsFuture::from(window.fetch_with_request(&request))
            .await
            .map_err(|e| anyhow::anyhow!("fetch failed: {:?}", e))?;

        let resp: web_sys::Response = resp_value
            .dyn_into()
            .map_err(|_| anyhow::anyhow!("response is not a Response"))?;

        if resp.status() == 401 {
            anyhow::bail!("WebChannel: unauthorized (401)");
        }

        if !resp.ok() {
            let text = JsFuture::from(
                resp.text()
                    .map_err(|e| anyhow::anyhow!("text() failed: {:?}", e))?,
            )
            .await
            .map_err(|e| anyhow::anyhow!("text await failed: {:?}", e))?
            .as_string()
            .unwrap_or_default();
            anyhow::bail!("WebChannel GET returned {}: {}", resp.status(), text);
        }

        let body = resp
            .body()
            .ok_or_else(|| anyhow::anyhow!("WebChannel GET response missing body"))?;
        let reader = body
            .get_reader()
            .dyn_into::<web_sys::ReadableStreamDefaultReader>()
            .map_err(|_| anyhow::anyhow!("failed to acquire ReadableStreamDefaultReader"))?;

        let mut buffer = Vec::<u8>::new();

        loop {
            let chunk = JsFuture::from(reader.read())
                .await
                .map_err(|e| anyhow::anyhow!("reader.read failed: {:?}", e))?;
            let done = js_sys::Reflect::get(&chunk, &wasm_bindgen::JsValue::from_str("done"))
                .map_err(|e| anyhow::anyhow!("Reflect.get(done) failed: {:?}", e))?
                .as_bool()
                .unwrap_or(false);

            let value = js_sys::Reflect::get(&chunk, &wasm_bindgen::JsValue::from_str("value"))
                .map_err(|e| anyhow::anyhow!("Reflect.get(value) failed: {:?}", e))?;

            if !value.is_undefined() && !value.is_null() {
                let bytes = js_sys::Uint8Array::new(&value);
                let mut chunk_bytes = vec![0u8; bytes.length() as usize];
                bytes.copy_to(&mut chunk_bytes);
                buffer.extend_from_slice(&chunk_bytes);

                if let Some((_, frames)) = parse_length_prefixed_frame_batches(&buffer)? {
                    let _ = JsFuture::from(reader.cancel()).await;
                    return Ok(frames);
                }
            }

            if done {
                break;
            }
        }

        if let Some((_, frames)) = parse_length_prefixed_frame_batches(&buffer)? {
            return Ok(frames);
        }

        if buffer.is_empty() {
            return Ok(Vec::new());
        }

        let text = String::from_utf8(buffer)
            .map_err(|e| anyhow::anyhow!("WebChannel body was not valid UTF-8: {}", e))?;
        parse_framed_response(&text)
    }
}

// ── Frame parsing ──────────────────────────────────────────────────────

/// Strip the optional length prefix from a WebChannel response.
/// Format: `<decimal_length>\n<json_payload>`
fn strip_length_prefix(text: &str) -> &str {
    let trimmed = text.trim();
    if let Some(newline_pos) = trimmed.find('\n') {
        let prefix = &trimmed[..newline_pos];
        if prefix.chars().all(|c| c.is_ascii_digit()) {
            return &trimmed[newline_pos + 1..];
        }
    }
    trimmed
}

fn parse_length_prefixed_frame_batches(
    buffer: &[u8],
) -> Result<Option<(usize, Vec<(i64, Vec<serde_json::Value>)>)>> {
    let mut cursor = 0usize;
    let mut all_frames = Vec::new();

    loop {
        while cursor < buffer.len() && buffer[cursor].is_ascii_whitespace() {
            cursor += 1;
        }

        if cursor >= buffer.len() {
            break;
        }

        if buffer[cursor] == b'[' || buffer[cursor] == b'{' {
            // Consume exactly one JSON frame here. Firebase sometimes emits
            // adjacent `<json><length>\n<json>` sequences in a single chunk,
            // so we alternate between JSON and length-prefixed blocks instead
            // of handing the remainder to a streaming deserializer (which
            // would choke on the intermediate decimal length prefix).
            match parse_one_json_frame_prefix(&buffer[cursor..])? {
                Some((consumed, frames)) => {
                    all_frames.extend(frames);
                    cursor += consumed;
                    continue;
                }
                None => break,
            }
        }

        let len_start = cursor;
        while cursor < buffer.len() && buffer[cursor].is_ascii_digit() {
            cursor += 1;
        }

        if cursor == len_start {
            anyhow::bail!("Unexpected WebChannel framing byte: {}", buffer[cursor]);
        }

        if cursor >= buffer.len() {
            break;
        }

        if buffer[cursor] != b'\n' {
            anyhow::bail!(
                "Invalid WebChannel frame delimiter: expected newline, found {}",
                buffer[cursor]
            );
        }

        let payload_len = std::str::from_utf8(&buffer[len_start..cursor])
            .context("WebChannel frame length was not valid UTF-8")?
            .parse::<usize>()
            .context("WebChannel frame length was not a valid number")?;
        cursor += 1;

        if buffer.len().saturating_sub(cursor) < payload_len {
            cursor = len_start;
            break;
        }

        let payload = std::str::from_utf8(&buffer[cursor..cursor + payload_len])
            .context("WebChannel payload was not valid UTF-8")?;
        all_frames.extend(parse_frame_payload(payload)?);
        cursor += payload_len;
    }

    if all_frames.is_empty() {
        Ok(None)
    } else {
        Ok(Some((cursor, all_frames)))
    }
}

fn parse_frame_payload(payload: &str) -> Result<Vec<(i64, Vec<serde_json::Value>)>> {
    let trimmed = payload.trim();
    if trimmed.is_empty() {
        return Ok(Vec::new());
    }

    let mut deserializer =
        serde_json::Deserializer::from_str(trimmed).into_iter::<serde_json::Value>();
    let mut frames = Vec::new();
    let mut saw_value = false;

    while let Some(value) = deserializer.next() {
        let parsed =
            value.with_context(|| format!("Failed to parse WebChannel frame: {}", trimmed))?;
        saw_value = true;
        frames.extend(parse_frame_value(parsed)?);
    }

    if !saw_value {
        anyhow::bail!("Failed to parse WebChannel frame: {}", trimmed);
    }

    Ok(frames)
}

fn parse_frame_value(parsed: serde_json::Value) -> Result<Vec<(i64, Vec<serde_json::Value>)>> {
    let outer = parsed.as_array().context("Frame is not an array")?;
    let mut frames = Vec::new();

    for item in outer {
        let pair = item.as_array().context("Frame item is not an array")?;
        let aid = pair.first().and_then(|v| v.as_i64()).unwrap_or(0);
        let messages = pair
            .get(1)
            .and_then(|v| v.as_array())
            .cloned()
            .unwrap_or_default();
        frames.push((aid, messages));
    }

    Ok(frames)
}

fn parse_one_json_frame_prefix(
    buffer: &[u8],
) -> Result<Option<(usize, Vec<(i64, Vec<serde_json::Value>)>)>> {
    let text = std::str::from_utf8(buffer).context("WebChannel payload was not valid UTF-8")?;
    let mut stream = serde_json::Deserializer::from_str(text).into_iter::<serde_json::Value>();
    let Some(value) = stream.next() else {
        return Ok(None);
    };

    let parsed = match value {
        Ok(parsed) => parsed,
        Err(err) if err.is_eof() => {
            // JSON is truncated mid-value — treat as "need more bytes" rather
            // than a hard parse failure so streaming readers can buffer more.
            return Ok(None);
        }
        Err(err) => {
            return Err(anyhow::Error::new(err)
                .context(format!("Failed to parse WebChannel frame: {}", text.trim())));
        }
    };
    let consumed = stream.byte_offset();
    let frames = parse_frame_value(parsed)?;
    Ok(Some((consumed, frames)))
}

/// Parse WebChannel frames into (aid, messages) tuples.
/// Supports either a raw JSON payload or one-or-more adjacent
/// `<length>\n<json_payload>` batches in a single response body.
fn parse_framed_response(text: &str) -> Result<Vec<(i64, Vec<serde_json::Value>)>> {
    let stripped = strip_length_prefix(text);
    if stripped.is_empty() {
        return Ok(Vec::new());
    }

    let trimmed = text.trim();
    let bytes = trimmed.as_bytes();
    let mut cursor = 0usize;
    let mut all_frames = Vec::new();

    loop {
        while cursor < bytes.len() && bytes[cursor].is_ascii_whitespace() {
            cursor += 1;
        }

        if cursor >= bytes.len() {
            break;
        }

        let remaining = &bytes[cursor..];

        match remaining[0] {
            b'[' | b'{' => {
                let Some((consumed, frames)) = parse_one_json_frame_prefix(remaining)? else {
                    break;
                };
                all_frames.extend(frames);
                cursor += consumed;
            }
            b'0'..=b'9' => {
                let Some((consumed, frames)) = parse_length_prefixed_frame_batches(remaining)?
                else {
                    anyhow::bail!(
                        "Incomplete length-prefixed WebChannel payload: {}",
                        std::str::from_utf8(remaining).unwrap_or("<non-utf8>")
                    );
                };
                all_frames.extend(frames);
                cursor += consumed;
            }
            other => {
                anyhow::bail!(
                    "Unexpected leading WebChannel byte {} in payload: {}",
                    other,
                    std::str::from_utf8(remaining).unwrap_or("<non-utf8>")
                );
            }
        }
    }

    Ok(all_frames)
}

/// Parse a single ListenResponse JSON value into a ListenEvent.
fn parse_listen_event(value: &serde_json::Value) -> Option<ListenEvent> {
    if let Some(tc) = value.get("targetChange") {
        let change_type = tc
            .get("targetChangeType")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();
        let target_ids = tc
            .get("targetIds")
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_i64().map(|n| n as i32))
                    .collect()
            })
            .unwrap_or_default();
        let resume_token = tc
            .get("resumeToken")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());
        let cause = tc.get("cause").map(|c| ListenError {
            code: c.get("code").and_then(|v| v.as_i64()).unwrap_or(0) as i32,
            message: c
                .get("message")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string(),
        });
        return Some(ListenEvent::TargetChange {
            target_change_type: change_type,
            target_ids,
            resume_token,
            cause,
        });
    }

    if let Some(dc) = value.get("documentChange") {
        let document = dc
            .get("document")
            .cloned()
            .unwrap_or(serde_json::Value::Null);
        let target_ids = dc
            .get("targetIds")
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_i64().map(|n| n as i32))
                    .collect()
            })
            .unwrap_or_default();
        return Some(ListenEvent::DocumentChange {
            document,
            target_ids,
        });
    }

    if let Some(dd) = value.get("documentDelete") {
        let document_path = dd
            .get("document")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();
        let target_ids = dd
            .get("removedTargetIds")
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_i64().map(|n| n as i32))
                    .collect()
            })
            .unwrap_or_default();
        return Some(ListenEvent::DocumentDelete {
            document_path,
            target_ids,
        });
    }

    if let Some(dr) = value.get("documentRemove") {
        let document_path = dr
            .get("document")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();
        let target_ids = dr
            .get("removedTargetIds")
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_i64().map(|n| n as i32))
                    .collect()
            })
            .unwrap_or_default();
        return Some(ListenEvent::DocumentRemove {
            document_path,
            target_ids,
        });
    }

    if let Some(f) = value.get("filter") {
        let target_id = f.get("targetId").and_then(|v| v.as_i64()).unwrap_or(0) as i32;
        let count = f.get("count").and_then(|v| v.as_i64()).unwrap_or(0) as i32;
        return Some(ListenEvent::Filter { target_id, count });
    }

    None
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_strip_length_prefix() {
        assert_eq!(
            strip_length_prefix("51\n[[0,[\"c\",\"abc\",\"\",8,14,30000]]]"),
            "[[0,[\"c\",\"abc\",\"\",8,14,30000]]]"
        );
        assert_eq!(strip_length_prefix("[]"), "[]");
        assert_eq!(strip_length_prefix("  42\n{\"a\":1}  "), "{\"a\":1}");
    }

    #[test]
    fn test_parse_frames() {
        let input = "[[1,[{\"targetChange\":{\"targetChangeType\":\"ADD\",\"targetIds\":[2]}}]],[2,[{\"targetChange\":{\"targetChangeType\":\"CURRENT\",\"targetIds\":[2]}}]]]";
        let frames = parse_framed_response(input).unwrap();
        assert_eq!(frames.len(), 2);
        assert_eq!(frames[0].0, 1);
        assert_eq!(frames[1].0, 2);
    }

    #[test]
    fn test_parse_listen_event_target_change() {
        let val: serde_json::Value =
            serde_json::from_str(r#"{"targetChange":{"targetChangeType":"ADD","targetIds":[1]}}"#)
                .unwrap();
        let event = parse_listen_event(&val).unwrap();
        match event {
            ListenEvent::TargetChange {
                target_change_type,
                target_ids,
                ..
            } => {
                assert_eq!(target_change_type, "ADD");
                assert_eq!(target_ids, vec![1]);
            }
            _ => assert!(false, "Expected TargetChange"),
        }
    }

    #[test]
    fn test_parse_listen_event_document_change() {
        let val: serde_json::Value = serde_json::from_str(
            r#"{"documentChange":{"document":{"name":"projects/p/databases/(default)/documents/col/doc1","fields":{"a":{"stringValue":"b"}}},"targetIds":[1]}}"#,
        )
        .unwrap();
        let event = parse_listen_event(&val).unwrap();
        match event {
            ListenEvent::DocumentChange {
                document,
                target_ids,
            } => {
                assert_eq!(target_ids, vec![1]);
                assert!(document.get("name").is_some());
            }
            _ => assert!(false, "Expected DocumentChange"),
        }
    }

    #[test]
    fn test_parse_listen_event_document_delete() {
        let val: serde_json::Value = serde_json::from_str(
            r#"{"documentDelete":{"document":"projects/p/databases/(default)/documents/col/doc1","removedTargetIds":[1]}}"#,
        )
        .unwrap();
        let event = parse_listen_event(&val).unwrap();
        match event {
            ListenEvent::DocumentDelete {
                document_path,
                target_ids,
            } => {
                assert!(document_path.ends_with("col/doc1"));
                assert_eq!(target_ids, vec![1]);
            }
            _ => assert!(false, "Expected DocumentDelete"),
        }
    }

    #[test]
    fn test_parse_listen_event_with_error_cause() {
        let val: serde_json::Value = serde_json::from_str(
            r#"{"targetChange":{"targetChangeType":"REMOVE","targetIds":[2],"cause":{"code":7,"message":"Missing or insufficient permissions."}}}"#,
        )
        .unwrap();
        let event = parse_listen_event(&val).unwrap();
        match event {
            ListenEvent::TargetChange { cause, .. } => {
                let cause = cause.unwrap();
                assert_eq!(cause.code, 7);
                assert!(cause.message.contains("permissions"));
            }
            _ => assert!(false, "Expected TargetChange"),
        }
    }

    #[test]
    fn test_parse_frames_with_length_prefix() {
        let payload = r#"[[1,[{"targetChange":{"targetChangeType":"ADD","targetIds":[2]}}]]]"#;
        let input = format!("{}\n{}", payload.len(), payload);
        let frames = parse_framed_response(&input).unwrap();
        assert_eq!(frames.len(), 1);
        assert_eq!(frames[0].0, 1);
    }

    #[test]
    fn test_parse_length_prefixed_frame_batches() {
        let payload = r#"[[1,[{"targetChange":{"targetChangeType":"ADD","targetIds":[2]}}]]]"#;
        let input = format!("{}\n{}", payload.len(), payload);
        let parsed = parse_length_prefixed_frame_batches(input.as_bytes())
            .unwrap()
            .unwrap();
        assert_eq!(parsed.1.len(), 1);
        assert_eq!(parsed.1[0].0, 1);
    }

    #[test]
    fn test_parse_length_prefixed_frame_batches_waits_for_complete_payload() {
        let partial = b"70\n[[1,[{\"targetChange\":{\"targetChangeType\":\"ADD\"";
        assert!(parse_length_prefixed_frame_batches(partial)
            .unwrap()
            .is_none());
    }

    #[test]
    fn test_parse_length_prefixed_frame_batches_mixed_raw_then_prefixed() {
        // Streamed body where a raw JSON array is immediately followed by a
        // length-prefixed frame in the same chunk. Prior to the fix, the
        // streaming WASM path would bail with "Failed to parse WebChannel
        // frame" because serde_json choked on the intermediate decimal length
        // prefix.
        let payload_one = r#"[[1,[{"targetChange":{"targetChangeType":"ADD","targetIds":[2]}}]]]"#;
        let payload_two = r#"[[2,[{"documentChange":{"document":{"name":"projects/p/databases/(default)/documents/col/doc1"}}}]]]"#;
        let input = format!("{}{}\n{}", payload_one, payload_two.len(), payload_two);
        let parsed = parse_length_prefixed_frame_batches(input.as_bytes())
            .unwrap()
            .unwrap();
        assert_eq!(parsed.1.len(), 2);
        assert_eq!(parsed.1[0].0, 1);
        assert_eq!(parsed.1[1].0, 2);
    }

    #[test]
    fn test_parse_length_prefixed_frame_batches_multiple_raw_adjacent() {
        let payload_one = r#"[[5,[{"documentChange":{"document":{"name":"projects/p/databases/(default)/documents/apps/app/devices/device-1"}}}]]]"#;
        let payload_two =
            r#"[[6,[{"targetChange":{"targetChangeType":"CURRENT","targetIds":[1]}}]]]"#;
        let input = format!("{}{}", payload_one, payload_two);
        let parsed = parse_length_prefixed_frame_batches(input.as_bytes())
            .unwrap()
            .unwrap();
        assert_eq!(parsed.1.len(), 2);
        assert_eq!(parsed.1[0].0, 5);
        assert_eq!(parsed.1[1].0, 6);
    }

    #[test]
    fn test_parse_framed_response_with_multiple_adjacent_length_prefixed_batches() {
        let payload_one = r#"[[1,[{"targetChange":{"targetChangeType":"ADD","targetIds":[2]}}]]]"#;
        let payload_two = r#"[[2,[{"documentChange":{"document":{"name":"projects/p/databases/(default)/documents/col/doc1"}}}]]]"#;
        let input = format!(
            "{}\n{}{}\n{}",
            payload_one.len(),
            payload_one,
            payload_two.len(),
            payload_two
        );

        let frames = parse_framed_response(&input).unwrap();
        assert_eq!(frames.len(), 2);
        assert_eq!(frames[0].0, 1);
        assert_eq!(frames[1].0, 2);
    }

    #[test]
    fn test_parse_framed_response_with_multiple_adjacent_raw_json_arrays() {
        let payload_one = r#"[[5,[{"documentChange":{"document":{"name":"projects/p/databases/(default)/documents/apps/app/devices/device-1"}}}]]]"#;
        let payload_two =
            r#"[[6,[{"targetChange":{"targetChangeType":"CURRENT","targetIds":[1]}}]]]"#;
        let input = format!("{}{}", payload_one, payload_two);

        let frames = parse_framed_response(&input).unwrap();
        assert_eq!(frames.len(), 2);
        assert_eq!(frames[0].0, 5);
        assert_eq!(frames[1].0, 6);
    }

    #[test]
    fn test_parse_framed_response_with_raw_frame_then_length_prefixed_batch() {
        let payload_one = r#"[[5,[{"documentChange":{"document":{"name":"projects/p/databases/(default)/documents/apps/app/devices/device-1"}}}]]]"#;
        let payload_two =
            r#"[[6,[{"targetChange":{"targetChangeType":"CURRENT","targetIds":[1]}}]]]"#;
        let input = format!("{}{}\n{}", payload_one, payload_two.len(), payload_two);

        let frames = parse_framed_response(&input).unwrap();
        assert_eq!(frames.len(), 2);
        assert_eq!(frames[0].0, 5);
        assert_eq!(frames[1].0, 6);
    }
}