Search in sources :

Example 1 with GraphQLProjectionInfo

use of com.yahoo.elide.graphql.parser.GraphQLProjectionInfo in project elide by yahoo.

the class GraphQLTableExportOperation method getProjections.

@Override
public Collection<EntityProjection> getProjections(TableExport export, RequestScope scope) {
    GraphQLProjectionInfo projectionInfo;
    try {
        String graphQLDocument = export.getQuery();
        Elide elide = getService().getElide();
        ObjectMapper mapper = elide.getMapper().getObjectMapper();
        JsonNode node = QueryRunner.getTopLevelNode(mapper, graphQLDocument);
        Map<String, Object> variables = QueryRunner.extractVariables(mapper, node);
        String queryString = QueryRunner.extractQuery(node);
        projectionInfo = new GraphQLEntityProjectionMaker(elide.getElideSettings(), variables, scope.getApiVersion()).make(queryString);
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
    return projectionInfo.getProjections().values();
}
Also used : GraphQLProjectionInfo(com.yahoo.elide.graphql.parser.GraphQLProjectionInfo) JsonNode(com.fasterxml.jackson.databind.JsonNode) GraphQLEntityProjectionMaker(com.yahoo.elide.graphql.parser.GraphQLEntityProjectionMaker) IOException(java.io.IOException) Elide(com.yahoo.elide.Elide) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 2 with GraphQLProjectionInfo

use of com.yahoo.elide.graphql.parser.GraphQLProjectionInfo in project elide by yahoo.

the class SubscriptionDataFetcherTest method runSubscription.

/**
 * Run a subscription.
 * @param request The subscription query.
 * @return A discrete list of results returned from the subscription.
 */
protected List<ExecutionResult> runSubscription(String request) {
    InMemoryDataStore inMemoryDataStore = new InMemoryDataStore(dataStore);
    DataStoreTransaction tx = inMemoryDataStore.beginTransaction();
    GraphQLProjectionInfo projectionInfo = new SubscriptionEntityProjectionMaker(settings, new HashMap<>(), NO_VERSION).make(request);
    GraphQLRequestScope requestScope = new GraphQLRequestScope(baseUrl, tx, null, NO_VERSION, settings, projectionInfo, UUID.randomUUID(), null);
    ExecutionInput executionInput = ExecutionInput.newExecutionInput().query(request).localContext(requestScope).build();
    ExecutionResult executionResult = api.execute(executionInput);
    if (!(executionResult.getData() instanceof Publisher)) {
        return List.of(executionResult);
    }
    Publisher<ExecutionResult> resultPublisher = executionResult.getData();
    requestScope.getTransaction().commit(requestScope);
    if (resultPublisher == null) {
        return List.of(executionResult);
    }
    List<ExecutionResult> results = new ArrayList<>();
    AtomicReference<Subscription> subscriptionRef = new AtomicReference<>();
    AtomicReference<Throwable> errorRef = new AtomicReference<>();
    resultPublisher.subscribe(new Subscriber<ExecutionResult>() {

        @Override
        public void onSubscribe(Subscription subscription) {
            subscriptionRef.set(subscription);
            subscription.request(1);
        }

        @Override
        public void onNext(ExecutionResult executionResult) {
            results.add(executionResult);
            subscriptionRef.get().request(1);
        }

        @Override
        public void onError(Throwable t) {
            errorRef.set(t);
        }

        @Override
        public void onComplete() {
        // NOOP
        }
    });
    return results;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) GraphQLProjectionInfo(com.yahoo.elide.graphql.parser.GraphQLProjectionInfo) GraphQLRequestScope(com.yahoo.elide.graphql.GraphQLRequestScope) ExecutionResult(graphql.ExecutionResult) AtomicReference(java.util.concurrent.atomic.AtomicReference) Publisher(org.reactivestreams.Publisher) InMemoryDataStore(com.yahoo.elide.core.datastore.inmemory.InMemoryDataStore) SubscriptionEntityProjectionMaker(com.yahoo.elide.graphql.parser.SubscriptionEntityProjectionMaker) DataStoreTransaction(com.yahoo.elide.core.datastore.DataStoreTransaction) ExecutionInput(graphql.ExecutionInput) Subscription(org.reactivestreams.Subscription)

Example 3 with GraphQLProjectionInfo

use of com.yahoo.elide.graphql.parser.GraphQLProjectionInfo in project elide by yahoo.

the class RequestHandler method executeRequest.

public synchronized ExecutionResult executeRequest(Subscribe subscribeRequest) {
    if (transaction != null) {
        throw new IllegalStateException("Already handling an active request.");
    }
    transaction = topicStore.beginReadTransaction();
    elide.getTransactionRegistry().addRunningTransaction(requestID, transaction);
    ElideSettings settings = elide.getElideSettings();
    GraphQLProjectionInfo projectionInfo = new SubscriptionEntityProjectionMaker(settings, subscribeRequest.getPayload().getVariables(), connectionInfo.getGetApiVersion()).make(subscribeRequest.getPayload().getQuery());
    GraphQLRequestScope requestScope = new GraphQLRequestScope(connectionInfo.getBaseUrl(), transaction, connectionInfo.getUser(), connectionInfo.getGetApiVersion(), settings, projectionInfo, requestID, connectionInfo.getParameters());
    ExecutionInput executionInput = ExecutionInput.newExecutionInput().query(subscribeRequest.getPayload().getQuery()).operationName(subscribeRequest.getPayload().getOperationName()).variables(subscribeRequest.getPayload().getVariables()).localContext(requestScope).build();
    log.info("Processing GraphQL query:\n{}", subscribeRequest.getPayload().getQuery());
    return api.execute(executionInput);
}
Also used : GraphQLProjectionInfo(com.yahoo.elide.graphql.parser.GraphQLProjectionInfo) ElideSettings(com.yahoo.elide.ElideSettings) GraphQLRequestScope(com.yahoo.elide.graphql.GraphQLRequestScope) ExecutionInput(graphql.ExecutionInput) SubscriptionEntityProjectionMaker(com.yahoo.elide.graphql.parser.SubscriptionEntityProjectionMaker)

Example 4 with GraphQLProjectionInfo

use of com.yahoo.elide.graphql.parser.GraphQLProjectionInfo in project elide by yahoo.

the class QueryRunner method executeGraphQLRequest.

private ElideResponse executeGraphQLRequest(String baseUrlEndPoint, ObjectMapper mapper, User principal, String graphQLDocument, GraphQLQuery query, UUID requestId, Map<String, List<String>> requestHeaders) {
    boolean isVerbose = false;
    String queryText = query.getQuery();
    boolean isMutation = isMutation(queryText);
    try (DataStoreTransaction tx = isMutation ? elide.getDataStore().beginTransaction() : elide.getDataStore().beginReadTransaction()) {
        elide.getTransactionRegistry().addRunningTransaction(requestId, tx);
        if (query.getQuery() == null || query.getQuery().isEmpty()) {
            return ElideResponse.builder().responseCode(HttpStatus.SC_BAD_REQUEST).body("A `query` key is required.").build();
        }
        // get variables from request for constructing entityProjections
        Map<String, Object> variables = query.getVariables();
        // TODO - get API version.
        GraphQLProjectionInfo projectionInfo = new GraphQLEntityProjectionMaker(elide.getElideSettings(), variables, apiVersion).make(queryText);
        GraphQLRequestScope requestScope = new GraphQLRequestScope(baseUrlEndPoint, tx, principal, apiVersion, elide.getElideSettings(), projectionInfo, requestId, requestHeaders);
        isVerbose = requestScope.getPermissionExecutor().isVerbose();
        // Logging all queries. It is recommended to put any private information that shouldn't be logged into
        // the "variables" section of your query. Variable values are not logged.
        log.info("Processing GraphQL query:\n{}", queryText);
        ExecutionInput.Builder executionInput = new ExecutionInput.Builder().localContext(requestScope).query(queryText);
        if (query.getOperationName() != null) {
            executionInput.operationName(query.getOperationName());
        }
        executionInput.variables(variables);
        ExecutionResult result = api.execute(executionInput);
        tx.preCommit(requestScope);
        requestScope.getPermissionExecutor().executeCommitChecks();
        if (isMutation) {
            if (!result.getErrors().isEmpty()) {
                HashMap<String, Object> abortedResponseObject = new HashMap<>();
                abortedResponseObject.put("errors", result.getErrors());
                abortedResponseObject.put("data", null);
                // Do not commit. Throw OK response to process tx.close correctly.
                throw new WebApplicationException(Response.ok(mapper.writeValueAsString(abortedResponseObject)).build());
            }
            requestScope.saveOrCreateObjects();
        }
        tx.flush(requestScope);
        requestScope.runQueuedPreCommitTriggers();
        elide.getAuditLogger().commit();
        tx.commit(requestScope);
        requestScope.runQueuedPostCommitTriggers();
        if (log.isTraceEnabled()) {
            requestScope.getPermissionExecutor().logCheckStats();
        }
        return ElideResponse.builder().responseCode(HttpStatus.SC_OK).body(mapper.writeValueAsString(result)).build();
    } catch (JsonProcessingException e) {
        log.debug("Invalid json body provided to GraphQL", e);
        return buildErrorResponse(mapper, new InvalidEntityBodyException(graphQLDocument), isVerbose);
    } catch (IOException e) {
        log.error("Uncaught IO Exception by Elide in GraphQL", e);
        return buildErrorResponse(mapper, new TransactionException(e), isVerbose);
    } catch (RuntimeException e) {
        return handleRuntimeException(elide, e, isVerbose);
    } finally {
        elide.getTransactionRegistry().removeRunningTransaction(requestId);
        elide.getAuditLogger().clear();
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) HashMap(java.util.HashMap) GraphQLProjectionInfo(com.yahoo.elide.graphql.parser.GraphQLProjectionInfo) ExecutionResult(graphql.ExecutionResult) IOException(java.io.IOException) InvalidEntityBodyException(com.yahoo.elide.core.exceptions.InvalidEntityBodyException) TransactionException(com.yahoo.elide.core.exceptions.TransactionException) DataStoreTransaction(com.yahoo.elide.core.datastore.DataStoreTransaction) GraphQLEntityProjectionMaker(com.yahoo.elide.graphql.parser.GraphQLEntityProjectionMaker) ExecutionInput(graphql.ExecutionInput) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Aggregations

GraphQLProjectionInfo (com.yahoo.elide.graphql.parser.GraphQLProjectionInfo)4 ExecutionInput (graphql.ExecutionInput)3 DataStoreTransaction (com.yahoo.elide.core.datastore.DataStoreTransaction)2 GraphQLRequestScope (com.yahoo.elide.graphql.GraphQLRequestScope)2 GraphQLEntityProjectionMaker (com.yahoo.elide.graphql.parser.GraphQLEntityProjectionMaker)2 SubscriptionEntityProjectionMaker (com.yahoo.elide.graphql.parser.SubscriptionEntityProjectionMaker)2 ExecutionResult (graphql.ExecutionResult)2 IOException (java.io.IOException)2 HashMap (java.util.HashMap)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 Elide (com.yahoo.elide.Elide)1 ElideSettings (com.yahoo.elide.ElideSettings)1 InMemoryDataStore (com.yahoo.elide.core.datastore.inmemory.InMemoryDataStore)1 InvalidEntityBodyException (com.yahoo.elide.core.exceptions.InvalidEntityBodyException)1 TransactionException (com.yahoo.elide.core.exceptions.TransactionException)1 ArrayList (java.util.ArrayList)1 AtomicReference (java.util.concurrent.atomic.AtomicReference)1 WebApplicationException (javax.ws.rs.WebApplicationException)1