Skip to content

Commit 9963a5e

Browse files
robjtedeMikailBag
andauthored
expose on_connect v2 (#1754)
Co-authored-by: Mikail Bagishov <[email protected]>
1 parent 4519db3 commit 9963a5e

16 files changed

Lines changed: 373 additions & 71 deletions

‎CHANGES.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
* Add request-local data extractor `web::ReqData`. [#1748]
77
* Add ability to register closure for request middleware logging. [#1749]
88
* Add `app_data` to `ServiceConfig`. [#1757]
9+
* Expose `on_connect` for access to the connection stream before request is handled. [#1754]
910

1011
### Changed
1112
* Print non-configured `Data<T>` type when attempting extraction. [#1743]
@@ -16,6 +17,7 @@
1617
[#1743]: https://github.com/actix/actix-web/pull/1743
1718
[#1748]: https://github.com/actix/actix-web/pull/1748
1819
[#1750]: https://github.com/actix/actix-web/pull/1750
20+
[#1754]: https://github.com/actix/actix-web/pull/1754
1921
[#1749]: https://github.com/actix/actix-web/pull/1749
2022

2123

‎Cargo.toml‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,14 @@ required-features = ["compress"]
6464
name = "test_server"
6565
required-features = ["compress"]
6666

67+
[[example]]
68+
name = "on_connect"
69+
required-features = []
70+
71+
[[example]]
72+
name = "client"
73+
required-features = ["rustls"]
74+
6775
[dependencies]
6876
actix-codec = "0.3.0"
6977
actix-service = "1.0.6"
@@ -105,7 +113,7 @@ tinyvec = { version = "1", features = ["alloc"] }
105113
actix = "0.10.0"
106114
actix-http = { version = "2.0.0", features = ["actors"] }
107115
rand = "0.7"
108-
env_logger = "0.7"
116+
env_logger = "0.8"
109117
serde_derive = "1.0"
110118
brotli2 = "0.3.2"
111119
flate2 = "1.0.13"
@@ -125,10 +133,6 @@ actix-files = { path = "actix-files" }
125133
actix-multipart = { path = "actix-multipart" }
126134
awc = { path = "awc" }
127135

128-
[[example]]
129-
name = "client"
130-
required-features = ["rustls"]
131-
132136
[[bench]]
133137
name = "server"
134138
harness = false

‎actix-http/CHANGES.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,16 @@
11
# Changes
22

33
## Unreleased - 2020-xx-xx
4+
### Added
5+
* Added more flexible `on_connect_ext` methods for on-connect handling. [#1754]
6+
7+
### Changed
48
* Upgrade `base64` to `0.13`.
59
* Upgrade `pin-project` to `1.0`.
610

11+
[#1754]: https://github.com/actix/actix-web/pull/1754
12+
13+
714
## 2.0.0 - 2020-09-11
815
* No significant changes from `2.0.0-beta.4`.
916

‎actix-http/src/builder.rs‎

Lines changed: 34 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,11 @@ use crate::helpers::{Data, DataFactory};
1414
use crate::request::Request;
1515
use crate::response::Response;
1616
use crate::service::HttpService;
17+
use crate::{ConnectCallback, Extensions};
1718

18-
/// A http service builder
19+
/// A HTTP service builder
1920
///
20-
/// This type can be used to construct an instance of `http service` through a
21+
/// This type can be used to construct an instance of [`HttpService`] through a
2122
/// builder-like pattern.
2223
pub struct HttpServiceBuilder<T, S, X = ExpectHandler, U = UpgradeHandler<T>> {
2324
keep_alive: KeepAlive,
@@ -27,7 +28,9 @@ pub struct HttpServiceBuilder<T, S, X = ExpectHandler, U = UpgradeHandler<T>> {
2728
local_addr: Option<net::SocketAddr>,
2829
expect: X,
2930
upgrade: Option<U>,
31+
// DEPRECATED: in favor of on_connect_ext
3032
on_connect: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
33+
on_connect_ext: Option<Rc<ConnectCallback<T>>>,
3134
_t: PhantomData<(T, S)>,
3235
}
3336

@@ -49,6 +52,7 @@ where
4952
expect: ExpectHandler,
5053
upgrade: None,
5154
on_connect: None,
55+
on_connect_ext: None,
5256
_t: PhantomData,
5357
}
5458
}
@@ -138,6 +142,7 @@ where
138142
expect: expect.into_factory(),
139143
upgrade: self.upgrade,
140144
on_connect: self.on_connect,
145+
on_connect_ext: self.on_connect_ext,
141146
_t: PhantomData,
142147
}
143148
}
@@ -167,14 +172,16 @@ where
167172
expect: self.expect,
168173
upgrade: Some(upgrade.into_factory()),
169174
on_connect: self.on_connect,
175+
on_connect_ext: self.on_connect_ext,
170176
_t: PhantomData,
171177
}
172178
}
173179

174180
/// Set on-connect callback.
175181
///
176-
/// It get called once per connection and result of the call
177-
/// get stored to the request's extensions.
182+
/// Called once per connection. Return value of the call is stored in request extensions.
183+
///
184+
/// *SOFT DEPRECATED*: Prefer the `on_connect_ext` style callback.
178185
pub fn on_connect<F, I>(mut self, f: F) -> Self
179186
where
180187
F: Fn(&T) -> I + 'static,
@@ -184,7 +191,20 @@ where
184191
self
185192
}
186193

187-
/// Finish service configuration and create *http service* for HTTP/1 protocol.
194+
/// Sets the callback to be run on connection establishment.
195+
///
196+
/// Has mutable access to a data container that will be merged into request extensions.
197+
/// This enables transport layer data (like client certificates) to be accessed in middleware
198+
/// and handlers.
199+
pub fn on_connect_ext<F>(mut self, f: F) -> Self
200+
where
201+
F: Fn(&T, &mut Extensions) + 'static,
202+
{
203+
self.on_connect_ext = Some(Rc::new(f));
204+
self
205+
}
206+
207+
/// Finish service configuration and create a HTTP Service for HTTP/1 protocol.
188208
pub fn h1<F, B>(self, service: F) -> H1Service<T, S, B, X, U>
189209
where
190210
B: MessageBody,
@@ -200,13 +220,15 @@ where
200220
self.secure,
201221
self.local_addr,
202222
);
223+
203224
H1Service::with_config(cfg, service.into_factory())
204225
.expect(self.expect)
205226
.upgrade(self.upgrade)
206227
.on_connect(self.on_connect)
228+
.on_connect_ext(self.on_connect_ext)
207229
}
208230

209-
/// Finish service configuration and create *http service* for HTTP/2 protocol.
231+
/// Finish service configuration and create a HTTP service for HTTP/2 protocol.
210232
pub fn h2<F, B>(self, service: F) -> H2Service<T, S, B>
211233
where
212234
B: MessageBody + 'static,
@@ -223,7 +245,10 @@ where
223245
self.secure,
224246
self.local_addr,
225247
);
226-
H2Service::with_config(cfg, service.into_factory()).on_connect(self.on_connect)
248+
249+
H2Service::with_config(cfg, service.into_factory())
250+
.on_connect(self.on_connect)
251+
.on_connect_ext(self.on_connect_ext)
227252
}
228253

229254
/// Finish service configuration and create `HttpService` instance.
@@ -243,9 +268,11 @@ where
243268
self.secure,
244269
self.local_addr,
245270
);
271+
246272
HttpService::with_config(cfg, service.into_factory())
247273
.expect(self.expect)
248274
.upgrade(self.upgrade)
249275
.on_connect(self.on_connect)
276+
.on_connect_ext(self.on_connect_ext)
250277
}
251278
}

