frakt 0.1.0

Ergonomic platform HTTP client bindings for Rust
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
#![allow(non_snake_case)]

//! Foundation backend using NSURLSession

/// Foundation delegate implementations
pub mod delegate;

/// Foundation cookie storage implementation
pub mod cookies;
pub use cookies::FoundationCookieStorage;

/// Foundation WebSocket implementation
pub mod websocket;
pub use websocket::{FoundationWebSocket, FoundationWebSocketBuilder};

/// Foundation error handling
pub mod error;

use crate::backend::types::{BackendRequest, BackendResponse};
use crate::{Error, Result};
use block2::StackBlock;
use objc2::rc::Retained;
use objc2::runtime::AnyObject;
use objc2::runtime::Bool;
use objc2::runtime::ProtocolObject;
use objc2_foundation::{NSHTTPURLResponse, NSMutableURLRequest, NSString, NSURL, NSURLSession};
use std::ptr::NonNull;
use tokio::sync::mpsc;
use url::Url;

/// Foundation backend using NSURLSession
#[derive(Clone)]
pub struct FoundationBackend {
    session: Retained<NSURLSession>,
    delegate: Retained<delegate::DataTaskDelegate>,
    cookie_jar: Option<crate::CookieJar>,
    default_headers: Option<http::HeaderMap>,
}

impl FoundationBackend {
    /// Create a new Foundation backend with default configuration
    pub fn new() -> Result<Self> {
        // Create delegate and session with delegate
        let delegate = delegate::DataTaskDelegate::new();
        let session = unsafe {
            NSURLSession::sessionWithConfiguration_delegate_delegateQueue(
                &objc2_foundation::NSURLSessionConfiguration::defaultSessionConfiguration(),
                Some(ProtocolObject::from_ref(&*delegate)),
                None,
            )
        };

        Ok(Self {
            session,
            delegate,
            cookie_jar: None,
            default_headers: None,
        })
    }

    /// Create a new Foundation backend with custom session configuration
    pub fn with_session(
        session: Retained<NSURLSession>,
        delegate: Retained<delegate::DataTaskDelegate>,
    ) -> Self {
        Self {
            session,
            delegate,
            cookie_jar: None,
            default_headers: None,
        }
    }

    /// Create a new Foundation backend with configuration
    pub fn with_config(config: crate::backend::BackendConfig) -> Result<Self> {
        let delegate = delegate::DataTaskDelegate::new();

        let session_config =
            unsafe { objc2_foundation::NSURLSessionConfiguration::defaultSessionConfiguration() };

        // Apply timeout configuration
        if let Some(timeout) = config.timeout {
            unsafe {
                session_config.setTimeoutIntervalForRequest(timeout.as_secs_f64());
            }
        }

        // Other configuration options like default headers are stored in the backend
        // and applied to individual requests

        let session = unsafe {
            NSURLSession::sessionWithConfiguration_delegate_delegateQueue(
                &session_config,
                Some(ProtocolObject::from_ref(&*delegate)),
                None,
            )
        };

        Ok(Self {
            session,
            delegate,
            cookie_jar: config.cookie_jar,
            default_headers: config.default_headers,
        })
    }

    /// Get the underlying NSURLSession (for WebSocket support)
    pub fn session(&self) -> &Retained<NSURLSession> {
        &self.session
    }

