bevy_http_client 0.11.0

A simple HTTP client for Bevy
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
#![doc = include_str!("../README.md")]

use bevy_app::{App, Plugin, Update};
use bevy_derive::Deref;
use bevy_ecs::{prelude::*, world::CommandQueue};
use bevy_tasks::IoTaskPool;
use crossbeam_channel::{Receiver, Sender};
use ehttp::{Headers, Request, Response};

use crate::{prelude::TypedRequest, typed::HttpObserved};

pub mod prelude;
mod typed;

/// JSON serialization fallback strategy when serialization fails
#[derive(Debug, Clone, Default)]
pub enum JsonFallback {
    /// Use empty object {} as fallback
    #[default]
    EmptyObject,
    /// Use empty array [] as fallback
    EmptyArray,
    /// Use null as fallback
    Null,
    /// Use custom data as fallback
    Custom(Vec<u8>),
}

/// JSON serialization error type
#[derive(Debug, Clone)]
pub enum JsonSerializationError {
    SerializationFailed {
        message: String,
        fallback_used: JsonFallback,
    },
}

impl std::fmt::Display for JsonSerializationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            JsonSerializationError::SerializationFailed {
                message,
                fallback_used,
            } => {
                write!(
                    f,
                    "JSON serialization failed: {}, fallback: {:?}",
                    message, fallback_used
                )
            }
        }
    }
}

impl std::error::Error for JsonSerializationError {}

/// HTTP client builder error type
#[derive(Debug, Clone)]
pub enum HttpClientBuilderError {
    MissingMethod,
    MissingUrl,
    MissingHeaders,
}

impl std::fmt::Display for HttpClientBuilderError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            HttpClientBuilderError::MissingMethod => write!(f, "HTTP method is required"),
            HttpClientBuilderError::MissingUrl => write!(f, "URL is required"),
            HttpClientBuilderError::MissingHeaders => write!(f, "Headers are required"),
        }
    }
}

impl std::error::Error for HttpClientBuilderError {}

/// Plugin that provides support for send http request and handle response.
///
/// # Example
/// ```
/// use bevy::prelude::*;
/// use bevy_http_client::prelude::*;
///
/// let mut app = App::new();
/// app.add_plugins(MinimalPlugins)
///    .add_plugins(HttpClientPlugin);
/// // Note: Don't call .run() in doctests as it starts the event loop
/// ```
#[derive(Default)]
pub struct HttpClientPlugin;

impl Plugin for HttpClientPlugin {
    fn build(&self, app: &mut App) {
        if !app.world().contains_resource::<HttpClientSetting>() {
            app.init_resource::<HttpClientSetting>();
        }
        app.add_message::<HttpRequest>();
        app.add_message::<HttpResponse>();
        app.add_message::<HttpResponseError>();
        app.add_systems(Update, (handle_request, handle_tasks));
    }
}

/// The setting of http client.
/// can set the max concurrent request.
#[derive(Resource, Debug)]
pub struct HttpClientSetting {
    /// max concurrent request
    pub client_limits: usize,
    current_clients: usize,
}

impl Default for HttpClientSetting {
    fn default() -> Self {
        Self {
            client_limits: 5,
            current_clients: 0,
        }
    }
}

impl HttpClientSetting {
    /// create a new http client setting
    pub fn new(max_concurrent: usize) -> Self {
        Self {
            client_limits: max_concurrent,
            current_clients: 0,
        }
    }

    /// check if the client is available
    #[inline]
    pub fn is_available(&self) -> bool {
        self.current_clients < self.client_limits
    }
}

#[derive(Event, Message, Debug, Clone)]
pub struct HttpRequest {
    pub from_entity: Option<Entity>,
    pub request: Request,
}

/// builder  for ehttp request
#[derive(Component, Debug, Clone)]
pub struct HttpClient {
    /// The entity that the request is associated with.
    from_entity: Option<Entity>,
    /// "GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", …
    method: Option<String>,

    /// https://…
    url: Option<String>,

    /// The data you send with e.g. "POST".
    body: Vec<u8>,

    /// ("Accept", "*/*"), …
    headers: Option<Headers>,

