Search in sources :

Example 1 with Suspended

use of javax.ws.rs.container.Suspended in project jersey by jersey.

the class ObservableAgentResource method observable.

@GET
public void observable(@Suspended final AsyncResponse async) {
    final long time = System.nanoTime();
    final Queue<String> errors = new ConcurrentLinkedQueue<>();
    Observable.just(new AgentResponse()).zipWith(visited(errors), (response, visited) -> {
        response.setVisited(visited);
        return response;
    }).zipWith(recommended(errors), (response, recommendations) -> {
        response.setRecommended(recommendations);
        return response;
    }).observeOn(Schedulers.io()).subscribe(response -> {
        response.setProcessingTime((System.nanoTime() - time) / 1000000);
        async.resume(response);
    }, async::resume);
}
Also used : Produces(javax.ws.rs.Produces) RxObservableInvokerProvider(org.glassfish.jersey.client.rx.rxjava.RxObservableInvokerProvider) GET(javax.ws.rs.GET) AsyncResponse(javax.ws.rs.container.AsyncResponse) RxObservableInvoker(org.glassfish.jersey.client.rx.rxjava.RxObservableInvoker) Path(javax.ws.rs.Path) Singleton(javax.inject.Singleton) Suspended(javax.ws.rs.container.Suspended) Calculation(org.glassfish.jersey.examples.rx.domain.Calculation) Uri(org.glassfish.jersey.server.Uri) Destination(org.glassfish.jersey.examples.rx.domain.Destination) Observable(rx.Observable) GenericType(javax.ws.rs.core.GenericType) Forecast(org.glassfish.jersey.examples.rx.domain.Forecast) List(java.util.List) Recommendation(org.glassfish.jersey.examples.rx.domain.Recommendation) Schedulers(rx.schedulers.Schedulers) Queue(java.util.Queue) WebTarget(javax.ws.rs.client.WebTarget) Collections(java.util.Collections) AgentResponse(org.glassfish.jersey.examples.rx.domain.AgentResponse) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) AgentResponse(org.glassfish.jersey.examples.rx.domain.AgentResponse) GET(javax.ws.rs.GET)

Example 2 with Suspended

use of javax.ws.rs.container.Suspended in project presto by prestodb.

the class TaskResource method getResults.