    /// Execute an HTTP request using NSURLSession
    pub async fn execute(&self, request: BackendRequest) -> Result<BackendResponse> {
        // Create NSURLRequest and validate URL
        let nsurl = unsafe {
            NSURL::URLWithString(&NSString::from_str(&request.url.as_str()))
                .ok_or(Error::InvalidUrl)?
        };

        // Validate URL scheme using Foundation APIs
        let scheme = unsafe { nsurl.scheme() };
        if let Some(scheme_str) = scheme {
            let scheme_string = scheme_str.to_string();
            match scheme_string.as_str() {
                "http" | "https" => {}
                _ => {
                    return Err(Error::InvalidUrl);
                }
            }
        } else {
            return Err(Error::InvalidUrl);
        }

        let nsrequest = unsafe {
            let req = NSMutableURLRequest::requestWithURL(&nsurl);
            req.setHTTPMethod(&NSString::from_str(request.method.as_str()));

            // Set default headers first
            if let Some(ref default_headers) = self.default_headers {
                for (name, value) in default_headers {
                    req.setValue_forHTTPHeaderField(
                        Some(&NSString::from_str(
                            value.to_str().expect("Invalid default header value"),
                        )),
                        &NSString::from_str(name.as_str()),
                    );
                }
            }

            // Set request headers (these can override default headers)
            for (name, value) in &request.headers {
                req.setValue_forHTTPHeaderField(
                    Some(&NSString::from_str(
                        value.to_str().expect("Invalid header value"),
                    )),
                    &NSString::from_str(name.as_str()),
                );
            }

            // Set body
            if let Some(body) = &request.body {
                match body {
                    crate::body::Body::Empty => {}
                    crate::body::Body::Bytes {
                        content,
                        content_type,
                    } => {
                        req.setValue_forHTTPHeaderField(
                            Some(&NSString::from_str(content_type)),
                            &NSString::from_str("Content-Type"),
                        );
                        let nsdata = objc2_foundation::NSData::from_vec(content.to_vec());
                        req.setHTTPBody(Some(&nsdata));
                    }
                    crate::body::Body::Form { fields } => {
                        req.setValue_forHTTPHeaderField(
                            Some(&NSString::from_str("application/x-www-form-urlencoded")),
                            &NSString::from_str("Content-Type"),
                        );
                        let encoded = encode_form_fields(fields);
                        let nsdata = objc2_foundation::NSData::from_vec(encoded.into_bytes());
                        req.setHTTPBody(Some(&nsdata));
                    }
                    #[cfg(feature = "json")]
                    crate::body::Body::Json { value } => {
                        req.setValue_forHTTPHeaderField(
                            Some(&NSString::from_str("application/json")),
                            &NSString::from_str("Content-Type"),
                        );
                        let json_bytes = serde_json::to_vec(value)?;
                        let nsdata = objc2_foundation::NSData::from_vec(json_bytes);
                        req.setHTTPBody(Some(&nsdata));
                    }
                    #[cfg(feature = "multipart")]
                    crate::body::Body::Multipart { parts } => {
                        let boundary = generate_boundary();
                        let content_type = format!("multipart/form-data; boundary={}", boundary);
                        req.setValue_forHTTPHeaderField(
                            Some(&NSString::from_str(&content_type)),
                            &NSString::from_str("Content-Type"),
                        );
                        let multipart_data = encode_multipart_data(&boundary, parts)?;
                        let nsdata = objc2_foundation::NSData::from_vec(multipart_data);
                        req.setHTTPBody(Some(&nsdata));
                    }
                }
            }

            req
        };

        // Create task context with progress callback if present
        let task_context = if let Some(progress_callback) = request.progress_callback {
            std::sync::Arc::new(
                delegate::shared_context::TaskSharedContext::with_progress_callback(
                    progress_callback,
                ),
            )
        } else {
            std::sync::Arc::new(delegate::shared_context::TaskSharedContext::new())
        };

        // Create data task
        let data_task = unsafe { self.session.dataTaskWithRequest(&nsrequest) };

        // Register the task context with the delegate using the task identifier
        let task_id = unsafe { data_task.taskIdentifier() } as usize;
        self.delegate.register_task(task_id, task_context.clone());

        // Create channel for response body
        let (tx, rx) = mpsc::channel(32);

        // Start task
        unsafe {
            data_task.resume();
        }

        // Wait for response headers
        while !task_context.is_completed() && task_context.response.load_full().is_none() {
            tokio::task::yield_now().await;
        }

        // Check for errors
        if let Some(error) = task_context.error.load_full() {
            return Err(Error::from_ns_error(&*error));
        }

        // Get response
        let response = task_context
            .response
            .load_full()
            .ok_or_else(|| Error::Internal("No response received".to_string()))?;

        let status = unsafe {
            // Try to cast to NSHTTPURLResponse to get status code
            let http_response: Option<&NSHTTPURLResponse> = response.as_ref().downcast_ref();
            if let Some(http_response) = http_response {
                http_response.statusCode() as u16
            } else {
                200
            }
        };
        let status_code = http::StatusCode::from_u16(status as u16).unwrap_or(http::StatusCode::OK);

        // Extract headers from NSHTTPURLResponse
        let mut headers = http::HeaderMap::new();

        unsafe {
            if let Some(http_response) = response.as_ref().downcast_ref::<NSHTTPURLResponse>() {
                let all_headers = http_response.allHeaderFields();

                use std::cell::RefCell;
                use std::sync::Arc;

                let headers_cell = Arc::new(RefCell::new(http::HeaderMap::new()));
                let headers_cell_clone = headers_cell.clone();

                let closure = move |key: NonNull<AnyObject>,
                                    value: NonNull<AnyObject>,
                                    _stop: NonNull<Bool>| {
                    // Cast to NSString
                    if let Some(key_nsstring) = key.as_ref().downcast_ref::<NSString>() {
                        if let Some(value_nsstring) = value.as_ref().downcast_ref::<NSString>() {
                            let key_str = key_nsstring.to_string();
                            let value_str = value_nsstring.to_string();

                            // Convert to http types and insert
                            if let (Ok(header_name), Ok(header_value)) = (
                                http::HeaderName::from_bytes(key_str.as_bytes()),
                                http::HeaderValue::from_str(&value_str),
                            ) {
                                headers_cell_clone
                                    .borrow_mut()
                                    .insert(header_name, header_value);
                            }
                        }
                    }
                };

                // Transform FnMut to Fn using RefCell
                let block = StackBlock::new(
                    move |key: NonNull<AnyObject>,
                          value: NonNull<AnyObject>,
                          stop: NonNull<Bool>| { closure(key, value, stop) },
                );

                // Call enumerateKeysAndObjectsUsingBlock
                let _: () =
                    objc2::msg_send![&*all_headers, enumerateKeysAndObjectsUsingBlock: &*block];
                drop(block);

                // Extract the final headers
                headers = Arc::try_unwrap(headers_cell)
                    .unwrap_or_else(|_| panic!("Headers RefCell still has references"))
                    .into_inner();
            }
        }

        // Spawn task to read body data
        let body_context = task_context.clone();
        tokio::spawn(async move {
            while !body_context.is_completed() {
                let data = body_context.response_buffer.lock().await.clone();
                if !data.is_empty() {
                    let bytes = bytes::Bytes::from(data);
                    if tx.send(Ok(bytes)).await.is_err() {
                        break;
                    }
                    // Clear the buffer
                    body_context.response_buffer.lock().await.clear();
                }
                tokio::task::yield_now().await;
            }

            // Send any remaining data when task completes
            let final_data = body_context.response_buffer.lock().await.clone();
            if !final_data.is_empty() {
                let bytes = bytes::Bytes::from(final_data);
                let _ = tx.send(Ok(bytes)).await;
            }
        });

        Ok(BackendResponse {
            status: status_code,
            headers,
            body_receiver: rx,
        })
    }

