├── .gitignore ├── .project ├── .settings └── org.eclipse.m2e.core.prefs ├── .travis.settings.xml ├── .travis.yml ├── LICENSE ├── README.md ├── core ├── .project ├── pom.xml └── src │ └── main │ └── java │ └── io │ └── reactiverse │ └── reactivecontexts │ └── core │ ├── CompletableFutureWrapper.java │ ├── CompletionStageWrapper.java │ ├── Context.java │ ├── ContextPropagator.java │ ├── ContextProvider.java │ ├── ContextState.java │ └── package-info.java ├── docs ├── Gemfile ├── README.md └── _config.yml ├── pom.xml ├── propagators-rxjava1 ├── .project ├── pom.xml └── src │ └── main │ ├── java │ └── io │ │ └── reactiverse │ │ └── reactivecontexts │ │ └── propagators │ │ └── rxjava1 │ │ ├── ContextPropagatorOnCompleteCreateAction.java │ │ ├── ContextPropagatorOnObservableCreateAction.java │ │ ├── ContextPropagatorOnSingleCreateAction.java │ │ └── RxJava1ContextPropagator.java │ └── resources │ └── META-INF │ └── services │ └── io.reactiverse.reactivecontexts.core.ContextPropagator ├── propagators-rxjava2 ├── .project ├── pom.xml └── src │ └── main │ ├── java │ └── io │ │ └── reactiverse │ │ └── reactivecontexts │ │ └── propagators │ │ └── rxjava2 │ │ ├── ContextPropagatorOnCompletableAssemblyAction.java │ │ ├── ContextPropagatorOnCompletableCreateAction.java │ │ ├── ContextPropagatorOnFlowableAssemblyAction.java │ │ ├── ContextPropagatorOnFlowableCreateAction.java │ │ ├── ContextPropagatorOnMaybeAssemblyAction.java │ │ ├── ContextPropagatorOnMaybeCreateAction.java │ │ ├── ContextPropagatorOnObservableAssemblyAction.java │ │ ├── ContextPropagatorOnObservableCreateAction.java │ │ ├── ContextPropagatorOnSingleAssemblyAction.java │ │ ├── ContextPropagatorOnSingleCreateAction.java │ │ └── RxJava2ContextPropagator.java │ └── resources │ └── META-INF │ └── services │ └── io.reactiverse.reactivecontexts.core.ContextPropagator └── tests ├── .project ├── pom.xml └── src ├── main ├── java │ └── io │ │ └── reactiverse │ │ └── reactivecontexts │ │ └── test │ │ ├── MyContext.java │ │ └── MyContextProvider.java └── resources │ └── META-INF │ └── services │ └── io.reactiverse.reactivecontexts.core.ContextProvider └── test └── java └── io └── reactiverse └── reactivecontexts └── test ├── BackPressureExceptionTest.java ├── ManualPropagationMultipleRequestTest.java ├── RxJava1MultipleRequestTest.java ├── RxJava1Test.java └── RxJava2Test.java /.gitignore: -------------------------------------------------------------------------------- 1 | */target 2 | */.classpath 3 | */.settings 4 | .settings 5 | .classpath 6 | -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | reactive-contexts-parent 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.m2e.core.maven2Builder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.m2e.core.maven2Nature 16 | 17 | 18 | -------------------------------------------------------------------------------- /.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /.travis.settings.xml: -------------------------------------------------------------------------------- 1 | 4 | 5 | false 6 | 7 | 8 | 9 | sonatype-repository 10 | 11 | 12 | sonatype-nexus-snapshots 13 | https://oss.sonatype.org/content/repositories/snapshots 14 | 15 | true 16 | 17 | default 18 | 19 | false 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | sonatype-repository 28 | 29 | 30 | 31 | 32 | sonatype-nexus-snapshots 33 | ${env.SONATYPE_NEXUS_USERNAME} 34 | ${env.SONATYPE_NEXUS_PASSWORD} 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | notifications: 3 | email: 4 | recipients: 5 | - stef@epardaud.fr 6 | on_success: always 7 | on_failure: always 8 | deploy: 9 | provider: script 10 | script: "cp .travis.settings.xml $HOME/.m2/settings.xml && mvn -X deploy" 11 | skip_cleanup: true 12 | on: 13 | branch: master 14 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Reactive Contexts 2 | 3 | [![Build Status](https://travis-ci.com/reactiverse/reactive-contexts.svg?branch=master)](https://travis-ci.com/reactiverse/reactive-contexts) 4 | 5 | Reactive Contexts is a library that allows you to capture contexts from various providers ([RESTEasy](https://resteasy.github.io), 6 | [Redpipe](http://redpipe.net), [Weld](http://weld.cdi-spec.org)) 7 | and propagate them along the reactive flow of various propagators ([RxJava1, RxJava2](https://github.com/ReactiveX/RxJava)). 8 | 9 | # License 10 | 11 | Reactive Contexts is licensed under the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0) terms. 12 | 13 | # The problem with contexts and reactive libraries 14 | 15 | Many libraries (for example: RESTEasy, [CDI](http://cdi-spec.org)) use a thread-local context that holds information required by user-executing 16 | code (in the case of RESTEasy: the current request, response and many other useful information so that the resource 17 | method can look them up when executed). 18 | 19 | This works well in settings where you have one thread per operation, but stops working if the operation spawns other 20 | threads, or gets executed in other threads, or simply later, as is the case in many Reactive libraries, such as RxJava, 21 | where users code is spread between the subscriber, operations such as filter/map, and producers, all of which can be 22 | executed in different thread schedulers. 23 | 24 | For example, the following RESTEasy/RxJava code works out of the box with the latest version of RESTEasy: 25 | 26 | @GET 27 | @Path("reactive-nodelay") 28 | public Single reactiveNoDelay(@Context UriInfo uriInfo){ 29 | return Single.just("hello") 30 | .map(str -> str + " from: "+uriInfo.getAbsolutePath()); 31 | } 32 | 33 | And will display something like `hello from: http://localhost:8081/reactive-nodelay`. 34 | 35 | But if you introduce a delay, which is only one of the many ways to introduce a thread-switch from RxJava: 36 | 37 | @GET 38 | @Path("reactive-delay") 39 | public Single reactiveDelay(@Context UriInfo uriInfo){ 40 | return Single.just("hello") 41 | .delay(1, TimeUnit.SECONDS) 42 | .map(str -> str + " from: "+uriInfo.getAbsolutePath()); 43 | } 44 | 45 | Then it breaks down with `RESTEASY003880: Unable to find contextual data of type: javax.ws.rs.core.UriInfo`. 46 | 47 | This is due to the fact that RESTEasy doesn't know that RxJava is going to schedule the delayed `map` operation 48 | into a different scheduler, on a thread which doesn't have the RESTEasy context set-up in a thread-local. 49 | 50 | This is not RESTEasy's fault: the exact same error will happen if you try to use CDI at that point, for the exact 51 | same reason. Many existing libraries rely on thread-locals for context propagation, and it does not work in the 52 | async/Reactive world. 53 | 54 | RxJava supports a system of hooks/plugins that we can use to capture and restore context, but there can only be 55 | one such hook/plugin, so if RESTEasy uses it, CDI cannot use it. Also, there would be a lot of code duplication 56 | as propagating contexts with RxJava hooks/plugins is not trivial. 57 | 58 | # The solution 59 | 60 | In order to enable automatic context propagation of any number of contexts, Reactive Context uses a system of plugins 61 | for saving/restoring contexts: `ContextProvider`, and plugins that hook into Reactive libraries/schedulers in 62 | order to use the `Context` API for saving/restoring all contexts: `ContextPropagator`. 63 | 64 | If your context-using framework is supported, and your Reactive library/scheduler is supported too, then all your 65 | contexts will be automatically propagated and your code will look great. If not, add support for your 66 | `ContextProvider` or `ContextPropagator`. If it's not possible, you can still use manual context 67 | propagation by accessing directly the `Context` API. 68 | 69 | To get back to our original problematic code: 70 | 71 | @GET 72 | @Path("reactive-delay") 73 | public Single reactiveDelay(@Context UriInfo uriInfo){ 74 | return Single.just("hello") 75 | .delay(1, TimeUnit.SECONDS) 76 | .map(str -> str + " from: "+uriInfo.getAbsolutePath()); 77 | } 78 | 79 | Will work fine if you use the RESTEasy `ContextProvider` with the RxJava2 `ContextPropagator`, without any change 80 | in your code. Automatic context propagation FTW! 81 | 82 | # Usage 83 | 84 | Import the following Maven module: 85 | 86 | ```xml 87 | 88 | io.reactiverse 89 | reactive-contexts-core 90 | 1.0.0 91 | 92 | ``` 93 | 94 | Then call `io.reactiverse.reactivecontexts.core.Context.load();` and your contexts will be propagated, depending on the 95 | presence of the following optional plugins in your classpath: 96 | 97 | artifactId | Description 98 | --- | --- 99 | `reactive-contexts-core` | Core engine 100 | `reactive-contexts-propagators-rxjava1` | Propagates contexts for RxJava1 101 | `reactive-contexts-propagators-rxjava2` | Propagates contexts for RxJava2 102 | 103 | If you are using RxJava 1 or 2, you don't need anything to propagate your contexts: every RxJava type (`Single`, 104 | `Flowable`…) will have the right contexts automatically propagated. If you are using reactive types that don't 105 | have a `reactive-contexts-propagator` plugin, such as `CompletionStage` in the JDK, see [below for how to manually 106 | propagate contexts](#manual-context-propagation) 107 | 108 | # Building 109 | 110 | Clone this repository, and run: 111 | 112 | ```shell 113 | $ mvn clean install 114 | ``` 115 | 116 | # For context providers 117 | 118 | If you have a context that your library provides and requires, which is often stored in thread-local 119 | variables, it's very likely it won't work with reactive applications that register callbacks and 120 | invoke them later in various threads. 121 | 122 | In order for your library to have its context propagated to all supported reactive libraries, you 123 | can implement the `io.reactiverse.reactivecontexts.core.ContextProvider` interface and specify how 124 | you can save and restore your context: 125 | 126 | ```java 127 | package my.library; 128 | 129 | public class MyContextProvider implements ContextProvider { 130 | 131 | @Override 132 | public MyState install(MyState state) { 133 | MyState previousState = MyContext.getState(); 134 | MyContext.setState(state); 135 | return previousState; 136 | } 137 | 138 | @Override 139 | public void restore(MyState previousState) { 140 | MyContext.setState(previousState); 141 | } 142 | 143 | @Override 144 | public MyState capture() { 145 | return MyContext.getState(); 146 | } 147 | } 148 | ``` 149 | 150 | Then you declare a `META-INF/services/io.reactiverse.reactivecontexts.core.ContextProvider` file which 151 | lists your fully-qualified class name implementing the `ContextProvider` interface (in this case 152 | `my.library.MyContextProvider`) and include it in your classpath. 153 | 154 | Upon initialisation, your context provider implementation will automatically be loaded and your 155 | context will be propagated to all supported reactive libraries. 156 | 157 | # For context propagators 158 | 159 | If you have a reactive library that supports scheduling of callbacks on various threads, you will need 160 | to register a `ContextPropagator` implementation that will be called by the `reactive-contexts` library, 161 | where you will register any required plumbing on the reactive library, to make sure it will properly 162 | propagate all contexts during scheduling. 163 | 164 | For example, here is how the RxJava1 propagator is implemented: 165 | 166 | ```java 167 | public class RxJava1ContextPropagator implements ContextPropagator { 168 | 169 | public void setup() { 170 | RxJavaHooks.setOnSingleCreate(new ContextPropagatorOnSingleCreateAction()); 171 | // ... 172 | } 173 | } 174 | ``` 175 | 176 | Don't forget to list your context propagator's fully-qualified class names in the 177 | `META-INF/services/io.reactiverse.reactivecontexts.core.ContextPropagator` file, and to include it in 178 | your classpath. 179 | 180 | Your plugin can capture all current contexts with `Context.capture()`, then install captured contexts with 181 | `Context.install(contexts)` and restore them with `Context.restore(contexts)`. 182 | 183 | For example, here is how contexts are propagated for RxJava1 `Single`: 184 | 185 | ```java 186 | public class ContextPropagatorOnSingleCreateAction implements Func1 { 187 | 188 | @Override 189 | public OnSubscribe call(OnSubscribe t) { 190 | return new ContextCapturerSingle(t); 191 | } 192 | 193 | final static class ContextCapturerSingle implements Single.OnSubscribe { 194 | 195 | final Single.OnSubscribe source; 196 | 197 | private ContextState states; 198 | 199 | public ContextCapturerSingle(Single.OnSubscribe source) { 200 | this.source = source; 201 | // capture the context 202 | states = Context.capture(); 203 | } 204 | 205 | @Override 206 | public void call(SingleSubscriber t) { 207 | // restore the context for subscription 208 | ContextState previousStates = states.install(); 209 | try { 210 | source.call(new OnAssemblySingleSubscriber(t, states)); 211 | }finally { 212 | previousStates.restore(); 213 | } 214 | } 215 | 216 | static final class OnAssemblySingleSubscriber extends SingleSubscriber { 217 | 218 | final SingleSubscriber actual; 219 | private final ContextState states; 220 | 221 | 222 | public OnAssemblySingleSubscriber(SingleSubscriber actual, ContextState states) { 223 | this.actual = actual; 224 | this.states = states; 225 | actual.add(this); 226 | } 227 | 228 | @Override 229 | public void onError(Throwable e) { 230 | // propagate the context for listeners 231 | ContextState previousStates = states.install(); 232 | try { 233 | actual.onError(e); 234 | }finally { 235 | previousStates.restore(); 236 | } 237 | } 238 | 239 | @Override 240 | public void onSuccess(T t) { 241 | // propagate the context for listeners 242 | ContextState previousStates = states.install(); 243 | try { 244 | actual.onSuccess(t); 245 | }finally { 246 | previousStates.restore(); 247 | } 248 | } 249 | } 250 | } 251 | 252 | } 253 | ``` 254 | 255 | ## Manual context propagation 256 | 257 | If you have a library that uses reactive types that don't support hooks, such as the JDK's `CompletionStage`, 258 | you will have to manually capture and restore contexts, for example: 259 | 260 | ```java 261 | CompletionStage userResponse = invokeUserAction(); 262 | ContextState states = Context.capture(); 263 | userResponse.thenAccept(response -> { 264 | ContextState previousStates = states.install(); 265 | try { 266 | writeResponse(response); 267 | }finally { 268 | previousStates.restore(); 269 | } 270 | }); 271 | ``` 272 | 273 | Alternately, you can use `Context.wrap` to propagate reactive contexts to many functional interfaces, for example: 274 | 275 | ```java 276 | CompletionStage userResponse = Context.wrap(invokeUserAction()); 277 | userResponse.thenAccept(response -> writeResponse(response)); 278 | ``` 279 | 280 | # Threads, class loaders 281 | 282 | If you are using a flat classpath, this is all you need to know. If you're using a modular class loader, 283 | or need to have several independent `Context` objects, each with their own list of providers and 284 | propagators, then you need to stop using the global `Context` instance and create your own. 285 | 286 | You can create your own Context with `new Context()`, then set it as a thread-local with 287 | `Context.setThreadInstance(Context)`, and when you're done you can clear the thread-local with 288 | `Context.clearThreadInstance()`. 289 | 290 | Note that each captured context state will restore the proper Context thread-local when 291 | calling `ContextState.install()` and `ContextState.restore()`, so as to avoid 292 | interference. 293 | 294 | -------------------------------------------------------------------------------- /core/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | core 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.jdt.core.javanature 21 | org.eclipse.m2e.core.maven2Nature 22 | 23 | 24 | -------------------------------------------------------------------------------- /core/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | io.reactiverse 7 | reactive-contexts-parent 8 | 1.0.2-SNAPSHOT 9 | 10 | reactive-contexts-core 11 | reactive-contexts-core 12 | http://maven.apache.org 13 | 14 | UTF-8 15 | 16 | 17 | 18 | junit 19 | junit 20 | test 21 | 22 | 23 | 24 | 25 | 26 | org.apache.maven.plugins 27 | maven-source-plugin 28 | 29 | 30 | org.apache.maven.plugins 31 | maven-javadoc-plugin 32 | 33 | 34 | 35 | 36 | 37 | release 38 | 39 | 40 | 41 | org.apache.maven.plugins 42 | maven-gpg-plugin 43 | 44 | 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /core/src/main/java/io/reactiverse/reactivecontexts/core/CompletableFutureWrapper.java: -------------------------------------------------------------------------------- 1 | package io.reactiverse.reactivecontexts.core; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | import java.util.concurrent.CompletionStage; 5 | import java.util.concurrent.ExecutionException; 6 | import java.util.concurrent.Executor; 7 | import java.util.concurrent.TimeUnit; 8 | import java.util.concurrent.TimeoutException; 9 | import java.util.function.BiConsumer; 10 | import java.util.function.BiFunction; 11 | import java.util.function.Consumer; 12 | import java.util.function.Function; 13 | 14 | final class CompletableFutureWrapper extends CompletableFuture { 15 | private final ContextState state; 16 | private final CompletableFuture f; 17 | 18 | CompletableFutureWrapper(ContextState state, CompletableFuture f) { 19 | this.state = state; 20 | this.f = f; 21 | } 22 | 23 | @Override 24 | public boolean complete(T value) { 25 | return f.complete(value); 26 | } 27 | 28 | @Override 29 | public boolean completeExceptionally(Throwable ex) { 30 | return f.completeExceptionally(ex); 31 | } 32 | 33 | @Override 34 | public boolean cancel(boolean mayInterruptIfRunning) { 35 | return f.cancel(mayInterruptIfRunning); 36 | } 37 | 38 | @Override 39 | public boolean isCancelled() { 40 | return f.isCancelled(); 41 | } 42 | 43 | @Override 44 | public boolean isCompletedExceptionally() { 45 | return f.isCompletedExceptionally(); 46 | } 47 | 48 | @Override 49 | public void obtrudeValue(T value) { 50 | f.obtrudeValue(value); 51 | } 52 | 53 | @Override 54 | public void obtrudeException(Throwable ex) { 55 | f.obtrudeException(ex); 56 | } 57 | 58 | @Override 59 | public int getNumberOfDependents() { 60 | return f.getNumberOfDependents(); 61 | } 62 | 63 | @Override 64 | public boolean isDone() { 65 | return f.isDone(); 66 | } 67 | 68 | @Override 69 | public T get() throws InterruptedException, ExecutionException { 70 | return f.get(); 71 | } 72 | 73 | @Override 74 | public T get(long timeout, TimeUnit unit) 75 | throws InterruptedException, ExecutionException, TimeoutException { 76 | return f.get(timeout, unit); 77 | } 78 | 79 | @Override 80 | public T join() { 81 | return f.join(); 82 | } 83 | 84 | @Override 85 | public T getNow(T valueIfAbsent) { 86 | return f.getNow(valueIfAbsent); 87 | } 88 | 89 | @Override 90 | public CompletableFuture toCompletableFuture() { 91 | return this; 92 | } 93 | 94 | @Override 95 | public CompletableFuture exceptionally(Function fn) { 96 | return Context.wrap(state, f.exceptionally(Context.wrap(state, fn))); 97 | } 98 | 99 | @Override 100 | public CompletableFuture handle(BiFunction fn) { 101 | return Context.wrap(state, f.handle(Context.wrap(state, fn))); 102 | } 103 | 104 | @Override 105 | public CompletableFuture handleAsync(BiFunction fn) { 106 | return Context.wrap(state, f.handleAsync(Context.wrap(state, fn))); 107 | } 108 | 109 | @Override 110 | public CompletableFuture handleAsync(BiFunction fn, 111 | Executor executor) { 112 | return Context.wrap(state, f.handleAsync(Context.wrap(state, fn), executor)); 113 | } 114 | 115 | @Override 116 | public CompletableFuture thenApply(Function fn) { 117 | return Context.wrap(state, f.thenApply(Context.wrap(state, fn))); 118 | } 119 | 120 | @Override 121 | public CompletableFuture thenApplyAsync(Function fn) { 122 | return Context.wrap(state, f.thenApplyAsync(Context.wrap(state, fn))); 123 | } 124 | 125 | @Override 126 | public CompletableFuture thenApplyAsync(Function fn, Executor executor) { 127 | return Context.wrap(state, f.thenApplyAsync(Context.wrap(state, fn), executor)); 128 | } 129 | 130 | @Override 131 | public CompletableFuture thenAccept(Consumer action) { 132 | return Context.wrap(state, f.thenAccept(Context.wrap(state, action))); 133 | } 134 | 135 | @Override 136 | public CompletableFuture thenAcceptAsync(Consumer action) { 137 | return Context.wrap(state, f.thenAcceptAsync(Context.wrap(state, action))); 138 | } 139 | 140 | @Override 141 | public CompletableFuture thenAcceptAsync(Consumer action, Executor executor) { 142 | return Context.wrap(state, f.thenAcceptAsync(Context.wrap(state, action), executor)); 143 | } 144 | 145 | @Override 146 | public CompletableFuture thenRun(Runnable action) { 147 | return Context.wrap(state, f.thenRun(Context.wrap(state, action))); 148 | } 149 | 150 | @Override 151 | public CompletableFuture thenRunAsync(Runnable action) { 152 | return Context.wrap(state, f.thenRunAsync(Context.wrap(state, action))); 153 | } 154 | 155 | @Override 156 | public CompletableFuture thenRunAsync(Runnable action, Executor executor) { 157 | return Context.wrap(state, f.thenRunAsync(Context.wrap(state, action), executor)); 158 | } 159 | 160 | @Override 161 | public CompletableFuture thenCombine(CompletionStage other, 162 | BiFunction fn) { 163 | return Context.wrap(state, f.thenCombine(other, Context.wrap(state, fn))); 164 | } 165 | 166 | @Override 167 | public CompletableFuture thenCombineAsync(CompletionStage other, 168 | BiFunction fn) { 169 | return Context.wrap(state, f.thenCombineAsync(other, Context.wrap(state, fn))); 170 | } 171 | 172 | @Override 173 | public CompletableFuture thenCombineAsync(CompletionStage other, 174 | BiFunction fn, Executor executor) { 175 | return Context.wrap(state, f.thenCombineAsync(other, Context.wrap(state, fn), executor)); 176 | } 177 | 178 | @Override 179 | public CompletableFuture thenAcceptBoth(CompletionStage other, 180 | BiConsumer action) { 181 | return Context.wrap(state, f.thenAcceptBoth(other, Context.wrap(state, action))); 182 | } 183 | 184 | @Override 185 | public CompletableFuture thenAcceptBothAsync(CompletionStage other, 186 | BiConsumer action) { 187 | return Context.wrap(state, f.thenAcceptBothAsync(other, Context.wrap(state, action))); 188 | } 189 | 190 | @Override 191 | public CompletableFuture thenAcceptBothAsync(CompletionStage other, 192 | BiConsumer action, Executor executor) { 193 | return Context.wrap(state, f.thenAcceptBothAsync(other, Context.wrap(state, action), executor)); 194 | } 195 | 196 | @Override 197 | public CompletableFuture runAfterBoth(CompletionStage other, Runnable action) { 198 | return Context.wrap(state, f.runAfterBoth(other, Context.wrap(state, action))); 199 | } 200 | 201 | @Override 202 | public CompletableFuture runAfterBothAsync(CompletionStage other, Runnable action) { 203 | return Context.wrap(state, f.runAfterBothAsync(other, Context.wrap(state, action))); 204 | } 205 | 206 | @Override 207 | public CompletableFuture runAfterBothAsync(CompletionStage other, Runnable action, 208 | Executor executor) { 209 | return Context.wrap(state, f.runAfterBothAsync(other, Context.wrap(state, action), executor)); 210 | } 211 | 212 | @Override 213 | public CompletableFuture applyToEither(CompletionStage other, 214 | Function fn) { 215 | return Context.wrap(state, f.applyToEither(other, Context.wrap(state, fn))); 216 | } 217 | 218 | @Override 219 | public CompletableFuture applyToEitherAsync(CompletionStage other, 220 | Function fn) { 221 | return Context.wrap(state, f.applyToEitherAsync(other, Context.wrap(state, fn))); 222 | } 223 | 224 | @Override 225 | public CompletableFuture applyToEitherAsync(CompletionStage other, 226 | Function fn, Executor executor) { 227 | return Context.wrap(state, f.applyToEitherAsync(other, Context.wrap(state, fn), executor)); 228 | } 229 | 230 | @Override 231 | public CompletableFuture acceptEither(CompletionStage other, 232 | Consumer action) { 233 | return Context.wrap(state, f.acceptEither(other, Context.wrap(state, action))); 234 | } 235 | 236 | @Override 237 | public CompletableFuture acceptEitherAsync(CompletionStage other, 238 | Consumer action) { 239 | return Context.wrap(state, f.acceptEitherAsync(other, Context.wrap(state, action))); 240 | } 241 | 242 | @Override 243 | public CompletableFuture acceptEitherAsync(CompletionStage other, 244 | Consumer action, Executor executor) { 245 | return Context.wrap(state, f.acceptEitherAsync(other, Context.wrap(state, action), executor)); 246 | } 247 | 248 | @Override 249 | public CompletableFuture runAfterEither(CompletionStage other, Runnable action) { 250 | return Context.wrap(state, f.runAfterEither(other, Context.wrap(state, action))); 251 | } 252 | 253 | @Override 254 | public CompletableFuture runAfterEitherAsync(CompletionStage other, Runnable action) { 255 | return Context.wrap(state, f.runAfterEitherAsync(other, Context.wrap(state, action))); 256 | } 257 | 258 | @Override 259 | public CompletableFuture runAfterEitherAsync(CompletionStage other, Runnable action, 260 | Executor executor) { 261 | return Context.wrap(state, f.runAfterEitherAsync(other, Context.wrap(state, action), executor)); 262 | } 263 | 264 | @Override 265 | public CompletableFuture thenCompose(Function> fn) { 266 | return Context.wrap(state, f.thenCompose(Context.wrap(state, fn))); 267 | } 268 | 269 | @Override 270 | public CompletableFuture thenComposeAsync(Function> fn) { 271 | return Context.wrap(state, f.thenComposeAsync(Context.wrap(state, fn))); 272 | } 273 | 274 | @Override 275 | public CompletableFuture thenComposeAsync(Function> fn, 276 | Executor executor) { 277 | return Context.wrap(state, f.thenComposeAsync(Context.wrap(state, fn), executor)); 278 | } 279 | 280 | @Override 281 | public CompletableFuture whenComplete(BiConsumer action) { 282 | return Context.wrap(state, f.whenComplete(Context.wrap(state, action))); 283 | } 284 | 285 | @Override 286 | public CompletableFuture whenCompleteAsync(BiConsumer action) { 287 | return Context.wrap(state, f.whenCompleteAsync(Context.wrap(state, action))); 288 | } 289 | 290 | @Override 291 | public CompletableFuture whenCompleteAsync(BiConsumer action, 292 | Executor executor) { 293 | return Context.wrap(state, f.whenCompleteAsync(Context.wrap(state, action), executor)); 294 | } 295 | 296 | @Override 297 | public String toString() { 298 | return f.toString(); 299 | } 300 | 301 | @Override 302 | public int hashCode() { 303 | return f.hashCode(); 304 | } 305 | 306 | @Override 307 | public boolean equals(Object obj) { 308 | return f.equals(obj); 309 | } 310 | } -------------------------------------------------------------------------------- /core/src/main/java/io/reactiverse/reactivecontexts/core/CompletionStageWrapper.java: -------------------------------------------------------------------------------- 1 | package io.reactiverse.reactivecontexts.core; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | import java.util.concurrent.CompletionStage; 5 | import java.util.concurrent.Executor; 6 | import java.util.function.BiConsumer; 7 | import java.util.function.BiFunction; 8 | import java.util.function.Consumer; 9 | import java.util.function.Function; 10 | 11 | final class CompletionStageWrapper implements CompletionStage { 12 | private final ContextState state; 13 | private final CompletionStage f; 14 | 15 | CompletionStageWrapper(ContextState state, CompletionStage f) { 16 | this.state = state; 17 | this.f = f; 18 | } 19 | 20 | @Override 21 | public CompletableFuture toCompletableFuture() { 22 | return Context.wrap(f.toCompletableFuture()); 23 | } 24 | 25 | @Override 26 | public CompletionStage exceptionally(Function fn) { 27 | return Context.wrap(state, f.exceptionally(Context.wrap(state, fn))); 28 | } 29 | 30 | @Override 31 | public CompletionStage handle(BiFunction fn) { 32 | return Context.wrap(state, f.handle(Context.wrap(state, fn))); 33 | } 34 | 35 | @Override 36 | public CompletionStage handleAsync(BiFunction fn) { 37 | return Context.wrap(state, f.handleAsync(Context.wrap(state, fn))); 38 | } 39 | 40 | @Override 41 | public CompletionStage handleAsync(BiFunction fn, 42 | Executor executor) { 43 | return Context.wrap(state, f.handleAsync(Context.wrap(state, fn), executor)); 44 | } 45 | 46 | @Override 47 | public CompletionStage thenApply(Function fn) { 48 | return Context.wrap(state, f.thenApply(Context.wrap(state, fn))); 49 | } 50 | 51 | @Override 52 | public CompletionStage thenApplyAsync(Function fn) { 53 | return Context.wrap(state, f.thenApplyAsync(Context.wrap(state, fn))); 54 | } 55 | 56 | @Override 57 | public CompletionStage thenApplyAsync(Function fn, Executor executor) { 58 | return Context.wrap(state, f.thenApplyAsync(Context.wrap(state, fn), executor)); 59 | } 60 | 61 | @Override 62 | public CompletionStage thenAccept(Consumer action) { 63 | return Context.wrap(state, f.thenAccept(Context.wrap(state, action))); 64 | } 65 | 66 | @Override 67 | public CompletionStage thenAcceptAsync(Consumer action) { 68 | return Context.wrap(state, f.thenAcceptAsync(Context.wrap(state, action))); 69 | } 70 | 71 | @Override 72 | public CompletionStage thenAcceptAsync(Consumer action, Executor executor) { 73 | return Context.wrap(state, f.thenAcceptAsync(Context.wrap(state, action), executor)); 74 | } 75 | 76 | @Override 77 | public CompletionStage thenRun(Runnable action) { 78 | return Context.wrap(state, f.thenRun(Context.wrap(state, action))); 79 | } 80 | 81 | @Override 82 | public CompletionStage thenRunAsync(Runnable action) { 83 | return Context.wrap(state, f.thenRunAsync(Context.wrap(state, action))); 84 | } 85 | 86 | @Override 87 | public CompletionStage thenRunAsync(Runnable action, Executor executor) { 88 | return Context.wrap(state, f.thenRunAsync(Context.wrap(state, action), executor)); 89 | } 90 | 91 | @Override 92 | public CompletionStage thenCombine(CompletionStage other, 93 | BiFunction fn) { 94 | return Context.wrap(state, f.thenCombine(other, Context.wrap(state, fn))); 95 | } 96 | 97 | @Override 98 | public CompletionStage thenCombineAsync(CompletionStage other, 99 | BiFunction fn) { 100 | return Context.wrap(state, f.thenCombineAsync(other, Context.wrap(state, fn))); 101 | } 102 | 103 | @Override 104 | public CompletionStage thenCombineAsync(CompletionStage other, 105 | BiFunction fn, Executor executor) { 106 | return Context.wrap(state, f.thenCombineAsync(other, Context.wrap(state, fn), executor)); 107 | } 108 | 109 | @Override 110 | public CompletionStage thenAcceptBoth(CompletionStage other, 111 | BiConsumer action) { 112 | return Context.wrap(state, f.thenAcceptBoth(other, Context.wrap(state, action))); 113 | } 114 | 115 | @Override 116 | public CompletionStage thenAcceptBothAsync(CompletionStage other, 117 | BiConsumer action) { 118 | return Context.wrap(state, f.thenAcceptBothAsync(other, Context.wrap(state, action))); 119 | } 120 | 121 | @Override 122 | public CompletionStage thenAcceptBothAsync(CompletionStage other, 123 | BiConsumer action, Executor executor) { 124 | return Context.wrap(state, f.thenAcceptBothAsync(other, Context.wrap(state, action), executor)); 125 | } 126 | 127 | @Override 128 | public CompletionStage runAfterBoth(CompletionStage other, Runnable action) { 129 | return Context.wrap(state, f.runAfterBoth(other, Context.wrap(state, action))); 130 | } 131 | 132 | @Override 133 | public CompletionStage runAfterBothAsync(CompletionStage other, Runnable action) { 134 | return Context.wrap(state, f.runAfterBothAsync(other, Context.wrap(state, action))); 135 | } 136 | 137 | @Override 138 | public CompletionStage runAfterBothAsync(CompletionStage other, Runnable action, 139 | Executor executor) { 140 | return Context.wrap(state, f.runAfterBothAsync(other, Context.wrap(state, action), executor)); 141 | } 142 | 143 | @Override 144 | public CompletionStage applyToEither(CompletionStage other, 145 | Function fn) { 146 | return Context.wrap(state, f.applyToEither(other, Context.wrap(state, fn))); 147 | } 148 | 149 | @Override 150 | public CompletionStage applyToEitherAsync(CompletionStage other, 151 | Function fn) { 152 | return Context.wrap(state, f.applyToEitherAsync(other, Context.wrap(state, fn))); 153 | } 154 | 155 | @Override 156 | public CompletionStage applyToEitherAsync(CompletionStage other, 157 | Function fn, Executor executor) { 158 | return Context.wrap(state, f.applyToEitherAsync(other, Context.wrap(state, fn), executor)); 159 | } 160 | 161 | @Override 162 | public CompletionStage acceptEither(CompletionStage other, 163 | Consumer action) { 164 | return Context.wrap(state, f.acceptEither(other, Context.wrap(state, action))); 165 | } 166 | 167 | @Override 168 | public CompletionStage acceptEitherAsync(CompletionStage other, 169 | Consumer action) { 170 | return Context.wrap(state, f.acceptEitherAsync(other, Context.wrap(state, action))); 171 | } 172 | 173 | @Override 174 | public CompletionStage acceptEitherAsync(CompletionStage other, 175 | Consumer action, Executor executor) { 176 | return Context.wrap(state, f.acceptEitherAsync(other, Context.wrap(state, action), executor)); 177 | } 178 | 179 | @Override 180 | public CompletionStage runAfterEither(CompletionStage other, Runnable action) { 181 | return Context.wrap(state, f.runAfterEither(other, Context.wrap(state, action))); 182 | } 183 | 184 | @Override 185 | public CompletionStage runAfterEitherAsync(CompletionStage other, Runnable action) { 186 | return Context.wrap(state, f.runAfterEitherAsync(other, Context.wrap(state, action))); 187 | } 188 | 189 | @Override 190 | public CompletionStage runAfterEitherAsync(CompletionStage other, Runnable action, 191 | Executor executor) { 192 | return Context.wrap(state, f.runAfterEitherAsync(other, Context.wrap(state, action), executor)); 193 | } 194 | 195 | @Override 196 | public CompletionStage thenCompose(Function> fn) { 197 | return Context.wrap(state, f.thenCompose(Context.wrap(state, fn))); 198 | } 199 | 200 | @Override 201 | public CompletionStage thenComposeAsync(Function> fn) { 202 | return Context.wrap(state, f.thenComposeAsync(Context.wrap(state, fn))); 203 | } 204 | 205 | @Override 206 | public CompletionStage thenComposeAsync(Function> fn, 207 | Executor executor) { 208 | return Context.wrap(state, f.thenComposeAsync(Context.wrap(state, fn), executor)); 209 | } 210 | 211 | @Override 212 | public CompletionStage whenComplete(BiConsumer action) { 213 | return Context.wrap(state, f.whenComplete(Context.wrap(state, action))); 214 | } 215 | 216 | @Override 217 | public CompletionStage whenCompleteAsync(BiConsumer action) { 218 | return Context.wrap(state, f.whenCompleteAsync(Context.wrap(state, action))); 219 | } 220 | 221 | @Override 222 | public CompletionStage whenCompleteAsync(BiConsumer action, 223 | Executor executor) { 224 | return Context.wrap(state, f.whenCompleteAsync(Context.wrap(state, action), executor)); 225 | } 226 | 227 | @Override 228 | public String toString() { 229 | return f.toString(); 230 | } 231 | 232 | @Override 233 | public int hashCode() { 234 | return f.hashCode(); 235 | } 236 | 237 | @Override 238 | public boolean equals(Object obj) { 239 | return f.equals(obj); 240 | } 241 | } -------------------------------------------------------------------------------- /core/src/main/java/io/reactiverse/reactivecontexts/core/Context.java: -------------------------------------------------------------------------------- 1 | package io.reactiverse.reactivecontexts.core; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.ServiceLoader; 6 | import java.util.concurrent.CompletableFuture; 7 | import java.util.concurrent.CompletionStage; 8 | import java.util.function.BiConsumer; 9 | import java.util.function.BiFunction; 10 | import java.util.function.Consumer; 11 | import java.util.function.Function; 12 | 13 | /** 14 | *