@GET
@Path("{taskId}/results/{bufferId}/{token}")
@Produces(PRESTO_PAGES)
public void getResults(@PathParam("taskId") TaskId taskId, @PathParam("bufferId") OutputBufferId bufferId, @PathParam("token") final long token, @HeaderParam(PRESTO_MAX_SIZE) DataSize maxSize, @Suspended AsyncResponse asyncResponse) throws InterruptedException {
    requireNonNull(taskId, "taskId is null");
    requireNonNull(bufferId, "bufferId is null");
    long start = System.nanoTime();
    ListenableFuture<BufferResult> bufferResultFuture = taskManager.getTaskResults(taskId, bufferId, token, maxSize);
    Duration waitTime = randomizeWaitTime(DEFAULT_MAX_WAIT_TIME);
    bufferResultFuture = addTimeout(bufferResultFuture, () -> BufferResult.emptyResults(taskManager.getTaskInstanceId(taskId), token, false), waitTime, timeoutExecutor);
    ListenableFuture<Response> responseFuture = Futures.transform(bufferResultFuture, result -> {
        List<SerializedPage> serializedPages = result.getSerializedPages();
        GenericEntity<?> entity = null;
        Status status;
        if (serializedPages.isEmpty()) {
            status = Status.NO_CONTENT;
        } else {
            entity = new GenericEntity<>(serializedPages, new TypeToken<List<Page>>() {
            }.getType());
            status = Status.OK;
        }
        return Response.status(status).entity(entity).header(PRESTO_TASK_INSTANCE_ID, result.getTaskInstanceId()).header(PRESTO_PAGE_TOKEN, result.getToken()).header(PRESTO_PAGE_NEXT_TOKEN, result.getNextToken()).header(PRESTO_BUFFER_COMPLETE, result.isBufferComplete()).build();
    });
    // For hard timeout, add an additional 5 seconds to max wait for thread scheduling contention and GC
    Duration timeout = new Duration(waitTime.toMillis() + 5000, MILLISECONDS);
    bindAsyncResponse(asyncResponse, responseFuture, responseExecutor).withTimeout(timeout, Response.status(Status.NO_CONTENT).header(PRESTO_TASK_INSTANCE_ID, taskManager.getTaskInstanceId(taskId)).header(PRESTO_PAGE_TOKEN, token).header(PRESTO_PAGE_NEXT_TOKEN, token).header(PRESTO_BUFFER_COMPLETE, false).build());
    responseFuture.addListener(() -> readFromOutputBufferTime.add(Duration.nanosSince(start)), directExecutor());
    asyncResponse.register((CompletionCallback) throwable -> resultsRequestTime.add(Duration.nanosSince(start)));
}
Also used : TaskStatus(com.facebook.presto.execution.TaskStatus) Status(javax.ws.rs.core.Response.Status) Page(com.facebook.presto.spi.Page) Produces(javax.ws.rs.Produces) Iterables.transform(com.google.common.collect.Iterables.transform) TaskStatus(com.facebook.presto.execution.TaskStatus) Path(javax.ws.rs.Path) AsyncResponseHandler.bindAsyncResponse(io.airlift.http.server.AsyncResponseHandler.bindAsyncResponse) TaskState(com.facebook.presto.execution.TaskState) Duration(io.airlift.units.Duration) OutputBufferId(com.facebook.presto.OutputBuffers.OutputBufferId) MediaType(javax.ws.rs.core.MediaType) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) BoundedExecutor(io.airlift.concurrent.BoundedExecutor) DefaultValue(javax.ws.rs.DefaultValue) HeaderParam(javax.ws.rs.HeaderParam) BufferResult(com.facebook.presto.execution.buffer.BufferResult) DELETE(javax.ws.rs.DELETE) PRESTO_PAGE_TOKEN(com.facebook.presto.client.PrestoHeaders.PRESTO_PAGE_TOKEN) Context(javax.ws.rs.core.Context) AsyncResponse(javax.ws.rs.container.AsyncResponse) GenericEntity(javax.ws.rs.core.GenericEntity) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) Suspended(javax.ws.rs.container.Suspended) MoreExecutors.directExecutor(com.google.common.util.concurrent.MoreExecutors.directExecutor) DataSize(io.airlift.units.DataSize) List(java.util.List) Response(javax.ws.rs.core.Response) CompletionCallback(javax.ws.rs.container.CompletionCallback) PRESTO_BUFFER_COMPLETE(com.facebook.presto.client.PrestoHeaders.PRESTO_BUFFER_COMPLETE) SerializedPage(com.facebook.presto.execution.buffer.SerializedPage) UriInfo(javax.ws.rs.core.UriInfo) PRESTO_CURRENT_STATE(com.facebook.presto.client.PrestoHeaders.PRESTO_CURRENT_STATE) Nested(org.weakref.jmx.Nested) PathParam(javax.ws.rs.PathParam) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) GET(javax.ws.rs.GET) TypeToken(com.google.common.reflect.TypeToken) Inject(javax.inject.Inject) PRESTO_TASK_INSTANCE_ID(com.facebook.presto.client.PrestoHeaders.PRESTO_TASK_INSTANCE_ID) ImmutableList(com.google.common.collect.ImmutableList) Managed(org.weakref.jmx.Managed) PRESTO_MAX_SIZE(com.facebook.presto.client.PrestoHeaders.PRESTO_MAX_SIZE) TaskManager(com.facebook.presto.execution.TaskManager) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) Objects.requireNonNull(java.util.Objects.requireNonNull) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) MoreFutures.addTimeout(io.airlift.concurrent.MoreFutures.addTimeout) PRESTO_PAGE_NEXT_TOKEN(com.facebook.presto.client.PrestoHeaders.PRESTO_PAGE_NEXT_TOKEN) SessionPropertyManager(com.facebook.presto.metadata.SessionPropertyManager) TimeStat(io.airlift.stats.TimeStat) Status(javax.ws.rs.core.Response.Status) POST(javax.ws.rs.POST) Executor(java.util.concurrent.Executor) Session(com.facebook.presto.Session) PRESTO_MAX_WAIT(com.facebook.presto.client.PrestoHeaders.PRESTO_MAX_WAIT) Futures(com.google.common.util.concurrent.Futures) PRESTO_PAGES(com.facebook.presto.PrestoMediaTypes.PRESTO_PAGES) TaskId(com.facebook.presto.execution.TaskId) TaskInfo(com.facebook.presto.execution.TaskInfo) SECONDS(java.util.concurrent.TimeUnit.SECONDS) Duration(io.airlift.units.Duration) AsyncResponseHandler.bindAsyncResponse(io.airlift.http.server.AsyncResponseHandler.bindAsyncResponse) AsyncResponse(javax.ws.rs.container.AsyncResponse) Response(javax.ws.rs.core.Response) BufferResult(com.facebook.presto.execution.buffer.BufferResult) SerializedPage(com.facebook.presto.execution.buffer.SerializedPage) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 3 with Suspended