    /// Execute a background download
    pub async fn execute_background_download(
        &self,
        url: Url,
        file_path: std::path::PathBuf,
        session_identifier: Option<String>,
        progress_callback: Option<Box<dyn Fn(u64, Option<u64>) + Send + Sync + 'static>>,
    ) -> Result<crate::client::download::DownloadResponse> {
        use delegate::background_session::BackgroundSessionDelegate;
        use delegate::shared_context::TaskSharedContext;
        use objc2_foundation::NSURLSessionConfiguration;
        use std::sync::Arc;

        // Generate session identifier if not provided
        let session_id = session_identifier.unwrap_or_else(|| {
            format!(
                "frakt-bg-{}-{}",
                std::process::id(),
                std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap_or_default()
                    .as_secs()
            )
        });

        // Create background session configuration
        let session_config = unsafe {
            NSURLSessionConfiguration::backgroundSessionConfigurationWithIdentifier(
                &NSString::from_str(&session_id),
            )
        };

        // Create background delegate
        let delegate = BackgroundSessionDelegate::new();
        let session = unsafe {
            NSURLSession::sessionWithConfiguration_delegate_delegateQueue(
                &session_config,
                Some(ProtocolObject::from_ref(&*delegate)),
                None,
            )
        };

        // Create download task
        let nsurl = unsafe {
            NSURL::URLWithString(&NSString::from_str(url.as_str())).ok_or(Error::InvalidUrl)?
        };

        let download_task = unsafe { session.downloadTaskWithURL(&nsurl) };
        let task_id = unsafe { download_task.taskIdentifier() } as usize;

        // Create task context
        let mut task_context = if let Some(callback) = progress_callback {
            TaskSharedContext::with_progress_callback(Arc::new(callback))
        } else {
            TaskSharedContext::new()
        };

        task_context.download_context = Some(Arc::new(
            delegate::shared_context::DownloadContext::new(Some(file_path.clone())),
        ));

        let task_context = Arc::new(task_context);

        // Register task with delegate
        delegate.register_task(task_id, task_context.clone());

        // Start download
        unsafe {
            download_task.resume();
        }

        // Wait for completion
        while !task_context.is_completed() {
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        }

        // Check for errors
        if let Some(error) = task_context.error.load_full() {
            return Err(Error::from_ns_error(&*error));
        }

        // Calculate bytes downloaded
        let bytes_downloaded = task_context
            .bytes_downloaded
            .load(std::sync::atomic::Ordering::Relaxed);

        Ok(crate::client::download::DownloadResponse {
            file_path,
            bytes_downloaded,
        })
    }