    /// Request mode used on fetch. Only available on wasm builds
    #[cfg(target_arch = "wasm32")]
    pub mode: ehttp::Mode,
}

impl Default for HttpClient {
    fn default() -> Self {
        Self {
            from_entity: None,
            method: None,
            url: None,
            body: vec![],
            headers: Some(Headers::new(&[("Accept", "*/*")])),
            #[cfg(target_arch = "wasm32")]
            mode: ehttp::Mode::default(),
        }
    }
}

impl HttpClient {
    /// This method is used to create a new `HttpClient` instance.
    ///
    /// # Returns
    ///
    /// * `Self` - Returns the instance of the `HttpClient` struct.
    ///
    /// # Examples
    ///
    /// ```
    /// use bevy_http_client::HttpClient;
    /// let http_client = HttpClient::new();
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// his method is used to create a new `HttpClient` instance with `Entity`.
    ///
    /// # Arguments
    ///
    /// * `entity`: Target Entity
    ///
    /// returns: HttpClient
    ///
    /// # Examples
    ///
    /// ```
    /// use bevy_http_client::HttpClient;
    /// use bevy_ecs::entity::Entity;
    ///
    /// let entity = Entity::from_raw_u32(42).unwrap(); // Example entity
    /// let http_client = HttpClient::new_with_entity(entity);
    /// ```
    pub fn new_with_entity(entity: Entity) -> Self {
        Self {
            from_entity: Some(entity),
            ..Default::default()
        }
    }

    /// This method is used to create a `GET` HTTP request.
    ///
    /// # Arguments
    ///
    /// * `url` - A value that can be converted into a string. This is the URL to which the HTTP
    ///   request will be sent.
    ///
    /// # Returns
    ///
    /// * `Self` - Returns the instance of the `HttpClient` struct, allowing for method chaining.
    ///
    /// # Examples
    ///
    /// ```
    /// use bevy_http_client::HttpClient;
    /// let http_client = HttpClient::new().get("http://example.com");
    /// ```
    pub fn get(mut self, url: impl ToString) -> Self {
        self.method = Some("GET".to_string());
        self.url = Some(url.to_string());
        self
    }

    /// This method is used to create a `POST` HTTP request.
    ///
    /// # Arguments
    ///
    /// * `url` - A value that can be converted into a string. This is the URL to which the HTTP
    ///   request will be sent.
    ///
    /// # Returns
    ///
    /// * `Self` - Returns the instance of the `HttpClient` struct, allowing for method chaining.
    ///
    /// # Examples
    ///
    /// ```
    /// use bevy_http_client::HttpClient;
    /// let http_client = HttpClient::new().post("http://example.com");
    /// ```
    pub fn post(mut self, url: impl ToString) -> Self {
        self.method = Some("POST".to_string());
        self.url = Some(url.to_string());
        self
    }

    /// This method is used to create a `PUT` HTTP request.
    ///
    /// # Arguments
    ///
    /// * `url` - A value that can be converted into a string. This is the URL to which the HTTP
    ///   request will be sent.
    ///
    /// # Returns
    ///
    /// * `Self` - Returns the instance of the `HttpClient` struct, allowing for method chaining.
    ///
    /// # Examples
    ///
    /// ```
    /// use bevy_http_client::HttpClient;
    /// let http_client = HttpClient::new().put("http://example.com");
    /// ```
    pub fn put(mut self, url: impl ToString) -> Self {
        self.method = Some("PUT".to_string());
        self.url = Some(url.to_string());
        self
    }

    /// This method is used to create a `PATCH` HTTP request.
    ///
    /// # Arguments
    ///
    /// * `url` - A value that can be converted into a string. This is the URL to which the HTTP
    ///   request will be sent.
    ///
    /// # Returns
    ///
    /// * `Self` - Returns the instance of the `HttpClient` struct, allowing for method chaining.
    ///
    /// # Examples
    ///
    /// ```
    /// use bevy_http_client::HttpClient;
    /// let http_client = HttpClient::new().patch("http://example.com");
    /// ```
    pub fn patch(mut self, url: impl ToString) -> Self {
        self.method = Some("PATCH".to_string());
        self.url = Some(url.to_string());
        self
    }