use of javax.ws.rs.container.Suspended in project jersey by jersey.

the class FlowableAgentResource method flowable.

@GET
public void flowable(@Suspended final AsyncResponse async) {
    final long time = System.nanoTime();
    final Queue<String> errors = new ConcurrentLinkedQueue<>();
    Flowable.just(new AgentResponse()).zipWith(visited(errors), (agentResponse, visited) -> {
        agentResponse.setVisited(visited);
        return agentResponse;
    }).zipWith(recommended(errors), (agentResponse, recommendations) -> {
        agentResponse.setRecommended(recommendations);
        return agentResponse;
    }).observeOn(Schedulers.io()).subscribe(agentResponse -> {
        agentResponse.setProcessingTime((System.nanoTime() - time) / 1000000);
        async.resume(agentResponse);
    }, async::resume);
}
Also used : Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) AsyncResponse(javax.ws.rs.container.AsyncResponse) Path(javax.ws.rs.Path) Singleton(javax.inject.Singleton) Suspended(javax.ws.rs.container.Suspended) Calculation(org.glassfish.jersey.examples.rx.domain.Calculation) Uri(org.glassfish.jersey.server.Uri) Destination(org.glassfish.jersey.examples.rx.domain.Destination) GenericType(javax.ws.rs.core.GenericType) Forecast(org.glassfish.jersey.examples.rx.domain.Forecast) List(java.util.List) Flowable(io.reactivex.Flowable) Recommendation(org.glassfish.jersey.examples.rx.domain.Recommendation) Schedulers(io.reactivex.schedulers.Schedulers) Queue(java.util.Queue) WebTarget(javax.ws.rs.client.WebTarget) RxFlowableInvoker(org.glassfish.jersey.client.rx.rxjava2.RxFlowableInvoker) RxFlowableInvokerProvider(org.glassfish.jersey.client.rx.rxjava2.RxFlowableInvokerProvider) Collections(java.util.Collections) AgentResponse(org.glassfish.jersey.examples.rx.domain.AgentResponse) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) AgentResponse(org.glassfish.jersey.examples.rx.domain.AgentResponse) GET(javax.ws.rs.GET)

Example 4 with Suspended

use of javax.ws.rs.container.Suspended in project pulsar by yahoo.

the class DestinationLookup method lookupDestinationAsync.