‎actix-http/src/extensions.rs‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use std::any::{Any, TypeId};
2-
use std::fmt;
2+
use std::{fmt, mem};
33

44
use fxhash::FxHashMap;
55

@@ -66,6 +66,11 @@ impl Extensions {
6666
pub fn extend(&mut self, other: Extensions) {
6767
self.map.extend(other.map);
6868
}
69+
70+
/// Sets (or overrides) items from `other` into this map.
71+
pub(crate) fn drain_from(&mut self, other: &mut Self) {
72+
self.map.extend(mem::take(&mut other.map));
73+
}
6974
}
7075

7176
impl fmt::Debug for Extensions {
@@ -213,4 +218,27 @@ mod tests {
213218
assert_eq!(extensions.get(), Some(&20u8));
214219
assert_eq!(extensions.get_mut(), Some(&mut 20u8));
215220
}
221+
222+
#[test]
223+
fn test_drain_from() {
224+
let mut ext = Extensions::new();
225+
ext.insert(2isize);
226+
227+
let mut more_ext = Extensions::new();
228+
229+
more_ext.insert(5isize);
230+
more_ext.insert(5usize);
231+
232+
assert_eq!(ext.get::<isize>(), Some(&2isize));
233+
assert_eq!(ext.get::<usize>(), None);
234+
assert_eq!(more_ext.get::<isize>(), Some(&5isize));
235+
assert_eq!(more_ext.get::<usize>(), Some(&5usize));
236+
237+
ext.drain_from(&mut more_ext);
238+
239+
assert_eq!(ext.get::<isize>(), Some(&5isize));
240+
assert_eq!(ext.get::<usize>(), Some(&5usize));
241+
assert_eq!(more_ext.get::<isize>(), None);
242+
assert_eq!(more_ext.get::<usize>(), None);
243+
}
216244
}