    /// This method is used to create a `DELETE` HTTP request.
    ///
    /// # Arguments
    ///
    /// * `url` - A value that can be converted into a string. This is the URL to which the HTTP
    ///   request will be sent.
    ///
    /// # Returns
    ///
    /// * `Self` - Returns the instance of the `HttpClient` struct, allowing for method chaining.
    ///
    /// # Examples
    ///
    /// ```
    /// use bevy_http_client::HttpClient;
    /// let http_client = HttpClient::new().delete("http://example.com");
    /// ```
    pub fn delete(mut self, url: impl ToString) -> Self {
        self.method = Some("DELETE".to_string());
        self.url = Some(url.to_string());
        self
    }

    /// This method is used to create a `HEAD` HTTP request.
    ///
    /// # Arguments
    ///
    /// * `url` - A value that can be converted into a string. This is the URL to which the HTTP
    ///   request will be sent.
    ///
    /// # Returns
    ///
    /// * `Self` - Returns the instance of the `HttpClient` struct, allowing for method chaining.
    ///
    /// # Examples
    ///
    /// ```
    /// use bevy_http_client::HttpClient;
    /// let http_client = HttpClient::new().head("http://example.com");
    /// ```
    pub fn head(mut self, url: impl ToString) -> Self {
        self.method = Some("HEAD".to_string());
        self.url = Some(url.to_string());
        self
    }

    /// This method is used to set the headers of the HTTP request.
    ///
    /// # Arguments
    ///
    /// * `headers` - A slice of tuples where each tuple represents a header. The first element of
    ///   the tuple is the header name and the second element is the header value.
    ///
    /// # Returns
    ///
    /// * `Self` - Returns the instance of the `HttpClient` struct, allowing for method chaining.
    ///
    /// # Examples
    ///
    /// ```
    /// use bevy_http_client::HttpClient;
    /// let http_client = HttpClient::new().post("http://example.com")
    ///     .headers(&[("Content-Type", "application/json"), ("Accept", "*/*")]);
    /// ```
    pub fn headers(mut self, headers: &[(&str, &str)]) -> Self {
        self.headers = Some(Headers::new(headers));
        self
    }

    /// Safe JSON serialization method with fallback strategy
    ///
    /// This method safely serializes the body to JSON and sets the Content-Type header.
    /// If serialization fails, it uses a fallback strategy instead of panicking.
    ///
    /// # Arguments
    /// * `body` - Data to serialize to JSON
    /// * `fallback` - Fallback strategy when serialization fails
    ///
    /// # Returns
    /// Returns HttpClient instance for method chaining
    ///
    /// # Examples
    /// ```
    /// use bevy_http_client::{HttpClient, JsonFallback};
    /// use serde::Serialize;
    ///
    /// #[derive(Serialize)]
    /// struct MyData { name: String }
    /// let data = MyData { name: "test".to_string() };
    ///
    /// let client = HttpClient::new()
    ///     .post("http://example.com")
    ///     .json_with_fallback(&data, JsonFallback::EmptyObject);
    /// ```
    pub fn json_with_fallback(
        mut self,
        body: &impl serde::Serialize,
        fallback: JsonFallback,
    ) -> Self {
        // Set Content-Type header
        if let Some(headers) = self.headers.as_mut() {
            headers.insert("Content-Type".to_string(), "application/json".to_string());
        } else {
            self.headers = Some(Headers::new(&[
                ("Content-Type", "application/json"),
                ("Accept", "*/*"),
            ]));
        }

        // Safe serialization with fallback strategy
        self.body = match serde_json::to_vec(body) {
            Ok(bytes) => {
                // Check for unreasonably large payloads
                if bytes.len() > 50 * 1024 * 1024 {
                    // 50MB limit
                    bevy_log::warn!(
                        "JSON payload is very large ({} bytes), this might cause performance issues",
                        bytes.len()
                    );
                }
                bytes
            }
            Err(e) => {
                // Get fallback data
                let fallback_data = match &fallback {
                    JsonFallback::EmptyObject => b"{}".to_vec(),
                    JsonFallback::EmptyArray => b"[]".to_vec(),
                    JsonFallback::Null => b"null".to_vec(),
                    JsonFallback::Custom(data) => data.clone(),
                };

                // Log error using bevy's logging system
                bevy_log::error!(
                    "JSON serialization failed: {}. Using fallback: {:?}",
                    e,
                    fallback
                );

                fallback_data
            }
        };

        self
    }

