Skip to content

Commit 98189ce

Browse files
committed
feat: subrequest support
1 parent 362c93e commit 98189ce

10 files changed

Lines changed: 647 additions & 31 deletions

File tree

.github/workflows/nginx.yaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ env:
5353
load_module ${{ github.workspace }}/nginx/objs/ngx_http_awssigv4_module.so;
5454
load_module ${{ github.workspace }}/nginx/objs/ngx_http_curl_module.so;
5555
load_module ${{ github.workspace }}/nginx/objs/ngx_http_shared_dict_module.so;
56+
load_module ${{ github.workspace }}/nginx/objs/ngx_http_subrequest_module.so;
5657
load_module ${{ github.workspace }}/nginx/objs/ngx_http_upstream_custom_module.so;
5758
5859
OPENSSL_VERSION: '3.0.16'

examples/Cargo.toml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,11 @@ name = "shared_dict"
5656
path = "shared_dict.rs"
5757
crate-type = ["cdylib"]
5858

59+
[[example]]
60+
name = "subrequest"
61+
path = "subrequest.rs"
62+
crate-type = ["cdylib"]
63+
5964
[features]
6065
default = ["export-modules", "ngx/vendored"]
6166
# Generate `ngx_modules` table with module exports

examples/config

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,14 @@ if [ $HTTP = YES ]; then
4747
ngx_rust_module
4848
fi
4949

50+
if :; then
51+
ngx_module_name=ngx_http_subrequest_module
52+
ngx_module_libs=
53+
ngx_rust_target_name=subrequest
54+
55+
ngx_rust_module
56+
fi
57+
5058
if :; then
5159
ngx_module_name=ngx_http_upstream_custom_module
5260
ngx_module_libs=

examples/subrequest.rs