‎actix-http/src/h1/dispatcher.rs‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ use bytes::{Buf, BytesMut};
1212
use log::{error, trace};
1313
use pin_project::pin_project;
1414

15-
use crate::body::{Body, BodySize, MessageBody, ResponseBody};
1615
use crate::cloneable::CloneableService;
1716
use crate::config::ServiceConfig;
1817
use crate::error::{DispatchError, Error};
@@ -21,6 +20,10 @@ use crate::helpers::DataFactory;
2120
use crate::httpmessage::HttpMessage;
2221
use crate::request::Request;
2322
use crate::response::Response;
23+
use crate::{
24+
body::{Body, BodySize, MessageBody, ResponseBody},
25+
Extensions,
26+
};
2427

2528
use super::codec::Codec;
2629
use super::payload::{Payload, PayloadSender, PayloadStatus};
@@ -88,6 +91,7 @@ where
8891
expect: CloneableService<X>,
8992
upgrade: Option<CloneableService<U>>,
9093
on_connect: Option<Box<dyn DataFactory>>,
94+
on_connect_data: Extensions,
9195
flags: Flags,
9296
peer_addr: Option<net::SocketAddr>,
9397
error: Option<DispatchError>,
@@ -167,14 +171,15 @@ where
167171
U: Service<Request = (Request, Framed<T, Codec>), Response = ()>,
168172
U::Error: fmt::Display,
169173
{
170-
/// Create http/1 dispatcher.
174+
/// Create HTTP/1 dispatcher.
171175
pub(crate) fn new(
172176
stream: T,
173177
config: ServiceConfig,
174178
service: CloneableService<S>,
175179
expect: CloneableService<X>,
176180
upgrade: Option<CloneableService<U>>,
177181
on_connect: Option<Box<dyn DataFactory>>,
182+
on_connect_data: Extensions,
178183
peer_addr: Option<net::SocketAddr>,
179184
) -> Self {
180185
Dispatcher::with_timeout(
@@ -187,6 +192,7 @@ where
187192
expect,
188193
upgrade,
189194
on_connect,
195+
on_connect_data,
190196
peer_addr,
191197
)
192198
}
@@ -202,6 +208,7 @@ where
202208
expect: CloneableService<X>,
203209
upgrade: Option<CloneableService<U>>,
204210
on_connect: Option<Box<dyn DataFactory>>,
211+
on_connect_data: Extensions,
205212
peer_addr: Option<net::SocketAddr>,
206213
) -> Self {
207214
let keepalive = config.keep_alive_enabled();
@@ -234,6 +241,7 @@ where
234241
expect,
235242
upgrade,
236243
on_connect,
244+
on_connect_data,
237245
flags,
238246
peer_addr,
239247
ka_expire,
@@ -526,11 +534,15 @@ where
526534
let pl = this.codec.message_type();
527535
req.head_mut().peer_addr = *this.peer_addr;
528536

537+
// DEPRECATED
529538
// set on_connect data
530539
if let Some(ref on_connect) = this.on_connect {
531540
on_connect.set(&mut req.extensions_mut());
532541
}
533542

543+
// merge on_connect_ext data into request extensions
544+
req.extensions_mut().drain_from(this.on_connect_data);
545+
534546
if pl == MessageType::Stream && this.upgrade.is_some() {
535547
this.messages.push_back(DispatcherMessage::Upgrade(req));
536548
break;
@@ -927,8 +939,10 @@ mod tests {
927939
CloneableService::new(ExpectHandler),
928940
None,
929941
None,
942+
Extensions::new(),
930943
None,
931944
);
945+
932946
match Pin::new(&mut h1).poll(cx) {
933947
Poll::Pending => panic!(),
934948
Poll::Ready(res) => assert!(res.is_err()),

0 commit comments

Comments
 (0)