Search in sources :

Example 1 with LRA_HTTP_CONTEXT_HEADER

use of org.eclipse.microprofile.lra.annotation.ws.rs.LRA.LRA_HTTP_CONTEXT_HEADER in project narayana by jbosstm.

the class LRATest method multiLevelNestedActivity.

private void multiLevelNestedActivity(CompletionType how, int nestedCnt) throws WebApplicationException, URISyntaxException {
    WebTarget resourcePath = client.target(TestPortProvider.generateURL("/base/test/multiLevelNestedActivity"));
    if (how == CompletionType.mixed && nestedCnt <= 1) {
        how = CompletionType.complete;
    }
    URI lra = new URI(client.target(TestPortProvider.generateURL("/base/test/start")).request().get(String.class));
    Response response = resourcePath.queryParam("nestedCnt", nestedCnt).request().header(LRA_HTTP_CONTEXT_HEADER, lra).put(Entity.text(""));
    // the response is a comma separated list of URIs (parent, children)
    String lraStr = response.readEntity(String.class);
    assertNotNull("expecting a LRA string returned from " + resourcePath.getUri(), lraStr);
    URI[] uris = Arrays.stream(lraStr.split(",")).map(s -> {
        try {
            return new URI(s);
        } catch (URISyntaxException e) {
            fail(e.getMessage());
            return null;
        }
    }).toArray(URI[]::new);
    // check that the multiLevelNestedActivity method returned the mandatory LRA followed by any nested LRAs
    assertEquals("multiLevelNestedActivity: step 1 (the test call went to " + resourcePath.getUri() + ")", nestedCnt + 1, uris.length);
    // first element should be the mandatory LRA
    assertEquals("multiLevelNestedActivity: step 2 (the test call went to " + resourcePath.getUri() + ")", lra, uris[0]);
    // and the mandatory lra seen by the multiLevelNestedActivity method
    assertFalse("multiLevelNestedActivity: top level LRA should be active (path called " + resourcePath.getUri() + ")", isFinished(uris[0]));
    // check that all nested activities were told to complete
    assertEquals("multiLevelNestedActivity: step 3 (called test path " + resourcePath.getUri() + ")", nestedCnt, completeCount.get());
    assertEquals("multiLevelNestedActivity: step 4 (called test path " + resourcePath.getUri() + ")", 0, compensateCount.get());
    // close the LRA
    if (how == CompletionType.compensate) {
        lraClient.cancelLRA(lra);
        // validate that the top level and nested LRAs are gone
        assertAllFinished(uris);
        /*
             * the test starts LRA1 calls a @Mandatory method multiLevelNestedActivity which enlists in LRA1
             * multiLevelNestedActivity then calls an @Nested method which starts L2 and enlists another participant
             *   when the method returns the nested participant is completed (ie completed count is incremented)
             * Canceling L1 should then compensate the L1 enlistment (ie compensate count is incremented)
             * which will then tell L2 to compensate (ie the compensate count is incremented again)
             */
        // each nested participant should have completed (the +nestedCnt)
        assertEquals("multiLevelNestedActivity: step 7 (called test path " + resourcePath.getUri() + ")", nestedCnt, completeCount.get());
        // each nested participant should have compensated. The top level enlistment should have compensated (the +1)
        assertEquals("multiLevelNestedActivity: step 8 (called test path " + resourcePath.getUri() + ")", nestedCnt + 1, compensateCount.get());
    } else if (how == CompletionType.complete) {
        lraClient.closeLRA(lra);
        // validate that the top level and nested LRAs are gone
        assertAllFinished(uris);
        // each nested participant and the top level participant should have completed (nestedCnt + 1) at least once
        assertTrue("multiLevelNestedActivity: step 5a (called test path " + resourcePath.getUri() + ")", completeCount.get() >= nestedCnt + 1);
        // each nested participant should have been told to forget
        assertEquals("multiLevelNestedActivity: step 5b (called test path " + resourcePath.getUri() + ")", forgetCount.get(), nestedCnt);
        // and that neither were still not told to compensate
        assertEquals("multiLevelNestedActivity: step 6 (called test path " + resourcePath.getUri() + ")", 0, compensateCount.get());
    } else {
        // compensate the first nested LRA in the enlisted resource
        try (Response r = client.target(TestPortProvider.generateURL("/base/test/end")).queryParam("cancel", true).request().header(LRA_HTTP_CONTEXT_HEADER, uris[1]).put(Entity.text(""))) {
            assertEquals("compensate the first nested LRA", 500, r.getStatus());
        }
        // should not complete any nested LRAs (since they have already completed via the interceptor)
        lraClient.closeLRA(lra);
        /*
             * Expect nestedCnt + 1 completions, 1 for the top level and one for each nested LRA
             * (NB the first nested LRA is completed and compensated)
             * Note that the top level complete should not call complete again on the nested LRA
             */
        assertEquals("multiLevelNestedActivity: step 10 (called test path " + resourcePath.getUri() + ")", nestedCnt + 1, completeCount.get());
        /*
             * The test is calling for a mixed outcome:
             * - the top level LRA was closed
             * - one of the nested LRAs was compensated the rest should have been completed
             */
        // there should be just 1 compensation (the first nested LRA)
        assertEquals("multiLevelNestedActivity: step 9 (called test path " + resourcePath.getUri() + ")", 1, compensateCount.get());
    }
}
Also used : Response(javax.ws.rs.core.Response) Arrays(java.util.Arrays) Produces(javax.ws.rs.Produces) AfterLRA(org.eclipse.microprofile.lra.annotation.AfterLRA) LRAService(io.narayana.lra.coordinator.domain.service.LRAService) URISyntaxException(java.net.URISyntaxException) Path(javax.ws.rs.Path) COORDINATOR_PATH_NAME(io.narayana.lra.LRAConstants.COORDINATOR_PATH_NAME) Application(javax.ws.rs.core.Application) com.arjuna.ats.arjuna.common.arjPropertyManager(com.arjuna.ats.arjuna.common.arjPropertyManager) ParticipantStatusOctetStreamProvider(io.narayana.lra.provider.ParticipantStatusOctetStreamProvider) MediaType(javax.ws.rs.core.MediaType) QueryParam(javax.ws.rs.QueryParam) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) After(org.junit.After) DefaultValue(javax.ws.rs.DefaultValue) HeaderParam(javax.ws.rs.HeaderParam) UndertowJaxrsServer(org.jboss.resteasy.plugins.server.undertow.UndertowJaxrsServer) Assert.fail(org.junit.Assert.fail) URI(java.net.URI) DELETE(javax.ws.rs.DELETE) ServerLRAFilter(io.narayana.lra.filter.ServerLRAFilter) Forget(org.eclipse.microprofile.lra.annotation.Forget) LRA_HTTP_RECOVERY_HEADER(org.eclipse.microprofile.lra.annotation.ws.rs.LRA.LRA_HTTP_RECOVERY_HEADER) Set(java.util.Set) Entity(javax.ws.rs.client.Entity) NotFoundException(javax.ws.rs.NotFoundException) Objects(java.util.Objects) NarayanaLRAClient(io.narayana.lra.client.NarayanaLRAClient) Response(javax.ws.rs.core.Response) Assert.assertFalse(org.junit.Assert.assertFalse) WebApplicationException(javax.ws.rs.WebApplicationException) Complete(org.eclipse.microprofile.lra.annotation.Complete) Link(javax.ws.rs.core.Link) IntStream(java.util.stream.IntStream) LRA_HTTP_CONTEXT_HEADER(org.eclipse.microprofile.lra.annotation.ws.rs.LRA.LRA_HTTP_CONTEXT_HEADER) BeforeClass(org.junit.BeforeClass) GET(javax.ws.rs.GET) Client(javax.ws.rs.client.Client) HashSet(java.util.HashSet) LRARecoveryModule(io.narayana.lra.coordinator.internal.LRARecoveryModule) ClientBuilder(javax.ws.rs.client.ClientBuilder) TestName(org.junit.rules.TestName) StringTokenizer(java.util.StringTokenizer) Coordinator(io.narayana.lra.coordinator.api.Coordinator) LRA_HTTP_PARENT_CONTEXT_HEADER(org.eclipse.microprofile.lra.annotation.ws.rs.LRA.LRA_HTTP_PARENT_CONTEXT_HEADER) Before(org.junit.Before) ParticipantStatus(org.eclipse.microprofile.lra.annotation.ParticipantStatus) TestPortProvider(org.jboss.resteasy.test.TestPortProvider) Assert.assertNotNull(org.junit.Assert.assertNotNull) ApplicationPath(javax.ws.rs.ApplicationPath) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) File(java.io.File) LRAStatus(org.eclipse.microprofile.lra.annotation.LRAStatus) Rule(org.junit.Rule) ChronoUnit(java.time.temporal.ChronoUnit) Assert.assertNull(org.junit.Assert.assertNull) LRA(org.eclipse.microprofile.lra.annotation.ws.rs.LRA) Compensate(org.eclipse.microprofile.lra.annotation.Compensate) LRALogger(io.narayana.lra.logging.LRALogger) PUT(javax.ws.rs.PUT) WebTarget(javax.ws.rs.client.WebTarget) Assert(org.junit.Assert) Assert.assertEquals(org.junit.Assert.assertEquals) WebTarget(javax.ws.rs.client.WebTarget) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI)