Lines changed: 260 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,260 @@
1+
use core::fmt::Display;
2+
3+
use ngx::core::Status;
4+
use ngx::http::subrequest::{SubRequestBuilder, SubRequestError};
5+
use ngx::http::{
6+
HTTPStatus, HttpModule, HttpModuleLocationConf, HttpPhase, HttpRequestHandler, Merge,
7+
MergeConfigError, Request, add_phase_handler,
8+
};
9+
use ngx::{ngx_log_debug_http, ngx_log_error};
10+
11+
use nginx_sys::{
12+
NGX_CONF_TAKE1, NGX_ERROR, NGX_HTTP_LOC_CONF, NGX_HTTP_LOC_CONF_OFFSET, ngx_command_t,
13+
ngx_conf_t, ngx_flag_t, ngx_http_complex_value_t, ngx_http_module_t, ngx_http_request_t,
14+
ngx_http_send_response, ngx_int_t, ngx_module_t, ngx_str_t, ngx_uint_t,
15+
};
16+
17+
const NGX_CONF_UNSET_FLAG: ngx_flag_t = nginx_sys::NGX_CONF_UNSET as _;
18+
19+
struct SampleHandler;
20+
21+
enum SampleHandlerError {
22+
ContextAllocation,
23+
SubRequestCreation(SubRequestError),
24+
SubRequest(ngx_int_t),
25+
Response(ngx_int_t),
26+
}
27+
28+
impl From<SubRequestError> for SampleHandlerError {
29+
fn from(e: SubRequestError) -> Self {
30+
SampleHandlerError::SubRequestCreation(e)
31+
}
32+
}
33+
34+
impl Display for SampleHandlerError {
35+
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
36+
match self {
37+
SampleHandlerError::ContextAllocation => {
38+
write!(f, "context allocation failed")
39+
}
40+
SampleHandlerError::SubRequestCreation(e) => {
41+
write!(f, "subrequest creation failed: {}", e)
42+
}
43+
SampleHandlerError::SubRequest(rc) => {
44+
write!(f, "subrequest failed with return code: {}", rc)
45+
}
46+
SampleHandlerError::Response(rc) => {
47+
write!(f, "response creation failed with return code: {}", rc)
48+
}
49+
}
50+
}
51+
}
52+
53+
impl HttpRequestHandler for SampleHandler {
54+
const PHASE: HttpPhase = HttpPhase::Access;
55+
type Output = Result<Status, SampleHandlerError>;
56+
57+
fn handler(request: &mut Request) -> Self::Output {
58+
let co = Module::location_conf(request).expect("module config is none");
59+
ngx_log_debug_http!(request, "subrequest module enabled: {}", co.enable);
60+
61+
if co.enable != 1 {
62+
return Ok(Status::NGX_DECLINED);
63+
}
64+
65+
let rptr: *mut ngx_http_request_t = request.as_mut();
66+
67+
match SRCtx::get(request) {
68+
Some(ctx) => ctx.rc.map_or(
69+
// `ctx` has been created but not filled yet - subrequest is still in progress
70+
Ok(Status::NGX_AGAIN),
71+
// `ctx` has been created and filled - subrequest is completed
72+
|rc| {
73+
let status = ctx.status.0;
74+
let msg = format!("subrequest completed with HTTP status: {status}, rc: {rc}");
75+
ngx_log_debug_http!(request, "{msg}");
76+
77+
if status >= nginx_sys::NGX_HTTP_SPECIAL_RESPONSE as _ {
78+
Ok(Status::from(ctx.status))
79+
} else if rc == nginx_sys::NGX_OK as _ && ctx.out.is_some() {
80+
let outbuf = unsafe { &*ctx.out.unwrap().buf };
81+
let mut ct = ctx.ct;
82+
let mut cv: ngx_http_complex_value_t = unsafe { core::mem::zeroed() };
83+
cv.value = ngx_str_t {
84+
len: unsafe { outbuf.last.offset_from(outbuf.pos) } as _,
85+
data: outbuf.pos as _,
86+
};
87+
let resp_rc = unsafe {
88+
ngx_http_send_response(rptr, status, &raw mut ct, &raw mut cv)
89+
};
90+
if resp_rc == nginx_sys::NGX_OK as _ {
91+
Ok(Status::from(ctx.status))
92+
} else {
93+
Err(SampleHandlerError::Response(resp_rc))
94+
}
95+
} else if rc == nginx_sys::NGX_OK as _ {
96+
Ok(Status::from(ctx.status))
97+
} else if let Ok(http_status) = HTTPStatus::try_from(rc) {
98+
Ok(Status::from(http_status))
99+
} else {
100+
Err(SampleHandlerError::SubRequest(rc))
101+
}
102+
},
103+
),
104+
None => {
105+
if SRCtx::create(request).is_some() {
106+
let uri: &str = co.uri.to_str().unwrap_or("/proxy");
107+
108+
SubRequestBuilder::new(request.pool(), uri)?
109+
.args("arg1=val1&arg2=val2")?
110+
.in_memory()
111+
.waited()
112+
.build(request, sr_handler)?;
113+
114+
Ok(Status::NGX_AGAIN)
115+
} else {
116+
Err(SampleHandlerError::ContextAllocation)
117+
}
118+
}
119+
}
120+
}
121+
}
122+
123+
struct SRCtx<'r> {
124+
rc: Option<ngx_int_t>,
125+
status: HTTPStatus,
126+
out: Option<&'r nginx_sys::ngx_chain_t>,
127+
ct: ngx_str_t,
128+
}
129+
130+
impl SRCtx<'_> {
131+
fn create(request: &mut Request) -> Option<&mut Self> {
132+
let ctx_ref = unsafe { request.pool().allocate_with_cleanup(Self::default)?.as_mut() };
133+
request.set_module_ctx(ctx_ref as *mut _ as _, Module::module());
134+
Some(ctx_ref)
135+
}
136+
137+
fn get(request: &Request) -> Option<&Self> {
138+
request.get_module_ctx::<Self>(Module::module())
139+
}
140+
141+
fn get_mut(request: &mut Request) -> Option<&mut Self> {
142+
request.get_module_ctx_mut::<Self>(Module::module())
143+
}
144+
}
145+
146+
impl Default for SRCtx<'_> {
147+
fn default() -> Self {
148+
Self { rc: None, status: HTTPStatus(NGX_ERROR as _), out: None, ct: ngx_str_t::empty() }
149+
}
150+
}
151+
152+
fn sr_handler(r: &mut Request, mut rc: ngx_int_t) -> ngx_int_t {
153+
let newctx = SRCtx {
154+
rc: Some(rc),
155+
status: r.get_status(),
156+
out: core::ptr::NonNull::new(r.as_ref().out).map(|out| unsafe { out.as_ref() }),
157+
ct: r.as_ref().headers_out.content_type,
158+
};
159+
if let Some(ctx) = SRCtx::get_mut(r.get_main_mut()) {
160+
*ctx = newctx;
161+
} else {
162+
ngx_log_error!(nginx_sys::NGX_LOG_ERR, r.log(), "subrequest: context not found");
163+
rc = NGX_ERROR as _;
164+
}
165+
rc
166+
}
167+
168+
static NGX_HTTP_SUBREQUEST_MODULE_CTX: ngx_http_module_t = ngx_http_module_t {
169+
preconfiguration: None,
170+
postconfiguration: Some(Module::postconfiguration),
171+
create_main_conf: None,
172+
init_main_conf: None,
173+
create_srv_conf: None,
174+
merge_srv_conf: None,
175+
create_loc_conf: Some(Module::create_loc_conf),
176+
merge_loc_conf: Some(Module::merge_loc_conf),
177+
};
178+
179+
#[cfg(feature = "export-modules")]
180+
ngx::ngx_modules!(ngx_http_subrequest_module);
181+
182+
#[used]
183+
#[allow(non_upper_case_globals)]
184+
#[cfg_attr(not(feature = "export-modules"), unsafe(no_mangle))]
185+
pub static mut ngx_http_subrequest_module: ngx_module_t = ngx_module_t {
186+
ctx: &raw const NGX_HTTP_SUBREQUEST_MODULE_CTX as _,
187+
commands: unsafe { &raw mut NGX_HTTP_SUBREQUEST_COMMANDS[0] },
188+
type_: nginx_sys::NGX_HTTP_MODULE as _,
189+
..ngx_module_t::default()
190+
};
191+
192+
struct Module;
193+
194+
impl HttpModule for Module {
195+
fn module() -> &'static ngx_module_t {
196+
unsafe { &*::core::ptr::addr_of!(ngx_http_subrequest_module) }
197+
}
198+
199+
unsafe extern "C" fn postconfiguration(cf: *mut ngx_conf_t) -> ngx_int_t {
200+
// SAFETY: this function is called with non-NULL cf always
201+
let cf = unsafe { &mut *cf };
202+
add_phase_handler::<SampleHandler>(cf)
203+
.map_or(nginx_sys::NGX_ERROR as _, |_| nginx_sys::NGX_OK as _)
204+
}
205+
}
206+
207+
#[derive(Debug)]
208+
struct ModuleConfig {
209+
enable: ngx_flag_t,
210+
uri: ngx_str_t,
211+
}
212+
213+
impl Default for ModuleConfig {
214+
fn default() -> Self {
215+
Self { enable: NGX_CONF_UNSET_FLAG, uri: ngx_str_t::empty() }
216+
}
217+
}
218+
219+
impl Merge for ModuleConfig {
220+
fn merge(&mut self, prev: &ModuleConfig) -> Result<(), MergeConfigError> {
221+
if self.enable == NGX_CONF_UNSET_FLAG {
222+
if prev.enable != NGX_CONF_UNSET_FLAG {
223+
self.enable = prev.enable;
224+
} else {
225+
self.enable = 0;
226+
}
227+
}
228+
if self.uri.data.is_null() {
229+
self.uri = prev.uri;
230+
}
231+
if self.enable == 1 && self.uri.data.is_null() {
232+
self.uri = ngx::ngx_string!("/proxy");
233+
}
234+
Ok(())
235+
}
236+
}
237+
238+
unsafe impl HttpModuleLocationConf for Module {
239+
type LocationConf = ModuleConfig;
240+
}
241+
242+
static mut NGX_HTTP_SUBREQUEST_COMMANDS: [ngx_command_t; 3] = [
243+
ngx_command_t {
244+
name: ngx::ngx_string!("subrequest"),
245+
type_: (NGX_HTTP_LOC_CONF | NGX_CONF_TAKE1) as ngx_uint_t,
246+
set: Some(nginx_sys::ngx_conf_set_flag_slot),
247+
conf: NGX_HTTP_LOC_CONF_OFFSET,
248+
offset: core::mem::offset_of!(ModuleConfig, enable),
249+
post: core::ptr::null_mut(),
250+
},
251+
ngx_command_t {
252+
name: ngx::ngx_string!("subrequest_uri"),
253+
type_: (NGX_HTTP_LOC_CONF | NGX_CONF_TAKE1) as ngx_uint_t,
254+
set: Some(nginx_sys::ngx_conf_set_str_slot),
255+
conf: NGX_HTTP_LOC_CONF_OFFSET,
256+
offset: core::mem::offset_of!(ModuleConfig, uri),
257+
post: core::ptr::null_mut(),
258+
},
259+
ngx_command_t::empty(),
260+
];

