-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
693 lines (610 loc) · 20.2 KB
/
lib.rs
File metadata and controls
693 lines (610 loc) · 20.2 KB
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
//! A Rust library for handling HTTP requests using a Python backend.
//!
//! This library provides a way to handle HTTP requests in Rust by delegating
//! the handling to a Python backend. It allows you to define a Python
//! handler that can process requests and return responses.
// #![deny(clippy::all)]
#![warn(clippy::dbg_macro, clippy::print_stdout)]
#![warn(missing_docs)]
#[cfg(feature = "napi-support")]
use std::{ffi::c_char, sync::Arc};
#[cfg(feature = "napi-support")]
use bytes::{Bytes, BytesMut};
#[cfg(feature = "napi-support")]
use http_handler::napi::{Request as NapiRequest, Response as NapiResponse};
#[cfg(feature = "napi-support")]
use http_handler::{BodyBuffer, Handler, Request, Response, ResponseBody};
#[cfg(feature = "napi-support")]
#[allow(unused_imports)]
use http_rewriter::napi::Rewriter;
#[cfg(feature = "napi-support")]
#[macro_use]
extern crate napi_derive;
#[cfg(feature = "napi-support")]
use napi::bindgen_prelude::*;
mod asgi;
use crate::asgi::HttpReceiveMessage;
pub use asgi::Asgi;
use tokio::sync::{mpsc::error::SendError, oneshot::error::RecvError};
/// The Python module and function for handling requests.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PythonHandlerTarget {
/// The name of the Python file (without the .py extension).
pub file: String,
/// The name of the function within the Python file that will handle requests.
pub function: String,
}
impl Default for PythonHandlerTarget {
fn default() -> Self {
PythonHandlerTarget {
file: "main".to_string(),
function: "app".to_string(),
}
}
}
impl TryFrom<&str> for PythonHandlerTarget {
type Error = String;
fn try_from(value: &str) -> std::result::Result<Self, String> {
let parts: Vec<&str> = value.split(':').collect();
if parts.len() != 2 {
return Err("Invalid format, expected \"file:function\"".to_string());
}
Ok(PythonHandlerTarget {
file: parts[0].to_string(),
function: parts[1].to_string(),
})
}
}
impl From<PythonHandlerTarget> for String {
fn from(target: PythonHandlerTarget) -> Self {
format!("{}:{}", target.file, target.function)
}
}
#[cfg(feature = "napi-support")]
impl FromNapiValue for PythonHandlerTarget {
unsafe fn from_napi_value(env: sys::napi_env, napi_val: sys::napi_value) -> Result<Self> {
use pyo3::ffi::c_str;
let mut result = PythonHandlerTarget {
file: String::new(),
function: String::new(),
};
let mut ty = 0;
unsafe { check_status!(sys::napi_typeof(env, napi_val, &mut ty)) }?;
if ty == sys::ValueType::napi_string {
let mut length: usize = 0;
unsafe {
check_status!(sys::napi_get_value_string_utf8(
env,
napi_val,
std::ptr::null_mut(),
0,
&mut length
))
}?;
let mut buffer = vec![0u8; length + 1];
unsafe {
check_status!(sys::napi_get_value_string_utf8(
env,
napi_val,
buffer.as_mut_ptr() as *mut c_char,
length + 1,
&mut length
))
}?;
let full_str = std::str::from_utf8(&buffer[..length])
.map_err(|_| Error::from_reason("Invalid UTF-8 string".to_string()))?;
result = full_str.try_into().map_err(Error::from_reason)?;
} else if ty == sys::ValueType::napi_object {
let mut file_val: sys::napi_value = std::ptr::null_mut();
let mut func_val: sys::napi_value = std::ptr::null_mut();
unsafe {
check_status!(sys::napi_get_named_property(
env,
napi_val,
c_str!("file").as_ptr(),
&mut file_val
))
}?;
unsafe {
check_status!(sys::napi_get_named_property(
env,
napi_val,
c_str!("function").as_ptr(),
&mut func_val
))
}?;
result.file = unsafe { String::from_napi_value(env, file_val) }?;
result.function = unsafe { String::from_napi_value(env, func_val) }?;
} else {
return Err(Error::from_reason(
"Expected string or object input".to_string(),
));
}
Ok(result)
}
}
#[cfg(feature = "napi-support")]
impl ToNapiValue for PythonHandlerTarget {
unsafe fn to_napi_value(env: sys::napi_env, val: Self) -> Result<sys::napi_value> {
let mut result: sys::napi_value = std::ptr::null_mut();
let full_str = format!("{}:{}", val.file, val.function);
unsafe {
check_status!(sys::napi_create_string_utf8(
env,
full_str.as_ptr() as *const c_char,
full_str.len() as isize,
&mut result
))
}?;
Ok(result)
}
}
/// Options for configuring the Python handler.
#[cfg_attr(feature = "napi-support", napi(object))]
#[derive(Clone, Debug, Default)]
pub struct PythonOptions {
/// The document root for the PHP instance.
pub docroot: Option<String>,
/// The name of the Python module and function which will handle requests.
/// Formatted as "module:function".
pub app_target: Option<PythonHandlerTarget>,
// /// Request rewriter
// pub rewriter: Option<Rewriter>,
}
/// A Python handler that can handle HTTP requests.
#[cfg(feature = "napi-support")]
#[napi(js_name = "Python")]
pub struct PythonHandler {
asgi: Arc<Asgi>,
}
#[cfg(feature = "napi-support")]
#[napi]
impl PythonHandler {
/// Create a new Python handler with the given options.
///
/// # Examples
///
/// ```js
/// const python = new Python({
/// argv: process.argv,
/// docroot: process.cwd(),
/// });
/// ```
#[napi(constructor)]
pub fn new(options: Option<PythonOptions>) -> Result<Self> {
let options = options.unwrap_or_default();
let asgi = Asgi::new(options.docroot, options.app_target)
.map_err(|e| Error::from_reason(e.to_string()))?;
Ok(PythonHandler {
asgi: Arc::new(asgi),
})
}
/// Get the document root for this Python handler.
///
/// # Examples
///
/// ```js
/// const python = new Python({
/// docroot: process.cwd(),
/// });
///
/// console.log(python.docroot);
/// ```
#[napi(getter)]
pub fn docroot(&self) -> String {
// We need to access the docroot from the Asgi struct
// Since Asgi has a PathBuf docroot field, we convert it to String
self.asgi.docroot().display().to_string()
}
/// Handle a Python request with buffered response (backward compatible).
///
/// This method uses the same asgi.handle() as handleStream, but buffers the
/// response body before returning. The body is available synchronously via
/// response.body getter.
///
/// # Examples
///
/// ```js
/// const python = new Python({
/// docroot: process.cwd(),
/// argv: process.argv
/// });
///
/// const response = await python.handleRequest(new Request({
/// method: 'GET',
/// url: 'http://example.com'
/// }));
///
/// console.log(response.status);
/// console.log(response.body.toString()); // Body is buffered and ready
/// ```
#[napi]
pub fn handle_request(
&self,
request: NapiRequest,
signal: Option<AbortSignal>,
) -> AsyncTask<PythonRequestTask> {
AsyncTask::with_optional_signal(
PythonRequestTask {
asgi: self.asgi.clone(),
request: Some(request.into_inner()),
},
signal,
)
}
/// Handle a Python request with streaming response.
///
/// This method uses the same asgi.handle() as handleRequest, but returns
/// immediately with a streaming response. Use AsyncIterator to read chunks.
///
/// # Examples
///
/// ```js
/// const python = new Python({
/// docroot: process.cwd(),
/// argv: process.argv
/// });
///
/// const response = await python.handleStream(new Request({
/// method: 'GET',
/// url: 'http://example.com'
/// }));
///
/// // Read response via AsyncIterator
/// for await (const chunk of response) {
/// console.log(chunk.toString());
/// }
/// ```
#[napi]
pub fn handle_stream(
&self,
request: NapiRequest,
signal: Option<AbortSignal>,
) -> AsyncTask<PythonStreamTask> {
AsyncTask::with_optional_signal(
PythonStreamTask {
asgi: self.asgi.clone(),
request: Some(request.into_inner()),
},
signal,
)
}
/// Handle a PHP request synchronously.
///
/// # Examples
///
/// ```js
/// const php = new Php({
/// docroot: process.cwd(),
/// argv: process.argv
/// });
///
/// const response = php.handleRequestSync(new Request({
/// method: 'GET',
/// url: 'http://example.com'
/// }));
///
/// console.log(response.status);
/// console.log(response.body);
/// ```
#[napi]
pub fn handle_request_sync(&self, request: NapiRequest) -> Result<NapiResponse> {
let mut task = PythonRequestTask {
asgi: self.asgi.clone(),
request: Some(request.into_inner()),
};
task.compute().map(Into::<NapiResponse>::into)
}
}
/// Task for buffered request handling.
/// Uses identical asgi.handle() call, just buffers the body afterward.
#[cfg(feature = "napi-support")]
pub struct PythonRequestTask {
asgi: Arc<Asgi>,
request: Option<Request>,
}
#[cfg(feature = "napi-support")]
impl Task for PythonRequestTask {
type Output = Response;
type JsValue = NapiResponse;
fn compute(&mut self) -> Result<Self::Output> {
// Take ownership of the request (FromNapiValue already created fresh body with BodyBuffer)
let request = self
.request
.take()
.ok_or_else(|| Error::from_reason("Request already consumed"))?;
// Use the shared fallback runtime handle
asgi::fallback_handle().block_on(async {
// Spawn task to send pending body data if present (from Request constructor)
// This prevents deadlock when body size exceeds duplex buffer size
let body_writer = if let Some(body_buffer) = request.extensions().get::<BodyBuffer>() {
let data = Bytes::copy_from_slice(body_buffer.as_bytes());
let mut body = request.body().clone();
Some(tokio::spawn(async move {
use tokio::io::AsyncWriteExt;
body.write_all(&data).await?;
body.shutdown().await?;
Ok::<(), std::io::Error>(())
}))
} else {
// No body provided - close stream immediately
let mut body = request.body().clone();
Some(tokio::spawn(async move {
use tokio::io::AsyncWriteExt;
body.shutdown().await?;
Ok::<(), std::io::Error>(())
}))
};
// Invoke handler immediately (starts reader task)
// Handler returns when headers are ready, body streaming continues in background
let response = self
.asgi
.handle(request)
.await
.map_err(|e| Error::from_reason(e.to_string()))?;
// Wait for body writing to complete
if let Some(writer) = body_writer {
writer
.await
.map_err(|e| Error::from_reason(format!("Body writer task failed: {}", e)))?
.map_err(|e| Error::from_reason(e.to_string()))?;
}
// Extract parts to buffer the body
let (mut parts, mut body) = response.into_parts();
// Buffer all body chunks - consuming starts immediately after headers
use http_body_util::BodyExt;
let mut buf = BytesMut::new();
while let Some(result) = body.frame().await {
match result {
Ok(frame) => {
if let Ok(data) = frame.into_data() {
buf.extend_from_slice(&data);
}
}
Err(e) => {
return Err(Error::from_reason(e));
}
}
}
let bytes = buf.freeze();
// Store buffered body in extension
parts.extensions.insert(BodyBuffer::from_bytes(bytes));
// Create a dummy ResponseBody since body is buffered in extension
let dummy_body = ResponseBody::new();
let buffered_response = http::Response::from_parts(parts, dummy_body);
Ok::<http::Response<ResponseBody>, Error>(buffered_response)
})
}
fn resolve(&mut self, _env: Env, output: Self::Output) -> Result<Self::JsValue> {
Ok(output.into())
}
}
/// Task container to run a Python streaming request in a worker thread.
#[cfg(feature = "napi-support")]
pub struct PythonStreamTask {
asgi: Arc<Asgi>,
request: Option<Request>,
}
#[cfg(feature = "napi-support")]
#[napi]
impl Task for PythonStreamTask {
type Output = Response;
type JsValue = Object<'static>;
// Handle the Python streaming request in the worker thread.
fn compute(&mut self) -> Result<Self::Output> {
// Take ownership of the request to avoid cloning
let request = self
.request
.take()
.ok_or_else(|| Error::from_reason("Request already consumed"))?;
// Get the current runtime handle or use the global fallback runtime
// This ensures background tasks stay alive even after compute() returns
asgi::fallback_handle().block_on(async {
// Check if this is a WebSocket request
let is_websocket = request
.extensions()
.get::<http_handler::WebSocketMode>()
.is_some();
// Spawn task to send pending body data if present (from Request constructor)
// This prevents deadlock when body size exceeds duplex buffer size
let body_writer = if let Some(body_buffer) = request.extensions().get::<BodyBuffer>() {
let data = Bytes::copy_from_slice(body_buffer.as_bytes());
let mut body = request.body().clone();
let should_close = !is_websocket;
Some(tokio::spawn(async move {
use tokio::io::AsyncWriteExt;
body.write_all(&data).await?;
if should_close {
body.shutdown().await?;
}
Ok::<(), std::io::Error>(())
}))
} else if !is_websocket {
// No body provided - close stream immediately for non-WebSocket requests
let mut body = request.body().clone();
Some(tokio::spawn(async move {
use tokio::io::AsyncWriteExt;
body.shutdown().await?;
Ok::<(), std::io::Error>(())
}))
} else {
None
};
// Invoke handler immediately (starts reader task)
// For streaming responses, returns when headers are ready
let response = self
.asgi
.handle(request)
.await
.map_err(|e| Error::from_reason(e.to_string()))?;
// Wait for body writing to complete
if let Some(writer) = body_writer {
writer
.await
.map_err(|e| Error::from_reason(format!("Body writer task failed: {}", e)))?
.map_err(|e| Error::from_reason(e.to_string()))?;
}
Ok(response)
})
}
// Handle converting the Python response to a JavaScript response in the main thread.
fn resolve(&mut self, env: Env, output: Self::Output) -> Result<Self::JsValue> {
// Convert to NapiResponse and set up async iterator
let response: NapiResponse = output.into();
response.make_streamable(env)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_python_handler_target_try_from_str_valid() {
let target = PythonHandlerTarget::try_from("main:app").unwrap();
assert_eq!(target.file, "main");
assert_eq!(target.function, "app");
let target = PythonHandlerTarget::try_from("my_module:my_function").unwrap();
assert_eq!(target.file, "my_module");
assert_eq!(target.function, "my_function");
}
#[test]
fn test_python_handler_target_try_from_str_invalid() {
// No colon
let result = PythonHandlerTarget::try_from("invalid");
assert!(result.is_err());
assert_eq!(
result.unwrap_err(),
"Invalid format, expected \"file:function\""
);
// Multiple colons
let result = PythonHandlerTarget::try_from("too:many:colons");
assert!(result.is_err());
assert_eq!(
result.unwrap_err(),
"Invalid format, expected \"file:function\""
);
// Empty string
let result = PythonHandlerTarget::try_from("");
assert!(result.is_err());
assert_eq!(
result.unwrap_err(),
"Invalid format, expected \"file:function\""
);
// Only colon - this actually succeeds with empty file and function
// The current implementation allows this: ":" -> file="", function=""
let result = PythonHandlerTarget::try_from(":");
assert!(result.is_ok());
let target = result.unwrap();
assert_eq!(target.file, "");
assert_eq!(target.function, "");
// Test with empty parts in different ways
let result = PythonHandlerTarget::try_from(":function");
assert!(result.is_ok());
let target = result.unwrap();
assert_eq!(target.file, "");
assert_eq!(target.function, "function");
let result = PythonHandlerTarget::try_from("file:");
assert!(result.is_ok());
let target = result.unwrap();
assert_eq!(target.file, "file");
assert_eq!(target.function, "");
}
#[test]
fn test_python_handler_target_from_string_conversion() {
let target = PythonHandlerTarget {
file: "test_module".to_string(),
function: "test_function".to_string(),
};
let result: String = target.into();
assert_eq!(result, "test_module:test_function");
}
#[test]
fn test_python_handler_target_default() {
let target = PythonHandlerTarget::default();
assert_eq!(target.file, "main");
assert_eq!(target.function, "app");
}
#[test]
fn test_python_handler_target_debug_clone_eq_hash() {
let target1 = PythonHandlerTarget {
file: "test".to_string(),
function: "app".to_string(),
};
let target2 = target1.clone();
// Test Debug
let debug_str = format!("{:?}", target1);
assert!(debug_str.contains("test"));
assert!(debug_str.contains("app"));
// Test Clone and PartialEq
assert_eq!(target1, target2);
// Test inequality
let target3 = PythonHandlerTarget {
file: "different".to_string(),
function: "app".to_string(),
};
assert_ne!(target1, target3);
// Test Hash by putting in a HashSet
use std::collections::HashSet;
let mut set = HashSet::new();
set.insert(target1);
set.insert(target2); // Should not increase size due to equality
assert_eq!(set.len(), 1);
}
}
/// Error types for the Python request handler.
#[allow(clippy::large_enum_variant)]
#[derive(thiserror::Error, Debug)]
pub enum HandlerError {
/// IO errors that may occur during file operations.
#[error("IO Error: {0}")]
IoError(#[from] std::io::Error),
/// Error when the current directory cannot be determined.
#[error("Failed to get current directory: {0}")]
CurrentDirectoryError(std::io::Error),
/// Error when the entry point for the Python application is not found.
#[error("Entry point not found: {0}")]
EntrypointNotFoundError(std::io::Error),
/// Error when converting a string to a C-compatible string.
#[error("Failed to convert string: {0}")]
StringCovertError(#[from] std::ffi::NulError),
/// Error when a Python operation fails.
#[error("Python error: {0}")]
PythonError(#[from] pyo3::prelude::PyErr),
/// Error when response channel is closed before sending a response.
#[error("No response sent")]
NoResponse,
/// Error when response is interrupted.
#[error("Response interrupted")]
ResponseInterrupted,
/// Error when response channel is closed.
#[error("Response channel closed: {0}")]
ResponseChannelClosed(#[from] RecvError),
/// Error when unable to send message to Python.
#[error("Unable to send message to Python: {0}")]
UnableToSendMessageToPython(#[from] SendError<HttpReceiveMessage>),
/// Error when creating an HTTP response fails.
#[error("Failed to create response: {0}")]
HttpHandlerError(#[from] http_handler::Error),
/// Error when event loop is closed.
#[error("Event loop closed")]
EventLoopClosed,
/// Error when PYTHON_NODE_WORKERS is invalid
#[error("Invalid PYTHON_NODE_WORKERS count: {0}")]
InvalidWorkerCount(#[from] std::num::ParseIntError),
/// Error when a lock is poisoned
#[error("Lock poisoned: {0}")]
LockPoisoned(String),
/// Error when a Tokio task fails
#[error("Tokio task error: {0}")]
TokioError(String),
/// Error when request stream has already been consumed
#[error("Request stream already consumed")]
StreamAlreadyConsumed,
/// Error when WebSocket connection was not accepted
#[error("WebSocket connection not accepted")]
WebSocketNotAccepted,
}
impl<T> From<std::sync::PoisonError<T>> for HandlerError {
fn from(err: std::sync::PoisonError<T>) -> Self {
HandlerError::LockPoisoned(err.to_string())
}
}