Skip to content

Commit e95e2b8

Browse files
committed
refactor: use NgxResult in handlers
1 parent 141c7a5 commit e95e2b8

File tree

9 files changed

+121
-76
lines changed

9 files changed

+121
-76
lines changed

examples/async.rs

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use std::ffi::{c_char, c_void};
2-
use std::ptr::{addr_of, addr_of_mut};
2+
use std::ptr::addr_of_mut;
33
use std::sync::atomic::{AtomicBool, AtomicPtr, Ordering};
44
use std::sync::{Arc, OnceLock};
55
use std::time::Instant;
@@ -145,24 +145,22 @@ http_request_handler!(async_access_handler, |request: &mut http::Request| {
145145
ngx_log_debug_http!(request, "async module enabled: {}", co.enable);
146146

147147
if !co.enable {
148-
return core::Status::NGX_DECLINED;
148+
return core::Status::NGX_DECLINED.into();
149149
}
150150

151-
if let Some(ctx) =
152-
unsafe { request.get_module_ctx::<RequestCTX>(&*addr_of!(ngx_http_async_module)) }
153-
{
151+
if let Some(ctx) = request.get_module_ctx::<RequestCTX>(Module::module()) {
154152
if !ctx.done.load(Ordering::Relaxed) {
155-
return core::Status::NGX_AGAIN;
153+
return core::Status::NGX_AGAIN.into();
156154
}
157155

158-
return core::Status::NGX_OK;
156+
return core::Status::NGX_OK.into();
159157
}
160158

161-
let ctx = request.pool().allocate(RequestCTX::default());
159+
let ctx = request.pool().alloc_with_cleanup(RequestCTX::default());
162160
if ctx.is_null() {
163-
return core::Status::NGX_ERROR;
161+
return core::Status::NGX_ERROR.into();
164162
}
165-
request.set_module_ctx(ctx.cast(), unsafe { &*addr_of!(ngx_http_async_module) });
163+
request.set_module_ctx(ctx.cast(), Module::module());
166164

167165
let ctx = unsafe { &mut *ctx };
168166
ctx.event.handler = Some(check_async_work_done);
@@ -194,7 +192,7 @@ http_request_handler!(async_access_handler, |request: &mut http::Request| {
194192
// and use the same trick as the thread pool)
195193
}));
196194

197-
core::Status::NGX_AGAIN
195+
core::Status::NGX_AGAIN.into()
198196
});
199197

200198
extern "C" fn ngx_http_async_commands_set_enable(

examples/awssig.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -272,7 +272,7 @@ http_request_handler!(awssigv4_header_handler, |request: &mut Request| {
272272
}
273273
});
274274
if !conf.enable {
275-
return core::Status::NGX_DECLINED;
275+
return core::Status::NGX_DECLINED.into();
276276
}
277277

278278
// TODO: build url properly from the original URL from client
@@ -284,7 +284,7 @@ http_request_handler!(awssigv4_header_handler, |request: &mut Request| {
284284
let datetime = chrono::Utc::now();
285285
let uri = match request.unparsed_uri().to_str() {
286286
Ok(v) => format!("https://{}.{}{}", conf.s3_bucket, conf.s3_endpoint, v),
287-
Err(_) => return core::Status::NGX_DECLINED,
287+
Err(_) => return core::Status::NGX_DECLINED.into(),
288288
};
289289

290290
let datetime_now = datetime.format("%Y%m%dT%H%M%SZ");
@@ -301,11 +301,11 @@ http_request_handler!(awssigv4_header_handler, |request: &mut Request| {
301301
if let Ok(value) = http::HeaderValue::from_bytes(value.as_bytes()) {
302302
headers.insert(http::header::HOST, value);
303303
} else {
304-
return core::Status::NGX_DECLINED;
304+
return core::Status::NGX_DECLINED.into();
305305
}
306306
}
307307
} else {
308-
return core::Status::NGX_DECLINED;
308+
return core::Status::NGX_DECLINED.into();
309309
}
310310
}
311311
headers.insert("X-Amz-Date", datetime_now.parse().unwrap());
@@ -338,5 +338,5 @@ http_request_handler!(awssigv4_header_handler, |request: &mut Request| {
338338
ngx_log_debug_http!(request, "headers_in {name}: {value}",);
339339
}
340340

341-
core::Status::NGX_OK
341+
core::Status::NGX_OK.into()
342342
});