examples/t/subrequest.t

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
#!/usr/bin/perl
2+
3+
# (C) Nginx, Inc
4+
5+
# Tests for ngx-rust example modules.
6+
7+
###############################################################################
8+
9+
use warnings;
10+
use strict;
11+
12+
use Test::More;
13+
14+
BEGIN { use FindBin; chdir($FindBin::Bin); }
15+
16+
use lib 'lib';
17+
use Test::Nginx;
18+
19+
###############################################################################
20+
21+
select STDERR; $| = 1;
22+
select STDOUT; $| = 1;
23+
24+
my $t = Test::Nginx->new()->has(qw/http proxy/)->plan(2)
25+
->write_file_expand('nginx.conf', <<"EOF");
26+
27+
%%TEST_GLOBALS%%
28+
29+
daemon off;
30+
31+
events {
32+
}
33+
34+
http {
35+
%%TEST_GLOBALS_HTTP%%
36+
37+
server {
38+
listen 127.0.0.1:8080;
39+
server_name localhost;
40+
41+
location / {
42+
subrequest on;
43+
}
44+
45+
location /non_existing {
46+
subrequest on;
47+
subrequest_uri /non_existing_upstream;
48+
}
49+
50+
location /proxy {
51+
internal;
52+
proxy_pass http://127.0.0.1:8081;
53+
}
54+
}
55+
56+
server {
57+
listen 127.0.0.1:8081;
58+
server_name localhost;
59+
60+
location / {
61+
return 200 'Hello from backend';
62+
}
63+
}
64+
}
65+
66+
EOF
67+
68+
$t->write_file('index.html', '');
69+
$t->run();
70+
71+
like(http_get('/'),
72+
qr/200 OK.*Hello from backend/s,
73+
'subrequest');
74+
like(http_get('/non_existing'), qr/404 Not Found/s,
75+
'subrequest to non-existing upstream');

src/http/mod.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@ mod request;
44
mod status;
55
mod upstream;
66

7+
/// HTTP subrequest builder and handler.
8+
#[cfg(feature = "alloc")]
9+
pub mod subrequest;
10+
711
pub use conf::*;
812
pub use module::*;
913
pub use request::*;

0 commit comments

Comments
 (0)