    /// Result-returning safe JSON serialization method
    ///
    /// # Arguments
    /// * `body` - Data to serialize to JSON
    ///
    /// # Returns
    /// * `Ok(HttpClient)` - Serialization successful
    /// * `Err(JsonSerializationError)` - Serialization failed
    ///
    /// # Examples
    /// ```
    /// use bevy_http_client::HttpClient;
    /// use serde::Serialize;
    ///
    /// #[derive(Serialize)]
    /// struct MyData { name: String }
    /// let data = MyData { name: "test".to_string() };
    ///
    /// match HttpClient::new().post("http://example.com").json_safe(&data) {
    ///     Ok(client) => { /* use client */ },
    ///     Err(e) => { /* handle error */ },
    /// }
    /// ```
    pub fn json_safe(
        mut self,
        body: &impl serde::Serialize,
    ) -> Result<Self, JsonSerializationError> {
        // Set Content-Type header
        if let Some(headers) = self.headers.as_mut() {
            headers.insert("Content-Type".to_string(), "application/json".to_string());
        } else {
            self.headers = Some(Headers::new(&[
                ("Content-Type", "application/json"),
                ("Accept", "*/*"),
            ]));
        }

        // Try serialization
        self.body = serde_json::to_vec(body).map_err(|e| {
            JsonSerializationError::SerializationFailed {
                message: e.to_string(),
                fallback_used: JsonFallback::EmptyObject, // Record intended fallback
            }
        })?;

        Ok(self)
    }

    /// Improved json method with safe fallback - maintains backward compatibility
    ///
    /// This method will automatically use empty object {} as fallback when serialization fails,
    /// instead of panicking. This maintains backward compatibility while providing better error handling.
    ///
    /// # Arguments
    /// * `body` - Data to serialize to JSON
    ///
    /// # Returns
    /// Returns HttpClient instance for method chaining
    ///
    /// # Examples
    /// ```
    /// use bevy_http_client::HttpClient;
    /// use serde::Serialize;
    ///
    /// #[derive(Serialize)]
    /// struct MyData { name: String }
    /// let my_data = MyData { name: "test".to_string() };
    ///
    /// let client = HttpClient::new()
    ///     .post("http://example.com")
    ///     .json(&my_data);  // Now safe, won't panic
    /// ```
    pub fn json(self, body: &impl serde::Serialize) -> Self {
        // Use default fallback strategy (empty object)
        self.json_with_fallback(body, JsonFallback::default())
    }

    /// Sets the request body as URL-encoded form data
    ///
    /// Used to send data in `application/x-www-form-urlencoded` format,
    /// which is the standard format for HTML form submissions. The data should be
    /// pre-encoded in key=value pairs separated by & characters.
    ///
    /// Automatically sets:
    /// - Content-Type: application/x-www-form-urlencoded
    ///
    /// # Arguments
    ///
    /// * `body` - A string slice containing URL-encoded form data (e.g., "key1=value1&key2=value2")
    ///
    /// # Returns
    ///
    /// * `Self` - Returns the instance of the `HttpClient` struct, allowing for method chaining
    ///
    /// # Examples
    ///
    /// ```
    /// use bevy_http_client::HttpClient;
    ///
    /// // Simple form submission
    /// let client = HttpClient::new()
    ///     .post("https://api.example.com/login")
    ///     .form_encoded("username=john&password=secret")
    ///     .headers(&[("Accept", "application/json")]);
    ///
    /// // With URL-encoded special characters
    /// let client = HttpClient::new()
    ///     .post("https://api.example.com/submit")
    ///     .form_encoded("email=user%40example.com&message=Hello%20World")
    ///     .headers(&[("Accept", "application/json")]);
    /// ```
    ///
    /// # Note
    ///
    /// The caller is responsible for properly URL-encoding the data. Special characters
    /// should be percent-encoded according to RFC 3986.
    pub fn form_encoded(mut self, body: &str) -> Self {
        if let Some(headers) = self.headers.as_mut() {
            headers.insert(
                "Content-Type".to_string(),
                "application/x-www-form-urlencoded".to_string(),
            );
        } else {
            self.headers = Some(ehttp::Headers::new(&[(
                "Content-Type",
                "application/x-www-form-urlencoded",
            )]));
        }

        self.body = body.as_bytes().to_vec();
        self
    }

