Search in sources :

Example 1 with MultiFuture

use of com.google.appengine.api.datastore.FutureHelper.MultiFuture in project appengine-java-standard by GoogleCloudPlatform.

the class AsyncDatastoreServiceImpl method doBatchDelete.

@Override
protected Future<Void> doBatchDelete(@Nullable Transaction txn, Collection<Key> keys) {
    DeleteRequest baseReq = new DeleteRequest();
    if (txn != null) {
        TransactionImpl.ensureTxnActive(txn);
        baseReq.setTransaction(InternalTransactionV3.toProto(txn));
    }
    // Do not group inside a transaction.
    boolean group = !baseReq.hasTransaction();
    Iterator<DeleteRequest> batches = deleteBatcher.getBatches(keys, baseReq, baseReq.getSerializedSize(), group);
    List<Future<DeleteResponse>> futures = deleteBatcher.makeCalls(batches);
    return registerInTransaction(txn, new MultiFuture<DeleteResponse, Void>(futures) {

        @Override
        public Void get() throws InterruptedException, ExecutionException {
            for (Future<DeleteResponse> future : futures) {
                future.get();
            }
            return null;
        }

        @Override
        public Void get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
            for (Future<DeleteResponse> future : futures) {
                future.get(timeout, unit);
            }
            return null;
        }
    });
}
Also used : DeleteResponse(com.google.apphosting.datastore.DatastoreV3Pb.DeleteResponse) Future(java.util.concurrent.Future) MultiFuture(com.google.appengine.api.datastore.FutureHelper.MultiFuture) ReorderingMultiFuture(com.google.appengine.api.datastore.Batcher.ReorderingMultiFuture) TimeUnit(java.util.concurrent.TimeUnit) ExecutionException(java.util.concurrent.ExecutionException) DeleteRequest(com.google.apphosting.datastore.DatastoreV3Pb.DeleteRequest) TimeoutException(java.util.concurrent.TimeoutException)

Example 2 with MultiFuture

use of com.google.appengine.api.datastore.FutureHelper.MultiFuture in project appengine-java-standard by GoogleCloudPlatform.

the class AsyncDatastoreServiceImpl method doBatchGet.