examples/curl.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -103,10 +103,10 @@ http_request_handler!(curl_access_handler, |request: &mut http::Request| {
103103
{
104104
http::HTTPStatus::FORBIDDEN.into()
105105
} else {
106-
core::Status::NGX_DECLINED
106+
core::Status::NGX_DECLINED.into()
107107
}
108108
}
109-
false => core::Status::NGX_DECLINED,
109+
false => core::Status::NGX_DECLINED.into(),
110110
}
111111
});
112112

examples/httporigdst.rs

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -196,7 +196,7 @@ http_variable_get!(
196196
if let Some(obj) = ctx {
197197
ngx_log_debug_http!(request, "httporigdst: found context and binding variable",);
198198
obj.bind_addr(v);
199-
return core::Status::NGX_OK;
199+
return core::Status::NGX_OK.into();
200200
}
201201
// lazy initialization:
202202
// get original dest information
@@ -207,17 +207,17 @@ http_variable_get!(
207207
let r = ngx_get_origdst(request);
208208
match r {
209209
Err(e) => {
210-
return e;
210+
return e.into();
211211
}
212212
Ok((ip, port)) => {
213213
// create context,
214214
// set context
215215
let new_ctx = request
216216
.pool()
217-
.allocate::<NgxHttpOrigDstCtx>(Default::default());
217+
.alloc_with_cleanup::<NgxHttpOrigDstCtx>(Default::default());
218218

219219
if new_ctx.is_null() {
220-
return core::Status::NGX_ERROR;
220+
return core::Status::NGX_ERROR.into();
221221
}
222222

223223
ngx_log_debug_http!(
@@ -232,7 +232,7 @@ http_variable_get!(
232232
.set_module_ctx(new_ctx as *mut c_void, &*addr_of!(ngx_http_orig_dst_module));
233233
}
234234
}
235-
core::Status::NGX_OK
235+
core::Status::NGX_OK.into()
236236
}
237237
);
238238

@@ -243,7 +243,7 @@ http_variable_get!(
243243
if let Some(obj) = ctx {
244244
ngx_log_debug_http!(request, "httporigdst: found context and binding variable",);
245245
obj.bind_port(v);
246-
return core::Status::NGX_OK;
246+
return core::Status::NGX_OK.into();
247247
}
248248
// lazy initialization:
249249
// get original dest information
@@ -254,17 +254,17 @@ http_variable_get!(
254254
let r = ngx_get_origdst(request);
255255
match r {
256256
Err(e) => {
257-
return e;
257+
return e.into();
258258
}
259259
Ok((ip, port)) => {
260260
// create context,
261261
// set context
262262
let new_ctx = request
263263
.pool()
264-
.allocate::<NgxHttpOrigDstCtx>(Default::default());
264+
.alloc_with_cleanup::<NgxHttpOrigDstCtx>(Default::default());
265265

266266
if new_ctx.is_null() {
267-
return core::Status::NGX_ERROR;
267+
return core::Status::NGX_ERROR.into();
268268
}
269269

270270
ngx_log_debug_http!(
@@ -279,7 +279,7 @@ http_variable_get!(
279279
.set_module_ctx(new_ctx as *mut c_void, &*addr_of!(ngx_http_orig_dst_module));
280280
}
281281
}
282-
core::Status::NGX_OK
282+
core::Status::NGX_OK.into()
283283
}
284284
);
285285

src/core/pool.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -272,7 +272,7 @@ impl Pool {
272272
///
273273
/// Returns a typed pointer to the allocated memory if successful, or a null pointer if
274274
/// allocation or cleanup handler addition fails.
275-
pub fn allocate<T>(&self, value: T) -> *mut T {
275+
pub fn alloc_with_cleanup<T>(&self, value: T) -> *mut T {
276276
unsafe {
277277
let p = self.alloc(mem::size_of::<T>()) as *mut T;
278278
ptr::write(p, value);
@@ -308,7 +308,7 @@ impl Pool {
308308
Ok(NonNull::slice_from_raw_parts(ptr, new_layout.size()))
309309
} else {
310310
let size = core::cmp::min(old_layout.size(), new_layout.size());
311-
let new_ptr = <Self as Allocator>::allocate(self, new_layout)?;
311+
let new_ptr = self.allocate(new_layout)?;
312312
unsafe {
313313
ptr.copy_to_nonoverlapping(new_ptr.cast(), size);
314314
self.deallocate(ptr, old_layout);

src/core/status.rs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
1+
use core::error::Error;
12
use core::ffi::c_char;
23
use core::fmt;
34
use core::ptr;
45

6+
use allocator_api2::alloc::AllocError;
7+
58
use crate::ffi::*;
69

710
/// Status
@@ -68,3 +71,34 @@ ngx_codes! {
6871
pub const NGX_CONF_ERROR: *mut c_char = ptr::null_mut::<c_char>().wrapping_offset(-1);
6972
/// Configuration handler succeeded.
7073
pub const NGX_CONF_OK: *mut c_char = ptr::null_mut();
74+
75+
/// Error type encapsulating normal NGINX return codes
76+
#[derive(Debug)]
77+
pub struct NgxError {}
78+
79+
impl fmt::Display for NgxError {
80+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81+
write!(f, "NGINX Error")
82+
}
83+
}
84+
85+
impl Error for NgxError {}
86+
87+
impl From<AllocError> for NgxError {
88+
fn from(_err: AllocError) -> Self {
89+
NgxError {}
90+
}
91+
}
92+
93+
/// Result type for NGINX status codes.
94+
pub type NgxResult<T = nginx_sys::ngx_int_t> = core::result::Result<T, NgxError>;
95+
96+
impl From<Status> for NgxResult {
97+
fn from(val: Status) -> Self {
98+
if val == Status::NGX_ERROR {
99+
Err(NgxError {})
100+
} else {
101+
Ok(val.0)
102+
}
103+
}
104+
}

src/http/module.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ pub trait HttpModule {
7878
Self::MainConf: Default,
7979
{
8080
let pool = Pool::from_ngx_pool((*cf).pool);
81-
pool.allocate::<Self::MainConf>(Default::default()) as *mut c_void
81+
pool.alloc_with_cleanup::<Self::MainConf>(Default::default()) as *mut c_void
8282
}
8383

8484
/// # Safety
@@ -103,7 +103,7 @@ pub trait HttpModule {
103103
Self::ServerConf: Default,
104104
{
105105
let pool = Pool::from_ngx_pool((*cf).pool);
106-
pool.allocate::<Self::ServerConf>(Default::default()) as *mut c_void
106+
pool.alloc_with_cleanup::<Self::ServerConf>(Default::default()) as *mut c_void
107107
}
108108

109109
/// # Safety
@@ -137,7 +137,7 @@ pub trait HttpModule {
137137
Self::LocationConf: Default,
138138
{
139139
let pool = Pool::from_ngx_pool((*cf).pool);
140-
pool.allocate::<Self::LocationConf>(Default::default()) as *mut c_void
140+
pool.alloc_with_cleanup::<Self::LocationConf>(Default::default()) as *mut c_void
141141
}
142142

143143
/// # Safety

0 commit comments

Comments
 (0)