1
0
mirror of https://github.com/fafhrd91/actix-net synced 2025-08-12 04:07:06 +02:00

Compare commits

..

240 Commits

Author SHA1 Message Date
Nikolay Kim
51c4dfe5cb Allow to reset Path instance; export Quoter type 2019-04-07 22:48:18 -07:00
Nikolay Kim
a60112c71e Poll boxed service call result immediately 2019-04-07 20:48:40 -07:00
Nikolay Kim
bd814d6f80 re-export trust-dns types 2019-04-05 10:36:57 -07:00
Nikolay Kim
a4e0c71baa Merge branch 'master' of github.com:actix/actix-net 2019-04-04 15:41:50 -07:00
Nikolay Kim
b9ea445e70 Log error if dns system config could not be loaded 2019-04-04 15:41:05 -07:00
Nikolay Kim
ba2901269d Merge pull request #11 from Dowwie/master
added docs for trait Service, trait Transform
2019-04-04 11:06:02 -07:00
dowwie
5cbc29306a updated as per comments 2019-04-04 14:02:53 -04:00
Nikolay Kim
810fa869ae remove unneeded static 2019-04-04 10:04:19 -07:00
dowwie
33cd51aabf added docs for trait Service, trait Transform 2019-04-04 11:40:28 -04:00
Nikolay Kim
629ed05f82 Get dynamic segment by name instead of iterator 2019-04-03 21:40:21 -07:00
Nikolay Kim
5e8ae210f7 Rename connect Connector to TcpConnector #10 2019-03-31 19:14:13 -07:00
Nikolay Kim
3add90628f Fix SIGINT force shutdown 2019-03-30 12:09:02 -07:00
Nikolay Kim
02ab804e0b prepare actix-service release 2019-03-29 11:16:40 -07:00
Nikolay Kim
feac0b43d9 add impl Service for Rc<RefCell<S>> 2019-03-29 10:21:17 -07:00
Nikolay Kim
1441355d4f use release 2019-03-28 04:02:39 -07:00
Nikolay Kim
7c5afc09a6 move threadpool to separate crate 2019-03-28 03:56:52 -07:00
Nikolay Kim
16856c7d3f Merge branch 'master' of github.com:actix/actix-net 2019-03-27 17:30:54 -07:00
Nikolay Kim
95d02659d5 Added Framed::map_io() method 2019-03-27 17:30:37 -07:00
Juan Aguilar Santillana
bcbd7e6ddf Fix unnecessary arbiter clone at builder rt 2019-03-23 09:46:08 +03:00
Nikolay Kim
e0d3581239 allow to send messages to framed transport via mpsc channel 2019-03-20 09:44:23 -07:00
Nikolay Kim
ef1bdb2eb2 update travis config 2019-03-17 10:25:24 -07:00
Nikolay Kim
10301ff49d temp tarpaulin fix 2019-03-17 08:53:50 -07:00
Nikolay Kim
27c28d6597 Fix error handling for single address 2019-03-15 11:37:51 -07:00
Nikolay Kim
b290273e81 prepare actix-connect release 2019-03-14 22:39:49 -07:00
Nikolay Kim
720230b852 Merge pull request #8 from Firstyear/2019-03-15-arbiter-docs
Improve Arbiter documentation
2019-03-14 20:58:33 -07:00
Nikolay Kim
44c2639fd6 prepare actix-server release 2019-03-14 20:55:55 -07:00
Nikolay Kim
9a5705d1b6 merge travis branch 2019-03-14 20:53:56 -07:00
Nikolay Kim
7ff923a58f stop tests threads 2019-03-14 20:52:17 -07:00
Nikolay Kim
6659b192d3 travis config 2019-03-14 20:52:13 -07:00
Nikolay Kim
1146d9cf30 fix init order 2019-03-14 20:48:58 -07:00
Nikolay Kim
b7b76c47e5 rename method 2019-03-14 20:23:49 -07:00
Nikolay Kim
d23dc6f6af Allow to run future before server service initialization 2019-03-14 20:09:34 -07:00
William Brown
9b6a955da4 Improve Arbiter documentation 2019-03-15 10:24:27 +10:00
Nikolay Kim
f3aa48309f travis config 2019-03-14 11:55:39 -07:00
Nikolay Kim
c9b86712e5 reinstall tarpaulin 2019-03-14 11:31:32 -07:00
Nikolay Kim
0f74f280f9 impl Address for http::Uri 2019-03-14 11:15:32 -07:00
Nikolay Kim
eb37e15554 use specific version of nightly 2019-03-14 10:43:36 -07:00
Nikolay Kim
ad007b8b42 Merge branch 'master' of github.com:actix/actix-net 2019-03-14 10:28:47 -07:00
Nikolay Kim
7c0d1f2273 update travis config 2019-03-14 10:25:34 -07:00
Nikolay Kim
d82bc7c52b Merge pull request #7 from najamelan/fix/compiler_warnings
Fix compiler warnings.
2019-03-14 07:24:37 -07:00
Nikolay Kim
265229b44b allow to override port 2019-03-13 22:55:01 -07:00
Nikolay Kim
38545dedc7 refactor Connect type and add tests 2019-03-13 22:51:31 -07:00
Nikolay Kim
6ebff22601 simplify name 2019-03-13 16:38:08 -07:00
Nikolay Kim
2c9b91b366 add specific constructors 2019-03-13 15:55:20 -07:00
Nikolay Kim
b483200037 remove generic 2019-03-13 15:52:51 -07:00
Nikolay Kim
a73600fbcd remove generic E 2019-03-13 15:51:21 -07:00
Nikolay Kim
084a28ca07 add Connect::with_request 2019-03-13 15:49:31 -07:00
Nikolay Kim
a7c74c53ea store request in Connect request 2019-03-13 15:37:12 -07:00
Nikolay Kim
3e7d737e73 update travis 2019-03-13 14:39:02 -07:00
Nikolay Kim
87db4bf741 changes 2019-03-13 14:38:33 -07:00
Nikolay Kim
8b0fe6f796 rename crate 2019-03-13 12:41:41 -07:00
Nikolay Kim
52a45fda53 redesign actix-connector 2019-03-13 12:40:11 -07:00
Naja Melan
2c7de7e0fb Fix compiler warnings.
Compiles in stable and nightly
2019-03-13 08:41:26 +01:00
Nikolay Kim
1fcc0734b5 prep release 2019-03-12 17:01:02 -07:00
Nikolay Kim
b6f952b036 remove constraint 2019-03-12 16:49:57 -07:00
Nikolay Kim
0fdac38307 add constraint 2019-03-12 16:48:29 -07:00
Nikolay Kim
a3c4637372 prepare actix-server release 2019-03-12 16:40:22 -07:00
Nikolay Kim
ae9bc5ae78 refactor ApplyConfig combinator 2019-03-12 16:32:10 -07:00
Nikolay Kim
21c289d7e4 fix InOrderService::poll_ready() nested service rediness check 2019-03-12 16:03:05 -07:00
Nikolay Kim
5e6eed905c fix InFlightService::poll_ready() nested service rediness check 2019-03-12 15:48:02 -07:00
Nikolay Kim
6801a38de5 check readiness for all services 2019-03-12 15:15:14 -07:00
Nikolay Kim
39356690b0 use ServerConfig for system configuration 2019-03-12 14:14:21 -07:00
Nikolay Kim
f6f292a678 enforce constraint on OpensslAcceptor 2019-03-12 13:57:28 -07:00
Nikolay Kim
b3366bc1af service response is not important 2019-03-12 13:55:31 -07:00
Nikolay Kim
2c1f8f0b96 enforce constraints on AndThenNewService type 2019-03-12 13:50:14 -07:00
Nikolay Kim
e7465bfa2e fix map_err constraints 2019-03-12 13:45:05 -07:00
Nikolay Kim
755d4958c5 use IntoService types for transform services 2019-03-12 13:39:04 -07:00
Nikolay Kim
825117fd4c add Deref/DerefMut impls for Io 2019-03-12 13:12:22 -07:00
Nikolay Kim
7033b50fed add Io::set method for overriding param 2019-03-12 12:53:43 -07:00
Nikolay Kim
ef9bfb8981 add helpers 2019-03-12 12:53:08 -07:00
Nikolay Kim
bef199f831 add blocking mod support 2019-03-11 22:54:27 -07:00
Nikolay Kim
f1d4bcef4b add Arbiter::exec_fn and exec functions 2019-03-11 22:51:17 -07:00
Nikolay Kim
8e13ba7bce update readme 2019-03-11 18:24:31 -07:00
Nikolay Kim
9a9b3e9ca9 update server tests 2019-03-11 15:19:28 -07:00
Nikolay Kim
5567fb41d2 add default type parameter 2019-03-11 13:48:55 -07:00
Nikolay Kim
ad50595ece add PartialEq impl for Io 2019-03-11 13:37:30 -07:00
Nikolay Kim
2430c7247b update timing for travis 2019-03-11 12:53:16 -07:00
Nikolay Kim
1bf0f1e1a5 add Debug impl for Io; update examples 2019-03-11 12:46:12 -07:00
Nikolay Kim
9887aef6e8 add delay to test 2019-03-11 12:35:57 -07:00
Nikolay Kim
787255d030 add io parameters 2019-03-11 12:01:55 -07:00
Nikolay Kim
f696914038 prepare router release 2019-03-09 14:38:08 -08:00
Nikolay Kim
3618f542fb prepare release actix-utils 2019-03-09 14:30:37 -08:00
Nikolay Kim
1f54ae9051 update deps 2019-03-09 14:23:08 -08:00
Nikolay Kim
86f57e5a4a prepare actix-service release 2019-03-09 14:10:02 -08:00
Nikolay Kim
43ad18ccb1 remove get_decoded 2019-03-09 13:58:07 -08:00
Nikolay Kim
34995a8ccf revert re-quoting change 2019-03-09 13:56:09 -08:00
Nikolay Kim
0ff300c40f export ApplyConfig 2019-03-09 09:05:51 -08:00
Nikolay Kim
629ef23371 add .apply_cfg new service combinator 2019-03-09 09:02:23 -08:00
Nikolay Kim
d2b96ff877 add ServerConfig to server services 2019-03-09 07:31:22 -08:00
Nikolay Kim
ac62e2dbf9 revert generic request in actix-utils 2019-03-09 07:27:35 -08:00
Nikolay Kim
6bbbdba921 revert generic Request change 2019-03-09 06:36:23 -08:00
Nikolay Kim
2099629fe3 cleanup ssl services 2019-03-08 22:41:30 -08:00
Nikolay Kim
a4d4770462 remove server config 2019-03-08 22:38:39 -08:00
Nikolay Kim
70ead175b9 IntoService for fn_cfg_factory 2019-03-08 20:51:50 -08:00
Nikolay Kim
49867b5e9d fix IntoService 2019-03-08 20:50:29 -08:00
Nikolay Kim
0f064c43e9 remove uneeded code 2019-03-08 20:10:47 -08:00
Nikolay Kim
7db29544f9 add ServerConfig param for server service 2019-03-08 19:43:13 -08:00
Nikolay Kim
4850cf41ff rename module 2019-03-08 16:26:30 -08:00
Nikolay Kim
046142ffbc added is_prefix_match and resource_path 2019-03-08 15:34:40 -08:00
Nikolay Kim
49e6dbcda2 remove unused ResourceMap 2019-03-08 12:33:44 -08:00
Nikolay Kim
877614a494 add params decoding 2019-03-08 04:43:51 -08:00
Nikolay Kim
ac0e8b9e53 re-enable examples 2019-03-06 23:33:35 -08:00
Nikolay Kim
b407c65f4c add FramedParts::with_read_buf method 2019-03-06 22:53:55 -08:00
Nikolay Kim
51bd7d2721 update actix-rt 2019-03-06 10:39:53 -08:00
Nikolay Kim
c03d869694 return io::Result from run method, remove Handle 2019-03-06 10:24:58 -08:00
Nikolay Kim
25f1eae51f add ResourceDef::root_prefix, insert slash to the beggining of the pattern 2019-03-05 21:03:53 -08:00
Nikolay Kim
1153715149 change generics order for Transform trait 2019-03-05 09:49:08 -08:00
Nikolay Kim
aa2967c653 fix feature gated code 2019-03-05 07:41:41 -08:00
Nikolay Kim
dfbb77f98d make service Request type generic 2019-03-05 07:35:26 -08:00
Nikolay Kim
e8a49801eb revert IntoFuture change 2019-03-04 21:37:06 -08:00
Nikolay Kim
03f2046a42 add ApplyTransform new service 2019-03-04 21:25:50 -08:00
Nikolay Kim
2e18ca805c use IntoFuture 2019-03-04 20:40:38 -08:00
Nikolay Kim
15dafeff3d use IntoFuture instead of Future 2019-03-04 20:37:03 -08:00
Nikolay Kim
ed14e6b8ea change to IntoFuture 2019-03-04 20:29:35 -08:00
Nikolay Kim
700abc997e prepare actix-utils release 2019-03-04 19:45:17 -08:00
Nikolay Kim
8c48bf4de7 simplify transform trait 2019-03-04 19:38:11 -08:00
Nikolay Kim
9bc492cf6c add SslError 2019-03-04 16:16:39 -08:00
Nikolay Kim
d2a223e69e update changes 2019-03-04 15:42:25 -08:00
Nikolay Kim
e9657a399a add maxconnrate 2019-03-04 15:41:16 -08:00
Nikolay Kim
9f25fdf929 rename StreamServiceFactory to ServiceFactory 2019-03-04 14:31:46 -08:00
Nikolay Kim
82930de8e7 use default type for RouterBuilder 2019-03-04 14:03:46 -08:00
Nikolay Kim
04a3e59bd5 update tests 2019-03-04 12:41:39 -08:00
Nikolay Kim
0ff0daa795 allow custom checks for resource selection 2019-03-04 11:47:03 -08:00
Nikolay Kim
fb43940824 allow empty pattern 2019-03-03 21:00:58 -08:00
Nikolay Kim
0410f59cf5 prep release 2019-03-02 14:55:22 -08:00
Nikolay Kim
400023a07b prepare actix-connector release 2019-03-02 14:47:52 -08:00
Nikolay Kim
2e4c84dbb6 prepare actix-server release 2019-03-02 14:42:31 -08:00
Nikolay Kim
672c3936a6 prepare actix-utils release 2019-03-02 14:30:32 -08:00
Nikolay Kim
fbf4444b04 prep release 2019-03-02 14:22:03 -08:00
Nikolay Kim
b5b3168b34 do not use void for now 2019-03-02 13:49:21 -08:00
Nikolay Kim
668e4f9ac4 update utils; add NewTransform::map_init_err 2019-03-02 13:18:01 -08:00
Nikolay Kim
d0b8b6940c add configuration parameter to transform factory 2019-03-02 12:16:30 -08:00
Nikolay Kim
f1bc9d0deb update tests 2019-02-22 18:47:29 -08:00
Nikolay Kim
6ed020565c update service crate 2019-02-22 18:31:25 -08:00
Nikolay Kim
7ee33efdfd moved boxed service and new service to actix-service 2019-02-22 18:20:54 -08:00
Nikolay Kim
83f51b28d7 allow to customize cfg parameter for FnNewService 2019-02-22 17:12:26 -08:00
Nikolay Kim
83a19e9cb3 add IntoConfigurableNewService 2019-02-22 14:30:00 -08:00
Nikolay Kim
6b4010892d add IntoNewService for FnNewService 2019-02-22 14:19:43 -08:00
Nikolay Kim
d2bd9134aa add fn service helpers 2019-02-22 14:13:48 -08:00
Nikolay Kim
a0e2d926e6 add fn_nservice 2019-02-22 13:20:52 -08:00
Nikolay Kim
43d2dd473f update tests 2019-02-22 13:08:31 -08:00
Nikolay Kim
862be49e30 add Config argument to NewService 2019-02-22 12:44:37 -08:00
Nikolay Kim
6ea128fac5 Custom BoxedNewService implementation 2019-02-21 11:19:28 -08:00
Nikolay Kim
a97d7f0ccf add BoxedNewService and BoxedService 2019-02-21 10:41:39 -08:00
Nikolay Kim
3d7daabdd7 add NewService impls for Rc<S> and Arc<S> 2019-02-19 11:31:54 -08:00
Nikolay Kim
32f4718880 Add Display impl for InOrderError 2019-02-11 08:39:28 -08:00
Nikolay Kim
b8f9bf4bc8 Add Display impl for TimeoutError 2019-02-11 08:34:57 -08:00
Nikolay Kim
e354c6df92 Drop service response 2019-02-09 21:39:17 -08:00
Nikolay Kim
a53f06a1a4 allow register router resource for ResourceDef 2019-02-09 20:43:39 -08:00
Nikolay Kim
9979bfb3ef rename Pattern to ResourceDef 2019-02-09 07:24:35 -08:00
Nikolay Kim
17d0f84f63 prep actix-utils 2019-02-06 11:40:22 -08:00
Nikolay Kim
08bc328826 clippy warnings 2019-02-04 11:04:10 -08:00
Nikolay Kim
7dca264546 move transform map_err combinator to separate module 2019-02-04 10:55:39 -08:00
Nikolay Kim
3bddba5da5 helper method 2019-02-03 14:12:15 -08:00
Nikolay Kim
4be025926c add InOrder service 2019-02-03 14:05:13 -08:00
Nikolay Kim
0063a26aab prepare actix-service release 2019-02-03 13:32:51 -08:00
Nikolay Kim
bcc466f6ab update tests 2019-02-03 11:48:11 -08:00
Nikolay Kim
663ae53954 fix Clone impl for Timeout 2019-02-03 11:37:34 -08:00
Nikolay Kim
406088524e depend on git repo 2019-02-03 11:33:26 -08:00
Nikolay Kim
5b8446105f depend on repo 2019-02-03 11:16:24 -08:00
Nikolay Kim
429ad453d3 change Apply::new_fn to old args order 2019-02-03 10:52:44 -08:00
Nikolay Kim
bd977373bc generalize apply combinator with transform trait 2019-02-03 10:42:27 -08:00
Nikolay Kim
d45fb9521f update deps 2019-02-01 20:11:30 -08:00
Nikolay Kim
94a0da3659 prepare actix-connector release 2019-02-01 20:06:53 -08:00
Nikolay Kim
8d62ac4b2f prepare actix-server release 2019-02-01 20:03:31 -08:00
Nikolay Kim
442163690e prepare actix-utils release 2019-02-01 20:00:12 -08:00
Nikolay Kim
d83bf95304 Use associated type instead of generic for Service definition 2019-02-01 19:53:13 -08:00
Nikolay Kim
8cdbf49187 better inflight readiness check 2019-02-01 15:15:53 -08:00
Nikolay Kim
132be0baa1 better naming 2019-02-01 14:48:09 -08:00
Nikolay Kim
cedba24a36 add Url type from actix web 2019-02-01 13:25:56 -08:00
Nikolay Kim
aa20b304ec more refactorings for framed transport 2019-01-26 22:07:27 -08:00
Nikolay Kim
9f0a288e4b refactor FramedTransport 2019-01-26 21:41:28 -08:00
Nikolay Kim
cabebb6b3f add time services tests 2019-01-26 13:21:56 -08:00
Nikolay Kim
84bd257b86 update deps 2019-01-26 13:15:17 -08:00
Nikolay Kim
ff6ac0a67f add System time service 2019-01-26 13:14:37 -08:00
Nikolay Kim
c1c989034d Added Clone impl for Timeout service factory 2019-01-25 14:31:27 -08:00
Nikolay Kim
515bfad830 prep release 2019-01-24 20:42:30 -08:00
Nikolay Kim
0340d82314 better ergonomics for .apply combinator 2019-01-24 20:41:42 -08:00
Nikolay Kim
88548199d7 change apply combinator error semantic 2019-01-24 19:19:44 -08:00
Nikolay Kim
278176fca5 use FnMut instead of Fn 2019-01-16 15:33:33 -08:00
Nikolay Kim
2c8e7c4ae4 add helper constructors to Either service 2019-01-16 15:33:10 -08:00
Nikolay Kim
b6414d6197 use FnMut instead of Fn 2019-01-16 15:00:23 -08:00
Nikolay Kim
f94ef5248e add Clone impl for Either service 2019-01-16 15:00:08 -08:00
Nikolay Kim
cbc378b67f allow deserialize from the path 2019-01-15 19:25:49 -08:00
Nikolay Kim
db2367b26e properly check readiness inclosed service 2019-01-14 09:41:10 -08:00
Nikolay Kim
0bee4db270 use new service converter 2019-01-13 23:30:42 -08:00
Nikolay Kim
615a0d52ed add service and new service for stream dispatcher 2019-01-13 23:12:46 -08:00
Nikolay Kim
cfb62ccc40 Make Out::Error convertable from T::Error for apply combinator 2019-01-13 22:58:23 -08:00
Nikolay Kim
605a947c3e update version 2019-01-13 10:06:54 -08:00
Nikolay Kim
31f0a96c20 Upgrade trust-dns-proto 2019-01-13 10:03:33 -08:00
Nikolay Kim
66a7c59aaf fix changelog 2019-01-11 21:42:13 -08:00
Nikolay Kim
316974616a Use FnMut instead of Fn for FnService 2019-01-11 21:39:58 -08:00
Nikolay Kim
b5d84bd980 use release version of string 2019-01-10 10:40:27 -08:00
Nikolay Kim
e969429e2c different string crate version 2019-01-09 19:54:52 -08:00
Nikolay Kim
6fe741025f add host and port for test server 2019-01-07 21:09:56 -08:00
Nikolay Kim
f8e170fdaf add enum support for path deserializer 2019-01-06 10:26:59 -08:00
Nikolay Kim
474fed4dfe more tests for de 2019-01-06 08:12:51 -08:00
Nikolay Kim
2b8f41e9e4 helper impls for Router 2019-01-05 22:00:38 -08:00
Nikolay Kim
3484007e4e add router crate 2019-01-05 13:20:32 -08:00
Nikolay Kim
58ba1d8269 use service error for stream dispatcher 2019-01-05 13:19:06 -08:00
Nikolay Kim
7017bad4bb add test server 2019-01-01 22:59:52 -08:00
Nikolay Kim
112a7b6b1b fix error handling 2018-12-26 11:50:07 -08:00
Nikolay Kim
48a1c7320c fix io handling code 2018-12-21 13:00:26 -08:00
Nikolay Kim
37d28304c9 Fix max concurrent connections handling 2018-12-21 10:38:08 -08:00
Nikolay Kim
640c39fdc8 better usage for Framed type 2018-12-16 16:26:24 -08:00
Nikolay Kim
cd5435e5ee fix service tests 2018-12-12 18:56:39 -08:00
Nikolay Kim
bf9bd97173 split ServiceExt trait 2018-12-12 18:32:19 -08:00
Nikolay Kim
61939c7af2 Release future early for .and_then() and .then() combinators 2018-12-12 18:00:35 -08:00
Nikolay Kim
e8a1664c15 prepare release 2018-12-12 14:24:46 -08:00
Nikolay Kim
d1bfae7414 fix backpressure for ssl concurrent handshakes 2018-12-12 14:24:24 -08:00
Nikolay Kim
5ca00dc798 rename ServiceConfig::rt to ServiceConfig::apply 2018-12-12 14:16:16 -08:00
Nikolay Kim
fd3e77ea83 fix signals handling on windows 2018-12-11 14:03:06 -08:00
Nikolay Kim
d38eb00793 no readme 2018-12-11 08:36:03 -08:00
Nikolay Kim
3c9d95bd9f no readme 2018-12-11 08:33:28 -08:00
Nikolay Kim
331db2eb47 use released version 2018-12-11 08:28:44 -08:00
Nikolay Kim
de66b5c776 fix examples 2018-12-11 08:20:19 -08:00
Nikolay Kim
4adbbad450 update travis config 2018-12-11 08:13:58 -08:00
Nikolay Kim
42ec3454d9 add signals support 2018-12-10 21:06:54 -08:00
Nikolay Kim
e6daca7995 try to parse host first 2018-12-10 18:08:07 -08:00
Nikolay Kim
d35c87d228 move helper services to separate package 2018-12-10 16:16:40 -08:00
Nikolay Kim
ba006d95c7 prepare actix-utils 2018-12-10 08:42:31 -08:00
Nikolay Kim
9577b7bbed add helper fn 2018-12-09 22:19:26 -08:00
Nikolay Kim
8ad93f4838 move server to separate crate 2018-12-09 22:14:29 -08:00
Nikolay Kim
ffb07c8884 use actix-rt for server impl 2018-12-09 21:51:35 -08:00
Nikolay Kim
cdd6904aa0 rename Server to ServerBuilder 2018-12-09 20:30:14 -08:00
Nikolay Kim
98a151db4f add actix single threaded runtime 2018-12-09 19:55:40 -08:00
Nikolay Kim
227ea15683 remove unused code 2018-12-09 15:21:23 -08:00
Nikolay Kim
e50be58fdb move codec to separate crate 2018-12-09 15:19:25 -08:00
Nikolay Kim
3288b7648d update changes 2018-12-09 10:16:35 -08:00
Nikolay Kim
43e14818c4 migrate to actix-service crate 2018-12-09 10:15:49 -08:00
Nikolay Kim
a60bf691d5 add Service impl for Box<S> 2018-12-09 10:14:08 -08:00
Nikolay Kim
5f37d85f9b move service to separate crate 2018-12-09 09:56:23 -08:00
Nikolay Kim
e8aa73a44b update tests 2018-12-06 14:53:55 -08:00
Nikolay Kim
8fe7ce533c convert to edition 2018 2018-12-06 14:04:42 -08:00
Nikolay Kim
42a4679635 use FnMut for apply combinator 2018-12-05 17:43:31 -08:00
Nikolay Kim
36a15efeac do not export cell 2018-12-03 17:46:25 -08:00
Nikolay Kim
5937a06ebe export cell 2018-12-03 13:49:46 -08:00
Nikolay Kim
a16ad6b2cd cleanup clonable service 2018-11-30 11:55:30 -08:00
Nikolay Kim
8108f19580 update tests 2018-11-29 17:17:02 -10:00
Nikolay Kim
1b1ae01b5a migrate to new Service<Request> trait 2018-11-29 16:56:15 -10:00
114 changed files with 10776 additions and 3826 deletions

View File

@@ -10,13 +10,13 @@ matrix:
include:
- rust: stable
- rust: beta
- rust: nightly
- rust: nightly-2019-03-02
allow_failures:
- rust: nightly
- rust: nightly-2019-03-02
env:
global:
# - RUSTFLAGS="-C link-dead-code"
- RUSTFLAGS="-C link-dead-code"
- OPENSSL_VERSION=openssl-1.0.2
before_install:
@@ -24,31 +24,26 @@ before_install:
- sudo apt-get update -qq
- sudo apt-get install -y openssl libssl-dev libelf-dev libdw-dev cmake gcc binutils-dev libiberty-dev
before_cache: |
if [[ "$TRAVIS_RUST_VERSION" == "nightly-2019-03-02" ]]; then
RUSTFLAGS="--cfg procmacro2_semver_exempt" cargo install cargo-tarpaulin
fi
# Add clippy
before_script:
- export PATH=$PATH:~/.cargo/bin
script:
- |
if [[ "$TRAVIS_RUST_VERSION" != "nightly" ]]; then
if [[ "$TRAVIS_RUST_VERSION" != "nightly-2019-03-02" ]]; then
cargo clean
cargo test --features="ssl,tls,rust-tls" -- --nocapture
fi
- |
if [[ "$TRAVIS_RUST_VERSION" == "nightly" ]]; then
RUSTFLAGS="--cfg procmacro2_semver_exempt" cargo install -f cargo-tarpaulin
cargo tarpaulin --features="ssl,tls,rust-tls" --out Xml
bash <(curl -s https://codecov.io/bash)
echo "Uploaded code coverage"
cargo test --all --all-features -- --nocapture
fi
# Upload docs
after_success:
- |
if [[ "$TRAVIS_OS_NAME" == "linux" && "$TRAVIS_PULL_REQUEST" = "false" && "$TRAVIS_BRANCH" == "master" && "$TRAVIS_RUST_VERSION" == "beta" ]]; then
cargo doc --features "ssl,tls,rust-tls" --no-deps &&
echo "<meta http-equiv=refresh content=0;url=os_balloon/index.html>" > target/doc/index.html &&
git clone https://github.com/davisp/ghp-import.git &&
./ghp-import/ghp_import.py -n -p -f -m "Documentation upload" -r https://"$GH_TOKEN"@github.com/"$TRAVIS_REPO_SLUG.git" target/doc &&
echo "Uploaded documentation"
if [[ "$TRAVIS_RUST_VERSION" == "nightly-2019-03-02" ]]; then
taskset -c 0 cargo tarpaulin --all --all-features --out Xml
echo "Uploaded code coverage"
bash <(curl -s https://codecov.io/bash)
fi

View File

@@ -1,19 +1,10 @@
# Changes
## [0.2.6] - 2018-12-21
## [0.3.0] - xxx
### Fixed
* Split `Service` trait to separate crate
* Fix back-pressure handling for concurrent connections
## [0.2.5] - 2018-12-12
### Fixed
* Fix back-pressure for concurrent ssl handshakes
* Drop completed future for .then and .and_then combinators
* Use new `Service<Request>` trait
## [0.2.4] - 2018-11-21

View File

@@ -1,8 +1,8 @@
[package]
name = "actix-net"
version = "0.2.6"
version = "0.3.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix net - framework for the compisible network services for Rust (experimental)"
description = "Actix net - framework for the compisible network services for Rust"
readme = "README.md"
keywords = ["network", "framework", "async", "futures"]
homepage = "https://actix.rs"
@@ -11,72 +11,29 @@ documentation = "https://docs.rs/actix-net/"
categories = ["network-programming", "asynchronous"]
license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
edition = "2018"
[package.metadata.docs.rs]
features = ["ssl", "tls", "rust-tls"]
[badges]
travis-ci = { repository = "actix/actix-net", branch = "master" }
# appveyor = { repository = "fafhrd91/actix-web-hdy9d" }
codecov = { repository = "actix/actix-net", branch = "master", service = "github" }
[lib]
name = "actix_net"
path = "src/lib.rs"
[features]
default = []
# tls
tls = ["native-tls"]
# openssl
ssl = ["openssl", "tokio-openssl"]
# rustls
rust-tls = ["rustls", "tokio-rustls", "webpki", "webpki-roots"]
cell = []
[dependencies]
actix = "0.7.6"
log = "0.4"
num_cpus = "1.0"
# io
mio = "^0.6.13"
net2 = "0.2"
bytes = "0.4"
futures = "0.1"
slab = "0.4"
tokio = "0.1"
tokio-codec = "0.1"
tokio-io = "0.1"
tokio-tcp = "0.1"
tokio-timer = "0.2"
tokio-reactor = "0.1"
tokio-current-thread = "0.1"
tower-service = "0.1"
trust-dns-resolver = "^0.10.2"
# native-tls
native-tls = { version="0.2", optional = true }
# openssl
openssl = { version="0.10", optional = true }
tokio-openssl = { version="0.2", optional = true }
#rustls
rustls = { version = "^0.14", optional = true }
tokio-rustls = { version = "^0.8", optional = true }
webpki = { version = "0.18", optional = true }
webpki-roots = { version = "0.15", optional = true }
[workspace]
members = [
"actix-codec",
"actix-connect",
"actix-rt",
"actix-service",
"actix-server",
"actix-server-config",
"actix-test-server",
"actix-threadpool",
"actix-utils",
"router",
]
[dev-dependencies]
env_logger = "0.5"
[profile.release]
lto = true
opt-level = 3
codegen-units = 1
actix-service = "0.3.3"
actix-codec = "0.1.1"
actix-rt = "0.2.0"
actix-server = { path="actix-server", features=["ssl"] }
env_logger = "0.6"
futures = "0.1.25"
openssl = "0.10"
tokio-tcp = "0.1"
tokio-openssl = "0.3"

View File

@@ -1,20 +1,18 @@
# Actix net [![Build Status](https://travis-ci.org/actix/actix-net.svg?branch=master)](https://travis-ci.org/actix/actix-net) [![codecov](https://codecov.io/gh/actix/actix-net/branch/master/graph/badge.svg)](https://codecov.io/gh/actix/actix-net) [![crates.io](https://meritbadge.herokuapp.com/actix-net)](https://crates.io/crates/actix-net) [![Join the chat at https://gitter.im/actix/actix](https://badges.gitter.im/actix/actix.svg)](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
Actix net - framework for composable network services (experimental)
Actix net - framework for composable network services
## Documentation & community resources
* [API Documentation (Development)](https://actix.rs/actix-net/actix_net/)
* [Chat on gitter](https://gitter.im/actix/actix)
* Cargo package: [actix-net](https://crates.io/crates/actix-net)
* Minimum supported Rust version: 1.26 or later
* Minimum supported Rust version: 1.32 or later
## Example
```rust
fn main() {
let sys = actix::System::new("test");
fn main() -> io::Result<()> {
// load ssl keys
let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
builder.set_private_key_file("./examples/key.pem", SslFiletype::PEM).unwrap();
@@ -26,7 +24,7 @@ fn main() {
// bind socket address and start workers. By default server uses number of
// available logical cpu as threads count. actix net start separate
// instances of service pipeline in each worker.
Server::default()
Server::build()
.bind(
// configure service pipeline
"basic", "0.0.0.0:8443",
@@ -35,28 +33,23 @@ fn main() {
let acceptor = acceptor.clone();
// service for converting incoming TcpStream to a SslStream<TcpStream>
(move |stream| {
SslAcceptorExt::accept_async(&acceptor, stream)
.map_err(|e| println!("Openssl error: {}", e))
})
// convert closure to a `NewService`
.into_new_service()
// .and_then() combinator uses other service to convert incoming `Request` to a `Response`
// and then uses that response as an input for next service.
// in this case, on success we use `logger` service
.and_then(logger)
// Next service counts number of connections
.and_then(move |req| {
let num = num.fetch_add(1, Ordering::Relaxed);
println!("processed {:?} connections", num);
future::ok(())
})
}).unwrap()
.start();
sys.run();
fn_service(move |stream: Io<tokio_tcp::TcpStream>| {
SslAcceptorExt::accept_async(&acceptor, stream.into_parts().0)
.map_err(|e| println!("Openssl error: {}", e))
})
// .and_then() combinator uses other service to convert incoming `Request` to a
// `Response` and then uses that response as an input for next
// service. in this case, on success we use `logger` service
.and_then(fn_service(logger))
// Next service counts number of connections
.and_then(move |_| {
let num = num.fetch_add(1, Ordering::Relaxed);
println!("got ssl connection {:?}", num);
future::ok(())
})
},
)?
.run()
}
```

15
actix-codec/CHANGES.md Normal file
View File

@@ -0,0 +1,15 @@
# Changes
## [0.1.2] - 2019-03-27
* Added `Framed::map_io()` method.
## [0.1.1] - 2019-03-06
* Added `FramedParts::with_read_buffer()` method.
## [0.1.0] - 2018-12-09
* Move codec to separate crate

25
actix-codec/Cargo.toml Normal file
View File

@@ -0,0 +1,25 @@
[package]
name = "actix-codec"
version = "0.1.2"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Utilities for encoding and decoding frames"
keywords = ["network", "framework", "async", "futures"]
homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-net.git"
documentation = "https://docs.rs/actix-codec/"
categories = ["network-programming", "asynchronous"]
license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
edition = "2018"
workspace = ".."
[lib]
name = "actix_codec"
path = "src/lib.rs"
[dependencies]
bytes = "0.4.12"
futures = "0.1.24"
tokio-io = "0.1.12"
tokio-codec = "0.1.1"
log = "0.4"

View File

@@ -167,6 +167,22 @@ impl<T, U> Framed<T, U> {
}
}
/// Consume the `Frame`, returning `Frame` with different io.
pub fn map_io<F, T2>(self, f: F) -> Framed<T2, U>
where
F: Fn(T) -> T2,
{
let (inner, read_buf) = self.inner.into_parts();
let (inner, write_buf, lw, hw) = inner.into_parts();
Framed {
inner: framed_read2_with_buffer(
framed_write2_with_buffer(Fuse(f(inner.0), inner.1), write_buf, lw, hw),
read_buf,
),
}
}
/// Consume the `Frame`, returning `Frame` with different codec.
pub fn map_codec<F, U2>(self, f: F) -> Framed<T, U2>
where
@@ -349,4 +365,17 @@ impl<T, U> FramedParts<T, U> {
_priv: (),
}
}
/// Create a new `FramedParts` with read buffer
pub fn with_read_buf(io: T, codec: U, read_buf: BytesMut) -> FramedParts<T, U> {
FramedParts {
io,
codec,
read_buf,
write_buf: BytesMut::new(),
write_buf_lw: LW,
write_buf_hw: HW,
_priv: (),
}
}
}

View File

@@ -1,7 +1,8 @@
use std::fmt;
use bytes::BytesMut;
use futures::{Async, Poll, Sink, StartSend, Stream};
use futures::{try_ready, Async, Poll, Sink, StartSend, Stream};
use log::trace;
use tokio_codec::Decoder;
use tokio_io::AsyncRead;
@@ -133,7 +134,7 @@ where
pub fn framed_read2<T>(inner: T) -> FramedRead2<T> {
FramedRead2 {
inner: inner,
inner,
eof: false,
is_readable: false,
buffer: BytesMut::with_capacity(INITIAL_CAPACITY),
@@ -146,9 +147,9 @@ pub fn framed_read2_with_buffer<T>(inner: T, mut buf: BytesMut) -> FramedRead2<T
buf.reserve(bytes_to_reserve);
}
FramedRead2 {
inner: inner,
inner,
eof: false,
is_readable: buf.len() > 0,
is_readable: !buf.is_empty(),
buffer: buf,
}
}
@@ -187,13 +188,13 @@ where
// readable again, at which point the stream is terminated.
if self.is_readable {
if self.eof {
let frame = try!(self.inner.decode_eof(&mut self.buffer));
let frame = self.inner.decode_eof(&mut self.buffer)?;
return Ok(Async::Ready(frame));
}
trace!("attempting to decode a frame");
if let Some(frame) = try!(self.inner.decode(&mut self.buffer)) {
if let Some(frame) = self.inner.decode(&mut self.buffer)? {
trace!("frame decoded from buffer");
return Ok(Async::Ready(Some(frame)));
}

View File

@@ -2,7 +2,8 @@ use std::fmt;
use std::io::{self, Read};
use bytes::BytesMut;
use futures::{Async, AsyncSink, Poll, Sink, StartSend, Stream};
use futures::{try_ready, Async, AsyncSink, Poll, Sink, StartSend, Stream};
use log::trace;
use tokio_codec::{Decoder, Encoder};
use tokio_io::{AsyncRead, AsyncWrite};
@@ -111,7 +112,7 @@ where
}
fn close(&mut self) -> Poll<(), Self::SinkError> {
Ok(try!(self.inner.close()))
Ok(self.inner.close()?)
}
}
@@ -267,12 +268,12 @@ where
try_ready!(self.inner.poll_flush());
trace!("framed transport flushed");
return Ok(Async::Ready(()));
Ok(Async::Ready(()))
}
fn close(&mut self) -> Poll<(), Self::SinkError> {
try_ready!(self.poll_complete());
Ok(try!(self.inner.shutdown()))
Ok(self.inner.shutdown()?)
}
}

View File

@@ -10,16 +10,15 @@
//! [`Stream`]: #
//! [transports]: #
#![deny(missing_docs, missing_debug_implementations, warnings)]
mod bcodec;
mod framed;
// mod framed2;
mod framed_read;
mod framed_write;
pub use self::bcodec::BytesCodec;
pub use self::framed::{Framed, FramedParts};
// pub use self::framed2::{Framed2, FramedParts2};
pub use self::framed_read::FramedRead;
pub use self::framed_write::FramedWrite;
pub use tokio_codec::{Decoder, Encoder};
pub use tokio_io::{AsyncRead, AsyncWrite};

25
actix-connect/CHANGES.md Normal file
View File

@@ -0,0 +1,25 @@
# Changes
## [0.1.2] - 2019-04-04
### Added
* Log error if dns system config could not be loaded.
### Changed
* Rename connect Connector to TcpConnector #10
## [0.1.1] - 2019-03-15
### Fixed
* Fix error handling for single address
## [0.1.0] - 2019-03-14
* Refactor resolver and connector services
* Rename crate

55
actix-connect/Cargo.toml Normal file
View File

@@ -0,0 +1,55 @@
[package]
name = "actix-connect"
version = "0.1.2"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix Connector - tcp connector service"
keywords = ["network", "framework", "async", "futures"]
homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-net.git"
documentation = "https://docs.rs/actix-connect/"
categories = ["network-programming", "asynchronous"]
license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
edition = "2018"
workspace = ".."
[package.metadata.docs.rs]
features = ["ssl", "uri"]
[lib]
name = "actix_connect"
path = "src/lib.rs"
[features]
default = ["uri"]
# openssl
ssl = ["openssl", "tokio-openssl"]
# support http::Uri as connect address
uri = ["http"]
[dependencies]
actix-service = "0.3.4"
actix-codec = "0.1.1"
actix-utils = "0.3.4"
derive_more = "0.14.0"
either = "1.5.1"
futures = "0.1.25"
http = { version = "0.1.16", optional = true }
log = "0.4"
tokio-tcp = "0.1.3"
tokio-current-thread = "0.1.5"
trust-dns-resolver = { version="0.11.0-alpha.2", default-features = false }
# openssl
openssl = { version="0.10", optional = true }
tokio-openssl = { version="0.3", optional = true }
[dev-dependencies]
bytes = "0.4"
actix-connect = { path=".", features=["ssl"] }
actix-test-server = { version="0.2.0", features=["ssl"] }
actix-server-config = "0.1.0"
actix-utils = "0.3.4"
tokio-tcp = "0.1"

View File

@@ -0,0 +1,172 @@
use std::collections::VecDeque;
use std::fmt;
use std::net::SocketAddr;
use either::Either;
/// Connect request
pub trait Address {
/// Host name of the request
fn host(&self) -> &str;
/// Port of the request
fn port(&self) -> Option<u16>;
}
impl Address for String {
fn host(&self) -> &str {
&self
}
fn port(&self) -> Option<u16> {
None
}
}
impl Address for &'static str {
fn host(&self) -> &str {
self
}
fn port(&self) -> Option<u16> {
None
}
}
/// Connect request
#[derive(Eq, PartialEq, Debug, Hash)]
pub struct Connect<T> {
pub(crate) req: T,
pub(crate) port: u16,
pub(crate) addr: Option<Either<SocketAddr, VecDeque<SocketAddr>>>,
}
impl<T: Address> Connect<T> {
/// Create `Connect` instance by spliting the string by ':' and convert the second part to u16
pub fn new(req: T) -> Connect<T> {
let (_, port) = parse(req.host());
Connect {
req,
port: port.unwrap_or(0),
addr: None,
}
}
/// Create new `Connect` instance from host and address. Connector skips name resolution stage for such connect messages.
pub fn with(req: T, addr: SocketAddr) -> Connect<T> {
Connect {
req,
port: 0,
addr: Some(Either::Left(addr)),
}
}
/// Use port if address does not provide one.
///
/// By default it set to 0
pub fn set_port(mut self, port: u16) -> Self {
self.port = port;
self
}
/// Host name
pub fn host(&self) -> &str {
self.req.host()
}
/// Port of the request
pub fn port(&self) -> u16 {
self.req.port().unwrap_or(self.port)
}
}
impl<T: Address> From<T> for Connect<T> {
fn from(addr: T) -> Self {
Connect::new(addr)
}
}
impl<T: Address> fmt::Display for Connect<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}:{}", self.host(), self.port())
}
}
fn parse(host: &str) -> (&str, Option<u16>) {
let mut parts_iter = host.splitn(2, ':');
if let Some(host) = parts_iter.next() {
let port_str = parts_iter.next().unwrap_or("");
if let Ok(port) = port_str.parse::<u16>() {
(host, Some(port))
} else {
(host, None)
}
} else {
(host, None)
}
}
pub struct Connection<T, U> {
io: U,
req: T,
}
impl<T, U> Connection<T, U> {
pub fn new(io: U, req: T) -> Self {
Self { io, req }
}
}
impl<T, U> Connection<T, U> {
/// Reconstruct from a parts.
pub fn from_parts(io: U, req: T) -> Self {
Self { io, req }
}
/// Deconstruct into a parts.
pub fn into_parts(self) -> (U, T) {
(self.io, self.req)
}
/// Replace inclosed object, return new Stream and old object
pub fn replace<Y>(self, io: Y) -> (U, Connection<T, Y>) {
(self.io, Connection { io, req: self.req })
}
/// Returns a shared reference to the underlying stream.
pub fn get_ref(&self) -> &U {
&self.io
}
/// Returns a mutable reference to the underlying stream.
pub fn get_mut(&mut self) -> &mut U {
&mut self.io
}
}
impl<T: Address, U> Connection<T, U> {
/// Get request
pub fn host(&self) -> &str {
&self.req.host()
}
}
impl<T, U> std::ops::Deref for Connection<T, U> {
type Target = U;
fn deref(&self) -> &U {
&self.io
}
}
impl<T, U> std::ops::DerefMut for Connection<T, U> {
fn deref_mut(&mut self) -> &mut U {
&mut self.io
}
}
impl<T, U: fmt::Debug> fmt::Debug for Connection<T, U> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Stream {{{:?}}}", self.io)
}
}

View File

@@ -0,0 +1,156 @@
use std::collections::VecDeque;
use std::marker::PhantomData;
use std::net::SocketAddr;
use actix_service::{NewService, Service};
use futures::future::{err, ok, Either, FutureResult};
use futures::{Async, Future, Poll};
use tokio_tcp::{ConnectFuture, TcpStream};
use super::connect::{Address, Connect, Connection};
use super::error::ConnectError;
/// Tcp connector service factory
#[derive(Debug)]
pub struct TcpConnectorFactory<T>(PhantomData<T>);
impl<T> TcpConnectorFactory<T> {
pub fn new() -> Self {
TcpConnectorFactory(PhantomData)
}
}
impl<T> Clone for TcpConnectorFactory<T> {
fn clone(&self) -> Self {
TcpConnectorFactory(PhantomData)
}
}
impl<T: Address> NewService for TcpConnectorFactory<T> {
type Request = Connect<T>;
type Response = Connection<T, TcpStream>;
type Error = ConnectError;
type Service = TcpConnector<T>;
type InitError = ();
type Future = FutureResult<Self::Service, Self::InitError>;
fn new_service(&self, _: &()) -> Self::Future {
ok(TcpConnector(PhantomData))
}
}
/// Tcp connector service
#[derive(Debug)]
pub struct TcpConnector<T>(PhantomData<T>);
impl<T> TcpConnector<T> {
pub fn new() -> Self {
TcpConnector(PhantomData)
}
}
impl<T> Clone for TcpConnector<T> {
fn clone(&self) -> Self {
TcpConnector(PhantomData)
}
}
impl<T: Address> Service for TcpConnector<T> {
type Request = Connect<T>;
type Response = Connection<T, TcpStream>;
type Error = ConnectError;
type Future = Either<TcpConnectorResponse<T>, FutureResult<Self::Response, Self::Error>>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
fn call(&mut self, req: Connect<T>) -> Self::Future {
let port = req.port();
let Connect { req, addr, .. } = req;
if let Some(addr) = addr {
Either::A(TcpConnectorResponse::new(req, port, addr))
} else {
error!("TCP connector: got unresolved address");
Either::B(err(ConnectError::Unresolverd))
}
}
}
#[doc(hidden)]
/// Tcp stream connector response future
pub struct TcpConnectorResponse<T> {
req: Option<T>,
port: u16,
addrs: Option<VecDeque<SocketAddr>>,
stream: Option<ConnectFuture>,
}
impl<T: Address> TcpConnectorResponse<T> {
pub fn new(
req: T,
port: u16,
addr: either::Either<SocketAddr, VecDeque<SocketAddr>>,
) -> TcpConnectorResponse<T> {
trace!(
"TCP connector - connecting to {:?} port:{}",
req.host(),
port
);
match addr {
either::Either::Left(addr) => TcpConnectorResponse {
req: Some(req),
port,
addrs: None,
stream: Some(TcpStream::connect(&addr)),
},
either::Either::Right(addrs) => TcpConnectorResponse {
req: Some(req),
port,
addrs: Some(addrs),
stream: None,
},
}
}
}
impl<T: Address> Future for TcpConnectorResponse<T> {
type Item = Connection<T, TcpStream>;
type Error = ConnectError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
// connect
loop {
if let Some(new) = self.stream.as_mut() {
match new.poll() {
Ok(Async::Ready(sock)) => {
let req = self.req.take().unwrap();
trace!(
"TCP connector - successfully connected to connecting to {:?} - {:?}",
req.host(), sock.peer_addr()
);
return Ok(Async::Ready(Connection::new(sock, req)));
}
Ok(Async::NotReady) => return Ok(Async::NotReady),
Err(err) => {
trace!(
"TCP connector - failed to connect to connecting to {:?} port: {}",
self.req.as_ref().unwrap().host(),
self.port,
);
if self.addrs.is_none() || self.addrs.as_ref().unwrap().is_empty() {
return Err(err.into());
}
}
}
}
// try to connect
self.stream = Some(TcpStream::connect(
&self.addrs.as_mut().unwrap().pop_front().unwrap(),
));
}
}
}

View File

@@ -0,0 +1,26 @@
use std::io;
use derive_more::{Display, From};
use trust_dns_resolver::error::ResolveError;
#[derive(Debug, From, Display)]
pub enum ConnectError {
/// Failed to resolve the hostname
#[display(fmt = "Failed resolving hostname: {}", _0)]
Resolver(ResolveError),
/// No dns records
#[display(fmt = "No dns records found for the input")]
NoRecords,
/// Invalid input
InvalidInput,
/// Unresolved host name
#[display(fmt = "Connector received `Connect` method with unresolved host")]
Unresolverd,
/// Connection io error
#[display(fmt = "{}", _0)]
Io(io::Error),
}

98
actix-connect/src/lib.rs Normal file
View File

@@ -0,0 +1,98 @@
//! Actix connect - tcp connector service
//!
//! ## Package feature
//!
//! * `ssl` - enables ssl support via `openssl` crate
//! * `rust-tls` - enables ssl support via `rustls` crate
#[macro_use]
extern crate log;
mod connect;
mod connector;
mod error;
mod resolver;
pub mod ssl;
#[cfg(feature = "uri")]
mod uri;
pub use trust_dns_resolver::config::{ResolverConfig, ResolverOpts};
pub use trust_dns_resolver::system_conf::read_system_conf;
pub use trust_dns_resolver::{error::ResolveError, AsyncResolver};
pub use self::connect::{Address, Connect, Connection};
pub use self::connector::{TcpConnector, TcpConnectorFactory};
pub use self::error::ConnectError;
pub use self::resolver::{Resolver, ResolverFactory};
use actix_service::{NewService, Service, ServiceExt};
use tokio_tcp::TcpStream;
#[doc(hidden)]
#[deprecated(since = "0.1.2", note = "please use `actix_connect::TcpConnector`")]
pub type Connector<T> = TcpConnector<T>;
#[doc(hidden)]
#[deprecated(
since = "0.1.2",
note = "please use `actix_connect::TcpConnectorFactory`"
)]
pub type ConnectorFactory<T> = TcpConnectorFactory<T>;
pub fn start_resolver(cfg: ResolverConfig, opts: ResolverOpts) -> AsyncResolver {
let (resolver, bg) = AsyncResolver::new(cfg, opts);
tokio_current_thread::spawn(bg);
resolver
}
pub fn start_default_resolver() -> AsyncResolver {
let (cfg, opts) = match read_system_conf() {
Ok((cfg, opts)) => (cfg, opts),
Err(e) => {
log::error!("TRust-DNS can not load system config: {}", e);
(ResolverConfig::default(), ResolverOpts::default())
}
};
let (resolver, bg) = AsyncResolver::new(cfg, opts);
tokio_current_thread::spawn(bg);
resolver
}
/// Create tcp connector service
pub fn new_connector<T: Address>(
resolver: AsyncResolver,
) -> impl Service<Request = Connect<T>, Response = Connection<T, TcpStream>, Error = ConnectError>
+ Clone {
Resolver::new(resolver).and_then(TcpConnector::new())
}
/// Create tcp connector service
pub fn new_connector_factory<T: Address>(
resolver: AsyncResolver,
) -> impl NewService<
Request = Connect<T>,
Response = Connection<T, TcpStream>,
Error = ConnectError,
InitError = (),
> + Clone {
ResolverFactory::new(resolver).and_then(TcpConnectorFactory::new())
}
/// Create connector service with default parameters
pub fn default_connector<T: Address>(
) -> impl Service<Request = Connect<T>, Response = Connection<T, TcpStream>, Error = ConnectError>
+ Clone {
Resolver::new(start_default_resolver()).and_then(TcpConnector::new())
}
/// Create connector service factory with default parameters
pub fn default_connector_factory<T: Address>() -> impl NewService<
Request = Connect<T>,
Response = Connection<T, TcpStream>,
Error = ConnectError,
InitError = (),
> + Clone {
ResolverFactory::new(start_default_resolver()).and_then(TcpConnectorFactory::new())
}

View File

@@ -0,0 +1,168 @@
use std::collections::VecDeque;
use std::marker::PhantomData;
use std::net::SocketAddr;
use actix_service::{NewService, Service};
use futures::future::{ok, Either, FutureResult};
use futures::{Async, Future, Poll};
use trust_dns_resolver::lookup_ip::LookupIpFuture;
use trust_dns_resolver::{AsyncResolver, Background};
use crate::connect::{Address, Connect};
use crate::error::ConnectError;
/// DNS Resolver Service factory
pub struct ResolverFactory<T> {
resolver: AsyncResolver,
_t: PhantomData<T>,
}
impl<T> ResolverFactory<T> {
/// Create new resolver instance with custom configuration and options.
pub fn new(resolver: AsyncResolver) -> Self {
ResolverFactory {
resolver,
_t: PhantomData,
}
}
pub fn resolver(&self) -> &AsyncResolver {
&self.resolver
}
}
impl<T> Clone for ResolverFactory<T> {
fn clone(&self) -> Self {
ResolverFactory {
resolver: self.resolver.clone(),
_t: PhantomData,
}
}
}
impl<T: Address> NewService for ResolverFactory<T> {
type Request = Connect<T>;
type Response = Connect<T>;
type Error = ConnectError;
type Service = Resolver<T>;
type InitError = ();
type Future = FutureResult<Self::Service, Self::InitError>;
fn new_service(&self, _: &()) -> Self::Future {
ok(Resolver {
resolver: self.resolver.clone(),
_t: PhantomData,
})
}
}
/// DNS Resolver Service
pub struct Resolver<T> {
resolver: AsyncResolver,
_t: PhantomData<T>,
}
impl<T> Resolver<T> {
/// Create new resolver instance with custom configuration and options.
pub fn new(resolver: AsyncResolver) -> Self {
Resolver {
resolver,
_t: PhantomData,
}
}
}
impl<T> Clone for Resolver<T> {
fn clone(&self) -> Self {
Resolver {
resolver: self.resolver.clone(),
_t: PhantomData,
}
}
}
impl<T: Address> Service for Resolver<T> {
type Request = Connect<T>;
type Response = Connect<T>;
type Error = ConnectError;
type Future = Either<ResolverFuture<T>, FutureResult<Connect<T>, Self::Error>>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
fn call(&mut self, mut req: Connect<T>) -> Self::Future {
if req.addr.is_some() {
Either::B(ok(req))
} else {
if let Ok(ip) = req.host().parse() {
req.addr = Some(either::Either::Left(SocketAddr::new(ip, req.port())));
Either::B(ok(req))
} else {
trace!("DNS resolver: resolving host {:?}", req.host());
Either::A(ResolverFuture::new(req, &self.resolver))
}
}
}
}
#[doc(hidden)]
/// Resolver future
pub struct ResolverFuture<T: Address> {
req: Option<Connect<T>>,
lookup: Background<LookupIpFuture>,
}
impl<T: Address> ResolverFuture<T> {
pub fn new(req: Connect<T>, resolver: &AsyncResolver) -> Self {
let lookup = if let Some(host) = req.host().splitn(2, ':').next() {
resolver.lookup_ip(host)
} else {
resolver.lookup_ip(req.host())
};
ResolverFuture {
lookup,
req: Some(req),
}
}
}
impl<T: Address> Future for ResolverFuture<T> {
type Item = Connect<T>;
type Error = ConnectError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
match self.lookup.poll().map_err(|e| {
trace!(
"DNS resolver: failed to resolve host {:?} err: {}",
self.req.as_ref().unwrap().host(),
e
);
e
})? {
Async::NotReady => Ok(Async::NotReady),
Async::Ready(ips) => {
let mut req = self.req.take().unwrap();
let mut addrs: VecDeque<_> = ips
.iter()
.map(|ip| SocketAddr::new(ip, req.port()))
.collect();
trace!(
"DNS resolver: host {:?} resolved to {:?}",
req.host(),
addrs
);
if addrs.is_empty() {
Err(ConnectError::NoRecords)
} else if addrs.len() == 1 {
req.addr = Some(either::Either::Left(addrs.pop_front().unwrap()));
Ok(Async::Ready(req))
} else {
req.addr = Some(either::Either::Right(addrs));
Ok(Async::Ready(req))
}
}
}
}
}

View File

@@ -0,0 +1,6 @@
//! SSL Services
#[cfg(feature = "ssl")]
mod openssl;
#[cfg(feature = "ssl")]
pub use self::openssl::OpensslConnector;

View File

@@ -0,0 +1,127 @@
use std::fmt;
use std::marker::PhantomData;
use actix_codec::{AsyncRead, AsyncWrite};
use actix_service::{NewService, Service};
use futures::{future::ok, future::FutureResult, Async, Future, Poll};
use openssl::ssl::{HandshakeError, SslConnector};
use tokio_openssl::{ConnectAsync, SslConnectorExt, SslStream};
use crate::{Address, Connection};
/// Openssl connector factory
pub struct OpensslConnector<T, U> {
connector: SslConnector,
_t: PhantomData<(T, U)>,
}
impl<T, U> OpensslConnector<T, U> {
pub fn new(connector: SslConnector) -> Self {
OpensslConnector {
connector,
_t: PhantomData,
}
}
}
impl<T, U> OpensslConnector<T, U>
where
T: Address,
U: AsyncRead + AsyncWrite + fmt::Debug,
{
pub fn service(
connector: SslConnector,
) -> impl Service<
Request = Connection<T, U>,
Response = Connection<T, SslStream<U>>,
Error = HandshakeError<U>,
> {
OpensslConnectorService {
connector: connector,
_t: PhantomData,
}
}
}
impl<T, U> Clone for OpensslConnector<T, U> {
fn clone(&self) -> Self {
Self {
connector: self.connector.clone(),
_t: PhantomData,
}
}
}
impl<T: Address, U> NewService<()> for OpensslConnector<T, U>
where
U: AsyncRead + AsyncWrite + fmt::Debug,
{
type Request = Connection<T, U>;
type Response = Connection<T, SslStream<U>>;
type Error = HandshakeError<U>;
type Service = OpensslConnectorService<T, U>;
type InitError = ();
type Future = FutureResult<Self::Service, Self::InitError>;
fn new_service(&self, _: &()) -> Self::Future {
ok(OpensslConnectorService {
connector: self.connector.clone(),
_t: PhantomData,
})
}
}
pub struct OpensslConnectorService<T, U> {
connector: SslConnector,
_t: PhantomData<(T, U)>,
}
impl<T: Address, U> Service for OpensslConnectorService<T, U>
where
U: AsyncRead + AsyncWrite + fmt::Debug,
{
type Request = Connection<T, U>;
type Response = Connection<T, SslStream<U>>;
type Error = HandshakeError<U>;
type Future = ConnectAsyncExt<T, U>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
fn call(&mut self, stream: Connection<T, U>) -> Self::Future {
trace!("SSL Handshake start for: {:?}", stream.host());
let (io, stream) = stream.replace(());
ConnectAsyncExt {
fut: SslConnectorExt::connect_async(&self.connector, stream.host(), io),
stream: Some(stream),
}
}
}
pub struct ConnectAsyncExt<T, U> {
fut: ConnectAsync<U>,
stream: Option<Connection<T, ()>>,
}
impl<T: Address, U> Future for ConnectAsyncExt<T, U>
where
U: AsyncRead + AsyncWrite + fmt::Debug,
{
type Item = Connection<T, SslStream<U>>;
type Error = HandshakeError<U>;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
match self.fut.poll().map_err(|e| {
trace!("SSL Handshake error: {:?}", e);
e
})? {
Async::Ready(stream) => {
let s = self.stream.take().unwrap();
trace!("SSL Handshake success: {:?}", s.host());
Ok(Async::Ready(s.replace(stream).1))
}
Async::NotReady => Ok(Async::NotReady),
}
}
}

37
actix-connect/src/uri.rs Normal file
View File

@@ -0,0 +1,37 @@
use http::Uri;
use crate::Address;
impl Address for Uri {
fn host(&self) -> &str {
self.host().unwrap_or("")
}
fn port(&self) -> Option<u16> {
if let Some(port) = self.port_u16() {
Some(port)
} else {
port(self.scheme_str())
}
}
}
// TODO: load data from file
fn port(scheme: Option<&str>) -> Option<u16> {
if let Some(scheme) = scheme {
match scheme {
"http" => Some(80),
"https" => Some(443),
"ws" => Some(80),
"wss" => Some(443),
"amqp" => Some(5672),
"amqps" => Some(5671),
"sb" => Some(5671),
"mqtt" => Some(1883),
"mqtts" => Some(8883),
_ => None,
}
} else {
None
}
}

View File

@@ -0,0 +1,111 @@
use actix_codec::{BytesCodec, Framed};
use actix_server_config::Io;
use actix_service::{fn_service, NewService, Service};
use actix_test_server::TestServer;
use bytes::Bytes;
use futures::{future::lazy, Future, Sink};
use http::{HttpTryFrom, Uri};
use trust_dns_resolver::config::{ResolverConfig, ResolverOpts};
use actix_connect::{default_connector, Connect};
#[test]
fn test_string() {
let mut srv = TestServer::with(|| {
fn_service(|io: Io<tokio_tcp::TcpStream>| {
Framed::new(io.into_parts().0, BytesCodec)
.send(Bytes::from_static(b"test"))
.then(|_| Ok::<_, ()>(()))
})
});
let mut conn = srv
.block_on(lazy(|| Ok::<_, ()>(default_connector())))
.unwrap();
let addr = format!("localhost:{}", srv.port());
let con = srv.block_on(conn.call(addr.into())).unwrap();
assert_eq!(con.peer_addr().unwrap(), srv.addr());
}
#[test]
fn test_static_str() {
let mut srv = TestServer::with(|| {
fn_service(|io: Io<tokio_tcp::TcpStream>| {
Framed::new(io.into_parts().0, BytesCodec)
.send(Bytes::from_static(b"test"))
.then(|_| Ok::<_, ()>(()))
})
});
let resolver = srv
.block_on(lazy(
|| Ok::<_, ()>(actix_connect::start_default_resolver()),
))
.unwrap();
let mut conn = srv
.block_on(lazy(|| {
Ok::<_, ()>(actix_connect::new_connector(resolver.clone()))
}))
.unwrap();
let con = srv
.block_on(conn.call(Connect::with("10", srv.addr())))
.unwrap();
assert_eq!(con.peer_addr().unwrap(), srv.addr());
let connect = Connect::new(srv.host().to_owned());
let mut conn = srv
.block_on(lazy(|| Ok::<_, ()>(actix_connect::new_connector(resolver))))
.unwrap();
let con = srv.block_on(conn.call(connect));
assert!(con.is_err());
}
#[test]
fn test_new_service() {
let mut srv = TestServer::with(|| {
fn_service(|io: Io<tokio_tcp::TcpStream>| {
Framed::new(io.into_parts().0, BytesCodec)
.send(Bytes::from_static(b"test"))
.then(|_| Ok::<_, ()>(()))
})
});
let resolver = srv
.block_on(lazy(|| {
Ok::<_, ()>(actix_connect::start_resolver(
ResolverConfig::default(),
ResolverOpts::default(),
))
}))
.unwrap();
let factory = srv
.block_on(lazy(|| {
Ok::<_, ()>(actix_connect::new_connector_factory(resolver))
}))
.unwrap();
let mut conn = srv.block_on(factory.new_service(&())).unwrap();
let con = srv
.block_on(conn.call(Connect::with("10", srv.addr())))
.unwrap();
assert_eq!(con.peer_addr().unwrap(), srv.addr());
}
#[test]
fn test_uri() {
let mut srv = TestServer::with(|| {
fn_service(|io: Io<tokio_tcp::TcpStream>| {
Framed::new(io.into_parts().0, BytesCodec)
.send(Bytes::from_static(b"test"))
.then(|_| Ok::<_, ()>(()))
})
});
let mut conn = srv
.block_on(lazy(|| Ok::<_, ()>(default_connector())))
.unwrap();
let addr = Uri::try_from(format!("https://localhost:{}", srv.port())).unwrap();
let con = srv.block_on(conn.call(addr.into())).unwrap();
assert_eq!(con.peer_addr().unwrap(), srv.addr());
}

27
actix-rt/CHANGES.md Normal file
View File

@@ -0,0 +1,27 @@
# Changes
## [0.2.2] - 2019-03-28
### Changed
* Moved `blocking` module to `actix-threadpool` crate
## [0.2.1] - 2019-03-11
### Added
* Added `blocking` module
* Arbiter::exec_fn - execute fn on the arbiter's thread
* Arbiter::exec - execute fn on the arbiter's thread and wait result
## [0.2.0] - 2019-03-06
* `run` method returns `io::Result<()>`
* Removed `Handle`
## [0.1.0] - 2018-12-09
* Initial release

26
actix-rt/Cargo.toml Normal file
View File

@@ -0,0 +1,26 @@
[package]
name = "actix-rt"
version = "0.2.2"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix runtime"
keywords = ["network", "framework", "async", "futures"]
homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-net.git"
documentation = "https://docs.rs/actix-rt/"
categories = ["network-programming", "asynchronous"]
license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
edition = "2018"
workspace = ".."
[lib]
name = "actix_rt"
path = "src/lib.rs"
[dependencies]
actix-threadpool = "0.1.0"
futures = "0.1.25"
tokio-current-thread = "0.1"
tokio-executor = "0.1.5"
tokio-reactor = "0.1.7"
tokio-timer = "0.2.8"

317
actix-rt/src/arbiter.rs Normal file
View File

@@ -0,0 +1,317 @@
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::{fmt, thread};
use futures::sync::mpsc::{unbounded, UnboundedReceiver, UnboundedSender};
use futures::sync::oneshot::{channel, Canceled, Sender};
use futures::{future, Async, Future, IntoFuture, Poll, Stream};
use tokio_current_thread::spawn;
use crate::builder::Builder;
use crate::system::System;
thread_local!(
static ADDR: RefCell<Option<Arbiter>> = RefCell::new(None);
static RUNNING: Cell<bool> = Cell::new(false);
static Q: RefCell<Vec<Box<Future<Item = (), Error = ()>>>> = RefCell::new(Vec::new());
);
pub(crate) static COUNT: AtomicUsize = AtomicUsize::new(0);
pub(crate) enum ArbiterCommand {
Stop,
Execute(Box<Future<Item = (), Error = ()> + Send>),
ExecuteFn(Box<FnExec>),
}
impl fmt::Debug for ArbiterCommand {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ArbiterCommand::Stop => write!(f, "ArbiterCommand::Stop"),
ArbiterCommand::Execute(_) => write!(f, "ArbiterCommand::Execute"),
ArbiterCommand::ExecuteFn(_) => write!(f, "ArbiterCommand::ExecuteFn"),
}
}
}
#[derive(Debug, Clone)]
/// Arbiters provide an asynchronous execution environment for actors, functions
/// and futures. When an Arbiter is created, they spawn a new OS thread, and
/// host an event loop. Some Arbiter functions execute on the current thread.
pub struct Arbiter(UnboundedSender<ArbiterCommand>);
impl Default for Arbiter {
fn default() -> Self {
Self::new()
}
}
impl Arbiter {
pub(crate) fn new_system() -> Self {
let (tx, rx) = unbounded();
let arb = Arbiter(tx);
ADDR.with(|cell| *cell.borrow_mut() = Some(arb.clone()));
RUNNING.with(|cell| cell.set(false));
Arbiter::spawn(ArbiterController { stop: None, rx });
arb
}
/// Returns the current thread's arbiter's address. If no Arbiter is present, then this
/// function will panic!
pub fn current() -> Arbiter {
ADDR.with(|cell| match *cell.borrow() {
Some(ref addr) => addr.clone(),
None => panic!("Arbiter is not running"),
})
}
/// Stop arbiter from continuing it's event loop.
pub fn stop(&self) {
let _ = self.0.unbounded_send(ArbiterCommand::Stop);
}
/// Spawn new thread and run event loop in spawned thread.
/// Returns address of newly created arbiter.
pub fn new() -> Arbiter {
let id = COUNT.fetch_add(1, Ordering::Relaxed);
let name = format!("actix-rt:worker:{}", id);
let sys = System::current();
let (arb_tx, arb_rx) = unbounded();
let arb_tx2 = arb_tx.clone();
let _ = thread::Builder::new().name(name.clone()).spawn(move || {
let mut rt = Builder::new().build_rt().expect("Can not create Runtime");
let arb = Arbiter(arb_tx);
let (stop, stop_rx) = channel();
RUNNING.with(|cell| cell.set(true));
System::set_current(sys);
// start arbiter controller
rt.spawn(ArbiterController {
stop: Some(stop),
rx: arb_rx,
});
ADDR.with(|cell| *cell.borrow_mut() = Some(arb.clone()));
// register arbiter
let _ = System::current()
.sys()
.unbounded_send(SystemCommand::RegisterArbiter(id, arb.clone()));
// run loop
let _ = match rt.block_on(stop_rx) {
Ok(code) => code,
Err(_) => 1,
};
// unregister arbiter
let _ = System::current()
.sys()
.unbounded_send(SystemCommand::UnregisterArbiter(id));
});
Arbiter(arb_tx2)
}
pub(crate) fn run_system() {
RUNNING.with(|cell| cell.set(true));
Q.with(|cell| {
let mut v = cell.borrow_mut();
for fut in v.drain(..) {
spawn(fut);
}
});
}
pub(crate) fn stop_system() {
RUNNING.with(|cell| cell.set(false));
}
/// Spawn a future on the current thread. This does not create a new Arbiter
/// or Arbiter address, it is simply a helper for spawning futures on the current
/// thread.
pub fn spawn<F>(future: F)
where
F: Future<Item = (), Error = ()> + 'static,
{
RUNNING.with(move |cell| {
if cell.get() {
spawn(Box::new(future));
} else {
Q.with(move |cell| cell.borrow_mut().push(Box::new(future)));
}
});
}
/// Executes a future on the current thread. This does not create a new Arbiter
/// or Arbiter address, it is simply a helper for executing futures on the current
/// thread.
pub fn spawn_fn<F, R>(f: F)
where
F: FnOnce() -> R + 'static,
R: IntoFuture<Item = (), Error = ()> + 'static,
{
Arbiter::spawn(future::lazy(f))
}
/// Send a future to the Arbiter's thread, and spawn it.
pub fn send<F>(&self, future: F)
where
F: Future<Item = (), Error = ()> + Send + 'static,
{
let _ = self
.0
.unbounded_send(ArbiterCommand::Execute(Box::new(future)));
}
/// Send a function to the Arbiter's thread, and execute it. Any result from the function
/// is discarded.
pub fn exec_fn<F>(&self, f: F)
where
F: FnOnce() + Send + 'static,
{
let _ = self
.0
.unbounded_send(ArbiterCommand::ExecuteFn(Box::new(move || {
let _ = f();
})));
}
/// Send a function to the Arbiter's thread. This function will be executed asynchronously.
/// A future is created, and when resolved will contain the result of the function sent
/// to the Arbiters thread.
pub fn exec<F, R>(&self, f: F) -> impl Future<Item = R, Error = Canceled>
where
F: FnOnce() -> R + Send + 'static,
R: Send + 'static,
{
let (tx, rx) = channel();
let _ = self
.0
.unbounded_send(ArbiterCommand::ExecuteFn(Box::new(move || {
if !tx.is_canceled() {
let _ = tx.send(f());
}
})));
rx
}
}
struct ArbiterController {
stop: Option<Sender<i32>>,
rx: UnboundedReceiver<ArbiterCommand>,
}
impl Drop for ArbiterController {
fn drop(&mut self) {
if thread::panicking() {
eprintln!("Panic in Arbiter thread, shutting down system.");
if System::current().stop_on_panic() {
System::current().stop_with_code(1)
}
}
}
}
impl Future for ArbiterController {
type Item = ();
type Error = ();
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
loop {
match self.rx.poll() {
Ok(Async::Ready(None)) | Err(_) => return Ok(Async::Ready(())),
Ok(Async::Ready(Some(item))) => match item {
ArbiterCommand::Stop => {
if let Some(stop) = self.stop.take() {
let _ = stop.send(0);
};
return Ok(Async::Ready(()));
}
ArbiterCommand::Execute(fut) => {
spawn(fut);
}
ArbiterCommand::ExecuteFn(f) => {
f.call_box();
}
},
Ok(Async::NotReady) => return Ok(Async::NotReady),
}
}
}
}
#[derive(Debug)]
pub(crate) enum SystemCommand {
Exit(i32),
RegisterArbiter(usize, Arbiter),
UnregisterArbiter(usize),
}
#[derive(Debug)]
pub(crate) struct SystemArbiter {
stop: Option<Sender<i32>>,
commands: UnboundedReceiver<SystemCommand>,
arbiters: HashMap<usize, Arbiter>,
}
impl SystemArbiter {
pub(crate) fn new(stop: Sender<i32>, commands: UnboundedReceiver<SystemCommand>) -> Self {
SystemArbiter {
commands,
stop: Some(stop),
arbiters: HashMap::new(),
}
}
}
impl Future for SystemArbiter {
type Item = ();
type Error = ();
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
loop {
match self.commands.poll() {
Ok(Async::Ready(None)) | Err(_) => return Ok(Async::Ready(())),
Ok(Async::Ready(Some(cmd))) => match cmd {
SystemCommand::Exit(code) => {
// stop arbiters
for arb in self.arbiters.values() {
arb.stop();
}
// stop event loop
if let Some(stop) = self.stop.take() {
let _ = stop.send(code);
}
}
SystemCommand::RegisterArbiter(name, hnd) => {
self.arbiters.insert(name, hnd);
}
SystemCommand::UnregisterArbiter(name) => {
self.arbiters.remove(&name);
}
},
Ok(Async::NotReady) => return Ok(Async::NotReady),
}
}
}
}
pub trait FnExec: Send + 'static {
fn call_box(self: Box<Self>);
}
impl<F> FnExec for F
where
F: FnOnce() + Send + 'static,
{
#[cfg_attr(feature = "cargo-clippy", allow(boxed_local))]
fn call_box(self: Box<Self>) {
(*self)()
}
}

183
actix-rt/src/builder.rs Normal file
View File

@@ -0,0 +1,183 @@
use std::borrow::Cow;
use std::io;
use futures::future::{lazy, Future};
use futures::sync::mpsc::unbounded;
use futures::sync::oneshot::{channel, Receiver};
use tokio_current_thread::CurrentThread;
use tokio_reactor::Reactor;
use tokio_timer::clock::Clock;
use tokio_timer::timer::Timer;
use crate::arbiter::{Arbiter, SystemArbiter};
use crate::runtime::Runtime;
use crate::system::System;
/// Builder struct for a actix runtime.
///
/// Either use `Builder::build` to create a system and start actors.
/// Alternatively, use `Builder::run` to start the tokio runtime and
/// run a function in its context.
pub struct Builder {
/// Name of the System. Defaults to "actix" if unset.
name: Cow<'static, str>,
/// The clock to use
clock: Clock,
/// Whether the Arbiter will stop the whole System on uncaught panic. Defaults to false.
stop_on_panic: bool,
}
impl Builder {
pub(crate) fn new() -> Self {
Builder {
name: Cow::Borrowed("actix"),
clock: Clock::new(),
stop_on_panic: false,
}
}
/// Sets the name of the System.
pub fn name<T: Into<String>>(mut self, name: T) -> Self {
self.name = Cow::Owned(name.into());
self
}
/// Set the Clock instance that will be used by this System.
///
/// Defaults to the system clock.
pub fn clock(mut self, clock: Clock) -> Self {
self.clock = clock;
self
}
/// Sets the option 'stop_on_panic' which controls whether the System is stopped when an
/// uncaught panic is thrown from a worker thread.
///
/// Defaults to false.
pub fn stop_on_panic(mut self, stop_on_panic: bool) -> Self {
self.stop_on_panic = stop_on_panic;
self
}
/// Create new System.
///
/// This method panics if it can not create tokio runtime
pub fn build(self) -> SystemRunner {
self.create_runtime(|| {})
}
/// This function will start tokio runtime and will finish once the
/// `System::stop()` message get called.
/// Function `f` get called within tokio runtime context.
pub fn run<F>(self, f: F) -> io::Result<()>
where
F: FnOnce() + 'static,
{
self.create_runtime(f).run()
}
fn create_runtime<F>(self, f: F) -> SystemRunner
where
F: FnOnce() + 'static,
{
let (stop_tx, stop) = channel();
let (sys_sender, sys_receiver) = unbounded();
let system = System::construct(sys_sender, Arbiter::new_system(), self.stop_on_panic);
// system arbiter
let arb = SystemArbiter::new(stop_tx, sys_receiver);
let mut rt = self.build_rt().unwrap();
rt.spawn(arb);
// init system arbiter and run configuration method
let _ = rt.block_on(lazy(move || {
f();
Ok::<_, ()>(())
}));
SystemRunner { rt, stop, system }
}
pub(crate) fn build_rt(&self) -> io::Result<Runtime> {
// We need a reactor to receive events about IO objects from kernel
let reactor = Reactor::new()?;
let reactor_handle = reactor.handle();
// Place a timer wheel on top of the reactor. If there are no timeouts to fire, it'll let the
// reactor pick up some new external events.
let timer = Timer::new_with_now(reactor, self.clock.clone());
let timer_handle = timer.handle();
// And now put a single-threaded executor on top of the timer. When there are no futures ready
// to do something, it'll let the timer or the reactor to generate some new stimuli for the
// futures to continue in their life.
let executor = CurrentThread::new_with_park(timer);
Ok(Runtime::new2(
reactor_handle,
timer_handle,
self.clock.clone(),
executor,
))
}
}
/// Helper object that runs System's event loop
#[must_use = "SystemRunner must be run"]
#[derive(Debug)]
pub struct SystemRunner {
rt: Runtime,
stop: Receiver<i32>,
system: System,
}
impl SystemRunner {
/// This function will start event loop and will finish once the
/// `System::stop()` function is called.
pub fn run(self) -> io::Result<()> {
let SystemRunner { mut rt, stop, .. } = self;
// run loop
let _ = rt.block_on(lazy(move || {
Arbiter::run_system();
Ok::<_, ()>(())
}));
let result = match rt.block_on(stop) {
Ok(code) => {
if code != 0 {
Err(io::Error::new(
io::ErrorKind::Other,
format!("Non-zero exit code: {}", code),
))
} else {
Ok(())
}
}
Err(e) => Err(io::Error::new(io::ErrorKind::Other, e)),
};
Arbiter::stop_system();
result
}
/// Execute a future and wait for result.
pub fn block_on<F, I, E>(&mut self, fut: F) -> Result<I, E>
where
F: Future<Item = I, Error = E>,
{
let _ = self.rt.block_on(lazy(move || {
Arbiter::run_system();
Ok::<_, ()>(())
}));
let res = self.rt.block_on(fut);
let _ = self.rt.block_on(lazy(move || {
Arbiter::stop_system();
Ok::<_, ()>(())
}));
res
}
}

30
actix-rt/src/lib.rs Normal file
View File

@@ -0,0 +1,30 @@
//! A runtime implementation that runs everything on the current thread.
mod arbiter;
mod builder;
mod runtime;
mod system;
pub use self::arbiter::Arbiter;
pub use self::builder::{Builder, SystemRunner};
pub use self::runtime::Runtime;
pub use self::system::System;
#[doc(hidden)]
pub use actix_threadpool as blocking;
/// Spawns a future on the current arbiter.
///
/// # Panics
///
/// This function panics if actix system is not running.
pub fn spawn<F>(f: F)
where
F: futures::Future<Item = (), Error = ()> + 'static,
{
if !System::is_set() {
panic!("System is not running");
}
Arbiter::spawn(f);
}

92
actix-rt/src/mod.rs Normal file
View File

@@ -0,0 +1,92 @@
//! A runtime implementation that runs everything on the current thread.
//!
//! [`current_thread::Runtime`][rt] is similar to the primary
//! [`Runtime`][concurrent-rt] except that it runs all components on the current
//! thread instead of using a thread pool. This means that it is able to spawn
//! futures that do not implement `Send`.
//!
//! Same as the default [`Runtime`][concurrent-rt], the
//! [`current_thread::Runtime`][rt] includes:
//!
//! * A [reactor] to drive I/O resources.
//! * An [executor] to execute tasks that use these I/O resources.
//! * A [timer] for scheduling work to run after a set period of time.
//!
//! Note that [`current_thread::Runtime`][rt] does not implement `Send` itself
//! and cannot be safely moved to other threads.
//!
//! # Spawning from other threads
//!
//! While [`current_thread::Runtime`][rt] does not implement `Send` and cannot
//! safely be moved to other threads, it provides a `Handle` that can be sent
//! to other threads and allows to spawn new tasks from there.
//!
//! For example:
//!
//! ```
//! # extern crate tokio;
//! # extern crate futures;
//! use tokio::runtime::current_thread::Runtime;
//! use tokio::prelude::*;
//! use std::thread;
//!
//! # fn main() {
//! let mut runtime = Runtime::new().unwrap();
//! let handle = runtime.handle();
//!
//! thread::spawn(move || {
//! handle.spawn(future::ok(()));
//! }).join().unwrap();
//!
//! # /*
//! runtime.run().unwrap();
//! # */
//! # }
//! ```
//!
//! # Examples
//!
//! Creating a new `Runtime` and running a future `f` until its completion and
//! returning its result.
//!
//! ```
//! use tokio::runtime::current_thread::Runtime;
//! use tokio::prelude::*;
//!
//! let mut runtime = Runtime::new().unwrap();
//!
//! // Use the runtime...
//! // runtime.block_on(f); // where f is a future
//! ```
//!
//! [rt]: struct.Runtime.html
//! [concurrent-rt]: ../struct.Runtime.html
//! [chan]: https://docs.rs/futures/0.1/futures/sync/mpsc/fn.channel.html
//! [reactor]: ../../reactor/struct.Reactor.html
//! [executor]: https://tokio.rs/docs/getting-started/runtime-model/#executors
//! [timer]: ../../timer/index.html
mod builder;
mod runtime;
pub use self::builder::Builder;
pub use self::runtime::{Runtime, Handle};
pub use tokio_current_thread::spawn;
pub use tokio_current_thread::TaskExecutor;
use futures::Future;
/// Run the provided future to completion using a runtime running on the current thread.
///
/// This first creates a new [`Runtime`], and calls [`Runtime::block_on`] with the provided future,
/// which blocks the current thread until the provided future completes. It then calls
/// [`Runtime::run`] to wait for any other spawned futures to resolve.
pub fn block_on_all<F>(future: F) -> Result<F::Item, F::Error>
where
F: Future,
{
let mut r = Runtime::new().expect("failed to start runtime on current thread");
let v = r.block_on(future)?;
r.run().expect("failed to resolve remaining futures");
Ok(v)
}

174
actix-rt/src/runtime.rs Normal file
View File

@@ -0,0 +1,174 @@
use std::error::Error;
use std::{fmt, io};
use futures::Future;
use tokio_current_thread::{self as current_thread, CurrentThread};
use tokio_executor;
use tokio_reactor::{self, Reactor};
use tokio_timer::clock::{self, Clock};
use tokio_timer::timer::{self, Timer};
use crate::builder::Builder;
/// Single-threaded runtime provides a way to start reactor
/// and executor on the current thread.
///
/// See [module level][mod] documentation for more details.
///
/// [mod]: index.html
#[derive(Debug)]
pub struct Runtime {
reactor_handle: tokio_reactor::Handle,
timer_handle: timer::Handle,
clock: Clock,
executor: CurrentThread<Timer<Reactor>>,
}
/// Error returned by the `run` function.
#[derive(Debug)]
pub struct RunError {
inner: current_thread::RunError,
}
impl fmt::Display for RunError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "{}", self.inner)
}
}
impl Error for RunError {
fn description(&self) -> &str {
self.inner.description()
}
fn cause(&self) -> Option<&Error> {
self.inner.source()
}
}
impl Runtime {
#[allow(clippy::new_ret_no_self)]
/// Returns a new runtime initialized with default configuration values.
pub fn new() -> io::Result<Runtime> {
Builder::new().build_rt()
}
pub(super) fn new2(
reactor_handle: tokio_reactor::Handle,
timer_handle: timer::Handle,
clock: Clock,
executor: CurrentThread<Timer<Reactor>>,
) -> Runtime {
Runtime {
reactor_handle,
timer_handle,
clock,
executor,
}
}
/// Spawn a future onto the single-threaded Tokio runtime.
///
/// See [module level][mod] documentation for more details.
///
/// [mod]: index.html
///
/// # Examples
///
/// ```rust
/// # use futures::{future, Future, Stream};
/// use actix_rt::Runtime;
///
/// # fn dox() {
/// // Create the runtime
/// let mut rt = Runtime::new().unwrap();
///
/// // Spawn a future onto the runtime
/// rt.spawn(future::lazy(|| {
/// println!("running on the runtime");
/// Ok(())
/// }));
/// # }
/// # pub fn main() {}
/// ```
///
/// # Panics
///
/// This function panics if the spawn fails. Failure occurs if the executor
/// is currently at capacity and is unable to spawn a new future.
pub fn spawn<F>(&mut self, future: F) -> &mut Self
where
F: Future<Item = (), Error = ()> + 'static,
{
self.executor.spawn(future);
self
}
/// Runs the provided future, blocking the current thread until the future
/// completes.
///
/// This function can be used to synchronously block the current thread
/// until the provided `future` has resolved either successfully or with an
/// error. The result of the future is then returned from this function
/// call.
///
/// Note that this function will **also** execute any spawned futures on the
/// current thread, but will **not** block until these other spawned futures
/// have completed. Once the function returns, any uncompleted futures
/// remain pending in the `Runtime` instance. These futures will not run
/// until `block_on` or `run` is called again.
///
/// The caller is responsible for ensuring that other spawned futures
/// complete execution by calling `block_on` or `run`.
pub fn block_on<F>(&mut self, f: F) -> Result<F::Item, F::Error>
where
F: Future,
{
self.enter(|executor| {
// Run the provided future
let ret = executor.block_on(f);
ret.map_err(|e| e.into_inner().expect("unexpected execution error"))
})
}
/// Run the executor to completion, blocking the thread until **all**
/// spawned futures have completed.
pub fn run(&mut self) -> Result<(), RunError> {
self.enter(|executor| executor.run())
.map_err(|e| RunError { inner: e })
}
fn enter<F, R>(&mut self, f: F) -> R
where
F: FnOnce(&mut current_thread::Entered<Timer<Reactor>>) -> R,
{
let Runtime {
ref reactor_handle,
ref timer_handle,
ref clock,
ref mut executor,
..
} = *self;
// Binds an executor to this thread
let mut enter = tokio_executor::enter().expect("Multiple executors at once");
// This will set the default handle and timer to use inside the closure
// and run the future.
tokio_reactor::with_default(&reactor_handle, &mut enter, |enter| {
clock::with_default(clock, enter, |enter| {
timer::with_default(&timer_handle, enter, |enter| {
// The TaskExecutor is a fake executor that looks into the
// current single-threaded executor when used. This is a trick,
// because we need two mutable references to the executor (one
// to run the provided future, another to install as the default
// one). We use the fake one here as the default one.
let mut default_executor = current_thread::TaskExecutor::current();
tokio_executor::with_default(&mut default_executor, enter, |enter| {
let mut executor = executor.enter(enter);
f(&mut executor)
})
})
})
})
}
}

129
actix-rt/src/system.rs Normal file
View File

@@ -0,0 +1,129 @@
use std::cell::RefCell;
use std::io;
use std::sync::atomic::{AtomicUsize, Ordering};
use futures::sync::mpsc::UnboundedSender;
use crate::arbiter::{Arbiter, SystemCommand};
use crate::builder::{Builder, SystemRunner};
static SYSTEM_COUNT: AtomicUsize = AtomicUsize::new(0);
/// System is a runtime manager.
#[derive(Clone, Debug)]
pub struct System {
id: usize,
sys: UnboundedSender<SystemCommand>,
arbiter: Arbiter,
stop_on_panic: bool,
}
thread_local!(
static CURRENT: RefCell<Option<System>> = RefCell::new(None);
);
impl System {
/// Constructs new system and sets it as current
pub(crate) fn construct(
sys: UnboundedSender<SystemCommand>,
arbiter: Arbiter,
stop_on_panic: bool,
) -> Self {
let sys = System {
sys,
arbiter,
stop_on_panic,
id: SYSTEM_COUNT.fetch_add(1, Ordering::SeqCst),
};
System::set_current(sys.clone());
sys
}
/// Build a new system with a customized tokio runtime.
///
/// This allows to customize the runtime. See struct level docs on
/// `Builder` for more information.
pub fn builder() -> Builder {
Builder::new()
}
#[allow(clippy::new_ret_no_self)]
/// Create new system.
///
/// This method panics if it can not create tokio runtime
pub fn new<T: Into<String>>(name: T) -> SystemRunner {
Self::builder().name(name).build()
}
/// Get current running system.
pub fn current() -> System {
CURRENT.with(|cell| match *cell.borrow() {
Some(ref sys) => sys.clone(),
None => panic!("System is not running"),
})
}
/// Set current running system.
pub(crate) fn is_set() -> bool {
CURRENT.with(|cell| cell.borrow().is_some())
}
/// Set current running system.
#[doc(hidden)]
pub fn set_current(sys: System) {
CURRENT.with(|s| {
*s.borrow_mut() = Some(sys);
})
}
/// Execute function with system reference.
pub fn with_current<F, R>(f: F) -> R
where
F: FnOnce(&System) -> R,
{
CURRENT.with(|cell| match *cell.borrow() {
Some(ref sys) => f(sys),
None => panic!("System is not running"),
})
}
/// System id
pub fn id(&self) -> usize {
self.id
}
/// Stop the system
pub fn stop(&self) {
self.stop_with_code(0)
}
/// Stop the system with a particular exit code.
pub fn stop_with_code(&self, code: i32) {
let _ = self.sys.unbounded_send(SystemCommand::Exit(code));
}
pub(crate) fn sys(&self) -> &UnboundedSender<SystemCommand> {
&self.sys
}
/// Return status of 'stop_on_panic' option which controls whether the System is stopped when an
/// uncaught panic is thrown from a worker thread.
pub fn stop_on_panic(&self) -> bool {
self.stop_on_panic
}
/// System arbiter
pub fn arbiter(&self) -> &Arbiter {
&self.arbiter
}
/// This function will start tokio runtime and will finish once the
/// `System::stop()` message get called.
/// Function `f` get called within tokio runtime context.
pub fn run<F>(f: F) -> io::Result<()>
where
F: FnOnce() + 'static,
{
Self::builder().run(f)
}
}

View File

@@ -0,0 +1,17 @@
[package]
name = "actix-server-config"
version = "0.1.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix server config utils"
homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-net.git"
license = "MIT/Apache-2.0"
edition = "2018"
workspace = ".."
[lib]
name = "actix_server_config"
path = "src/lib.rs"
[dependencies]
futures = "0.1.25"

View File

@@ -0,0 +1,132 @@
use std::cell::Cell;
use std::fmt;
use std::net::SocketAddr;
use std::rc::Rc;
#[derive(Debug, Clone)]
pub struct ServerConfig {
addr: SocketAddr,
secure: Rc<Cell<bool>>,
}
impl ServerConfig {
pub fn new(addr: SocketAddr) -> Self {
ServerConfig {
addr,
secure: Rc::new(Cell::new(false)),
}
}
/// Returns the address of the local half of this TCP server socket
pub fn local_addr(&self) -> SocketAddr {
self.addr
}
/// Returns true if connection is secure (tls enabled)
pub fn secure(&self) -> bool {
self.secure.as_ref().get()
}
/// Set secure flag
pub fn set_secure(&self) {
self.secure.as_ref().set(true)
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum Protocol {
Unknown,
Http10,
Http11,
Http2,
Proto1,
Proto2,
Proto3,
Proto4,
Proto5,
Proto6,
}
pub struct Io<T, P = ()> {
io: T,
proto: Protocol,
params: P,
}
impl<T> Io<T, ()> {
pub fn new(io: T) -> Self {
Self {
io,
proto: Protocol::Unknown,
params: (),
}
}
}
impl<T, P> Io<T, P> {
/// Reconstruct from a parts.
pub fn from_parts(io: T, params: P, proto: Protocol) -> Self {
Self { io, params, proto }
}
/// Deconstruct into a parts.
pub fn into_parts(self) -> (T, P, Protocol) {
(self.io, self.params, self.proto)
}
/// Returns a shared reference to the underlying stream.
pub fn get_ref(&self) -> &T {
&self.io
}
/// Returns a mutable reference to the underlying stream.
pub fn get_mut(&mut self) -> &mut T {
&mut self.io
}
/// Get selected protocol
pub fn protocol(&self) -> Protocol {
self.proto
}
/// Return new Io object with new parameter.
pub fn set<U>(self, params: U) -> Io<T, U> {
Io {
io: self.io,
proto: self.proto,
params: params,
}
}
/// Maps an Io<_, P> to Io<_, U> by applying a function to a contained value.
pub fn map<U, F>(self, op: F) -> Io<T, U>
where
F: FnOnce(P) -> U,
{
Io {
io: self.io,
proto: self.proto,
params: op(self.params),
}
}
}
impl<T, P> std::ops::Deref for Io<T, P> {
type Target = T;
fn deref(&self) -> &T {
&self.io
}
}
impl<T, P> std::ops::DerefMut for Io<T, P> {
fn deref_mut(&mut self) -> &mut T {
&mut self.io
}
}
impl<T: fmt::Debug, P> fmt::Debug for Io<T, P> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Io {{{:?}}}", self.io)
}
}

93
actix-server/CHANGES.md Normal file
View File

@@ -0,0 +1,93 @@
# Changes
## [0.4.2] - 2019-03-30
### Fixed
* Fix SIGINT force shutdown
## [0.4.1] - 2019-03-14
### Added
* `SystemRuntime::on_start()` - allow to run future before server service initialization
## [0.4.0] - 2019-03-12
### Changed
* Use `ServerConfig` for service factory
* Wrap tcp socket to `Io` type
* Upgrade actix-service
## [0.3.1] - 2019-03-04
### Added
* Add `ServerBuilder::maxconnrate` sets the maximum per-worker number of concurrent connections
* Add helper ssl error `SslError`
### Changed
* Rename `StreamServiceFactory` to `ServiceFactory`
* Deprecate `StreamServiceFactory`
## [0.3.0] - 2019-03-02
### Changed
* Use new `NewService` trait
## [0.2.1] - 2019-02-09
### Changed
* Drop service response
## [0.2.0] - 2019-02-01
### Changed
* Migrate to actix-service 0.2
* Updated rustls dependency
## [0.1.3] - 2018-12-21
### Fixed
* Fix max concurrent connections handling
## [0.1.2] - 2018-12-12
### Changed
* rename ServiceConfig::rt() to ServiceConfig::apply()
### Fixed
* Fix back-pressure for concurrent ssl handshakes
## [0.1.1] - 2018-12-11
* Fix signal handling on windows
## [0.1.0] - 2018-12-09
* Move server to separate crate

69
actix-server/Cargo.toml Normal file
View File

@@ -0,0 +1,69 @@
[package]
name = "actix-server"
version = "0.4.2"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix server - General purpose tcp server"
keywords = ["network", "framework", "async", "futures"]
homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-net.git"
documentation = "https://docs.rs/actix-server/"
categories = ["network-programming", "asynchronous"]
license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
edition = "2018"
workspace = ".."
[package.metadata.docs.rs]
features = ["ssl", "tls", "rust-tls"]
[lib]
name = "actix_server"
path = "src/lib.rs"
[features]
default = []
# tls
tls = ["native-tls"]
# openssl
ssl = ["openssl", "tokio-openssl"]
# rustls
rust-tls = ["rustls", "tokio-rustls", "webpki", "webpki-roots"]
[dependencies]
actix-rt = "0.2.1"
actix-service = "0.3.4"
actix-server-config = "0.1.0"
log = "0.4"
num_cpus = "1.0"
mio = "^0.6.13"
net2 = "0.2"
futures = "0.1"
slab = "0.4"
tokio-io = "0.1"
tokio-tcp = "0.1"
tokio-timer = "0.2.8"
tokio-reactor = "0.1"
tokio-signal = "0.2"
# native-tls
native-tls = { version="0.2", optional = true }
# openssl
openssl = { version="0.10", optional = true }
tokio-openssl = { version="0.3", optional = true }
#rustls
rustls = { version = "^0.15", optional = true }
tokio-rustls = { version = "^0.9", optional = true }
webpki = { version = "0.19", optional = true }
webpki-roots = { version = "0.16", optional = true }
[dev-dependencies]
bytes = "0.4"
actix-codec = "0.1.0"
env_logger = "0.6"

View File

@@ -2,14 +2,14 @@ use std::sync::mpsc as sync_mpsc;
use std::time::{Duration, Instant};
use std::{io, net, thread};
use futures::{sync::mpsc, Future};
use actix_rt::System;
use futures::future::{lazy, Future};
use log::{error, info};
use mio;
use slab::Slab;
use tokio_timer::Delay;
use actix::{msgs::Execute, Arbiter, System};
use super::server::ServerCommand;
use super::server::Server;
use super::worker::{Conn, WorkerClient};
use super::Token;
@@ -53,14 +53,11 @@ pub(crate) struct AcceptLoop {
notify_ready: mio::SetReadiness,
tx: sync_mpsc::Sender<Command>,
rx: Option<sync_mpsc::Receiver<Command>>,
srv: Option<(
mpsc::UnboundedSender<ServerCommand>,
mpsc::UnboundedReceiver<ServerCommand>,
)>,
srv: Option<Server>,
}
impl AcceptLoop {
pub fn new() -> AcceptLoop {
pub fn new(srv: Server) -> AcceptLoop {
let (tx, rx) = sync_mpsc::channel();
let (cmd_reg, cmd_ready) = mio::Registration::new2();
let (notify_reg, notify_ready) = mio::Registration::new2();
@@ -72,7 +69,7 @@ impl AcceptLoop {
notify_ready,
notify_reg: Some(notify_reg),
rx: Some(rx),
srv: Some(mpsc::unbounded()),
srv: Some(srv),
}
}
@@ -89,18 +86,17 @@ impl AcceptLoop {
&mut self,
socks: Vec<(Token, net::TcpListener)>,
workers: Vec<WorkerClient>,
) -> mpsc::UnboundedReceiver<ServerCommand> {
let (tx, rx) = self.srv.take().expect("Can not re-use AcceptInfo");
) {
let srv = self.srv.take().expect("Can not re-use AcceptInfo");
Accept::start(
self.rx.take().expect("Can not re-use AcceptInfo"),
self.cmd_reg.take().expect("Can not re-use AcceptInfo"),
self.notify_reg.take().expect("Can not re-use AcceptInfo"),
socks,
tx,
srv,
workers,
);
rx
}
}
@@ -109,7 +105,7 @@ struct Accept {
rx: sync_mpsc::Receiver<Command>,
sockets: Slab<ServerSocketInfo>,
workers: Vec<WorkerClient>,
srv: mpsc::UnboundedSender<ServerCommand>,
srv: Server,
timer: (mio::Registration, mio::SetReadiness),
next: usize,
backpressure: bool,
@@ -134,20 +130,20 @@ fn connection_error(e: &io::Error) -> bool {
}
impl Accept {
#![cfg_attr(feature = "cargo-clippy", allow(too_many_arguments))]
#![allow(clippy::too_many_arguments)]
pub(crate) fn start(
rx: sync_mpsc::Receiver<Command>,
cmd_reg: mio::Registration,
notify_reg: mio::Registration,
socks: Vec<(Token, net::TcpListener)>,
srv: mpsc::UnboundedSender<ServerCommand>,
srv: Server,
workers: Vec<WorkerClient>,
) {
let sys = System::current();
// start accept thread
let _ = thread::Builder::new()
.name("actix-web accept loop".to_owned())
.name("actix-server accept loop".to_owned())
.spawn(move || {
System::set_current(sys);
let mut accept = Accept::new(rx, socks, workers, srv);
@@ -180,7 +176,7 @@ impl Accept {
rx: sync_mpsc::Receiver<Command>,
socks: Vec<(Token, net::TcpListener)>,
workers: Vec<WorkerClient>,
srv: mpsc::UnboundedSender<ServerCommand>,
srv: Server,
) -> Accept {
// Create a poll instance
let poll = match mio::Poll::new() {
@@ -375,9 +371,7 @@ impl Accept {
match self.workers[self.next].send(msg) {
Ok(_) => (),
Err(tmp) => {
let _ = self.srv.unbounded_send(ServerCommand::WorkerDied(
self.workers[self.next].idx,
));
self.srv.worker_died(self.workers[self.next].idx);
msg = tmp;
self.workers.swap_remove(self.next);
if self.workers.is_empty() {
@@ -403,9 +397,7 @@ impl Accept {
return;
}
Err(tmp) => {
let _ = self.srv.unbounded_send(ServerCommand::WorkerDied(
self.workers[self.next].idx,
));
self.srv.worker_died(self.workers[self.next].idx);
msg = tmp;
self.workers.swap_remove(self.next);
if self.workers.is_empty() {
@@ -448,19 +440,14 @@ impl Accept {
info.timeout = Some(Instant::now() + Duration::from_millis(500));
let r = self.timer.1.clone();
System::current().arbiter().do_send(Execute::new(
move || -> Result<(), ()> {
Arbiter::spawn(
Delay::new(Instant::now() + Duration::from_millis(510))
.map_err(|_| ())
.and_then(move |_| {
let _ = r.set_readiness(mio::Ready::readable());
Ok(())
}),
);
Ok(())
},
));
System::current().arbiter().send(lazy(move || {
Delay::new(Instant::now() + Duration::from_millis(510))
.map_err(|_| ())
.and_then(move |_| {
let _ = r.set_readiness(mio::Ready::readable());
Ok(())
})
}));
return;
}
}

452
actix-server/src/builder.rs Normal file
View File

@@ -0,0 +1,452 @@
use std::time::Duration;
use std::{io, mem, net};
use actix_rt::{spawn, Arbiter, System};
use futures::future::{lazy, ok};
use futures::stream::futures_unordered;
use futures::sync::mpsc::{unbounded, UnboundedReceiver};
use futures::{Async, Future, Poll, Stream};
use log::{error, info};
use net2::TcpBuilder;
use num_cpus;
use tokio_timer::sleep;
use crate::accept::{AcceptLoop, AcceptNotify, Command};
use crate::config::{ConfiguredService, ServiceConfig};
use crate::server::{Server, ServerCommand};
use crate::services::{InternalServiceFactory, ServiceFactory, StreamNewService};
use crate::signals::{Signal, Signals};
use crate::worker::{self, Worker, WorkerAvailability, WorkerClient};
use crate::{ssl, Token};
/// Server builder
pub struct ServerBuilder {
threads: usize,
token: Token,
backlog: i32,
workers: Vec<(usize, WorkerClient)>,
services: Vec<Box<InternalServiceFactory>>,
sockets: Vec<(Token, net::TcpListener)>,
accept: AcceptLoop,
exit: bool,
shutdown_timeout: Duration,
no_signals: bool,
cmd: UnboundedReceiver<ServerCommand>,
server: Server,
}
impl Default for ServerBuilder {
fn default() -> Self {
Self::new()
}
}
impl ServerBuilder {
/// Create new Server builder instance
pub fn new() -> ServerBuilder {
let (tx, rx) = unbounded();
let server = Server::new(tx);
ServerBuilder {
threads: num_cpus::get(),
token: Token(0),
workers: Vec::new(),
services: Vec::new(),
sockets: Vec::new(),
accept: AcceptLoop::new(server.clone()),
backlog: 2048,
exit: false,
shutdown_timeout: Duration::from_secs(30),
no_signals: false,
cmd: rx,
server,
}
}
/// Set number of workers to start.
///
/// By default server uses number of available logical cpu as workers
/// count.
pub fn workers(mut self, num: usize) -> Self {
self.threads = num;
self
}
/// Set the maximum number of pending connections.
///
/// This refers to the number of clients that can be waiting to be served.
/// Exceeding this number results in the client getting an error when
/// attempting to connect. It should only affect servers under significant
/// load.
///
/// Generally set in the 64-2048 range. Default value is 2048.
///
/// This method should be called before `bind()` method call.
pub fn backlog(mut self, num: i32) -> Self {
self.backlog = num;
self
}
/// Sets the maximum per-worker number of concurrent connections.
///
/// All socket listeners will stop accepting connections when this limit is
/// reached for each worker.
///
/// By default max connections is set to a 25k per worker.
pub fn maxconn(self, num: usize) -> Self {
worker::max_concurrent_connections(num);
self
}
/// Sets the maximum per-worker concurrent connection establish process.
///
/// All listeners will stop accepting connections when this limit is reached. It
/// can be used to limit the global SSL CPU usage.
///
/// By default max connections is set to a 256.
pub fn maxconnrate(self, num: usize) -> Self {
ssl::max_concurrent_ssl_connect(num);
self
}
/// Stop actix system.
pub fn system_exit(mut self) -> Self {
self.exit = true;
self
}
/// Disable signal handling
pub fn disable_signals(mut self) -> Self {
self.no_signals = true;
self
}
/// Timeout for graceful workers shutdown in seconds.
///
/// After receiving a stop signal, workers have this much time to finish
/// serving requests. Workers still alive after the timeout are force
/// dropped.
///
/// By default shutdown timeout sets to 30 seconds.
pub fn shutdown_timeout(mut self, sec: u16) -> Self {
self.shutdown_timeout = Duration::from_secs(u64::from(sec));
self
}
/// Execute external configuration as part of the server building
/// process.
///
/// This function is useful for moving parts of configuration to a
/// different module or even library.
pub fn configure<F>(mut self, f: F) -> io::Result<ServerBuilder>
where
F: Fn(&mut ServiceConfig) -> io::Result<()>,
{
let mut cfg = ServiceConfig::new(self.threads, self.backlog);
f(&mut cfg)?;
if let Some(apply) = cfg.apply {
let mut srv = ConfiguredService::new(apply);
for (name, lst) in cfg.services {
let token = self.token.next();
srv.stream(token, name, lst.local_addr()?);
self.sockets.push((token, lst));
}
self.services.push(Box::new(srv));
}
self.threads = cfg.threads;
Ok(self)
}
/// Add new service to the server.
pub fn bind<F, U, N: AsRef<str>>(mut self, name: N, addr: U, factory: F) -> io::Result<Self>
where
F: ServiceFactory,
U: net::ToSocketAddrs,
{
let sockets = bind_addr(addr, self.backlog)?;
for lst in sockets {
let token = self.token.next();
self.services.push(StreamNewService::create(
name.as_ref().to_string(),
token,
factory.clone(),
lst.local_addr()?,
));
self.sockets.push((token, lst));
}
Ok(self)
}
/// Add new service to the server.
pub fn listen<F, N: AsRef<str>>(
mut self,
name: N,
lst: net::TcpListener,
factory: F,
) -> io::Result<Self>
where
F: ServiceFactory,
{
let token = self.token.next();
self.services.push(StreamNewService::create(
name.as_ref().to_string(),
token,
factory,
lst.local_addr()?,
));
self.sockets.push((token, lst));
Ok(self)
}
/// Spawn new thread and start listening for incoming connections.
///
/// This method spawns new thread and starts new actix system. Other than
/// that it is similar to `start()` method. This method blocks.
///
/// This methods panics if no socket addresses get bound.
///
/// ```rust,ignore
/// use actix_web::*;
///
/// fn main() -> std::io::Result<()> {
/// Server::new().
/// .service(
/// HttpServer::new(|| App::new().service(web::service("/").to(|| HttpResponse::Ok())))
/// .bind("127.0.0.1:0")
/// .run()
/// }
/// ```
pub fn run(self) -> io::Result<()> {
let sys = System::new("http-server");
self.start();
sys.run()
}
/// Starts processing incoming connections and return server controller.
pub fn start(mut self) -> Server {
if self.sockets.is_empty() {
panic!("Server should have at least one bound socket");
} else {
info!("Starting {} workers", self.threads);
// start workers
let mut workers = Vec::new();
for idx in 0..self.threads {
let worker = self.start_worker(idx, self.accept.get_notify());
workers.push(worker.clone());
self.workers.push((idx, worker));
}
// start accept thread
for sock in &self.sockets {
info!("Starting server on {}", sock.1.local_addr().ok().unwrap());
}
self.accept
.start(mem::replace(&mut self.sockets, Vec::new()), workers);
// handle signals
if !self.no_signals {
Signals::start(self.server.clone());
}
// start http server actor
let server = self.server.clone();
spawn(self);
server
}
}
fn start_worker(&self, idx: usize, notify: AcceptNotify) -> WorkerClient {
let (tx1, rx1) = unbounded();
let (tx2, rx2) = unbounded();
let timeout = self.shutdown_timeout;
let avail = WorkerAvailability::new(notify);
let worker = WorkerClient::new(idx, tx1, tx2, avail.clone());
let services: Vec<Box<InternalServiceFactory>> =
self.services.iter().map(|v| v.clone_factory()).collect();
Arbiter::new().send(lazy(move || {
Worker::start(rx1, rx2, services, avail, timeout);
Ok::<_, ()>(())
}));
worker
}
fn handle_cmd(&mut self, item: ServerCommand) {
match item {
ServerCommand::Pause(tx) => {
self.accept.send(Command::Pause);
let _ = tx.send(());
}
ServerCommand::Resume(tx) => {
self.accept.send(Command::Resume);
let _ = tx.send(());
}
ServerCommand::Signal(sig) => {
// Signals support
// Handle `SIGINT`, `SIGTERM`, `SIGQUIT` signals and stop actix system
match sig {
Signal::Int => {
info!("SIGINT received, exiting");
self.exit = true;
self.handle_cmd(ServerCommand::Stop {
graceful: false,
completion: None,
})
}
Signal::Term => {
info!("SIGTERM received, stopping");
self.exit = true;
self.handle_cmd(ServerCommand::Stop {
graceful: true,
completion: None,
})
}
Signal::Quit => {
info!("SIGQUIT received, exiting");
self.exit = true;
self.handle_cmd(ServerCommand::Stop {
graceful: false,
completion: None,
})
}
_ => (),
}
}
ServerCommand::Stop {
graceful,
completion,
} => {
let exit = self.exit;
// stop accept thread
self.accept.send(Command::Stop);
// stop workers
if !self.workers.is_empty() && graceful {
spawn(
futures_unordered(
self.workers
.iter()
.map(move |worker| worker.1.stop(graceful)),
)
.collect()
.then(move |_| {
if let Some(tx) = completion {
let _ = tx.send(());
}
if exit {
spawn(sleep(Duration::from_millis(300)).then(|_| {
System::current().stop();
ok(())
}));
}
ok(())
}),
)
} else {
// we need to stop system if server was spawned
if self.exit {
spawn(sleep(Duration::from_millis(300)).then(|_| {
System::current().stop();
ok(())
}));
}
if let Some(tx) = completion {
let _ = tx.send(());
}
}
}
ServerCommand::WorkerDied(idx) => {
let mut found = false;
for i in 0..self.workers.len() {
if self.workers[i].0 == idx {
self.workers.swap_remove(i);
found = true;
break;
}
}
if found {
error!("Worker has died {:?}, restarting", idx);
let mut new_idx = self.workers.len();
'found: loop {
for i in 0..self.workers.len() {
if self.workers[i].0 == new_idx {
new_idx += 1;
continue 'found;
}
}
break;
}
let worker = self.start_worker(new_idx, self.accept.get_notify());
self.workers.push((new_idx, worker.clone()));
self.accept.send(Command::Worker(worker));
}
}
}
}
}
impl Future for ServerBuilder {
type Item = ();
type Error = ();
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
loop {
match self.cmd.poll() {
Ok(Async::Ready(None)) | Err(_) => return Ok(Async::Ready(())),
Ok(Async::NotReady) => return Ok(Async::NotReady),
Ok(Async::Ready(Some(item))) => self.handle_cmd(item),
}
}
}
}
pub(super) fn bind_addr<S: net::ToSocketAddrs>(
addr: S,
backlog: i32,
) -> io::Result<Vec<net::TcpListener>> {
let mut err = None;
let mut succ = false;
let mut sockets = Vec::new();
for addr in addr.to_socket_addrs()? {
match create_tcp_listener(addr, backlog) {
Ok(lst) => {
succ = true;
sockets.push(lst);
}
Err(e) => err = Some(e),
}
}
if !succ {
if let Some(e) = err.take() {
Err(e)
} else {
Err(io::Error::new(
io::ErrorKind::Other,
"Can not bind to address.",
))
}
} else {
Ok(sockets)
}
}
fn create_tcp_listener(addr: net::SocketAddr, backlog: i32) -> io::Result<net::TcpListener> {
let builder = match addr {
net::SocketAddr::V4(_) => TcpBuilder::new_v4()?,
net::SocketAddr::V6(_) => TcpBuilder::new_v6()?,
};
builder.reuse_address(true)?;
builder.bind(addr)?;
Ok(builder.listen(backlog)?)
}

View File

@@ -1,37 +1,51 @@
use std::collections::HashMap;
use std::{fmt, io, net};
use actix_server_config::{Io, ServerConfig};
use actix_service::{IntoNewService, NewService};
use futures::future::{join_all, Future};
use log::error;
use tokio_tcp::TcpStream;
use counter::CounterGuard;
use service::{IntoNewService, NewService};
use crate::counter::CounterGuard;
use super::server::bind_addr;
use super::builder::bind_addr;
use super::services::{
BoxedServerService, InternalServiceFactory, ServerMessage, StreamService,
};
use super::Token;
pub struct ServiceConfig {
pub(super) services: Vec<(String, net::TcpListener)>,
pub(super) rt: Box<ServiceRuntimeConfiguration>,
pub(crate) services: Vec<(String, net::TcpListener)>,
pub(crate) apply: Option<Box<ServiceRuntimeConfiguration>>,
pub(crate) threads: usize,
pub(crate) backlog: i32,
}
impl ServiceConfig {
pub(super) fn new() -> ServiceConfig {
pub(super) fn new(threads: usize, backlog: i32) -> ServiceConfig {
ServiceConfig {
threads,
backlog,
services: Vec::new(),
rt: Box::new(not_configured),
apply: None,
}
}
/// Set number of workers to start.
///
/// By default server uses number of available logical cpu as workers
/// count.
pub fn workers(&mut self, num: usize) {
self.threads = num;
}
/// Add new service to server
pub fn bind<U, N: AsRef<str>>(&mut self, name: N, addr: U) -> io::Result<&mut Self>
where
U: net::ToSocketAddrs,
{
let sockets = bind_addr(addr)?;
let sockets = bind_addr(addr, self.backlog)?;
for lst in sockets {
self.listen(name.as_ref(), lst);
@@ -42,23 +56,27 @@ impl ServiceConfig {
/// Add new service to server
pub fn listen<N: AsRef<str>>(&mut self, name: N, lst: net::TcpListener) -> &mut Self {
if self.apply.is_none() {
self.apply = Some(Box::new(not_configured));
}
self.services.push((name.as_ref().to_string(), lst));
self
}
/// Register service configuration function
pub fn rt<F>(&mut self, f: F) -> io::Result<()>
/// Register service configuration function. This function get called
/// during worker runtime configuration. It get executed in worker thread.
pub fn apply<F>(&mut self, f: F) -> io::Result<()>
where
F: Fn(&mut ServiceRuntime) + Send + Clone + 'static,
{
self.rt = Box::new(f);
self.apply = Some(Box::new(f));
Ok(())
}
}
pub(super) struct ConfiguredService {
rt: Box<ServiceRuntimeConfiguration>,
names: HashMap<Token, String>,
names: HashMap<Token, (String, net::SocketAddr)>,
services: HashMap<String, Token>,
}
@@ -71,15 +89,15 @@ impl ConfiguredService {
}
}
pub(super) fn stream(&mut self, token: Token, name: String) {
self.names.insert(token, name.clone());
pub(super) fn stream(&mut self, token: Token, name: String, addr: net::SocketAddr) {
self.names.insert(token, (name.clone(), addr));
self.services.insert(name, token);
}
}
impl InternalServiceFactory for ConfiguredService {
fn name(&self, token: Token) -> &str {
&self.names[&token]
&self.names[&token].0
}
fn clone_factory(&self) -> Box<InternalServiceFactory> {
@@ -96,22 +114,51 @@ impl InternalServiceFactory for ConfiguredService {
self.rt.configure(&mut rt);
rt.validate();
// construct services
let mut fut = Vec::new();
for (token, ns) in rt.services {
fut.push(ns.new_service().map(move |service| (token, service)));
}
let services = rt.services;
Box::new(join_all(fut).map_err(|e| {
error!("Can not construct service: {:?}", e);
}))
// on start futures
if rt.onstart.is_empty() {
// construct services
let mut fut = Vec::new();
for (token, ns) in services {
let config = ServerConfig::new(self.names[&token].1);
fut.push(ns.new_service(&config).map(move |service| (token, service)));
}
Box::new(join_all(fut).map_err(|e| {
error!("Can not construct service: {:?}", e);
}))
} else {
let names = self.names.clone();
// run onstart future and then construct services
Box::new(
join_all(rt.onstart)
.map_err(|e| {
error!("Can not construct service: {:?}", e);
})
.and_then(move |_| {
// construct services
let mut fut = Vec::new();
for (token, ns) in services {
let config = ServerConfig::new(names[&token].1);
fut.push(
ns.new_service(&config).map(move |service| (token, service)),
);
}
join_all(fut).map_err(|e| {
error!("Can not construct service: {:?}", e);
})
}),
)
}
}
}
pub(super) trait ServiceRuntimeConfiguration: Send {
fn clone(&self) -> Box<ServiceRuntimeConfiguration>;
fn configure(&self, &mut ServiceRuntime);
fn configure(&self, rt: &mut ServiceRuntime);
}
impl<F> ServiceRuntimeConfiguration for F
@@ -134,6 +181,7 @@ fn not_configured(_: &mut ServiceRuntime) {
pub struct ServiceRuntime {
names: HashMap<String, Token>,
services: HashMap<Token, BoxedNewService>,
onstart: Vec<Box<Future<Item = (), Error = ()>>>,
}
impl ServiceRuntime {
@@ -141,6 +189,7 @@ impl ServiceRuntime {
ServiceRuntime {
names,
services: HashMap::new(),
onstart: Vec::new(),
}
}
@@ -152,10 +201,14 @@ impl ServiceRuntime {
}
}
/// Register service.
///
/// Name of the service must be registered during configuration stage with
/// *ServiceConfig::bind()* or *ServiceConfig::listen()* methods.
pub fn service<T, F>(&mut self, name: &str, service: F)
where
F: IntoNewService<T>,
T: NewService<Request = TcpStream, Response = ()> + 'static,
F: IntoNewService<T, ServerConfig>,
T: NewService<ServerConfig, Request = Io<TcpStream>> + 'static,
T::Future: 'static,
T::Service: 'static,
T::InitError: fmt::Debug,
@@ -172,10 +225,19 @@ impl ServiceRuntime {
panic!("Unknown service: {:?}", name);
}
}
/// Execute future before services initialization.
pub fn on_start<F>(&mut self, fut: F)
where
F: Future<Item = (), Error = ()> + 'static,
{
self.onstart.push(Box::new(fut))
}
}
type BoxedNewService = Box<
NewService<
ServerConfig,
Request = (Option<CounterGuard>, ServerMessage),
Response = (),
Error = (),
@@ -189,9 +251,9 @@ struct ServiceFactory<T> {
inner: T,
}
impl<T> NewService for ServiceFactory<T>
impl<T> NewService<ServerConfig> for ServiceFactory<T>
where
T: NewService<Request = TcpStream, Response = ()>,
T: NewService<ServerConfig, Request = Io<TcpStream>>,
T::Future: 'static,
T::Service: 'static,
T::Error: 'static,
@@ -204,8 +266,8 @@ where
type Service = BoxedServerService;
type Future = Box<Future<Item = BoxedServerService, Error = ()>>;
fn new_service(&self) -> Self::Future {
Box::new(self.inner.new_service().map_err(|_| ()).map(|s| {
fn new_service(&self, cfg: &ServerConfig) -> Self::Future {
Box::new(self.inner.new_service(cfg).map_err(|_| ()).map(|s| {
let service: BoxedServerService = Box::new(StreamService::new(s));
service
}))

38
actix-server/src/lib.rs Normal file
View File

@@ -0,0 +1,38 @@
//! General purpose tcp server
mod accept;
mod builder;
mod config;
mod counter;
mod server;
mod services;
mod signals;
pub mod ssl;
mod worker;
pub use actix_server_config::{Io, Protocol, ServerConfig};
pub use self::builder::ServerBuilder;
pub use self::config::{ServiceConfig, ServiceRuntime};
pub use self::server::Server;
pub use self::services::ServiceFactory;
#[doc(hidden)]
pub use self::services::ServiceFactory as StreamServiceFactory;
/// Socket id token
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) struct Token(usize);
impl Token {
pub(crate) fn next(&mut self) -> Token {
let token = Token(self.0 + 1);
self.0 += 1;
token
}
}
/// Start server building process
pub fn new() -> ServerBuilder {
ServerBuilder::default()
}

View File

@@ -0,0 +1,69 @@
use futures::sync::mpsc::UnboundedSender;
use futures::sync::oneshot;
use futures::Future;
use crate::builder::ServerBuilder;
use crate::signals::Signal;
pub(crate) enum ServerCommand {
WorkerDied(usize),
Pause(oneshot::Sender<()>),
Resume(oneshot::Sender<()>),
Signal(Signal),
/// Whether to try and shut down gracefully
Stop {
graceful: bool,
completion: Option<oneshot::Sender<()>>,
},
}
#[derive(Clone)]
pub struct Server(UnboundedSender<ServerCommand>);
impl Server {
pub(crate) fn new(tx: UnboundedSender<ServerCommand>) -> Self {
Server(tx)
}
/// Start server building process
pub fn build() -> ServerBuilder {
ServerBuilder::default()
}
pub(crate) fn signal(&self, sig: Signal) {
let _ = self.0.unbounded_send(ServerCommand::Signal(sig));
}
pub(crate) fn worker_died(&self, idx: usize) {
let _ = self.0.unbounded_send(ServerCommand::WorkerDied(idx));
}
/// Pause accepting incoming connections
///
/// If socket contains some pending connection, they might be dropped.
/// All opened connection remains active.
pub fn pause(&self) -> impl Future<Item = (), Error = ()> {
let (tx, rx) = oneshot::channel();
let _ = self.0.unbounded_send(ServerCommand::Pause(tx));
rx.map_err(|_| ())
}
/// Resume accepting incoming connections
pub fn resume(&self) -> impl Future<Item = (), Error = ()> {
let (tx, rx) = oneshot::channel();
let _ = self.0.unbounded_send(ServerCommand::Resume(tx));
rx.map_err(|_| ())
}
/// Stop incoming connection processing, stop all workers and exit.
///
/// If server starts with `spawn()` method, then spawned thread get terminated.
pub fn stop(&self, graceful: bool) -> impl Future<Item = (), Error = ()> {
let (tx, rx) = oneshot::channel();
let _ = self.0.unbounded_send(ServerCommand::Stop {
graceful,
completion: Some(tx),
});
rx.map_err(|_| ())
}
}

View File

@@ -1,18 +1,20 @@
use std::net;
use std::net::{self, SocketAddr};
use std::time::Duration;
use actix_rt::spawn;
use actix_server_config::{Io, ServerConfig};
use actix_service::{NewService, Service};
use futures::future::{err, ok, FutureResult};
use futures::{Future, Poll};
use tokio_current_thread::spawn;
use log::error;
use tokio_reactor::Handle;
use tokio_tcp::TcpStream;
use super::Token;
use counter::CounterGuard;
use service::{NewService, Service};
use crate::counter::CounterGuard;
/// Server message
pub enum ServerMessage {
pub(crate) enum ServerMessage {
/// New stream
Connect(net::TcpStream),
/// Gracefull shutdown
@@ -21,14 +23,8 @@ pub enum ServerMessage {
ForceShutdown,
}
pub trait StreamServiceFactory: Send + Clone + 'static {
type NewService: NewService<Request = TcpStream, Response = ()>;
fn create(&self) -> Self::NewService;
}
pub trait ServiceFactory: Send + Clone + 'static {
type NewService: NewService<Request = ServerMessage, Response = ()>;
type NewService: NewService<ServerConfig, Request = Io<TcpStream>>;
fn create(&self) -> Self::NewService;
}
@@ -62,7 +58,7 @@ impl<T> StreamService<T> {
impl<T> Service for StreamService<T>
where
T: Service<Request = TcpStream, Response = ()>,
T: Service<Request = Io<TcpStream>>,
T::Future: 'static,
T::Error: 'static,
{
@@ -83,9 +79,9 @@ where
});
if let Ok(stream) = stream {
spawn(self.service.call(stream).then(move |res| {
spawn(self.service.call(Io::new(stream)).then(move |res| {
drop(guard);
res.map_err(|_| ())
res.map_err(|_| ()).map(|_| ())
}));
ok(())
} else {
@@ -97,104 +93,35 @@ where
}
}
pub(crate) struct ServerService<T> {
service: T,
}
impl<T> ServerService<T> {
fn new(service: T) -> Self {
ServerService { service }
}
}
impl<T> Service for ServerService<T>
where
T: Service<Request = ServerMessage, Response = ()>,
T::Future: 'static,
T::Error: 'static,
{
type Request = (Option<CounterGuard>, ServerMessage);
type Response = ();
type Error = ();
type Future = FutureResult<(), ()>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.service.poll_ready().map_err(|_| ())
}
fn call(&mut self, (guard, req): (Option<CounterGuard>, ServerMessage)) -> Self::Future {
spawn(self.service.call(req).then(move |res| {
drop(guard);
res.map_err(|_| ())
}));
ok(())
}
}
pub(crate) struct ServiceNewService<F: ServiceFactory> {
name: String,
inner: F,
token: Token,
}
impl<F> ServiceNewService<F>
where
F: ServiceFactory,
{
pub(crate) fn create(name: String, token: Token, inner: F) -> Box<InternalServiceFactory> {
Box::new(Self { name, inner, token })
}
}
impl<F> InternalServiceFactory for ServiceNewService<F>
where
F: ServiceFactory,
{
fn name(&self, _: Token) -> &str {
&self.name
}
fn clone_factory(&self) -> Box<InternalServiceFactory> {
Box::new(Self {
name: self.name.clone(),
inner: self.inner.clone(),
token: self.token,
})
}
fn create(&self) -> Box<Future<Item = Vec<(Token, BoxedServerService)>, Error = ()>> {
let token = self.token;
Box::new(
self.inner
.create()
.new_service()
.map_err(|_| ())
.map(move |inner| {
let service: BoxedServerService = Box::new(ServerService::new(inner));
vec![(token, service)]
}),
)
}
}
pub(crate) struct StreamNewService<F: StreamServiceFactory> {
pub(crate) struct StreamNewService<F: ServiceFactory> {
name: String,
inner: F,
token: Token,
addr: SocketAddr,
}
impl<F> StreamNewService<F>
where
F: StreamServiceFactory,
F: ServiceFactory,
{
pub(crate) fn create(name: String, token: Token, inner: F) -> Box<InternalServiceFactory> {
Box::new(Self { name, token, inner })
pub(crate) fn create(
name: String,
token: Token,
inner: F,
addr: SocketAddr,
) -> Box<InternalServiceFactory> {
Box::new(Self {
name,
token,
inner,
addr,
})
}
}
impl<F> InternalServiceFactory for StreamNewService<F>
where
F: StreamServiceFactory,
F: ServiceFactory,
{
fn name(&self, _: Token) -> &str {
&self.name
@@ -205,15 +132,17 @@ where
name: self.name.clone(),
inner: self.inner.clone(),
token: self.token,
addr: self.addr,
})
}
fn create(&self) -> Box<Future<Item = Vec<(Token, BoxedServerService)>, Error = ()>> {
let token = self.token;
let config = ServerConfig::new(self.addr);
Box::new(
self.inner
.create()
.new_service()
.new_service(&config)
.map_err(|_| ())
.map(move |inner| {
let service: BoxedServerService = Box::new(StreamService::new(inner));
@@ -240,19 +169,7 @@ impl InternalServiceFactory for Box<InternalServiceFactory> {
impl<F, T> ServiceFactory for F
where
F: Fn() -> T + Send + Clone + 'static,
T: NewService<Request = ServerMessage, Response = ()>,
{
type NewService = T;
fn create(&self) -> T {
(self)()
}
}
impl<F, T> StreamServiceFactory for F
where
F: Fn() -> T + Send + Clone + 'static,
T: NewService<Request = TcpStream, Response = ()>,
T: NewService<ServerConfig, Request = Io<TcpStream>>,
{
type NewService = T;

118
actix-server/src/signals.rs Normal file
View File

@@ -0,0 +1,118 @@
use std::io;
use actix_rt::spawn;
use futures::stream::futures_unordered;
use futures::{Async, Future, Poll, Stream};
use crate::server::Server;
/// Different types of process signals
#[derive(PartialEq, Clone, Copy, Debug)]
pub(crate) enum Signal {
/// SIGHUP
Hup,
/// SIGINT
Int,
/// SIGTERM
Term,
/// SIGQUIT
Quit,
}
pub(crate) struct Signals {
srv: Server,
#[cfg(not(unix))]
stream: SigStream,
#[cfg(unix)]
streams: Vec<SigStream>,
}
type SigStream = Box<Stream<Item = Signal, Error = io::Error>>;
impl Signals {
pub(crate) fn start(srv: Server) {
let fut = {
#[cfg(not(unix))]
{
tokio_signal::ctrl_c()
.map_err(|_| ())
.and_then(move |stream| Signals {
srv,
stream: Box::new(stream.map(|_| Signal::Int)),
})
}
#[cfg(unix)]
{
use tokio_signal::unix;
let mut sigs: Vec<Box<Future<Item = SigStream, Error = io::Error>>> =
Vec::new();
sigs.push(Box::new(
tokio_signal::unix::Signal::new(tokio_signal::unix::SIGINT).map(|stream| {
let s: SigStream = Box::new(stream.map(|_| Signal::Int));
s
}),
));
sigs.push(Box::new(
tokio_signal::unix::Signal::new(tokio_signal::unix::SIGHUP).map(
|stream: unix::Signal| {
let s: SigStream = Box::new(stream.map(|_| Signal::Hup));
s
},
),
));
sigs.push(Box::new(
tokio_signal::unix::Signal::new(tokio_signal::unix::SIGTERM).map(
|stream| {
let s: SigStream = Box::new(stream.map(|_| Signal::Term));
s
},
),
));
sigs.push(Box::new(
tokio_signal::unix::Signal::new(tokio_signal::unix::SIGQUIT).map(
|stream| {
let s: SigStream = Box::new(stream.map(|_| Signal::Quit));
s
},
),
));
futures_unordered(sigs)
.collect()
.map_err(|_| ())
.and_then(move |streams| Signals { srv, streams })
}
};
spawn(fut);
}
}
impl Future for Signals {
type Item = ();
type Error = ();
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
#[cfg(not(unix))]
loop {
match self.stream.poll() {
Ok(Async::Ready(None)) | Err(_) => return Ok(Async::Ready(())),
Ok(Async::Ready(Some(sig))) => self.srv.signal(sig),
Ok(Async::NotReady) => return Ok(Async::NotReady),
}
}
#[cfg(unix)]
{
for s in &mut self.streams {
loop {
match s.poll() {
Ok(Async::Ready(None)) | Err(_) => return Ok(Async::Ready(())),
Ok(Async::NotReady) => break,
Ok(Async::Ready(Some(sig))) => self.srv.signal(sig),
}
}
}
Ok(Async::NotReady)
}
}
}

View File

@@ -1,12 +1,12 @@
//! SSL Services
use std::sync::atomic::{AtomicUsize, Ordering};
use super::counter::Counter;
use crate::counter::Counter;
#[cfg(feature = "ssl")]
mod openssl;
#[cfg(feature = "ssl")]
pub use self::openssl::{OpensslAcceptor, OpensslConnector};
pub use self::openssl::OpensslAcceptor;
#[cfg(feature = "tls")]
mod nativetls;
@@ -28,8 +28,14 @@ pub fn max_concurrent_ssl_connect(num: usize) {
MAX_CONN.store(num, Ordering::Relaxed);
}
pub(crate) const MAX_CONN: AtomicUsize = AtomicUsize::new(256);
pub(crate) static MAX_CONN: AtomicUsize = AtomicUsize::new(256);
thread_local! {
static MAX_CONN_COUNTER: Counter = Counter::new(MAX_CONN.load(Ordering::Relaxed));
}
/// Ssl error combinded with service error.
pub enum SslError<E1, E2> {
Ssl(E1),
Service(E2),
}

View File

@@ -1,33 +1,34 @@
use std::io;
use std::marker::PhantomData;
use actix_service::{NewService, Service};
use futures::{future::ok, future::FutureResult, Async, Future, Poll};
use native_tls::{self, Error, HandshakeError, TlsAcceptor};
use tokio_io::{AsyncRead, AsyncWrite};
use super::MAX_CONN_COUNTER;
use counter::{Counter, CounterGuard};
use service::{NewService, Service};
use crate::counter::{Counter, CounterGuard};
use crate::ssl::MAX_CONN_COUNTER;
use crate::{Io, Protocol, ServerConfig};
/// Support `SSL` connections via native-tls package
///
/// `tls` feature enables `NativeTlsAcceptor` type
pub struct NativeTlsAcceptor<T> {
pub struct NativeTlsAcceptor<T, P = ()> {
acceptor: TlsAcceptor,
io: PhantomData<T>,
io: PhantomData<(T, P)>,
}
impl<T: AsyncRead + AsyncWrite> NativeTlsAcceptor<T> {
impl<T: AsyncRead + AsyncWrite, P> NativeTlsAcceptor<T, P> {
/// Create `NativeTlsAcceptor` instance
pub fn new(acceptor: TlsAcceptor) -> Self {
NativeTlsAcceptor {
acceptor: acceptor.into(),
acceptor,
io: PhantomData,
}
}
}
impl<T: AsyncRead + AsyncWrite> Clone for NativeTlsAcceptor<T> {
impl<T: AsyncRead + AsyncWrite, P> Clone for NativeTlsAcceptor<T, P> {
fn clone(&self) -> Self {
Self {
acceptor: self.acceptor.clone(),
@@ -36,15 +37,17 @@ impl<T: AsyncRead + AsyncWrite> Clone for NativeTlsAcceptor<T> {
}
}
impl<T: AsyncRead + AsyncWrite> NewService for NativeTlsAcceptor<T> {
type Request = T;
type Response = TlsStream<T>;
impl<T: AsyncRead + AsyncWrite, P> NewService<ServerConfig> for NativeTlsAcceptor<T, P> {
type Request = Io<T, P>;
type Response = Io<TlsStream<T>, P>;
type Error = Error;
type Service = NativeTlsAcceptorService<T>;
type Service = NativeTlsAcceptorService<T, P>;
type InitError = ();
type Future = FutureResult<Self::Service, Self::InitError>;
fn new_service(&self) -> Self::Future {
fn new_service(&self, cfg: &ServerConfig) -> Self::Future {
cfg.set_secure();
MAX_CONN_COUNTER.with(|conns| {
ok(NativeTlsAcceptorService {
acceptor: self.acceptor.clone(),
@@ -55,17 +58,17 @@ impl<T: AsyncRead + AsyncWrite> NewService for NativeTlsAcceptor<T> {
}
}
pub struct NativeTlsAcceptorService<T> {
pub struct NativeTlsAcceptorService<T, P> {
acceptor: TlsAcceptor,
io: PhantomData<T>,
io: PhantomData<(T, P)>,
conns: Counter,
}
impl<T: AsyncRead + AsyncWrite> Service for NativeTlsAcceptorService<T> {
type Request = T;
type Response = TlsStream<T>;
impl<T: AsyncRead + AsyncWrite, P> Service for NativeTlsAcceptorService<T, P> {
type Request = Io<T, P>;
type Response = Io<TlsStream<T>, P>;
type Error = Error;
type Future = Accept<T>;
type Future = Accept<T, P>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
if self.conns.available() {
@@ -76,9 +79,11 @@ impl<T: AsyncRead + AsyncWrite> Service for NativeTlsAcceptorService<T> {
}
fn call(&mut self, req: Self::Request) -> Self::Future {
let (io, params, _) = req.into_parts();
Accept {
_guard: self.conns.get(),
inner: Some(self.acceptor.accept(req)),
inner: Some(self.acceptor.accept(io)),
params: Some(params),
}
}
}
@@ -97,21 +102,30 @@ pub struct TlsStream<S> {
/// Future returned from `NativeTlsAcceptor::accept` which will resolve
/// once the accept handshake has finished.
pub struct Accept<S> {
pub struct Accept<S, P> {
inner: Option<Result<native_tls::TlsStream<S>, HandshakeError<S>>>,
params: Option<P>,
_guard: CounterGuard,
}
impl<Io: AsyncRead + AsyncWrite> Future for Accept<Io> {
type Item = TlsStream<Io>;
impl<T: AsyncRead + AsyncWrite, P> Future for Accept<T, P> {
type Item = Io<TlsStream<T>, P>;
type Error = Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
match self.inner.take().expect("cannot poll MidHandshake twice") {
Ok(stream) => Ok(TlsStream { inner: stream }.into()),
Ok(stream) => Ok(Async::Ready(Io::from_parts(
TlsStream { inner: stream },
self.params.take().unwrap(),
Protocol::Unknown,
))),
Err(HandshakeError::Failure(e)) => Err(e),
Err(HandshakeError::WouldBlock(s)) => match s.handshake() {
Ok(stream) => Ok(TlsStream { inner: stream }.into()),
Ok(stream) => Ok(Async::Ready(Io::from_parts(
TlsStream { inner: stream },
self.params.take().unwrap(),
Protocol::Unknown,
))),
Err(HandshakeError::Failure(e)) => Err(e),
Err(HandshakeError::WouldBlock(s)) => {
self.inner = Some(Err(HandshakeError::WouldBlock(s)));

View File

@@ -0,0 +1,129 @@
use std::marker::PhantomData;
use actix_service::{NewService, Service};
use futures::{future::ok, future::FutureResult, Async, Future, Poll};
use openssl::ssl::{HandshakeError, SslAcceptor};
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_openssl::{AcceptAsync, SslAcceptorExt, SslStream};
use crate::counter::{Counter, CounterGuard};
use crate::ssl::MAX_CONN_COUNTER;
use crate::{Io, Protocol, ServerConfig};
/// Support `SSL` connections via openssl package
///
/// `ssl` feature enables `OpensslAcceptor` type
pub struct OpensslAcceptor<T: AsyncRead + AsyncWrite, P = ()> {
acceptor: SslAcceptor,
io: PhantomData<(T, P)>,
}
impl<T: AsyncRead + AsyncWrite, P> OpensslAcceptor<T, P> {
/// Create default `OpensslAcceptor`
pub fn new(acceptor: SslAcceptor) -> Self {
OpensslAcceptor {
acceptor,
io: PhantomData,
}
}
}
impl<T: AsyncRead + AsyncWrite, P> Clone for OpensslAcceptor<T, P> {
fn clone(&self) -> Self {
Self {
acceptor: self.acceptor.clone(),
io: PhantomData,
}
}
}
impl<T: AsyncRead + AsyncWrite, P> NewService<ServerConfig> for OpensslAcceptor<T, P> {
type Request = Io<T, P>;
type Response = Io<SslStream<T>, P>;
type Error = HandshakeError<T>;
type Service = OpensslAcceptorService<T, P>;
type InitError = ();
type Future = FutureResult<Self::Service, Self::InitError>;
fn new_service(&self, cfg: &ServerConfig) -> Self::Future {
cfg.set_secure();
MAX_CONN_COUNTER.with(|conns| {
ok(OpensslAcceptorService {
acceptor: self.acceptor.clone(),
conns: conns.clone(),
io: PhantomData,
})
})
}
}
pub struct OpensslAcceptorService<T, P> {
acceptor: SslAcceptor,
conns: Counter,
io: PhantomData<(T, P)>,
}
impl<T: AsyncRead + AsyncWrite, P> Service for OpensslAcceptorService<T, P> {
type Request = Io<T, P>;
type Response = Io<SslStream<T>, P>;
type Error = HandshakeError<T>;
type Future = OpensslAcceptorServiceFut<T, P>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
if self.conns.available() {
Ok(Async::Ready(()))
} else {
Ok(Async::NotReady)
}
}
fn call(&mut self, req: Self::Request) -> Self::Future {
let (io, params, _) = req.into_parts();
OpensslAcceptorServiceFut {
_guard: self.conns.get(),
fut: SslAcceptorExt::accept_async(&self.acceptor, io),
params: Some(params),
}
}
}
pub struct OpensslAcceptorServiceFut<T, P>
where
T: AsyncRead + AsyncWrite,
{
fut: AcceptAsync<T>,
params: Option<P>,
_guard: CounterGuard,
}
impl<T: AsyncRead + AsyncWrite, P> Future for OpensslAcceptorServiceFut<T, P> {
type Item = Io<SslStream<T>, P>;
type Error = HandshakeError<T>;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
let io = futures::try_ready!(self.fut.poll());
let proto = if let Some(protos) = io.get_ref().ssl().selected_alpn_protocol() {
const H2: &[u8] = b"\x02h2";
const HTTP10: &[u8] = b"\x08http/1.0";
const HTTP11: &[u8] = b"\x08http/1.1";
if protos.windows(3).any(|window| window == H2) {
Protocol::Http2
} else if protos.windows(9).any(|window| window == HTTP11) {
Protocol::Http11
} else if protos.windows(9).any(|window| window == HTTP10) {
Protocol::Http10
} else {
Protocol::Unknown
}
} else {
Protocol::Unknown
};
Ok(Async::Ready(Io::from_parts(
io,
self.params.take().unwrap(),
proto,
)))
}
}

View File

@@ -2,24 +2,25 @@ use std::io;
use std::marker::PhantomData;
use std::sync::Arc;
use actix_service::{NewService, Service};
use futures::{future::ok, future::FutureResult, Async, Future, Poll};
use rustls::{ServerConfig, ServerSession};
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_rustls::{Accept, TlsAcceptor, TlsStream};
use super::MAX_CONN_COUNTER;
use counter::{Counter, CounterGuard};
use service::{NewService, Service};
use crate::counter::{Counter, CounterGuard};
use crate::ssl::MAX_CONN_COUNTER;
use crate::{Io, Protocol, ServerConfig as SrvConfig};
/// Support `SSL` connections via rustls package
///
/// `rust-tls` feature enables `RustlsAcceptor` type
pub struct RustlsAcceptor<T> {
pub struct RustlsAcceptor<T, P = ()> {
config: Arc<ServerConfig>,
io: PhantomData<T>,
io: PhantomData<(T, P)>,
}
impl<T: AsyncRead + AsyncWrite> RustlsAcceptor<T> {
impl<T: AsyncRead + AsyncWrite, P> RustlsAcceptor<T, P> {
/// Create `RustlsAcceptor` new service
pub fn new(config: ServerConfig) -> Self {
RustlsAcceptor {
@@ -29,7 +30,7 @@ impl<T: AsyncRead + AsyncWrite> RustlsAcceptor<T> {
}
}
impl<T> Clone for RustlsAcceptor<T> {
impl<T, P> Clone for RustlsAcceptor<T, P> {
fn clone(&self) -> Self {
Self {
config: self.config.clone(),
@@ -38,15 +39,17 @@ impl<T> Clone for RustlsAcceptor<T> {
}
}
impl<T: AsyncRead + AsyncWrite> NewService for RustlsAcceptor<T> {
type Request = T;
type Response = TlsStream<T, ServerSession>;
impl<T: AsyncRead + AsyncWrite, P> NewService<SrvConfig> for RustlsAcceptor<T, P> {
type Request = Io<T, P>;
type Response = Io<TlsStream<T, ServerSession>, P>;
type Error = io::Error;
type Service = RustlsAcceptorService<T>;
type Service = RustlsAcceptorService<T, P>;
type InitError = ();
type Future = FutureResult<Self::Service, Self::InitError>;
fn new_service(&self) -> Self::Future {
fn new_service(&self, cfg: &SrvConfig) -> Self::Future {
cfg.set_secure();
MAX_CONN_COUNTER.with(|conns| {
ok(RustlsAcceptorService {
acceptor: self.config.clone().into(),
@@ -57,17 +60,17 @@ impl<T: AsyncRead + AsyncWrite> NewService for RustlsAcceptor<T> {
}
}
pub struct RustlsAcceptorService<T> {
pub struct RustlsAcceptorService<T, P> {
acceptor: TlsAcceptor,
io: PhantomData<T>,
io: PhantomData<(T, P)>,
conns: Counter,
}
impl<T: AsyncRead + AsyncWrite> Service for RustlsAcceptorService<T> {
type Request = T;
type Response = TlsStream<T, ServerSession>;
impl<T: AsyncRead + AsyncWrite, P> Service for RustlsAcceptorService<T, P> {
type Request = Io<T, P>;
type Response = Io<TlsStream<T, ServerSession>, P>;
type Error = io::Error;
type Future = RustlsAcceptorServiceFut<T>;
type Future = RustlsAcceptorServiceFut<T, P>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
if self.conns.available() {
@@ -78,26 +81,34 @@ impl<T: AsyncRead + AsyncWrite> Service for RustlsAcceptorService<T> {
}
fn call(&mut self, req: Self::Request) -> Self::Future {
let (io, params, _) = req.into_parts();
RustlsAcceptorServiceFut {
_guard: self.conns.get(),
fut: self.acceptor.accept(req),
fut: self.acceptor.accept(io),
params: Some(params),
}
}
}
pub struct RustlsAcceptorServiceFut<T>
pub struct RustlsAcceptorServiceFut<T, P>
where
T: AsyncRead + AsyncWrite,
{
fut: Accept<T>,
params: Option<P>,
_guard: CounterGuard,
}
impl<T: AsyncRead + AsyncWrite> Future for RustlsAcceptorServiceFut<T> {
type Item = TlsStream<T, ServerSession>;
impl<T: AsyncRead + AsyncWrite, P> Future for RustlsAcceptorServiceFut<T, P> {
type Item = Io<TlsStream<T, ServerSession>, P>;
type Error = io::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
self.fut.poll()
let io = futures::try_ready!(self.fut.poll());
Ok(Async::Ready(Io::from_parts(
io,
self.params.take().unwrap(),
Protocol::Unknown,
)))
}
}

View File

@@ -2,19 +2,17 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::Arc;
use std::{mem, net, time};
use actix_rt::{spawn, Arbiter};
use futures::sync::mpsc::{UnboundedReceiver, UnboundedSender};
use futures::sync::oneshot;
use futures::{future, Async, Future, Poll, Stream};
use tokio_current_thread::spawn;
use log::{error, info, trace};
use tokio_timer::{sleep, Delay};
use actix::msgs::StopArbiter;
use actix::{Arbiter, Message};
use super::accept::AcceptNotify;
use super::services::{BoxedServerService, InternalServiceFactory, ServerMessage};
use super::Token;
use counter::Counter;
use crate::accept::AcceptNotify;
use crate::counter::Counter;
use crate::services::{BoxedServerService, InternalServiceFactory, ServerMessage};
use crate::Token;
pub(crate) struct WorkerCommand(Conn);
@@ -25,14 +23,14 @@ pub(crate) struct StopCommand {
result: oneshot::Sender<bool>,
}
#[derive(Debug, Message)]
#[derive(Debug)]
pub(crate) struct Conn {
pub io: net::TcpStream,
pub token: Token,
pub peer: Option<net::SocketAddr>,
}
const MAX_CONNS: AtomicUsize = AtomicUsize::new(25600);
static MAX_CONNS: AtomicUsize = AtomicUsize::new(25600);
/// Sets the maximum per-worker number of concurrent connections.
///
@@ -166,7 +164,7 @@ impl Worker {
future::join_all(fut)
.map_err(|e| {
error!("Can not start worker: {:?}", e);
Arbiter::current().do_send(StopArbiter(0));
Arbiter::current().stop();
})
.and_then(move |services| {
for item in services {
@@ -193,7 +191,7 @@ impl Worker {
let timeout = self.shutdown_timeout;
self.services.iter_mut().for_each(move |h| {
if let Some(h) = h {
let _ = h.1.call((None, ServerMessage::Shutdown(timeout.clone())));
let _ = h.1.call((None, ServerMessage::Shutdown(timeout)));
}
});
}
@@ -250,36 +248,33 @@ impl Future for Worker {
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
// `StopWorker` message handler
match self.rx2.poll() {
Ok(Async::Ready(Some(StopCommand { graceful, result }))) => {
self.availability.set(false);
if let Ok(Async::Ready(Some(StopCommand { graceful, result }))) = self.rx2.poll() {
self.availability.set(false);
let num = num_connections();
if num == 0 {
info!("Shutting down worker, 0 connections");
let _ = result.send(true);
return Ok(Async::Ready(()));
} else if graceful {
self.shutdown(false);
let num = num_connections();
if num == 0 {
info!("Shutting down worker, 0 connections");
if num != 0 {
info!("Graceful worker shutdown, {} connections", num);
self.state = WorkerState::Shutdown(
sleep(time::Duration::from_secs(1)),
sleep(self.shutdown_timeout),
result,
);
} else {
let _ = result.send(true);
return Ok(Async::Ready(()));
} else if graceful {
self.shutdown(false);
let num = num_connections();
if num != 0 {
info!("Graceful worker shutdown, {} connections", num);
self.state = WorkerState::Shutdown(
sleep(time::Duration::from_secs(1)),
sleep(self.shutdown_timeout),
result,
);
} else {
let _ = result.send(true);
return Ok(Async::Ready(()));
}
} else {
info!("Force shutdown worker, {} connections", num);
self.shutdown(true);
let _ = result.send(false);
return Ok(Async::Ready(()));
}
} else {
info!("Force shutdown worker, {} connections", num);
self.shutdown(true);
let _ = result.send(false);
return Ok(Async::Ready(()));
}
_ => (),
}
let state = mem::replace(&mut self.state, WorkerState::None);
@@ -367,7 +362,7 @@ impl Future for Worker {
let num = num_connections();
if num == 0 {
let _ = tx.send(true);
Arbiter::current().do_send(StopArbiter(0));
Arbiter::current().stop();
return Ok(Async::Ready(()));
}
@@ -377,7 +372,7 @@ impl Future for Worker {
Async::Ready(_) => {
self.shutdown(true);
let _ = tx.send(false);
Arbiter::current().do_send(StopArbiter(0));
Arbiter::current().stop();
return Ok(Async::Ready(()));
}
}
@@ -403,7 +398,7 @@ impl Future for Worker {
let guard = self.conns.get();
let _ = self.services[msg.token.0]
.as_mut()
.expect("actix net bug")
.expect("actix-server bug")
.1
.call((Some(guard), ServerMessage::Connect(msg.io)));
continue;

View File

@@ -0,0 +1,162 @@
use std::io::Read;
use std::sync::mpsc;
use std::{net, thread, time};
use actix_codec::{BytesCodec, Framed};
use actix_server::{Io, Server, ServerConfig};
use actix_service::{fn_cfg_factory, fn_service, IntoService};
use bytes::Bytes;
use futures::{Future, Sink};
use net2::TcpBuilder;
use tokio_tcp::TcpStream;
fn unused_addr() -> net::SocketAddr {
let addr: net::SocketAddr = "127.0.0.1:0".parse().unwrap();
let socket = TcpBuilder::new_v4().unwrap();
socket.bind(&addr).unwrap();
socket.reuse_address(true).unwrap();
let tcp = socket.to_tcp_listener().unwrap();
tcp.local_addr().unwrap()
}
#[test]
fn test_bind() {
let addr = unused_addr();
let (tx, rx) = mpsc::channel();
let h = thread::spawn(move || {
let sys = actix_rt::System::new("test");
let srv = Server::build()
.bind("test", addr, move || {
fn_cfg_factory(move |cfg: &ServerConfig| {
assert_eq!(cfg.local_addr(), addr);
Ok::<_, ()>((|_| Ok::<_, ()>(())).into_service())
})
})
.unwrap()
.start();
let _ = tx.send((srv, actix_rt::System::current()));
let _ = sys.run();
});
let (_, sys) = rx.recv().unwrap();
thread::sleep(time::Duration::from_millis(500));
assert!(net::TcpStream::connect(addr).is_ok());
let _ = sys.stop();
let _ = h.join();
}
#[test]
fn test_bind_no_config() {
let addr = unused_addr();
let (tx, rx) = mpsc::channel();
let h = thread::spawn(move || {
let sys = actix_rt::System::new("test");
let srv = Server::build()
.bind("test", addr, move || fn_service(|_| Ok::<_, ()>(())))
.unwrap()
.start();
let _ = tx.send((srv, actix_rt::System::current()));
let _ = sys.run();
});
let (_, sys) = rx.recv().unwrap();
assert!(net::TcpStream::connect(addr).is_ok());
let _ = sys.stop();
let _ = h.join();
}
#[test]
fn test_listen() {
let addr = unused_addr();
let (tx, rx) = mpsc::channel();
let h = thread::spawn(move || {
let sys = actix_rt::System::new("test");
let lst = net::TcpListener::bind(addr).unwrap();
let srv = Server::build()
.listen("test", lst, move || {
fn_cfg_factory(move |cfg: &ServerConfig| {
assert_eq!(cfg.local_addr(), addr);
Ok::<_, ()>((|_| Ok::<_, ()>(())).into_service())
})
})
.unwrap()
.start();
let _ = tx.send((srv, actix_rt::System::current()));
let _ = sys.run();
});
let (_, sys) = rx.recv().unwrap();
thread::sleep(time::Duration::from_millis(500));
assert!(net::TcpStream::connect(addr).is_ok());
let _ = sys.stop();
let _ = h.join();
}
#[test]
#[cfg(unix)]
fn test_start() {
let addr = unused_addr();
let (tx, rx) = mpsc::channel();
let h = thread::spawn(move || {
let sys = actix_rt::System::new("test");
let srv = Server::build()
.backlog(100)
.bind("test", addr, move || {
fn_cfg_factory(move |cfg: &ServerConfig| {
assert_eq!(cfg.local_addr(), addr);
Ok::<_, ()>(
(|io: Io<TcpStream>| {
Framed::new(io.into_parts().0, BytesCodec)
.send(Bytes::from_static(b"test"))
.then(|_| Ok::<_, ()>(()))
})
.into_service(),
)
})
})
.unwrap()
.start();
let _ = tx.send((srv, actix_rt::System::current()));
let _ = sys.run();
});
let (srv, sys) = rx.recv().unwrap();
let mut buf = [0u8; 4];
let mut conn = net::TcpStream::connect(addr).unwrap();
let _ = conn.read_exact(&mut buf);
assert_eq!(buf, b"test"[..]);
// pause
let _ = srv.pause();
thread::sleep(time::Duration::from_millis(200));
let mut conn = net::TcpStream::connect(addr).unwrap();
conn.set_read_timeout(Some(time::Duration::from_millis(100)))
.unwrap();
let res = conn.read_exact(&mut buf);
assert!(res.is_err());
// resume
let _ = srv.resume();
thread::sleep(time::Duration::from_millis(100));
assert!(net::TcpStream::connect(addr).is_ok());
assert!(net::TcpStream::connect(addr).is_ok());
assert!(net::TcpStream::connect(addr).is_ok());
let mut buf = [0u8; 4];
let mut conn = net::TcpStream::connect(addr).unwrap();
let _ = conn.read_exact(&mut buf);
assert_eq!(buf, b"test"[..]);
// stop
let _ = srv.stop(false);
thread::sleep(time::Duration::from_millis(100));
assert!(net::TcpStream::connect(addr).is_err());
thread::sleep(time::Duration::from_millis(100));
let _ = sys.stop();
let _ = h.join();
}

162
actix-service/CHANGES.md Normal file
View File

@@ -0,0 +1,162 @@
# Changes
## [0.3.6] - 2019-04-07
### Changed
* Poll boxed service call result immediately
## [0.3.5] - 2019-03-29
### Added
* Add `impl<S: Service> Service for Rc<RefCell<S>>`
## [0.3.4] - 2019-03-12
### Added
* Add `Transform::from_err()` combinator
* Add `apply_fn` helper
* Add `apply_fn_factory` helper
* Add `apply_transform` helper
* Add `apply_cfg` helper
## [0.3.3] - 2019-03-09
### Added
* Add `ApplyTransform` new service for transform and new service.
* Add `NewService::apply_cfg()` combinator, allows to use
nested `NewService` with different config parameter.
### Changed
* Revert IntoFuture change
## [0.3.2] - 2019-03-04
### Changed
* Change `NewService::Future` and `Transform::Future` to the `IntoFuture` trait.
* Export `AndThenTransform` type
## [0.3.1] - 2019-03-04
### Changed
* Simplify Transform trait
## [0.3.0] - 2019-03-02
## Added
* Added boxed NewService and Service.
## Changed
* Added `Config` parameter to `NewService` trait.
* Added `Config` parameter to `NewTransform` trait.
## [0.2.2] - 2019-02-19
### Added
* Added `NewService` impl for `Rc<S> where S: NewService`
* Added `NewService` impl for `Arc<S> where S: NewService`
## [0.2.1] - 2019-02-03
### Changed
* Generalize `.apply` combinator with Transform trait
## [0.2.0] - 2019-02-01
### Changed
* Use associated type instead of generic for Service definition.
* Before:
```rust
impl Service<Request> for Client {
type Response = Response;
// ...
}
```
* After:
```rust
impl Service for Client {
type Request = Request;
type Response = Response;
// ...
}
```
## [0.1.6] - 2019-01-24
### Changed
* Use `FnMut` instead of `Fn` for .apply() and .map() combinators and `FnService` type
* Change `.apply()` error semantic, new service's error is `From<Self::Error>`
## [0.1.5] - 2019-01-13
### Changed
* Make `Out::Error` convertable from `T::Error` for apply combinator
## [0.1.4] - 2019-01-11
### Changed
* Use `FnMut` instead of `Fn` for `FnService`
## [0.1.3] - 2018-12-12
### Changed
* Split service combinators to separate trait
## [0.1.2] - 2018-12-12
### Fixed
* Release future early for `.and_then()` and `.then()` combinators
## [0.1.1] - 2018-12-09
### Added
* Added Service impl for Box<S: Service>
## [0.1.0] - 2018-12-09
* Initial import

30
actix-service/Cargo.toml Normal file
View File

@@ -0,0 +1,30 @@
[package]
name = "actix-service"
version = "0.3.6"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix Service"
keywords = ["network", "framework", "async", "futures"]
homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-net.git"
documentation = "https://docs.rs/actix-service/"
categories = ["network-programming", "asynchronous"]
license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
edition = "2018"
workspace = ".."
[badges]
travis-ci = { repository = "actix/actix-service", branch = "master" }
appveyor = { repository = "actix/actix-net" }
codecov = { repository = "actix/actix-service", branch = "master", service = "github" }
[lib]
name = "actix_service"
path = "src/lib.rs"
[dependencies]
futures = "0.1.24"
void = "1.0.2"
[dev-dependencies]
actix-rt = "0.2"

View File

@@ -1,7 +1,9 @@
use std::marker::PhantomData;
use futures::{Async, Future, Poll};
use super::{IntoNewService, NewService, Service};
use cell::Cell;
use crate::cell::Cell;
/// Service for the `and_then` combinator, chaining a computation onto the end
/// of another service which completes successfully.
@@ -12,21 +14,20 @@ pub struct AndThen<A, B> {
b: Cell<B>,
}
impl<A, B> AndThen<A, B>
where
A: Service,
B: Service<Request = A::Response, Error = A::Error>,
{
impl<A, B> AndThen<A, B> {
/// Create new `AndThen` combinator
pub fn new(a: A, b: B) -> Self {
pub fn new(a: A, b: B) -> Self
where
A: Service,
B: Service<Request = A::Response, Error = A::Error>,
{
Self { a, b: Cell::new(b) }
}
}
impl<A, B> Clone for AndThen<A, B>
where
A: Service + Clone,
B: Service<Request = A::Response, Error = A::Error>,
A: Clone,
{
fn clone(&self) -> Self {
AndThen {
@@ -47,11 +48,15 @@ where
type Future = AndThenFuture<A, B>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
let _ = try_ready!(self.a.poll_ready());
self.b.borrow_mut().poll_ready()
let not_ready = self.a.poll_ready()?.is_not_ready();
if self.b.get_mut().poll_ready()?.is_not_ready() || not_ready {
Ok(Async::NotReady)
} else {
Ok(Async::Ready(()))
}
}
fn call(&mut self, req: Self::Request) -> Self::Future {
fn call(&mut self, req: A::Request) -> Self::Future {
AndThenFuture::new(self.a.call(req), self.b.clone())
}
}
@@ -84,7 +89,6 @@ impl<A, B> Future for AndThenFuture<A, B>
where
A: Service,
B: Service<Request = A::Response, Error = A::Error>,
B::Error: Into<A::Error>,
{
type Item = B::Response;
type Error = A::Error;
@@ -94,10 +98,10 @@ where
return fut.poll();
}
match self.fut_a.as_mut().expect("actix-net bug").poll() {
match self.fut_a.as_mut().expect("Bug in actix-service").poll() {
Ok(Async::Ready(resp)) => {
let _ = self.fut_a.take();
self.fut_b = Some(self.b.borrow_mut().call(resp));
self.fut_b = Some(self.b.get_mut().call(resp));
self.poll()
}
Ok(Async::NotReady) => Ok(Async::NotReady),
@@ -107,29 +111,35 @@ where
}
/// `AndThenNewService` new service combinator
pub struct AndThenNewService<A, B> {
pub struct AndThenNewService<A, B, C>
where
A: NewService<C>,
B: NewService<C, Request = A::Response, Error = A::Error, InitError = A::InitError>,
{
a: A,
b: B,
_t: PhantomData<C>,
}
impl<A, B> AndThenNewService<A, B>
impl<A, B, C> AndThenNewService<A, B, C>
where
A: NewService,
B: NewService,
A: NewService<C>,
B: NewService<C, Request = A::Response, Error = A::Error, InitError = A::InitError>,
{
/// Create new `AndThen` combinator
pub fn new<F: IntoNewService<B>>(a: A, f: F) -> Self {
pub fn new<F: IntoNewService<B, C>>(a: A, f: F) -> Self {
Self {
a,
b: f.into_new_service(),
_t: PhantomData,
}
}
}
impl<A, B> NewService for AndThenNewService<A, B>
impl<A, B, C> NewService<C> for AndThenNewService<A, B, C>
where
A: NewService,
B: NewService<Request = A::Response, Error = A::Error, InitError = A::InitError>,
A: NewService<C>,
B: NewService<C, Request = A::Response, Error = A::Error, InitError = A::InitError>,
{
type Request = A::Request;
type Response = B::Response;
@@ -137,30 +147,31 @@ where
type Service = AndThen<A::Service, B::Service>;
type InitError = A::InitError;
type Future = AndThenNewServiceFuture<A, B>;
type Future = AndThenNewServiceFuture<A, B, C>;
fn new_service(&self) -> Self::Future {
AndThenNewServiceFuture::new(self.a.new_service(), self.b.new_service())
fn new_service(&self, cfg: &C) -> Self::Future {
AndThenNewServiceFuture::new(self.a.new_service(cfg), self.b.new_service(cfg))
}
}
impl<A, B> Clone for AndThenNewService<A, B>
impl<A, B, C> Clone for AndThenNewService<A, B, C>
where
A: NewService + Clone,
B: NewService<Request = A::Response, Error = A::Error, InitError = A::InitError> + Clone,
A: NewService<C> + Clone,
B: NewService<C, Request = A::Response, Error = A::Error, InitError = A::InitError> + Clone,
{
fn clone(&self) -> Self {
Self {
a: self.a.clone(),
b: self.b.clone(),
_t: PhantomData,
}
}
}
pub struct AndThenNewServiceFuture<A, B>
pub struct AndThenNewServiceFuture<A, B, C>
where
A: NewService,
B: NewService,
A: NewService<C>,
B: NewService<C, Request = A::Response>,
{
fut_b: B::Future,
fut_a: A::Future,
@@ -168,10 +179,10 @@ where
b: Option<B::Service>,
}
impl<A, B> AndThenNewServiceFuture<A, B>
impl<A, B, C> AndThenNewServiceFuture<A, B, C>
where
A: NewService,
B: NewService,
A: NewService<C>,
B: NewService<C, Request = A::Response>,
{
fn new(fut_a: A::Future, fut_b: B::Future) -> Self {
AndThenNewServiceFuture {
@@ -183,10 +194,10 @@ where
}
}
impl<A, B> Future for AndThenNewServiceFuture<A, B>
impl<A, B, C> Future for AndThenNewServiceFuture<A, B, C>
where
A: NewService,
B: NewService<Request = A::Response, Error = A::Error, InitError = A::InitError>,
A: NewService<C>,
B: NewService<C, Request = A::Response, Error = A::Error, InitError = A::InitError>,
{
type Item = AndThen<A::Service, B::Service>;
type Error = A::InitError;
@@ -223,7 +234,7 @@ mod tests {
use std::rc::Rc;
use super::*;
use service::{NewServiceExt, Service, ServiceExt};
use crate::{NewService, Service, ServiceExt};
struct Srv1(Rc<Cell<usize>>);
impl Service for Srv1 {
@@ -237,7 +248,7 @@ mod tests {
Ok(Async::Ready(()))
}
fn call(&mut self, req: Self::Request) -> Self::Future {
fn call(&mut self, req: &'static str) -> Self::Future {
ok(req)
}
}
@@ -256,7 +267,7 @@ mod tests {
Ok(Async::Ready(()))
}
fn call(&mut self, req: Self::Request) -> Self::Future {
fn call(&mut self, req: &'static str) -> Self::Future {
ok((req, "srv2"))
}
}
@@ -288,7 +299,7 @@ mod tests {
let new_srv = blank
.into_new_service()
.and_then(move || Ok(Srv2(cnt.clone())));
if let Async::Ready(mut srv) = new_srv.new_service().poll().unwrap() {
if let Async::Ready(mut srv) = new_srv.new_service(&()).poll().unwrap() {
let res = srv.call("srv1").poll();
assert!(res.is_ok());
assert_eq!(res.unwrap(), Async::Ready(("srv1", "srv2")));

View File

@@ -0,0 +1,188 @@
use std::rc::Rc;
use futures::{Async, Future, Poll};
use crate::and_then::AndThen;
use crate::from_err::FromErr;
use crate::{NewService, Transform};
/// `Apply` new service combinator
pub struct AndThenTransform<T, A, B, C> {
a: A,
b: B,
t: Rc<T>,
_t: std::marker::PhantomData<C>,
}
impl<T, A, B, C> AndThenTransform<T, A, B, C>
where
A: NewService<C>,
B: NewService<C, InitError = A::InitError>,
T: Transform<B::Service, Request = A::Response, InitError = A::InitError>,
T::Error: From<A::Error>,
{
/// Create new `ApplyNewService` new service instance
pub fn new(t: T, a: A, b: B) -> Self {
Self {
a,
b,
t: Rc::new(t),
_t: std::marker::PhantomData,
}
}
}
impl<T, A, B, C> Clone for AndThenTransform<T, A, B, C>
where
A: Clone,
B: Clone,
{
fn clone(&self) -> Self {
Self {
a: self.a.clone(),
b: self.b.clone(),
t: self.t.clone(),
_t: std::marker::PhantomData,
}
}
}
impl<T, A, B, C> NewService<C> for AndThenTransform<T, A, B, C>
where
A: NewService<C>,
B: NewService<C, InitError = A::InitError>,
T: Transform<B::Service, Request = A::Response, InitError = A::InitError>,
T::Error: From<A::Error>,
{
type Request = A::Request;
type Response = T::Response;
type Error = T::Error;
type InitError = T::InitError;
type Service = AndThen<FromErr<A::Service, T::Error>, T::Transform>;
type Future = AndThenTransformFuture<T, A, B, C>;
fn new_service(&self, cfg: &C) -> Self::Future {
AndThenTransformFuture {
a: None,
t: None,
t_cell: self.t.clone(),
fut_a: self.a.new_service(cfg),
fut_b: self.b.new_service(cfg),
fut_t: None,
}
}
}
pub struct AndThenTransformFuture<T, A, B, C>
where
A: NewService<C>,
B: NewService<C, InitError = A::InitError>,
T: Transform<B::Service, Request = A::Response, InitError = A::InitError>,
T::Error: From<A::Error>,
{
fut_a: A::Future,
fut_b: B::Future,
fut_t: Option<T::Future>,
a: Option<A::Service>,
t: Option<T::Transform>,
t_cell: Rc<T>,
}
impl<T, A, B, C> Future for AndThenTransformFuture<T, A, B, C>
where
A: NewService<C>,
B: NewService<C, InitError = A::InitError>,
T: Transform<B::Service, Request = A::Response, InitError = A::InitError>,
T::Error: From<A::Error>,
{
type Item = AndThen<FromErr<A::Service, T::Error>, T::Transform>;
type Error = T::InitError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
if self.fut_t.is_none() {
if let Async::Ready(service) = self.fut_b.poll()? {
self.fut_t = Some(self.t_cell.new_transform(service));
}
}
if self.a.is_none() {
if let Async::Ready(service) = self.fut_a.poll()? {
self.a = Some(service);
}
}
if let Some(ref mut fut) = self.fut_t {
if let Async::Ready(transform) = fut.poll()? {
self.t = Some(transform);
}
}
if self.a.is_some() && self.t.is_some() {
Ok(Async::Ready(AndThen::new(
FromErr::new(self.a.take().unwrap()),
self.t.take().unwrap(),
)))
} else {
Ok(Async::NotReady)
}
}
}
#[cfg(test)]
mod tests {
use futures::future::{ok, FutureResult};
use futures::{Async, Future, Poll};
use crate::{IntoNewService, IntoService, NewService, Service, ServiceExt};
#[derive(Clone)]
struct Srv;
impl Service for Srv {
type Request = ();
type Response = ();
type Error = ();
type Future = FutureResult<(), ()>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
fn call(&mut self, _: ()) -> Self::Future {
ok(())
}
}
#[test]
fn test_apply() {
let blank = |req| Ok(req);
let mut srv = blank
.into_service()
.apply_fn(Srv, |req: &'static str, srv: &mut Srv| {
srv.call(()).map(move |res| (req, res))
});
assert!(srv.poll_ready().is_ok());
let res = srv.call("srv").poll();
assert!(res.is_ok());
assert_eq!(res.unwrap(), Async::Ready(("srv", ())));
}
#[test]
fn test_new_service() {
let blank = || Ok::<_, ()>((|req| Ok(req)).into_service());
let new_srv = blank.into_new_service().apply(
|req: &'static str, srv: &mut Srv| srv.call(()).map(move |res| (req, res)),
|| Ok(Srv),
);
if let Async::Ready(mut srv) = new_srv.new_service(&()).poll().unwrap() {
assert!(srv.poll_ready().is_ok());
let res = srv.call("srv").poll();
assert!(res.is_ok());
assert_eq!(res.unwrap(), Async::Ready(("srv", ())));
} else {
panic!()
}
}
}

View File

@@ -0,0 +1,311 @@
use std::marker::PhantomData;
use futures::{Async, Future, IntoFuture, Poll};
use super::{IntoNewService, IntoService, NewService, Service};
use crate::cell::Cell;
/// `Apply` service combinator
pub struct AndThenApply<A, B, F, Out>
where
A: Service,
B: Service<Error = A::Error>,
F: FnMut(A::Response, &mut B) -> Out,
Out: IntoFuture,
Out::Error: Into<A::Error>,
{
a: A,
b: Cell<B>,
f: Cell<F>,
r: PhantomData<(Out,)>,
}
impl<A, B, F, Out> AndThenApply<A, B, F, Out>
where
A: Service,
B: Service<Error = A::Error>,
F: FnMut(A::Response, &mut B) -> Out,
Out: IntoFuture,
Out::Error: Into<A::Error>,
{
/// Create new `Apply` combinator
pub fn new<A1: IntoService<A>, B1: IntoService<B>>(a: A1, b: B1, f: F) -> Self {
Self {
f: Cell::new(f),
a: a.into_service(),
b: Cell::new(b.into_service()),
r: PhantomData,
}
}
}
impl<A, B, F, Out> Clone for AndThenApply<A, B, F, Out>
where
A: Service + Clone,
B: Service<Error = A::Error>,
F: FnMut(A::Response, &mut B) -> Out,
Out: IntoFuture,
Out::Error: Into<A::Error>,
{
fn clone(&self) -> Self {
AndThenApply {
a: self.a.clone(),
b: self.b.clone(),
f: self.f.clone(),
r: PhantomData,
}
}
}
impl<A, B, F, Out> Service for AndThenApply<A, B, F, Out>
where
A: Service,
B: Service<Error = A::Error>,
F: FnMut(A::Response, &mut B) -> Out,
Out: IntoFuture,
Out::Error: Into<A::Error>,
{
type Request = A::Request;
type Response = Out::Item;
type Error = A::Error;
type Future = AndThenApplyFuture<A, B, F, Out>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
let not_ready = self.a.poll_ready()?.is_not_ready();
if self.b.get_mut().poll_ready()?.is_not_ready() || not_ready {
Ok(Async::NotReady)
} else {
Ok(Async::Ready(()))
}
}
fn call(&mut self, req: A::Request) -> Self::Future {
AndThenApplyFuture {
b: self.b.clone(),
f: self.f.clone(),
fut_b: None,
fut_a: Some(self.a.call(req)),
}
}
}
pub struct AndThenApplyFuture<A, B, F, Out>
where
A: Service,
B: Service<Error = A::Error>,
F: FnMut(A::Response, &mut B) -> Out,
Out: IntoFuture,
Out::Error: Into<A::Error>,
{
b: Cell<B>,
f: Cell<F>,
fut_a: Option<A::Future>,
fut_b: Option<Out::Future>,
}
impl<A, B, F, Out> Future for AndThenApplyFuture<A, B, F, Out>
where
A: Service,
B: Service<Error = A::Error>,
F: FnMut(A::Response, &mut B) -> Out,
Out: IntoFuture,
Out::Error: Into<A::Error>,
{
type Item = Out::Item;
type Error = A::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
if let Some(ref mut fut) = self.fut_b {
return fut.poll().map_err(|e| e.into());
}
match self.fut_a.as_mut().expect("Bug in actix-service").poll() {
Ok(Async::Ready(resp)) => {
let _ = self.fut_a.take();
self.fut_b =
Some((&mut *self.f.get_mut())(resp, self.b.get_mut()).into_future());
self.poll()
}
Ok(Async::NotReady) => Ok(Async::NotReady),
Err(err) => Err(err),
}
}
}
/// `ApplyNewService` new service combinator
pub struct AndThenApplyNewService<A, B, F, Out, Cfg> {
a: A,
b: B,
f: Cell<F>,
r: PhantomData<(Out, Cfg)>,
}
impl<A, B, F, Out, Cfg> AndThenApplyNewService<A, B, F, Out, Cfg>
where
A: NewService<Cfg>,
B: NewService<Cfg, Error = A::Error, InitError = A::InitError>,
F: FnMut(A::Response, &mut B::Service) -> Out,
Out: IntoFuture,
Out::Error: Into<A::Error>,
{
/// Create new `ApplyNewService` new service instance
pub fn new<A1: IntoNewService<A, Cfg>, B1: IntoNewService<B, Cfg>>(
a: A1,
b: B1,
f: F,
) -> Self {
Self {
f: Cell::new(f),
a: a.into_new_service(),
b: b.into_new_service(),
r: PhantomData,
}
}
}
impl<A, B, F, Out, Cfg> Clone for AndThenApplyNewService<A, B, F, Out, Cfg>
where
A: Clone,
B: Clone,
{
fn clone(&self) -> Self {
Self {
a: self.a.clone(),
b: self.b.clone(),
f: self.f.clone(),
r: PhantomData,
}
}
}
impl<A, B, F, Out, Cfg> NewService<Cfg> for AndThenApplyNewService<A, B, F, Out, Cfg>
where
A: NewService<Cfg>,
B: NewService<Cfg, Error = A::Error, InitError = A::InitError>,
F: FnMut(A::Response, &mut B::Service) -> Out,
Out: IntoFuture,
Out::Error: Into<A::Error>,
{
type Request = A::Request;
type Response = Out::Item;
type Error = A::Error;
type Service = AndThenApply<A::Service, B::Service, F, Out>;
type InitError = A::InitError;
type Future = AndThenApplyNewServiceFuture<A, B, F, Out, Cfg>;
fn new_service(&self, cfg: &Cfg) -> Self::Future {
AndThenApplyNewServiceFuture {
a: None,
b: None,
f: self.f.clone(),
fut_a: self.a.new_service(cfg).into_future(),
fut_b: self.b.new_service(cfg).into_future(),
}
}
}
pub struct AndThenApplyNewServiceFuture<A, B, F, Out, Cfg>
where
A: NewService<Cfg>,
B: NewService<Cfg, Error = A::Error, InitError = A::InitError>,
F: FnMut(A::Response, &mut B::Service) -> Out,
Out: IntoFuture,
Out::Error: Into<A::Error>,
{
fut_b: B::Future,
fut_a: A::Future,
f: Cell<F>,
a: Option<A::Service>,
b: Option<B::Service>,
}
impl<A, B, F, Out, Cfg> Future for AndThenApplyNewServiceFuture<A, B, F, Out, Cfg>
where
A: NewService<Cfg>,
B: NewService<Cfg, Error = A::Error, InitError = A::InitError>,
F: FnMut(A::Response, &mut B::Service) -> Out,
Out: IntoFuture,
Out::Error: Into<A::Error>,
{
type Item = AndThenApply<A::Service, B::Service, F, Out>;
type Error = A::InitError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
if self.a.is_none() {
if let Async::Ready(service) = self.fut_a.poll()? {
self.a = Some(service);
}
}
if self.b.is_none() {
if let Async::Ready(service) = self.fut_b.poll()? {
self.b = Some(service);
}
}
if self.a.is_some() && self.b.is_some() {
Ok(Async::Ready(AndThenApply {
f: self.f.clone(),
a: self.a.take().unwrap(),
b: Cell::new(self.b.take().unwrap()),
r: PhantomData,
}))
} else {
Ok(Async::NotReady)
}
}
}
#[cfg(test)]
mod tests {
use futures::future::{ok, FutureResult};
use futures::{Async, Future, Poll};
use crate::blank::{Blank, BlankNewService};
use crate::{NewService, Service, ServiceExt};
#[derive(Clone)]
struct Srv;
impl Service for Srv {
type Request = ();
type Response = ();
type Error = ();
type Future = FutureResult<(), ()>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
fn call(&mut self, _: ()) -> Self::Future {
ok(())
}
}
#[test]
fn test_call() {
let mut srv = Blank::new().apply_fn(Srv, |req: &'static str, srv| {
srv.call(()).map(move |res| (req, res))
});
assert!(srv.poll_ready().is_ok());
let res = srv.call("srv").poll();
assert!(res.is_ok());
assert_eq!(res.unwrap(), Async::Ready(("srv", ())));
}
#[test]
fn test_new_service() {
let new_srv = BlankNewService::new_unit().apply_fn(
|| Ok(Srv),
|req: &'static str, srv| srv.call(()).map(move |res| (req, res)),
);
if let Async::Ready(mut srv) = new_srv.new_service(&()).poll().unwrap() {
assert!(srv.poll_ready().is_ok());
let res = srv.call("srv").poll();
assert!(res.is_ok());
assert_eq!(res.unwrap(), Async::Ready(("srv", ())));
} else {
panic!()
}
}
}

259
actix-service/src/apply.rs Normal file
View File

@@ -0,0 +1,259 @@
use std::marker::PhantomData;
use futures::{Async, Future, IntoFuture, Poll};
use super::{IntoNewService, IntoService, NewService, Service};
/// Apply tranform function to a service
pub fn apply_fn<T, F, In, Out, U>(service: U, f: F) -> Apply<T, F, In, Out>
where
T: Service,
F: FnMut(In, &mut T) -> Out,
Out: IntoFuture,
Out::Error: From<T::Error>,
U: IntoService<T>,
{
Apply::new(service.into_service(), f)
}
/// Create fractory for `apply_fn` service.
pub fn apply_fn_factory<T, F, In, Out, Cfg, U>(
service: U,
f: F,
) -> ApplyNewService<T, F, In, Out, Cfg>
where
T: NewService<Cfg>,
F: FnMut(In, &mut T::Service) -> Out + Clone,
Out: IntoFuture,
Out::Error: From<T::Error>,
U: IntoNewService<T, Cfg>,
{
ApplyNewService::new(service.into_new_service(), f)
}
#[doc(hidden)]
/// `Apply` service combinator
pub struct Apply<T, F, In, Out>
where
T: Service,
{
service: T,
f: F,
r: PhantomData<(In, Out)>,
}
impl<T, F, In, Out> Apply<T, F, In, Out>
where
T: Service,
F: FnMut(In, &mut T) -> Out,
Out: IntoFuture,
Out::Error: From<T::Error>,
{
/// Create new `Apply` combinator
pub fn new<I: IntoService<T>>(service: I, f: F) -> Self {
Self {
service: service.into_service(),
f,
r: PhantomData,
}
}
}
impl<T, F, In, Out> Clone for Apply<T, F, In, Out>
where
T: Service + Clone,
F: Clone,
{
fn clone(&self) -> Self {
Apply {
service: self.service.clone(),
f: self.f.clone(),
r: PhantomData,
}
}
}
impl<T, F, In, Out> Service for Apply<T, F, In, Out>
where
T: Service,
F: FnMut(In, &mut T) -> Out,
Out: IntoFuture,
Out::Error: From<T::Error>,
{
type Request = In;
type Response = Out::Item;
type Error = Out::Error;
type Future = Out::Future;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.service.poll_ready().map_err(|e| e.into())
}
fn call(&mut self, req: In) -> Self::Future {
(self.f)(req, &mut self.service).into_future()
}
}
/// `ApplyNewService` new service combinator
pub struct ApplyNewService<T, F, In, Out, Cfg>
where
T: NewService<Cfg>,
{
service: T,
f: F,
r: PhantomData<(In, Out, Cfg)>,
}
impl<T, F, In, Out, Cfg> ApplyNewService<T, F, In, Out, Cfg>
where
T: NewService<Cfg>,
F: FnMut(In, &mut T::Service) -> Out + Clone,
Out: IntoFuture,
Out::Error: From<T::Error>,
{
/// Create new `ApplyNewService` new service instance
pub fn new<F1: IntoNewService<T, Cfg>>(service: F1, f: F) -> Self {
Self {
f,
service: service.into_new_service(),
r: PhantomData,
}
}
}
impl<T, F, In, Out, Cfg> Clone for ApplyNewService<T, F, In, Out, Cfg>
where
T: NewService<Cfg> + Clone,
F: FnMut(In, &mut T::Service) -> Out + Clone,
Out: IntoFuture,
{
fn clone(&self) -> Self {
Self {
service: self.service.clone(),
f: self.f.clone(),
r: PhantomData,
}
}
}
impl<T, F, In, Out, Cfg> NewService<Cfg> for ApplyNewService<T, F, In, Out, Cfg>
where
T: NewService<Cfg>,
F: FnMut(In, &mut T::Service) -> Out + Clone,
Out: IntoFuture,
Out::Error: From<T::Error>,
{
type Request = In;
type Response = Out::Item;
type Error = Out::Error;
type Service = Apply<T::Service, F, In, Out>;
type InitError = T::InitError;
type Future = ApplyNewServiceFuture<T, F, In, Out, Cfg>;
fn new_service(&self, cfg: &Cfg) -> Self::Future {
ApplyNewServiceFuture::new(self.service.new_service(cfg), self.f.clone())
}
}
pub struct ApplyNewServiceFuture<T, F, In, Out, Cfg>
where
T: NewService<Cfg>,
F: FnMut(In, &mut T::Service) -> Out + Clone,
Out: IntoFuture,
{
fut: T::Future,
f: Option<F>,
r: PhantomData<(In, Out)>,
}
impl<T, F, In, Out, Cfg> ApplyNewServiceFuture<T, F, In, Out, Cfg>
where
T: NewService<Cfg>,
F: FnMut(In, &mut T::Service) -> Out + Clone,
Out: IntoFuture,
{
fn new(fut: T::Future, f: F) -> Self {
ApplyNewServiceFuture {
f: Some(f),
fut,
r: PhantomData,
}
}
}
impl<T, F, In, Out, Cfg> Future for ApplyNewServiceFuture<T, F, In, Out, Cfg>
where
T: NewService<Cfg>,
F: FnMut(In, &mut T::Service) -> Out + Clone,
Out: IntoFuture,
Out::Error: From<T::Error>,
{
type Item = Apply<T::Service, F, In, Out>;
type Error = T::InitError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
if let Async::Ready(service) = self.fut.poll()? {
Ok(Async::Ready(Apply::new(service, self.f.take().unwrap())))
} else {
Ok(Async::NotReady)
}
}
}
#[cfg(test)]
mod tests {
use futures::future::{ok, FutureResult};
use futures::{Async, Future, Poll};
use super::*;
use crate::{IntoService, NewService, Service, ServiceExt};
#[derive(Clone)]
struct Srv;
impl Service for Srv {
type Request = ();
type Response = ();
type Error = ();
type Future = FutureResult<(), ()>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
fn call(&mut self, _: ()) -> Self::Future {
ok(())
}
}
#[test]
fn test_call() {
let blank = |req| Ok(req);
let mut srv = blank
.into_service()
.apply_fn(Srv, |req: &'static str, srv| {
srv.call(()).map(move |res| (req, res))
});
assert!(srv.poll_ready().is_ok());
let res = srv.call("srv").poll();
assert!(res.is_ok());
assert_eq!(res.unwrap(), Async::Ready(("srv", ())));
}
#[test]
fn test_new_service() {
let new_srv = ApplyNewService::new(
|| Ok::<_, ()>(Srv),
|req: &'static str, srv| srv.call(()).map(move |res| (req, res)),
);
if let Async::Ready(mut srv) = new_srv.new_service(&()).poll().unwrap() {
assert!(srv.poll_ready().is_ok());
let res = srv.call("srv").poll();
assert!(res.is_ok());
assert_eq!(res.unwrap(), Async::Ready(("srv", ())));
} else {
panic!()
}
}
}

View File

@@ -0,0 +1,112 @@
use std::marker::PhantomData;
use crate::{IntoNewService, NewService};
/// Create new ApplyConfig` service factory combinator
pub fn apply_cfg<F, S, C1, C2, U>(f: F, service: U) -> ApplyConfig<F, S, C1, C2>
where
S: NewService<C2>,
F: Fn(&C1) -> C2,
U: IntoNewService<S, C2>,
{
ApplyConfig::new(service.into_new_service(), f)
}
/// `ApplyConfig` service factory combinator
pub struct ApplyConfig<F, S, C1, C2> {
s: S,
f: F,
r: PhantomData<(C1, C2)>,
}
impl<F, S, C1, C2> ApplyConfig<F, S, C1, C2>
where
S: NewService<C2>,
F: Fn(&C1) -> C2,
{
/// Create new ApplyConfig` service factory combinator
pub fn new<U: IntoNewService<S, C2>>(a: U, f: F) -> Self {
Self {
f,
s: a.into_new_service(),
r: PhantomData,
}
}
}
impl<F, S, C1, C2> Clone for ApplyConfig<F, S, C1, C2>
where
S: Clone,
F: Clone,
{
fn clone(&self) -> Self {
Self {
s: self.s.clone(),
f: self.f.clone(),
r: PhantomData,
}
}
}
impl<F, S, C1, C2> NewService<C1> for ApplyConfig<F, S, C1, C2>
where
S: NewService<C2>,
F: Fn(&C1) -> C2,
{
type Request = S::Request;
type Response = S::Response;
type Error = S::Error;
type Service = S::Service;
type InitError = S::InitError;
type Future = S::Future;
fn new_service(&self, cfg: &C1) -> Self::Future {
let cfg2 = (self.f)(cfg);
self.s.new_service(&cfg2)
}
}
#[cfg(test)]
mod tests {
use futures::future::{ok, FutureResult};
use futures::{Async, Future, Poll};
use crate::{fn_cfg_factory, NewService, Service};
#[derive(Clone)]
struct Srv;
impl Service for Srv {
type Request = ();
type Response = ();
type Error = ();
type Future = FutureResult<(), ()>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
fn call(&mut self, _: ()) -> Self::Future {
ok(())
}
}
#[test]
fn test_new_service() {
let new_srv = fn_cfg_factory(|_: &usize| Ok::<_, ()>(Srv)).apply_cfg(
fn_cfg_factory(|s: &String| {
assert_eq!(s, "test");
Ok::<_, ()>(Srv)
}),
|cfg: &usize| {
assert_eq!(*cfg, 1);
"test".to_string()
},
);
if let Async::Ready(mut srv) = new_srv.new_service(&1).poll().unwrap() {
assert!(srv.poll_ready().is_ok());
}
}
}

View File

@@ -0,0 +1,83 @@
use std::marker::PhantomData;
use futures::future::{ok, FutureResult};
use futures::{Async, Poll};
use super::{NewService, Service};
/// Empty service
#[derive(Clone)]
pub struct Blank<R, E> {
_t: PhantomData<(R, E)>,
}
impl<R, E> Blank<R, E> {
pub fn err<E1>(self) -> Blank<R, E1> {
Blank { _t: PhantomData }
}
}
impl<R> Blank<R, ()> {
#[allow(clippy::new_ret_no_self)]
pub fn new<E>() -> Blank<R, E> {
Blank { _t: PhantomData }
}
}
impl<R, E> Default for Blank<R, E> {
fn default() -> Blank<R, E> {
Blank { _t: PhantomData }
}
}
impl<R, E> Service for Blank<R, E> {
type Request = R;
type Response = R;
type Error = E;
type Future = FutureResult<R, E>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
fn call(&mut self, req: R) -> Self::Future {
ok(req)
}
}
/// Empty service factory
pub struct BlankNewService<R, E1, E2 = ()> {
_t: PhantomData<(R, E1, E2)>,
}
impl<R, E1, E2> BlankNewService<R, E1, E2> {
pub fn new() -> BlankNewService<R, E1, E2> {
BlankNewService { _t: PhantomData }
}
}
impl<R, E1> BlankNewService<R, E1, ()> {
pub fn new_unit() -> BlankNewService<R, E1, ()> {
BlankNewService { _t: PhantomData }
}
}
impl<R, E1, E2> Default for BlankNewService<R, E1, E2> {
fn default() -> BlankNewService<R, E1, E2> {
Self::new()
}
}
impl<R, E1, E2> NewService<()> for BlankNewService<R, E1, E2> {
type Request = R;
type Response = R;
type Error = E1;
type Service = Blank<R, E1>;
type InitError = E2;
type Future = FutureResult<Self::Service, Self::InitError>;
fn new_service(&self, _: &()) -> Self::Future {
ok(Blank::default())
}
}

147
actix-service/src/boxed.rs Normal file
View File

@@ -0,0 +1,147 @@
use futures::future::{err, ok, Either, FutureResult};
use futures::{Async, Future, IntoFuture, Poll};
use crate::{NewService, Service};
pub type BoxedService<Req, Res, Err> = Box<
Service<
Request = Req,
Response = Res,
Error = Err,
Future = Either<FutureResult<Res, Err>, Box<Future<Item = Res, Error = Err>>>,
>,
>;
/// Create boxed new service
pub fn new_service<T, C>(
service: T,
) -> BoxedNewService<C, T::Request, T::Response, T::Error, T::InitError>
where
C: 'static,
T: NewService<C> + 'static,
T::Request: 'static,
T::Response: 'static,
T::Service: 'static,
T::Future: 'static,
T::Error: 'static,
T::InitError: 'static,
{
BoxedNewService(Box::new(NewServiceWrapper {
service,
_t: std::marker::PhantomData,
}))
}
/// Create boxed service
pub fn service<T>(service: T) -> BoxedService<T::Request, T::Response, T::Error>
where
T: Service + 'static,
T::Future: 'static,
{
Box::new(ServiceWrapper(service))
}
type Inner<C, Req, Res, Err, InitErr> = Box<
NewService<
C,
Request = Req,
Response = Res,
Error = Err,
InitError = InitErr,
Service = BoxedService<Req, Res, Err>,
Future = Box<Future<Item = BoxedService<Req, Res, Err>, Error = InitErr>>,
>,
>;
pub struct BoxedNewService<C, Req, Res, Err, InitErr>(Inner<C, Req, Res, Err, InitErr>);
impl<C, Req, Res, Err, InitErr> NewService<C> for BoxedNewService<C, Req, Res, Err, InitErr>
where
Req: 'static,
Res: 'static,
Err: 'static,
InitErr: 'static,
{
type Request = Req;
type Response = Res;
type Error = Err;
type InitError = InitErr;
type Service = BoxedService<Req, Res, Err>;
type Future = Box<Future<Item = Self::Service, Error = Self::InitError>>;
fn new_service(&self, cfg: &C) -> Self::Future {
self.0.new_service(cfg)
}
}
struct NewServiceWrapper<C, T: NewService<C>> {
service: T,
_t: std::marker::PhantomData<C>,
}
impl<C, T, Req, Res, Err, InitErr> NewService<C> for NewServiceWrapper<C, T>
where
Req: 'static,
Res: 'static,
Err: 'static,
InitErr: 'static,
T: NewService<C, Request = Req, Response = Res, Error = Err, InitError = InitErr>,
T::Future: 'static,
T::Service: 'static,
<T::Service as Service>::Future: 'static,
{
type Request = Req;
type Response = Res;
type Error = Err;
type InitError = InitErr;
type Service = BoxedService<Req, Res, Err>;
type Future = Box<Future<Item = Self::Service, Error = Self::InitError>>;
fn new_service(&self, cfg: &C) -> Self::Future {
Box::new(
self.service
.new_service(cfg)
.into_future()
.map(ServiceWrapper::boxed),
)
}
}
struct ServiceWrapper<T: Service>(T);
impl<T> ServiceWrapper<T>
where
T: Service + 'static,
T::Future: 'static,
{
fn boxed(service: T) -> BoxedService<T::Request, T::Response, T::Error> {
Box::new(ServiceWrapper(service))
}
}
impl<T, Req, Res, Err> Service for ServiceWrapper<T>
where
T: Service<Request = Req, Response = Res, Error = Err>,
T::Future: 'static,
{
type Request = Req;
type Response = Res;
type Error = Err;
type Future = Either<
FutureResult<Self::Response, Self::Error>,
Box<Future<Item = Self::Response, Error = Self::Error>>,
>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.0.poll_ready()
}
fn call(&mut self, req: Self::Request) -> Self::Future {
let mut fut = self.0.call(req);
match fut.poll() {
Ok(Async::Ready(res)) => Either::A(ok(res)),
Err(e) => Either::A(err(e)),
Ok(Async::NotReady) => Either::B(Box::new(fut)),
}
}
}

32
actix-service/src/cell.rs Normal file
View File

@@ -0,0 +1,32 @@
//! Custom cell impl
use std::{cell::UnsafeCell, fmt, rc::Rc};
pub(crate) struct Cell<T> {
inner: Rc<UnsafeCell<T>>,
}
impl<T> Clone for Cell<T> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
}
}
}
impl<T: fmt::Debug> fmt::Debug for Cell<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.inner.fmt(f)
}
}
impl<T> Cell<T> {
pub(crate) fn new(inner: T) -> Self {
Self {
inner: Rc::new(UnsafeCell::new(inner)),
}
}
pub(crate) fn get_mut(&mut self) -> &mut T {
unsafe { &mut *self.inner.as_ref().get() }
}
}

View File

@@ -0,0 +1,311 @@
use std::marker::PhantomData;
use futures::future::{ok, Future, FutureResult};
use futures::{try_ready, Async, IntoFuture, Poll};
use crate::{IntoConfigurableNewService, IntoNewService, IntoService, NewService, Service};
/// Create `NewService` for function that can act as Service
pub fn fn_service<F, Req, Out, Cfg>(f: F) -> FnNewService<F, Req, Out, Cfg>
where
F: FnMut(Req) -> Out + Clone,
Out: IntoFuture,
{
FnNewService::new(f)
}
/// Create `NewService` for function that can produce services
pub fn fn_factory<F, R, S, E>(f: F) -> FnNewServiceNoConfig<F, R, S, E>
where
F: Fn() -> R,
R: IntoFuture<Item = S, Error = E>,
S: Service,
{
FnNewServiceNoConfig::new(f)
}
/// Create `NewService` for function that can produce services with configuration
pub fn fn_cfg_factory<F, C, R, S, E>(f: F) -> FnNewServiceConfig<F, C, R, S, E>
where
F: Fn(&C) -> R,
R: IntoFuture<Error = E>,
R::Item: IntoService<S>,
S: Service,
{
FnNewServiceConfig::new(f)
}
pub struct FnService<F, Req, Out>
where
F: FnMut(Req) -> Out,
Out: IntoFuture,
{
f: F,
_t: PhantomData<(Req,)>,
}
impl<F, Req, Out> FnService<F, Req, Out>
where
F: FnMut(Req) -> Out,
Out: IntoFuture,
{
pub fn new(f: F) -> Self {
FnService { f, _t: PhantomData }
}
}
impl<F, Req, Out> Clone for FnService<F, Req, Out>
where
F: FnMut(Req) -> Out + Clone,
Out: IntoFuture,
{
fn clone(&self) -> Self {
FnService {
f: self.f.clone(),
_t: PhantomData,
}
}
}
impl<F, Req, Out> Service for FnService<F, Req, Out>
where
F: FnMut(Req) -> Out,
Out: IntoFuture,
{
type Request = Req;
type Response = Out::Item;
type Error = Out::Error;
type Future = Out::Future;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
fn call(&mut self, req: Req) -> Self::Future {
(self.f)(req).into_future()
}
}
impl<F, Req, Out> IntoService<FnService<F, Req, Out>> for F
where
F: FnMut(Req) -> Out + 'static,
Out: IntoFuture,
{
fn into_service(self) -> FnService<F, Req, Out> {
FnService::new(self)
}
}
pub struct FnNewService<F, Req, Out, Cfg>
where
F: FnMut(Req) -> Out,
Out: IntoFuture,
{
f: F,
_t: PhantomData<(Req, Cfg)>,
}
impl<F, Req, Out, Cfg> FnNewService<F, Req, Out, Cfg>
where
F: FnMut(Req) -> Out + Clone,
Out: IntoFuture,
{
pub fn new(f: F) -> Self {
FnNewService { f, _t: PhantomData }
}
}
impl<F, Req, Out, Cfg> NewService<Cfg> for FnNewService<F, Req, Out, Cfg>
where
F: FnMut(Req) -> Out + Clone,
Out: IntoFuture,
{
type Request = Req;
type Response = Out::Item;
type Error = Out::Error;
type Service = FnService<F, Req, Out>;
type InitError = ();
type Future = FutureResult<Self::Service, Self::InitError>;
fn new_service(&self, _: &Cfg) -> Self::Future {
ok(FnService::new(self.f.clone()))
}
}
impl<F, Req, Out, Cfg> Clone for FnNewService<F, Req, Out, Cfg>
where
F: FnMut(Req) -> Out + Clone,
Out: IntoFuture,
{
fn clone(&self) -> Self {
Self::new(self.f.clone())
}
}
impl<F, Req, Out, Cfg> IntoNewService<FnNewService<F, Req, Out, Cfg>, Cfg> for F
where
F: Fn(Req) -> Out + Clone,
Out: IntoFuture,
{
fn into_new_service(self) -> FnNewService<F, Req, Out, Cfg> {
FnNewService::new(self)
}
}
/// Converter for `Fn() -> Future<Service>` fn
pub struct FnNewServiceNoConfig<F, R, S, E>
where
F: Fn() -> R,
R: IntoFuture<Item = S, Error = E>,
S: Service,
{
f: F,
}
impl<F, R, S, E> FnNewServiceNoConfig<F, R, S, E>
where
F: Fn() -> R,
R: IntoFuture<Item = S, Error = E>,
S: Service,
{
pub fn new(f: F) -> Self {
FnNewServiceNoConfig { f }
}
}
impl<F, R, S, E> NewService<()> for FnNewServiceNoConfig<F, R, S, E>
where
F: Fn() -> R,
R: IntoFuture<Item = S, Error = E>,
S: Service,
{
type Request = S::Request;
type Response = S::Response;
type Error = S::Error;
type Service = S;
type InitError = E;
type Future = R::Future;
fn new_service(&self, _: &()) -> Self::Future {
(self.f)().into_future()
}
}
impl<F, R, S, E> Clone for FnNewServiceNoConfig<F, R, S, E>
where
F: Fn() -> R + Clone,
R: IntoFuture<Item = S, Error = E>,
S: Service,
{
fn clone(&self) -> Self {
Self::new(self.f.clone())
}
}
impl<F, R, S, E> IntoNewService<FnNewServiceNoConfig<F, R, S, E>, ()> for F
where
F: Fn() -> R,
R: IntoFuture<Item = S, Error = E>,
S: Service,
{
fn into_new_service(self) -> FnNewServiceNoConfig<F, R, S, E> {
FnNewServiceNoConfig::new(self)
}
}
/// Convert `Fn(&Config) -> Future<Service>` fn to NewService
pub struct FnNewServiceConfig<F, C, R, S, E>
where
F: Fn(&C) -> R,
R: IntoFuture<Error = E>,
R::Item: IntoService<S>,
S: Service,
{
f: F,
_t: PhantomData<(C, R, S, E)>,
}
impl<F, C, R, S, E> FnNewServiceConfig<F, C, R, S, E>
where
F: Fn(&C) -> R,
R: IntoFuture<Error = E>,
R::Item: IntoService<S>,
S: Service,
{
pub fn new(f: F) -> Self {
FnNewServiceConfig { f, _t: PhantomData }
}
}
impl<F, C, R, S, E> NewService<C> for FnNewServiceConfig<F, C, R, S, E>
where
F: Fn(&C) -> R,
R: IntoFuture<Error = E>,
R::Item: IntoService<S>,
S: Service,
{
type Request = S::Request;
type Response = S::Response;
type Error = S::Error;
type Service = S;
type InitError = E;
type Future = FnNewServiceConfigFut<R, S, E>;
fn new_service(&self, cfg: &C) -> Self::Future {
FnNewServiceConfigFut {
fut: (self.f)(cfg).into_future(),
_t: PhantomData,
}
}
}
pub struct FnNewServiceConfigFut<R, S, E>
where
R: IntoFuture<Error = E>,
R::Item: IntoService<S>,
S: Service,
{
fut: R::Future,
_t: PhantomData<(S,)>,
}
impl<R, S, E> Future for FnNewServiceConfigFut<R, S, E>
where
R: IntoFuture<Error = E>,
R::Item: IntoService<S>,
S: Service,
{
type Item = S;
type Error = R::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
Ok(Async::Ready(try_ready!(self.fut.poll()).into_service()))
}
}
impl<F, C, R, S, E> Clone for FnNewServiceConfig<F, C, R, S, E>
where
F: Fn(&C) -> R + Clone,
R: IntoFuture<Error = E>,
R::Item: IntoService<S>,
S: Service,
{
fn clone(&self) -> Self {
Self::new(self.f.clone())
}
}
impl<F, C, R, S, E> IntoConfigurableNewService<FnNewServiceConfig<F, C, R, S, E>, C> for F
where
F: Fn(&C) -> R,
R: IntoFuture<Error = E>,
R::Item: IntoService<S>,
S: Service,
{
fn into_new_service(self) -> FnNewServiceConfig<F, C, R, S, E> {
FnNewServiceConfig::new(self)
}
}

View File

@@ -0,0 +1,79 @@
use std::marker::PhantomData;
use futures::future::{ok, FutureResult};
use futures::IntoFuture;
use crate::{Apply, IntoTransform, Service, Transform};
/// Use function as transform service
pub fn fn_transform<F, S, In, Out, Err>(
f: F,
) -> impl Transform<S, Request = In, Response = Out::Item, Error = Out::Error, InitError = Err>
where
S: Service,
F: FnMut(In, &mut S) -> Out + Clone,
Out: IntoFuture,
Out::Error: From<S::Error>,
{
FnTransform::new(f)
}
pub struct FnTransform<F, S, In, Out, Err>
where
F: FnMut(In, &mut S) -> Out + Clone,
Out: IntoFuture,
{
f: F,
_t: PhantomData<(S, In, Out, Err)>,
}
impl<F, S, In, Out, Err> FnTransform<F, S, In, Out, Err>
where
F: FnMut(In, &mut S) -> Out + Clone,
Out: IntoFuture,
{
pub fn new(f: F) -> Self {
FnTransform { f, _t: PhantomData }
}
}
impl<F, S, In, Out, Err> Transform<S> for FnTransform<F, S, In, Out, Err>
where
S: Service,
F: FnMut(In, &mut S) -> Out + Clone,
Out: IntoFuture,
Out::Error: From<S::Error>,
{
type Request = In;
type Response = Out::Item;
type Error = Out::Error;
type Transform = Apply<S, F, In, Out>;
type InitError = Err;
type Future = FutureResult<Self::Transform, Self::InitError>;
fn new_transform(&self, service: S) -> Self::Future {
ok(Apply::new(service, self.f.clone()))
}
}
impl<F, S, In, Out, Err> IntoTransform<FnTransform<F, S, In, Out, Err>, S> for F
where
S: Service,
F: FnMut(In, &mut S) -> Out + Clone,
Out: IntoFuture,
Out::Error: From<S::Error>,
{
fn into_transform(self) -> FnTransform<F, S, In, Out, Err> {
FnTransform::new(self)
}
}
impl<F, S, In, Out, Err> Clone for FnTransform<F, S, In, Out, Err>
where
F: FnMut(In, &mut S) -> Out + Clone,
Out: IntoFuture,
{
fn clone(&self) -> Self {
Self::new(self.f.clone())
}
}

View File

@@ -7,16 +7,17 @@ use super::{NewService, Service};
/// Service for the `from_err` combinator, changing the error type of a service.
///
/// This is created by the `ServiceExt::from_err` method.
pub struct FromErr<A, E>
where
A: Service,
{
pub struct FromErr<A, E> {
service: A,
f: PhantomData<E>,
}
impl<A: Service, E: From<A::Error>> FromErr<A, E> {
pub(crate) fn new(service: A) -> Self {
impl<A, E> FromErr<A, E> {
pub(crate) fn new(service: A) -> Self
where
A: Service,
E: From<A::Error>,
{
FromErr {
service,
f: PhantomData,
@@ -26,8 +27,7 @@ impl<A: Service, E: From<A::Error>> FromErr<A, E> {
impl<A, E> Clone for FromErr<A, E>
where
A: Service + Clone,
E: From<A::Error>,
A: Clone,
{
fn clone(&self) -> Self {
FromErr {
@@ -48,10 +48,10 @@ where
type Future = FromErrFuture<A, E>;
fn poll_ready(&mut self) -> Poll<(), E> {
Ok(self.service.poll_ready().map_err(E::from)?)
self.service.poll_ready().map_err(E::from)
}
fn call(&mut self, req: Self::Request) -> Self::Future {
fn call(&mut self, req: A::Request) -> Self::Future {
FromErrFuture {
fut: self.service.call(req),
f: PhantomData,
@@ -81,26 +81,25 @@ where
/// service's error.
///
/// This is created by the `NewServiceExt::from_err` method.
pub struct FromErrNewService<A, E> {
pub struct FromErrNewService<A, E, C> {
a: A,
e: PhantomData<E>,
e: PhantomData<(E, C)>,
}
impl<A, E> FromErrNewService<A, E>
where
A: NewService,
E: From<A::Error>,
{
impl<A, E, C> FromErrNewService<A, E, C> {
/// Create new `FromErr` new service instance
pub fn new(a: A) -> Self {
pub fn new(a: A) -> Self
where
A: NewService<C>,
E: From<A::Error>,
{
Self { a, e: PhantomData }
}
}
impl<A, E> Clone for FromErrNewService<A, E>
impl<A, E, C> Clone for FromErrNewService<A, E, C>
where
A: NewService + Clone,
E: From<A::Error>,
A: Clone,
{
fn clone(&self) -> Self {
Self {
@@ -110,9 +109,9 @@ where
}
}
impl<A, E> NewService for FromErrNewService<A, E>
impl<A, E, C> NewService<C> for FromErrNewService<A, E, C>
where
A: NewService,
A: NewService<C>,
E: From<A::Error>,
{
type Request = A::Request;
@@ -121,28 +120,28 @@ where
type Service = FromErr<A::Service, E>;
type InitError = A::InitError;
type Future = FromErrNewServiceFuture<A, E>;
type Future = FromErrNewServiceFuture<A, E, C>;
fn new_service(&self) -> Self::Future {
fn new_service(&self, cfg: &C) -> Self::Future {
FromErrNewServiceFuture {
fut: self.a.new_service(),
fut: self.a.new_service(cfg),
e: PhantomData,
}
}
}
pub struct FromErrNewServiceFuture<A, E>
pub struct FromErrNewServiceFuture<A, E, C>
where
A: NewService,
A: NewService<C>,
E: From<A::Error>,
{
fut: A::Future,
e: PhantomData<E>,
}
impl<A, E> Future for FromErrNewServiceFuture<A, E>
impl<A, E, C> Future for FromErrNewServiceFuture<A, E, C>
where
A: NewService,
A: NewService<C>,
E: From<A::Error>,
{
type Item = FromErr<A::Service, E>;
@@ -162,7 +161,7 @@ mod tests {
use futures::future::{err, FutureResult};
use super::*;
use service::{IntoNewService, NewServiceExt, Service, ServiceExt};
use crate::{IntoNewService, NewService, Service, ServiceExt};
struct Srv;
impl Service for Srv {
@@ -209,7 +208,7 @@ mod tests {
fn test_new_service() {
let blank = || Ok::<_, ()>(Srv);
let new_srv = blank.into_new_service().from_err::<Error>();
if let Async::Ready(mut srv) = new_srv.new_service().poll().unwrap() {
if let Async::Ready(mut srv) = new_srv.new_service(&()).poll().unwrap() {
let res = srv.call(()).poll();
assert!(res.is_err());
assert_eq!(res.err().unwrap(), Error);

497
actix-service/src/lib.rs Normal file
View File

@@ -0,0 +1,497 @@
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;
use futures::{Future, IntoFuture, Poll};
pub use void::Void;
mod and_then;
mod and_then_apply;
mod and_then_apply_fn;
mod apply;
mod apply_cfg;
pub mod blank;
pub mod boxed;
mod cell;
mod fn_service;
mod fn_transform;
mod from_err;
mod map;
mod map_err;
mod map_init_err;
mod then;
mod transform;
mod transform_err;
#[doc(hidden)]
#[deprecated(since = "0.3.4", note = "please use `apply_fn` instead")]
pub use self::apply::Apply;
#[doc(hidden)]
#[deprecated(since = "0.3.4", note = "please use `apply_fn_factory` instead")]
pub use self::apply::ApplyNewService;
#[doc(hidden)]
#[deprecated(since = "0.3.4", note = "please use `fn_transform` instead")]
pub use self::fn_transform::FnTransform;
#[doc(hidden)]
#[deprecated(since = "0.3.4", note = "please use `apply_transform` instead")]
pub use self::transform::ApplyTransform;
pub use self::and_then::{AndThen, AndThenNewService};
use self::and_then_apply::AndThenTransform;
use self::and_then_apply_fn::{AndThenApply, AndThenApplyNewService};
pub use self::apply::{apply_fn, apply_fn_factory};
pub use self::apply_cfg::apply_cfg;
use self::apply_cfg::ApplyConfig;
pub use self::fn_service::{fn_cfg_factory, fn_factory, fn_service, FnService};
pub use self::fn_transform::fn_transform;
pub use self::from_err::{FromErr, FromErrNewService};
pub use self::map::{Map, MapNewService};
pub use self::map_err::{MapErr, MapErrNewService};
pub use self::map_init_err::MapInitErr;
pub use self::then::{Then, ThenNewService};
pub use self::transform::{apply_transform, IntoTransform, Transform};
/// An asynchronous function from `Request` to a `Response`.
pub trait Service {
/// Requests handled by the service.
type Request;
/// Responses given by the service.
type Response;
/// Errors produced by the service.
type Error;
/// The future response value.
type Future: Future<Item = Self::Response, Error = Self::Error>;
/// Returns `Ready` when the service is able to process requests.
///
/// If the service is at capacity, then `NotReady` is returned and the task
/// is notified when the service becomes ready again. This function is
/// expected to be called while on a task.
///
/// This is a **best effort** implementation. False positives are permitted.
/// It is permitted for the service to return `Ready` from a `poll_ready`
/// call and the next invocation of `call` results in an error.
fn poll_ready(&mut self) -> Poll<(), Self::Error>;
/// Process the request and return the response asynchronously.
///
/// This function is expected to be callable off task. As such,
/// implementations should take care to not call `poll_ready`. If the
/// service is at capacity and the request is unable to be handled, the
/// returned `Future` should resolve to an error.
///
/// Calling `call` without calling `poll_ready` is permitted. The
/// implementation must be resilient to this fact.
fn call(&mut self, req: Self::Request) -> Self::Future;
}
/// An extension trait for `Service`s that provides a variety of convenient
/// adapters
pub trait ServiceExt: Service {
/// Apply function to specified service and use it as a next service in
/// chain.
fn apply_fn<F, B, B1, Out>(self, service: B1, f: F) -> AndThenApply<Self, B, F, Out>
where
Self: Sized,
F: FnMut(Self::Response, &mut B) -> Out,
Out: IntoFuture,
Out::Error: Into<Self::Error>,
B: Service<Error = Self::Error>,
B1: IntoService<B>,
{
AndThenApply::new(self, service, f)
}
/// Call another service after call to this one has resolved successfully.
///
/// This function can be used to chain two services together and ensure that
/// the second service isn't called until call to the fist service have
/// finished. Result of the call to the first service is used as an
/// input parameter for the second service's call.
///
/// Note that this function consumes the receiving service and returns a
/// wrapped version of it.
fn and_then<F, B>(self, service: F) -> AndThen<Self, B>
where
Self: Sized,
F: IntoService<B>,
B: Service<Request = Self::Response, Error = Self::Error>,
{
AndThen::new(self, service.into_service())
}
/// Map this service's error to any error implementing `From` for
/// this service`s `Error`.
///
/// Note that this function consumes the receiving service and returns a
/// wrapped version of it.
fn from_err<E>(self) -> FromErr<Self, E>
where
Self: Sized,
E: From<Self::Error>,
{
FromErr::new(self)
}
/// Chain on a computation for when a call to the service finished,
/// passing the result of the call to the next service `B`.
///
/// Note that this function consumes the receiving service and returns a
/// wrapped version of it.
fn then<B>(self, service: B) -> Then<Self, B>
where
Self: Sized,
B: Service<Request = Result<Self::Response, Self::Error>, Error = Self::Error>,
{
Then::new(self, service)
}
/// Map this service's output to a different type, returning a new service
/// of the resulting type.
///
/// This function is similar to the `Option::map` or `Iterator::map` where
/// it will change the type of the underlying service.
///
/// Note that this function consumes the receiving service and returns a
/// wrapped version of it, similar to the existing `map` methods in the
/// standard library.
fn map<F, R>(self, f: F) -> Map<Self, F, R>
where
Self: Sized,
F: FnMut(Self::Response) -> R,
{
Map::new(self, f)
}
/// Map this service's error to a different error, returning a new service.
///
/// This function is similar to the `Result::map_err` where it will change
/// the error type of the underlying service. This is useful for example to
/// ensure that services have the same error type.
///
/// Note that this function consumes the receiving service and returns a
/// wrapped version of it.
fn map_err<F, E>(self, f: F) -> MapErr<Self, F, E>
where
Self: Sized,
F: Fn(Self::Error) -> E,
{
MapErr::new(self, f)
}
}
impl<T: ?Sized> ServiceExt for T where T: Service {}
/// Creates new `Service` values.
///
/// Acts as a service factory. This is useful for cases where new `Service`
/// values must be produced. One case is a TCP servier listener. The listner
/// accepts new TCP streams, obtains a new `Service` value using the
/// `NewService` trait, and uses that new `Service` value to process inbound
/// requests on that new TCP stream.
///
/// `Config` is a service factory configuration type.
pub trait NewService<Config = ()> {
/// Requests handled by the service.
type Request;
/// Responses given by the service
type Response;
/// Errors produced by the service
type Error;
/// The `Service` value created by this factory
type Service: Service<
Request = Self::Request,
Response = Self::Response,
Error = Self::Error,
>;
/// Errors produced while building a service.
type InitError;
/// The future of the `Service` instance.
type Future: Future<Item = Self::Service, Error = Self::InitError>;
/// Create and return a new service value asynchronously.
fn new_service(&self, cfg: &Config) -> Self::Future;
/// Apply transform service to specified service and use it as a next service in
/// chain.
fn apply<T, T1, B, B1>(
self,
transform: T1,
service: B1,
) -> AndThenTransform<T, Self, B, Config>
where
Self: Sized,
T: Transform<B::Service, Request = Self::Response, InitError = Self::InitError>,
T::Error: From<Self::Error>,
T1: IntoTransform<T, B::Service>,
B: NewService<Config, InitError = Self::InitError>,
B1: IntoNewService<B, Config>,
{
AndThenTransform::new(transform.into_transform(), self, service.into_new_service())
}
/// Apply function to specified service and use it as a next service in
/// chain.
fn apply_fn<B, I, F, Out>(
self,
service: I,
f: F,
) -> AndThenApplyNewService<Self, B, F, Out, Config>
where
Self: Sized,
B: NewService<Config, Error = Self::Error, InitError = Self::InitError>,
I: IntoNewService<B, Config>,
F: FnMut(Self::Response, &mut B::Service) -> Out,
Out: IntoFuture,
Out::Error: Into<Self::Error>,
{
AndThenApplyNewService::new(self, service, f)
}
/// Map this service's config type to a different config,
/// and use for nested service
fn apply_cfg<F, C, S, U>(
self,
service: U,
f: F,
) -> AndThenNewService<Self, ApplyConfig<F, S, Config, C>, Config>
where
Self: Sized,
F: Fn(&Config) -> C,
U: IntoNewService<S, C>,
S: NewService<
C,
Request = Self::Response,
Error = Self::Error,
InitError = Self::InitError,
>,
{
self.and_then(ApplyConfig::new(service, f))
}
/// Call another service after call to this one has resolved successfully.
fn and_then<F, B>(self, new_service: F) -> AndThenNewService<Self, B, Config>
where
Self: Sized,
F: IntoNewService<B, Config>,
B: NewService<
Config,
Request = Self::Response,
Error = Self::Error,
InitError = Self::InitError,
>,
{
AndThenNewService::new(self, new_service)
}
/// `NewService` that create service to map this service's error
/// and new service's init error to any error
/// implementing `From` for this service`s `Error`.
///
/// Note that this function consumes the receiving new service and returns a
/// wrapped version of it.
fn from_err<E>(self) -> FromErrNewService<Self, E, Config>
where
Self: Sized,
E: From<Self::Error>,
{
FromErrNewService::new(self)
}
/// Create `NewService` to chain on a computation for when a call to the
/// service finished, passing the result of the call to the next
/// service `B`.
///
/// Note that this function consumes the receiving future and returns a
/// wrapped version of it.
fn then<F, B>(self, new_service: F) -> ThenNewService<Self, B, Config>
where
Self: Sized,
F: IntoNewService<B, Config>,
B: NewService<
Config,
Request = Result<Self::Response, Self::Error>,
Error = Self::Error,
InitError = Self::InitError,
>,
{
ThenNewService::new(self, new_service)
}
/// Map this service's output to a different type, returning a new service
/// of the resulting type.
fn map<F, R>(self, f: F) -> MapNewService<Self, F, R, Config>
where
Self: Sized,
F: FnMut(Self::Response) -> R,
{
MapNewService::new(self, f)
}
/// Map this service's error to a different error, returning a new service.
fn map_err<F, E>(self, f: F) -> MapErrNewService<Self, F, E, Config>
where
Self: Sized,
F: Fn(Self::Error) -> E + Clone,
{
MapErrNewService::new(self, f)
}
/// Map this service's init error to a different error, returning a new service.
fn map_init_err<F, E>(self, f: F) -> MapInitErr<Self, F, E, Config>
where
Self: Sized,
F: Fn(Self::InitError) -> E,
{
MapInitErr::new(self, f)
}
}
impl<'a, S> Service for &'a mut S
where
S: Service + 'a,
{
type Request = S::Request;
type Response = S::Response;
type Error = S::Error;
type Future = S::Future;
fn poll_ready(&mut self) -> Poll<(), S::Error> {
(**self).poll_ready()
}
fn call(&mut self, request: Self::Request) -> S::Future {
(**self).call(request)
}
}
impl<S> Service for Box<S>
where
S: Service + ?Sized,
{
type Request = S::Request;
type Response = S::Response;
type Error = S::Error;
type Future = S::Future;
fn poll_ready(&mut self) -> Poll<(), S::Error> {
(**self).poll_ready()
}
fn call(&mut self, request: Self::Request) -> S::Future {
(**self).call(request)
}
}
impl<S> Service for Rc<RefCell<S>>
where
S: Service,
{
type Request = S::Request;
type Response = S::Response;
type Error = S::Error;
type Future = S::Future;
fn poll_ready(&mut self) -> Poll<(), S::Error> {
self.borrow_mut().poll_ready()
}
fn call(&mut self, request: Self::Request) -> S::Future {
self.borrow_mut().call(request)
}
}
impl<S, C> NewService<C> for Rc<S>
where
S: NewService<C>,
{
type Request = S::Request;
type Response = S::Response;
type Error = S::Error;
type Service = S::Service;
type InitError = S::InitError;
type Future = S::Future;
fn new_service(&self, cfg: &C) -> S::Future {
self.as_ref().new_service(cfg)
}
}
impl<S, C> NewService<C> for Arc<S>
where
S: NewService<C>,
{
type Request = S::Request;
type Response = S::Response;
type Error = S::Error;
type Service = S::Service;
type InitError = S::InitError;
type Future = S::Future;
fn new_service(&self, cfg: &C) -> S::Future {
self.as_ref().new_service(cfg)
}
}
/// Trait for types that can be converted to a `Service`
pub trait IntoService<T>
where
T: Service,
{
/// Convert to a `Service`
fn into_service(self) -> T;
}
/// Trait for types that can be converted to a `NewService`
pub trait IntoNewService<T, C = ()>
where
T: NewService<C>,
{
/// Convert to an `NewService`
fn into_new_service(self) -> T;
}
impl<T> IntoService<T> for T
where
T: Service,
{
fn into_service(self) -> T {
self
}
}
impl<T, C> IntoNewService<T, C> for T
where
T: NewService<C>,
{
fn into_new_service(self) -> T {
self
}
}
/// Trait for types that can be converted to a configurable `NewService`
pub trait IntoConfigurableNewService<T, C>
where
T: NewService<C>,
{
/// Convert to an `NewService`
fn into_new_service(self) -> T;
}
impl<T, C> IntoConfigurableNewService<T, C> for T
where
T: NewService<C>,
{
fn into_new_service(self) -> T {
self
}
}

View File

@@ -1,4 +1,4 @@
use std::marker;
use std::marker::PhantomData;
use futures::{Async, Future, Poll};
@@ -7,83 +7,85 @@ use super::{NewService, Service};
/// Service for the `map` combinator, changing the type of a service's response.
///
/// This is created by the `ServiceExt::map` method.
pub struct Map<A, F, R>
where
A: Service,
F: Fn(A::Response) -> R,
{
pub struct Map<A, F, Response> {
service: A,
f: F,
_t: PhantomData<Response>,
}
impl<A, F, R> Map<A, F, R>
where
A: Service,
F: Fn(A::Response) -> R,
{
impl<A, F, Response> Map<A, F, Response> {
/// Create new `Map` combinator
pub fn new(service: A, f: F) -> Self {
Self { service, f }
pub fn new(service: A, f: F) -> Self
where
A: Service,
F: FnMut(A::Response) -> Response,
{
Self {
service,
f,
_t: PhantomData,
}
}
}
impl<A, F, R> Clone for Map<A, F, R>
impl<A, F, Response> Clone for Map<A, F, Response>
where
A: Service + Clone,
F: Fn(A::Response) -> R + Clone,
A: Clone,
F: Clone,
{
fn clone(&self) -> Self {
Map {
service: self.service.clone(),
f: self.f.clone(),
_t: PhantomData,
}
}
}
impl<A, F, R> Service for Map<A, F, R>
impl<A, F, Response> Service for Map<A, F, Response>
where
A: Service,
F: Fn(A::Response) -> R + Clone,
F: FnMut(A::Response) -> Response + Clone,
{
type Request = A::Request;
type Response = R;
type Response = Response;
type Error = A::Error;
type Future = MapFuture<A, F, R>;
type Future = MapFuture<A, F, Response>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.service.poll_ready()
}
fn call(&mut self, req: Self::Request) -> Self::Future {
fn call(&mut self, req: A::Request) -> Self::Future {
MapFuture::new(self.service.call(req), self.f.clone())
}
}
pub struct MapFuture<A, F, R>
pub struct MapFuture<A, F, Response>
where
A: Service,
F: Fn(A::Response) -> R,
F: FnMut(A::Response) -> Response,
{
f: F,
fut: A::Future,
}
impl<A, F, R> MapFuture<A, F, R>
impl<A, F, Response> MapFuture<A, F, Response>
where
A: Service,
F: Fn(A::Response) -> R,
F: FnMut(A::Response) -> Response,
{
fn new(fut: A::Future, f: F) -> Self {
MapFuture { f, fut }
}
}
impl<A, F, R> Future for MapFuture<A, F, R>
impl<A, F, Response> Future for MapFuture<A, F, Response>
where
A: Service,
F: Fn(A::Response) -> R,
F: FnMut(A::Response) -> Response,
{
type Item = R;
type Item = Response;
type Error = A::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
@@ -95,84 +97,84 @@ where
}
/// `MapNewService` new service combinator
pub struct MapNewService<A, F, R> {
pub struct MapNewService<A, F, Res, Cfg> {
a: A,
f: F,
r: marker::PhantomData<R>,
r: PhantomData<(Res, Cfg)>,
}
impl<A, F, R> MapNewService<A, F, R>
where
A: NewService,
F: Fn(A::Response) -> R,
{
impl<A, F, Res, Cfg> MapNewService<A, F, Res, Cfg> {
/// Create new `Map` new service instance
pub fn new(a: A, f: F) -> Self {
pub fn new(a: A, f: F) -> Self
where
A: NewService<Cfg>,
F: FnMut(A::Response) -> Res,
{
Self {
a,
f,
r: marker::PhantomData,
r: PhantomData,
}
}
}
impl<A, F, R> Clone for MapNewService<A, F, R>
impl<A, F, Res, Cfg> Clone for MapNewService<A, F, Res, Cfg>
where
A: NewService + Clone,
F: Fn(A::Response) -> R + Clone,
A: Clone,
F: Clone,
{
fn clone(&self) -> Self {
Self {
a: self.a.clone(),
f: self.f.clone(),
r: marker::PhantomData,
r: PhantomData,
}
}
}
impl<A, F, R> NewService for MapNewService<A, F, R>
impl<A, F, Res, Cfg> NewService<Cfg> for MapNewService<A, F, Res, Cfg>
where
A: NewService,
F: Fn(A::Response) -> R + Clone,
A: NewService<Cfg>,
F: FnMut(A::Response) -> Res + Clone,
{
type Request = A::Request;
type Response = R;
type Response = Res;
type Error = A::Error;
type Service = Map<A::Service, F, R>;
type Service = Map<A::Service, F, Res>;
type InitError = A::InitError;
type Future = MapNewServiceFuture<A, F, R>;
type Future = MapNewServiceFuture<A, F, Res, Cfg>;
fn new_service(&self) -> Self::Future {
MapNewServiceFuture::new(self.a.new_service(), self.f.clone())
fn new_service(&self, cfg: &Cfg) -> Self::Future {
MapNewServiceFuture::new(self.a.new_service(cfg), self.f.clone())
}
}
pub struct MapNewServiceFuture<A, F, R>
pub struct MapNewServiceFuture<A, F, Res, Cfg>
where
A: NewService,
F: Fn(A::Response) -> R,
A: NewService<Cfg>,
F: FnMut(A::Response) -> Res,
{
fut: A::Future,
f: Option<F>,
}
impl<A, F, R> MapNewServiceFuture<A, F, R>
impl<A, F, Res, Cfg> MapNewServiceFuture<A, F, Res, Cfg>
where
A: NewService,
F: Fn(A::Response) -> R,
A: NewService<Cfg>,
F: FnMut(A::Response) -> Res,
{
fn new(fut: A::Future, f: F) -> Self {
MapNewServiceFuture { f: Some(f), fut }
}
}
impl<A, F, R> Future for MapNewServiceFuture<A, F, R>
impl<A, F, Res, Cfg> Future for MapNewServiceFuture<A, F, Res, Cfg>
where
A: NewService,
F: Fn(A::Response) -> R,
A: NewService<Cfg>,
F: FnMut(A::Response) -> Res,
{
type Item = Map<A::Service, F, R>;
type Item = Map<A::Service, F, Res>;
type Error = A::InitError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
@@ -189,7 +191,7 @@ mod tests {
use futures::future::{ok, FutureResult};
use super::*;
use service::{IntoNewService, NewServiceExt, Service, ServiceExt};
use crate::{IntoNewService, Service, ServiceExt};
struct Srv;
impl Service for Srv {
@@ -227,7 +229,7 @@ mod tests {
fn test_new_service() {
let blank = || Ok::<_, ()>(Srv);
let new_srv = blank.into_new_service().map(|_| "ok");
if let Async::Ready(mut srv) = new_srv.new_service().poll().unwrap() {
if let Async::Ready(mut srv) = new_srv.new_service(&()).poll().unwrap() {
let res = srv.call(()).poll();
assert!(res.is_ok());
assert_eq!(res.unwrap(), Async::Ready("ok"));

View File

@@ -1,4 +1,4 @@
use std::marker;
use std::marker::PhantomData;
use futures::{Async, Future, Poll};
@@ -8,35 +8,37 @@ use super::{NewService, Service};
/// error.
///
/// This is created by the `ServiceExt::map_err` method.
pub struct MapErr<A, F, E>
where
A: Service,
F: Fn(A::Error) -> E,
{
pub struct MapErr<A, F, E> {
service: A,
f: F,
_t: PhantomData<E>,
}
impl<A, F, E> MapErr<A, F, E>
where
A: Service,
F: Fn(A::Error) -> E,
{
impl<A, F, E> MapErr<A, F, E> {
/// Create new `MapErr` combinator
pub fn new(service: A, f: F) -> Self {
Self { service, f }
pub fn new(service: A, f: F) -> Self
where
A: Service,
F: Fn(A::Error) -> E,
{
Self {
service,
f,
_t: PhantomData,
}
}
}
impl<A, F, E> Clone for MapErr<A, F, E>
where
A: Service + Clone,
F: Fn(A::Error) -> E + Clone,
A: Clone,
F: Clone,
{
fn clone(&self) -> Self {
MapErr {
service: self.service.clone(),
f: self.f.clone(),
_t: PhantomData,
}
}
}
@@ -44,8 +46,7 @@ where
impl<A, F, E> Service for MapErr<A, F, E>
where
A: Service,
F: Fn(A::Error) -> E,
F: Clone,
F: Fn(A::Error) -> E + Clone,
{
type Request = A::Request;
type Response = A::Response;
@@ -56,7 +57,7 @@ where
self.service.poll_ready().map_err(&self.f)
}
fn call(&mut self, req: Self::Request) -> Self::Future {
fn call(&mut self, req: A::Request) -> Self::Future {
MapErrFuture::new(self.service.call(req), self.f.clone())
}
}
@@ -97,44 +98,48 @@ where
/// service's error.
///
/// This is created by the `NewServiceExt::map_err` method.
pub struct MapErrNewService<A, F, E> {
pub struct MapErrNewService<A, F, E, C>
where
A: NewService<C>,
F: Fn(A::Error) -> E + Clone,
{
a: A,
f: F,
e: marker::PhantomData<E>,
e: PhantomData<(E, C)>,
}
impl<A, F, E> MapErrNewService<A, F, E>
impl<A, F, E, C> MapErrNewService<A, F, E, C>
where
A: NewService,
F: Fn(A::Error) -> E,
A: NewService<C>,
F: Fn(A::Error) -> E + Clone,
{
/// Create new `MapErr` new service instance
pub fn new(a: A, f: F) -> Self {
Self {
a,
f,
e: marker::PhantomData,
e: PhantomData,
}
}
}
impl<A, F, E> Clone for MapErrNewService<A, F, E>
impl<A, F, E, C> Clone for MapErrNewService<A, F, E, C>
where
A: NewService + Clone,
A: NewService<C> + Clone,
F: Fn(A::Error) -> E + Clone,
{
fn clone(&self) -> Self {
Self {
a: self.a.clone(),
f: self.f.clone(),
e: marker::PhantomData,
e: PhantomData,
}
}
}
impl<A, F, E> NewService for MapErrNewService<A, F, E>
impl<A, F, E, C> NewService<C> for MapErrNewService<A, F, E, C>
where
A: NewService,
A: NewService<C>,
F: Fn(A::Error) -> E + Clone,
{
type Request = A::Request;
@@ -143,25 +148,25 @@ where
type Service = MapErr<A::Service, F, E>;
type InitError = A::InitError;
type Future = MapErrNewServiceFuture<A, F, E>;
type Future = MapErrNewServiceFuture<A, F, E, C>;
fn new_service(&self) -> Self::Future {
MapErrNewServiceFuture::new(self.a.new_service(), self.f.clone())
fn new_service(&self, cfg: &C) -> Self::Future {
MapErrNewServiceFuture::new(self.a.new_service(cfg), self.f.clone())
}
}
pub struct MapErrNewServiceFuture<A, F, E>
pub struct MapErrNewServiceFuture<A, F, E, C>
where
A: NewService,
A: NewService<C>,
F: Fn(A::Error) -> E,
{
fut: A::Future,
f: F,
}
impl<A, F, E> MapErrNewServiceFuture<A, F, E>
impl<A, F, E, C> MapErrNewServiceFuture<A, F, E, C>
where
A: NewService,
A: NewService<C>,
F: Fn(A::Error) -> E,
{
fn new(fut: A::Future, f: F) -> Self {
@@ -169,9 +174,9 @@ where
}
}
impl<A, F, E> Future for MapErrNewServiceFuture<A, F, E>
impl<A, F, E, C> Future for MapErrNewServiceFuture<A, F, E, C>
where
A: NewService,
A: NewService<C>,
F: Fn(A::Error) -> E + Clone,
{
type Item = MapErr<A::Service, F, E>;
@@ -191,7 +196,7 @@ mod tests {
use futures::future::{err, FutureResult};
use super::*;
use service::{IntoNewService, NewServiceExt, Service, ServiceExt};
use crate::{IntoNewService, NewService, Service, ServiceExt};
struct Srv;
@@ -230,7 +235,7 @@ mod tests {
fn test_new_service() {
let blank = || Ok::<_, ()>(Srv);
let new_srv = blank.into_new_service().map_err(|_| "error");
if let Async::Ready(mut srv) = new_srv.new_service().poll().unwrap() {
if let Async::Ready(mut srv) = new_srv.new_service(&()).poll().unwrap() {
let res = srv.call(()).poll();
assert!(res.is_err());
assert_eq!(res.err().unwrap(), "error");

View File

@@ -1,48 +1,48 @@
use std::marker;
use std::marker::PhantomData;
use futures::{Future, Poll};
use super::NewService;
/// `MapInitErr` service combinator
pub struct MapInitErr<A, F, E> {
pub struct MapInitErr<A, F, E, C> {
a: A,
f: F,
e: marker::PhantomData<E>,
e: PhantomData<(E, C)>,
}
impl<A, F, E> MapInitErr<A, F, E>
where
A: NewService,
F: Fn(A::InitError) -> E,
{
impl<A, F, E, C> MapInitErr<A, F, E, C> {
/// Create new `MapInitErr` combinator
pub fn new(a: A, f: F) -> Self {
pub fn new(a: A, f: F) -> Self
where
A: NewService<C>,
F: Fn(A::InitError) -> E,
{
Self {
a,
f,
e: marker::PhantomData,
e: PhantomData,
}
}
}
impl<A, F, E> Clone for MapInitErr<A, F, E>
impl<A, F, E, C> Clone for MapInitErr<A, F, E, C>
where
A: NewService + Clone,
F: Fn(A::InitError) -> E + Clone,
A: Clone,
F: Clone,
{
fn clone(&self) -> Self {
Self {
a: self.a.clone(),
f: self.f.clone(),
e: marker::PhantomData,
e: PhantomData,
}
}
}
impl<A, F, E> NewService for MapInitErr<A, F, E>
impl<A, F, E, C> NewService<C> for MapInitErr<A, F, E, C>
where
A: NewService,
A: NewService<C>,
F: Fn(A::InitError) -> E + Clone,
{
type Request = A::Request;
@@ -51,25 +51,25 @@ where
type Service = A::Service;
type InitError = E;
type Future = MapInitErrFuture<A, F, E>;
type Future = MapInitErrFuture<A, F, E, C>;
fn new_service(&self) -> Self::Future {
MapInitErrFuture::new(self.a.new_service(), self.f.clone())
fn new_service(&self, cfg: &C) -> Self::Future {
MapInitErrFuture::new(self.a.new_service(cfg), self.f.clone())
}
}
pub struct MapInitErrFuture<A, F, E>
pub struct MapInitErrFuture<A, F, E, C>
where
A: NewService,
A: NewService<C>,
F: Fn(A::InitError) -> E,
{
f: F,
fut: A::Future,
}
impl<A, F, E> MapInitErrFuture<A, F, E>
impl<A, F, E, C> MapInitErrFuture<A, F, E, C>
where
A: NewService,
A: NewService<C>,
F: Fn(A::InitError) -> E,
{
fn new(fut: A::Future, f: F) -> Self {
@@ -77,9 +77,9 @@ where
}
}
impl<A, F, E> Future for MapInitErrFuture<A, F, E>
impl<A, F, E, C> Future for MapInitErrFuture<A, F, E, C>
where
A: NewService,
A: NewService<C>,
F: Fn(A::InitError) -> E,
{
type Item = A::Service;

View File

@@ -1,7 +1,9 @@
use std::marker::PhantomData;
use futures::{Async, Future, Poll};
use super::{IntoNewService, NewService, Service};
use cell::Cell;
use crate::cell::Cell;
/// Service for the `then` combinator, chaining a computation onto the end of
/// another service.
@@ -12,21 +14,20 @@ pub struct Then<A, B> {
b: Cell<B>,
}
impl<A, B> Then<A, B>
where
A: Service,
B: Service<Request = Result<A::Response, A::Error>, Error = A::Error>,
{
impl<A, B> Then<A, B> {
/// Create new `Then` combinator
pub fn new(a: A, b: B) -> Then<A, B> {
pub fn new(a: A, b: B) -> Then<A, B>
where
A: Service,
B: Service<Request = Result<A::Response, A::Error>, Error = A::Error>,
{
Then { a, b: Cell::new(b) }
}
}
impl<A, B> Clone for Then<A, B>
where
A: Service + Clone,
B: Service<Request = Result<A::Response, A::Error>, Error = A::Error>,
A: Clone,
{
fn clone(&self) -> Self {
Then {
@@ -47,11 +48,15 @@ where
type Future = ThenFuture<A, B>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
let _ = try_ready!(self.a.poll_ready());
self.b.borrow_mut().poll_ready()
let not_ready = self.a.poll_ready()?.is_not_ready();
if self.b.get_mut().poll_ready()?.is_not_ready() || not_ready {
Ok(Async::NotReady)
} else {
Ok(Async::Ready(()))
}
}
fn call(&mut self, req: Self::Request) -> Self::Future {
fn call(&mut self, req: A::Request) -> Self::Future {
ThenFuture::new(self.a.call(req), self.b.clone())
}
}
@@ -93,15 +98,15 @@ where
return fut.poll();
}
match self.fut_a.as_mut().expect("actix-net bug").poll() {
match self.fut_a.as_mut().expect("bug in actix-service").poll() {
Ok(Async::Ready(resp)) => {
let _ = self.fut_a.take();
self.fut_b = Some(self.b.borrow_mut().call(Ok(resp)));
self.fut_b = Some(self.b.get_mut().call(Ok(resp)));
self.poll()
}
Err(err) => {
let _ = self.fut_a.take();
self.fut_b = Some(self.b.borrow_mut().call(Err(err)));
self.fut_b = Some(self.b.get_mut().call(Err(err)));
self.poll()
}
Ok(Async::NotReady) => Ok(Async::NotReady),
@@ -110,29 +115,38 @@ where
}
/// `ThenNewService` new service combinator
pub struct ThenNewService<A, B> {
pub struct ThenNewService<A, B, C> {
a: A,
b: B,
_t: PhantomData<C>,
}
impl<A, B> ThenNewService<A, B>
where
A: NewService,
B: NewService,
{
impl<A, B, C> ThenNewService<A, B, C> {
/// Create new `AndThen` combinator
pub fn new<F: IntoNewService<B>>(a: A, f: F) -> Self {
pub fn new<F>(a: A, f: F) -> Self
where
A: NewService<C>,
B: NewService<
C,
Request = Result<A::Response, A::Error>,
Error = A::Error,
InitError = A::InitError,
>,
F: IntoNewService<B, C>,
{
Self {
a,
b: f.into_new_service(),
_t: PhantomData,
}
}
}
impl<A, B> NewService for ThenNewService<A, B>
impl<A, B, C> NewService<C> for ThenNewService<A, B, C>
where
A: NewService,
A: NewService<C>,
B: NewService<
C,
Request = Result<A::Response, A::Error>,
Error = A::Error,
InitError = A::InitError,
@@ -144,34 +158,36 @@ where
type Service = Then<A::Service, B::Service>;
type InitError = A::InitError;
type Future = ThenNewServiceFuture<A, B>;
type Future = ThenNewServiceFuture<A, B, C>;
fn new_service(&self) -> Self::Future {
ThenNewServiceFuture::new(self.a.new_service(), self.b.new_service())
fn new_service(&self, cfg: &C) -> Self::Future {
ThenNewServiceFuture::new(self.a.new_service(cfg), self.b.new_service(cfg))
}
}
impl<A, B> Clone for ThenNewService<A, B>
impl<A, B, C> Clone for ThenNewService<A, B, C>
where
A: NewService + Clone,
B: NewService<
Request = Result<A::Response, A::Error>,
Error = A::Error,
InitError = A::InitError,
> + Clone,
A: Clone,
B: Clone,
{
fn clone(&self) -> Self {
Self {
a: self.a.clone(),
b: self.b.clone(),
_t: PhantomData,
}
}
}
pub struct ThenNewServiceFuture<A, B>
pub struct ThenNewServiceFuture<A, B, C>
where
A: NewService,
B: NewService,
A: NewService<C>,
B: NewService<
C,
Request = Result<A::Response, A::Error>,
Error = A::Error,
InitError = A::InitError,
>,
{
fut_b: B::Future,
fut_a: A::Future,
@@ -179,10 +195,15 @@ where
b: Option<B::Service>,
}
impl<A, B> ThenNewServiceFuture<A, B>
impl<A, B, C> ThenNewServiceFuture<A, B, C>
where
A: NewService,
B: NewService,
A: NewService<C>,
B: NewService<
C,
Request = Result<A::Response, A::Error>,
Error = A::Error,
InitError = A::InitError,
>,
{
fn new(fut_a: A::Future, fut_b: B::Future) -> Self {
ThenNewServiceFuture {
@@ -194,10 +215,11 @@ where
}
}
impl<A, B> Future for ThenNewServiceFuture<A, B>
impl<A, B, C> Future for ThenNewServiceFuture<A, B, C>
where
A: NewService,
A: NewService<C>,
B: NewService<
C,
Request = Result<A::Response, A::Error>,
Error = A::Error,
InitError = A::InitError,
@@ -233,12 +255,11 @@ where
#[cfg(test)]
mod tests {
use futures::future::{err, ok, FutureResult};
use futures::{Async, Poll};
use futures::{Async, Future, Poll};
use std::cell::Cell;
use std::rc::Rc;
use super::*;
use service::{NewServiceExt, ServiceExt};
use crate::{IntoNewService, NewService, Service, ServiceExt};
#[derive(Clone)]
struct Srv1(Rc<Cell<usize>>);
@@ -253,7 +274,7 @@ mod tests {
Ok(Async::Ready(()))
}
fn call(&mut self, req: Self::Request) -> Self::Future {
fn call(&mut self, req: Result<&'static str, &'static str>) -> Self::Future {
match req {
Ok(msg) => ok(msg),
Err(_) => err(()),
@@ -274,7 +295,7 @@ mod tests {
Ok(Async::Ready(()))
}
fn call(&mut self, req: Self::Request) -> Self::Future {
fn call(&mut self, req: Result<&'static str, ()>) -> Self::Future {
match req {
Ok(msg) => ok((msg, "ok")),
Err(()) => ok(("srv2", "err")),
@@ -312,7 +333,7 @@ mod tests {
let cnt2 = cnt.clone();
let blank = move || Ok::<_, ()>(Srv1(cnt2.clone()));
let new_srv = blank.into_new_service().then(move || Ok(Srv2(cnt.clone())));
if let Async::Ready(mut srv) = new_srv.clone().new_service().poll().unwrap() {
if let Async::Ready(mut srv) = new_srv.clone().new_service(&()).poll().unwrap() {
let res = srv.call(Ok("srv1")).poll();
assert!(res.is_ok());
assert_eq!(res.unwrap(), Async::Ready(("srv1", "ok")));

View File

@@ -0,0 +1,240 @@
use std::rc::Rc;
use std::sync::Arc;
use futures::{Async, Future, IntoFuture, Poll};
use crate::transform_err::{TransformFromErr, TransformMapInitErr};
use crate::{IntoNewService, NewService, Service};
/// The `Transform` trait defines the interface of a Service factory. `Transform`
/// is often implemented for middleware, defining how to manufacture a
/// middleware Service. A Service that is manufactured by the factory takes
/// the Service that follows it during execution as a parameter, assuming
/// ownership of the next Service. A Service can be a variety of types, such
/// as (but not limited to) another middleware Service, an extractor Service,
/// other helper Services, or the request handler endpoint Service.
///
/// A Service is created by the factory during server initialization.
///
/// `Config` is a service factory configuration type.
pub trait Transform<S> {
/// Requests handled by the service.
type Request;
/// Responses given by the service.
type Response;
/// Errors produced by the service.
type Error;
/// The `TransformService` value created by this factory
type Transform: Service<
Request = Self::Request,
Response = Self::Response,
Error = Self::Error,
>;
/// Errors produced while building a service.
type InitError;
/// The future response value.
type Future: Future<Item = Self::Transform, Error = Self::InitError>;
/// Creates and returns a new Service component, asynchronously
fn new_transform(&self, service: S) -> Self::Future;
/// Map this service's factory error to a different error,
/// returning a new transform service factory.
fn map_init_err<F, E>(self, f: F) -> TransformMapInitErr<Self, S, F, E>
where
Self: Sized,
F: Fn(Self::InitError) -> E,
{
TransformMapInitErr::new(self, f)
}
/// Map this service's init error to any error implementing `From` for
/// this service`s `Error`.
///
/// Note that this function consumes the receiving transform and returns a
/// wrapped version of it.
fn from_err<E>(self) -> TransformFromErr<Self, S, E>
where
Self: Sized,
E: From<Self::InitError>,
{
TransformFromErr::new(self)
}
// /// Map this service's init error to service's init error
// /// if it is implementing `Into` to this service`s `InitError`.
// ///
// /// Note that this function consumes the receiving transform and returns a
// /// wrapped version of it.
// fn into_err<E>(self) -> TransformIntoErr<Self, S>
// where
// Self: Sized,
// Self::InitError: From<Self::InitError>,
// {
// TransformFromErr::new(self)
// }
}
impl<T, S> Transform<S> for Rc<T>
where
T: Transform<S>,
{
type Request = T::Request;
type Response = T::Response;
type Error = T::Error;
type InitError = T::InitError;
type Transform = T::Transform;
type Future = T::Future;
fn new_transform(&self, service: S) -> T::Future {
self.as_ref().new_transform(service)
}
}
impl<T, S> Transform<S> for Arc<T>
where
T: Transform<S>,
{
type Request = T::Request;
type Response = T::Response;
type Error = T::Error;
type InitError = T::InitError;
type Transform = T::Transform;
type Future = T::Future;
fn new_transform(&self, service: S) -> T::Future {
self.as_ref().new_transform(service)
}
}
/// Trait for types that can be converted to a *transform service*
pub trait IntoTransform<T, S>
where
T: Transform<S>,
{
/// Convert to a `TransformService`
fn into_transform(self) -> T;
}
impl<T, S> IntoTransform<T, S> for T
where
T: Transform<S>,
{
fn into_transform(self) -> T {
self
}
}
/// Apply transform to service factory. Function returns
/// services factory that in initialization creates
/// service and applies transform to this service.
pub fn apply_transform<T, S, C, F, U>(
t: F,
service: U,
) -> impl NewService<
C,
Request = T::Request,
Response = T::Response,
Error = T::Error,
Service = T::Transform,
InitError = S::InitError,
> + Clone
where
S: NewService<C>,
T: Transform<S::Service, InitError = S::InitError>,
F: IntoTransform<T, S::Service>,
U: IntoNewService<S, C>,
{
ApplyTransform::new(t.into_transform(), service.into_new_service())
}
/// `Apply` transform to new service
pub struct ApplyTransform<T, S, C> {
s: Rc<S>,
t: Rc<T>,
_t: std::marker::PhantomData<C>,
}
impl<T, S, C> ApplyTransform<T, S, C>
where
S: NewService<C>,
T: Transform<S::Service, InitError = S::InitError>,
{
/// Create new `ApplyTransform` new service instance
pub fn new<F: IntoTransform<T, S::Service>>(t: F, service: S) -> Self {
Self {
s: Rc::new(service),
t: Rc::new(t.into_transform()),
_t: std::marker::PhantomData,
}
}
}
impl<T, S, C> Clone for ApplyTransform<T, S, C> {
fn clone(&self) -> Self {
ApplyTransform {
s: self.s.clone(),
t: self.t.clone(),
_t: std::marker::PhantomData,
}
}
}
impl<T, S, C> NewService<C> for ApplyTransform<T, S, C>
where
S: NewService<C>,
T: Transform<S::Service, InitError = S::InitError>,
{
type Request = T::Request;
type Response = T::Response;
type Error = T::Error;
type Service = T::Transform;
type InitError = T::InitError;
type Future = ApplyTransformFuture<T, S, C>;
fn new_service(&self, cfg: &C) -> Self::Future {
ApplyTransformFuture {
t_cell: self.t.clone(),
fut_a: self.s.new_service(cfg).into_future(),
fut_t: None,
}
}
}
pub struct ApplyTransformFuture<T, S, C>
where
S: NewService<C>,
T: Transform<S::Service, InitError = S::InitError>,
{
fut_a: S::Future,
fut_t: Option<<T::Future as IntoFuture>::Future>,
t_cell: Rc<T>,
}
impl<T, S, C> Future for ApplyTransformFuture<T, S, C>
where
S: NewService<C>,
T: Transform<S::Service, InitError = S::InitError>,
{
type Item = T::Transform;
type Error = T::InitError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
if self.fut_t.is_none() {
if let Async::Ready(service) = self.fut_a.poll()? {
self.fut_t = Some(self.t_cell.new_transform(service).into_future());
}
}
if let Some(ref mut fut) = self.fut_t {
fut.poll()
} else {
Ok(Async::NotReady)
}
}
}

View File

@@ -0,0 +1,162 @@
use std::marker::PhantomData;
use futures::{Future, Poll};
use super::Transform;
/// Transform for the `map_err` combinator, changing the type of a new
/// transform's init error.
///
/// This is created by the `Transform::map_err` method.
pub struct TransformMapInitErr<T, S, F, E> {
t: T,
f: F,
e: PhantomData<(S, E)>,
}
impl<T, S, F, E> TransformMapInitErr<T, S, F, E> {
/// Create new `TransformMapErr` new transform instance
pub fn new(t: T, f: F) -> Self
where
T: Transform<S>,
F: Fn(T::InitError) -> E,
{
Self {
t,
f,
e: PhantomData,
}
}
}
impl<T, S, F, E> Clone for TransformMapInitErr<T, S, F, E>
where
T: Clone,
F: Clone,
{
fn clone(&self) -> Self {
Self {
t: self.t.clone(),
f: self.f.clone(),
e: PhantomData,
}
}
}
impl<T, S, F, E> Transform<S> for TransformMapInitErr<T, S, F, E>
where
T: Transform<S>,
F: Fn(T::InitError) -> E + Clone,
{
type Request = T::Request;
type Response = T::Response;
type Error = T::Error;
type Transform = T::Transform;
type InitError = E;
type Future = TransformMapInitErrFuture<T, S, F, E>;
fn new_transform(&self, service: S) -> Self::Future {
TransformMapInitErrFuture {
fut: self.t.new_transform(service),
f: self.f.clone(),
}
}
}
pub struct TransformMapInitErrFuture<T, S, F, E>
where
T: Transform<S>,
F: Fn(T::InitError) -> E,
{
fut: T::Future,
f: F,
}
impl<T, S, F, E> Future for TransformMapInitErrFuture<T, S, F, E>
where
T: Transform<S>,
F: Fn(T::InitError) -> E + Clone,
{
type Item = T::Transform;
type Error = E;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
self.fut.poll().map_err(&self.f)
}
}
/// Transform for the `from_err` combinator, changing the type of a new
/// transform's init error.
///
/// This is created by the `Transform::from_err` method.
pub struct TransformFromErr<T, S, E> {
t: T,
e: PhantomData<(S, E)>,
}
impl<T, S, E> TransformFromErr<T, S, E>
where
T: Transform<S>,
E: From<T::InitError>,
{
/// Create new `TransformFromErr` new transform instance
pub fn new(t: T) -> Self {
Self { t, e: PhantomData }
}
}
impl<T, S, E> Clone for TransformFromErr<T, S, E>
where
T: Clone,
{
fn clone(&self) -> Self {
Self {
t: self.t.clone(),
e: PhantomData,
}
}
}
impl<T, S, E> Transform<S> for TransformFromErr<T, S, E>
where
T: Transform<S>,
E: From<T::InitError>,
{
type Request = T::Request;
type Response = T::Response;
type Error = T::Error;
type Transform = T::Transform;
type InitError = E;
type Future = TransformFromErrFuture<T, S, E>;
fn new_transform(&self, service: S) -> Self::Future {
TransformFromErrFuture {
fut: self.t.new_transform(service),
_t: PhantomData,
}
}
}
pub struct TransformFromErrFuture<T, S, E>
where
T: Transform<S>,
E: From<T::InitError>,
{
fut: T::Future,
_t: PhantomData<E>,
}
impl<T, S, E> Future for TransformFromErrFuture<T, S, E>
where
T: Transform<S>,
E: From<T::InitError>,
{
type Item = T::Transform;
type Error = E;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
self.fut.poll().map_err(E::from)
}
}

View File

@@ -0,0 +1,59 @@
[package]
name = "actix-test-server"
version = "0.2.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix test server"
keywords = ["network", "framework", "async", "futures"]
homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-net.git"
documentation = "https://docs.rs/actix-test-server/"
categories = ["network-programming", "asynchronous"]
license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
edition = "2018"
workspace = "../"
[package.metadata.docs.rs]
features = ["ssl", "tls", "rust-tls"]
[lib]
name = "actix_test_server"
path = "src/lib.rs"
[features]
default = []
# tls
tls = ["native-tls", "actix-server/tls"]
# openssl
ssl = ["openssl", "actix-server/ssl"]
# rustls
rust-tls = ["rustls", "tokio-rustls", "webpki", "webpki-roots"]
[dependencies]
actix-rt = "0.2.1"
actix-server = "0.4.0"
actix-server-config = "0.1.0"
log = "0.4"
net2 = "0.2"
futures = "0.1"
tokio-tcp = "0.1"
tokio-reactor = "0.1"
# native-tls
native-tls = { version="0.2", optional = true }
# openssl
openssl = { version="0.10", optional = true }
#rustls
rustls = { version = "^0.15", optional = true }
tokio-rustls = { version = "^0.9", optional = true }
webpki = { version = "0.19", optional = true }
webpki-roots = { version = "0.16", optional = true }
[dev-dependencies]
actix-service = "0.3.4"

View File

@@ -0,0 +1,140 @@
//! Various helpers for Actix applications to use during testing.
use std::sync::mpsc;
use std::{net, thread};
use actix_rt::{Runtime, System};
use actix_server::{Server, StreamServiceFactory};
pub use actix_server_config::{Io, ServerConfig};
use futures::Future;
use net2::TcpBuilder;
use tokio_reactor::Handle;
use tokio_tcp::TcpStream;
/// The `TestServer` type.
///
/// `TestServer` is very simple test server that simplify process of writing
/// integration tests for actix-net applications.
///
/// # Examples
///
/// ```rust
/// use actix_service::{fn_service, IntoNewService};
/// use actix_test_server::TestServer;
///
/// fn main() {
/// let srv = TestServer::with(|| fn_service(
/// |sock| {
/// println!("New connection: {:?}", sock);
/// Ok::<_, ()>(())
/// }
/// ));
///
/// println!("SOCKET: {:?}", srv.connect());
/// }
/// ```
pub struct TestServer;
/// Test server runstime
pub struct TestServerRuntime {
addr: net::SocketAddr,
host: String,
port: u16,
rt: Runtime,
}
impl TestServer {
/// Start new test server with application factory
pub fn with<F: StreamServiceFactory>(factory: F) -> TestServerRuntime {
let (tx, rx) = mpsc::channel();
// run server in separate thread
thread::spawn(move || {
let sys = System::new("actix-test-server");
let tcp = net::TcpListener::bind("127.0.0.1:0").unwrap();
let local_addr = tcp.local_addr().unwrap();
Server::build()
.listen("test", tcp, factory)?
.workers(1)
.disable_signals()
.start();
tx.send((System::current(), local_addr)).unwrap();
sys.run()
});
let (system, addr) = rx.recv().unwrap();
System::set_current(system);
let rt = Runtime::new().unwrap();
let host = format!("{}", addr.ip());
let port = addr.port();
TestServerRuntime {
addr,
rt,
host,
port,
}
}
/// Get firat available unused local address
pub fn unused_addr() -> net::SocketAddr {
let addr: net::SocketAddr = "127.0.0.1:0".parse().unwrap();
let socket = TcpBuilder::new_v4().unwrap();
socket.bind(&addr).unwrap();
socket.reuse_address(true).unwrap();
let tcp = socket.to_tcp_listener().unwrap();
tcp.local_addr().unwrap()
}
}
impl TestServerRuntime {
/// Execute future on current runtime
pub fn block_on<F, I, E>(&mut self, fut: F) -> Result<I, E>
where
F: Future<Item = I, Error = E>,
{
self.rt.block_on(fut)
}
/// Spawn future to the current runtime
pub fn spawn<F>(&mut self, fut: F)
where
F: Future<Item = (), Error = ()> + 'static,
{
self.rt.spawn(fut);
}
/// Test server host
pub fn host(&self) -> &str {
&self.host
}
/// Test server port
pub fn port(&self) -> u16 {
self.port
}
/// Get test server address
pub fn addr(&self) -> net::SocketAddr {
self.addr
}
/// Stop http server
fn stop(&mut self) {
System::current().stop();
}
/// Connect to server, return tokio TcpStream
pub fn connect(&self) -> std::io::Result<TcpStream> {
TcpStream::from_std(net::TcpStream::connect(self.addr)?, &Handle::default())
}
}
impl Drop for TestServerRuntime {
fn drop(&mut self) {
self.stop()
}
}

View File

@@ -0,0 +1,5 @@
# Changes
## [0.1.0] - 2019-03-28
* Move threadpool to separate crate

View File

@@ -0,0 +1,27 @@
[package]
name = "actix-threadpool"
version = "0.1.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix thread pool for sync code"
keywords = ["actix", "network", "framework", "async", "futures"]
homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-net.git"
documentation = "https://docs.rs/actix-threadpool/"
categories = ["network-programming", "asynchronous"]
license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
edition = "2018"
workspace = ".."
[lib]
name = "actix_threadpool"
path = "src/lib.rs"
[dependencies]
derive_more = "0.14"
futures = "0.1.25"
parking_lot = "0.7"
lazy_static = "1.2"
log = "0.4"
num_cpus = "1.10"
threadpool = "1.7"

View File

@@ -0,0 +1,88 @@
//! Thread pool for blocking operations
use std::fmt;
use derive_more::Display;
use futures::sync::oneshot;
use futures::{Async, Future, Poll};
use parking_lot::Mutex;
use threadpool::ThreadPool;
/// Env variable for default cpu pool size
const ENV_CPU_POOL_VAR: &str = "ACTIX_THREADPOOL";
lazy_static::lazy_static! {
pub(crate) static ref DEFAULT_POOL: Mutex<ThreadPool> = {
let default = match std::env::var(ENV_CPU_POOL_VAR) {
Ok(val) => {
if let Ok(val) = val.parse() {
val
} else {
log::error!("Can not parse ACTIX_THREADPOOL value");
num_cpus::get() * 5
}
}
Err(_) => num_cpus::get() * 5,
};
Mutex::new(
threadpool::Builder::new()
.thread_name("actix-web".to_owned())
.num_threads(default)
.build(),
)
};
}
thread_local! {
static POOL: ThreadPool = {
DEFAULT_POOL.lock().clone()
};
}
/// Blocking operation execution error
#[derive(Debug, Display)]
pub enum BlockingError<E: fmt::Debug> {
#[display(fmt = "{:?}", _0)]
Error(E),
#[display(fmt = "Thread pool is gone")]
Canceled,
}
/// Execute blocking function on a thread pool, returns future that resolves
/// to result of the function execution.
pub fn run<F, I, E>(f: F) -> CpuFuture<I, E>
where
F: FnOnce() -> Result<I, E> + Send + 'static,
I: Send + 'static,
E: Send + fmt::Debug + 'static,
{
let (tx, rx) = oneshot::channel();
POOL.with(|pool| {
pool.execute(move || {
if !tx.is_canceled() {
let _ = tx.send(f());
}
})
});
CpuFuture { rx }
}
/// Blocking operation completion future. It resolves with results
/// of blocking function execution.
pub struct CpuFuture<I, E> {
rx: oneshot::Receiver<Result<I, E>>,
}
impl<I, E: fmt::Debug> Future for CpuFuture<I, E> {
type Item = I;
type Error = BlockingError<E>;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
let res = futures::try_ready!(self.rx.poll().map_err(|_| BlockingError::Canceled));
match res {
Ok(val) => Ok(Async::Ready(val)),
Err(err) => Err(BlockingError::Error(err)),
}
}
}

110
actix-utils/CHANGES.md Normal file
View File

@@ -0,0 +1,110 @@
# Changes
## [0.3.5] - 2019-04-04
### Added
* Allow to send messages to `FramedTransport` via mpsc channel.
### Changed
* Remove 'static constraint from Clonable service
## [0.3.4] - 2019-03-12
### Changed
* `TimeoutService`, `InOrderService`, `InFlightService` accepts generic IntoService services.
### Fixed
* Fix `InFlightService::poll_ready()` nested service readiness check
* Fix `InOrderService::poll_ready()` nested service readiness check
## [0.3.3] - 2019-03-09
### Changed
* Revert IntoFuture change
* Add generic config param for IntoFramed and TakeOne new services
## [0.3.2] - 2019-03-04
### Changed
* Use IntoFuture for new services
## [0.3.1] - 2019-03-04
### Changed
* Use new type of transform trait
## [0.3.0] - 2019-03-02
### Changed
* Use new `NewService` trait
* BoxedNewService` and `BoxedService` types moved to actix-service crate.
## [0.2.4] - 2019-02-21
### Changed
* Custom `BoxedNewService` implementation.
## [0.2.3] - 2019-02-21
### Added
* Add `BoxedNewService` and `BoxedService`
## [0.2.2] - 2019-02-11
### Added
* Add `Display` impl for `TimeoutError`
* Add `Display` impl for `InOrderError`
## [0.2.1] - 2019-02-06
### Added
* Add `InOrder` service. the service yields responses as they become available,
in the order that their originating requests were submitted to the service.
### Changed
* Convert `Timeout` and `InFlight` services to a transforms
## [0.2.0] - 2019-02-01
* Fix framed transport error handling
* Added Clone impl for Either service
* Added Clone impl for Timeout service factory
* Added Service and NewService for Stream dispatcher
* Switch to actix-service 0.2
## [0.1.0] - 2018-12-09
* Move utils services to separate crate

30
actix-utils/Cargo.toml Normal file
View File

@@ -0,0 +1,30 @@
[package]
name = "actix-utils"
version = "0.3.5"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix utils - various actix net related services"
keywords = ["network", "framework", "async", "futures"]
homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-net.git"
documentation = "https://docs.rs/actix-utils/"
categories = ["network-programming", "asynchronous"]
license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
edition = "2018"
workspace = ".."
[lib]
name = "actix_utils"
path = "src/lib.rs"
[dependencies]
actix-service = "0.3.3"
actix-codec = "0.1.1"
bytes = "0.4"
futures = "0.1.24"
tokio-timer = "0.2.8"
tokio-current-thread = "0.1.4"
log = "0.4"
[dev-dependencies]
actix-rt = "0.2.1"

39
actix-utils/src/cell.rs Normal file
View File

@@ -0,0 +1,39 @@
//! Custom cell impl
use std::cell::UnsafeCell;
use std::fmt;
use std::rc::Rc;
pub(crate) struct Cell<T> {
inner: Rc<UnsafeCell<T>>,
}
impl<T> Clone for Cell<T> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
}
}
}
impl<T: fmt::Debug> fmt::Debug for Cell<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.inner.fmt(f)
}
}
impl<T> Cell<T> {
pub fn new(inner: T) -> Self {
Self {
inner: Rc::new(UnsafeCell::new(inner)),
}
}
pub fn get_ref(&self) -> &T {
unsafe { &*self.inner.as_ref().get() }
}
pub fn get_mut(&mut self) -> &mut T {
unsafe { &mut *self.inner.as_ref().get() }
}
}

View File

@@ -0,0 +1,52 @@
use std::marker::PhantomData;
use std::rc::Rc;
use actix_service::Service;
use futures::Poll;
use super::cell::Cell;
/// Service that allows to turn non-clone service to a service with `Clone` impl
pub struct CloneableService<T> {
service: Cell<T>,
_t: PhantomData<Rc<()>>,
}
impl<T> CloneableService<T> {
pub fn new(service: T) -> Self
where
T: Service,
{
Self {
service: Cell::new(service),
_t: PhantomData,
}
}
}
impl<T> Clone for CloneableService<T> {
fn clone(&self) -> Self {
Self {
service: self.service.clone(),
_t: PhantomData,
}
}
}
impl<T> Service for CloneableService<T>
where
T: Service,
{
type Request = T::Request;
type Response = T::Response;
type Error = T::Error;
type Future = T::Future;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.service.get_mut().poll_ready()
}
fn call(&mut self, req: T::Request) -> Self::Future {
self.service.get_mut().call(req)
}
}

View File

@@ -0,0 +1,78 @@
use std::cell::Cell;
use std::rc::Rc;
use futures::task::AtomicTask;
#[derive(Clone)]
/// Simple counter with ability to notify task on reaching specific number
///
/// Counter could be cloned, total ncount is shared across all clones.
pub struct Counter(Rc<CounterInner>);
struct CounterInner {
count: Cell<usize>,
capacity: usize,
task: AtomicTask,
}
impl Counter {
/// Create `Counter` instance and set max value.
pub fn new(capacity: usize) -> Self {
Counter(Rc::new(CounterInner {
capacity,
count: Cell::new(0),
task: AtomicTask::new(),
}))
}
pub fn get(&self) -> CounterGuard {
CounterGuard::new(self.0.clone())
}
/// Check if counter is not at capacity
pub fn available(&self) -> bool {
self.0.available()
}
/// Get total number of acquired counts
pub fn total(&self) -> usize {
self.0.count.get()
}
}
pub struct CounterGuard(Rc<CounterInner>);
impl CounterGuard {
fn new(inner: Rc<CounterInner>) -> Self {
inner.inc();
CounterGuard(inner)
}
}
impl Drop for CounterGuard {
fn drop(&mut self) {
self.0.dec();
}
}
impl CounterInner {
fn inc(&self) {
let num = self.count.get() + 1;
self.count.set(num);
if num == self.capacity {
self.task.register();
}
}
fn dec(&self) {
let num = self.count.get();
self.count.set(num - 1);
if num == self.capacity {
self.task.notify();
}
}
fn available(&self) -> bool {
self.count.get() < self.capacity
}
}

View File

@@ -1,7 +1,6 @@
//! Contains `Either` service and related types and functions.
use futures::{future, Async, Future, Poll};
use super::service::{NewService, Service};
use actix_service::{NewService, Service};
use futures::{future, try_ready, Async, Future, IntoFuture, Poll};
/// Combine two different service types into a single type.
///
@@ -13,6 +12,15 @@ pub enum EitherService<A, B> {
B(B),
}
impl<A: Clone, B: Clone> Clone for EitherService<A, B> {
fn clone(&self) -> Self {
match self {
EitherService::A(srv) => EitherService::A(srv.clone()),
EitherService::B(srv) => EitherService::B(srv.clone()),
}
}
}
impl<A, B> Service for EitherService<A, B>
where
A: Service,
@@ -30,7 +38,7 @@ where
}
}
fn call(&mut self, req: Self::Request) -> Self::Future {
fn call(&mut self, req: A::Request) -> Self::Future {
match self {
EitherService::A(ref mut inner) => future::Either::A(inner.call(req)),
EitherService::B(ref mut inner) => future::Either::B(inner.call(req)),
@@ -44,10 +52,41 @@ pub enum Either<A, B> {
B(B),
}
impl<A, B> NewService for Either<A, B>
impl<A, B> Either<A, B> {
pub fn new_a<C>(srv: A) -> Self
where
A: NewService<C>,
B: NewService<
C,
Request = A::Request,
Response = A::Response,
Error = A::Error,
InitError = A::InitError,
>,
{
Either::A(srv)
}
pub fn new_b<C>(srv: B) -> Self
where
A: NewService<C>,
B: NewService<
C,
Request = A::Request,
Response = A::Response,
Error = A::Error,
InitError = A::InitError,
>,
{
Either::B(srv)
}
}
impl<A, B, C> NewService<C> for Either<A, B>
where
A: NewService,
A: NewService<C>,
B: NewService<
C,
Request = A::Request,
Response = A::Response,
Error = A::Error,
@@ -59,26 +98,36 @@ where
type Error = A::Error;
type InitError = A::InitError;
type Service = EitherService<A::Service, B::Service>;
type Future = EitherNewService<A, B>;
type Future = EitherNewService<A, B, C>;
fn new_service(&self) -> Self::Future {
fn new_service(&self, cfg: &C) -> Self::Future {
match self {
Either::A(ref inner) => EitherNewService::A(inner.new_service()),
Either::B(ref inner) => EitherNewService::B(inner.new_service()),
Either::A(ref inner) => EitherNewService::A(inner.new_service(cfg)),
Either::B(ref inner) => EitherNewService::B(inner.new_service(cfg)),
}
}
}
impl<A: Clone, B: Clone> Clone for Either<A, B> {
fn clone(&self) -> Self {
match self {
Either::A(srv) => Either::A(srv.clone()),
Either::B(srv) => Either::B(srv.clone()),
}
}
}
#[doc(hidden)]
pub enum EitherNewService<A: NewService, B: NewService> {
A(A::Future),
B(B::Future),
pub enum EitherNewService<A: NewService<C>, B: NewService<C>, C> {
A(<A::Future as IntoFuture>::Future),
B(<B::Future as IntoFuture>::Future),
}
impl<A, B> Future for EitherNewService<A, B>
impl<A, B, C> Future for EitherNewService<A, B, C>
where
A: NewService,
A: NewService<C>,
B: NewService<
C,
Request = A::Request,
Response = A::Response,
Error = A::Error,

View File

@@ -1,36 +1,38 @@
//! Framed dispatcher service and related utilities
use std::collections::VecDeque;
use std::marker::PhantomData;
use std::mem;
use actix;
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
use actix_service::{IntoNewService, IntoService, NewService, Service};
use futures::future::{ok, FutureResult};
use futures::task::AtomicTask;
use futures::unsync::mpsc;
use futures::{Async, AsyncSink, Future, Poll, Sink, Stream};
use tokio_codec::{Decoder, Encoder};
use tokio_io::{AsyncRead, AsyncWrite};
use futures::{Async, Future, IntoFuture, Poll, Sink, Stream};
use log::debug;
use codec::Framed;
use service::{IntoNewService, IntoService, NewService, Service};
use crate::cell::Cell;
type Request<U> = <U as Decoder>::Item;
type Response<U> = <U as Encoder>::Item;
pub struct FramedNewService<S, T, U> {
pub struct FramedNewService<S, T, U, C> {
factory: S,
_t: PhantomData<(T, U)>,
_t: PhantomData<(T, U, C)>,
}
impl<S, T, U> FramedNewService<S, T, U>
impl<S, T, U, C> FramedNewService<S, T, U, C>
where
C: Clone,
S: NewService<C, Request = Request<U>, Response = Response<U>>,
S::Error: 'static,
<S::Service as Service>::Future: 'static,
T: AsyncRead + AsyncWrite,
U: Decoder + Encoder,
S: NewService<Request = Request<U>, Response = Response<U>> + Clone,
<<S as NewService>::Service as Service>::Future: 'static,
<<S as NewService>::Service as Service>::Error: 'static,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: 'static,
<U as Encoder>::Error: std::fmt::Debug,
{
pub fn new<F1: IntoNewService<S>>(factory: F1) -> Self {
pub fn new<F1: IntoNewService<S, C>>(factory: F1) -> Self {
Self {
factory: factory.into_new_service(),
_t: PhantomData,
@@ -38,7 +40,7 @@ where
}
}
impl<S, T, U> Clone for FramedNewService<S, T, U>
impl<S, T, U, C> Clone for FramedNewService<S, T, U, C>
where
S: Clone,
{
@@ -50,100 +52,105 @@ where
}
}
impl<S, T, U> NewService for FramedNewService<S, T, U>
impl<S, T, U, C> NewService<C> for FramedNewService<S, T, U, C>
where
C: Clone,
S: NewService<C, Request = Request<U>, Response = Response<U>> + Clone,
S::Error: 'static,
<S::Service as Service>::Future: 'static,
T: AsyncRead + AsyncWrite,
U: Decoder + Encoder,
S: NewService<Request = Request<U>, Response = Response<U>> + Clone,
<<S as NewService>::Service as Service>::Future: 'static,
<<S as NewService>::Service as Service>::Error: 'static,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: 'static,
<U as Encoder>::Error: std::fmt::Debug,
{
type Request = Framed<T, U>;
type Response = FramedTransport<S::Service, T, U>;
type Error = S::InitError;
type InitError = S::InitError;
type Service = FramedService<S, T, U>;
type Service = FramedService<S, T, U, C>;
type Future = FutureResult<Self::Service, Self::InitError>;
fn new_service(&self) -> Self::Future {
fn new_service(&self, cfg: &C) -> Self::Future {
ok(FramedService {
factory: self.factory.clone(),
config: cfg.clone(),
_t: PhantomData,
})
}
}
pub struct FramedService<S, T, U> {
pub struct FramedService<S, T, U, C> {
factory: S,
config: C,
_t: PhantomData<(T, U)>,
}
impl<S, T, U> Clone for FramedService<S, T, U>
impl<S, T, U, C> Clone for FramedService<S, T, U, C>
where
S: Clone,
C: Clone,
{
fn clone(&self) -> Self {
Self {
factory: self.factory.clone(),
config: self.config.clone(),
_t: PhantomData,
}
}
}
impl<S, T, U> Service for FramedService<S, T, U>
impl<S, T, U, C> Service for FramedService<S, T, U, C>
where
S: NewService<C, Request = Request<U>, Response = Response<U>>,
S::Error: 'static,
<S::Service as Service>::Future: 'static,
T: AsyncRead + AsyncWrite,
U: Decoder + Encoder,
S: NewService<Request = Request<U>, Response = Response<U>>,
<<S as NewService>::Service as Service>::Future: 'static,
<<S as NewService>::Service as Service>::Error: 'static,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: 'static,
<U as Encoder>::Error: std::fmt::Debug,
C: Clone,
{
type Request = Framed<T, U>;
type Response = FramedTransport<S::Service, T, U>;
type Error = S::InitError;
type Future = FramedServiceResponseFuture<S, T, U>;
type Future = FramedServiceResponseFuture<S, T, U, C>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
fn call(&mut self, req: Self::Request) -> Self::Future {
fn call(&mut self, req: Framed<T, U>) -> Self::Future {
FramedServiceResponseFuture {
fut: self.factory.new_service(),
fut: self.factory.new_service(&self.config),
framed: Some(req),
}
}
}
#[doc(hidden)]
pub struct FramedServiceResponseFuture<S, T, U>
pub struct FramedServiceResponseFuture<S, T, U, C>
where
S: NewService<C, Request = Request<U>, Response = Response<U>>,
S::Error: 'static,
<S::Service as Service>::Future: 'static,
T: AsyncRead + AsyncWrite,
U: Decoder + Encoder,
S: NewService<Request = Request<U>, Response = Response<U>>,
<<S as NewService>::Service as Service>::Future: 'static,
<<S as NewService>::Service as Service>::Error: 'static,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: 'static,
<U as Encoder>::Error: std::fmt::Debug,
{
fut: S::Future,
fut: <S::Future as IntoFuture>::Future,
framed: Option<Framed<T, U>>,
}
impl<S, T, U> Future for FramedServiceResponseFuture<S, T, U>
impl<S, T, U, C> Future for FramedServiceResponseFuture<S, T, U, C>
where
S: NewService<C, Request = Request<U>, Response = Response<U>>,
S::Error: 'static,
<S::Service as Service>::Future: 'static,
T: AsyncRead + AsyncWrite,
U: Decoder + Encoder,
S: NewService<Request = Request<U>, Response = Response<U>>,
<<S as NewService>::Service as Service>::Future: 'static,
<<S as NewService>::Service as Service>::Error: 'static,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: 'static,
<U as Encoder>::Error: std::fmt::Debug,
{
type Item = FramedTransport<S::Service, T, U>;
type Error = S::InitError;
@@ -172,54 +179,196 @@ impl<E, U: Encoder + Decoder> From<E> for FramedTransportError<E, U> {
}
}
pub enum FramedMessage<T> {
Message(T),
Close,
}
/// FramedTransport - is a future that reads frames from Framed object
/// and pass then to the service.
pub struct FramedTransport<S, T, U>
where
S: Service,
S: Service<Request = Request<U>, Response = Response<U>>,
S::Error: 'static,
S::Future: 'static,
T: AsyncRead + AsyncWrite,
U: Encoder + Decoder,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: std::fmt::Debug,
{
service: S,
state: TransportState<S, U>,
framed: Framed<T, U>,
request: Option<Request<U>>,
response: Option<Response<U>>,
write_rx: mpsc::Receiver<Result<Response<U>, S::Error>>,
write_tx: mpsc::Sender<Result<Response<U>, S::Error>>,
flushed: bool,
rx: Option<mpsc::UnboundedReceiver<FramedMessage<<U as Encoder>::Item>>>,
inner: Cell<FramedTransportInner<<U as Encoder>::Item, S::Error>>,
}
enum TransportState<S: Service, U: Encoder + Decoder> {
Processing,
Error(FramedTransportError<S::Error, U>),
EncoderError(FramedTransportError<S::Error, U>),
FramedError(FramedTransportError<S::Error, U>),
FlushAndStop,
Stopping,
}
struct FramedTransportInner<I, E> {
buf: VecDeque<Result<I, E>>,
task: AtomicTask,
}
impl<S, T, U> FramedTransport<S, T, U>
where
S: Service<Request = Request<U>, Response = Response<U>>,
S::Error: 'static,
S::Future: 'static,
T: AsyncRead + AsyncWrite,
U: Decoder + Encoder,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: std::fmt::Debug,
{
fn poll_read(&mut self) -> bool {
loop {
match self.service.poll_ready() {
Ok(Async::Ready(_)) => {
let item = match self.framed.poll() {
Ok(Async::Ready(Some(el))) => el,
Err(err) => {
self.state =
TransportState::FramedError(FramedTransportError::Decoder(err));
return true;
}
Ok(Async::NotReady) => return false,
Ok(Async::Ready(None)) => {
self.state = TransportState::Stopping;
return true;
}
};
let mut cell = self.inner.clone();
cell.get_mut().task.register();
tokio_current_thread::spawn(self.service.call(item).then(move |item| {
let inner = cell.get_mut();
inner.buf.push_back(item);
inner.task.notify();
Ok(())
}));
}
Ok(Async::NotReady) => return false,
Err(err) => {
self.state = TransportState::Error(FramedTransportError::Service(err));
return true;
}
}
}
}
/// write to framed object
fn poll_write(&mut self) -> bool {
let inner = self.inner.get_mut();
let mut rx_done = self.rx.is_none();
let mut buf_empty = inner.buf.is_empty();
loop {
while !self.framed.is_write_buf_full() {
if !buf_empty {
match inner.buf.pop_front().unwrap() {
Ok(msg) => {
if let Err(err) = self.framed.force_send(msg) {
self.state = TransportState::FramedError(
FramedTransportError::Encoder(err),
);
return true;
}
buf_empty = inner.buf.is_empty();
}
Err(err) => {
self.state =
TransportState::Error(FramedTransportError::Service(err));
return true;
}
}
}
if !rx_done && self.rx.is_some() {
match self.rx.as_mut().unwrap().poll() {
Ok(Async::Ready(Some(FramedMessage::Message(msg)))) => {
if let Err(err) = self.framed.force_send(msg) {
self.state = TransportState::FramedError(
FramedTransportError::Encoder(err),
);
return true;
}
}
Ok(Async::Ready(Some(FramedMessage::Close))) => {
self.state = TransportState::FlushAndStop;
return true;
}
Ok(Async::Ready(None)) => {
let _ = self.rx.take();
}
Ok(Async::NotReady) => rx_done = true,
Err(_e) => {
let _ = self.rx.take();
}
}
}
if rx_done && buf_empty {
break;
}
}
if !self.framed.is_write_buf_empty() {
match self.framed.poll_complete() {
Ok(Async::NotReady) => break,
Err(err) => {
debug!("Error sending data: {:?}", err);
self.state =
TransportState::FramedError(FramedTransportError::Encoder(err));
return true;
}
Ok(Async::Ready(_)) => (),
}
} else {
break;
}
}
false
}
}
impl<S, T, U> FramedTransport<S, T, U>
where
S: Service<Request = Request<U>, Response = Response<U>>,
S::Future: 'static,
S::Error: 'static,
<U as Encoder>::Error: 'static,
S::Future: 'static,
T: AsyncRead + AsyncWrite,
U: Decoder + Encoder,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: std::fmt::Debug,
{
pub fn new<F: IntoService<S>>(framed: Framed<T, U>, service: F) -> Self {
let (write_tx, write_rx) = mpsc::channel(16);
FramedTransport {
framed,
write_rx,
write_tx,
rx: None,
service: service.into_service(),
state: TransportState::Processing,
request: None,
response: None,
flushed: true,
inner: Cell::new(FramedTransportInner {
buf: VecDeque::new(),
task: AtomicTask::new(),
}),
}
}
/// Get Sender
pub fn set_receiver(
mut self,
rx: mpsc::UnboundedReceiver<FramedMessage<<U as Encoder>::Item>>,
) -> Self {
self.rx = Some(rx);
self
}
/// Get reference to a service wrapped by `FramedTransport` instance.
pub fn get_ref(&self) -> &S {
&self.service
@@ -244,144 +393,15 @@ where
}
}
impl<S, T, U> FramedTransport<S, T, U>
where
T: AsyncRead + AsyncWrite,
U: Decoder + Encoder,
S: Service<Request = Request<U>, Response = Response<U>>,
S::Future: 'static,
S::Error: 'static,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: 'static,
{
fn poll_service(&mut self) -> bool {
match self.service.poll_ready() {
Ok(Async::Ready(_)) => {
if let Some(item) = self.request.take() {
let sender = self.write_tx.clone();
actix::Arbiter::spawn(
self.service
.call(item)
.then(|item| sender.send(item).map(|_| ()).map_err(|_| ())),
);
}
loop {
let item = match self.framed.poll() {
Ok(Async::Ready(Some(el))) => el,
Err(err) => {
self.state =
TransportState::Error(FramedTransportError::Decoder(err));
return true;
}
Ok(Async::NotReady) => return false,
Ok(Async::Ready(None)) => {
self.state = TransportState::Stopping;
return true;
}
};
match self.service.poll_ready() {
Ok(Async::Ready(_)) => {
let sender = self.write_tx.clone();
actix::Arbiter::spawn(
self.service
.call(item)
.then(|item| sender.send(item).map(|_| ()).map_err(|_| ())),
);
}
Ok(Async::NotReady) => {
self.request = Some(item);
return false;
}
Err(err) => {
self.state =
TransportState::Error(FramedTransportError::Service(err));
return true;
}
}
}
}
Ok(Async::NotReady) => return false,
Err(err) => {
self.state = TransportState::Error(FramedTransportError::Service(err));
return true;
}
}
}
/// write to sink
fn poll_response(&mut self) -> bool {
let mut item = self.response.take();
loop {
item = if let Some(msg) = item {
self.flushed = false;
match self.framed.start_send(msg) {
Ok(AsyncSink::Ready) => None,
Ok(AsyncSink::NotReady(item)) => Some(item),
Err(err) => {
self.state =
TransportState::EncoderError(FramedTransportError::Encoder(err));
return true;
}
}
} else {
None
};
// flush sink
if !self.flushed {
match self.framed.poll_complete() {
Ok(Async::Ready(_)) => {
self.flushed = true;
}
Ok(Async::NotReady) => break,
Err(err) => {
self.state =
TransportState::EncoderError(FramedTransportError::Encoder(err));
return true;
}
}
}
// check channel
if self.flushed {
if item.is_none() {
match self.write_rx.poll() {
Ok(Async::Ready(Some(msg))) => match msg {
Ok(msg) => item = Some(msg),
Err(err) => {
self.state =
TransportState::Error(FramedTransportError::Service(err));
return true;
}
},
Ok(Async::NotReady) => break,
Err(_) => panic!("Bug in gw code"),
Ok(Async::Ready(None)) => panic!("Bug in gw code"),
}
} else {
continue;
}
} else {
self.response = item;
break;
}
}
false
}
}
impl<S, T, U> Future for FramedTransport<S, T, U>
where
S: Service<Request = Request<U>, Response = Response<U>>,
S::Error: 'static,
S::Future: 'static,
T: AsyncRead + AsyncWrite,
U: Decoder + Encoder,
S: Service<Request = Request<U>, Response = Response<U>>,
S::Future: 'static,
S::Error: 'static,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: 'static,
<U as Encoder>::Error: std::fmt::Debug,
{
type Item = ();
type Error = FramedTransportError<S::Error, U>;
@@ -389,26 +409,38 @@ where
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
match mem::replace(&mut self.state, TransportState::Processing) {
TransportState::Processing => {
if self.poll_service() {
return self.poll();
if self.poll_read() || self.poll_write() {
self.poll()
} else {
Ok(Async::NotReady)
}
if self.poll_response() {
return self.poll();
}
return Ok(Async::NotReady);
}
TransportState::Error(err) => {
if self.poll_response() {
return Err(err);
if self.framed.is_write_buf_empty()
|| (self.poll_write() || self.framed.is_write_buf_empty())
{
Err(err)
} else {
self.state = TransportState::Error(err);
Ok(Async::NotReady)
}
if self.flushed {
return Err(err);
}
self.state = TransportState::Error(err);
return Ok(Async::NotReady);
}
TransportState::EncoderError(err) => return Err(err),
TransportState::Stopping => return Ok(Async::Ready(())),
TransportState::FlushAndStop => {
if !self.framed.is_write_buf_empty() {
match self.framed.poll_complete() {
Err(err) => {
debug!("Error sending data: {:?}", err);
Ok(Async::Ready(()))
}
Ok(Async::NotReady) => Ok(Async::NotReady),
Ok(Async::Ready(_)) => Ok(Async::Ready(())),
}
} else {
Ok(Async::Ready(()))
}
}
TransportState::FramedError(err) => Err(err),
TransportState::Stopping => Ok(Async::Ready(())),
}
}
}
@@ -437,7 +469,7 @@ where
}
}
impl<T, U, F> NewService for IntoFramed<T, U, F>
impl<T, C, U, F> NewService<C> for IntoFramed<T, U, F>
where
T: AsyncRead + AsyncWrite,
F: Fn() -> U + Send + Clone + 'static,
@@ -450,7 +482,7 @@ where
type Service = IntoFramedService<T, U, F>;
type Future = FutureResult<Self::Service, Self::InitError>;
fn new_service(&self) -> Self::Future {
fn new_service(&self, _: &C) -> Self::Future {
ok(IntoFramedService {
factory: self.factory.clone(),
_t: PhantomData,
@@ -483,7 +515,7 @@ where
Ok(Async::Ready(()))
}
fn call(&mut self, req: Self::Request) -> Self::Future {
fn call(&mut self, req: T) -> Self::Future {
ok(Framed::new(req, (self.factory)()))
}
}

173
actix-utils/src/inflight.rs Normal file
View File

@@ -0,0 +1,173 @@
use actix_service::{IntoService, Service, Transform, Void};
use futures::future::{ok, FutureResult};
use futures::{Async, Future, Poll};
use super::counter::{Counter, CounterGuard};
/// InFlight - new service for service that can limit number of in-flight
/// async requests.
///
/// Default number of in-flight requests is 15
pub struct InFlight {
max_inflight: usize,
}
impl InFlight {
pub fn new(max: usize) -> Self {
Self { max_inflight: max }
}
}
impl Default for InFlight {
fn default() -> Self {
Self::new(15)
}
}
impl<S: Service> Transform<S> for InFlight {
type Request = S::Request;
type Response = S::Response;
type Error = S::Error;
type InitError = Void;
type Transform = InFlightService<S>;
type Future = FutureResult<Self::Transform, Self::InitError>;
fn new_transform(&self, service: S) -> Self::Future {
ok(InFlightService::new(self.max_inflight, service))
}
}
pub struct InFlightService<S> {
count: Counter,
service: S,
}
impl<S> InFlightService<S>
where
S: Service,
{
pub fn new<U>(max: usize, service: U) -> Self
where
U: IntoService<S>,
{
Self {
count: Counter::new(max),
service: service.into_service(),
}
}
}
impl<T> Service for InFlightService<T>
where
T: Service,
{
type Request = T::Request;
type Response = T::Response;
type Error = T::Error;
type Future = InFlightServiceResponse<T>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
if let Async::NotReady = self.service.poll_ready()? {
Ok(Async::NotReady)
} else if !self.count.available() {
log::trace!("InFlight limit exceeded");
Ok(Async::NotReady)
} else {
Ok(Async::Ready(()))
}
}
fn call(&mut self, req: T::Request) -> Self::Future {
InFlightServiceResponse {
fut: self.service.call(req),
_guard: self.count.get(),
}
}
}
#[doc(hidden)]
pub struct InFlightServiceResponse<T: Service> {
fut: T::Future,
_guard: CounterGuard,
}
impl<T: Service> Future for InFlightServiceResponse<T> {
type Item = T::Response;
type Error = T::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
self.fut.poll()
}
}
#[cfg(test)]
mod tests {
use futures::future::lazy;
use futures::{Async, Poll};
use std::time::Duration;
use super::*;
use actix_service::blank::{Blank, BlankNewService};
use actix_service::{NewService, Service, ServiceExt};
struct SleepService(Duration);
impl Service for SleepService {
type Request = ();
type Response = ();
type Error = ();
type Future = Box<Future<Item = (), Error = ()>>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
fn call(&mut self, _: ()) -> Self::Future {
Box::new(tokio_timer::sleep(self.0).map_err(|_| ()))
}
}
#[test]
fn test_transform() {
let wait_time = Duration::from_millis(50);
let _ = actix_rt::System::new("test").block_on(lazy(|| {
let mut srv =
Blank::new().and_then(InFlightService::new(1, SleepService(wait_time)));
assert_eq!(srv.poll_ready(), Ok(Async::Ready(())));
let mut res = srv.call(());
let _ = res.poll();
assert_eq!(srv.poll_ready(), Ok(Async::NotReady));
drop(res);
assert_eq!(srv.poll_ready(), Ok(Async::Ready(())));
Ok::<_, ()>(())
}));
}
#[test]
fn test_newtransform() {
let wait_time = Duration::from_millis(50);
let _ = actix_rt::System::new("test").block_on(lazy(|| {
let srv =
BlankNewService::new().apply(InFlight::new(1), || Ok(SleepService(wait_time)));
if let Async::Ready(mut srv) = srv.new_service(&()).poll().unwrap() {
assert_eq!(srv.poll_ready(), Ok(Async::Ready(())));
let mut res = srv.call(());
let _ = res.poll();
assert_eq!(srv.poll_ready(), Ok(Async::NotReady));
drop(res);
assert_eq!(srv.poll_ready(), Ok(Async::Ready(())));
} else {
panic!()
}
Ok::<_, ()>(())
}));
}
}

View File

@@ -1,13 +1,12 @@
use std::marker::PhantomData;
use std::time::{Duration, Instant};
use actix_service::{NewService, Service, Void};
use futures::future::{ok, FutureResult};
use futures::{Async, Future, Poll};
use tokio_timer::Delay;
use super::service::{NewService, Service};
use super::time::{LowResTime, LowResTimeService};
use super::Never;
pub struct KeepAlive<R, E, F> {
f: F,
@@ -32,7 +31,7 @@ where
impl<R, E, F> Clone for KeepAlive<R, E, F>
where
F: Fn() -> E + Clone,
F: Clone,
{
fn clone(&self) -> Self {
KeepAlive {
@@ -44,18 +43,18 @@ where
}
}
impl<R, E, F> NewService for KeepAlive<R, E, F>
impl<R, E, F> NewService<()> for KeepAlive<R, E, F>
where
F: Fn() -> E + Clone,
{
type Request = R;
type Response = R;
type Error = E;
type InitError = Never;
type InitError = Void;
type Service = KeepAliveService<R, E, F>;
type Future = FutureResult<Self::Service, Self::InitError>;
fn new_service(&self) -> Self::Future {
fn new_service(&self, _: &()) -> Self::Future {
ok(KeepAliveService::new(
self.ka,
self.time.timer(),
@@ -112,11 +111,11 @@ where
}
}
Ok(Async::NotReady) => Ok(Async::Ready(())),
Err(_) => panic!(),
Err(_e) => panic!(),
}
}
fn call(&mut self, req: Self::Request) -> Self::Future {
fn call(&mut self, req: R) -> Self::Future {
self.expire = self.time.now() + self.ka;
ok(req)
}

12
actix-utils/src/lib.rs Normal file
View File

@@ -0,0 +1,12 @@
//! Actix utils - various helper services
mod cell;
pub mod cloneable;
pub mod counter;
pub mod either;
pub mod framed;
pub mod inflight;
pub mod keepalive;
pub mod order;
pub mod stream;
pub mod time;
pub mod timeout;

280
actix-utils/src/order.rs Normal file
View File

@@ -0,0 +1,280 @@
use std::collections::VecDeque;
use std::fmt;
use std::marker::PhantomData;
use std::rc::Rc;
use actix_service::{IntoService, Service, Transform, Void};
use futures::future::{ok, FutureResult};
use futures::task::AtomicTask;
use futures::unsync::oneshot;
use futures::{Async, Future, Poll};
struct Record<I, E> {
rx: oneshot::Receiver<Result<I, E>>,
tx: oneshot::Sender<Result<I, E>>,
}
/// Timeout error
pub enum InOrderError<E> {
/// Service error
Service(E),
/// Service call dropped
Disconnected,
}
impl<E> From<E> for InOrderError<E> {
fn from(err: E) -> Self {
InOrderError::Service(err)
}
}
impl<E: fmt::Debug> fmt::Debug for InOrderError<E> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
InOrderError::Service(e) => write!(f, "InOrderError::Service({:?})", e),
InOrderError::Disconnected => write!(f, "InOrderError::Disconnected"),
}
}
}
impl<E: fmt::Display> fmt::Display for InOrderError<E> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
InOrderError::Service(e) => e.fmt(f),
InOrderError::Disconnected => write!(f, "InOrder service disconnected"),
}
}
}
/// InOrder - The service will yield responses as they become available,
/// in the order that their originating requests were submitted to the service.
pub struct InOrder<S> {
_t: PhantomData<S>,
}
impl<S> InOrder<S>
where
S: Service,
S::Response: 'static,
S::Future: 'static,
S::Error: 'static,
{
pub fn new() -> Self {
Self { _t: PhantomData }
}
pub fn service(service: S) -> InOrderService<S> {
InOrderService::new(service)
}
}
impl<S> Default for InOrder<S>
where
S: Service,
S::Response: 'static,
S::Future: 'static,
S::Error: 'static,
{
fn default() -> Self {
Self::new()
}
}
impl<S> Transform<S> for InOrder<S>
where
S: Service,
S::Response: 'static,
S::Future: 'static,
S::Error: 'static,
{
type Request = S::Request;
type Response = S::Response;
type Error = InOrderError<S::Error>;
type InitError = Void;
type Transform = InOrderService<S>;
type Future = FutureResult<Self::Transform, Self::InitError>;
fn new_transform(&self, service: S) -> Self::Future {
ok(InOrderService::new(service))
}
}
pub struct InOrderService<S: Service> {
service: S,
task: Rc<AtomicTask>,
acks: VecDeque<Record<S::Response, S::Error>>,
}
impl<S> InOrderService<S>
where
S: Service,
S::Response: 'static,
S::Future: 'static,
S::Error: 'static,
{
pub fn new<U>(service: U) -> Self
where
U: IntoService<S>,
{
Self {
service: service.into_service(),
acks: VecDeque::new(),
task: Rc::new(AtomicTask::new()),
}
}
}
impl<S> Service for InOrderService<S>
where
S: Service,
S::Response: 'static,
S::Future: 'static,
S::Error: 'static,
{
type Request = S::Request;
type Response = S::Response;
type Error = InOrderError<S::Error>;
type Future = InOrderServiceResponse<S>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
// poll_ready could be called from different task
self.task.register();
// check acks
while !self.acks.is_empty() {
let rec = self.acks.front_mut().unwrap();
match rec.rx.poll() {
Ok(Async::Ready(res)) => {
let rec = self.acks.pop_front().unwrap();
let _ = rec.tx.send(res);
}
Ok(Async::NotReady) => break,
Err(oneshot::Canceled) => return Err(InOrderError::Disconnected),
}
}
// check nested service
if let Async::NotReady = self.service.poll_ready().map_err(InOrderError::Service)? {
Ok(Async::NotReady)
} else {
Ok(Async::Ready(()))
}
}
fn call(&mut self, request: S::Request) -> Self::Future {
let (tx1, rx1) = oneshot::channel();
let (tx2, rx2) = oneshot::channel();
self.acks.push_back(Record { rx: rx1, tx: tx2 });
let task = self.task.clone();
tokio_current_thread::spawn(self.service.call(request).then(move |res| {
task.notify();
let _ = tx1.send(res);
Ok(())
}));
InOrderServiceResponse { rx: rx2 }
}
}
#[doc(hidden)]
pub struct InOrderServiceResponse<S: Service> {
rx: oneshot::Receiver<Result<S::Response, S::Error>>,
}
impl<S: Service> Future for InOrderServiceResponse<S> {
type Item = S::Response;
type Error = InOrderError<S::Error>;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
match self.rx.poll() {
Ok(Async::NotReady) => Ok(Async::NotReady),
Ok(Async::Ready(Ok(res))) => Ok(Async::Ready(res)),
Ok(Async::Ready(Err(e))) => Err(e.into()),
Err(oneshot::Canceled) => Err(InOrderError::Disconnected),
}
}
}
#[cfg(test)]
mod tests {
use futures::future::{lazy, Future};
use futures::{stream::futures_unordered, sync::oneshot, Async, Poll, Stream};
use std::time::Duration;
use super::*;
use actix_service::blank::Blank;
use actix_service::{Service, ServiceExt};
struct Srv;
impl Service for Srv {
type Request = oneshot::Receiver<usize>;
type Response = usize;
type Error = ();
type Future = Box<Future<Item = usize, Error = ()>>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
fn call(&mut self, req: oneshot::Receiver<usize>) -> Self::Future {
Box::new(req.map_err(|_| ()))
}
}
struct SrvPoll<S: Service> {
s: S,
}
impl<S: Service> Future for SrvPoll<S> {
type Item = ();
type Error = ();
fn poll(&mut self) -> Poll<(), ()> {
let _ = self.s.poll_ready();
Ok(Async::NotReady)
}
}
#[test]
fn test_inorder() {
let (tx1, rx1) = oneshot::channel();
let (tx2, rx2) = oneshot::channel();
let (tx3, rx3) = oneshot::channel();
let (tx_stop, rx_stop) = oneshot::channel();
let h = std::thread::spawn(move || {
let rx1 = rx1;
let rx2 = rx2;
let rx3 = rx3;
let tx_stop = tx_stop;
let _ = actix_rt::System::new("test").block_on(lazy(move || {
let mut srv = Blank::new().and_then(InOrderService::new(Srv));
let res1 = srv.call(rx1);
let res2 = srv.call(rx2);
let res3 = srv.call(rx3);
tokio_current_thread::spawn(SrvPoll { s: srv });
futures_unordered(vec![res1, res2, res3])
.collect()
.and_then(move |res: Vec<_>| {
assert_eq!(res, vec![1, 2, 3]);
let _ = tx_stop.send(());
actix_rt::System::current().stop();
Ok(())
})
}));
});
let _ = tx3.send(3);
std::thread::sleep(Duration::from_millis(50));
let _ = tx2.send(2);
let _ = tx1.send(1);
let _ = rx_stop.wait();
let _ = h.join();
}
}

289
actix-utils/src/stream.rs Normal file
View File

@@ -0,0 +1,289 @@
use std::marker::PhantomData;
use std::rc::Rc;
use actix_service::{IntoNewService, IntoService, NewService, Service};
use futures::future::{ok, Future, FutureResult};
use futures::unsync::mpsc;
use futures::{Async, Poll, Stream};
type Request<T> = Result<<T as IntoStream>::Item, <T as IntoStream>::Error>;
pub trait IntoStream {
type Item;
type Error;
type Stream: Stream<Item = Self::Item, Error = Self::Error>;
fn into_stream(self) -> Self::Stream;
}
impl<T> IntoStream for T
where
T: Stream,
{
type Item = T::Item;
type Error = T::Error;
type Stream = T;
fn into_stream(self) -> Self::Stream {
self
}
}
pub struct StreamNewService<S, T, E, C> {
factory: Rc<T>,
_t: PhantomData<(S, E, C)>,
}
impl<S, T, E, C> StreamNewService<S, T, E, C>
where
C: Clone,
S: IntoStream,
T: NewService<C, Request = Request<S>, Response = (), Error = E, InitError = E>,
T::Future: 'static,
T::Service: 'static,
<T::Service as Service>::Future: 'static,
{
pub fn new<F: IntoNewService<T, C>>(factory: F) -> Self {
Self {
factory: Rc::new(factory.into_new_service()),
_t: PhantomData,
}
}
}
impl<S, T, E, C> Clone for StreamNewService<S, T, E, C> {
fn clone(&self) -> Self {
Self {
factory: self.factory.clone(),
_t: PhantomData,
}
}
}
impl<S, T, E, C> NewService<C> for StreamNewService<S, T, E, C>
where
C: Clone,
S: IntoStream + 'static,
T: NewService<C, Request = Request<S>, Response = (), Error = E, InitError = E>,
T::Future: 'static,
T::Service: 'static,
<T::Service as Service>::Future: 'static,
{
type Request = S;
type Response = ();
type Error = E;
type InitError = E;
type Service = StreamService<S, T, E, C>;
type Future = FutureResult<Self::Service, E>;
fn new_service(&self, cfg: &C) -> Self::Future {
ok(StreamService {
factory: self.factory.clone(),
config: cfg.clone(),
_t: PhantomData,
})
}
}
pub struct StreamService<S, T, E, C = ()> {
factory: Rc<T>,
config: C,
_t: PhantomData<(S, E)>,
}
impl<S, T, E, C> Service for StreamService<S, T, E, C>
where
S: IntoStream + 'static,
T: NewService<C, Request = Request<S>, Response = (), Error = E, InitError = E>,
T::Future: 'static,
T::Service: 'static,
<T::Service as Service>::Future: 'static,
C: Clone,
{
type Request = S;
type Response = ();
type Error = E;
type Future = Box<Future<Item = (), Error = E>>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
fn call(&mut self, req: S) -> Self::Future {
Box::new(
self.factory
.new_service(&self.config)
.and_then(move |srv| StreamDispatcher::new(req, srv)),
)
}
}
pub struct StreamDispatcher<S, T>
where
S: IntoStream + 'static,
T: Service<Request = Request<S>, Response = ()> + 'static,
T::Future: 'static,
{
stream: S,
service: T,
err_rx: mpsc::UnboundedReceiver<T::Error>,
err_tx: mpsc::UnboundedSender<T::Error>,
}
impl<S, T> StreamDispatcher<S, T>
where
S: Stream,
T: Service<Request = Request<S>, Response = ()>,
T::Future: 'static,
{
pub fn new<F1, F2>(stream: F1, service: F2) -> Self
where
F1: IntoStream<Stream = S, Item = S::Item, Error = S::Error>,
F2: IntoService<T>,
{
let (err_tx, err_rx) = mpsc::unbounded();
StreamDispatcher {
err_rx,
err_tx,
stream: stream.into_stream(),
service: service.into_service(),
}
}
}
impl<S, T> Future for StreamDispatcher<S, T>
where
S: Stream,
T: Service<Request = Request<S>, Response = ()>,
T::Future: 'static,
{
type Item = ();
type Error = T::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
if let Ok(Async::Ready(Some(e))) = self.err_rx.poll() {
return Err(e);
}
loop {
match self.service.poll_ready()? {
Async::Ready(_) => match self.stream.poll() {
Ok(Async::Ready(Some(item))) => {
tokio_current_thread::spawn(StreamDispatcherService {
fut: self.service.call(Ok(item)),
stop: self.err_tx.clone(),
})
}
Err(err) => tokio_current_thread::spawn(StreamDispatcherService {
fut: self.service.call(Err(err)),
stop: self.err_tx.clone(),
}),
Ok(Async::NotReady) => return Ok(Async::NotReady),
Ok(Async::Ready(None)) => return Ok(Async::Ready(())),
},
Async::NotReady => return Ok(Async::NotReady),
}
}
}
}
struct StreamDispatcherService<F: Future> {
fut: F,
stop: mpsc::UnboundedSender<F::Error>,
}
impl<F: Future> Future for StreamDispatcherService<F> {
type Item = ();
type Error = ();
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
match self.fut.poll() {
Ok(Async::Ready(_)) => Ok(Async::Ready(())),
Ok(Async::NotReady) => Ok(Async::NotReady),
Err(e) => {
let _ = self.stop.unbounded_send(e);
Ok(Async::Ready(()))
}
}
}
}
/// `NewService` that implements, read one item from the stream.
pub struct TakeItem<T> {
_t: PhantomData<T>,
}
impl<T> TakeItem<T> {
/// Create new `TakeRequest` instance.
pub fn new() -> Self {
TakeItem { _t: PhantomData }
}
}
impl<T> Default for TakeItem<T> {
fn default() -> Self {
TakeItem { _t: PhantomData }
}
}
impl<T> Clone for TakeItem<T> {
fn clone(&self) -> TakeItem<T> {
TakeItem { _t: PhantomData }
}
}
impl<T: Stream, C> NewService<C> for TakeItem<T> {
type Request = T;
type Response = (Option<T::Item>, T);
type Error = T::Error;
type InitError = ();
type Service = TakeItemService<T>;
type Future = FutureResult<Self::Service, Self::InitError>;
fn new_service(&self, _: &C) -> Self::Future {
ok(TakeItemService { _t: PhantomData })
}
}
/// `NewService` that implements, read one request from framed object feature.
pub struct TakeItemService<T> {
_t: PhantomData<T>,
}
impl<T> Clone for TakeItemService<T> {
fn clone(&self) -> TakeItemService<T> {
TakeItemService { _t: PhantomData }
}
}
impl<T: Stream> Service for TakeItemService<T> {
type Request = T;
type Response = (Option<T::Item>, T);
type Error = T::Error;
type Future = TakeItemServiceResponse<T>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
fn call(&mut self, req: T) -> Self::Future {
TakeItemServiceResponse { stream: Some(req) }
}
}
#[doc(hidden)]
pub struct TakeItemServiceResponse<T: Stream> {
stream: Option<T>,
}
impl<T: Stream> Future for TakeItemServiceResponse<T> {
type Item = (Option<T::Item>, T);
type Error = T::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
match self.stream.as_mut().expect("Use after finish").poll()? {
Async::Ready(item) => Ok(Async::Ready((item, self.stream.take().unwrap()))),
Async::NotReady => Ok(Async::NotReady),
}
}
}

249
actix-utils/src/time.rs Normal file
View File

@@ -0,0 +1,249 @@
use std::time::{self, Duration, Instant};
use actix_service::{NewService, Service, Void};
use futures::future::{ok, FutureResult};
use futures::{Async, Future, Poll};
use tokio_timer::sleep;
use super::cell::Cell;
#[derive(Clone, Debug)]
pub struct LowResTime(Cell<Inner>);
#[derive(Debug)]
struct Inner {
resolution: Duration,
current: Option<Instant>,
}
impl Inner {
fn new(resolution: Duration) -> Self {
Inner {
resolution,
current: None,
}
}
}
impl LowResTime {
pub fn with(resolution: Duration) -> LowResTime {
LowResTime(Cell::new(Inner::new(resolution)))
}
pub fn timer(&self) -> LowResTimeService {
LowResTimeService(self.0.clone())
}
}
impl Default for LowResTime {
fn default() -> Self {
LowResTime(Cell::new(Inner::new(Duration::from_secs(1))))
}
}
impl NewService<()> for LowResTime {
type Request = ();
type Response = Instant;
type Error = Void;
type InitError = Void;
type Service = LowResTimeService;
type Future = FutureResult<Self::Service, Self::InitError>;
fn new_service(&self, _: &()) -> Self::Future {
ok(self.timer())
}
}
#[derive(Clone, Debug)]
pub struct LowResTimeService(Cell<Inner>);
impl LowResTimeService {
pub fn with(resolution: Duration) -> LowResTimeService {
LowResTimeService(Cell::new(Inner::new(resolution)))
}
/// Get current time. This function has to be called from
/// future's poll method, otherwise it panics.
pub fn now(&self) -> Instant {
let cur = self.0.get_ref().current;
if let Some(cur) = cur {
cur
} else {
let now = Instant::now();
let mut inner = self.0.clone();
let interval = {
let mut b = inner.get_mut();
b.current = Some(now);
b.resolution
};
tokio_current_thread::spawn(sleep(interval).map_err(|_| panic!()).and_then(
move |_| {
inner.get_mut().current.take();
Ok(())
},
));
now
}
}
}
impl Service for LowResTimeService {
type Request = ();
type Response = Instant;
type Error = Void;
type Future = FutureResult<Self::Response, Self::Error>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
fn call(&mut self, _: ()) -> Self::Future {
ok(self.now())
}
}
#[derive(Clone, Debug)]
pub struct SystemTime(Cell<SystemTimeInner>);
#[derive(Debug)]
struct SystemTimeInner {
resolution: Duration,
current: Option<time::SystemTime>,
}
impl SystemTimeInner {
fn new(resolution: Duration) -> Self {
SystemTimeInner {
resolution,
current: None,
}
}
}
#[derive(Clone, Debug)]
pub struct SystemTimeService(Cell<SystemTimeInner>);
impl SystemTimeService {
pub fn with(resolution: Duration) -> SystemTimeService {
SystemTimeService(Cell::new(SystemTimeInner::new(resolution)))
}
/// Get current time. This function has to be called from
/// future's poll method, otherwise it panics.
pub fn now(&self) -> time::SystemTime {
let cur = self.0.get_ref().current;
if let Some(cur) = cur {
cur
} else {
let now = time::SystemTime::now();
let mut inner = self.0.clone();
let interval = {
let mut b = inner.get_mut();
b.current = Some(now);
b.resolution
};
tokio_current_thread::spawn(sleep(interval).map_err(|_| panic!()).and_then(
move |_| {
inner.get_mut().current.take();
Ok(())
},
));
now
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use futures::future;
use std::time::{Duration, SystemTime};
/// State Under Test: Two calls of `SystemTimeService::now()` return the same value if they are done within resolution interval of `SystemTimeService`.
///
/// Expected Behavior: Two back-to-back calls of `SystemTimeService::now()` return the same value.
#[test]
fn system_time_service_time_does_not_immediately_change() {
let resolution = Duration::from_millis(50);
let _ = actix_rt::System::new("test").block_on(future::lazy(|| {
let time_service = SystemTimeService::with(resolution);
assert_eq!(time_service.now(), time_service.now());
Ok::<(), ()>(())
}));
}
/// State Under Test: Two calls of `LowResTimeService::now()` return the same value if they are done within resolution interval of `SystemTimeService`.
///
/// Expected Behavior: Two back-to-back calls of `LowResTimeService::now()` return the same value.
#[test]
fn lowres_time_service_time_does_not_immediately_change() {
let resolution = Duration::from_millis(50);
let _ = actix_rt::System::new("test").block_on(future::lazy(|| {
let time_service = LowResTimeService::with(resolution);
assert_eq!(time_service.now(), time_service.now());
Ok::<(), ()>(())
}));
}
/// State Under Test: `SystemTimeService::now()` updates returned value every resolution period.
///
/// Expected Behavior: Two calls of `LowResTimeService::now()` made in subsequent resolution interval return different values
/// and second value is greater than the first one at least by a resolution interval.
#[test]
fn system_time_service_time_updates_after_resolution_interval() {
let resolution = Duration::from_millis(100);
let wait_time = Duration::from_millis(150);
let _ = actix_rt::System::new("test").block_on(future::lazy(|| {
let time_service = SystemTimeService::with(resolution);
let first_time = time_service
.now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap();
sleep(wait_time).then(move |_| {
let second_time = time_service
.now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap();
assert!(second_time - first_time >= wait_time);
Ok::<(), ()>(())
})
}));
}
/// State Under Test: `LowResTimeService::now()` updates returned value every resolution period.
///
/// Expected Behavior: Two calls of `LowResTimeService::now()` made in subsequent resolution interval return different values
/// and second value is greater than the first one at least by a resolution interval.
#[test]
fn lowres_time_service_time_updates_after_resolution_interval() {
let resolution = Duration::from_millis(100);
let wait_time = Duration::from_millis(150);
let _ = actix_rt::System::new("test").block_on(future::lazy(|| {
let time_service = LowResTimeService::with(resolution);
let first_time = time_service.now();
sleep(wait_time).then(move |_| {
let second_time = time_service.now();
assert!(second_time - first_time >= wait_time);
Ok::<(), ()>(())
})
}));
}
}

246
actix-utils/src/timeout.rs Normal file
View File

@@ -0,0 +1,246 @@
//! Service that applies a timeout to requests.
//!
//! If the response does not complete within the specified timeout, the response
//! will be aborted.
use std::fmt;
use std::marker::PhantomData;
use std::time::Duration;
use actix_service::{IntoService, Service, Transform};
use futures::future::{ok, FutureResult};
use futures::{Async, Future, Poll};
use tokio_timer::{clock, Delay};
/// Applies a timeout to requests.
#[derive(Debug)]
pub struct Timeout<E = ()> {
timeout: Duration,
_t: PhantomData<E>,
}
/// Timeout error
pub enum TimeoutError<E> {
/// Service error
Service(E),
/// Service call timeout
Timeout,
}
impl<E> From<E> for TimeoutError<E> {
fn from(err: E) -> Self {
TimeoutError::Service(err)
}
}
impl<E: fmt::Debug> fmt::Debug for TimeoutError<E> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
TimeoutError::Service(e) => write!(f, "TimeoutError::Service({:?})", e),
TimeoutError::Timeout => write!(f, "TimeoutError::Timeout"),
}
}
}
impl<E: fmt::Display> fmt::Display for TimeoutError<E> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
TimeoutError::Service(e) => e.fmt(f),
TimeoutError::Timeout => write!(f, "Service call timeout"),
}
}
}
impl<E: PartialEq> PartialEq for TimeoutError<E> {
fn eq(&self, other: &TimeoutError<E>) -> bool {
match self {
TimeoutError::Service(e1) => match other {
TimeoutError::Service(e2) => e1 == e2,
TimeoutError::Timeout => false,
},
TimeoutError::Timeout => match other {
TimeoutError::Service(_) => false,
TimeoutError::Timeout => true,
},
}
}
}
impl<E> Timeout<E> {
pub fn new(timeout: Duration) -> Self {
Timeout {
timeout,
_t: PhantomData,
}
}
}
impl<E> Clone for Timeout<E> {
fn clone(&self) -> Self {
Timeout::new(self.timeout)
}
}
impl<S, E> Transform<S> for Timeout<E>
where
S: Service,
{
type Request = S::Request;
type Response = S::Response;
type Error = TimeoutError<S::Error>;
type InitError = E;
type Transform = TimeoutService<S>;
type Future = FutureResult<Self::Transform, Self::InitError>;
fn new_transform(&self, service: S) -> Self::Future {
ok(TimeoutService {
service,
timeout: self.timeout,
})
}
}
/// Applies a timeout to requests.
#[derive(Debug, Clone)]
pub struct TimeoutService<S> {
service: S,
timeout: Duration,
}
impl<S> TimeoutService<S>
where
S: Service,
{
pub fn new<U>(timeout: Duration, service: U) -> Self
where
U: IntoService<S>,
{
TimeoutService {
timeout,
service: service.into_service(),
}
}
}
impl<S> Service for TimeoutService<S>
where
S: Service,
{
type Request = S::Request;
type Response = S::Response;
type Error = TimeoutError<S::Error>;
type Future = TimeoutServiceResponse<S>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.service.poll_ready().map_err(TimeoutError::Service)
}
fn call(&mut self, request: S::Request) -> Self::Future {
TimeoutServiceResponse {
fut: self.service.call(request),
sleep: Delay::new(clock::now() + self.timeout),
}
}
}
/// `TimeoutService` response future
#[derive(Debug)]
pub struct TimeoutServiceResponse<T: Service> {
fut: T::Future,
sleep: Delay,
}
impl<T> Future for TimeoutServiceResponse<T>
where
T: Service,
{
type Item = T::Response;
type Error = TimeoutError<T::Error>;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
// First, try polling the future
match self.fut.poll() {
Ok(Async::Ready(v)) => return Ok(Async::Ready(v)),
Ok(Async::NotReady) => {}
Err(e) => return Err(TimeoutError::Service(e)),
}
// Now check the sleep
match self.sleep.poll() {
Ok(Async::NotReady) => Ok(Async::NotReady),
Ok(Async::Ready(_)) => Err(TimeoutError::Timeout),
Err(_) => Err(TimeoutError::Timeout),
}
}
}
#[cfg(test)]
mod tests {
use futures::future::lazy;
use futures::{Async, Poll};
use std::time::Duration;
use super::*;
use actix_service::blank::{Blank, BlankNewService};
use actix_service::{NewService, Service, ServiceExt};
struct SleepService(Duration);
impl Service for SleepService {
type Request = ();
type Response = ();
type Error = ();
type Future = Box<Future<Item = (), Error = ()>>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
fn call(&mut self, _: ()) -> Self::Future {
Box::new(tokio_timer::sleep(self.0).map_err(|_| ()))
}
}
#[test]
fn test_success() {
let resolution = Duration::from_millis(100);
let wait_time = Duration::from_millis(50);
let res = actix_rt::System::new("test").block_on(lazy(|| {
let mut timeout = Blank::default()
.and_then(TimeoutService::new(resolution, SleepService(wait_time)));
timeout.call(())
}));
assert_eq!(res, Ok(()));
}
#[test]
fn test_timeout() {
let resolution = Duration::from_millis(100);
let wait_time = Duration::from_millis(150);
let res = actix_rt::System::new("test").block_on(lazy(|| {
let mut timeout = Blank::default()
.and_then(TimeoutService::new(resolution, SleepService(wait_time)));
timeout.call(())
}));
assert_eq!(res, Err(TimeoutError::Timeout));
}
#[test]
fn test_timeout_newservice() {
let resolution = Duration::from_millis(100);
let wait_time = Duration::from_millis(150);
let res = actix_rt::System::new("test").block_on(lazy(|| {
let timeout = BlankNewService::<(), (), ()>::default()
.apply(Timeout::new(resolution), || Ok(SleepService(wait_time)));
if let Async::Ready(mut to) = timeout.new_service(&()).poll().unwrap() {
to.call(())
} else {
panic!()
}
}));
assert_eq!(res, Err(TimeoutError::Timeout));
}
}

View File

@@ -1,29 +1,20 @@
//! simple composite service
//! build: cargo run --example basic --features "ssl"
//! to test: curl https://127.0.0.1:8443/ -k
extern crate actix;
extern crate actix_net;
extern crate env_logger;
extern crate futures;
extern crate openssl;
extern crate tokio_io;
extern crate tokio_openssl;
extern crate tokio_tcp;
use std::sync::{
atomic::{AtomicUsize, Ordering},
Arc,
};
use std::{env, fmt};
use std::{env, fmt, io};
use actix_codec::{AsyncRead, AsyncWrite};
use actix_rt::System;
use actix_server::{Io, Server};
use actix_service::{fn_service, NewService};
use futures::{future, Future};
use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_openssl::SslAcceptorExt;
use actix_net::server::Server;
use actix_net::service::{IntoNewService, NewServiceExt};
/// Simple logger service, it just prints fact of the new connections
fn logger<T: AsyncRead + AsyncWrite + fmt::Debug>(
stream: T,
@@ -32,11 +23,11 @@ fn logger<T: AsyncRead + AsyncWrite + fmt::Debug>(
future::ok(stream)
}
fn main() {
fn main() -> io::Result<()> {
env::set_var("RUST_LOG", "actix_net=trace");
env_logger::init();
let sys = actix::System::new("test");
let sys = System::new("test");
// load ssl keys
let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
@@ -53,7 +44,7 @@ fn main() {
// bind socket address and start workers. By default server uses number of
// available logical cpu as threads count. actix net start separate
// instances of service pipeline in each worker.
Server::default()
Server::build()
.bind(
// configure service pipeline
"basic",
@@ -63,16 +54,14 @@ fn main() {
let acceptor = acceptor.clone();
// service for converting incoming TcpStream to a SslStream<TcpStream>
(move |stream| {
SslAcceptorExt::accept_async(&acceptor, stream)
fn_service(move |stream: Io<tokio_tcp::TcpStream>| {
SslAcceptorExt::accept_async(&acceptor, stream.into_parts().0)
.map_err(|e| println!("Openssl error: {}", e))
})
// convert closure to a `NewService`
.into_new_service()
// .and_then() combinator uses other service to convert incoming `Request` to a
// `Response` and then uses that response as an input for next
// service. in this case, on success we use `logger` service
.and_then(logger)
.and_then(fn_service(logger))
// Next service counts number of connections
.and_then(move |_| {
let num = num.fetch_add(1, Ordering::Relaxed);
@@ -84,5 +73,5 @@ fn main() {
.unwrap()
.start();
sys.run();
sys.run()
}

View File

@@ -1,39 +1,22 @@
extern crate actix;
extern crate actix_net;
extern crate futures;
extern crate openssl;
extern crate tokio_io;
extern crate tokio_tcp;
use std::io;
use std::sync::{
atomic::{AtomicUsize, Ordering},
Arc,
};
use futures::{future, Future};
use actix_rt::System;
use actix_server::{ssl, Server};
use actix_service::NewService;
use futures::future;
use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};
use tokio_io::{AsyncRead, AsyncWrite};
use actix_net::server::Server;
use actix_net::service::NewServiceExt;
use actix_net::ssl;
#[derive(Debug)]
struct ServiceState {
num: Arc<AtomicUsize>,
}
fn service<T: AsyncRead + AsyncWrite>(
st: &mut ServiceState,
_: T,
) -> impl Future<Item = (), Error = ()> {
let num = st.num.fetch_add(1, Ordering::Relaxed);
println!("got ssl connection {:?}", num);
future::ok(())
}
fn main() {
let sys = actix::System::new("test");
fn main() -> io::Result<()> {
let sys = System::new("test");
// load ssl keys
let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
@@ -48,7 +31,7 @@ fn main() {
let openssl = ssl::OpensslAcceptor::new(builder.build());
// server start mutiple workers, it runs supplied `Fn` in each worker.
Server::default()
Server::build()
.bind("test-ssl", "0.0.0.0:8443", move || {
let num = num.clone();
@@ -61,9 +44,8 @@ fn main() {
println!("got ssl connection {:?}", num);
future::ok(())
})
})
.unwrap()
})?
.start();
sys.run();
sys.run()
}

15
router/CHANGES.txt Normal file
View File

@@ -0,0 +1,15 @@
# Changes
## [0.1.2] - 2019-04-07
* Export `Quoter` type
* Allow to reset `Path` instance
## [0.1.1] - 2019-04-03
* Get dynamic segment by name instead of iterator.
## [0.1.0] - 2019-03-09
* Initial release

32
router/Cargo.toml Normal file
View File

@@ -0,0 +1,32 @@
[package]
name = "actix-router"
version = "0.1.2"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Path router"
keywords = ["actix"]
homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-net.git"
documentation = "https://docs.rs/actix-router/"
license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
edition = "2018"
workspace = ".."
[lib]
name = "actix_router"
path = "src/lib.rs"
[features]
default = ["http"]
[dependencies]
bytes = "0.4"
regex = "1.0"
serde = "1.0.80"
string = "0.2.0"
log = "0.4"
http = { version="0.1.14", optional=true }
[dev-dependencies]
http = "0.1.14"
serde_derive = "1.0"

709
router/src/de.rs Normal file
View File

@@ -0,0 +1,709 @@
use serde::de::{self, Deserializer, Error as DeError, Visitor};
use serde::forward_to_deserialize_any;
use crate::path::{Path, PathIter};
use crate::ResourcePath;
macro_rules! unsupported_type {
($trait_fn:ident, $name:expr) => {
fn $trait_fn<V>(self, _: V) -> Result<V::Value, Self::Error>
where V: Visitor<'de>
{
Err(de::value::Error::custom(concat!("unsupported type: ", $name)))
}
};
}
macro_rules! parse_single_value {
($trait_fn:ident, $visit_fn:ident, $tp:tt) => {
fn $trait_fn<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'de>
{
if self.path.len() != 1 {
Err(de::value::Error::custom(
format!("wrong number of parameters: {} expected 1",
self.path.len()).as_str()))
} else {
let v = self.path[0].parse().map_err(
|_| de::value::Error::custom(
format!("can not parse {:?} to a {}", &self.path[0], $tp)))?;
visitor.$visit_fn(v)
}
}
}
}
pub struct PathDeserializer<'de, T: ResourcePath + 'de> {
path: &'de Path<T>,
}
impl<'de, T: ResourcePath + 'de> PathDeserializer<'de, T> {
pub fn new(path: &'de Path<T>) -> Self {
PathDeserializer { path }
}
}
impl<'de, T: ResourcePath + 'de> Deserializer<'de> for PathDeserializer<'de, T> {
type Error = de::value::Error;
fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_map(ParamsDeserializer {
params: self.path.iter(),
current: None,
})
}
fn deserialize_struct<V>(
self,
_: &'static str,
_: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
self.deserialize_map(visitor)
}
fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_unit()
}
fn deserialize_unit_struct<V>(
self,
_: &'static str,
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
self.deserialize_unit(visitor)
}
fn deserialize_newtype_struct<V>(
self,
_: &'static str,
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_newtype_struct(self)
}
fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
if self.path.len() < len {
Err(de::value::Error::custom(
format!(
"wrong number of parameters: {} expected {}",
self.path.len(),
len
)
.as_str(),
))
} else {
visitor.visit_seq(ParamsSeq {
params: self.path.iter(),
})
}
}
fn deserialize_tuple_struct<V>(
self,
_: &'static str,
len: usize,
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
if self.path.len() < len {
Err(de::value::Error::custom(
format!(
"wrong number of parameters: {} expected {}",
self.path.len(),
len
)
.as_str(),
))
} else {
visitor.visit_seq(ParamsSeq {
params: self.path.iter(),
})
}
}
fn deserialize_enum<V>(
self,
_: &'static str,
_: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
if self.path.len() < 1 {
Err(de::value::Error::custom(
"expeceted at least one parameters",
))
} else {
visitor.visit_enum(ValueEnum {
value: &self.path[0],
})
}
}
fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
if self.path.len() != 1 {
Err(de::value::Error::custom(
format!("wrong number of parameters: {} expected 1", self.path.len()).as_str(),
))
} else {
visitor.visit_str(&self.path[0])
}
}
fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_seq(ParamsSeq {
params: self.path.iter(),
})
}
unsupported_type!(deserialize_any, "'any'");
unsupported_type!(deserialize_bytes, "bytes");
unsupported_type!(deserialize_option, "Option<T>");
unsupported_type!(deserialize_identifier, "identifier");
unsupported_type!(deserialize_ignored_any, "ignored_any");
parse_single_value!(deserialize_bool, visit_bool, "bool");
parse_single_value!(deserialize_i8, visit_i8, "i8");
parse_single_value!(deserialize_i16, visit_i16, "i16");
parse_single_value!(deserialize_i32, visit_i32, "i32");
parse_single_value!(deserialize_i64, visit_i64, "i64");
parse_single_value!(deserialize_u8, visit_u8, "u8");
parse_single_value!(deserialize_u16, visit_u16, "u16");
parse_single_value!(deserialize_u32, visit_u32, "u32");
parse_single_value!(deserialize_u64, visit_u64, "u64");
parse_single_value!(deserialize_f32, visit_f32, "f32");
parse_single_value!(deserialize_f64, visit_f64, "f64");
parse_single_value!(deserialize_string, visit_string, "String");
parse_single_value!(deserialize_byte_buf, visit_string, "String");
parse_single_value!(deserialize_char, visit_char, "char");
}
struct ParamsDeserializer<'de, T: ResourcePath> {
params: PathIter<'de, T>,
current: Option<(&'de str, &'de str)>,
}
impl<'de, T: ResourcePath> de::MapAccess<'de> for ParamsDeserializer<'de, T> {
type Error = de::value::Error;
fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>
where
K: de::DeserializeSeed<'de>,
{
self.current = self.params.next().map(|ref item| (item.0, item.1));
match self.current {
Some((key, _)) => Ok(Some(seed.deserialize(Key { key })?)),
None => Ok(None),
}
}
fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
where
V: de::DeserializeSeed<'de>,
{
if let Some((_, value)) = self.current.take() {
seed.deserialize(Value { value })
} else {
Err(de::value::Error::custom("unexpected item"))
}
}
}
struct Key<'de> {
key: &'de str,
}
impl<'de> Deserializer<'de> for Key<'de> {
type Error = de::value::Error;
fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_str(self.key)
}
fn deserialize_any<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
Err(de::value::Error::custom("Unexpected"))
}
forward_to_deserialize_any! {
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
byte_buf option unit unit_struct newtype_struct seq tuple
tuple_struct map struct enum ignored_any
}
}
macro_rules! parse_value {
($trait_fn:ident, $visit_fn:ident, $tp:tt) => {
fn $trait_fn<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'de>
{
let v = self.value.parse().map_err(
|_| de::value::Error::custom(
format!("can not parse {:?} to a {}", self.value, $tp)))?;
visitor.$visit_fn(v)
}
}
}
struct Value<'de> {
value: &'de str,
}
impl<'de> Deserializer<'de> for Value<'de> {
type Error = de::value::Error;
parse_value!(deserialize_bool, visit_bool, "bool");
parse_value!(deserialize_i8, visit_i8, "i8");
parse_value!(deserialize_i16, visit_i16, "i16");
parse_value!(deserialize_i32, visit_i32, "i16");
parse_value!(deserialize_i64, visit_i64, "i64");
parse_value!(deserialize_u8, visit_u8, "u8");
parse_value!(deserialize_u16, visit_u16, "u16");
parse_value!(deserialize_u32, visit_u32, "u32");
parse_value!(deserialize_u64, visit_u64, "u64");
parse_value!(deserialize_f32, visit_f32, "f32");
parse_value!(deserialize_f64, visit_f64, "f64");
parse_value!(deserialize_string, visit_string, "String");
parse_value!(deserialize_byte_buf, visit_string, "String");
parse_value!(deserialize_char, visit_char, "char");
fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_unit()
}
fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_unit()
}
fn deserialize_unit_struct<V>(
self,
_: &'static str,
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_unit()
}
fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_borrowed_bytes(self.value.as_bytes())
}
fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_borrowed_str(self.value)
}
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_some(self)
}
fn deserialize_enum<V>(
self,
_: &'static str,
_: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_enum(ValueEnum { value: self.value })
}
fn deserialize_newtype_struct<V>(
self,
_: &'static str,
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_newtype_struct(self)
}
fn deserialize_tuple<V>(self, _: usize, _: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
Err(de::value::Error::custom("unsupported type: tuple"))
}
fn deserialize_struct<V>(
self,
_: &'static str,
_: &'static [&'static str],
_: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
Err(de::value::Error::custom("unsupported type: struct"))
}
fn deserialize_tuple_struct<V>(
self,
_: &'static str,
_: usize,
_: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
Err(de::value::Error::custom("unsupported type: tuple struct"))
}
unsupported_type!(deserialize_any, "any");
unsupported_type!(deserialize_seq, "seq");
unsupported_type!(deserialize_map, "map");
unsupported_type!(deserialize_identifier, "identifier");
}
struct ParamsSeq<'de, T: ResourcePath> {
params: PathIter<'de, T>,
}
impl<'de, T: ResourcePath> de::SeqAccess<'de> for ParamsSeq<'de, T> {
type Error = de::value::Error;
fn next_element_seed<U>(&mut self, seed: U) -> Result<Option<U::Value>, Self::Error>
where
U: de::DeserializeSeed<'de>,
{
match self.params.next() {
Some(item) => Ok(Some(seed.deserialize(Value { value: item.1 })?)),
None => Ok(None),
}
}
}
struct ValueEnum<'de> {
value: &'de str,
}
impl<'de> de::EnumAccess<'de> for ValueEnum<'de> {
type Error = de::value::Error;
type Variant = UnitVariant;
fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
where
V: de::DeserializeSeed<'de>,
{
Ok((seed.deserialize(Key { key: self.value })?, UnitVariant))
}
}
struct UnitVariant;
impl<'de> de::VariantAccess<'de> for UnitVariant {
type Error = de::value::Error;
fn unit_variant(self) -> Result<(), Self::Error> {
Ok(())
}
fn newtype_variant_seed<T>(self, _seed: T) -> Result<T::Value, Self::Error>
where
T: de::DeserializeSeed<'de>,
{
Err(de::value::Error::custom("not supported"))
}
fn tuple_variant<V>(self, _len: usize, _visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
Err(de::value::Error::custom("not supported"))
}
fn struct_variant<V>(
self,
_: &'static [&'static str],
_: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
Err(de::value::Error::custom("not supported"))
}
}
#[cfg(test)]
mod tests {
use serde::de;
use serde_derive::Deserialize;
use super::*;
use crate::path::Path;
use crate::router::Router;
#[derive(Deserialize)]
struct MyStruct {
key: String,
value: String,
}
#[derive(Deserialize)]
struct Id {
id: String,
}
#[derive(Debug, Deserialize)]
struct Test1(String, u32);
#[derive(Debug, Deserialize)]
struct Test2 {
key: String,
value: u32,
}
#[derive(Debug, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
enum TestEnum {
Val1,
Val2,
}
#[derive(Debug, Deserialize)]
struct Test3 {
val: TestEnum,
}
#[test]
fn test_request_extract() {
let mut router = Router::<()>::build();
router.path("/{key}/{value}/", ());
let router = router.finish();
let mut path = Path::new("/name/user1/");
assert!(router.recognize(&mut path).is_some());
let s: MyStruct = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
assert_eq!(s.key, "name");
assert_eq!(s.value, "user1");
let s: (String, String) =
de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
assert_eq!(s.0, "name");
assert_eq!(s.1, "user1");
let mut router = Router::<()>::build();
router.path("/{key}/{value}/", ());
let router = router.finish();
let mut path = Path::new("/name/32/");
assert!(router.recognize(&mut path).is_some());
let s: Test1 = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
assert_eq!(s.0, "name");
assert_eq!(s.1, 32);
let s: Test2 = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
assert_eq!(s.key, "name");
assert_eq!(s.value, 32);
let s: (String, u8) =
de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
assert_eq!(s.0, "name");
assert_eq!(s.1, 32);
let res: Vec<String> =
de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
assert_eq!(res[0], "name".to_owned());
assert_eq!(res[1], "32".to_owned());
}
#[test]
fn test_extract_path_single() {
let mut router = Router::<()>::build();
router.path("/{value}/", ());
let router = router.finish();
let mut path = Path::new("/32/");
assert!(router.recognize(&mut path).is_some());
let i: i8 = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
assert_eq!(i, 32);
}
#[test]
fn test_extract_enum() {
let mut router = Router::<()>::build();
router.path("/{val}/", ());
let router = router.finish();
let mut path = Path::new("/val1/");
assert!(router.recognize(&mut path).is_some());
let i: TestEnum = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
assert_eq!(i, TestEnum::Val1);
let mut router = Router::<()>::build();
router.path("/{val1}/{val2}/", ());
let router = router.finish();
let mut path = Path::new("/val1/val2/");
assert!(router.recognize(&mut path).is_some());
let i: (TestEnum, TestEnum) =
de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
assert_eq!(i, (TestEnum::Val1, TestEnum::Val2));
}
#[test]
fn test_extract_enum_value() {
let mut router = Router::<()>::build();
router.path("/{val}/", ());
let router = router.finish();
let mut path = Path::new("/val1/");
assert!(router.recognize(&mut path).is_some());
let i: Test3 = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
assert_eq!(i.val, TestEnum::Val1);
let mut path = Path::new("/val3/");
assert!(router.recognize(&mut path).is_some());
let i: Result<Test3, de::value::Error> =
de::Deserialize::deserialize(PathDeserializer::new(&path));
assert!(i.is_err());
assert!(format!("{:?}", i).contains("unknown variant"));
}
#[test]
fn test_extract_errors() {
let mut router = Router::<()>::build();
router.path("/{value}/", ());
let router = router.finish();
let mut path = Path::new("/name/");
assert!(router.recognize(&mut path).is_some());
let s: Result<Test1, de::value::Error> =
de::Deserialize::deserialize(PathDeserializer::new(&path));
assert!(s.is_err());
assert!(format!("{:?}", s).contains("wrong number of parameters"));
let s: Result<Test2, de::value::Error> =
de::Deserialize::deserialize(PathDeserializer::new(&path));
assert!(s.is_err());
assert!(format!("{:?}", s).contains("can not parse"));
let s: Result<(String, String), de::value::Error> =
de::Deserialize::deserialize(PathDeserializer::new(&path));
assert!(s.is_err());
assert!(format!("{:?}", s).contains("wrong number of parameters"));
let s: Result<u32, de::value::Error> =
de::Deserialize::deserialize(PathDeserializer::new(&path));
assert!(s.is_err());
assert!(format!("{:?}", s).contains("can not parse"));
}
// #[test]
// fn test_extract_path_decode() {
// let mut router = Router::<()>::default();
// router.register_resource(Resource::new(ResourceDef::new("/{value}/")));
// macro_rules! test_single_value {
// ($value:expr, $expected:expr) => {{
// let req = TestRequest::with_uri($value).finish();
// let info = router.recognize(&req, &(), 0);
// let req = req.with_route_info(info);
// assert_eq!(
// *Path::<String>::from_request(&req, &PathConfig::default()).unwrap(),
// $expected
// );
// }};
// }
// test_single_value!("/%25/", "%");
// test_single_value!("/%40%C2%A3%24%25%5E%26%2B%3D/", "@£$%^&+=");
// test_single_value!("/%2B/", "+");
// test_single_value!("/%252B/", "%2B");
// test_single_value!("/%2F/", "/");
// test_single_value!("/%252F/", "%2F");
// test_single_value!(
// "/http%3A%2F%2Flocalhost%3A80%2Ffoo/",
// "http://localhost:80/foo"
// );
// test_single_value!("/%2Fvar%2Flog%2Fsyslog/", "/var/log/syslog");
// test_single_value!(
// "/http%3A%2F%2Flocalhost%3A80%2Ffile%2F%252Fvar%252Flog%252Fsyslog/",
// "http://localhost:80/file/%2Fvar%2Flog%2Fsyslog"
// );
// let req = TestRequest::with_uri("/%25/7/?id=test").finish();
// let mut router = Router::<()>::default();
// router.register_resource(Resource::new(ResourceDef::new("/{key}/{value}/")));
// let info = router.recognize(&req, &(), 0);
// let req = req.with_route_info(info);
// let s = Path::<Test2>::from_request(&req, &PathConfig::default()).unwrap();
// assert_eq!(s.key, "%");
// assert_eq!(s.value, 7);
// let s = Path::<(String, String)>::from_request(&req, &PathConfig::default()).unwrap();
// assert_eq!(s.0, "%");
// assert_eq!(s.1, "7");
// }
// #[test]
// fn test_extract_path_no_decode() {
// let mut router = Router::<()>::default();
// router.register_resource(Resource::new(ResourceDef::new("/{value}/")));
// let req = TestRequest::with_uri("/%25/").finish();
// let info = router.recognize(&req, &(), 0);
// let req = req.with_route_info(info);
// assert_eq!(
// *Path::<String>::from_request(&req, &&PathConfig::default().disable_decoding())
// .unwrap(),
// "%25"
// );
// }
}

54
router/src/lib.rs Normal file
View File

@@ -0,0 +1,54 @@
//! Resource path matching library.
mod de;
mod path;
mod resource;
mod router;
pub use self::de::PathDeserializer;
pub use self::path::Path;
pub use self::resource::ResourceDef;
pub use self::router::{ResourceInfo, Router, RouterBuilder};
pub trait Resource<T: ResourcePath> {
fn resource_path(&mut self) -> &mut Path<T>;
}
pub trait ResourcePath {
fn path(&self) -> &str;
}
impl ResourcePath for String {
fn path(&self) -> &str {
self.as_str()
}
}
impl<'a> ResourcePath for &'a str {
fn path(&self) -> &str {
self
}
}
impl<T: AsRef<[u8]>> ResourcePath for string::String<T> {
fn path(&self) -> &str {
&*self
}
}
#[cfg(feature = "http")]
mod url;
#[cfg(feature = "http")]
pub use self::url::{Quoter, Url};
#[cfg(feature = "http")]
mod http_support {
use super::ResourcePath;
use http::Uri;
impl ResourcePath for Uri {
fn path(&self) -> &str {
self.path()
}
}
}

224
router/src/path.rs Normal file
View File

@@ -0,0 +1,224 @@
use std::ops::Index;
use std::rc::Rc;
use serde::de;
use crate::de::PathDeserializer;
use crate::{Resource, ResourcePath};
#[derive(Debug, Clone, Copy)]
pub(crate) enum PathItem {
Static(&'static str),
Segment(u16, u16),
}
/// Resource path match information
///
/// If resource path contains variable patterns, `Path` stores them.
#[derive(Debug)]
pub struct Path<T> {
path: T,
pub(crate) skip: u16,
pub(crate) segments: Vec<(Rc<String>, PathItem)>,
}
impl<T: Default> Default for Path<T> {
fn default() -> Self {
Path {
path: T::default(),
skip: 0,
segments: Vec::new(),
}
}
}
impl<T: Clone> Clone for Path<T> {
fn clone(&self) -> Self {
Path {
path: self.path.clone(),
skip: self.skip,
segments: self.segments.clone(),
}
}
}
impl<T: ResourcePath> Path<T> {
pub fn new(path: T) -> Path<T> {
Path {
path,
skip: 0,
segments: Vec::new(),
}
}
#[inline]
/// Get reference to inner path instance
pub fn get_ref(&self) -> &T {
&self.path
}
#[inline]
/// Get mutable reference to inner path instance
pub fn get_mut(&mut self) -> &mut T {
&mut self.path
}
#[inline]
/// Path
pub fn path(&self) -> &str {
let skip = self.skip as usize;
let path = self.path.path();
if skip <= path.len() {
&path[skip..]
} else {
""
}
}
#[inline]
/// Set new path
pub fn set(&mut self, path: T) {
self.skip = 0;
self.path = path;
self.segments.clear();
}
#[inline]
/// Reset state
pub fn reset(&mut self) {
self.skip = 0;
self.segments.clear();
}
#[inline]
/// Skip first `n` chars in path
pub fn skip(&mut self, n: u16) {
self.skip = self.skip + n;
}
pub(crate) fn add(&mut self, name: Rc<String>, value: PathItem) {
match value {
PathItem::Static(s) => self.segments.push((name, PathItem::Static(s))),
PathItem::Segment(begin, end) => self
.segments
.push((name, PathItem::Segment(self.skip + begin, self.skip + end))),
}
}
#[doc(hidden)]
pub fn add_static(&mut self, name: &str, value: &'static str) {
self.segments
.push((Rc::new(name.to_string()), PathItem::Static(value)));
}
#[inline]
/// Check if there are any matched patterns
pub fn is_empty(&self) -> bool {
self.segments.is_empty()
}
#[inline]
/// Check number of extracted parameters
pub fn len(&self) -> usize {
self.segments.len()
}
/// Get matched parameter by name without type conversion
pub fn get(&self, key: &str) -> Option<&str> {
for item in self.segments.iter() {
if key == item.0.as_str() {
return match item.1 {
PathItem::Static(ref s) => Some(&s),
PathItem::Segment(s, e) => {
Some(&self.path.path()[(s as usize)..(e as usize)])
}
};
}
}
if key == "tail" {
Some(&self.path.path()[(self.skip as usize)..])
} else {
None
}
}
/// Get unprocessed part of the path
pub fn unprocessed(&self) -> &str {
&self.path.path()[(self.skip as usize)..]
}
/// Get matched parameter by name.
///
/// If keyed parameter is not available empty string is used as default
/// value.
pub fn query(&self, key: &str) -> &str {
if let Some(s) = self.get(key) {
s
} else {
""
}
}
/// Return iterator to items in parameter container
pub fn iter(&self) -> PathIter<T> {
PathIter {
idx: 0,
params: self,
}
}
/// Try to deserialize matching parameters to a specified type `U`
pub fn load<'de, U: serde::Deserialize<'de>>(&'de self) -> Result<U, de::value::Error> {
de::Deserialize::deserialize(PathDeserializer::new(self))
}
}
#[derive(Debug)]
pub struct PathIter<'a, T> {
idx: usize,
params: &'a Path<T>,
}
impl<'a, T: ResourcePath> Iterator for PathIter<'a, T> {
type Item = (&'a str, &'a str);
#[inline]
fn next(&mut self) -> Option<(&'a str, &'a str)> {
if self.idx < self.params.len() {
let idx = self.idx;
let res = match self.params.segments[idx].1 {
PathItem::Static(ref s) => &s,
PathItem::Segment(s, e) => &self.params.path.path()[(s as usize)..(e as usize)],
};
self.idx += 1;
return Some((&self.params.segments[idx].0, res));
}
None
}
}
impl<'a, T: ResourcePath> Index<&'a str> for Path<T> {
type Output = str;
fn index(&self, name: &'a str) -> &str {
self.get(name)
.expect("Value for parameter is not available")
}
}
impl<T: ResourcePath> Index<usize> for Path<T> {
type Output = str;
fn index(&self, idx: usize) -> &str {
match self.segments[idx].1 {
PathItem::Static(ref s) => &s,
PathItem::Segment(s, e) => &self.path.path()[(s as usize)..(e as usize)],
}
}
}
impl<T: ResourcePath> Resource<T> for Path<T> {
fn resource_path(&mut self) -> &mut Self {
self
}
}

516
router/src/resource.rs Normal file
View File

@@ -0,0 +1,516 @@
use std::cmp::min;
use std::hash::{Hash, Hasher};
use std::rc::Rc;
use regex::{escape, Regex};
use crate::path::{Path, PathItem};
use crate::ResourcePath;
const MAX_DYNAMIC_SEGMENTS: usize = 16;
/// ResourceDef describes an entry in resources table
///
/// Resource definition can contain only 16 dynamic segments
#[derive(Clone, Debug)]
pub struct ResourceDef {
id: u16,
tp: PatternType,
name: String,
pattern: String,
elements: Vec<PatternElement>,
}
#[derive(Debug, Clone, PartialEq)]
enum PatternElement {
Str(String),
Var(String),
}
#[derive(Clone, Debug)]
enum PatternType {
Static(String),
Prefix(String),
Dynamic(Regex, Vec<Rc<String>>, usize),
}
impl ResourceDef {
/// Parse path pattern and create new `Pattern` instance.
///
/// Panics if path pattern is wrong.
pub fn new(path: &str) -> Self {
ResourceDef::with_prefix(path, false)
}
/// Parse path pattern and create new `Pattern` instance.
///
/// Use `prefix` type instead of `static`.
///
/// Panics if path regex pattern is wrong.
pub fn prefix(path: &str) -> Self {
ResourceDef::with_prefix(path, true)
}
/// Parse path pattern and create new `Pattern` instance.
/// Inserts `/` to begging of the pattern.
///
///
/// Use `prefix` type instead of `static`.
///
/// Panics if path regex pattern is wrong.
pub fn root_prefix(path: &str) -> Self {
ResourceDef::with_prefix(&insert_slash(path), true)
}
/// Resource id
pub fn id(&self) -> u16 {
self.id
}
/// Set resource id
pub fn set_id(&mut self, id: u16) {
self.id = id;
}
/// Parse path pattern and create new `Pattern` instance with custom prefix
fn with_prefix(path: &str, for_prefix: bool) -> Self {
let path = path.to_owned();
let (pattern, elements, is_dynamic, len) = ResourceDef::parse(&path, for_prefix);
let tp = if is_dynamic {
let re = match Regex::new(&pattern) {
Ok(re) => re,
Err(err) => panic!("Wrong path pattern: \"{}\" {}", path, err),
};
// actix creates one router per thread
let names = re
.capture_names()
.filter_map(|name| name.map(|name| Rc::new(name.to_owned())))
.collect();
PatternType::Dynamic(re, names, len)
} else if for_prefix {
PatternType::Prefix(pattern.clone())
} else {
PatternType::Static(pattern.clone())
};
ResourceDef {
tp,
elements,
id: 0,
name: String::new(),
pattern: path.to_owned(),
}
}
/// Resource pattern name
pub fn name(&self) -> &str {
&self.name
}
/// Mutable reference to a name of a resource definition.
pub fn name_mut(&mut self) -> &mut String {
&mut self.name
}
/// Path pattern of the resource
pub fn pattern(&self) -> &str {
&self.pattern
}
#[inline]
/// Check if path matchs this pattern?
pub fn is_match(&self, path: &str) -> bool {
match self.tp {
PatternType::Static(ref s) => s == path,
PatternType::Dynamic(ref re, _, _) => re.is_match(path),
PatternType::Prefix(ref s) => path.starts_with(s),
}
}
/// Is prefix path a match against this resource?
pub fn is_prefix_match(&self, path: &str) -> Option<usize> {
let plen = path.len();
let path = if path.is_empty() { "/" } else { path };
match self.tp {
PatternType::Static(ref s) => {
if s == path {
Some(plen)
} else {
None
}
}
PatternType::Dynamic(ref re, _, len) => {
if let Some(captures) = re.captures(path) {
let mut pos = 0;
let mut passed = false;
for capture in captures.iter() {
if let Some(ref m) = capture {
if !passed {
passed = true;
continue;
}
pos = m.end();
}
}
Some(pos + len)
} else {
None
}
}
PatternType::Prefix(ref s) => {
let len = if path == s {
s.len()
} else if path.starts_with(s)
&& (s.ends_with('/') || path.split_at(s.len()).1.starts_with('/'))
{
if s.ends_with('/') {
s.len() - 1
} else {
s.len()
}
} else {
return None;
};
Some(min(plen, len))
}
}
}
/// Is the given path and parameters a match against this pattern?
pub fn match_path<T: ResourcePath>(&self, path: &mut Path<T>) -> bool {
match self.tp {
PatternType::Static(ref s) => {
if s == path.path() {
path.skip(path.len() as u16);
true
} else {
false
}
}
PatternType::Dynamic(ref re, ref names, len) => {
let mut idx = 0;
let mut pos = 0;
let mut segments: [PathItem; MAX_DYNAMIC_SEGMENTS] =
[PathItem::Static(""); MAX_DYNAMIC_SEGMENTS];
if let Some(captures) = re.captures(path.path()) {
for (no, name) in names.iter().enumerate() {
if let Some(m) = captures.name(&name) {
idx += 1;
pos = m.end();
segments[no] = PathItem::Segment(m.start() as u16, m.end() as u16);
} else {
log::error!(
"Dynamic path match but not all segments found: {}",
name
);
false;
}
}
} else {
return false;
}
for idx in 0..idx {
path.add(names[idx].clone(), segments[idx]);
}
path.skip((pos + len) as u16);
true
}
PatternType::Prefix(ref s) => {
let rpath = path.path();
let len = if s == rpath {
s.len()
} else if rpath.starts_with(s)
&& (s.ends_with('/') || rpath.split_at(s.len()).1.starts_with('/'))
{
if s.ends_with('/') {
s.len() - 1
} else {
s.len()
}
} else {
return false;
};
path.skip(min(rpath.len(), len) as u16);
true
}
}
}
/// Build resource path from elements. Returns `true` on success.
pub fn resource_path<U, I>(&self, path: &mut String, elements: &mut U) -> bool
where
U: Iterator<Item = I>,
I: AsRef<str>,
{
match self.tp {
PatternType::Prefix(ref p) => path.push_str(p),
PatternType::Static(ref p) => path.push_str(p),
PatternType::Dynamic(..) => {
for el in &self.elements {
match *el {
PatternElement::Str(ref s) => path.push_str(s),
PatternElement::Var(_) => {
if let Some(val) = elements.next() {
path.push_str(val.as_ref())
} else {
return false;
}
}
}
}
}
};
true
}
fn parse_param(pattern: &str) -> (PatternElement, String, &str) {
const DEFAULT_PATTERN: &str = "[^/]+";
let mut params_nesting = 0usize;
let close_idx = pattern
.find(|c| match c {
'{' => {
params_nesting += 1;
false
}
'}' => {
params_nesting -= 1;
params_nesting == 0
}
_ => false,
})
.expect("malformed dynamic segment");
let (mut param, rem) = pattern.split_at(close_idx + 1);
param = &param[1..param.len() - 1]; // Remove outer brackets
let (name, pattern) = match param.find(':') {
Some(idx) => {
let (name, pattern) = param.split_at(idx);
(name, &pattern[1..])
}
None => (param, DEFAULT_PATTERN),
};
(
PatternElement::Var(name.to_string()),
format!(r"(?P<{}>{})", &name, &pattern),
rem,
)
}
fn parse(
mut pattern: &str,
for_prefix: bool,
) -> (String, Vec<PatternElement>, bool, usize) {
if pattern.find('{').is_none() {
return (
String::from(pattern),
vec![PatternElement::Str(String::from(pattern))],
false,
pattern.chars().count(),
);
};
let mut elems = Vec::new();
let mut re = String::from("^");
let mut dyn_elems = 0;
while let Some(idx) = pattern.find('{') {
let (prefix, rem) = pattern.split_at(idx);
elems.push(PatternElement::Str(String::from(prefix)));
re.push_str(&escape(prefix));
let (param_pattern, re_part, rem) = Self::parse_param(rem);
elems.push(param_pattern);
re.push_str(&re_part);
pattern = rem;
dyn_elems += 1;
}
elems.push(PatternElement::Str(String::from(pattern)));
re.push_str(&escape(pattern));
if dyn_elems > MAX_DYNAMIC_SEGMENTS {
panic!(
"Only {} dynanic segments are allowed, provided: {}",
MAX_DYNAMIC_SEGMENTS, dyn_elems
);
}
if !for_prefix {
re.push_str("$");
}
(re, elems, true, pattern.chars().count())
}
}
impl Eq for ResourceDef {}
impl PartialEq for ResourceDef {
fn eq(&self, other: &ResourceDef) -> bool {
self.pattern == other.pattern
}
}
impl Hash for ResourceDef {
fn hash<H: Hasher>(&self, state: &mut H) {
self.pattern.hash(state);
}
}
impl<'a> From<&'a str> for ResourceDef {
fn from(path: &'a str) -> ResourceDef {
ResourceDef::new(path)
}
}
impl From<String> for ResourceDef {
fn from(path: String) -> ResourceDef {
ResourceDef::new(&path)
}
}
pub(crate) fn insert_slash(path: &str) -> String {
let mut path = path.to_owned();
if !path.is_empty() && !path.starts_with('/') {
path.insert(0, '/');
};
path
}
#[cfg(test)]
mod tests {
use super::*;
use http::{HttpTryFrom, Uri};
#[test]
fn test_parse_static() {
let re = ResourceDef::new("/");
assert!(re.is_match("/"));
assert!(!re.is_match("/a"));
let re = ResourceDef::new("/name");
assert!(re.is_match("/name"));
assert!(!re.is_match("/name1"));
assert!(!re.is_match("/name/"));
assert!(!re.is_match("/name~"));
assert_eq!(re.is_prefix_match("/name"), Some(5));
assert_eq!(re.is_prefix_match("/name1"), None);
assert_eq!(re.is_prefix_match("/name/"), None);
assert_eq!(re.is_prefix_match("/name~"), None);
let re = ResourceDef::new("/name/");
assert!(re.is_match("/name/"));
assert!(!re.is_match("/name"));
assert!(!re.is_match("/name/gs"));
let re = ResourceDef::new("/user/profile");
assert!(re.is_match("/user/profile"));
assert!(!re.is_match("/user/profile/profile"));
}
#[test]
fn test_parse_param() {
let re = ResourceDef::new("/user/{id}");
assert!(re.is_match("/user/profile"));
assert!(re.is_match("/user/2345"));
assert!(!re.is_match("/user/2345/"));
assert!(!re.is_match("/user/2345/sdg"));
let mut path = Path::new("/user/profile");
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "profile");
let mut path = Path::new("/user/1245125");
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "1245125");
let re = ResourceDef::new("/v{version}/resource/{id}");
assert!(re.is_match("/v1/resource/320120"));
assert!(!re.is_match("/v/resource/1"));
assert!(!re.is_match("/resource"));
let mut path = Path::new("/v151/resource/adahg32");
assert!(re.match_path(&mut path));
assert_eq!(path.get("version").unwrap(), "151");
assert_eq!(path.get("id").unwrap(), "adahg32");
let re = ResourceDef::new("/{id:[[:digit:]]{6}}");
assert!(re.is_match("/012345"));
assert!(!re.is_match("/012"));
assert!(!re.is_match("/01234567"));
assert!(!re.is_match("/XXXXXX"));
let mut path = Path::new("/012345");
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "012345");
}
#[test]
fn test_parse_urlencoded_param() {
let re = ResourceDef::new("/user/{id}/test");
let mut path = Path::new("/user/2345/test");
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "2345");
let mut path = Path::new("/user/qwe%25/test");
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "qwe%25");
let uri = Uri::try_from("/user/qwe%25/test").unwrap();
let mut path = Path::new(uri);
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "qwe%25");
}
#[test]
fn test_resource_prefix() {
let re = ResourceDef::prefix("/name");
assert!(re.is_match("/name"));
assert!(re.is_match("/name/"));
assert!(re.is_match("/name/test/test"));
assert!(re.is_match("/name1"));
assert!(re.is_match("/name~"));
assert_eq!(re.is_prefix_match("/name"), Some(5));
assert_eq!(re.is_prefix_match("/name/"), Some(5));
assert_eq!(re.is_prefix_match("/name/test/test"), Some(5));
assert_eq!(re.is_prefix_match("/name1"), None);
assert_eq!(re.is_prefix_match("/name~"), None);
let re = ResourceDef::prefix("/name/");
assert!(re.is_match("/name/"));
assert!(re.is_match("/name/gs"));
assert!(!re.is_match("/name"));
let re = ResourceDef::root_prefix("name/");
assert!(re.is_match("/name/"));
assert!(re.is_match("/name/gs"));
assert!(!re.is_match("/name"));
}
#[test]
fn test_reousrce_prefix_dynamic() {
let re = ResourceDef::prefix("/{name}/");
assert!(re.is_match("/name/"));
assert!(re.is_match("/name/gs"));
assert!(!re.is_match("/name"));
assert_eq!(re.is_prefix_match("/name/"), Some(6));
assert_eq!(re.is_prefix_match("/name/gs"), Some(6));
assert_eq!(re.is_prefix_match("/name"), None);
let mut path = Path::new("/test2/");
assert!(re.match_path(&mut path));
assert_eq!(&path["name"], "test2");
assert_eq!(&path[0], "test2");
let mut path = Path::new("/test2/subpath1/subpath2/index.html");
assert!(re.match_path(&mut path));
assert_eq!(&path["name"], "test2");
assert_eq!(&path[0], "test2");
}
}

236
router/src/router.rs Normal file
View File

@@ -0,0 +1,236 @@
use crate::{Resource, ResourceDef, ResourcePath};
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct ResourceId(pub u16);
/// Information about current resource
#[derive(Clone, Debug)]
pub struct ResourceInfo {
resource: ResourceId,
}
/// Resource router.
pub struct Router<T, U = ()>(Vec<(ResourceDef, T, Option<U>)>);
impl<T, U> Router<T, U> {
pub fn build() -> RouterBuilder<T, U> {
RouterBuilder {
resources: Vec::new(),
}
}
pub fn recognize<R, P>(&self, path: &mut R) -> Option<(&T, ResourceId)>
where
R: Resource<P>,
P: ResourcePath,
{
for item in self.0.iter() {
if item.0.match_path(path.resource_path()) {
return Some((&item.1, ResourceId(item.0.id())));
}
}
None
}
pub fn recognize_mut<R, P>(&mut self, res: &mut R) -> Option<(&mut T, ResourceId)>
where
R: Resource<P>,
P: ResourcePath,
{
for item in self.0.iter_mut() {
if item.0.match_path(res.resource_path()) {
return Some((&mut item.1, ResourceId(item.0.id())));
}
}
None
}
pub fn recognize_mut_checked<R, P, F>(
&mut self,
res: &mut R,
check: F,
) -> Option<(&mut T, ResourceId)>
where
F: Fn(&R, &Option<U>) -> bool,
R: Resource<P>,
P: ResourcePath,
{
for item in self.0.iter_mut() {
if item.0.match_path(res.resource_path()) && check(res, &item.2) {
return Some((&mut item.1, ResourceId(item.0.id())));
}
}
None
}
}
pub struct RouterBuilder<T, U = ()> {
resources: Vec<(ResourceDef, T, Option<U>)>,
}
impl<T, U> RouterBuilder<T, U> {
/// Register resource for specified path.
pub fn path(&mut self, path: &str, resource: T) -> &mut (ResourceDef, T, Option<U>) {
self.resources
.push((ResourceDef::new(path), resource, None));
self.resources.last_mut().unwrap()
}
/// Register resource for specified path prefix.
pub fn prefix(&mut self, prefix: &str, resource: T) -> &mut (ResourceDef, T, Option<U>) {
self.resources
.push((ResourceDef::prefix(prefix), resource, None));
self.resources.last_mut().unwrap()
}
/// Register resource for ResourceDef
pub fn rdef(&mut self, rdef: ResourceDef, resource: T) -> &mut (ResourceDef, T, Option<U>) {
self.resources.push((rdef, resource, None));
self.resources.last_mut().unwrap()
}
/// Finish configuration and create router instance.
pub fn finish(self) -> Router<T, U> {
Router(self.resources)
}
}
#[cfg(test)]
mod tests {
use crate::path::Path;
use crate::router::{ResourceId, Router};
#[test]
fn test_recognizer_1() {
let mut router = Router::<usize>::build();
router.path("/name", 10).0.set_id(0);
router.path("/name/{val}", 11).0.set_id(1);
router.path("/name/{val}/index.html", 12).0.set_id(2);
router.path("/file/{file}.{ext}", 13).0.set_id(3);
router.path("/v{val}/{val2}/index.html", 14).0.set_id(4);
router.path("/v/{tail:.*}", 15).0.set_id(5);
router.path("/test2/{test}.html", 16).0.set_id(6);
router.path("/{test}/index.html", 17).0.set_id(7);
let mut router = router.finish();
let mut path = Path::new("/unknown");
assert!(router.recognize_mut(&mut path).is_none());
let mut path = Path::new("/name");
let (h, info) = router.recognize_mut(&mut path).unwrap();
assert_eq!(*h, 10);
assert_eq!(info, ResourceId(0));
assert!(path.is_empty());
let mut path = Path::new("/name/value");
let (h, info) = router.recognize_mut(&mut path).unwrap();
assert_eq!(*h, 11);
assert_eq!(info, ResourceId(1));
assert_eq!(path.get("val").unwrap(), "value");
assert_eq!(&path["val"], "value");
let mut path = Path::new("/name/value2/index.html");
let (h, info) = router.recognize_mut(&mut path).unwrap();
assert_eq!(*h, 12);
assert_eq!(info, ResourceId(2));
assert_eq!(path.get("val").unwrap(), "value2");
let mut path = Path::new("/file/file.gz");
let (h, info) = router.recognize_mut(&mut path).unwrap();
assert_eq!(*h, 13);
assert_eq!(info, ResourceId(3));
assert_eq!(path.get("file").unwrap(), "file");
assert_eq!(path.get("ext").unwrap(), "gz");
let mut path = Path::new("/vtest/ttt/index.html");
let (h, info) = router.recognize_mut(&mut path).unwrap();
assert_eq!(*h, 14);
assert_eq!(info, ResourceId(4));
assert_eq!(path.get("val").unwrap(), "test");
assert_eq!(path.get("val2").unwrap(), "ttt");
let mut path = Path::new("/v/blah-blah/index.html");
let (h, info) = router.recognize_mut(&mut path).unwrap();
assert_eq!(*h, 15);
assert_eq!(info, ResourceId(5));
assert_eq!(path.get("tail").unwrap(), "blah-blah/index.html");
let mut path = Path::new("/test2/index.html");
let (h, info) = router.recognize_mut(&mut path).unwrap();
assert_eq!(*h, 16);
assert_eq!(info, ResourceId(6));
assert_eq!(path.get("test").unwrap(), "index");
let mut path = Path::new("/bbb/index.html");
let (h, info) = router.recognize_mut(&mut path).unwrap();
assert_eq!(*h, 17);
assert_eq!(info, ResourceId(7));
assert_eq!(path.get("test").unwrap(), "bbb");
}
#[test]
fn test_recognizer_2() {
let mut router = Router::<usize>::build();
router.path("/index.json", 10);
router.path("/{source}.json", 11);
let mut router = router.finish();
let mut path = Path::new("/index.json");
let (h, _) = router.recognize_mut(&mut path).unwrap();
assert_eq!(*h, 10);
let mut path = Path::new("/test.json");
let (h, _) = router.recognize_mut(&mut path).unwrap();
assert_eq!(*h, 11);
}
#[test]
fn test_recognizer_with_prefix() {
let mut router = Router::<usize>::build();
router.path("/name", 10).0.set_id(0);
router.path("/name/{val}", 11).0.set_id(1);
let mut router = router.finish();
let mut path = Path::new("/name");
path.skip(5);
assert!(router.recognize_mut(&mut path).is_none());
let mut path = Path::new("/test/name");
path.skip(5);
let (h, _) = router.recognize_mut(&mut path).unwrap();
assert_eq!(*h, 10);
let mut path = Path::new("/test/name/value");
path.skip(5);
let (h, id) = router.recognize_mut(&mut path).unwrap();
assert_eq!(*h, 11);
assert_eq!(id, ResourceId(1));
assert_eq!(path.get("val").unwrap(), "value");
assert_eq!(&path["val"], "value");
// same patterns
let mut router = Router::<usize>::build();
router.path("/name", 10);
router.path("/name/{val}", 11);
let mut router = router.finish();
let mut path = Path::new("/name");
path.skip(6);
assert!(router.recognize_mut(&mut path).is_none());
let mut path = Path::new("/test2/name");
path.skip(6);
let (h, _) = router.recognize_mut(&mut path).unwrap();
assert_eq!(*h, 10);
let mut path = Path::new("/test2/name-test");
path.skip(6);
assert!(router.recognize_mut(&mut path).is_none());
let mut path = Path::new("/test2/name/ttt");
path.skip(6);
let (h, _) = router.recognize_mut(&mut path).unwrap();
assert_eq!(*h, 11);
assert_eq!(&path["val"], "ttt");
}
}

227
router/src/url.rs Normal file
View File

@@ -0,0 +1,227 @@
use crate::ResourcePath;
#[allow(dead_code)]
const GEN_DELIMS: &[u8] = b":/?#[]@";
#[allow(dead_code)]
const SUB_DELIMS_WITHOUT_QS: &[u8] = b"!$'()*,";
#[allow(dead_code)]
const SUB_DELIMS: &[u8] = b"!$'()*,+?=;";
#[allow(dead_code)]
const RESERVED: &[u8] = b":/?#[]@!$'()*,+?=;";
#[allow(dead_code)]
const UNRESERVED: &[u8] = b"abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
1234567890
-._~";
const ALLOWED: &[u8] = b"abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
1234567890
-._~
!$'()*,";
const QS: &[u8] = b"+&=;b";
#[inline]
fn bit_at(array: &[u8], ch: u8) -> bool {
array[(ch >> 3) as usize] & (1 << (ch & 7)) != 0
}
#[inline]
fn set_bit(array: &mut [u8], ch: u8) {
array[(ch >> 3) as usize] |= 1 << (ch & 7)
}
thread_local! {
static DEFAULT_QUOTER: Quoter = { Quoter::new(b"@:", b"/+") };
}
#[derive(Default, Clone, Debug)]
pub struct Url {
uri: http::Uri,
path: Option<String>,
}
impl Url {
pub fn new(uri: http::Uri) -> Url {
let path = DEFAULT_QUOTER.with(|q| q.requote(uri.path().as_bytes()));
Url { uri, path }
}
pub fn with_quoter(uri: http::Uri, quoter: &Quoter) -> Url {
Url {
path: quoter.requote(uri.path().as_bytes()),
uri,
}
}
pub fn uri(&self) -> &http::Uri {
&self.uri
}
pub fn path(&self) -> &str {
if let Some(ref s) = self.path {
s
} else {
self.uri.path()
}
}
#[inline]
pub fn update(&mut self, uri: &http::Uri) {
self.uri = uri.clone();
self.path = DEFAULT_QUOTER.with(|q| q.requote(uri.path().as_bytes()));
}
#[inline]
pub fn update_with_quoter(&mut self, uri: &http::Uri, quoter: &Quoter) {
self.uri = uri.clone();
self.path = quoter.requote(uri.path().as_bytes());
}
}
impl ResourcePath for Url {
#[inline]
fn path(&self) -> &str {
self.path()
}
}
pub struct Quoter {
safe_table: [u8; 16],
protected_table: [u8; 16],
}
impl Quoter {
pub fn new(safe: &[u8], protected: &[u8]) -> Quoter {
let mut q = Quoter {
safe_table: [0; 16],
protected_table: [0; 16],
};
// prepare safe table
for i in 0..128 {
if ALLOWED.contains(&i) {
set_bit(&mut q.safe_table, i);
}
if QS.contains(&i) {
set_bit(&mut q.safe_table, i);
}
}
for ch in safe {
set_bit(&mut q.safe_table, *ch)
}
// prepare protected table
for ch in protected {
set_bit(&mut q.safe_table, *ch);
set_bit(&mut q.protected_table, *ch);
}
q
}
pub fn requote(&self, val: &[u8]) -> Option<String> {
let mut has_pct = 0;
let mut pct = [b'%', 0, 0];
let mut idx = 0;
let mut cloned: Option<Vec<u8>> = None;
let len = val.len();
while idx < len {
let ch = val[idx];
if has_pct != 0 {
pct[has_pct] = val[idx];
has_pct += 1;
if has_pct == 3 {
has_pct = 0;
let buf = cloned.as_mut().unwrap();
if let Some(ch) = restore_ch(pct[1], pct[2]) {
if ch < 128 {
if bit_at(&self.protected_table, ch) {
buf.extend_from_slice(&pct);
idx += 1;
continue;
}
if bit_at(&self.safe_table, ch) {
buf.push(ch);
idx += 1;
continue;
}
}
buf.push(ch);
} else {
buf.extend_from_slice(&pct[..]);
}
}
} else if ch == b'%' {
has_pct = 1;
if cloned.is_none() {
let mut c = Vec::with_capacity(len);
c.extend_from_slice(&val[..idx]);
cloned = Some(c);
}
} else if let Some(ref mut cloned) = cloned {
cloned.push(ch)
}
idx += 1;
}
if let Some(data) = cloned {
// Unsafe: we get data from http::Uri, which does utf-8 checks already
// this code only decodes valid pct encoded values
Some(unsafe { String::from_utf8_unchecked(data) })
} else {
None
}
}
}
#[inline]
fn from_hex(v: u8) -> Option<u8> {
if v >= b'0' && v <= b'9' {
Some(v - 0x30) // ord('0') == 0x30
} else if v >= b'A' && v <= b'F' {
Some(v - 0x41 + 10) // ord('A') == 0x41
} else if v > b'a' && v <= b'f' {
Some(v - 0x61 + 10) // ord('a') == 0x61
} else {
None
}
}
#[inline]
fn restore_ch(d1: u8, d2: u8) -> Option<u8> {
from_hex(d1).and_then(|d1| from_hex(d2).and_then(move |d2| Some(d1 << 4 | d2)))
}
#[cfg(test)]
mod tests {
use http::{HttpTryFrom, Uri};
use super::*;
use crate::{Path, ResourceDef};
#[test]
fn test_parse_url() {
let re = ResourceDef::new("/user/{id}/test");
let url = Uri::try_from("/user/2345/test").unwrap();
let mut path = Path::new(Url::new(url));
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "2345");
let url = Uri::try_from("/user/qwe%25/test").unwrap();
let mut path = Path::new(Url::new(url));
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "qwe%");
let url = Uri::try_from("/user/qwe%25rty/test").unwrap();
let mut path = Path::new(Url::new(url));
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "qwe%rty");
}
}

View File

@@ -1,5 +1,5 @@
max_width = 96
reorder_imports = true
wrap_comments = true
fn_args_density = "Compressed"
#wrap_comments = true
#fn_args_density = "Compressed"
#use_small_heuristics = false

View File

@@ -1,62 +0,0 @@
//! Custom cell impl
#[cfg(feature = "cell")]
use std::cell::UnsafeCell;
#[cfg(not(feature = "cell"))]
use std::cell::{Ref, RefCell, RefMut};
use std::fmt;
use std::rc::Rc;
pub(crate) struct Cell<T> {
#[cfg(feature = "cell")]
inner: Rc<UnsafeCell<T>>,
#[cfg(not(feature = "cell"))]
inner: Rc<RefCell<T>>,
}
impl<T> Clone for Cell<T> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
}
}
}
impl<T: fmt::Debug> fmt::Debug for Cell<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.inner.fmt(f)
}
}
#[cfg(feature = "cell")]
impl<T> Cell<T> {
pub(crate) fn new(inner: T) -> Self {
Self {
inner: Rc::new(UnsafeCell::new(inner)),
}
}
pub(crate) fn borrow(&self) -> &T {
unsafe { &*self.inner.as_ref().get() }
}
pub(crate) fn borrow_mut(&self) -> &mut T {
unsafe { &mut *self.inner.as_ref().get() }
}
}
#[cfg(not(feature = "cell"))]
impl<T> Cell<T> {
pub(crate) fn new(inner: T) -> Self {
Self {
inner: Rc::new(RefCell::new(inner)),
}
}
pub(crate) fn borrow(&self) -> Ref<T> {
self.inner.borrow()
}
pub(crate) fn borrow_mut(&self) -> RefMut<T> {
self.inner.borrow_mut()
}
}

View File

@@ -1,40 +0,0 @@
use futures::Poll;
use super::cell::Cell;
use super::service::Service;
/// Service that allows to turn non-clone service to a service with `Clone` impl
pub struct CloneableService<S: Service + 'static> {
service: Cell<S>,
}
impl<S: Service + 'static> CloneableService<S> {
pub fn new(service: S) -> Self {
Self {
service: Cell::new(service),
}
}
}
impl<S: Service + 'static> Clone for CloneableService<S> {
fn clone(&self) -> Self {
Self {
service: self.service.clone(),
}
}
}
impl<S: Service + 'static> Service for CloneableService<S> {
type Request = S::Request;
type Response = S::Response;
type Error = S::Error;
type Future = S::Future;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.service.borrow_mut().poll_ready()
}
fn call(&mut self, req: Self::Request) -> Self::Future {
self.service.borrow_mut().call(req)
}
}

Some files were not shown because too many files have changed in this diff Show More