Skip to main content

eggfetch_node/
client.rs

1//! Eggfetch Client for Node.js.
2
3use napi_derive::napi;
4use std::ptr;
5
6use eggfetch_ffi::ErrorHandle;
7
8/// Shared ownership for the FFI client handle.
9///
10/// In-flight requests hold an `Arc` clone for the duration of the
11/// `spawn_blocking` future, so `Drop for EggfetchClient` cannot free the
12/// handle while a request is outstanding. This does not rely on napi-rs
13/// `this`-reference tracking (napi 2.x codegen); the `napi = "2"` pin in
14/// `crates/eggfetch-node/Cargo.toml` must be kept with this comment.
15struct ClientHandleInner {
16    ptr: std::sync::Mutex<*mut eggfetch_ffi::ClientHandle>,
17}
18
19// SAFETY: the pointee is `Send + Sync` per eggfetch-ffi; the raw pointer is
20// only accessed under the mutex and is freed exactly once by
21// `Drop for ClientHandleInner`.
22unsafe impl Send for ClientHandleInner {}
23unsafe impl Sync for ClientHandleInner {}
24
25impl Drop for ClientHandleInner {
26    fn drop(&mut self) {
27        // Free even on poison (no leak); poison reports the inner ptr.
28        let mut guard = self
29            .ptr
30            .lock()
31            .unwrap_or_else(std::sync::PoisonError::into_inner);
32        let ptr = std::mem::replace(&mut *guard, std::ptr::null_mut());
33        if !ptr.is_null() {
34            unsafe {
35                eggfetch_ffi::eggfetch_client_free(ptr);
36            }
37        }
38    }
39}
40
41/// HTTP client wrapping eggfetch-ffi.
42///
43/// The underlying `ClientHandle` is shared via `Arc<ClientHandleInner>` so
44/// in-flight `spawn_blocking` requests extend its lifetime independently of
45/// napi-rs finalization order. The raw pointer preserves provenance (no
46/// `usize ↔ *mut` round-trip); the underlying `ClientHandle` is `Send + Sync`
47/// per eggfetch-ffi documentation.
48///
49/// # Lifetime safety for in-flight requests
50///
51/// Each request clones the `Arc` into its `'static` future before entering
52/// `spawn_blocking`. `Drop for ClientHandleInner` frees the FFI handle only
53/// when the last clone (client plus all in-flight requests) is dropped, so
54/// a JS garbage-collection of the client object cannot free the handle
55/// underneath a running request. Do not replace this with a pattern that
56/// frees the handle from `Drop for EggfetchClient` directly without holding
57/// the shared `Arc` alive in the future.
58///
59/// This remains an experimental prototype (see `lib.rs`): requests execute
60/// through the synchronous C ABI inside `spawn_blocking`.
61#[napi]
62pub struct EggfetchClient {
63    inner: std::sync::Arc<ClientHandleInner>,
64}
65
66#[napi]
67impl EggfetchClient {
68    /// Create a new client with default settings.
69    ///
70    /// # Errors
71    ///
72    /// Returns an error if the underlying FFI client allocation fails.
73    #[napi(constructor)]
74    pub fn new() -> napi::Result<Self> {
75        let inner = unsafe { eggfetch_ffi::eggfetch_client_new() };
76        if inner.is_null() {
77            return Err(napi::Error::from_reason(
78                "failed to create eggfetch client: allocation failed or runtime unavailable",
79            ));
80        }
81        Ok(Self {
82            inner: std::sync::Arc::new(ClientHandleInner {
83                ptr: std::sync::Mutex::new(inner),
84            }),
85        })
86    }
87
88    /// Send a GET request and return the response.
89    ///
90    /// # Errors
91    ///
92    /// Returns an error if the request fails or the URL is invalid.
93    #[napi]
94    pub async fn get(&self, url: String) -> napi::Result<crate::EggfetchResponse> {
95        self.send_request("GET", &url, None).await
96    }
97
98    /// Send a POST request with optional body.
99    ///
100    /// # Errors
101    ///
102    /// Returns an error if the request fails or the URL/body is invalid.
103    #[napi]
104    pub async fn post(
105        &self,
106        url: String,
107        body: Option<String>,
108    ) -> napi::Result<crate::EggfetchResponse> {
109        self.send_request("POST", &url, body.as_deref()).await
110    }
111
112    /// Send a PUT request with optional body.
113    ///
114    /// # Errors
115    ///
116    /// Returns an error if the request fails or the URL/body is invalid.
117    #[napi]
118    pub async fn put(
119        &self,
120        url: String,
121        body: Option<String>,
122    ) -> napi::Result<crate::EggfetchResponse> {
123        self.send_request("PUT", &url, body.as_deref()).await
124    }
125
126    /// Send a PATCH request with optional body.
127    ///
128    /// # Errors
129    ///
130    /// Returns an error if the request fails or the URL/body is invalid.
131    #[napi]
132    pub async fn patch(
133        &self,
134        url: String,
135        body: Option<String>,
136    ) -> napi::Result<crate::EggfetchResponse> {
137        self.send_request("PATCH", &url, body.as_deref()).await
138    }
139
140    /// Send a DELETE request.
141    ///
142    /// # Errors
143    ///
144    /// Returns an error if the request fails or the URL is invalid.
145    #[napi]
146    pub async fn delete(&self, url: String) -> napi::Result<crate::EggfetchResponse> {
147        self.send_request("DELETE", &url, None).await
148    }
149
150    /// Send a HEAD request.
151    ///
152    /// # Errors
153    ///
154    /// Returns an error if the request fails or the URL is invalid.
155    #[napi]
156    pub async fn head(&self, url: String) -> napi::Result<crate::EggfetchResponse> {
157        self.send_request("HEAD", &url, None).await
158    }
159
160    /// Send an OPTIONS request.
161    ///
162    /// # Errors
163    ///
164    /// Returns an error if the request fails or the URL is invalid.
165    #[napi]
166    pub async fn options(&self, url: String) -> napi::Result<crate::EggfetchResponse> {
167        self.send_request("OPTIONS", &url, None).await
168    }
169
170    /// Send a request with a custom method.
171    ///
172    /// The optional body is UTF-8 text only; arbitrary binary payloads
173    /// (interior NUL) are rejected with an error. Use a byte-oriented
174    /// API for binary uploads.
175    ///
176    /// # Errors
177    ///
178    /// Returns an error if the request fails or the method/URL is invalid.
179    #[napi]
180    pub async fn request(
181        &self,
182        method: String,
183        url: String,
184        body: Option<String>,
185    ) -> napi::Result<crate::EggfetchResponse> {
186        self.send_request(&method, &url, body.as_deref()).await
187    }
188}
189
190impl EggfetchClient {
191    fn send_request(
192        &self,
193        method: &str,
194        url: &str,
195        body: Option<&str>,
196    ) -> impl std::future::Future<Output = napi::Result<crate::EggfetchResponse>> + Send {
197        // Clone the shared handle so the FFI client outlives this future
198        // even if the JS object is collected first.
199        let shared = std::sync::Arc::clone(&self.inner);
200        let method = method.to_owned();
201        let url = url.to_owned();
202        let body = body.map(String::from);
203
204        async move {
205            napi::bindgen_prelude::spawn_blocking(move || {
206                let client = shared
207                    .ptr
208                    .lock()
209                    .map_or(std::ptr::null_mut(), |guard| *guard);
210                if client.is_null() {
211                    return Err(napi::Error::from_reason("client is closed"));
212                }
213                // Keep `shared` alive for the whole blocking section.
214                let _keep_alive = &shared;
215                let method_c = std::ffi::CString::new(method)
216                    .map_err(|e| napi::Error::from_reason(format!("invalid method string: {e}")))?;
217                let url_c = std::ffi::CString::new(url)
218                    .map_err(|e| napi::Error::from_reason(format!("invalid url string: {e}")))?;
219
220                let req = unsafe {
221                    eggfetch_ffi::eggfetch_client_request(client, method_c.as_ptr(), url_c.as_ptr())
222                };
223                if req.is_null() {
224                    return Err(napi::Error::from_reason("failed to create request"));
225                }
226
227                if let Some(body_str) = &body {
228                    let body_c = match std::ffi::CString::new(body_str.as_str()) {
229                        Ok(body_c) => body_c,
230                        Err(e) => {
231                            unsafe {
232                                eggfetch_ffi::eggfetch_request_free(req);
233                            }
234                            return Err(napi::Error::from_reason(format!(
235                                "invalid body string: {e}"
236                            )));
237                        }
238                    };
239                    let rc =
240                        unsafe { eggfetch_ffi::eggfetch_request_body_str(req, body_c.as_ptr()) };
241                    if rc != 0 {
242                        unsafe {
243                            eggfetch_ffi::eggfetch_request_free(req);
244                        }
245                        return Err(napi::Error::from_reason(format!(
246                            "failed to set request body (code {rc})"
247                        )));
248                    }
249                }
250
251                let mut err: *mut ErrorHandle = ptr::null_mut();
252                let resp = unsafe { eggfetch_ffi::eggfetch_client_send(client, req, &raw mut err) };
253
254                if resp.is_null() {
255                    if !err.is_null() {
256                        let kind = unsafe { eggfetch_ffi::eggfetch_error_kind(err) };
257                        let msg = unsafe { eggfetch_ffi::eggfetch_error_message(err) };
258                        let kind_str = if kind.is_null() {
259                            "unknown".to_owned()
260                        } else {
261                            unsafe { std::ffi::CStr::from_ptr(kind) }
262                                .to_string_lossy()
263                                .into_owned()
264                        };
265                        let msg_str = if msg.is_null() {
266                            "unknown error".to_owned()
267                        } else {
268                            unsafe { std::ffi::CStr::from_ptr(msg) }
269                                .to_string_lossy()
270                                .into_owned()
271                        };
272                        unsafe {
273                            if !kind.is_null() {
274                                eggfetch_ffi::eggfetch_string_free(kind);
275                            }
276                            if !msg.is_null() {
277                                eggfetch_ffi::eggfetch_string_free(msg);
278                            }
279                            eggfetch_ffi::eggfetch_error_free(err);
280                        }
281                        return Err(napi::Error::from_reason(format!(
282                            "eggfetch error [{kind_str}]: {msg_str}"
283                        )));
284                    }
285                    return Err(napi::Error::from_reason(
286                        "request failed with unknown error",
287                    ));
288                }
289
290                crate::EggfetchResponse::from_raw(resp)
291            })
292            .await
293            .map_err(|e| napi::Error::from_reason(format!("request worker failed: {e}")))?
294        }
295    }
296}