    /// This method is used to set the properties of the `HttpClient` instance using an `Request`
    /// instance. This version of the method is used when the target architecture is not
    /// `wasm32`.
    ///
    /// # Arguments
    ///
    /// * `request` - An instance of `Request` which includes the HTTP method, URL, body, and
    ///   headers.
    ///
    /// # Returns
    ///
    /// * `Self` - Returns the instance of the `HttpClient` struct, allowing for method chaining.
    ///
    /// # Examples
    ///
    /// ```
    /// use bevy_http_client::HttpClient;
    /// use ehttp::{Request, Headers};
    ///
    /// let request = Request {
    ///     method: "POST".to_string(),
    ///     url: "http://example.com".to_string(),
    ///     body: vec![],
    ///     headers: Headers::new(&[("Content-Type", "application/json"), ("Accept", "*/*")]),
    /// };
    /// let http_client = HttpClient::new().request(request);
    /// ```
    #[cfg(not(target_arch = "wasm32"))]
    pub fn request(mut self, request: Request) -> Self {
        self.method = Some(request.method);
        self.url = Some(request.url);
        self.body = request.body;
        self.headers = Some(request.headers);

        self
    }

    /// Associates an `Entity` with the `HttpClient`.
    ///
    /// This method is used to associate an `Entity` with the `HttpClient`. This can be useful when
    /// you want to track which entity initiated the HTTP request.
    ///
    /// # Parameters
    ///
    /// * `entity`: The `Entity` that you want to associate with the `HttpClient`.
    ///
    /// # Returns
    ///
    /// A mutable reference to the `HttpClient`. This is used to allow method chaining.
    ///
    /// # Examples
    ///
    /// ```
    /// use bevy_http_client::HttpClient;
    /// use bevy_ecs::entity::Entity;
    ///
    /// let entity = Entity::from_raw_u32(42).unwrap(); // Example entity
    /// let http_client = HttpClient::new().entity(entity);
    /// ```
    pub fn entity(mut self, entity: Entity) -> Self {
        self.from_entity = Some(entity);
        self
    }

    /// This method is used to set the properties of the `HttpClient` instance using an `Request`
    /// instance. This version of the method is used when the target architecture is `wasm32`.
    ///
    /// # Arguments
    ///
    /// * `request` - An instance of `Request` which includes the HTTP method, URL, body, headers,
    ///   and mode.
    ///
    /// # Returns
    ///
    /// * `Self` - Returns the instance of the `HttpClient` struct, allowing for method chaining.
    ///
    /// # Examples
    ///
    /// ```
    /// use bevy_http_client::HttpClient;
    /// use ehttp::{Request, Headers, Mode};
    ///
    /// let request = Request {
    ///     method: "POST".to_string(),
    ///     url: "http://example.com".to_string(),
    ///     body: vec![],
    ///     headers: Headers::new(&[("Content-Type", "application/json"), ("Accept", "*/*")]),
    ///     mode: Mode::Cors,
    /// };
    /// let http_client = HttpClient::new().request(request);
    /// ```
    #[cfg(target_arch = "wasm32")]
    pub fn request(mut self, request: Request) -> Self {
        self.method = Some(request.method);
        self.url = Some(request.url);
        self.body = request.body;
        self.headers = Some(request.headers);
        self.mode = request.mode;

        self
    }