Example 2 with LRA_HTTP_CONTEXT_HEADER

use of org.eclipse.microprofile.lra.annotation.ws.rs.LRA.LRA_HTTP_CONTEXT_HEADER in project helidon by oracle.

the class NonJaxRsResource method createNonJaxRsParticipantResource.

Service createNonJaxRsParticipantResource() {
    return rules -> rules.any("/{type}/{fqdn}/{methodName}", (req, res) -> {
        LOGGER.log(Level.FINE, () -> "Non JAX-RS LRA resource " + req.method().name() + " " + req.absoluteUri());
        RequestHeaders headers = req.headers();
        HttpRequest.Path path = req.path();
        URI lraId = headers.first(LRA_HTTP_CONTEXT_HEADER).or(() -> headers.first(LRA_HTTP_ENDED_CONTEXT_HEADER)).map(URI::create).orElse(null);
        URI parentId = headers.first(LRA_HTTP_PARENT_CONTEXT_HEADER).map(URI::create).orElse(null);
        PropagatedHeaders propagatedHeaders = participantService.prepareCustomHeaderPropagation(headers.toMap());
        String fqdn = path.param("fqdn");
        String method = path.param("methodName");
        String type = path.param("type");
        switch(type) {
            case "compensate":
            case "complete":
                Single.<Optional<?>>empty().observeOn(exec).onCompleteResumeWithSingle(o -> participantService.invoke(fqdn, method, lraId, parentId, propagatedHeaders)).forSingle(result -> result.ifPresentOrElse(r -> sendResult(res, r), res::send)).exceptionallyAccept(t -> sendError(lraId, req, res, t));
                break;
            case "afterlra":
                req.content().as(String.class).map(LRAStatus::valueOf).observeOn(exec).flatMapSingle(s -> Single.defer(() -> participantService.invoke(fqdn, method, lraId, s, propagatedHeaders))).onComplete(res::send).onError(t -> sendError(lraId, req, res, t)).ignoreElement();
                break;
            case "status":
                Single.<Optional<?>>empty().observeOn(exec).onCompleteResumeWithSingle(o -> participantService.invoke(fqdn, method, lraId, null, propagatedHeaders)).forSingle(result -> result.ifPresentOrElse(r -> sendResult(res, r), // or in the case of non-JAX-RS method returning ParticipantStatus null.
                () -> res.status(Response.Status.GONE.getStatusCode()).send())).exceptionallyAccept(t -> sendError(lraId, req, res, t));
                break;
            case "forget":
                Single.<Optional<?>>empty().observeOn(exec).onCompleteResumeWithSingle(o -> participantService.invoke(fqdn, method, lraId, parentId, propagatedHeaders)).onComplete(res::send).onError(t -> sendError(lraId, req, res, t)).ignoreElement();
                break;
            default:
                LOGGER.severe(() -> "Unexpected non Jax-Rs LRA compensation type " + type + ": " + req.absoluteUri());
                res.status(404).send();
                break;
        }
    });
}
Also used : LRAResponse(org.eclipse.microprofile.lra.LRAResponse) LRA_HTTP_CONTEXT_HEADER(org.eclipse.microprofile.lra.annotation.ws.rs.LRA.LRA_HTTP_CONTEXT_HEADER) PropagatedHeaders(io.helidon.lra.coordinator.client.PropagatedHeaders) LRA_HTTP_ENDED_CONTEXT_HEADER(org.eclipse.microprofile.lra.annotation.ws.rs.LRA.LRA_HTTP_ENDED_CONTEXT_HEADER) Supplier(java.util.function.Supplier) Level(java.util.logging.Level) Response(jakarta.ws.rs.core.Response) Map(java.util.Map) ServerResponse(io.helidon.webserver.ServerResponse) Single(io.helidon.common.reactive.Single) URI(java.net.URI) Service(io.helidon.webserver.Service) Reflected(io.helidon.common.Reflected) ExecutorService(java.util.concurrent.ExecutorService) LRA_HTTP_PARENT_CONTEXT_HEADER(org.eclipse.microprofile.lra.annotation.ws.rs.LRA.LRA_HTTP_PARENT_CONTEXT_HEADER) ParticipantStatus(org.eclipse.microprofile.lra.annotation.ParticipantStatus) Config(io.helidon.config.Config) PreDestroy(jakarta.annotation.PreDestroy) Logger(java.util.logging.Logger) RequestHeaders(io.helidon.webserver.RequestHeaders) Collectors(java.util.stream.Collectors) ServerRequest(io.helidon.webserver.ServerRequest) TimeUnit(java.util.concurrent.TimeUnit) LRAStatus(org.eclipse.microprofile.lra.annotation.LRAStatus) Optional(java.util.Optional) ConfigProperty(org.eclipse.microprofile.config.inject.ConfigProperty) Inject(jakarta.inject.Inject) ThreadPoolSupplier(io.helidon.common.configurable.ThreadPoolSupplier) HttpRequest(io.helidon.common.http.HttpRequest) HttpRequest(io.helidon.common.http.HttpRequest) PropagatedHeaders(io.helidon.lra.coordinator.client.PropagatedHeaders) Optional(java.util.Optional) RequestHeaders(io.helidon.webserver.RequestHeaders) URI(java.net.URI)

