-
Notifications
You must be signed in to change notification settings - Fork 90
/
Copy pathDataLoaderHelper.java
493 lines (441 loc) · 21.1 KB
/
DataLoaderHelper.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
package org.dataloader;
import org.dataloader.annotations.GuardedBy;
import org.dataloader.annotations.Internal;
import org.dataloader.impl.CompletableFutureKit;
import org.dataloader.stats.StatisticsCollector;
import java.time.Clock;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.atomic.AtomicReference;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.concurrent.CompletableFuture.allOf;
import static java.util.concurrent.CompletableFuture.completedFuture;
import static java.util.stream.Collectors.toList;
import static org.dataloader.impl.Assertions.assertState;
import static org.dataloader.impl.Assertions.nonNull;
/**
* This helps break up the large DataLoader class functionality and it contains the logic to dispatch the
* promises on behalf of its peer dataloader
*
* @param <K> the type of keys
* @param <V> the type of values
*/
@Internal
class DataLoaderHelper<K, V> {
static class LoaderQueueEntry<K, V> {
final K key;
final V value;
final Object callContext;
public LoaderQueueEntry(K key, V value, Object callContext) {
this.key = key;
this.value = value;
this.callContext = callContext;
}
K getKey() {
return key;
}
V getValue() {
return value;
}
Object getCallContext() {
return callContext;
}
}
private final DataLoader<K, V> dataLoader;
private final Object batchLoadFunction;
private final DataLoaderOptions loaderOptions;
private final CacheMap<Object, V> futureCache;
private final ValueCache<K, V> valueCache;
private final List<LoaderQueueEntry<K, CompletableFuture<V>>> loaderQueue;
private final StatisticsCollector stats;
private final Clock clock;
private final AtomicReference<Instant> lastDispatchTime;
DataLoaderHelper(DataLoader<K, V> dataLoader,
Object batchLoadFunction,
DataLoaderOptions loaderOptions,
CacheMap<Object, V> futureCache,
ValueCache<K, V> valueCache,
StatisticsCollector stats,
Clock clock) {
this.dataLoader = dataLoader;
this.batchLoadFunction = batchLoadFunction;
this.loaderOptions = loaderOptions;
this.futureCache = futureCache;
this.valueCache = valueCache;
this.loaderQueue = new ArrayList<>();
this.stats = stats;
this.clock = clock;
this.lastDispatchTime = new AtomicReference<>();
this.lastDispatchTime.set(now());
}
Instant now() {
return clock.instant();
}
public Instant getLastDispatchTime() {
return lastDispatchTime.get();
}
Optional<CompletableFuture<V>> getIfPresent(K key) {
synchronized (dataLoader) {
boolean cachingEnabled = loaderOptions.cachingEnabled();
if (cachingEnabled) {
Object cacheKey = getCacheKey(nonNull(key));
if (futureCache.containsKey(cacheKey)) {
stats.incrementCacheHitCount();
return Optional.of(futureCache.get(cacheKey));
}
}
}
return Optional.empty();
}
Optional<CompletableFuture<V>> getIfCompleted(K key) {
synchronized (dataLoader) {
Optional<CompletableFuture<V>> cachedPromise = getIfPresent(key);
if (cachedPromise.isPresent()) {
CompletableFuture<V> promise = cachedPromise.get();
if (promise.isDone()) {
return cachedPromise;
}
}
}
return Optional.empty();
}
CompletableFuture<V> load(K key, Object loadContext) {
synchronized (dataLoader) {
boolean batchingEnabled = loaderOptions.batchingEnabled();
boolean cachingEnabled = loaderOptions.cachingEnabled();
stats.incrementLoadCount();
if (cachingEnabled) {
return loadFromCache(key, loadContext, batchingEnabled);
} else {
return queueOrInvokeLoader(key, loadContext, batchingEnabled, false);
}
}
}
@SuppressWarnings("unchecked")
Object getCacheKey(K key) {
return loaderOptions.cacheKeyFunction().isPresent() ?
loaderOptions.cacheKeyFunction().get().getKey(key) : key;
}
@SuppressWarnings("unchecked")
Object getCacheKeyWithContext(K key, Object context) {
return loaderOptions.cacheKeyFunction().isPresent() ?
loaderOptions.cacheKeyFunction().get().getKeyWithContext(key, context) : key;
}
DispatchResult<V> dispatch() {
boolean batchingEnabled = loaderOptions.batchingEnabled();
//
// we copy the pre-loaded set of futures ready for dispatch
final List<K> keys = new ArrayList<>();
final List<Object> callContexts = new ArrayList<>();
final List<CompletableFuture<V>> queuedFutures = new ArrayList<>();
synchronized (dataLoader) {
loaderQueue.forEach(entry -> {
keys.add(entry.getKey());
queuedFutures.add(entry.getValue());
callContexts.add(entry.getCallContext());
});
loaderQueue.clear();
lastDispatchTime.set(now());
}
if (!batchingEnabled || keys.isEmpty()) {
return new DispatchResult<>(completedFuture(emptyList()), 0);
}
final int totalEntriesHandled = keys.size();
//
// order of keys -> values matter in data loader hence the use of linked hash map
//
// See /~https://github.com/facebook/dataloader/blob/master/README.md for more details
//
//
// when the promised list of values completes, we transfer the values into
// the previously cached future objects that the client already has been given
// via calls to load("foo") and loadMany(["foo","bar"])
//
int maxBatchSize = loaderOptions.maxBatchSize();
CompletableFuture<List<V>> futureList;
if (maxBatchSize > 0 && maxBatchSize < keys.size()) {
futureList = sliceIntoBatchesOfBatches(keys, queuedFutures, callContexts, maxBatchSize);
} else {
futureList = dispatchQueueBatch(keys, callContexts, queuedFutures);
}
return new DispatchResult<>(futureList, totalEntriesHandled);
}
private CompletableFuture<List<V>> sliceIntoBatchesOfBatches(List<K> keys, List<CompletableFuture<V>> queuedFutures, List<Object> callContexts, int maxBatchSize) {
// the number of keys is > than what the batch loader function can accept
// so make multiple calls to the loader
List<CompletableFuture<List<V>>> allBatches = new ArrayList<>();
int len = keys.size();
int batchCount = (int) Math.ceil(len / (double) maxBatchSize);
for (int i = 0; i < batchCount; i++) {
int fromIndex = i * maxBatchSize;
int toIndex = Math.min((i + 1) * maxBatchSize, len);
List<K> subKeys = keys.subList(fromIndex, toIndex);
List<CompletableFuture<V>> subFutures = queuedFutures.subList(fromIndex, toIndex);
List<Object> subCallContexts = callContexts.subList(fromIndex, toIndex);
allBatches.add(dispatchQueueBatch(subKeys, subCallContexts, subFutures));
}
//
// now reassemble all the futures into one that is the complete set of results
return allOf(allBatches.toArray(new CompletableFuture[0]))
.thenApply(v -> allBatches.stream()
.map(CompletableFuture::join)
.flatMap(Collection::stream)
.collect(toList()));
}
@SuppressWarnings("unchecked")
private CompletableFuture<List<V>> dispatchQueueBatch(List<K> keys, List<Object> callContexts, List<CompletableFuture<V>> queuedFutures) {
stats.incrementBatchLoadCountBy(keys.size());
CompletableFuture<List<V>> batchLoad = invokeLoader(keys, callContexts, loaderOptions.cachingEnabled());
return batchLoad
.thenApply(values -> {
assertResultSize(keys, values);
List<K> clearCacheKeys = new ArrayList<>();
for (int idx = 0; idx < queuedFutures.size(); idx++) {
V value = values.get(idx);
CompletableFuture<V> future = queuedFutures.get(idx);
if (value instanceof Throwable) {
stats.incrementLoadErrorCount();
future.completeExceptionally((Throwable) value);
clearCacheKeys.add(keys.get(idx));
} else if (value instanceof Try) {
// we allow the batch loader to return a Try so we can better represent a computation
// that might have worked or not.
Try<V> tryValue = (Try<V>) value;
if (tryValue.isSuccess()) {
future.complete(tryValue.get());
} else {
stats.incrementLoadErrorCount();
future.completeExceptionally(tryValue.getThrowable());
clearCacheKeys.add(keys.get(idx));
}
} else {
future.complete(value);
}
}
possiblyClearCacheEntriesOnExceptions(clearCacheKeys);
return values;
}).exceptionally(ex -> {
stats.incrementBatchLoadExceptionCount();
if (ex instanceof CompletionException) {
ex = ex.getCause();
}
for (int idx = 0; idx < queuedFutures.size(); idx++) {
K key = keys.get(idx);
CompletableFuture<V> future = queuedFutures.get(idx);
future.completeExceptionally(ex);
// clear any cached view of this key because they all failed
dataLoader.clear(key);
}
return emptyList();
});
}
private void assertResultSize(List<K> keys, List<V> values) {
assertState(keys.size() == values.size(), () -> "The size of the promised values MUST be the same size as the key list");
}
private void possiblyClearCacheEntriesOnExceptions(List<K> keys) {
if (keys.isEmpty()) {
return;
}
// by default we don't clear the cached view of this entry to avoid
// frequently loading the same error. This works for short lived request caches
// but might work against long lived caches. Hence we have an option that allows
// it to be cleared
if (!loaderOptions.cachingExceptionsEnabled()) {
keys.forEach(dataLoader::clear);
}
}
@GuardedBy("dataLoader")
private CompletableFuture<V> loadFromCache(K key, Object loadContext, boolean batchingEnabled) {
final Object cacheKey = loadContext == null ? getCacheKey(key) : getCacheKeyWithContext(key, loadContext);
if (futureCache.containsKey(cacheKey)) {
// We already have a promise for this key, no need to check value cache or queue up load
stats.incrementCacheHitCount();
return futureCache.get(cacheKey);
}
CompletableFuture<V> loadCallFuture = queueOrInvokeLoader(key, loadContext, batchingEnabled, true);
futureCache.set(cacheKey, loadCallFuture);
return loadCallFuture;
}
@GuardedBy("dataLoader")
private CompletableFuture<V> queueOrInvokeLoader(K key, Object loadContext, boolean batchingEnabled, boolean cachingEnabled) {
if (batchingEnabled) {
CompletableFuture<V> loadCallFuture = new CompletableFuture<>();
loaderQueue.add(new LoaderQueueEntry<>(key, loadCallFuture, loadContext));
return loadCallFuture;
} else {
stats.incrementBatchLoadCountBy(1);
// immediate execution of batch function
return invokeLoaderImmediately(key, loadContext, cachingEnabled);
}
}
CompletableFuture<V> invokeLoaderImmediately(K key, Object keyContext, boolean cachingEnabled) {
List<K> keys = singletonList(key);
List<Object> keyContexts = singletonList(keyContext);
return invokeLoader(keys, keyContexts, cachingEnabled)
.thenApply(list -> list.get(0))
.toCompletableFuture();
}
CompletableFuture<List<V>> invokeLoader(List<K> keys, List<Object> keyContexts, boolean cachingEnabled) {
if (!cachingEnabled) {
return invokeLoader(keys, keyContexts);
}
CompletableFuture<List<Try<V>>> cacheCallCF = getFromValueCache(keys);
return cacheCallCF.thenCompose(cachedValues -> {
// the following is NOT a Map because keys in data loader can repeat (by design)
// and hence "a","b","c","b" is a valid set of keys
List<Try<V>> valuesInKeyOrder = new ArrayList<>();
List<Integer> missedKeyIndexes = new ArrayList<>();
List<K> missedKeys = new ArrayList<>();
List<Object> missedKeyContexts = new ArrayList<>();
// if they return a ValueCachingNotSupported exception then we insert this special marker value, and it
// means it's a total miss, we need to get all these keys via the batch loader
if (cachedValues == NOT_SUPPORTED_LIST) {
for (int i = 0; i < keys.size(); i++) {
valuesInKeyOrder.add(ALWAYS_FAILED);
missedKeyIndexes.add(i);
missedKeys.add(keys.get(i));
missedKeyContexts.add(keyContexts.get(i));
}
} else {
assertState(keys.size() == cachedValues.size(), () -> "The size of the cached values MUST be the same size as the key list");
for (int i = 0; i < keys.size(); i++) {
Try<V> cacheGet = cachedValues.get(i);
valuesInKeyOrder.add(cacheGet);
if (cacheGet.isFailure()) {
missedKeyIndexes.add(i);
missedKeys.add(keys.get(i));
missedKeyContexts.add(keyContexts.get(i));
}
}
}
if (missedKeys.isEmpty()) {
//
// everything was cached
//
List<V> assembledValues = valuesInKeyOrder.stream().map(Try::get).collect(toList());
return completedFuture(assembledValues);
} else {
//
// we missed some of the keys from cache, so send them to the batch loader
// and then fill in their values
//
CompletableFuture<List<V>> batchLoad = invokeLoader(missedKeys, missedKeyContexts);
return batchLoad.thenCompose(missedValues -> {
assertResultSize(missedKeys, missedValues);
for (int i = 0; i < missedValues.size(); i++) {
V v = missedValues.get(i);
Integer listIndex = missedKeyIndexes.get(i);
valuesInKeyOrder.set(listIndex, Try.succeeded(v));
}
List<V> assembledValues = valuesInKeyOrder.stream().map(Try::get).collect(toList());
//
// fire off a call to the ValueCache to allow it to set values into the
// cache now that we have them
return setToValueCache(assembledValues, missedKeys, missedValues);
});
}
});
}
CompletableFuture<List<V>> invokeLoader(List<K> keys, List<Object> keyContexts) {
CompletableFuture<List<V>> batchLoad;
try {
Object context = loaderOptions.getBatchLoaderContextProvider().getContext();
BatchLoaderEnvironment environment = BatchLoaderEnvironment.newBatchLoaderEnvironment()
.context(context).keyContexts(keys, keyContexts).build();
if (isMapLoader()) {
batchLoad = invokeMapBatchLoader(keys, environment);
} else {
batchLoad = invokeListBatchLoader(keys, environment);
}
} catch (Exception e) {
batchLoad = CompletableFutureKit.failedFuture(e);
}
return batchLoad;
}
@SuppressWarnings("unchecked")
private CompletableFuture<List<V>> invokeListBatchLoader(List<K> keys, BatchLoaderEnvironment environment) {
CompletionStage<List<V>> loadResult;
if (batchLoadFunction instanceof BatchLoaderWithContext) {
loadResult = ((BatchLoaderWithContext<K, V>) batchLoadFunction).load(keys, environment);
} else {
loadResult = ((BatchLoader<K, V>) batchLoadFunction).load(keys);
}
return nonNull(loadResult, () -> "Your batch loader function MUST return a non null CompletionStage").toCompletableFuture();
}
/*
* Turns a map of results that MAY be smaller than the key list back into a list by mapping null
* to missing elements.
*/
@SuppressWarnings("unchecked")
private CompletableFuture<List<V>> invokeMapBatchLoader(List<K> keys, BatchLoaderEnvironment environment) {
CompletionStage<Map<K, V>> loadResult;
Set<K> setOfKeys = new LinkedHashSet<>(keys);
if (batchLoadFunction instanceof MappedBatchLoaderWithContext) {
loadResult = ((MappedBatchLoaderWithContext<K, V>) batchLoadFunction).load(setOfKeys, environment);
} else {
loadResult = ((MappedBatchLoader<K, V>) batchLoadFunction).load(setOfKeys);
}
CompletableFuture<Map<K, V>> mapBatchLoad = nonNull(loadResult, () -> "Your batch loader function MUST return a non null CompletionStage").toCompletableFuture();
return mapBatchLoad.thenApply(map -> {
List<V> values = new ArrayList<>();
for (K key : keys) {
V value = map.get(key);
values.add(value);
}
return values;
});
}
private boolean isMapLoader() {
return batchLoadFunction instanceof MappedBatchLoader || batchLoadFunction instanceof MappedBatchLoaderWithContext;
}
int dispatchDepth() {
synchronized (dataLoader) {
return loaderQueue.size();
}
}
private final List<Try<V>> NOT_SUPPORTED_LIST = emptyList();
private final CompletableFuture<List<Try<V>>> NOT_SUPPORTED = CompletableFuture.completedFuture(NOT_SUPPORTED_LIST);
private final Try<V> ALWAYS_FAILED = Try.alwaysFailed();
private CompletableFuture<List<Try<V>>> getFromValueCache(List<K> keys) {
try {
return nonNull(valueCache.getValues(keys), () -> "Your ValueCache.getValues function MUST return a non null CompletableFuture");
} catch (ValueCache.ValueCachingNotSupported ignored) {
// use of a final field prevents CF object allocation for this special purpose
return NOT_SUPPORTED;
} catch (RuntimeException e) {
return CompletableFutureKit.failedFuture(e);
}
}
private CompletableFuture<List<V>> setToValueCache(List<V> assembledValues, List<K> missedKeys, List<V> missedValues) {
try {
boolean completeValueAfterCacheSet = loaderOptions.getValueCacheOptions().isCompleteValueAfterCacheSet();
if (completeValueAfterCacheSet) {
return nonNull(valueCache
.setValues(missedKeys, missedValues), () -> "Your ValueCache.setValues function MUST return a non null CompletableFuture")
// we don't trust the set cache to give us the values back - we have them - lets use them
// if the cache set fails - then they won't be in cache and maybe next time they will
.handle((ignored, setExIgnored) -> assembledValues);
} else {
// no one is waiting for the set to happen here so if its truly async
// it will happen eventually but no result will be dependent on it
valueCache.setValues(missedKeys, missedValues);
}
} catch (ValueCache.ValueCachingNotSupported ignored) {
// ok no set caching is fine if they say so
} catch (RuntimeException ignored) {
// if we can't set values back into the cache - so be it - this must be a faulty
// ValueCache implementation
}
return CompletableFuture.completedFuture(assembledValues);
}
}