    /// Builds an `HttpRequest` from the `HttpClient` instance.
    ///
    /// This method is used to construct an `HttpRequest` from the current state of the `HttpClient`
    /// instance. The resulting `HttpRequest` includes the HTTP method, URL, body, headers, and mode
    /// (only available on wasm builds).
    ///
    /// # Returns
    ///
    /// An `HttpRequest` instance which includes the HTTP method, URL, body, headers, and mode (only
    /// available on wasm builds).
    ///
    /// # Panics
    ///
    /// This method will panic if the HTTP method, URL, or headers are not set in the `HttpClient`
    /// instance.
    ///
    /// # Examples
    ///
    /// ```
    /// use bevy_http_client::HttpClient;
    /// use serde::Serialize;
    ///
    /// #[derive(Serialize)]
    /// struct MyData { name: String }
    /// let data = MyData { name: "test".to_string() };
    ///
    /// let http_request = HttpClient::new().post("http://example.com")
    ///     .headers(&[("Content-Type", "application/json"), ("Accept", "*/*")])
    ///     .json(&data)
    ///     .build();
    /// ```
    ///
    /// # Note
    ///
    /// This method consumes the `HttpClient` instance, meaning it can only be called once per
    /// instance.
    #[deprecated(
        since = "0.8.3",
        note = "Use `try_build()` instead for better error handling"
    )]
    pub fn build(self) -> HttpRequest {
        HttpRequest {
            from_entity: self.from_entity,
            request: Request {
                method: self.method.expect("method is required"),
                url: self.url.expect("url is required"),
                body: self.body,
                headers: self.headers.expect("headers is required"),
                #[cfg(target_arch = "wasm32")]
                mode: self.mode,
            },
        }
    }

    /// Safe version of build() that returns a Result instead of panicking
    ///
    /// This method safely builds an `HttpRequest` from the `HttpClient` instance.
    /// Returns an error if required fields (method, url, headers) are missing.
    ///
    /// # Returns
    ///
    /// * `Ok(HttpRequest)` - Successfully built HTTP request
    /// * `Err(HttpClientBuilderError)` - Missing required fields
    ///
    /// # Examples
    ///
    /// ```
    /// use bevy_http_client::HttpClient;
    ///
    /// let result = HttpClient::new().post("http://example.com")
    ///     .headers(&[("Content-Type", "application/json")])
    ///     .try_build();
    ///
    /// match result {
    ///     Ok(request) => { /* use request */ },
    ///     Err(e) => eprintln!("Build failed: {}", e),
    /// }
    /// ```
    pub fn try_build(self) -> Result<HttpRequest, HttpClientBuilderError> {
        let method = self.method.ok_or(HttpClientBuilderError::MissingMethod)?;
        let url = self
            .url
            .filter(|u| !u.trim().is_empty())
            .ok_or(HttpClientBuilderError::MissingUrl)?;
        let headers = self.headers.ok_or(HttpClientBuilderError::MissingHeaders)?;

        Ok(HttpRequest {
            from_entity: self.from_entity,
            request: Request {
                method,
                url,
                body: self.body,
                headers,
                #[cfg(target_arch = "wasm32")]
                mode: self.mode,
            },
        })
    }

    #[deprecated(
        since = "0.8.3",
        note = "Use `try_with_type()` instead for better error handling"
    )]
    pub fn with_type<T: Send + Sync + 'static + for<'a> serde::Deserialize<'a>>(
        self,
    ) -> TypedRequest<T> {
        TypedRequest::new(
            Request {
                method: self.method.expect("method is required"),
                url: self.url.expect("url is required"),
                body: self.body,
                headers: self.headers.expect("headers is required"),
                #[cfg(target_arch = "wasm32")]
                mode: self.mode,
            },
            self.from_entity,
        )
    }

    /// Safe version of with_type() that returns a Result instead of panicking
    ///
    /// This method safely creates a typed request from the `HttpClient` instance.
    /// Returns an error if required fields (method, url, headers) are missing.
    ///
    /// # Type Parameters
    ///
    /// * `T` - The expected response type that implements Deserialize
    ///
    /// # Returns
    ///
    /// * `Ok(TypedRequest<T>)` - Successfully built typed request
    /// * `Err(HttpClientBuilderError)` - Missing required fields
    ///
    /// # Examples
    ///
    /// ```
    /// use bevy_http_client::HttpClient;
    /// use serde::Deserialize;
    ///
    /// #[derive(Deserialize)]
    /// struct MyResponseType { id: u32, name: String }
    ///
    /// let result = HttpClient::new().get("https://api.example.com")
    ///     .try_with_type::<MyResponseType>();
    ///
    /// match result {
    ///     Ok(request) => { /* use typed request */ },
    ///     Err(e) => eprintln!("Build failed: {}", e),
    /// }
    /// ```
    pub fn try_with_type<T: Send + Sync + 'static + for<'a> serde::Deserialize<'a>>(
        self,
    ) -> Result<TypedRequest<T>, HttpClientBuilderError> {
        let method = self.method.ok_or(HttpClientBuilderError::MissingMethod)?;
        let url = self
            .url
            .filter(|u| !u.trim().is_empty())
            .ok_or(HttpClientBuilderError::MissingUrl)?;
        let headers = self.headers.ok_or(HttpClientBuilderError::MissingHeaders)?;

        Ok(TypedRequest::new(
            Request {
                method,
                url,
                body: self.body,
                headers,
                #[cfg(target_arch = "wasm32")]
                mode: self.mode,
            },
            self.from_entity,
        ))
    }
}