@GET
@Path("persistent/{property}/{cluster}/{namespace}/{dest}")
@Produces(MediaType.APPLICATION_JSON)
public void lookupDestinationAsync(@PathParam("property") String property, @PathParam("cluster") String cluster, @PathParam("namespace") String namespace, @PathParam("dest") @Encoded String dest, @QueryParam("authoritative") @DefaultValue("false") boolean authoritative, @Suspended AsyncResponse asyncResponse) {
    dest = Codec.decode(dest);
    DestinationName topic = DestinationName.get("persistent", property, cluster, namespace, dest);
    if (!pulsar().getBrokerService().getLookupRequestSemaphore().tryAcquire()) {
        log.warn("No broker was found available for topic {}", topic);
        asyncResponse.resume(new WebApplicationException(Response.Status.SERVICE_UNAVAILABLE));
        return;
    }
    try {
        validateClusterOwnership(topic.getCluster());
        checkConnect(topic);
        validateReplicationSettingsOnNamespace(pulsar(), topic.getNamespaceObject());
    } catch (WebApplicationException we) {
        // Validation checks failed
        log.error("Validation check failed: {}", we.getMessage());
        completeLookupResponseExceptionally(asyncResponse, we);
        return;
    } catch (Throwable t) {
        // Validation checks failed with unknown error
        log.error("Validation check failed: {}", t.getMessage(), t);
        completeLookupResponseExceptionally(asyncResponse, new RestException(t));
        return;
    }
    CompletableFuture<LookupResult> lookupFuture = pulsar().getNamespaceService().getBrokerServiceUrlAsync(topic, authoritative);
    lookupFuture.thenAccept(result -> {
        if (result == null) {
            log.warn("No broker was found available for topic {}", topic);
            completeLookupResponseExceptionally(asyncResponse, new WebApplicationException(Response.Status.SERVICE_UNAVAILABLE));
            return;
        }
        if (result.isRedirect()) {
            boolean newAuthoritative = this.isLeaderBroker();
            URI redirect;
            try {
                String redirectUrl = isRequestHttps() ? result.getLookupData().getHttpUrlTls() : result.getLookupData().getHttpUrl();
                redirect = new URI(String.format("%s%s%s?authoritative=%s", redirectUrl, "/lookup/v2/destination/", topic.getLookupName(), newAuthoritative));
            } catch (URISyntaxException e) {
                log.error("Error in preparing redirect url for {}: {}", topic, e.getMessage(), e);
                completeLookupResponseExceptionally(asyncResponse, e);
                return;
            }
            if (log.isDebugEnabled()) {
                log.debug("Redirect lookup for topic {} to {}", topic, redirect);
            }
            completeLookupResponseExceptionally(asyncResponse, new WebApplicationException(Response.temporaryRedirect(redirect).build()));
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Lookup succeeded for topic {} -- broker: {}", topic, result.getLookupData());
            }
            completeLookupResponseSuccessfully(asyncResponse, result.getLookupData());
        }
    }).exceptionally(exception -> {
        log.warn("Failed to lookup broker for topic {}: {}", topic, exception.getMessage(), exception);
        completeLookupResponseExceptionally(asyncResponse, exception);
        return null;
    });
}
Also used : PathParam(javax.ws.rs.PathParam) RestException(com.yahoo.pulsar.broker.web.RestException) ServerError(com.yahoo.pulsar.common.api.proto.PulsarApi.ServerError) Encoded(javax.ws.rs.Encoded) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) URISyntaxException(java.net.URISyntaxException) Path(javax.ws.rs.Path) LoggerFactory(org.slf4j.LoggerFactory) CompletableFuture(java.util.concurrent.CompletableFuture) LookupData(com.yahoo.pulsar.common.lookup.data.LookupData) MediaType(javax.ws.rs.core.MediaType) QueryParam(javax.ws.rs.QueryParam) ClusterData(com.yahoo.pulsar.common.policies.data.ClusterData) ByteBuf(io.netty.buffer.ByteBuf) DefaultValue(javax.ws.rs.DefaultValue) PulsarService(com.yahoo.pulsar.broker.PulsarService) URI(java.net.URI) Codec(com.yahoo.pulsar.common.util.Codec) LookupType(com.yahoo.pulsar.common.api.proto.PulsarApi.CommandLookupTopicResponse.LookupType) Status(javax.ws.rs.core.Response.Status) DestinationName(com.yahoo.pulsar.common.naming.DestinationName) Logger(org.slf4j.Logger) AsyncResponse(javax.ws.rs.container.AsyncResponse) NoSwaggerDocumentation(com.yahoo.pulsar.broker.web.NoSwaggerDocumentation) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) Commands.newLookupResponse(com.yahoo.pulsar.common.api.Commands.newLookupResponse) Suspended(javax.ws.rs.container.Suspended) PulsarWebResource(com.yahoo.pulsar.broker.web.PulsarWebResource) Response(javax.ws.rs.core.Response) WebApplicationException(javax.ws.rs.WebApplicationException) PulsarClientException(com.yahoo.pulsar.client.api.PulsarClientException) WebApplicationException(javax.ws.rs.WebApplicationException) DestinationName(com.yahoo.pulsar.common.naming.DestinationName) RestException(com.yahoo.pulsar.broker.web.RestException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Aggregations

GET (javax.ws.rs.GET)4 Path (javax.ws.rs.Path)4 Produces (javax.ws.rs.Produces)4 AsyncResponse (javax.ws.rs.container.AsyncResponse)4 Suspended (javax.ws.rs.container.Suspended)4 List (java.util.List)3 Collections (java.util.Collections)2 Queue (java.util.Queue)2 OutputBufferId (com.facebook.presto.OutputBuffers.OutputBufferId)1 PRESTO_PAGES (com.facebook.presto.PrestoMediaTypes.PRESTO_PAGES)1 Session (com.facebook.presto.Session)1 PRESTO_BUFFER_COMPLETE (com.facebook.presto.client.PrestoHeaders.PRESTO_BUFFER_COMPLETE)1 PRESTO_CURRENT_STATE (com.facebook.presto.client.PrestoHeaders.PRESTO_CURRENT_STATE)1 PRESTO_MAX_SIZE (com.facebook.presto.client.PrestoHeaders.PRESTO_MAX_SIZE)1 PRESTO_MAX_WAIT (com.facebook.presto.client.PrestoHeaders.PRESTO_MAX_WAIT)1 PRESTO_PAGE_NEXT_TOKEN (com.facebook.presto.client.PrestoHeaders.PRESTO_PAGE_NEXT_TOKEN)1 PRESTO_PAGE_TOKEN (com.facebook.presto.client.PrestoHeaders.PRESTO_PAGE_TOKEN)1 PRESTO_TASK_INSTANCE_ID (com.facebook.presto.client.PrestoHeaders.PRESTO_TASK_INSTANCE_ID)1 TaskId (com.facebook.presto.execution.TaskId)1 TaskInfo (com.facebook.presto.execution.TaskInfo)1