Example 3 with LRA_HTTP_CONTEXT_HEADER

use of org.eclipse.microprofile.lra.annotation.ws.rs.LRA.LRA_HTTP_CONTEXT_HEADER in project helidon by oracle.

the class LraAnnotationHandler method handleJaxRsAfter.

@Override
public void handleJaxRsAfter(ContainerRequestContext reqCtx, ContainerResponseContext resCtx, ResourceInfo resourceInfo) {
    Optional<URI> lraId = Optional.ofNullable((URI) reqCtx.getProperty(LRA_HTTP_CONTEXT_HEADER)).or(() -> Contexts.context().flatMap(c -> c.get(LRA_HTTP_CONTEXT_HEADER, URI.class)));
    PropagatedHeaders propagatedHeaders = participantService.prepareCustomHeaderPropagation(reqCtx.getHeaders());
    Response.Status resStatus = resCtx.getStatusInfo().toEnum();
    Response.Status.Family resFamily = resCtx.getStatusInfo().getFamily();
    boolean end = annotation.end();
    boolean cancel = annotation.cancelOnFamily().contains(resFamily) || annotation.cancelOn().contains(resStatus);
    lraId.ifPresent(id -> {
        if (cancel) {
            cancel(id, propagatedHeaders);
        } else if (end) {
            close(id, propagatedHeaders);
        }
        resCtx.getHeaders().putSingle(LRA_HTTP_CONTEXT_HEADER, id);
    });
    Optional.ofNullable(reqCtx.getProperty(LRA_HTTP_PARENT_CONTEXT_HEADER)).map(URI.class::cast).ifPresent(suppressedLra -> resCtx.getHeaders().putSingle(LRA_HTTP_CONTEXT_HEADER, suppressedLra));
}
Also used : LRA_HTTP_CONTEXT_HEADER(org.eclipse.microprofile.lra.annotation.ws.rs.LRA.LRA_HTTP_CONTEXT_HEADER) PropagatedHeaders(io.helidon.lra.coordinator.client.PropagatedHeaders) LRA_HTTP_RECOVERY_HEADER(org.eclipse.microprofile.lra.annotation.ws.rs.LRA.LRA_HTTP_RECOVERY_HEADER) Participant(io.helidon.lra.coordinator.client.Participant) CompletionException(java.util.concurrent.CompletionException) Logger(java.util.logging.Logger) WebApplicationException(jakarta.ws.rs.WebApplicationException) Contexts(io.helidon.common.context.Contexts) Response(jakarta.ws.rs.core.Response) ContainerRequestContext(jakarta.ws.rs.container.ContainerRequestContext) CoordinatorConnectionException(io.helidon.lra.coordinator.client.CoordinatorConnectionException) AnnotationInstance(org.jboss.jandex.AnnotationInstance) Duration(java.time.Duration) ResourceInfo(jakarta.ws.rs.container.ResourceInfo) Optional(java.util.Optional) Single(io.helidon.common.reactive.Single) CoordinatorClient(io.helidon.lra.coordinator.client.CoordinatorClient) ContainerResponseContext(jakarta.ws.rs.container.ContainerResponseContext) URI(java.net.URI) Method(java.lang.reflect.Method) LRA_HTTP_PARENT_CONTEXT_HEADER(org.eclipse.microprofile.lra.annotation.ws.rs.LRA.LRA_HTTP_PARENT_CONTEXT_HEADER) Response(jakarta.ws.rs.core.Response) PropagatedHeaders(io.helidon.lra.coordinator.client.PropagatedHeaders) URI(java.net.URI)

