1

I am new to Reactive programming paradigm, but recently I have decided to base a simple Http client on Spring WebClient, since the old sync RestTemplate is already under maintenance and might be deprecated in upoming releases.

So first I had a look at Spring documentation and, after that, I've searched the web for examples.

I must say that (only for the time being) I have consciously decided not to go through the Reactor lib documentation, so beyond the Publisher-Subscriber pattern, my knowledge about Mono's and Flux's is scarce. I focused instead on having something working.

My scenario is a simple POST to send a callback to a Server from which the client is only interested in response status code. No body is returned. So I finally came up with this code snippet that works:

private void notifyJobSuccess(final InternalJobData jobData) {
        
        SuccessResult result = new SuccessResult();
        result.setJobId(jobData.getJobId());
        result.setStatus(Status.SUCCESS);
        result.setInstanceId(jobData.getInstanceId());
        
        log.info("Result to send back:" + System.lineSeparator() + "{}", result.toString());
        
        this.webClient.post()
            .uri(jobData.getCallbackUrl())
            .body(Mono.just(result), ReplaySuccessResult.class)
            .retrieve()
            .onStatus(s -> s.equals(HttpStatus.OK), resp -> {   
                log.info("Expected CCDM response received with HttpStatus = {}", HttpStatus.OK);
                return Mono.empty();
            })
            .onStatus(HttpStatus::is4xxClientError, resp -> {   
                log.error("CCDM response received with unexpected Client Error HttpStatus {}. "
                        + "The POST request sent by EDA2 stub did not match CCDM OpenApi spec", resp.statusCode());
                return Mono.empty();
            })
            .onStatus(HttpStatus::is5xxServerError, resp -> {   
                log.error("CCDM response received with unexpected Server Error HttpStatus {}", resp.statusCode());
                return Mono.empty();
            }).bodyToMono(Void.class).subscribe(Eda2StubHttpClient::handleResponseFromCcdm);
        
    }

My poor understanding of how the reactive WebClient works starts with the call to subscribe. None of the tens of examples that I checked before coding my client included such a call, but the fact is that before I included that call, the Server was sitting forever waiting for the request.

Then I bumped into the mantra "Nothing happens until you subscribe". Knowing the pattern Plublisher-Subscriber I knew that, but I (wrongly) assumed that the subscription was handled by WebClient API, in any of the exchage, or bodyToMono methods... block() definitely must subscribe, because when you block it, the request gets out at once.

So my first question is: is this call to subscribe() really needed?

Second question is why the method StubHttpClient::handleResponse is never called back. For this, the only explanation that I find is that as the Mono returned is a Mono<Void>, because there is nothing in the response besides the status code, as it is never instantiated, the method is totally dummy... I could even replace it by just .subscribe(). Is this a correct assumption.

Last, is it too much to ask for a complete example of a a method receiving a body in a Mono that is later consumed? All examples I find just focus on getting the request out, but how the Mono or Flux is later consumed is now beyond my understanding... I know that I have to end up checking the Reactor doc sooner better than later, but I would appreciate a bit of help because I am having issues with Exceptions and errors handlin.

Thanks!

sandrooco
  • 8,016
  • 9
  • 48
  • 86