15 | * Main class for initialising the list of {@link ContextPropagator} and {@link ContextProvider}. 16 | *

17 | *

18 | * Upon startup, you should initialise Reactive Contexts by calling {@link #load()}, which 19 | * will initialise all {@link ContextPropagator} and {@link ContextProvider} via the {@link ServiceLoader} 20 | * mechanism. 21 | *

22 | *

23 | * If you don't have an automatic {@link ContextPropagator}, you can then manually capture contexts with 24 | * {@link #capture()}, and then surround your context-requiring code with: 25 | *

26 | * 27 | *

 28 |  * ContextState context = Context.capture();
 29 |  * // ...
 30 |  * ContextState previousContext = context.install();
 31 |  * try{
 32 |  *     // your context-requiring code
 33 |  * }finally{
 34 |  *     previousContext.restore();
 35 |  * }
 36 |  *  
37 | *

38 | * Or you can use one of the many {@link #wrap(Runnable)} methods for wrapping reactive types: 39 | *

40 | * 41 | *

 42 |  *  Runnable runnableWithContext = Context.wrap(() -> ...your context-requiring code...);
 43 |  *  CompletionStage<String> completionStageWithContext = Context.wrap(originalCompletionStage);
 44 |  *  
45 | *

Threads, class loaders

46 | *

47 | * If you are using a flat classpath, this is all you need to know. If you're using a modular class loader, 48 | * or need to have several independent {@link Context} objects, each with their own list of providers and 49 | * propagators, then you need to stop using the global {@link Context} instance and create your own. 50 | *

51 | *

52 | * You can create your own Context with {@link #Context()}, then set it as a thread-local with 53 | * {@link #setThreadInstance(Context)}, and when you're done you can clear the thread-local with 54 | * {@link #clearThreadInstance()}. 55 | *

56 | *

57 | * Note that each captured context state will restore the proper Context thread-local when 58 | * calling {@link #install(ContextState)} and {@link #restore(ContextState)}, so as to avoid 59 | * interference. 60 | *

61 | * @author Stéphane Épardaud 62 | */ 63 | public class Context { 64 | 65 | private static Context instance = new Context(); 66 | private static ThreadLocal threadInstance = new ThreadLocal(); 67 | 68 | /** 69 | * Initialises the list of registered {@link ContextProvider} and {@link ContextPropagator} 70 | * if they are not already initialised. Otherwise, has no effect. 71 | */ 72 | public static void load() { 73 | // does not do anything, but triggers the static block load 74 | } 75 | 76 | /** 77 | * Returns a {@link Context} type suitable for handling Reactive Contexts. If there is a 78 | * thread-local {@link Context} as installed by {@link #setThreadInstance(Context)}, the 79 | * thread-local instance is returned. If not, a global shared instance is returned. 80 | * @return a thread-local or global instance of {@link Context}. 81 | * @see #setThreadInstance(Context) 82 | */ 83 | public static Context getInstance() { 84 | Context ret = threadInstance.get(); 85 | if(ret == null) 86 | ret = instance; 87 | return ret; 88 | } 89 | 90 | /** 91 | * Installs a {@link Context} instance to use in the current thread. It will be returned 92 | * by {@link #getInstance()} within the current thread. 93 | * 94 | * @param instance the {@link Context} instance to install in the current thread 95 | * @return the previous instance of {@link Context} that was associated to the current thread 96 | * @see #clearThreadInstance() 97 | */ 98 | public static Context setThreadInstance(Context instance) { 99 | Context oldInstance = threadInstance.get(); 100 | threadInstance.set(instance); 101 | return oldInstance; 102 | } 103 | 104 | /** 105 | * Clears the currently-associated {@link Context} instance for the current thread. 106 | * @see #setThreadInstance(Context) 107 | */ 108 | public static void clearThreadInstance() { 109 | threadInstance.remove(); 110 | } 111 | 112 | private List> providers = new ArrayList<>(); 113 | private List propagators = new ArrayList<>(); 114 | 115 | /** 116 | * Creates a new Context instance with the associated {@link ContextProvider} and {@link ContextPropagator} 117 | * as looked up by {@link ServiceLoader#load(Class)} for the current classloader. 118 | */ 119 | public Context() { 120 | for (ContextProvider listener : ServiceLoader.load(ContextProvider.class)) { 121 | providers.add(listener); 122 | } 123 | for (ContextPropagator propagator : ServiceLoader.load(ContextPropagator.class)) { 124 | propagators.add(propagator); 125 | propagator.setup(); 126 | } 127 | } 128 | 129 | /** 130 | * Captures the current state as given by the current context. 131 | * @return the current context state 132 | * @see #getInstance() 133 | */ 134 | public static ContextState capture() { 135 | return getInstance().captureState(); 136 | } 137 | 138 | /** 139 | * Captures all contexts currently registered via this {@link Context}'s {@link ContextProvider} plugins. 140 | * @return the storage required for all currently registered contexts. 141 | * @see #install(ContextState) 142 | */ 143 | public ContextState captureState() { 144 | Object[] ret = new Object[providers.size()]; 145 | for (int i = 0; i < providers.size(); i++) { 146 | ContextProvider plugin = providers.get(i); 147 | ret[i] = plugin.capture(); 148 | } 149 | return new ContextState(this, ret, threadInstance.get()); 150 | } 151 | 152 | /** 153 | * Installs a set of contexts previously captured with {@link #captureState()} to all 154 | * currently registered {@link ContextProvider} plugins in this {@link Context}. 155 | * @param state the context state previously captured with {@link #captureState()} 156 | * @return the (current/before installation) storage required for all currently registered contexts. 157 | * @see #captureState() 158 | * @see #restore(ContextState) 159 | * @throws IllegalArgumentException if the state to install has not been captured by this {@link Context} instance. 160 | */ 161 | public ContextState install(ContextState state) { 162 | if(this != state.getContext()) 163 | throw new IllegalArgumentException("State was captured with different context"); 164 | Object[] oldStates = new Object[providers.size()]; 165 | Object[] states = state.getState(); 166 | for (int i = 0; i < providers.size(); i++) { 167 | @SuppressWarnings("unchecked") 168 | ContextProvider plugin = (ContextProvider) providers.get(i); 169 | oldStates[i] = plugin.install(states[i]); 170 | } 171 | return new ContextState(this, oldStates, setThreadInstance(this)); 172 | } 173 | 174 | /** 175 | * Restores a set of contexts previously captured with {@link #install(ContextState)} to all 176 | * currently registered {@link ContextProvider} plugins of this {@link Context}. 177 | * @param state a set of contexts previously captured with {@link #install(ContextState)} 178 | * @see #install(ContextState) 179 | * @throws IllegalArgumentException if the state to install has not been captured by this {@link Context} instance. 180 | */ 181 | public void restore(ContextState state) { 182 | if(this != state.getContext()) 183 | throw new IllegalArgumentException("State was captured with different context"); 184 | Object[] states = state.getState(); 185 | for (int i = 0; i < providers.size(); i++) { 186 | @SuppressWarnings("unchecked") 187 | ContextProvider plugin = (ContextProvider) providers.get(i); 188 | plugin.restore(states[i]); 189 | } 190 | Context previousThreadContext = state.getPreviousThreadContext(); 191 | if(previousThreadContext == null) 192 | clearThreadInstance(); 193 | else 194 | setThreadInstance(previousThreadContext); 195 | } 196 | 197 | /** 198 | * Wraps a {@link Runnable} so that its {@link Runnable#run()} method will 199 | * be called with the current reactive context. 200 | * @param f the {@link Runnable} to wrap 201 | * @return a {@link Runnable} which will have its reactive context set to the current context. 202 | */ 203 | public static Runnable wrap(Runnable f) { 204 | return wrap(capture(), f); 205 | } 206 | 207 | static Runnable wrap(ContextState state, Runnable f) { 208 | return () -> { 209 | ContextState oldState = state.install(); 210 | try { 211 | f.run(); 212 | }finally { 213 | oldState.restore(); 214 | } 215 | }; 216 | } 217 | 218 | /** 219 | * Wraps a {@link Consumer} so that its {@link Consumer#accept(Object)} method will 220 | * be called with the current reactive context. 221 | * @param f the {@link Consumer} to wrap 222 | * @return a {@link Consumer} which will have its reactive context set to the current context. 223 | */ 224 | public static Consumer wrap(Consumer f) { 225 | return wrap(capture(), f); 226 | } 227 | 228 | static Consumer wrap(ContextState state, Consumer f) { 229 | return v -> { 230 | ContextState oldState = state.install(); 231 | try { 232 | f.accept(v); 233 | }finally { 234 | oldState.restore(); 235 | } 236 | }; 237 | } 238 | 239 | /** 240 | * Wraps a {@link BiConsumer} so that its {@link BiConsumer#accept(Object, Object)} method will 241 | * be called with the current reactive context. 242 | * @param f the {@link BiConsumer} to wrap 243 | * @return a {@link BiConsumer} which will have its reactive context set to the current context. 244 | */ 245 | public static BiConsumer wrap(BiConsumer f) { 246 | return wrap(capture(), f); 247 | } 248 | 249 | static BiConsumer wrap(ContextState state, BiConsumer f) { 250 | return (t, u) -> { 251 | ContextState oldState = state.install(); 252 | try { 253 | f.accept(t, u); 254 | }finally { 255 | oldState.restore(); 256 | } 257 | }; 258 | } 259 | 260 | /** 261 | * Wraps a {@link BiFunction} so that its {@link BiFunction#apply(Object, Object)} method will 262 | * be called with the current reactive context. 263 | * @param fn the {@link BiFunction} to wrap 264 | * @return a {@link BiFunction} which will have its reactive context set to the current context. 265 | */ 266 | public static BiFunction wrap(BiFunction fn){ 267 | return wrap(capture(), fn); 268 | } 269 | 270 | static BiFunction wrap(ContextState state, BiFunction fn){ 271 | return (t, u) -> { 272 | ContextState oldState = state.install(); 273 | try { 274 | return fn.apply(t, u); 275 | }finally { 276 | oldState.restore(); 277 | } 278 | }; 279 | } 280 | 281 | /** 282 | * Wraps a {@link Function} so that its {@link Function#apply(Object)} method will 283 | * be called with the current reactive context. 284 | * @param fn the {@link Function} to wrap 285 | * @return a {@link Function} which will have its reactive context set to the current context. 286 | */ 287 | public static Function wrap(Function fn){ 288 | return wrap(capture(), fn); 289 | } 290 | 291 | static Function wrap(ContextState state, Function fn){ 292 | return v -> { 293 | ContextState oldState = state.install(); 294 | try { 295 | return fn.apply(v); 296 | }finally { 297 | oldState.restore(); 298 | } 299 | }; 300 | } 301 | 302 | /** 303 | * Wraps a {@link CompletableFuture} so that all its handlers 304 | * are called with the current reactive context. 305 | * @param f the {@link CompletableFuture} to wrap 306 | * @return a {@link CompletableFuture} which will have its reactive context set to the current context. 307 | */ 308 | public static CompletableFuture wrap(CompletableFuture f) { 309 | return wrap(capture(), f); 310 | } 311 | 312 | static CompletableFuture wrap(ContextState state, CompletableFuture f) { 313 | return new CompletableFutureWrapper(state, f); 314 | } 315 | 316 | /** 317 | * Wraps a {@link CompletionStage} so that all its handlers 318 | * are called with the current reactive context. 319 | * @param f the {@link CompletionStage} to wrap 320 | * @return a {@link CompletionStage} which will have its reactive context set to the current context. 321 | */ 322 | public static CompletionStage wrap(CompletionStage f) { 323 | return wrap(capture(), f); 324 | } 325 | 326 | static CompletionStage wrap(ContextState state, CompletionStage f) { 327 | return new CompletionStageWrapper(state, f); 328 | } 329 | } 330 | -------------------------------------------------------------------------------- /core/src/main/java/io/reactiverse/reactivecontexts/core/ContextPropagator.java: -------------------------------------------------------------------------------- 1 | package io.reactiverse.reactivecontexts.core; 2 | 3 | /** 4 | *

5 | * A Context Propagator is a plugin for Reactive Contexts which can automatically propagate 6 | * contexts by plugging into a Reactive library or scheduler via hooks and plugins. If you get notified 7 | * by the target Reactive library or scheduler of when user code gets executed, you can choose to capture 8 | * and restore all registered contexts using the {@link Context} API. 9 | *

10 | *

11 | * For example, in RxJava, the {@link ContextPropagator} will use the existing RxJava mechanism for plugins 12 | * so that whenever a Reactive type is created, the contexts are associated to the Reactive type, and then 13 | * restored every time the Reactive type subscribers get called, thus propagating all contexts to the 14 | * chain of Reactive type operations. 15 | *

16 | *

17 | * In order to register your {@link ContextPropagator} you need to create a file in 18 | * META-INF/services/io.reactiverse.reactivecontexts.core.ContextPropagator which contains a list 19 | * of fully-qualified type names of each of your implementations of {@link ContextPropagator} (one per line). 20 | *

21 | * 22 | * @author Stéphane Épardaud 23 | * @see Context 24 | */ 25 | public interface ContextPropagator { 26 | 27 | /** 28 | * Called by {@link Context} to initialise every propagator. Implement this method 29 | * to register your propagator in whatever Reactive library/scheduler you want to propagate 30 | * contexts for. 31 | */ 32 | public void setup(); 33 | } 34 | -------------------------------------------------------------------------------- /core/src/main/java/io/reactiverse/reactivecontexts/core/ContextProvider.java: -------------------------------------------------------------------------------- 1 | package io.reactiverse.reactivecontexts.core; 2 | 3 | /** 4 | *

5 | * A Context Provider is a plugin for Reactive Contexts which can automatically capture, install and restore 6 | * contexts for a library which requires a context object to be propagated. 7 | *

8 | *

9 | * For example, RESTEasy uses a thread-local context that holds the current request, response and many other 10 | * useful information so that the resource method can look them up when executed. This works well in settings 11 | * where you have one thread per operation, but stops working if the operation spawns other threads, or gets 12 | * executed in other threads, or simply later, as is the case in many Reactive libraries. 13 | *

14 | *

15 | * In your implementation of {@link ContextProvider} you will be responsible for telling Reactive Contexts 16 | * how to capture and reinstall the context for the library you want to support. In practice it will mean 17 | * giving access to the thread-local storage that the target library uses. 18 | *

19 | *

20 | * In order to register your {@link ContextProvider} you need to create a file in 21 | * META-INF/services/io.reactiverse.reactivecontexts.core.ContextProvider which contains a list 22 | * of fully-qualified type names of each of your implementations of {@link ContextProvider} (one per line). 23 | *

24 | * 25 | * @author Stéphane Épardaud 26 | * @see Context 27 | */ 28 | public interface ContextProvider { 29 | 30 | /** 31 | * Called by {@link Context#install(ContextState)} to install your previously-captured state. 32 | * @param state your context state, as previously captured by {@link #capture()} or {@link #install(Object)}. 33 | * @return the current/previous context state, before reinstalling the new state. 34 | */ 35 | public State install(State state); 36 | 37 | /** 38 | * Called by {@link Context#restore(ContextState)} to install your previously-captured state. 39 | * @param previousState your context state, as previously captured by {@link #capture()} or {@link #install(Object)}. 40 | */ 41 | public void restore(State previousState); 42 | 43 | /** 44 | * Captures your current context state. 45 | * @return your current context state. 46 | */ 47 | public State capture(); 48 | } 49 | -------------------------------------------------------------------------------- /core/src/main/java/io/reactiverse/reactivecontexts/core/ContextState.java: -------------------------------------------------------------------------------- 1 | package io.reactiverse.reactivecontexts.core; 2 | 3 | /** 4 | * Opaque context state class which contains context state that has been captured, and can be restored. 5 | * 6 | * @see Context 7 | * @author Stéphane Épardaud 8 | */ 9 | public class ContextState { 10 | private Context context; 11 | private Context previousThreadContext; 12 | private Object[] state; 13 | 14 | ContextState(Context context, Object[] state, Context previousThreadContext) { 15 | this.context = context; 16 | this.state = state; 17 | this.previousThreadContext = previousThreadContext; 18 | } 19 | 20 | Context getContext() { 21 | return context; 22 | } 23 | 24 | Object[] getState() { 25 | return state; 26 | } 27 | 28 | Context getPreviousThreadContext() { 29 | return previousThreadContext; 30 | } 31 | 32 | public ContextState install() { 33 | return context.install(this); 34 | } 35 | 36 | public void restore() { 37 | context.restore(this); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /core/src/main/java/io/reactiverse/reactivecontexts/core/package-info.java: -------------------------------------------------------------------------------- 1 | /** 2 | *

3 | * Reactive Contexts is a library which supports automatic context propagation in Reactive libraries. 4 | *

5 | *

6 | * Many libraries (for example: RESTEasy) use a thread-local context that holds information required by user-executing 7 | * code (in the case of RESTEasy: the current request, response and many other useful information so that the resource 8 | * method can look them up when executed). 9 | *

10 | *

11 | * This works well in settings where you have one thread per operation, but stops working if the operation spawns other 12 | * threads, or gets executed in other threads, or simply later, as is the case in many Reactive libraries, such as RxJava, 13 | * where users code is spread between the subscriber, operations such as filter/map, and producers, all of which can be 14 | * executed in different thread schedulers. 15 | *

16 | *

17 | * In order to enable automatic context propagation of any number of contexts, Reactive Context uses a system of plugins 18 | * for saving/restoring contexts: {@link io.reactiverse.reactivecontexts.core.ContextProvider}, and plugins that 19 | * hook into Reactive libraries/schedulers in 20 | * order to use the {@link io.reactiverse.reactivecontexts.core.Context} API for saving/restoring all contexts: 21 | * {@link io.reactiverse.reactivecontexts.core.ContextPropagator}. 22 | *

23 | *

24 | * If your context-using framework is supported, and your Reactive library/scheduler is supported too, then all your 25 | * contexts will be automatically propagated and your code will look great. If not, add support for your 26 | * {@link io.reactiverse.reactivecontexts.core.ContextProvider} or {@link io.reactiverse.reactivecontexts.core.ContextPropagator}. 27 | * If it's not possible, you can still use manual context 28 | * propagation by accessing directly the {@link io.reactiverse.reactivecontexts.core.Context} API or by wrapping any reactive 29 | * type with the many {@link Context#wrap(Runnable)} functions. 30 | *

31 | * 32 | * @author Stéphane Épardaud 33 | */ 34 | package io.reactiverse.reactivecontexts.core; 35 | 36 | -------------------------------------------------------------------------------- /docs/Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | 3 | gem 'github-pages', group: :jekyll_plugins 4 | -------------------------------------------------------------------------------- /docs/README.md: -------------------------------------------------------------------------------- 1 | # Reactive Contexts 2 | 3 | [![Build Status](https://travis-ci.com/reactiverse/reactive-contexts.svg?branch=master)](https://travis-ci.com/reactiverse/reactive-contexts) 4 | 5 | Reactive Contexts is a library that allows you to capture contexts from various providers ([RESTEasy](https://resteasy.github.io), 6 | [Redpipe](http://redpipe.net), [Weld](http://weld.cdi-spec.org)) 7 | and propagate them along the reactive flow of various propagators ([RxJava1, RxJava2](https://github.com/ReactiveX/RxJava)). 8 | 9 | # License 10 | 11 | Reactive Contexts is licensed under the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0) terms. 12 | 13 | # The problem with contexts and reactive libraries 14 | 15 | Many libraries (for example: RESTEasy, [CDI](http://cdi-spec.org)) use a thread-local context that holds information required by user-executing 16 | code (in the case of RESTEasy: the current request, response and many other useful information so that the resource 17 | method can look them up when executed). 18 | 19 | This works well in settings where you have one thread per operation, but stops working if the operation spawns other 20 | threads, or gets executed in other threads, or simply later, as is the case in many Reactive libraries, such as RxJava, 21 | where users code is spread between the subscriber, operations such as filter/map, and producers, all of which can be 22 | executed in different thread schedulers. 23 | 24 | For example, the following RESTEasy/RxJava code works out of the box with the latest version of RESTEasy: 25 | 26 | @GET 27 | @Path("reactive-nodelay") 28 | public Single reactiveNoDelay(@Context UriInfo uriInfo){ 29 | return Single.just("hello") 30 | .map(str -> str + " from: "+uriInfo.getAbsolutePath()); 31 | } 32 | 33 | And will display something like `hello from: http://localhost:8081/reactive-nodelay`. 34 | 35 | But if you introduce a delay, which is only one of the many ways to introduce a thread-switch from RxJava: 36 | 37 | @GET 38 | @Path("reactive-delay") 39 | public Single reactiveDelay(@Context UriInfo uriInfo){ 40 | return Single.just("hello") 41 | .delay(1, TimeUnit.SECONDS) 42 | .map(str -> str + " from: "+uriInfo.getAbsolutePath()); 43 | } 44 | 45 | Then it breaks down with `RESTEASY003880: Unable to find contextual data of type: javax.ws.rs.core.UriInfo`. 46 | 47 | This is due to the fact that RESTEasy doesn't know that RxJava is going to schedule the delayed `map` operation 48 | into a different scheduler, on a thread which doesn't have the RESTEasy context set-up in a thread-local. 49 | 50 | This is not RESTEasy's fault: the exact same error will happen if you try to use CDI at that point, for the exact 51 | same reason. Many existing libraries rely on thread-locals for context propagation, and it does not work in the 52 | async/Reactive world. 53 | 54 | RxJava supports a system of hooks/plugins that we can use to capture and restore context, but there can only be 55 | one such hook/plugin, so if RESTEasy uses it, CDI cannot use it. Also, there would be a lot of code duplication 56 | as propagating contexts with RxJava hooks/plugins is not trivial. 57 | 58 | # The solution 59 | 60 | In order to enable automatic context propagation of any number of contexts, Reactive Context uses a system of plugins 61 | for saving/restoring contexts: `ContextProvider`, and plugins that hook into Reactive libraries/schedulers in 62 | order to use the `Context` API for saving/restoring all contexts: `ContextPropagator`. 63 | 64 | If your context-using framework is supported, and your Reactive library/scheduler is supported too, then all your 65 | contexts will be automatically propagated and your code will look great. If not, add support for your 66 | `ContextProvider` or `ContextPropagator`. If it's not possible, you can still use manual context 67 | propagation by accessing directly the `Context` API. 68 | 69 | To get back to our original problematic code: 70 | 71 | @GET 72 | @Path("reactive-delay") 73 | public Single reactiveDelay(@Context UriInfo uriInfo){ 74 | return Single.just("hello") 75 | .delay(1, TimeUnit.SECONDS) 76 | .map(str -> str + " from: "+uriInfo.getAbsolutePath()); 77 | } 78 | 79 | Will work fine if you use the RESTEasy `ContextProvider` with the RxJava2 `ContextPropagator`, without any change 80 | in your code. Automatic context propagation FTW! 81 | 82 | # Usage 83 | 84 | Import the following Maven module: 85 | 86 | ```xml 87 | 88 | io.reactiverse 89 | reactive-contexts-core 90 | 1.0.0 91 | 92 | ``` 93 | 94 | Then call `io.reactiverse.reactivecontexts.core.Context.load();` and your contexts will be propagated, depending on the 95 | presence of the following optional plugins in your classpath: 96 | 97 | artifactId | Description 98 | --- | --- 99 | `reactive-contexts-core` | Core engine 100 | `reactive-contexts-propagators-rxjava1` | Propagates contexts for RxJava1 101 | `reactive-contexts-propagators-rxjava2` | Propagates contexts for RxJava2 102 | 103 | If you are using RxJava 1 or 2, you don't need anything to propagate your contexts: every RxJava type (`Single`, 104 | `Flowable`…) will have the right contexts automatically propagated. If you are using reactive types that don't 105 | have a `reactive-contexts-propagator` plugin, such as `CompletionStage` in the JDK, see [below for how to manually 106 | propagate contexts](#manual-context-propagation) 107 | 108 | # Building 109 | 110 | Clone this repository, and run: 111 | 112 | ```shell 113 | $ mvn clean install 114 | ``` 115 | 116 | # For context providers 117 | 118 | If you have a context that your library provides and requires, which is often stored in thread-local 119 | variables, it's very likely it won't work with reactive applications that register callbacks and 120 | invoke them later in various threads. 121 | 122 | In order for your library to have its context propagated to all supported reactive libraries, you 123 | can implement the `io.reactiverse.reactivecontexts.core.ContextProvider` interface and specify how 124 | you can save and restore your context: 125 | 126 | ```java 127 | package my.library; 128 | 129 | public class MyContextProvider implements ContextProvider { 130 | 131 | @Override 132 | public MyState install(MyState state) { 133 | MyState previousState = MyContext.getState(); 134 | MyContext.setState(state); 135 | return previousState; 136 | } 137 | 138 | @Override 139 | public void restore(MyState previousState) { 140 | MyContext.setState(previousState); 141 | } 142 | 143 | @Override 144 | public MyState capture() { 145 | return MyContext.getState(); 146 | } 147 | } 148 | ``` 149 | 150 | Then you declare a `META-INF/services/io.reactiverse.reactivecontexts.core.ContextProvider` file which 151 | lists your fully-qualified class name implementing the `ContextProvider` interface (in this case 152 | `my.library.MyContextProvider`) and include it in your classpath. 153 | 154 | Upon initialisation, your context provider implementation will automatically be loaded and your 155 | context will be propagated to all supported reactive libraries. 156 | 157 | # For context propagators 158 | 159 | If you have a reactive library that supports scheduling of callbacks on various threads, you will need 160 | to register a `ContextPropagator` implementation that will be called by the `reactive-contexts` library, 161 | where you will register any required plumbing on the reactive library, to make sure it will properly 162 | propagate all contexts during scheduling. 163 | 164 | For example, here is how the RxJava1 propagator is implemented: 165 | 166 | ```java 167 | public class RxJava1ContextPropagator implements ContextPropagator { 168 | 169 | public void setup() { 170 | RxJavaHooks.setOnSingleCreate(new ContextPropagatorOnSingleCreateAction()); 171 | // ... 172 | } 173 | } 174 | ``` 175 | 176 | Don't forget to list your context propagator's fully-qualified class names in the 177 | `META-INF/services/io.reactiverse.reactivecontexts.core.ContextPropagator` file, and to include it in 178 | your classpath. 179 | 180 | Your plugin can capture all current contexts with `Context.capture()`, then install captured contexts with 181 | `Context.install(contexts)` and restore them with `Context.restore(contexts)`. 182 | 183 | For example, here is how contexts are propagated for RxJava1 `Single`: 184 | 185 | ```java 186 | public class ContextPropagatorOnSingleCreateAction implements Func1 { 187 | 188 | @Override 189 | public OnSubscribe call(OnSubscribe t) { 190 | return new ContextCapturerSingle(t); 191 | } 192 | 193 | final static class ContextCapturerSingle implements Single.OnSubscribe { 194 | 195 | final Single.OnSubscribe source; 196 | 197 | private ContextState states; 198 | 199 | public ContextCapturerSingle(Single.OnSubscribe source) { 200 | this.source = source; 201 | // capture the context 202 | states = Context.capture(); 203 | } 204 | 205 | @Override 206 | public void call(SingleSubscriber t) { 207 | // restore the context for subscription 208 | ContextState previousStates = states.install(); 209 | try { 210 | source.call(new OnAssemblySingleSubscriber(t, states)); 211 | }finally { 212 | previousStates.restore(); 213 | } 214 | } 215 | 216 | static final class OnAssemblySingleSubscriber extends SingleSubscriber { 217 | 218 | final SingleSubscriber actual; 219 | private final ContextState states; 220 | 221 | 222 | public OnAssemblySingleSubscriber(SingleSubscriber actual, ContextState states) { 223 | this.actual = actual; 224 | this.states = states; 225 | actual.add(this); 226 | } 227 | 228 | @Override 229 | public void onError(Throwable e) { 230 | // propagate the context for listeners 231 | ContextState previousStates = states.install(); 232 | try { 233 | actual.onError(e); 234 | }finally { 235 | previousStates.restore(); 236 | } 237 | } 238 | 239 | @Override 240 | public void onSuccess(T t) { 241 | // propagate the context for listeners 242 | ContextState previousStates = states.install(); 243 | try { 244 | actual.onSuccess(t); 245 | }finally { 246 | previousStates.restore(); 247 | } 248 | } 249 | } 250 | } 251 | 252 | } 253 | ``` 254 | 255 | ## Manual context propagation 256 | 257 | If you have a library that uses reactive types that don't support hooks, such as the JDK's `CompletionStage`, 258 | you will have to manually capture and restore contexts, for example: 259 | 260 | ```java 261 | CompletionStage userResponse = invokeUserAction(); 262 | ContextState states = Context.capture(); 263 | userResponse.thenAccept(response -> { 264 | ContextState previousStates = states.install(); 265 | try { 266 | writeResponse(response); 267 | }finally { 268 | previousStates.restore(); 269 | } 270 | }); 271 | ``` 272 | 273 | Alternately, you can use `Context.wrap` to propagate reactive contexts to many functional interfaces, for example: 274 | 275 | ```java 276 | CompletionStage userResponse = Context.wrap(invokeUserAction()); 277 | userResponse.thenAccept(response -> writeResponse(response)); 278 | ``` 279 | 280 | # Threads, class loaders 281 | 282 | If you are using a flat classpath, this is all you need to know. If you're using a modular class loader, 283 | or need to have several independent `Context` objects, each with their own list of providers and 284 | propagators, then you need to stop using the global `Context` instance and create your own. 285 | 286 | You can create your own Context with `new Context()`, then set it as a thread-local with 287 | `Context.setThreadInstance(Context)`, and when you're done you can clear the thread-local with 288 | `Context.clearThreadInstance()`. 289 | 290 | Note that each captured context state will restore the proper Context thread-local when 291 | calling `ContextState.install()` and `ContextState.restore()`, so as to avoid 292 | interference. 293 | 294 | -------------------------------------------------------------------------------- /docs/_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-minimal 2 | repository: Reactiverse/reactive-contexts 3 | 4 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | 7 | org.sonatype.oss 8 | oss-parent 9 | 9 10 | 11 | 12 | io.reactiverse 13 | reactive-contexts-parent 14 | 1.0.2-SNAPSHOT 15 | pom 16 | 17 | Reactive Contexts 18 | https://github.com/reactiverse/reactive-contexts 19 | A pluggable library for context propagation in reactive libraries 20 | 21 | 22 | 23 | The Apache Software License, Version 2.0 24 | http://www.apache.org/licenses/LICENSE-2.0.txt 25 | repo 26 | 27 | 28 | 29 | 30 | scm:git:git@github.com:reactiverse/reactive-contexts.git 31 | scm:git:git@github.com:reactiverse/reactive-contexts.git 32 | git@github.com:reactiverse/reactive-contexts.git 33 | HEAD 34 | 35 | 36 | 37 | 8 38 | 8 39 | 40 | 41 | 42 | 43 | Stéphane Épardaud 44 | stef@epardaud.fr 45 | 46 | 47 | 48 | 49 | 50 | 51 | junit 52 | junit 53 | 4.12 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | org.apache.maven.plugins 63 | maven-source-plugin 64 | 2.2.1 65 | 66 | 67 | attach-sources 68 | 69 | jar-no-fork 70 | 71 | 72 | 73 | 74 | 75 | org.apache.maven.plugins 76 | maven-compiler-plugin 77 | 3.8.1 78 | 79 | 80 | org.apache.maven.plugins 81 | maven-javadoc-plugin 82 | 3.1.1 83 | 84 | 85 | attach-javadocs 86 | 87 | jar 88 | 89 | 90 | 91 | 92 | 93 | org.apache.maven.plugins 94 | maven-gpg-plugin 95 | 1.5 96 | 97 | 98 | sign-artifacts 99 | verify 100 | 101 | sign 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | org.apache.maven.plugins 112 | maven-release-plugin 113 | 2.5.3 114 | 115 | true 116 | false 117 | release 118 | deploy 119 | 120 | 121 | 122 | org.apache.maven.plugins 123 | maven-javadoc-plugin 124 | 125 | 8 126 | 127 | 128 | 129 | org.apache.maven.plugins 130 | maven-compiler-plugin 131 | 132 | 8 133 | 8 134 | 135 | 136 | 137 | 138 | 139 | 140 | core 141 | propagators-rxjava1 142 | propagators-rxjava2 143 | tests 144 | 145 | -------------------------------------------------------------------------------- /propagators-rxjava1/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | reactive-contexts-propagators-rxjava1 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.jdt.core.javanature 21 | org.eclipse.m2e.core.maven2Nature 22 | 23 | 24 | -------------------------------------------------------------------------------- /propagators-rxjava1/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | 5 | io.reactiverse 6 | reactive-contexts-parent 7 | 1.0.2-SNAPSHOT 8 | 9 | reactive-contexts-propagators-rxjava1 10 | reactive-contexts-propagators-rxjava1 11 | http://maven.apache.org 12 | 13 | UTF-8 14 | 15 | 16 | 17 | junit 18 | junit 19 | test 20 | 21 | 22 | 23 | io.reactiverse 24 | reactive-contexts-core 25 | ${project.version} 26 | 27 | 28 | 29 | io.reactivex 30 | rxjava 31 | 1.3.4 32 | 33 | 34 | 35 | 36 | 37 | 38 | org.apache.maven.plugins 39 | maven-source-plugin 40 | 41 | 42 | org.apache.maven.plugins 43 | maven-javadoc-plugin 44 | 45 | 46 | 47 | 48 | 49 | release 50 | 51 | 52 | 53 | org.apache.maven.plugins 54 | maven-gpg-plugin 55 | 56 | 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /propagators-rxjava1/src/main/java/io/reactiverse/reactivecontexts/propagators/rxjava1/ContextPropagatorOnCompleteCreateAction.java: -------------------------------------------------------------------------------- 1 | package io.reactiverse.reactivecontexts.propagators.rxjava1; 2 | 3 | import io.reactiverse.reactivecontexts.core.Context; 4 | import io.reactiverse.reactivecontexts.core.ContextState; 5 | import rx.Completable.OnSubscribe; 6 | import rx.CompletableSubscriber; 7 | import rx.Subscription; 8 | import rx.functions.Func1; 9 | 10 | public class ContextPropagatorOnCompleteCreateAction implements Func1 { 11 | 12 | @Override 13 | public OnSubscribe call(OnSubscribe t) { 14 | return new ContextCapturerCompletable(t); 15 | } 16 | 17 | final static class ContextCapturerCompletable implements OnSubscribe { 18 | 19 | final OnSubscribe source; 20 | 21 | private ContextState states; 22 | 23 | public ContextCapturerCompletable(OnSubscribe source) { 24 | this.source = source; 25 | states = Context.capture(); 26 | } 27 | 28 | @Override 29 | public void call(CompletableSubscriber t) { 30 | ContextState previousStates = states.install(); 31 | try { 32 | source.call(new OnAssemblyCompletableSubscriber(t, states)); 33 | }finally { 34 | previousStates.restore(); 35 | } 36 | } 37 | 38 | static final class OnAssemblyCompletableSubscriber implements CompletableSubscriber { 39 | 40 | final CompletableSubscriber actual; 41 | private final ContextState states; 42 | 43 | 44 | public OnAssemblyCompletableSubscriber(CompletableSubscriber actual, ContextState states) { 45 | this.actual = actual; 46 | this.states = states; 47 | } 48 | 49 | @Override 50 | public void onError(Throwable e) { 51 | ContextState previousStates = states.install(); 52 | try { 53 | actual.onError(e); 54 | }finally { 55 | previousStates.restore(); 56 | } 57 | } 58 | 59 | @Override 60 | public void onCompleted() { 61 | ContextState previousStates = states.install(); 62 | try { 63 | actual.onCompleted(); 64 | }finally { 65 | previousStates.restore(); 66 | } 67 | } 68 | 69 | @Override 70 | public void onSubscribe(Subscription d) { 71 | ContextState previousStates = states.install(); 72 | try { 73 | actual.onSubscribe(d); 74 | }finally { 75 | previousStates.restore(); 76 | } 77 | } 78 | } 79 | } 80 | 81 | } 82 | -------------------------------------------------------------------------------- /propagators-rxjava1/src/main/java/io/reactiverse/reactivecontexts/propagators/rxjava1/ContextPropagatorOnObservableCreateAction.java: -------------------------------------------------------------------------------- 1 | package io.reactiverse.reactivecontexts.propagators.rxjava1; 2 | 3 | import io.reactiverse.reactivecontexts.core.Context; 4 | import io.reactiverse.reactivecontexts.core.ContextState; 5 | import rx.Observable; 6 | import rx.Observable.OnSubscribe; 7 | import rx.Subscriber; 8 | import rx.functions.Func1; 9 | 10 | public class ContextPropagatorOnObservableCreateAction implements Func1 { 11 | 12 | @Override 13 | public OnSubscribe call(OnSubscribe t) { 14 | return new ContextCapturerObservable(t); 15 | } 16 | 17 | final static class ContextCapturerObservable implements Observable.OnSubscribe { 18 | 19 | final Observable.OnSubscribe source; 20 | 21 | private ContextState states; 22 | 23 | public ContextCapturerObservable(Observable.OnSubscribe source) { 24 | this.source = source; 25 | states = Context.capture(); 26 | } 27 | 28 | @Override 29 | public void call(Subscriber t) { 30 | ContextState previousStates = states.install(); 31 | try { 32 | source.call(new OnAssemblyObservableSubscriber(t, states)); 33 | }finally { 34 | previousStates.restore(); 35 | } 36 | 37 | } 38 | 39 | static final class OnAssemblyObservableSubscriber extends Subscriber { 40 | 41 | final Subscriber actual; 42 | private final ContextState states; 43 | 44 | public OnAssemblyObservableSubscriber(Subscriber actual, ContextState states) { 45 | super(actual); 46 | this.actual = actual; 47 | this.states = states; 48 | actual.add(this); 49 | } 50 | 51 | @Override 52 | public void onError(Throwable e) { 53 | ContextState previousStates = states.install(); 54 | try { 55 | actual.onError(e); 56 | }finally { 57 | previousStates.restore(); 58 | } 59 | } 60 | 61 | @Override 62 | public void onNext(T t) { 63 | ContextState previousStates = states.install(); 64 | try { 65 | actual.onNext(t); 66 | }finally { 67 | previousStates.restore(); 68 | } 69 | } 70 | 71 | @Override 72 | public void onCompleted() { 73 | ContextState previousStates = states.install(); 74 | try { 75 | actual.onCompleted(); 76 | }finally { 77 | previousStates.restore(); 78 | } 79 | } 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /propagators-rxjava1/src/main/java/io/reactiverse/reactivecontexts/propagators/rxjava1/ContextPropagatorOnSingleCreateAction.java: -------------------------------------------------------------------------------- 1 | package io.reactiverse.reactivecontexts.propagators.rxjava1; 2 | 3 | import io.reactiverse.reactivecontexts.core.Context; 4 | import io.reactiverse.reactivecontexts.core.ContextState; 5 | import rx.Single; 6 | import rx.Single.OnSubscribe; 7 | import rx.SingleSubscriber; 8 | import rx.functions.Func1; 9 | 10 | public class ContextPropagatorOnSingleCreateAction implements Func1 { 11 | 12 | @Override 13 | public OnSubscribe call(OnSubscribe t) { 14 | return new ContextCapturerSingle(t); 15 | } 16 | 17 | final static class ContextCapturerSingle implements Single.OnSubscribe { 18 | 19 | final Single.OnSubscribe source; 20 | 21 | private ContextState states; 22 | 23 | public ContextCapturerSingle(Single.OnSubscribe source) { 24 | this.source = source; 25 | states = Context.capture(); 26 | } 27 | 28 | @Override 29 | public void call(SingleSubscriber t) { 30 | ContextState previousStates = states.install(); 31 | try { 32 | source.call(new OnAssemblySingleSubscriber(t, states)); 33 | }finally { 34 | previousStates.restore(); 35 | } 36 | } 37 | 38 | static final class OnAssemblySingleSubscriber extends SingleSubscriber { 39 | 40 | final SingleSubscriber actual; 41 | private final ContextState states; 42 | 43 | 44 | public OnAssemblySingleSubscriber(SingleSubscriber actual, ContextState states) { 45 | this.actual = actual; 46 | this.states = states; 47 | actual.add(this); 48 | } 49 | 50 | @Override 51 | public void onError(Throwable e) { 52 | ContextState previousStates = states.install(); 53 | try { 54 | actual.onError(e); 55 | }finally { 56 | previousStates.restore(); 57 | } 58 | } 59 | 60 | @Override 61 | public void onSuccess(T t) { 62 | ContextState previousStates = states.install(); 63 | try { 64 | actual.onSuccess(t); 65 | }finally { 66 | previousStates.restore(); 67 | } 68 | } 69 | } 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /propagators-rxjava1/src/main/java/io/reactiverse/reactivecontexts/propagators/rxjava1/RxJava1ContextPropagator.java: -------------------------------------------------------------------------------- 1 | package io.reactiverse.reactivecontexts.propagators.rxjava1; 2 | 3 | import io.reactiverse.reactivecontexts.core.ContextPropagator; 4 | import rx.Completable; 5 | import rx.Observable; 6 | import rx.Single; 7 | import rx.plugins.RxJavaHooks; 8 | 9 | /** 10 | * Reactive Context propagator for RxJava 1. Supports propagating context to all {@link Single}, 11 | * {@link Observable} and {@link Completable} types. 12 | * 13 | * @author Stéphane Épardaud 14 | */ 15 | public class RxJava1ContextPropagator implements ContextPropagator { 16 | 17 | public void setup() { 18 | RxJavaHooks.setOnSingleCreate(new ContextPropagatorOnSingleCreateAction()); 19 | RxJavaHooks.setOnObservableCreate(new ContextPropagatorOnObservableCreateAction()); 20 | RxJavaHooks.setOnCompletableCreate(new ContextPropagatorOnCompleteCreateAction()); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /propagators-rxjava1/src/main/resources/META-INF/services/io.reactiverse.reactivecontexts.core.ContextPropagator: -------------------------------------------------------------------------------- 1 | io.reactiverse.reactivecontexts.propagators.rxjava1.RxJava1ContextPropagator 2 | -------------------------------------------------------------------------------- /propagators-rxjava2/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | reactive-contexts-propagators-rxjava2 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.jdt.core.javanature 21 | org.eclipse.m2e.core.maven2Nature 22 | 23 | 24 | -------------------------------------------------------------------------------- /propagators-rxjava2/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | 5 | io.reactiverse 6 | reactive-contexts-parent 7 | 1.0.2-SNAPSHOT 8 | 9 | reactive-contexts-propagators-rxjava2 10 | reactive-contexts-propagators-rxjava2 11 | http://maven.apache.org 12 | 13 | UTF-8 14 | 15 | 16 | 17 | junit 18 | junit 19 | test 20 | 21 | 22 | 23 | io.reactiverse 24 | reactive-contexts-core 25 | ${project.version} 26 | 27 | 28 | 29 | io.reactivex.rxjava2 30 | rxjava 31 | 2.1.12 32 | 33 | 34 | 35 | 36 | 37 | 38 | org.apache.maven.plugins 39 | maven-source-plugin 40 | 41 | 42 | org.apache.maven.plugins 43 | maven-javadoc-plugin 44 | 45 | 46 | 47 | 48 | 49 | release 50 | 51 | 52 | 53 | org.apache.maven.plugins 54 | maven-gpg-plugin 55 | 56 | 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /propagators-rxjava2/src/main/java/io/reactiverse/reactivecontexts/propagators/rxjava2/ContextPropagatorOnCompletableAssemblyAction.java: -------------------------------------------------------------------------------- 1 | package io.reactiverse.reactivecontexts.propagators.rxjava2; 2 | 3 | import io.reactiverse.reactivecontexts.core.Context; 4 | import io.reactiverse.reactivecontexts.core.ContextState; 5 | import io.reactivex.Completable; 6 | import io.reactivex.CompletableObserver; 7 | import io.reactivex.functions.Function; 8 | 9 | public class ContextPropagatorOnCompletableAssemblyAction implements Function { 10 | 11 | @Override 12 | public Completable apply(Completable t) throws Exception { 13 | return new ContextPropagatorCompletable(t); 14 | } 15 | 16 | public class ContextPropagatorCompletable extends Completable { 17 | 18 | private Completable source; 19 | private ContextState context; 20 | 21 | public ContextPropagatorCompletable(Completable t) { 22 | this.source = t; 23 | this.context = Context.capture(); 24 | } 25 | 26 | @Override 27 | protected void subscribeActual(CompletableObserver observer) { 28 | ContextState previousContext = context.install(); 29 | try { 30 | source.subscribe(observer); 31 | }finally { 32 | previousContext.restore(); 33 | } 34 | } 35 | 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /propagators-rxjava2/src/main/java/io/reactiverse/reactivecontexts/propagators/rxjava2/ContextPropagatorOnCompletableCreateAction.java: -------------------------------------------------------------------------------- 1 | package io.reactiverse.reactivecontexts.propagators.rxjava2; 2 | 3 | import io.reactiverse.reactivecontexts.core.Context; 4 | import io.reactiverse.reactivecontexts.core.ContextState; 5 | import io.reactivex.Completable; 6 | import io.reactivex.CompletableObserver; 7 | import io.reactivex.disposables.Disposable; 8 | import io.reactivex.functions.BiFunction; 9 | 10 | public class ContextPropagatorOnCompletableCreateAction 11 | implements BiFunction { 12 | 13 | @Override 14 | public CompletableObserver apply(Completable completable, CompletableObserver observer) throws Exception { 15 | return new ContextCapturerCompletable(completable, observer); 16 | } 17 | 18 | final static class ContextCapturerCompletable implements CompletableObserver { 19 | 20 | private final CompletableObserver source; 21 | private final ContextState states; 22 | 23 | public ContextCapturerCompletable(Completable s, CompletableObserver o) { 24 | this.source = o; 25 | this.states = Context.capture(); 26 | } 27 | 28 | @Override 29 | public void onError(Throwable t) { 30 | ContextState previousStates = states.install(); 31 | try { 32 | source.onError(t); 33 | }finally { 34 | previousStates.restore(); 35 | } 36 | } 37 | 38 | @Override 39 | public void onSubscribe(Disposable d) { 40 | ContextState previousStates = states.install(); 41 | try { 42 | source.onSubscribe(d); 43 | }finally { 44 | previousStates.restore(); 45 | } 46 | } 47 | 48 | @Override 49 | public void onComplete() { 50 | ContextState previousStates = states.install(); 51 | try { 52 | source.onComplete(); 53 | }finally { 54 | previousStates.restore(); 55 | } 56 | } 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /propagators-rxjava2/src/main/java/io/reactiverse/reactivecontexts/propagators/rxjava2/ContextPropagatorOnFlowableAssemblyAction.java: -------------------------------------------------------------------------------- 1 | package io.reactiverse.reactivecontexts.propagators.rxjava2; 2 | 3 | import org.reactivestreams.Subscriber; 4 | 5 | import io.reactiverse.reactivecontexts.core.Context; 6 | import io.reactiverse.reactivecontexts.core.ContextState; 7 | import io.reactivex.Flowable; 8 | import io.reactivex.functions.Function; 9 | 10 | public class ContextPropagatorOnFlowableAssemblyAction implements Function { 11 | 12 | @Override 13 | public Flowable apply(Flowable t) throws Exception { 14 | return new ContextPropagatorFlowable(t); 15 | } 16 | 17 | public class ContextPropagatorFlowable extends Flowable { 18 | 19 | private Flowable source; 20 | private ContextState context; 21 | 22 | public ContextPropagatorFlowable(Flowable t) { 23 | this.source = t; 24 | this.context = Context.capture(); 25 | } 26 | 27 | @Override 28 | protected void subscribeActual(Subscriber observer) { 29 | ContextState previousContext = context.install(); 30 | try { 31 | source.subscribe(observer); 32 | }finally { 33 | previousContext.restore(); 34 | } 35 | } 36 | 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /propagators-rxjava2/src/main/java/io/reactiverse/reactivecontexts/propagators/rxjava2/ContextPropagatorOnFlowableCreateAction.java: -------------------------------------------------------------------------------- 1 | package io.reactiverse.reactivecontexts.propagators.rxjava2; 2 | 3 | import org.reactivestreams.Subscriber; 4 | import org.reactivestreams.Subscription; 5 | 6 | import io.reactiverse.reactivecontexts.core.Context; 7 | import io.reactiverse.reactivecontexts.core.ContextState; 8 | import io.reactivex.Flowable; 9 | import io.reactivex.functions.BiFunction; 10 | 11 | public class ContextPropagatorOnFlowableCreateAction 12 | implements BiFunction { 13 | 14 | @Override 15 | public Subscriber apply(Flowable flowable, Subscriber observer) throws Exception { 16 | return new ContextCapturerFlowable<>(flowable, observer); 17 | } 18 | 19 | public class ContextCapturerFlowable implements Subscriber { 20 | 21 | private final Subscriber source; 22 | private final ContextState states; 23 | 24 | public ContextCapturerFlowable(Flowable observable, Subscriber observer) { 25 | this.source = observer; 26 | this.states = Context.capture(); 27 | } 28 | 29 | @Override 30 | public void onComplete() { 31 | ContextState previousStates = states.install(); 32 | try { 33 | source.onComplete(); 34 | }finally { 35 | previousStates.restore(); 36 | } 37 | } 38 | 39 | @Override 40 | public void onError(Throwable t) { 41 | ContextState previousStates = states.install(); 42 | try { 43 | source.onError(t); 44 | }finally { 45 | previousStates.restore(); 46 | } 47 | } 48 | 49 | @Override 50 | public void onNext(T v) { 51 | ContextState previousStates = states.install(); 52 | try { 53 | source.onNext(v); 54 | }finally { 55 | previousStates.restore(); 56 | } 57 | } 58 | 59 | @Override 60 | public void onSubscribe(Subscription s) { 61 | ContextState previousStates = states.install(); 62 | try { 63 | source.onSubscribe(s); 64 | }finally { 65 | previousStates.restore(); 66 | } 67 | } 68 | } 69 | 70 | } 71 | -------------------------------------------------------------------------------- /propagators-rxjava2/src/main/java/io/reactiverse/reactivecontexts/propagators/rxjava2/ContextPropagatorOnMaybeAssemblyAction.java: -------------------------------------------------------------------------------- 1 | package io.reactiverse.reactivecontexts.propagators.rxjava2; 2 | 3 | import io.reactiverse.reactivecontexts.core.Context; 4 | import io.reactiverse.reactivecontexts.core.ContextState; 5 | import io.reactivex.Maybe; 6 | import io.reactivex.MaybeObserver; 7 | import io.reactivex.functions.Function; 8 | 9 | public class ContextPropagatorOnMaybeAssemblyAction implements Function { 10 | 11 | @Override 12 | public Maybe apply(Maybe t) throws Exception { 13 | return new ContextPropagatorMaybe(t); 14 | } 15 | 16 | public class ContextPropagatorMaybe extends Maybe { 17 | 18 | private Maybe source; 19 | private ContextState context; 20 | 21 | public ContextPropagatorMaybe(Maybe t) { 22 | this.source = t; 23 | this.context = Context.capture(); 24 | } 25 | 26 | @Override 27 | protected void subscribeActual(MaybeObserver observer) { 28 | ContextState previousContext = context.install(); 29 | try { 30 | source.subscribe(observer); 31 | }finally { 32 | previousContext.restore(); 33 | } 34 | } 35 | 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /propagators-rxjava2/src/main/java/io/reactiverse/reactivecontexts/propagators/rxjava2/ContextPropagatorOnMaybeCreateAction.java: -------------------------------------------------------------------------------- 1 | package io.reactiverse.reactivecontexts.propagators.rxjava2; 2 | 3 | import io.reactiverse.reactivecontexts.core.Context; 4 | import io.reactiverse.reactivecontexts.core.ContextState; 5 | import io.reactivex.Maybe; 6 | import io.reactivex.MaybeObserver; 7 | import io.reactivex.disposables.Disposable; 8 | import io.reactivex.functions.BiFunction; 9 | 10 | public class ContextPropagatorOnMaybeCreateAction 11 | implements BiFunction { 12 | 13 | @Override 14 | public MaybeObserver apply(Maybe maybe, MaybeObserver observer) throws Exception { 15 | return new ContextCapturerMaybe<>(maybe, observer); 16 | } 17 | 18 | public class ContextCapturerMaybe implements MaybeObserver { 19 | 20 | private final MaybeObserver source; 21 | private final ContextState states; 22 | 23 | public ContextCapturerMaybe(Maybe observable, MaybeObserver observer) { 24 | this.source = observer; 25 | this.states = Context.capture(); 26 | } 27 | 28 | @Override 29 | public void onComplete() { 30 | ContextState previousStates = states.install(); 31 | try { 32 | source.onComplete(); 33 | }finally { 34 | previousStates.restore(); 35 | } 36 | } 37 | 38 | @Override 39 | public void onError(Throwable t) { 40 | ContextState previousStates = states.install(); 41 | try { 42 | source.onError(t); 43 | }finally { 44 | previousStates.restore(); 45 | } 46 | } 47 | 48 | @Override 49 | public void onSubscribe(Disposable d) { 50 | ContextState previousStates = states.install(); 51 | try { 52 | source.onSubscribe(d); 53 | }finally { 54 | previousStates.restore(); 55 | } 56 | } 57 | 58 | @Override 59 | public void onSuccess(T v) { 60 | ContextState previousStates = states.install(); 61 | try { 62 | source.onSuccess(v); 63 | }finally { 64 | previousStates.restore(); 65 | } 66 | } 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /propagators-rxjava2/src/main/java/io/reactiverse/reactivecontexts/propagators/rxjava2/ContextPropagatorOnObservableAssemblyAction.java: -------------------------------------------------------------------------------- 1 | package io.reactiverse.reactivecontexts.propagators.rxjava2; 2 | 3 | import io.reactiverse.reactivecontexts.core.Context; 4 | import io.reactiverse.reactivecontexts.core.ContextState; 5 | import io.reactivex.Observable; 6 | import io.reactivex.Observer; 7 | import io.reactivex.functions.Function; 8 | 9 | public class ContextPropagatorOnObservableAssemblyAction implements Function { 10 | 11 | @Override 12 | public Observable apply(Observable t) throws Exception { 13 | return new ContextPropagatorObservable(t); 14 | } 15 | 16 | public class ContextPropagatorObservable extends Observable { 17 | 18 | private Observable source; 19 | private ContextState context; 20 | 21 | public ContextPropagatorObservable(Observable t) { 22 | this.source = t; 23 | this.context = Context.capture(); 24 | } 25 | 26 | @Override 27 | protected void subscribeActual(Observer observer) { 28 | ContextState previousContext = context.install(); 29 | try { 30 | source.subscribe(observer); 31 | }finally { 32 | previousContext.restore(); 33 | } 34 | } 35 | 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /propagators-rxjava2/src/main/java/io/reactiverse/reactivecontexts/propagators/rxjava2/ContextPropagatorOnObservableCreateAction.java: -------------------------------------------------------------------------------- 1 | package io.reactiverse.reactivecontexts.propagators.rxjava2; 2 | 3 | import io.reactiverse.reactivecontexts.core.Context; 4 | import io.reactiverse.reactivecontexts.core.ContextState; 5 | import io.reactivex.Observable; 6 | import io.reactivex.Observer; 7 | import io.reactivex.disposables.Disposable; 8 | import io.reactivex.functions.BiFunction; 9 | 10 | public class ContextPropagatorOnObservableCreateAction 11 | implements BiFunction { 12 | 13 | @Override 14 | public Observer apply(Observable observable, Observer observer) throws Exception { 15 | return new ContextCapturerObservable(observable, observer); 16 | } 17 | 18 | public class ContextCapturerObservable implements Observer { 19 | 20 | private final Observer source; 21 | private final ContextState states; 22 | 23 | public ContextCapturerObservable(Observable observable, Observer observer) { 24 | this.source = observer; 25 | this.states = Context.capture(); 26 | } 27 | 28 | @Override 29 | public void onComplete() { 30 | ContextState previousStates = states.install(); 31 | try { 32 | source.onComplete(); 33 | }finally { 34 | previousStates.restore(); 35 | } 36 | } 37 | 38 | @Override 39 | public void onError(Throwable t) { 40 | ContextState previousStates = states.install(); 41 | try { 42 | source.onError(t); 43 | }finally { 44 | previousStates.restore(); 45 | } 46 | } 47 | 48 | @Override 49 | public void onNext(T v) { 50 | ContextState previousStates = states.install(); 51 | try { 52 | source.onNext(v); 53 | }finally { 54 | previousStates.restore(); 55 | } 56 | } 57 | 58 | @Override 59 | public void onSubscribe(Disposable d) { 60 | ContextState previousStates = states.install(); 61 | try { 62 | source.onSubscribe(d); 63 | }finally { 64 | previousStates.restore(); 65 | } 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /propagators-rxjava2/src/main/java/io/reactiverse/reactivecontexts/propagators/rxjava2/ContextPropagatorOnSingleAssemblyAction.java: -------------------------------------------------------------------------------- 1 | package io.reactiverse.reactivecontexts.propagators.rxjava2; 2 | 3 | import io.reactiverse.reactivecontexts.core.Context; 4 | import io.reactiverse.reactivecontexts.core.ContextState; 5 | import io.reactivex.Single; 6 | import io.reactivex.SingleObserver; 7 | import io.reactivex.functions.Function; 8 | 9 | public class ContextPropagatorOnSingleAssemblyAction implements Function { 10 | 11 | @Override 12 | public Single apply(Single t) throws Exception { 13 | return new ContextPropagatorSingle(t); 14 | } 15 | 16 | public class ContextPropagatorSingle extends Single { 17 | 18 | private Single source; 19 | private ContextState context; 20 | 21 | public ContextPropagatorSingle(Single t) { 22 | this.source = t; 23 | this.context = Context.capture(); 24 | } 25 | 26 | @Override 27 | protected void subscribeActual(SingleObserver observer) { 28 | ContextState previousContext = context.install(); 29 | try { 30 | source.subscribe(observer); 31 | }finally { 32 | previousContext.restore(); 33 | } 34 | } 35 | 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /propagators-rxjava2/src/main/java/io/reactiverse/reactivecontexts/propagators/rxjava2/ContextPropagatorOnSingleCreateAction.java: -------------------------------------------------------------------------------- 1 | package io.reactiverse.reactivecontexts.propagators.rxjava2; 2 | 3 | import io.reactiverse.reactivecontexts.core.Context; 4 | import io.reactiverse.reactivecontexts.core.ContextState; 5 | import io.reactivex.Single; 6 | import io.reactivex.SingleObserver; 7 | import io.reactivex.disposables.Disposable; 8 | import io.reactivex.functions.BiFunction; 9 | 10 | public class ContextPropagatorOnSingleCreateAction implements BiFunction { 11 | 12 | @Override 13 | public SingleObserver apply(Single s, SingleObserver o) throws Exception { 14 | return new ContextCapturerSingle(s, o); 15 | } 16 | 17 | final static class ContextCapturerSingle implements SingleObserver { 18 | 19 | private final SingleObserver source; 20 | private final ContextState states; 21 | 22 | public ContextCapturerSingle(Single s, SingleObserver o) { 23 | this.source = o; 24 | this.states = Context.capture(); 25 | } 26 | 27 | @Override 28 | public void onError(Throwable t) { 29 | ContextState previousStates = states.install(); 30 | try { 31 | source.onError(t); 32 | }finally { 33 | previousStates.restore(); 34 | } 35 | } 36 | 37 | @Override 38 | public void onSubscribe(Disposable d) { 39 | ContextState previousStates = states.install(); 40 | try { 41 | source.onSubscribe(d); 42 | }finally { 43 | previousStates.restore(); 44 | } 45 | } 46 | 47 | @Override 48 | public void onSuccess(T v) { 49 | ContextState previousStates = states.install(); 50 | try { 51 | source.onSuccess(v); 52 | }finally { 53 | previousStates.restore(); 54 | } 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /propagators-rxjava2/src/main/java/io/reactiverse/reactivecontexts/propagators/rxjava2/RxJava2ContextPropagator.java: -------------------------------------------------------------------------------- 1 | package io.reactiverse.reactivecontexts.propagators.rxjava2; 2 | 3 | import io.reactiverse.reactivecontexts.core.ContextPropagator; 4 | import io.reactivex.Completable; 5 | import io.reactivex.Flowable; 6 | import io.reactivex.Maybe; 7 | import io.reactivex.Observable; 8 | import io.reactivex.Single; 9 | import io.reactivex.plugins.RxJavaPlugins; 10 | 11 | /** 12 | * Reactive Context propagator for RxJava 1. Supports propagating context to all {@link Single}, 13 | * {@link Observable}, {@link Completable}, {@link Flowable} and {@link Maybe} types. 14 | * 15 | * @author Stéphane Épardaud 16 | */ 17 | public class RxJava2ContextPropagator implements ContextPropagator { 18 | 19 | public void setup() { 20 | RxJavaPlugins.setOnSingleSubscribe(new ContextPropagatorOnSingleCreateAction()); 21 | RxJavaPlugins.setOnCompletableSubscribe(new ContextPropagatorOnCompletableCreateAction()); 22 | RxJavaPlugins.setOnFlowableSubscribe(new ContextPropagatorOnFlowableCreateAction()); 23 | RxJavaPlugins.setOnMaybeSubscribe(new ContextPropagatorOnMaybeCreateAction()); 24 | RxJavaPlugins.setOnObservableSubscribe(new ContextPropagatorOnObservableCreateAction()); 25 | 26 | RxJavaPlugins.setOnSingleAssembly(new ContextPropagatorOnSingleAssemblyAction()); 27 | RxJavaPlugins.setOnCompletableAssembly(new ContextPropagatorOnCompletableAssemblyAction()); 28 | RxJavaPlugins.setOnFlowableAssembly(new ContextPropagatorOnFlowableAssemblyAction()); 29 | RxJavaPlugins.setOnMaybeAssembly(new ContextPropagatorOnMaybeAssemblyAction()); 30 | RxJavaPlugins.setOnObservableAssembly(new ContextPropagatorOnObservableAssemblyAction()); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /propagators-rxjava2/src/main/resources/META-INF/services/io.reactiverse.reactivecontexts.core.ContextPropagator: -------------------------------------------------------------------------------- 1 | io.reactiverse.reactivecontexts.propagators.rxjava2.RxJava2ContextPropagator 2 | -------------------------------------------------------------------------------- /tests/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | reactive-contexts-test 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.jdt.core.javanature 21 | org.eclipse.m2e.core.maven2Nature 22 | 23 | 24 | -------------------------------------------------------------------------------- /tests/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | 5 | io.reactiverse 6 | reactive-contexts-parent 7 | 1.0.2-SNAPSHOT 8 | 9 | reactive-contexts-test 10 | reactive-contexts-test 11 | http://maven.apache.org 12 | 13 | true 14 | UTF-8 15 | 16 | 17 | 18 | junit 19 | junit 20 | test 21 | 22 | 23 | 24 | ${project.groupId} 25 | reactive-contexts-core 26 | ${project.version} 27 | 28 | 29 | 30 | ${project.groupId} 31 | reactive-contexts-propagators-rxjava1 32 | ${project.version} 33 | test 34 | 35 | 36 | 37 | ${project.groupId} 38 | reactive-contexts-propagators-rxjava2 39 | ${project.version} 40 | test 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | org.apache.maven.plugins 49 | maven-deploy-plugin 50 | 51 | true 52 | 53 | 54 | 55 | org.apache.maven.plugins 56 | maven-install-plugin 57 | 58 | true 59 | 60 | 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /tests/src/main/java/io/reactiverse/reactivecontexts/test/MyContext.java: -------------------------------------------------------------------------------- 1 | package io.reactiverse.reactivecontexts.test; 2 | 3 | public class MyContext { 4 | private static ThreadLocal context = new ThreadLocal(); 5 | 6 | public static void init() { 7 | context.set(new MyContext()); 8 | } 9 | 10 | public static void clear() { 11 | context.remove(); 12 | } 13 | 14 | public static MyContext get() { 15 | return context.get(); 16 | } 17 | 18 | public static void set(MyContext newContext) { 19 | context.set(newContext); 20 | } 21 | 22 | private String reqId; 23 | 24 | public void set(String reqId) { 25 | this.reqId = reqId; 26 | } 27 | 28 | public String getReqId() { 29 | return reqId; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /tests/src/main/java/io/reactiverse/reactivecontexts/test/MyContextProvider.java: -------------------------------------------------------------------------------- 1 | package io.reactiverse.reactivecontexts.test; 2 | 3 | import io.reactiverse.reactivecontexts.core.ContextProvider; 4 | 5 | public class MyContextProvider implements ContextProvider { 6 | 7 | @Override 8 | public MyContext install(MyContext state) { 9 | MyContext old = MyContext.get(); 10 | MyContext.set(state); 11 | return old; 12 | } 13 | 14 | @Override 15 | public void restore(MyContext previousState) { 16 | MyContext.set(previousState); 17 | } 18 | 19 | @Override 20 | public MyContext capture() { 21 | return MyContext.get(); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /tests/src/main/resources/META-INF/services/io.reactiverse.reactivecontexts.core.ContextProvider: -------------------------------------------------------------------------------- 1 | io.reactiverse.reactivecontexts.test.MyContextProvider 2 | -------------------------------------------------------------------------------- /tests/src/test/java/io/reactiverse/reactivecontexts/test/BackPressureExceptionTest.java: -------------------------------------------------------------------------------- 1 | package io.reactiverse.reactivecontexts.test; 2 | 3 | import io.reactiverse.reactivecontexts.core.Context; 4 | import io.reactivex.observers.TestObserver; 5 | import rx.observers.AssertableSubscriber; 6 | 7 | import org.junit.BeforeClass; 8 | import org.junit.Test; 9 | 10 | import java.util.concurrent.TimeUnit; 11 | 12 | import static java.util.Arrays.asList; 13 | 14 | public class BackPressureExceptionTest { 15 | 16 | @BeforeClass 17 | public static void before() { 18 | Context.load(); 19 | } 20 | 21 | 22 | @Test 23 | public void testBackPressureRxJava1() { 24 | AssertableSubscriber test = 25 | rx.Observable.from(asList(1,2,3,4,5,6)) 26 | .concatMap(integer -> rx.Observable.just(integer).delay(100, TimeUnit.MILLISECONDS)) 27 | .test(); 28 | 29 | test.awaitTerminalEvent(); 30 | 31 | test.assertNoErrors(); 32 | test.assertReceivedOnNext(asList(1,2,3,4,5,6)); 33 | } 34 | 35 | @Test 36 | public void testBackPressureRxJava2() { 37 | TestObserver test = 38 | io.reactivex.Observable.just(1,2,3,4,5,6) 39 | .concatMap(integer -> io.reactivex.Observable.just(integer).delay(100, TimeUnit.MILLISECONDS)) 40 | .test(); 41 | 42 | test.awaitTerminalEvent(); 43 | 44 | test.assertNoErrors(); 45 | test.assertValues(1,2,3,4,5,6); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /tests/src/test/java/io/reactiverse/reactivecontexts/test/ManualPropagationMultipleRequestTest.java: -------------------------------------------------------------------------------- 1 | package io.reactiverse.reactivecontexts.test; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | import java.util.concurrent.CountDownLatch; 5 | import java.util.concurrent.ExecutorService; 6 | import java.util.concurrent.Executors; 7 | import java.util.concurrent.Future; 8 | 9 | import org.junit.Assert; 10 | import org.junit.BeforeClass; 11 | import org.junit.Test; 12 | 13 | import io.reactiverse.reactivecontexts.core.Context; 14 | 15 | public class ManualPropagationMultipleRequestTest { 16 | 17 | @BeforeClass 18 | public static void init() { 19 | // initialise 20 | Context.load(); 21 | } 22 | 23 | public void newRequest(String reqId) { 24 | // seed 25 | MyContext.init(); 26 | 27 | MyContext.get().set(reqId); 28 | } 29 | 30 | public void endOfRequest() { 31 | MyContext.clear(); 32 | } 33 | 34 | @Test 35 | public void testRunnableOnSingleWorkerThread() throws Throwable { 36 | testRunnable(Executors.newFixedThreadPool(1)); 37 | } 38 | 39 | @Test 40 | public void testRunnableOnTwoWorkerThread() throws Throwable { 41 | testRunnable(Executors.newFixedThreadPool(2)); 42 | } 43 | 44 | private void testRunnable(ExecutorService executor) throws Throwable { 45 | newRequest("req 1"); 46 | Future task1 = executor.submit(Context.wrap(() -> { 47 | checkContextCaptured("req 1"); 48 | endOfRequest(); 49 | })); 50 | 51 | newRequest("req 2"); 52 | Future task2 = executor.submit(Context.wrap(() -> { 53 | checkContextCaptured("req 2"); 54 | endOfRequest(); 55 | })); 56 | 57 | task1.get(); 58 | task2.get(); 59 | executor.shutdown(); 60 | } 61 | 62 | @Test 63 | public void testCompletionStageOnSingleWorkerThread() throws Throwable { 64 | testCompletionStage(Executors.newFixedThreadPool(1)); 65 | } 66 | 67 | @Test 68 | public void testCompletionStageOnTwoWorkerThread() throws Throwable { 69 | testCompletionStage(Executors.newFixedThreadPool(2)); 70 | } 71 | 72 | private void testCompletionStage(ExecutorService executor) throws Throwable { 73 | CountDownLatch latch = new CountDownLatch(2); 74 | 75 | Throwable[] ret = new Throwable[2]; 76 | 77 | newRequest("req 1"); 78 | CompletableFuture cf1 = Context.wrap(new CompletableFuture<>()); 79 | cf1.handleAsync((v, t) -> { 80 | try { 81 | ret[0] = t; 82 | checkContextCaptured("req 1"); 83 | endOfRequest(); 84 | }catch(Throwable t2) { 85 | ret[0] = t2; 86 | } 87 | latch.countDown(); 88 | return null; 89 | }, executor); 90 | 91 | newRequest("req 2"); 92 | CompletableFuture cf2 = Context.wrap(new CompletableFuture<>()); 93 | cf2.handleAsync((v, t) -> { 94 | try { 95 | ret[1] = t; 96 | checkContextCaptured("req 2"); 97 | endOfRequest(); 98 | }catch(Throwable t2) { 99 | ret[1] = t2; 100 | } 101 | latch.countDown(); 102 | return null; 103 | }, executor); 104 | 105 | cf1.complete(null); 106 | cf2.complete(null); 107 | latch.await(); 108 | if(ret[0] != null) 109 | throw ret[0]; 110 | if(ret[1] != null) 111 | throw ret[1]; 112 | executor.shutdown(); 113 | } 114 | 115 | private void checkContextCaptured(String reqId) { 116 | Assert.assertEquals(reqId, MyContext.get().getReqId()); 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /tests/src/test/java/io/reactiverse/reactivecontexts/test/RxJava1MultipleRequestTest.java: -------------------------------------------------------------------------------- 1 | package io.reactiverse.reactivecontexts.test; 2 | 3 | import java.util.concurrent.CountDownLatch; 4 | import java.util.concurrent.Executor; 5 | import java.util.concurrent.Executors; 6 | 7 | import org.junit.Assert; 8 | import org.junit.BeforeClass; 9 | import org.junit.Test; 10 | 11 | import io.reactiverse.reactivecontexts.core.Context; 12 | import io.reactiverse.reactivecontexts.test.MyContext; 13 | import rx.Emitter.BackpressureMode; 14 | import rx.Observable; 15 | import rx.Scheduler; 16 | import rx.schedulers.Schedulers; 17 | 18 | public class RxJava1MultipleRequestTest { 19 | 20 | @BeforeClass 21 | public static void init() { 22 | // initialise 23 | Context.load(); 24 | } 25 | 26 | public void newRequest(String reqId) { 27 | // seed 28 | MyContext.init(); 29 | 30 | MyContext.get().set(reqId); 31 | } 32 | 33 | public void endOfRequest() { 34 | MyContext.clear(); 35 | } 36 | 37 | @Test 38 | public void testObservableOnSingleWorkerThread() throws Throwable { 39 | Executor myExecutor = Executors.newSingleThreadExecutor(); 40 | testObservable(Schedulers.from(myExecutor)); 41 | } 42 | 43 | @Test 44 | public void testObservableOnNewWorkerThreads() throws Throwable { 45 | testObservable(Schedulers.newThread()); 46 | } 47 | 48 | private void testObservable(Scheduler scheduler) throws Throwable { 49 | CountDownLatch latch = new CountDownLatch(4); 50 | 51 | Throwable[] ret = new Throwable[1]; 52 | 53 | newRequest("req 1"); 54 | Observable.create(emitter -> { 55 | checkContextCaptured("req 1"); 56 | new Thread(() -> { 57 | emitter.onNext("a"); 58 | try { 59 | Thread.sleep(500); 60 | } catch (InterruptedException e) { 61 | // TODO Auto-generated catch block 62 | e.printStackTrace(); 63 | } 64 | emitter.onNext("b"); 65 | emitter.onCompleted(); 66 | }).start(); 67 | }, BackpressureMode.BUFFER) 68 | .subscribeOn(scheduler) 69 | .observeOn(scheduler) 70 | .doOnCompleted(() -> { 71 | checkContextCaptured("req 1"); 72 | endOfRequest(); 73 | }) 74 | .subscribe(success -> { 75 | checkContextCaptured("req 1"); 76 | latch.countDown(); 77 | }, error -> { 78 | ret[0] = error; 79 | latch.countDown(); 80 | latch.countDown(); 81 | }); 82 | 83 | newRequest("req 2"); 84 | Observable.create(emitter -> { 85 | checkContextCaptured("req 2"); 86 | new Thread(() -> { 87 | emitter.onNext("a"); 88 | try { 89 | Thread.sleep(500); 90 | } catch (InterruptedException e) { 91 | // TODO Auto-generated catch block 92 | e.printStackTrace(); 93 | } 94 | emitter.onNext("b"); 95 | emitter.onCompleted(); 96 | }).start(); 97 | }, BackpressureMode.BUFFER) 98 | .subscribeOn(scheduler) 99 | .observeOn(scheduler) 100 | .doOnCompleted(() -> { 101 | checkContextCaptured("req 2"); 102 | endOfRequest(); 103 | }) 104 | .subscribe(success -> { 105 | checkContextCaptured("req 2"); 106 | latch.countDown(); 107 | }, error -> { 108 | ret[0] = error; 109 | latch.countDown(); 110 | latch.countDown(); 111 | }); 112 | 113 | latch.await(); 114 | if (ret[0] != null) 115 | throw ret[0]; 116 | } 117 | 118 | private void checkContextCaptured(String reqId) { 119 | Assert.assertEquals(reqId, MyContext.get().getReqId()); 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /tests/src/test/java/io/reactiverse/reactivecontexts/test/RxJava1Test.java: -------------------------------------------------------------------------------- 1 | package io.reactiverse.reactivecontexts.test; 2 | 3 | import java.util.concurrent.CountDownLatch; 4 | 5 | import org.junit.After; 6 | import org.junit.Assert; 7 | import org.junit.Before; 8 | import org.junit.BeforeClass; 9 | import org.junit.Test; 10 | 11 | import io.reactiverse.reactivecontexts.core.Context; 12 | import io.reactiverse.reactivecontexts.test.MyContext; 13 | import rx.Completable; 14 | import rx.Emitter.BackpressureMode; 15 | import rx.Observable; 16 | import rx.Single; 17 | import rx.schedulers.Schedulers; 18 | 19 | public class RxJava1Test { 20 | 21 | @BeforeClass 22 | public static void init() { 23 | // initialise 24 | Context.getInstance(); 25 | } 26 | 27 | @Before 28 | public void before() { 29 | MyContext.init(); 30 | MyContext.get().set("test"); 31 | } 32 | 33 | @After 34 | public void after() { 35 | MyContext.clear(); 36 | } 37 | 38 | @Test 39 | public void testCompletable() throws Throwable { 40 | // check initial state 41 | checkContextCaptured(); 42 | CountDownLatch latch = new CountDownLatch(1); 43 | 44 | Throwable[] ret = new Throwable[1]; 45 | Completable.create(subscriber -> { 46 | // check deferred state 47 | checkContextCaptured(); 48 | 49 | subscriber.onCompleted(); 50 | }) 51 | .subscribeOn(Schedulers.newThread()) 52 | .subscribe(() -> { 53 | latch.countDown(); 54 | }, error -> { 55 | ret[0] = error; 56 | latch.countDown(); 57 | }); 58 | 59 | latch.await(); 60 | if (ret[0] != null) 61 | throw ret[0]; 62 | } 63 | 64 | @Test 65 | public void testSingle() throws Throwable { 66 | // check initial state 67 | checkContextCaptured(); 68 | CountDownLatch latch = new CountDownLatch(1); 69 | 70 | Throwable[] ret = new Throwable[1]; 71 | Single.create(subscriber -> { 72 | // check deferred state 73 | checkContextCaptured(); 74 | 75 | subscriber.onSuccess("YES"); 76 | }) 77 | .subscribeOn(Schedulers.newThread()) 78 | .subscribe(success -> { 79 | latch.countDown(); 80 | }, error -> { 81 | ret[0] = error; 82 | latch.countDown(); 83 | }); 84 | 85 | latch.await(); 86 | if (ret[0] != null) 87 | throw ret[0]; 88 | } 89 | 90 | @Test 91 | public void testObservable() throws Throwable { 92 | // check initial state 93 | checkContextCaptured(); 94 | CountDownLatch latch = new CountDownLatch(1); 95 | 96 | Throwable[] ret = new Throwable[1]; 97 | Observable.create(emitter -> { 98 | // check deferred state 99 | checkContextCaptured(); 100 | 101 | emitter.onNext("a"); 102 | emitter.onCompleted(); 103 | }, BackpressureMode.BUFFER) 104 | .subscribeOn(Schedulers.newThread()) 105 | .subscribe(success -> { 106 | latch.countDown(); 107 | }, error -> { 108 | ret[0] = error; 109 | latch.countDown(); 110 | }); 111 | 112 | latch.await(); 113 | if (ret[0] != null) 114 | throw ret[0]; 115 | } 116 | 117 | private void checkContextCaptured() { 118 | Assert.assertEquals("test", MyContext.get().getReqId()); 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /tests/src/test/java/io/reactiverse/reactivecontexts/test/RxJava2Test.java: -------------------------------------------------------------------------------- 1 | package io.reactiverse.reactivecontexts.test; 2 | 3 | import java.util.concurrent.CountDownLatch; 4 | 5 | import org.junit.After; 6 | import org.junit.Assert; 7 | import org.junit.Before; 8 | import org.junit.BeforeClass; 9 | import org.junit.Test; 10 | 11 | import io.reactiverse.reactivecontexts.core.Context; 12 | import io.reactiverse.reactivecontexts.test.MyContext; 13 | import io.reactivex.BackpressureStrategy; 14 | import io.reactivex.Completable; 15 | import io.reactivex.Flowable; 16 | import io.reactivex.Maybe; 17 | import io.reactivex.Observable; 18 | import io.reactivex.Single; 19 | import io.reactivex.schedulers.Schedulers; 20 | 21 | public class RxJava2Test { 22 | 23 | @BeforeClass 24 | public static void init() { 25 | // initialise 26 | Context.load(); 27 | } 28 | 29 | @Before 30 | public void before() { 31 | MyContext.init(); 32 | MyContext.get().set("test"); 33 | } 34 | 35 | @After 36 | public void after() { 37 | MyContext.clear(); 38 | } 39 | 40 | @Test 41 | public void testCompletable() throws Throwable { 42 | // check initial state 43 | checkContextCaptured(); 44 | CountDownLatch latch = new CountDownLatch(1); 45 | 46 | Throwable[] ret = new Throwable[1]; 47 | Completable.create(subscriber -> { 48 | // check deferred state 49 | checkContextCaptured(); 50 | 51 | subscriber.onComplete(); 52 | }) 53 | .subscribeOn(Schedulers.newThread()) 54 | .subscribe(() -> { 55 | latch.countDown(); 56 | }, error -> { 57 | ret[0] = error; 58 | latch.countDown(); 59 | }); 60 | 61 | latch.await(); 62 | if (ret[0] != null) 63 | throw ret[0]; 64 | } 65 | 66 | @Test 67 | public void testSingle() throws Throwable { 68 | // check initial state 69 | checkContextCaptured(); 70 | CountDownLatch latch = new CountDownLatch(1); 71 | 72 | Throwable[] ret = new Throwable[1]; 73 | Single.create(subscriber -> { 74 | // check deferred state 75 | checkContextCaptured(); 76 | 77 | subscriber.onSuccess("YES"); 78 | }) 79 | .subscribeOn(Schedulers.newThread()) 80 | .subscribe(success -> { 81 | latch.countDown(); 82 | }, error -> { 83 | ret[0] = error; 84 | latch.countDown(); 85 | }); 86 | 87 | latch.await(); 88 | if (ret[0] != null) 89 | throw ret[0]; 90 | } 91 | 92 | @Test 93 | public void testObservable() throws Throwable { 94 | // check initial state 95 | checkContextCaptured(); 96 | CountDownLatch latch = new CountDownLatch(1); 97 | 98 | Throwable[] ret = new Throwable[1]; 99 | Observable.create(emitter -> { 100 | // check deferred state 101 | checkContextCaptured(); 102 | 103 | emitter.onNext("a"); 104 | emitter.onComplete(); 105 | }) 106 | .subscribeOn(Schedulers.newThread()) 107 | .subscribe(success -> { 108 | latch.countDown(); 109 | }, error -> { 110 | ret[0] = error; 111 | latch.countDown(); 112 | }); 113 | 114 | latch.await(); 115 | if (ret[0] != null) 116 | throw ret[0]; 117 | } 118 | 119 | @Test 120 | public void testFlowable() throws Throwable { 121 | // check initial state 122 | checkContextCaptured(); 123 | CountDownLatch latch = new CountDownLatch(1); 124 | 125 | Throwable[] ret = new Throwable[1]; 126 | Flowable.create(emitter -> { 127 | // check deferred state 128 | checkContextCaptured(); 129 | 130 | emitter.onNext("a"); 131 | emitter.onComplete(); 132 | }, BackpressureStrategy.BUFFER) 133 | .subscribeOn(Schedulers.newThread()) 134 | .subscribe(success -> { 135 | latch.countDown(); 136 | }, error -> { 137 | ret[0] = error; 138 | latch.countDown(); 139 | }); 140 | 141 | latch.await(); 142 | if (ret[0] != null) 143 | throw ret[0]; 144 | } 145 | 146 | @Test 147 | public void testMaybe() throws Throwable { 148 | // check initial state 149 | checkContextCaptured(); 150 | CountDownLatch latch = new CountDownLatch(1); 151 | 152 | Throwable[] ret = new Throwable[1]; 153 | Maybe.create(emitter -> { 154 | // check deferred state 155 | checkContextCaptured(); 156 | 157 | emitter.onSuccess("a"); 158 | emitter.onComplete(); 159 | }) 160 | .subscribeOn(Schedulers.newThread()) 161 | .subscribe(success -> { 162 | latch.countDown(); 163 | }, error -> { 164 | ret[0] = error; 165 | latch.countDown(); 166 | }); 167 | 168 | latch.await(); 169 | if (ret[0] != null) 170 | throw ret[0]; 171 | } 172 | 173 | private void checkContextCaptured() { 174 | Assert.assertEquals("test", MyContext.get().getReqId()); 175 | } 176 | } 177 | --------------------------------------------------------------------------------