use of com.google.storage.onestore.v3.OnestoreEntity.Reference in project appengine-java-standard by GoogleCloudPlatform.
the class KeyTranslatorTest method testConvertFromPbNoElements.
@Test
public void testConvertFromPbNoElements() throws Exception {
Reference ref = new Reference();
assertThrows(IllegalArgumentException.class, () -> KeyTranslator.createFromPb(ref));
}
use of com.google.storage.onestore.v3.OnestoreEntity.Reference in project appengine-java-standard by GoogleCloudPlatform.
the class KeyTranslatorTest method testUpdateKey_Id.
@Test
public void testUpdateKey_Id() {
Key key = new Key("yam");
AppIdNamespace appIdNamespace = key.getAppIdNamespace();
Reference ref = new Reference();
ref.setApp("my app");
Path path = new Path();
Element ele = path.addElement();
ele.setId(23);
ref.setPath(path);
KeyTranslator.updateKey(ref, key);
assertThat(key.getAppIdNamespace()).isEqualTo(appIdNamespace);
// coverage
assertThat(key.getAppId()).isEqualTo(appIdNamespace.getAppId());
assertThat(key.getId()).isEqualTo(23);
assertThat(key.getName()).isNull();
}
use of com.google.storage.onestore.v3.OnestoreEntity.Reference in project appengine-java-standard by GoogleCloudPlatform.
the class KeyTranslatorTest method testConvertToPbTwoLevelsWithName.
@Test
public void testConvertToPbTwoLevelsWithName() throws Exception {
Key key1 = new Key("foo", "name");
Key key2 = new Key("bar", key1, "name");
assertThat(key2.isComplete()).isTrue();
assertThat(key2.getName()).isEqualTo("name");
Reference ref2 = KeyTranslator.convertToPb(key2);
assertThat(ref2.getPath().elementSize()).isEqualTo(2);
assertThat(ref2.getPath().elements().get(0).getType()).isEqualTo("foo");
assertThat(ref2.getPath().elements().get(0).hasName()).isTrue();
assertThat(ref2.getPath().elements().get(0).getName()).isEqualTo("name");
assertThat(ref2.getPath().elements().get(0).hasId()).isFalse();
assertThat(ref2.getPath().elements().get(1).getType()).isEqualTo("bar");
assertThat(ref2.getPath().elements().get(1).hasName()).isTrue();
assertThat(ref2.getPath().elements().get(1).getName()).isEqualTo("name");
assertThat(ref2.getPath().elements().get(1).hasId()).isFalse();
}
use of com.google.storage.onestore.v3.OnestoreEntity.Reference in project appengine-java-standard by GoogleCloudPlatform.
the class KeyTranslatorTest method testConvertToPbOneLevelWithName.
@Test
public void testConvertToPbOneLevelWithName() throws Exception {
Key key1 = new Key("foo", "name");
assertThat(key1.isComplete()).isTrue();
Reference ref1 = KeyTranslator.convertToPb(key1);
assertThat(ref1.getPath().elementSize()).isEqualTo(1);
assertThat(ref1.getPath().elements().get(0).getType()).isEqualTo("foo");
assertThat(ref1.getPath().elements().get(0).hasId()).isFalse();
assertThat(ref1.getPath().elements().get(0).hasName()).isTrue();
assertThat(ref1.getPath().elements().get(0).getName()).isEqualTo("name");
}
use of com.google.storage.onestore.v3.OnestoreEntity.Reference 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;
}
});
}
Aggregations