/
DatastoreImpl.java
598 lines (543 loc) · 20 KB
/
DatastoreImpl.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
/*
* Copyright 2015 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.datastore;
import com.google.api.gax.retrying.RetrySettings;
import com.google.cloud.BaseService;
import com.google.cloud.ExceptionHandler;
import com.google.cloud.RetryHelper;
import com.google.cloud.RetryHelper.RetryHelperException;
import com.google.cloud.ServiceOptions;
import com.google.cloud.datastore.ReadOption.EventualConsistency;
import com.google.cloud.datastore.spi.v1.DatastoreRpc;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import com.google.common.collect.AbstractIterator;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.google.datastore.v1.ReadOptions.ReadConsistency;
import com.google.datastore.v1.ReserveIdsRequest;
import com.google.datastore.v1.TransactionOptions;
import com.google.protobuf.ByteString;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
final class DatastoreImpl extends BaseService<DatastoreOptions> implements Datastore {
private final DatastoreRpc datastoreRpc;
private final RetrySettings retrySettings;
private static final ExceptionHandler TRANSACTION_EXCEPTION_HANDLER =
TransactionExceptionHandler.build();
private static final ExceptionHandler TRANSACTION_OPERATION_EXCEPTION_HANDLER =
TransactionOperationExceptionHandler.build();
DatastoreImpl(DatastoreOptions options) {
super(options);
this.datastoreRpc = options.getDatastoreRpcV1();
retrySettings =
MoreObjects.firstNonNull(options.getRetrySettings(), ServiceOptions.getNoRetrySettings());
}
@Override
public Batch newBatch() {
return new BatchImpl(this);
}
@Override
public Transaction newTransaction(TransactionOptions transactionOptions) {
return new TransactionImpl(this, transactionOptions);
}
@Override
public Transaction newTransaction() {
return new TransactionImpl(this);
}
static class ReadWriteTransactionCallable<T> implements Callable<T> {
private final Datastore datastore;
private final TransactionCallable<T> callable;
private volatile TransactionOptions options;
private volatile Transaction transaction;
ReadWriteTransactionCallable(
Datastore datastore, TransactionCallable<T> callable, TransactionOptions options) {
this.datastore = datastore;
this.callable = callable;
this.options = options;
this.transaction = null;
}
Datastore getDatastore() {
return datastore;
}
TransactionOptions getOptions() {
return options;
}
Transaction getTransaction() {
return transaction;
}
void setPrevTransactionId(ByteString transactionId) {
TransactionOptions.ReadWrite readWrite =
TransactionOptions.ReadWrite.newBuilder().setPreviousTransaction(transactionId).build();
options = options.toBuilder().setReadWrite(readWrite).build();
}
@Override
public T call() throws DatastoreException {
transaction = datastore.newTransaction(options);
try {
T value = callable.run(transaction);
transaction.commit();
return value;
} catch (Exception ex) {
transaction.rollback();
throw DatastoreException.propagateUserException(ex);
} finally {
if (transaction.isActive()) {
transaction.rollback();
}
if (options != null
&& options.getModeCase().equals(TransactionOptions.ModeCase.READ_WRITE)) {
setPrevTransactionId(transaction.getTransactionId());
}
}
}
}
@Override
public <T> T runInTransaction(final TransactionCallable<T> callable) {
final DatastoreImpl self = this;
try {
return RetryHelper.runWithRetries(
new ReadWriteTransactionCallable<T>(self, callable, null),
retrySettings,
TRANSACTION_EXCEPTION_HANDLER,
getOptions().getClock());
} catch (RetryHelperException e) {
throw DatastoreException.translateAndThrow(e);
}
}
@Override
public <T> T runInTransaction(
final TransactionCallable<T> callable, TransactionOptions transactionOptions) {
final DatastoreImpl self = this;
try {
return RetryHelper.runWithRetries(
new ReadWriteTransactionCallable<T>(self, callable, transactionOptions),
retrySettings,
TRANSACTION_EXCEPTION_HANDLER,
getOptions().getClock());
} catch (RetryHelperException e) {
throw DatastoreException.translateAndThrow(e);
}
}
@Override
public <T> QueryResults<T> run(Query<T> query) {
return run(null, query);
}
@Override
public <T> QueryResults<T> run(Query<T> query, ReadOption... options) {
return run(toReadOptionsPb(options), query);
}
<T> QueryResults<T> run(com.google.datastore.v1.ReadOptions readOptionsPb, Query<T> query) {
return new QueryResultsImpl<>(this, readOptionsPb, query);
}
com.google.datastore.v1.RunQueryResponse runQuery(
final com.google.datastore.v1.RunQueryRequest requestPb) {
try {
return RetryHelper.runWithRetries(
new Callable<com.google.datastore.v1.RunQueryResponse>() {
@Override
public com.google.datastore.v1.RunQueryResponse call() throws DatastoreException {
return datastoreRpc.runQuery(requestPb);
}
},
retrySettings,
requestPb.getReadOptions().getTransaction().isEmpty()
? EXCEPTION_HANDLER
: TRANSACTION_OPERATION_EXCEPTION_HANDLER,
getOptions().getClock());
} catch (RetryHelperException e) {
throw DatastoreException.translateAndThrow(e);
}
}
@Override
public Key allocateId(IncompleteKey key) {
return DatastoreHelper.allocateId(this, key);
}
private boolean verifyIncompleteKeyType(IncompleteKey... keys) {
for (IncompleteKey key : keys) {
if (key instanceof Key) {
return false;
}
}
return true;
}
@Override
public List<Key> allocateId(IncompleteKey... keys) {
Preconditions.checkArgument(
verifyIncompleteKeyType(keys), "keys must be IncompleteKey instances");
if (keys.length == 0) {
return Collections.emptyList();
}
com.google.datastore.v1.AllocateIdsRequest.Builder requestPb =
com.google.datastore.v1.AllocateIdsRequest.newBuilder();
for (IncompleteKey key : keys) {
requestPb.addKeys(trimNameOrId(key).toPb());
}
com.google.datastore.v1.AllocateIdsResponse responsePb = allocateIds(requestPb.build());
ImmutableList.Builder<Key> keyList = ImmutableList.builder();
for (com.google.datastore.v1.Key keyPb : responsePb.getKeysList()) {
keyList.add(Key.fromPb(keyPb));
}
return keyList.build();
}
private com.google.datastore.v1.AllocateIdsResponse allocateIds(
final com.google.datastore.v1.AllocateIdsRequest requestPb) {
try {
return RetryHelper.runWithRetries(
new Callable<com.google.datastore.v1.AllocateIdsResponse>() {
@Override
public com.google.datastore.v1.AllocateIdsResponse call() throws DatastoreException {
return datastoreRpc.allocateIds(requestPb);
}
},
retrySettings,
EXCEPTION_HANDLER,
getOptions().getClock());
} catch (RetryHelperException e) {
throw DatastoreException.translateAndThrow(e);
}
}
private IncompleteKey trimNameOrId(IncompleteKey key) {
if (key instanceof Key) {
return IncompleteKey.newBuilder(key).build();
}
return key;
}
@Override
public Entity add(FullEntity<?> entity) {
return DatastoreHelper.add(this, entity);
}
@SuppressWarnings("unchecked")
@Override
public List<Entity> add(FullEntity<?>... entities) {
if (entities.length == 0) {
return Collections.emptyList();
}
List<com.google.datastore.v1.Mutation> mutationsPb = new ArrayList<>();
Map<Key, Entity> completeEntities = new LinkedHashMap<>();
for (FullEntity<?> entity : entities) {
Entity completeEntity = null;
if (entity.getKey() instanceof Key) {
completeEntity = Entity.convert((FullEntity<Key>) entity);
}
if (completeEntity != null) {
if (completeEntities.put(completeEntity.getKey(), completeEntity) != null) {
throw DatastoreException.throwInvalidRequest(
"Duplicate entity with the key %s", entity.getKey());
}
} else {
Preconditions.checkArgument(entity.hasKey(), "Entity %s is missing a key", entity);
}
mutationsPb.add(
com.google.datastore.v1.Mutation.newBuilder().setInsert(entity.toPb()).build());
}
com.google.datastore.v1.CommitResponse commitResponse = commitMutation(mutationsPb);
Iterator<com.google.datastore.v1.MutationResult> mutationResults =
commitResponse.getMutationResultsList().iterator();
ImmutableList.Builder<Entity> responseBuilder = ImmutableList.builder();
for (FullEntity<?> entity : entities) {
Entity completeEntity = completeEntities.get(entity.getKey());
if (completeEntity != null) {
responseBuilder.add(completeEntity);
mutationResults.next();
} else {
responseBuilder.add(
Entity.newBuilder(Key.fromPb(mutationResults.next().getKey()), entity).build());
}
}
return responseBuilder.build();
}
@Override
public Entity get(Key key) {
return DatastoreHelper.get(this, key);
}
@Override
public Entity get(Key key, ReadOption... options) {
return DatastoreHelper.get(this, key, options);
}
@Override
public Iterator<Entity> get(Key... keys) {
return get(null, keys);
}
@Override
public Iterator<Entity> get(Iterable<Key> keys, ReadOption... options) {
return get(toReadOptionsPb(options), Iterables.toArray(keys, Key.class));
}
private static com.google.datastore.v1.ReadOptions toReadOptionsPb(ReadOption... options) {
com.google.datastore.v1.ReadOptions readOptionsPb = null;
if (options != null
&& ReadOption.asImmutableMap(options).containsKey(EventualConsistency.class)) {
readOptionsPb =
com.google.datastore.v1.ReadOptions.newBuilder()
.setReadConsistency(ReadConsistency.EVENTUAL)
.build();
}
return readOptionsPb;
}
@Override
public List<Entity> fetch(Key... keys) {
return DatastoreHelper.fetch(this, keys);
}
@Override
public List<Entity> fetch(Iterable<Key> keys, ReadOption... options) {
return DatastoreHelper.fetch(this, Iterables.toArray(keys, Key.class), options);
}
Iterator<Entity> get(com.google.datastore.v1.ReadOptions readOptionsPb, final Key... keys) {
if (keys.length == 0) {
return Collections.emptyIterator();
}
com.google.datastore.v1.LookupRequest.Builder requestPb =
com.google.datastore.v1.LookupRequest.newBuilder();
if (readOptionsPb != null) {
requestPb.setReadOptions(readOptionsPb);
}
for (Key k : Sets.newLinkedHashSet(Arrays.asList(keys))) {
requestPb.addKeys(k.toPb());
}
return new ResultsIterator(requestPb);
}
final class ResultsIterator extends AbstractIterator<Entity> {
private final com.google.datastore.v1.LookupRequest.Builder requestPb;
Iterator<com.google.datastore.v1.EntityResult> iter;
ResultsIterator(com.google.datastore.v1.LookupRequest.Builder requestPb) {
this.requestPb = requestPb;
loadResults();
}
private void loadResults() {
com.google.datastore.v1.LookupResponse responsePb = lookup(requestPb.build());
iter = responsePb.getFoundList().iterator();
requestPb.clearKeys();
if (responsePb.getDeferredCount() > 0) {
requestPb.addAllKeys(responsePb.getDeferredList());
}
}
@SuppressWarnings("unchecked")
@Override
protected Entity computeNext() {
while (!iter.hasNext()) {
if (requestPb.getKeysCount() == 0) {
return endOfData();
}
loadResults();
}
return Entity.fromPb(iter.next().getEntity());
}
}
com.google.datastore.v1.LookupResponse lookup(
final com.google.datastore.v1.LookupRequest requestPb) {
try {
return RetryHelper.runWithRetries(
new Callable<com.google.datastore.v1.LookupResponse>() {
@Override
public com.google.datastore.v1.LookupResponse call() throws DatastoreException {
return datastoreRpc.lookup(requestPb);
}
},
retrySettings,
requestPb.getReadOptions().getTransaction().isEmpty()
? EXCEPTION_HANDLER
: TRANSACTION_OPERATION_EXCEPTION_HANDLER,
getOptions().getClock());
} catch (RetryHelperException e) {
throw DatastoreException.translateAndThrow(e);
}
}
@Override
public List<Key> reserveIds(Key... keys) {
ReserveIdsRequest.Builder requestPb = ReserveIdsRequest.newBuilder();
for (Key key : keys) {
requestPb.addKeys(key.toPb());
}
com.google.datastore.v1.ReserveIdsResponse responsePb = reserveIds(requestPb.build());
ImmutableList.Builder<Key> keyList = ImmutableList.builder();
if (responsePb.isInitialized()) {
for (Key key : keys) {
keyList.add(key);
}
}
return keyList.build();
}
com.google.datastore.v1.ReserveIdsResponse reserveIds(
final com.google.datastore.v1.ReserveIdsRequest requestPb) {
try {
return RetryHelper.runWithRetries(
new Callable<com.google.datastore.v1.ReserveIdsResponse>() {
@Override
public com.google.datastore.v1.ReserveIdsResponse call() throws DatastoreException {
return datastoreRpc.reserveIds(requestPb);
}
},
retrySettings,
EXCEPTION_HANDLER,
getOptions().getClock());
} catch (RetryHelperException e) {
throw DatastoreException.translateAndThrow(e);
}
}
@Override
public void update(Entity... entities) {
if (entities.length > 0) {
List<com.google.datastore.v1.Mutation> mutationsPb = new ArrayList<>();
Map<Key, Entity> dedupEntities = new LinkedHashMap<>();
for (Entity entity : entities) {
dedupEntities.put(entity.getKey(), entity);
}
for (Entity entity : dedupEntities.values()) {
mutationsPb.add(
com.google.datastore.v1.Mutation.newBuilder().setUpdate(entity.toPb()).build());
}
commitMutation(mutationsPb);
}
}
@Override
public Entity put(FullEntity<?> entity) {
return DatastoreHelper.put(this, entity);
}
@SuppressWarnings("unchecked")
@Override
public List<Entity> put(FullEntity<?>... entities) {
if (entities.length == 0) {
return Collections.emptyList();
}
List<com.google.datastore.v1.Mutation> mutationsPb = new ArrayList<>();
Map<Key, Entity> dedupEntities = new LinkedHashMap<>();
for (FullEntity<?> entity : entities) {
Preconditions.checkArgument(entity.hasKey(), "Entity %s is missing a key", entity);
if (entity.getKey() instanceof Key) {
Entity completeEntity = Entity.convert((FullEntity<Key>) entity);
dedupEntities.put(completeEntity.getKey(), completeEntity);
} else {
mutationsPb.add(
com.google.datastore.v1.Mutation.newBuilder().setUpsert(entity.toPb()).build());
}
}
for (Entity entity : dedupEntities.values()) {
mutationsPb.add(
com.google.datastore.v1.Mutation.newBuilder().setUpsert(entity.toPb()).build());
}
com.google.datastore.v1.CommitResponse commitResponse = commitMutation(mutationsPb);
Iterator<com.google.datastore.v1.MutationResult> mutationResults =
commitResponse.getMutationResultsList().iterator();
ImmutableList.Builder<Entity> responseBuilder = ImmutableList.builder();
for (FullEntity<?> entity : entities) {
Entity completeEntity = dedupEntities.get(entity.getKey());
if (completeEntity != null) {
responseBuilder.add(completeEntity);
} else {
responseBuilder.add(
Entity.newBuilder(Key.fromPb(mutationResults.next().getKey()), entity).build());
}
}
return responseBuilder.build();
}
@Override
public void delete(Key... keys) {
if (keys.length > 0) {
List<com.google.datastore.v1.Mutation> mutationsPb = new ArrayList<>();
Set<Key> dedupKeys = new LinkedHashSet<>(Arrays.asList(keys));
for (Key key : dedupKeys) {
mutationsPb.add(
com.google.datastore.v1.Mutation.newBuilder().setDelete(key.toPb()).build());
}
commitMutation(mutationsPb);
}
}
@Override
public KeyFactory newKeyFactory() {
return DatastoreHelper.newKeyFactory(getOptions());
}
private com.google.datastore.v1.CommitResponse commitMutation(
List<com.google.datastore.v1.Mutation> mutationsPb) {
com.google.datastore.v1.CommitRequest.Builder requestPb =
com.google.datastore.v1.CommitRequest.newBuilder();
requestPb.setMode(com.google.datastore.v1.CommitRequest.Mode.NON_TRANSACTIONAL);
requestPb.addAllMutations(mutationsPb);
return commit(requestPb.build());
}
com.google.datastore.v1.CommitResponse commit(
final com.google.datastore.v1.CommitRequest requestPb) {
try {
return RetryHelper.runWithRetries(
new Callable<com.google.datastore.v1.CommitResponse>() {
@Override
public com.google.datastore.v1.CommitResponse call() throws DatastoreException {
return datastoreRpc.commit(requestPb);
}
},
retrySettings,
requestPb.getTransaction().isEmpty()
? EXCEPTION_HANDLER
: TRANSACTION_OPERATION_EXCEPTION_HANDLER,
getOptions().getClock());
} catch (RetryHelperException e) {
throw DatastoreException.translateAndThrow(e);
}
}
ByteString requestTransactionId(
com.google.datastore.v1.BeginTransactionRequest.Builder requestPb) {
return beginTransaction(requestPb.build()).getTransaction();
}
com.google.datastore.v1.BeginTransactionResponse beginTransaction(
final com.google.datastore.v1.BeginTransactionRequest requestPb) {
try {
return RetryHelper.runWithRetries(
new Callable<com.google.datastore.v1.BeginTransactionResponse>() {
@Override
public com.google.datastore.v1.BeginTransactionResponse call()
throws DatastoreException {
return datastoreRpc.beginTransaction(requestPb);
}
},
retrySettings,
EXCEPTION_HANDLER,
getOptions().getClock());
} catch (RetryHelperException e) {
throw DatastoreException.translateAndThrow(e);
}
}
void rollbackTransaction(ByteString transaction) {
com.google.datastore.v1.RollbackRequest.Builder requestPb =
com.google.datastore.v1.RollbackRequest.newBuilder();
requestPb.setTransaction(transaction);
rollback(requestPb.build());
}
void rollback(final com.google.datastore.v1.RollbackRequest requestPb) {
try {
RetryHelper.runWithRetries(
new Callable<Void>() {
@Override
public Void call() throws DatastoreException {
datastoreRpc.rollback(requestPb);
return null;
}
},
retrySettings,
EXCEPTION_HANDLER,
getOptions().getClock());
} catch (RetryHelperException e) {
throw DatastoreException.translateAndThrow(e);
}
}
}