WinterBoot
  • 399
  • 1
  • 5
  • 15
  • `I must say that I have consciously decided not to go through the Reactor lib documentation` then tbh i suggest you do so [how much research effort is expected of stack overflow users](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) – Toerktumlare Jun 09 '21 at 23:22
  • possible duplicate? [who calls subscribe on Flux or Mono in reactive webapplication](https://stackoverflow.com/questions/56487429/who-calls-subscribe-on-flux-or-mono-in-reactive-webapplication) – Toerktumlare Jun 09 '21 at 23:25
  • @ToerkTumlare, I've admitted that I haven't gone deep into the Reactor documentation before my attempt to use Spring Reactive WebClient, pretty much like hundreds of people do, I am pretty sure. But I can tell for certain that I NEVER post any question before trying myself to find a solution/explanation. As a matter of fact, you are redirecting me to a question pretty much like mine, but without acknowledging what has not been investigated. Anyway, if you think otherwise, that's fine with me. At the end of the day, I don't care much about reputation. – WinterBoot Jun 10 '21 at 07:18
  • @Toerktumlare, the post you suggest ONLY addresses my first question, yes, that's right. With this one I was also aming to have one post where someone could help to provide a complete example of use of WebClient, not just the thousands of lines spread all over the web to just get the request out of the application, which is the easy part. – WinterBoot Jun 10 '21 at 07:23
  • Last, to be honest, if you think this question doesn't show much of investigation, I cannot imagine what you think about the one you refer to, asking how does browser of postman deal with Mono and Flux calling subscribe()... Have you read it twice before sending it back to me? Please, if you have experience in this matter, I think it would be more helpful, not only for me but for the community, that you provide a good and complete example. Thanks! – WinterBoot Jun 10 '21 at 07:31
  • people at stack overflow answer questions on their free time, always remember that. Im not going to spend an hour, writing an answer that is already in the documentation just because you consciously decided to not read the documentation. 100s of people everyday that say "they are beginners and they havn't read the manual". The documentation is there for a reason. Reading the docs will make you a better dev. It will answer most of your questions. I have a lot of experience in the matter, just because i spent a couple of days, reading and im recommending you to do the same before asking here. – Toerktumlare Jun 10 '21 at 09:01
  • @WinterBoot are you developing a reactive application (where the controller returns Mono/Flux) or a traditional blocking application? What is the context of the code snippet you shared? What is `StubHttpClient::handleResponse` supposed to do? – Martin Tarjányi Jun 10 '21 at 18:52
  • reactive... that's why I don't call block() to trigger the chain of events to have WebClient sending out the request. StubHttpClient::handleResponse is dummy so far; I only use it to call subcribe() and see if it ever was called back, but it is not. As a matter of fact I have everything I need the client to do in the onStatus() calls, since the response does not have any content at all. My doubt was if I really need this explicit subscription or if I am probably doing something wrong... As the code is the request gets out and the response codes are processed in the onStatus() callbacks. – WinterBoot Jun 11 '21 at 09:32
  • I am also concerned about the Disposable returned by subscribe(): am I responsible to call dispose() to avoid a memory leak? If I compare this to Angular Observables, the answer is yes, Angular takes care of some automatically (for example those to handle http responses), but for others the SPA is responsible.... I am still making my mind of the complete picture of how Reactive works in Spring. THANKS! – WinterBoot Jun 11 '21 at 09:36
  • I've also put the context where the webclient.post is used. Basically, an asynchronous task starts upon reception of a POST, once it finishes, the service calls notifyJobSuccess(), that returns a void because the service delegates the sending of the request and the processin of the answer to this HttpClientNotifier::notifyJobSuccess – WinterBoot Jun 11 '21 at 09:45

1 Answers1

-1

Some time has passed since I asked for help here. Now I'd like not to edit but to add an answer to my previous question, so that the answer remains clear and separate from he original question and comments. So here goes a complete example.

CONTEXT: An application, acting as a client, that requests an Access Token from an OAuth2 Authorization server. The Access Token is requested asynchronously to avoid blocking the appliction's thread while the token request is processed at the other end and the response arrives.

First, this is a class that serves Access Token to its clients (method getAccessToken): if the Access Token is already initialized and it's valid, it returns the value stored; otherwise fetches a new one calling the internal method fetchAccessTokenAsync:

public class Oauth2ClientBroker {
private static final String OAUHT2_SRVR_TOKEN_PATH= "/auth/realms/oam/protocol/openid-connect/token";
private static final String GRANT_TYPE = "client_credentials";

@Qualifier("oAuth2Client")
private final WebClient oAuth2Client;

private final ConfigurationHolder CfgHolder;

@GuardedBy("this")
private String token = null;

@GuardedBy("this")
private Instant tokenExpireTime;

@GuardedBy("this")
private String tokenUrlEndPoint;

public void getAccessToken(final CompletableFuture<String> completableFuture) {

    if (!isTokenInitialized() || isTokenExpired()) {
        log.trace("Access Token not initialized or has exired: go fetch a new one...");
        synchronized (this) {
            this.token = null;
        }
        fetchAccessTokenAsync(completableFuture);
    } else {
        log.trace("Reusing Access Token (not expired)");
        final String token;
        synchronized (this) {
            token = this.token;
        }
        completableFuture.complete(token);
    }
}

... }

Next, we will see that fetchAccessTokenAsync does:

private void fetchAccessTokenAsync(final CompletableFuture<String> tokenReceivedInFuture) {

    Mono<String> accessTokenResponse = postAccessTokenRequest();
    accessTokenResponse.subscribe(tr -> processResponseBodyInFuture(tr, tokenReceivedInFuture));

}

Two things happen here:

  1. The method postAccessTokenRequest() builds a POST request and declares how the reponse will be consumed (when WebFlux makes it available once it is received), by using exchangeToMono:
private Mono postAccessTokenRequest() {

        log.trace("Request Access Token for OAuth2 client {}", cfgHolder.getClientId());

        final URI uri = URI.create(cfgHolder.getsecServiceHostAndPort().concat(OAUHT2_SRVR_TOKEN_PATH));
            } else {
                uri = URI.create(tokenUrlEndPoint);
            }

        }
        log.debug("Access Token endpoint OAuth2 Authorization server: {}", uri.toString());

        return oAuth2Client.post().uri(uri)
                .body(BodyInserters.fromFormData("client_id", cfgHolder.getEdaClientId())
                        .with("client_secret", cfgHolder.getClientSecret())
                        .with("scope", cfgHolder.getClientScopes()).with("grant_type", GRANT_TYPE))
                .exchangeToMono(resp -> {
                    if (resp.statusCode().equals(HttpStatus.OK)) {
                        log.info("Access Token successfully obtained");
                        return resp.bodyToMono(String.class);
                    } else if (resp.statusCode().equals(HttpStatus.BAD_REQUEST)) {
                        log.error("Bad request sent to Authorization Server!");
                        return resp.bodyToMono(String.class);
                    } else if (resp.statusCode().equals(HttpStatus.UNAUTHORIZED)) {
                        log.error("OAuth2 Credentials exchange with Authorization Server failed!");
                        return resp.bodyToMono(String.class);
                    } else if (resp.statusCode().is5xxServerError()) {
                        log.error("Authorization Server could not generate a token due to a server error");
                        return resp.bodyToMono(String.class);
                    } else {
                        log.error("Authorization Server returned an unexpected status code: {}",
                                resp.statusCode().toString());
                        return Mono.error(new Exception(
                                String.format("Authorization Server returned an unexpected status code: %s",
                                        resp.statusCode().toString())));
                    }
                }).onErrorResume(e -> {
                    log.error(
                            "Access Token could not be obtained. Process ends here");
                    return Mono.empty();
                });
    }