@Override
protected final Future<Map<Key, Entity>> doBatchGet(@Nullable Transaction txn, final Set<Key> keysToGet, final Map<Key, Entity> resultMap) {
    // Initializing base request.
    final GetRequest baseReq = new GetRequest();
    baseReq.setAllowDeferred(true);
    if (txn != null) {
        TransactionImpl.ensureTxnActive(txn);
        baseReq.setTransaction(InternalTransactionV3.toProto(txn));
    }
    if (datastoreServiceConfig.getReadPolicy().getConsistency() == EVENTUAL) {
        baseReq.setFailoverMs(ARBITRARY_FAILOVER_READ_MS);
        // Allows the datastore to always use READ_CONSISTENT.
        baseReq.setStrong(false);
    }
    final boolean shouldUseMultipleBatches = txn == null && datastoreServiceConfig.getReadPolicy().getConsistency() != EVENTUAL;
    // Batch and issue the request(s).
    Iterator<GetRequest> batches = getByKeyBatcher.getBatches(keysToGet, baseReq, baseReq.getSerializedSize(), shouldUseMultipleBatches);
    List<Future<GetResponse>> futures = getByKeyBatcher.makeCalls(batches);
    return registerInTransaction(txn, new MultiFuture<GetResponse, Map<Key, Entity>>(futures) {

        /**
         * A Map from a Reference without an App Id specified to the corresponding Key that the
         * user requested. This is a workaround for the Remote API to support matching requested
         * Keys to Entities that may be from a different App Id .
         */
        private Map<Reference, Key> keyMapIgnoringAppId;

        @Override
        public Map<Key, Entity> get() throws InterruptedException, ExecutionException {
            try {
                aggregate(futures, null, null);
            } catch (TimeoutException e) {
                // Should never happen because we are passing null for the timeout params.
                throw new RuntimeException(e);
            }
            return resultMap;
        }

        @Override
        public Map<Key, Entity> get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
            aggregate(futures, timeout, unit);
            return resultMap;
        }

        /**
         * Aggregates the results of the given Futures and issues (synchronous) followup requests
         * if any results were deferred.
         *
         * @param currentFutures the Futures corresponding to the batches of the initial
         *     GetRequests.
         * @param timeout the timeout to use while waiting on the Future, or null for none.
         * @param timeoutUnit the unit of the timeout, or null for none.
         */
        private void aggregate(Iterable<Future<GetResponse>> currentFutures, @Nullable Long timeout, @Nullable TimeUnit timeoutUnit) throws ExecutionException, InterruptedException, TimeoutException {
            // Use a while (true) loop so that we can issue followup requests for any deferred keys.
            while (true) {
                List<Reference> deferredRefs = Lists.newLinkedList();
                // roundtrips)
                for (Future<GetResponse> currentFuture : currentFutures) {
                    GetResponse resp = getFutureWithOptionalTimeout(currentFuture, timeout, timeoutUnit);
                    addEntitiesToResultMap(resp);
                    deferredRefs.addAll(resp.deferreds());
                }
                if (deferredRefs.isEmpty()) {
                    // Done.
                    break;
                }
                // Some keys were deferred.  Issue followup requests, and loop again.
                Iterator<GetRequest> followupBatches = getByReferenceBatcher.getBatches(deferredRefs, baseReq, baseReq.getSerializedSize(), shouldUseMultipleBatches);
                currentFutures = getByReferenceBatcher.makeCalls(followupBatches);
            }
        }

        /**
         * Convenience method to get the result of a Future and optionally specify a timeout.
         *
         * @param future the Future to get.
         * @param timeout the timeout to use while waiting on the Future, or null for none.
         * @param timeoutUnit the unit of the timeout, or null for none.
         * @return the result of the Future.
         * @throws TimeoutException will only ever be thrown if a timeout is provided.
         */
        private GetResponse getFutureWithOptionalTimeout(Future<GetResponse> future, @Nullable Long timeout, @Nullable TimeUnit timeoutUnit) throws ExecutionException, InterruptedException, TimeoutException {
            if (timeout == null) {
                return future.get();
            } else {
                return future.get(timeout, timeoutUnit);
            }
        }

        /**
         * Adds the Entities from the GetResponse to the resultMap. Will omit Keys that were
         * missing. Handles Keys with different App Ids from the Entity.Key. See {@link
         * #findKeyFromRequestIgnoringAppId(Reference)}
         */
        private void addEntitiesToResultMap(GetResponse response) {
            for (GetResponse.Entity entityResult : response.entitys()) {
                if (entityResult.hasEntity()) {
                    Entity responseEntity = EntityTranslator.createFromPb(entityResult.getEntity());
                    Key responseKey = responseEntity.getKey();
                    // Hack for Remote API which rewrites App Ids on Keys.
                    if (!keysToGet.contains(responseKey)) {
                        responseKey = findKeyFromRequestIgnoringAppId(entityResult.getEntity().getKey());
                    }
                    resultMap.put(responseKey, responseEntity);
                }
            // Else, the Key was missing.
            }
        }

        /**
         * This is a hack to support calls going through the Remote API. The problem is:
         *
         * <p>The requested Key may have a local app id. The returned Entity may have a remote app
         * id.
         *
         * <p>In this case, we want to return a Map.Entry with {LocalKey, RemoteEntity}. This way,
         * the user can always do map.get(keyFromRequest).
         *
         * <p>This method will find the corresponding requested LocalKey for a RemoteKey by
         * ignoring the AppId field.
         *
         * <p>Note that we used to be able to rely on the order of the Response Entities matching
         * the order of Request Keys. We can no longer do so with the addition of Deferred
         * results.
         *
         * @param referenceFromResponse the reference from the Response that did not match any of
         *     the requested Keys. (May be mutated.)
         * @return the Key from the request that corresponds to the given Reference from the
         *     Response (ignoring AppId.)
         */
        private Key findKeyFromRequestIgnoringAppId(Reference referenceFromResponse) {
            // We'll create this Map lazily the first time, then cache it for future calls.
            if (keyMapIgnoringAppId == null) {
                keyMapIgnoringAppId = Maps.newHashMap();
                for (Key requestKey : keysToGet) {
                    Reference requestKeyAsRefWithoutApp = KeyTranslator.convertToPb(requestKey).clearApp();
                    keyMapIgnoringAppId.put(requestKeyAsRefWithoutApp, requestKey);
                }
            }
            // Note: mutating the input ref, but that's ok.
            Key result = keyMapIgnoringAppId.get(referenceFromResponse.clearApp());
            if (result == null) {
                // TODO: What should we do here?
                throw new DatastoreFailureException("Internal error");
            }
            return result;
        }
    });
}
Also used : GetRequest(com.google.apphosting.datastore.DatastoreV3Pb.GetRequest) Iterator(java.util.Iterator) TimeUnit(java.util.concurrent.TimeUnit) ArrayList(java.util.ArrayList) List(java.util.List) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException) Reference(com.google.storage.onestore.v3.OnestoreEntity.Reference) GetResponse(com.google.apphosting.datastore.DatastoreV3Pb.GetResponse) Future(java.util.concurrent.Future) MultiFuture(com.google.appengine.api.datastore.FutureHelper.MultiFuture) ReorderingMultiFuture(com.google.appengine.api.datastore.Batcher.ReorderingMultiFuture) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Aggregations

ReorderingMultiFuture (com.google.appengine.api.datastore.Batcher.ReorderingMultiFuture)2 MultiFuture (com.google.appengine.api.datastore.FutureHelper.MultiFuture)2 ExecutionException (java.util.concurrent.ExecutionException)2 Future (java.util.concurrent.Future)2 TimeUnit (java.util.concurrent.TimeUnit)2 TimeoutException (java.util.concurrent.TimeoutException)2 DeleteRequest (com.google.apphosting.datastore.DatastoreV3Pb.DeleteRequest)1 DeleteResponse (com.google.apphosting.datastore.DatastoreV3Pb.DeleteResponse)1 GetRequest (com.google.apphosting.datastore.DatastoreV3Pb.GetRequest)1 GetResponse (com.google.apphosting.datastore.DatastoreV3Pb.GetResponse)1 Reference (com.google.storage.onestore.v3.OnestoreEntity.Reference)1 ArrayList (java.util.ArrayList)1 Iterator (java.util.Iterator)1 LinkedHashMap (java.util.LinkedHashMap)1 List (java.util.List)1 Map (java.util.Map)1