Aggregations

URI (java.net.URI)3 LRA_HTTP_CONTEXT_HEADER (org.eclipse.microprofile.lra.annotation.ws.rs.LRA.LRA_HTTP_CONTEXT_HEADER)3 LRA_HTTP_PARENT_CONTEXT_HEADER (org.eclipse.microprofile.lra.annotation.ws.rs.LRA.LRA_HTTP_PARENT_CONTEXT_HEADER)3 Single (io.helidon.common.reactive.Single)2 PropagatedHeaders (io.helidon.lra.coordinator.client.PropagatedHeaders)2 Response (jakarta.ws.rs.core.Response)2 Optional (java.util.Optional)2 LRAStatus (org.eclipse.microprofile.lra.annotation.LRAStatus)2 ParticipantStatus (org.eclipse.microprofile.lra.annotation.ParticipantStatus)2 com.arjuna.ats.arjuna.common.arjPropertyManager (com.arjuna.ats.arjuna.common.arjPropertyManager)1 Reflected (io.helidon.common.Reflected)1 ThreadPoolSupplier (io.helidon.common.configurable.ThreadPoolSupplier)1 Contexts (io.helidon.common.context.Contexts)1 HttpRequest (io.helidon.common.http.HttpRequest)1 Config (io.helidon.config.Config)1 CoordinatorClient (io.helidon.lra.coordinator.client.CoordinatorClient)1 CoordinatorConnectionException (io.helidon.lra.coordinator.client.CoordinatorConnectionException)1 Participant (io.helidon.lra.coordinator.client.Participant)1 RequestHeaders (io.helidon.webserver.RequestHeaders)1 ServerRequest (io.helidon.webserver.ServerRequest)1