/// wrap for ehttp response
#[derive(Event, Message, Debug, Clone, Deref)]
pub struct HttpResponse(pub Response);

/// wrap for ehttp error
#[derive(Event, Message, Debug, Clone, Deref)]
pub struct HttpResponseError {
    pub err: String,
}

impl HttpResponseError {
    pub fn new(err: String) -> Self {
        Self { err }
    }
}

/// task for ehttp response result
#[derive(Component, Debug)]
pub struct RequestTask {
    tx: Sender<CommandQueue>,
    rx: Receiver<CommandQueue>,
}

fn handle_request(
    mut commands: Commands,
    mut req_res: ResMut<HttpClientSetting>,
    mut requests: MessageReader<HttpRequest>,
    q_tasks: Query<&RequestTask>,
) {
    let thread_pool = IoTaskPool::get();
    for request in requests.read() {
        if req_res.is_available() {
            let req = request.clone();
            let (entity, has_from_entity) = if let Some(entity) = req.from_entity {
                (entity, true)
            } else {
                (commands.spawn_empty().id(), false)
            };

            let tx = get_channel(&mut commands, q_tasks, entity);

            thread_pool
                .spawn(async move {
                    let mut command_queue = CommandQueue::default();

                    let response = ehttp::fetch_async(req.request).await;
                    command_queue.push(move |world: &mut World| {
                        match response {
                            Ok(res) => {
                                if let Some(mut events) =
                                    world.get_resource_mut::<Messages<HttpResponse>>()
                                {
                                    events.write(HttpResponse(res.clone()));
                                } else {
                                    bevy_log::error!("HttpResponse events resource not found");
                                }
                                world.trigger(HttpObserved::new(entity, HttpResponse(res)));
                            }
                            Err(e) => {
                                if let Some(mut events) =
                                    world.get_resource_mut::<Messages<HttpResponseError>>()
                                {
                                    events.write(HttpResponseError::new(e.to_string()));
                                } else {
                                    bevy_log::error!("HttpResponseError events resource not found");
                                }
                                world.trigger(HttpObserved::new(
                                    entity,
                                    HttpResponseError::new(e.to_string()),
                                ));
                            }
                        }

                        if !has_from_entity {
                            world.entity_mut(entity).despawn();
                        }
                    });

                    if let Err(e) = tx.send(command_queue) {
                        bevy_log::error!("Failed to send command queue: {}", e);
                    }
                })
                .detach();

            req_res.current_clients += 1;
        }
    }
}

fn get_channel(
    commands: &mut Commands,
    q_tasks: Query<&RequestTask>,
    entity: Entity,
) -> Sender<CommandQueue> {
    if let Ok(task) = q_tasks.get(entity) {
        task.tx.clone()
    } else {
        let (tx, rx) = crossbeam_channel::bounded(5);

        commands.entity(entity).insert(RequestTask {
            tx: tx.clone(),
            rx: rx.clone(),
        });

        tx
    }
}

fn handle_tasks(
    mut commands: Commands,
    mut req_res: ResMut<HttpClientSetting>,
    mut request_tasks: Query<&RequestTask>,
) {
    for task in request_tasks.iter_mut() {
        if let Ok(mut command_queue) = task.rx.try_recv() {
            commands.append(&mut command_queue);
            req_res.current_clients -= 1;
        }
    }
}