Skip to content

Commit 1a720e5

Browse files
committed
feat: subrequest support
1 parent d419cf8 commit 1a720e5

10 files changed

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

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: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@ mod request;
44
mod status;
55
mod upstream;
66

7+
/// HTTP subrequest builder and handler.
8+
pub mod subrequest;
9+
710
pub use conf::*;
811
pub use module::*;
912
pub use request::*;

0 commit comments

Comments
 (0)