    /// Get the cookie jar if configured
    pub fn cookie_jar(&self) -> Option<&crate::CookieJar> {
        self.cookie_jar.as_ref()
    }
}

fn encode_form_fields(
    fields: &[(
        std::borrow::Cow<'static, str>,
        std::borrow::Cow<'static, str>,
    )],
) -> String {
    fields
        .iter()
        .map(|(k, v)| format!("{}={}", urlencoding::encode(k), urlencoding::encode(v)))
        .collect::<Vec<_>>()
        .join("&")
}

#[cfg(feature = "multipart")]
fn generate_boundary() -> String {
    use std::time::{SystemTime, UNIX_EPOCH};
    let timestamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_nanos();
    format!("----formdata-frakt-{}", timestamp)
}

#[cfg(feature = "multipart")]
fn encode_multipart_data(boundary: &str, parts: &[crate::body::MultipartPart]) -> Result<Vec<u8>> {
    let mut data = Vec::new();

    for part in parts {
        data.extend_from_slice(format!("\r\n--{}\r\n", boundary).as_bytes());

        let mut disposition = format!("Content-Disposition: form-data; name=\"{}\"", part.name);
        if let Some(filename) = &part.filename {
            disposition.push_str(&format!("; filename=\"{}\"", filename));
        }
        data.extend_from_slice(disposition.as_bytes());
        data.extend_from_slice(b"\r\n");

        if let Some(content_type) = &part.content_type {
            data.extend_from_slice(format!("Content-Type: {}\r\n", content_type).as_bytes());
        }

        data.extend_from_slice(b"\r\n");
        data.extend_from_slice(&part.content);
    }

    data.extend_from_slice(format!("\r\n--{}--\r\n", boundary).as_bytes());
    Ok(data)
}