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
use bevy::prelude::*;
use bevy::tasks::AsyncComputeTaskPool;
pub use reqwest;

#[cfg(target_family = "wasm")]
use crossbeam_channel::{bounded, Receiver};

#[cfg(not(target_family = "wasm"))]
use {bevy::tasks::Task, futures_lite::future};

#[derive(Resource)]
pub struct ReqwestClient(pub reqwest::Client);
impl Default for ReqwestClient {
    fn default() -> Self {
        Self(reqwest::Client::new())
    }
}

/// we have to use an option to be able to ".take()" later
#[derive(Component, Deref)]
pub struct ReqwestRequest(pub Option<reqwest::Request>);

impl Into<ReqwestRequest> for reqwest::Request {
    fn into(self) -> ReqwestRequest {
        ReqwestRequest(Some(self))
    }
}

#[cfg(target_family = "wasm")]
#[derive(Component, Deref)]
struct ReqwestInflight(pub Receiver<reqwest::Result<bytes::Bytes>>);

// Dont touch these, its just to poll once every request
#[cfg(not(target_family = "wasm"))]
#[derive(Component, Deref)]
struct ReqwestInflight(pub Task<reqwest::Result<bytes::Bytes>>);

#[derive(Component, Deref)]
pub struct ReqwestBytesResult(pub reqwest::Result<bytes::Bytes>);

impl ReqwestBytesResult {
    pub fn as_str(&self) -> Option<&str> {
        match &self.0 {
            Ok(string) => Some(std::str::from_utf8(&string).ok()?),
            Err(_) => None,
        }
    }
    pub fn as_string(&mut self) -> Option<String> {
        Some(self.as_str()?.into())
    }
    pub fn deserialize_json<'de, T: serde::Deserialize<'de>>(&'de mut self) -> Option<T> {
        serde_json::from_str(self.as_str()?).ok()
    }
}

pub struct ReqwestPlugin;
impl Plugin for ReqwestPlugin {
    fn build(&self, app: &mut App) {
        if !app.world.contains_resource::<ReqwestClient>() {
            app.init_resource::<ReqwestClient>();
        }
        app.add_system(Self::start_handling_requests);
        app.add_system(Self::poll_inflight_requests_to_bytes);
    }
}

//TODO: Make type generic, and we can create systems for JSON and TEXT requests
impl ReqwestPlugin {
    fn start_handling_requests(
        mut commands: Commands,
        http_client: ResMut<ReqwestClient>,
        mut requests: Query<(Entity, &mut ReqwestRequest), Added<ReqwestRequest>>,
    ) {
        let thread_pool = AsyncComputeTaskPool::get();
        for (entity, mut request) in requests.iter_mut() {
            bevy::log::debug!("Creating: {entity:?}");
            // if we take the data, we can use it
            if let Some(request) = request.0.take() {
                let client = http_client.0.clone();

                // wasm implementation
                #[cfg(target_family = "wasm")]
                let (tx, task) = bounded(1);
                #[cfg(target_family = "wasm")]
                thread_pool
                    .spawn(async move {
                        let r = client.execute(request).await;
                        let r = match r {
                            Ok(res) => res.bytes().await,
                            Err(r) => Err(r),
                        };
                        tx.send(r).ok();
                    })
                    .detach();

                // otherwise
                #[cfg(not(target_family = "wasm"))]
                let task = {
                    thread_pool.spawn(async move {
                        #[cfg(not(target_family = "wasm"))]
                        let r = async_compat::Compat::new(async {
                            client.execute(request).await?.bytes().await
                        })
                        .await;
                        r
                    })
                };
                // put it as a component to be polled, and remove the request, it has been handled
                commands.entity(entity).insert(ReqwestInflight(task));
                commands.entity(entity).remove::<ReqwestRequest>();
            }
        }
    }

    fn poll_inflight_requests_to_bytes(
        mut commands: Commands,
        // Very important to have the Without, otherwise we get task failure upon completed task
        mut requests: Query<(Entity, &mut ReqwestInflight), Without<ReqwestBytesResult>>,
    ) {
        for (entity, mut request) in requests.iter_mut() {
            bevy::log::debug!("polling: {entity:?}");

            #[cfg(target_family = "wasm")]
            if let Ok(result) = request.0.try_recv() {
                // move the result over to a new component
                commands
                    .entity(entity)
                    .insert(ReqwestBytesResult(result))
                    .remove::<ReqwestRequest>();
            }

            #[cfg(not(target_family = "wasm"))]
            if let Some(result) = future::block_on(future::poll_once(&mut request.0)) {
                // move the result over to a new component
                commands
                    .entity(entity)
                    .insert(ReqwestBytesResult(result))
                    .remove::<ReqwestRequest>();
            }
        }
    }
}