The exchangeToMono method does most of the magic here: tells WebFlux to return a Mono that will asynchronously receive a signal as soon as the response is received, wrapped in a ClientResponse, the parameter resp consumed in the lambda. But it is important to keep in mind that NO request has been sent out yet at this point; we are just passing in the Function that will take the ClientResponse when it arrives and will return a Mono<String> with the part of the body of our interest (the Access Token, as we will see).

  1. Once the POST is built and the Mono returned, then the real thing starts when we subscribe to the Mono<String> returned before. As the Reacive mantra says: nothing happens until you subscribe or, in our case, the request is not actually sent until something attempts to read or wait for the response. There are other ways in WebClient fluent API to implicitly subscribe, but we have chosen here the explicit way of returing the Mono -which implements the reactor Publisher interface- and subscribe to it. Here we blocking the thread no more, releasing CPU for other stuff, probably more useful than just waiting for an answer.

So far, so good: we have sent out the request, released CPU, but where the processing will continue whenever the response comes? The subscribe() method takes as an argument a Consumer parameterized in our case with a String, being nothing less than the body of the response we are waiting for, wrapped in Mono. When the response comes, WebFlux will notify the event to our Mono, which will call the method processResponseBodyInFuture, where we finally receive the response body:

private void processResponseBodyInFuture(final String body, final CompletableFuture<String> tokenReceivedInFuture) {

    DocumentContext jsonContext = JsonPath.parse(body);

    try {
        log.info("Access Token response received: {}", body);
        final String aTkn = jsonContext.read("$.access_token");
        log.trace("Access Token parsed: {}", aTkn);
        final int expiresIn = jsonContext.read("$.expires_in");
        synchronized (this) {
            this.token = aTkn;
            this.tokenExpireTime = Instant.now().plusSeconds(expiresIn);
        }
        log.trace("Signal Access Token request completion. Processing will continue calling client...");
        tokenReceivedInFuture.complete(aTkn);
    } catch (PathNotFoundException e) {
        try {
            log.error(e.getMessage());
            log.info(String.format(
                    "Could not extract Access Token. The response returned corresponds to the error %s: %s",
                    jsonContext.read("$.error"), jsonContext.read("$.error_description")));
        } catch (PathNotFoundException e2) {
            log.error(e2.getMessage().concat(" - Unexpected json content received from OAuth2 Server"));
        }
    }

}

The invocation of this method happens as soon as the Mono is signalled about the reception of the response. So here we try to parse the json content with an Access Token and do something with it... In this case call complete() onto the CompletableFuture passed in by the caller of the initial method getAccessToken, that hopefully will know what to do with it. Our job is done here... Asynchronously!

Summary: To summarize, these are the basic considerations to have your request sent out and the responses processed when you ise reactive WebClient:

  1. Consider having a method in charge of preparing the request by means of the WebClient fluent API (to set http method, uri, headers and body). Remember: by doing this you are not sending any request yet.
  2. Think on the strategy you will use to obtain the Publisher that will be receive the http client events (response or errors). retreive() is the most straight forward, but it has less power to manipulate the response than exchangeToMono.
  3. Subscribe... or nothing will happen. Many examples you will find around will cheat you: they claim to use WebClient for asyncrhony, but then they "forget" about subscribing to the Publisher and call block() instead. Well, while this makes things easier and they seem to work (you will see responses received and passed to your application), the thing is that this is not asynchronous anymore: your Mono (or Flux, whatever you use) will be blocking until the response arrives. No good.
  4. Have a separate method (being the Consumer passed in the subscribe() method) where the response body is processed.
WinterBoot
  • 399
  • 1
  • 5
  • 15
  • this answer is filled with strange decisions and is not idiomatic reactive programming. For instance the mixage of CompletableFutures instead of using Fluxes or Monos. Also the mixing of using imperative java using Try/Catch blocks. Downvoted because this clearly shows the lack of not reading documentation. – Toerktumlare May 01 '23 at 12:07