forked from datahub-project/datahub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBaseLocalDAO.java
764 lines (670 loc) · 31 KB
/
BaseLocalDAO.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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
package com.linkedin.metadata.dao;
import com.linkedin.common.AuditStamp;
import com.linkedin.common.urn.Urn;
import com.linkedin.data.schema.validation.CoercionMode;
import com.linkedin.data.schema.validation.RequiredMode;
import com.linkedin.data.schema.validation.UnrecognizedFieldMode;
import com.linkedin.data.schema.validation.ValidateDataAgainstSchema;
import com.linkedin.data.schema.validation.ValidationOptions;
import com.linkedin.data.schema.validation.ValidationResult;
import com.linkedin.data.template.RecordTemplate;
import com.linkedin.data.template.UnionTemplate;
import com.linkedin.metadata.backfill.BackfillMode;
import com.linkedin.metadata.dao.equality.DefaultEqualityTester;
import com.linkedin.metadata.dao.equality.EqualityTester;
import com.linkedin.metadata.dao.exception.ModelValidationException;
import com.linkedin.metadata.dao.producer.BaseMetadataEventProducer;
import com.linkedin.metadata.dao.retention.IndefiniteRetention;
import com.linkedin.metadata.dao.retention.Retention;
import com.linkedin.metadata.dao.retention.TimeBasedRetention;
import com.linkedin.metadata.dao.retention.VersionBasedRetention;
import com.linkedin.metadata.dao.storage.LocalDAOStorageConfig;
import com.linkedin.metadata.query.ExtraInfo;
import com.linkedin.metadata.query.IndexCriterion;
import com.linkedin.metadata.query.IndexCriterionArray;
import com.linkedin.metadata.query.IndexFilter;
import java.time.Clock;
import java.util.Collections;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import lombok.Value;
/**
* A base class for all Local DAOs.
*
* <p>Local DAO is a standardized interface to store and retrieve aspects from a document store.
*
* @param <ASPECT_UNION> must be a valid aspect union type defined in com.linkedin.metadata.aspect
* @param <URN> must be the entity URN type in {@code ASPECT_UNION}
*/
public abstract class BaseLocalDAO<ASPECT_UNION extends UnionTemplate, URN extends Urn>
extends BaseReadDAO<ASPECT_UNION, URN> {
@Value
static class AspectEntry<ASPECT extends RecordTemplate> {
ASPECT aspect;
ExtraInfo extraInfo;
}
@Value
static class AddResult<ASPECT extends RecordTemplate> {
ASPECT oldValue;
ASPECT newValue;
}
private static final String DEFAULT_ID_NAMESPACE = "global";
private static final IndefiniteRetention INDEFINITE_RETENTION = new IndefiniteRetention();
private static final int DEFAULT_MAX_TRANSACTION_RETRY = 3;
protected final BaseMetadataEventProducer _producer;
protected final LocalDAOStorageConfig _storageConfig;
// Maps an aspect class to the corresponding retention policy
private final Map<Class<? extends RecordTemplate>, Retention> _aspectRetentionMap = new HashMap<>();
// Maps as aspect class to a list of post-update hooks
private final Map<Class<? extends RecordTemplate>, List<BiConsumer<Urn, RecordTemplate>>> _aspectPostUpdateHooksMap =
new HashMap<>();
// Maps an aspect class to the corresponding equality tester
private final Map<Class<? extends RecordTemplate>, EqualityTester<? extends RecordTemplate>>
_aspectEqualityTesterMap = new HashMap<>();
private boolean _modelValidationOnWrite = true;
// Always emit MAE on every update regardless if there's any actual change in value
private boolean _alwaysEmitAuditEvent = false;
// Opt in to emit Aspect Specific MAE, at initial migration stage, always emit the event
private boolean _emitAspectSpecificAuditEvent = false;
// Flag for enabling reads and writes to local secondary index
private boolean _enableLocalSecondaryIndex = false;
// Flag for backfilling local secondary index
private boolean _backfillLocalSecondaryIndex = false;
private Clock _clock = Clock.systemUTC();
/**
* Constructor for BaseLocalDAO.
*
* @param aspectUnionClass containing union of all supported aspects. Must be a valid aspect union defined in
* com.linkedin.metadata.aspect
* @param producer {@link BaseMetadataEventProducer} for the metadata event producer
*/
public BaseLocalDAO(@Nonnull Class<ASPECT_UNION> aspectUnionClass, @Nonnull BaseMetadataEventProducer producer) {
super(aspectUnionClass);
_producer = producer;
_storageConfig = LocalDAOStorageConfig.builder().build();
}
/**
* Constructor for BaseLocalDAO.
*
* @param producer {@link BaseMetadataEventProducer} for the metadata event producer
* @param storageConfig {@link LocalDAOStorageConfig} containing storage config of full list of supported aspects
*/
public BaseLocalDAO(@Nonnull BaseMetadataEventProducer producer, @Nonnull LocalDAOStorageConfig storageConfig) {
super(storageConfig.getAspectStorageConfigMap().keySet());
_producer = producer;
_storageConfig = storageConfig;
}
/**
* For tests to override the internal clock.
*/
public void setClock(@Nonnull Clock clock) {
_clock = clock;
}
/**
* Sets {@link Retention} for a specific aspect type.
*/
public <ASPECT extends RecordTemplate> void setRetention(@Nonnull Class<ASPECT> aspectClass,
@Nonnull Retention retention) {
checkValidAspect(aspectClass);
_aspectRetentionMap.put(aspectClass, retention);
}
/**
* Gets the {@link Retention} for an aspect type, or {@link IndefiniteRetention} if none is registered.
*/
@Nonnull
public <ASPECT extends RecordTemplate> Retention getRetention(@Nonnull Class<ASPECT> aspectClass) {
checkValidAspect(aspectClass);
return _aspectRetentionMap.getOrDefault(aspectClass, INDEFINITE_RETENTION);
}
/**
* Registers a post-update hook for a specific aspect.
*
* <p>The hook will be invoked with the latest value of an aspect after it's updated. There's no guarantee on the
* order of invocation when multiple hooks are added for a single aspect. Adding the same hook again will result in
* {@link IllegalArgumentException} thrown. Hooks are invoked in the order they're registered.
*/
public <URN extends Urn, ASPECT extends RecordTemplate> void addPostUpdateHook(@Nonnull Class<ASPECT> aspectClass,
@Nonnull BiConsumer<URN, ASPECT> postUpdateHook) {
checkValidAspect(aspectClass);
// TODO: Also validate Urn once we convert all aspect models to PDL with proper annotation
final List<BiConsumer<Urn, RecordTemplate>> hooks =
_aspectPostUpdateHooksMap.getOrDefault(aspectClass, new LinkedList<>());
if (hooks.contains(postUpdateHook)) {
throw new IllegalArgumentException("Adding an already-registered hook");
}
hooks.add((BiConsumer<Urn, RecordTemplate>) postUpdateHook);
_aspectPostUpdateHooksMap.put(aspectClass, hooks);
}
/**
* Sets the {@link EqualityTester} for a specific aspect type.
*/
public <ASPECT extends RecordTemplate> void setEqualityTester(@Nonnull Class<ASPECT> aspectClass,
@Nonnull EqualityTester<ASPECT> tester) {
checkValidAspect(aspectClass);
_aspectEqualityTesterMap.put(aspectClass, tester);
}
/**
* Gets the {@link EqualityTester} for an aspect, or {@link DefaultEqualityTester} if none is registered.
*/
@Nonnull
public <ASPECT extends RecordTemplate> EqualityTester<ASPECT> getEqualityTester(@Nonnull Class<ASPECT> aspectClass) {
checkValidAspect(aspectClass);
return (EqualityTester<ASPECT>) _aspectEqualityTesterMap.computeIfAbsent(aspectClass,
key -> new DefaultEqualityTester<ASPECT>());
}
/**
* Enables or disables model validation before persisting.
*/
public void enableModelValidationOnWrite(boolean enabled) {
_modelValidationOnWrite = enabled;
}
/**
* Sets if MAE should be always emitted after each update even if there's no actual value change.
*/
public void setAlwaysEmitAuditEvent(boolean alwaysEmitAuditEvent) {
_alwaysEmitAuditEvent = alwaysEmitAuditEvent;
}
/**
* Sets if aspect specific MAE should be always emitted after each update even if there's no actual value change.
*/
public void setEmitAspectSpecificAuditEvent(boolean emitAspectSpecificAuditEvent) {
_emitAspectSpecificAuditEvent = emitAspectSpecificAuditEvent;
}
/**
* Sets if writes to local secondary index enabled.
*
* @deprecated Use {@link #enableLocalSecondaryIndex(boolean)} instead
*/
public void setWriteToLocalSecondaryIndex(boolean writeToLocalSecondaryIndex) {
_enableLocalSecondaryIndex = writeToLocalSecondaryIndex;
}
/**
* Enables reads from and writes to local secondary index.
*/
public void enableLocalSecondaryIndex(boolean enableLocalSecondaryIndex) {
_enableLocalSecondaryIndex = enableLocalSecondaryIndex;
}
/**
* Gets if reads and writes to local secondary index are enabled.
*/
public boolean isLocalSecondaryIndexEnabled() {
return _enableLocalSecondaryIndex;
}
/**
* Sets if local secondary index backfilling is enabled.
*/
public void setBackfillLocalSecondaryIndex(boolean backfillLocalSecondaryIndex) {
_backfillLocalSecondaryIndex = backfillLocalSecondaryIndex;
}
/**
* Adds a new version of aspect for an entity.
*
* <p>The new aspect will have an automatically assigned version number, which is guaranteed to be positive and
* monotonically increasing. Older versions of aspect will be purged automatically based on the retention setting. A
* MetadataAuditEvent is also emitted if there's an actual update.
*
* @param urn the URN for the entity the aspect is attached to
* @param auditStamp the audit stamp for the operation
* @param updateLambda a lambda expression that takes the previous version of aspect and returns the new version
* @return {@link RecordTemplate} of the new value of aspect
*/
@Nonnull
public <ASPECT extends RecordTemplate> ASPECT add(@Nonnull URN urn, @Nonnull Class<ASPECT> aspectClass,
@Nonnull Function<Optional<ASPECT>, ASPECT> updateLambda, @Nonnull AuditStamp auditStamp,
int maxTransactionRetry) {
checkValidAspect(aspectClass);
final EqualityTester<ASPECT> equalityTester = getEqualityTester(aspectClass);
final AddResult<ASPECT> result = runInTransactionWithRetry(() -> {
// 1. Compute newValue based on oldValue
AspectEntry<ASPECT> latest = getLatest(urn, aspectClass);
final ASPECT oldValue = latest == null ? null : latest.getAspect();
final ASPECT newValue = updateLambda.apply(Optional.ofNullable(oldValue));
checkValidAspect(newValue.getClass());
if (_modelValidationOnWrite) {
validateAgainstSchema(newValue);
}
// 2. Skip saving if there's no actual change
if (oldValue != null && equalityTester.equals(oldValue, newValue)) {
return new AddResult<>(oldValue, oldValue);
}
// 3. Save the newValue as the latest version
long largestVersion =
saveLatest(urn, aspectClass, oldValue, latest == null ? null : latest.getExtraInfo().getAudit(), newValue,
auditStamp);
// 4. Apply retention policy
applyRetention(urn, aspectClass, getRetention(aspectClass), largestVersion);
// 5. Save to local secondary index
if (_enableLocalSecondaryIndex) {
updateLocalIndex(urn, newValue, largestVersion);
}
return new AddResult<>(oldValue, newValue);
}, maxTransactionRetry);
final ASPECT oldValue = result.getOldValue();
final ASPECT newValue = result.getNewValue();
// 6. Produce MAE after a successful update
if (_alwaysEmitAuditEvent || oldValue != newValue) {
_producer.produceMetadataAuditEvent(urn, oldValue, newValue);
}
// TODO: Replace step 6 with step 6.1 with diff option after pipeline is fully migrated to aspect specific events.
// 6.1. Produce aspect specific MAE after a successful update
if (_emitAspectSpecificAuditEvent) {
_producer.produceAspectSpecificMetadataAuditEvent(urn, oldValue, newValue);
}
// 7. Invoke post-update hooks if there's any
if (_aspectPostUpdateHooksMap.containsKey(aspectClass)) {
_aspectPostUpdateHooksMap.get(aspectClass).forEach(hook -> hook.accept(urn, newValue));
}
return newValue;
}
/**
* Similar to {@link #add(Urn, Class, Function, AuditStamp, int)} but uses the default maximum transaction retry.
*/
@Nonnull
public <ASPECT extends RecordTemplate> ASPECT add(@Nonnull URN urn, @Nonnull Class<ASPECT> aspectClass,
@Nonnull Function<Optional<ASPECT>, ASPECT> updateLambda, @Nonnull AuditStamp auditStamp) {
return add(urn, aspectClass, updateLambda, auditStamp, DEFAULT_MAX_TRANSACTION_RETRY);
}
/**
* Similar to {@link #add(Urn, Class, Function, AuditStamp)} but takes the new value directly.
*/
@Nonnull
public <ASPECT extends RecordTemplate> ASPECT add(@Nonnull URN urn, @Nonnull ASPECT newValue,
@Nonnull AuditStamp auditStamp) {
return add(urn, (Class<ASPECT>) newValue.getClass(), ignored -> newValue, auditStamp);
}
private <ASPECT extends RecordTemplate> void applyRetention(@Nonnull URN urn, @Nonnull Class<ASPECT> aspectClass,
@Nonnull Retention retention, long largestVersion) {
if (retention instanceof IndefiniteRetention) {
return;
}
if (retention instanceof VersionBasedRetention) {
applyVersionBasedRetention(aspectClass, urn, (VersionBasedRetention) retention, largestVersion);
return;
}
if (retention instanceof TimeBasedRetention) {
applyTimeBasedRetention(aspectClass, urn, (TimeBasedRetention) retention, _clock.millis());
return;
}
}
/**
* Saves the latest aspect.
*
* @param urn the URN for the entity the aspect is attached to
* @param aspectClass the aspectClass of the aspect being saved
* @param oldEntry {@link RecordTemplate} of the previous latest value of aspect, null if new value is the first version
* @param oldAuditStamp the audit stamp of the previous latest aspect, null if new value is the first version
* @param newEntry {@link RecordTemplate} of the new latest value of aspect
* @param newAuditStamp the audit stamp for the operation
* @return the largest version
*/
protected abstract <ASPECT extends RecordTemplate> long saveLatest(@Nonnull URN urn,
@Nonnull Class<ASPECT> aspectClass, @Nullable ASPECT oldEntry, @Nullable AuditStamp oldAuditStamp,
@Nonnull ASPECT newEntry, @Nonnull AuditStamp newAuditStamp);
/**
* Saves the new value of an aspect to local secondary index.
*
* @param urn the URN for the entity the aspect is attached to
* @param newValue {@link RecordTemplate} of the new value of aspect
* @param version version of the aspect
*/
protected abstract <ASPECT extends RecordTemplate> void updateLocalIndex(@Nonnull URN urn,
@Nullable ASPECT newValue, long version);
/**
* Returns list of urns from local secondary index that satisfy the given filter conditions.
*
* <p>Results are ordered lexicographically by the string representation of the URN.
*
* @param indexFilter {@link IndexFilter} containing filter conditions to be applied
* @param lastUrn last urn of the previous fetched page. For the first page, this should be set as NULL
* @param pageSize maximum number of distinct urns to return
* @return {@link ListResult} of urns from local secondary index that satisfy the given filter conditions
*/
@Nonnull
public abstract ListResult<URN> listUrns(@Nonnull IndexFilter indexFilter, @Nullable URN lastUrn, int pageSize);
/**
* Similar to {@link #listUrns(IndexFilter, URN, int)}. This is to get all urns with type URN.
*/
@Nonnull
public ListResult<URN> listUrns(@Nonnull Class<URN> urnClazz, @Nullable URN lastUrn, int pageSize) {
final IndexFilter indexFilter = new IndexFilter()
.setCriteria(new IndexCriterionArray(new IndexCriterion().setAspect(urnClazz.getCanonicalName())));
return listUrns(indexFilter, lastUrn, pageSize);
}
/**
* Retrieves {@link ListResult} of {@link UrnAspectEntry} containing latest version of aspects along with the urn for the list of urns
* returned from local secondary index that satisfy given filter conditions. The returned list is ordered lexicographically by the string
* representation of the URN.
*
* @param aspectClasses aspect classes whose latest versions need to be retrieved
* @param indexFilter {@link IndexFilter} containing filter conditions to be applied
* @param lastUrn last urn of the previous fetched page. For the first page, this should be set as NULL
* @param pageSize maximum number of distinct urns whose aspects need to be retrieved
* @return {@link ListResult} containing ordered list of latest versions of aspects along with urns returned from local secondary index
* satisfying given filter conditions
*/
@Nonnull
public ListResult<UrnAspectEntry<URN>> getAspects(@Nonnull Set<Class<? extends RecordTemplate>> aspectClasses,
@Nonnull IndexFilter indexFilter, @Nullable URN lastUrn, int pageSize) {
final ListResult<URN> urns = listUrns(indexFilter, lastUrn, pageSize);
final Map<URN, Map<Class<? extends RecordTemplate>, Optional<? extends RecordTemplate>>> urnAspectMap =
get(aspectClasses, new HashSet<>(urns.getValues()));
final Map<URN, List<RecordTemplate>> urnListAspectMap = new LinkedHashMap<>();
for (URN urn : urns.getValues()) {
final Map<Class<? extends RecordTemplate>, Optional<? extends RecordTemplate>> aspectMap = urnAspectMap.get(urn);
urnListAspectMap.compute(urn, (k, v) -> {
if (v == null) {
v = new ArrayList<>();
}
return v;
});
for (Optional<? extends RecordTemplate> aspect : aspectMap.values()) {
aspect.ifPresent(record -> urnListAspectMap.get(urn).add(record));
}
}
final List<UrnAspectEntry<URN>> urnAspectEntries = urnListAspectMap.entrySet()
.stream()
.map(entry -> new UrnAspectEntry<>(entry.getKey(), entry.getValue()))
.collect(Collectors.toList());
return ListResult.<UrnAspectEntry<URN>>builder().values(urnAspectEntries)
.havingMore(urns.isHavingMore())
.nextStart(urns.getNextStart())
.pageSize(urns.getPageSize())
.totalCount(urns.getTotalCount())
.totalPageCount(urns.getTotalPageCount())
.build();
}
/**
* Runs the given lambda expression in a transaction with a limited number of retries.
*
* @param block the lambda expression to run
* @param maxTransactionRetry maximum number of transaction retries before throwing an exception
* @param <T> type for the result object
* @return the result object from a successfully committed transaction
*/
@Nonnull
protected abstract <T> T runInTransactionWithRetry(@Nonnull Supplier<T> block, int maxTransactionRetry);
/**
* Gets the latest version of a specific aspect type for an entity.
*
* @param urn {@link Urn} for the entity
* @param aspectClass the type of aspect to get
* @return the latest version for the aspect type, or null if there's none
*/
@Nullable
protected abstract <ASPECT extends RecordTemplate> AspectEntry<ASPECT> getLatest(@Nonnull URN urn,
@Nonnull Class<ASPECT> aspectClass);
/**
* Gets the next version to use for an entity's specific aspect type.
*
* @param urn {@link Urn} for the entity
* @param aspectClass the type of aspect to get
* @return the next version number to use, or {@link #LATEST_VERSION} if there's no previous versions
*/
protected abstract <ASPECT extends RecordTemplate> long getNextVersion(@Nonnull URN urn,
@Nonnull Class<ASPECT> aspectClass);
/**
* Saves an aspect for an entity with specific version & {@link AuditStamp}.
*
* @param urn {@link Urn} for the entity
* @param value the aspect to save
* @param auditStamp the {@link AuditStamp} for the aspect
* @param version the version for the aspect
* @param insert use insert, instead of update, operation to save
*/
protected abstract void save(@Nonnull URN urn, @Nonnull RecordTemplate value, @Nonnull AuditStamp auditStamp,
long version, boolean insert);
/**
* Applies version-based retention against a specific aspect type for an entity.
*
* @param aspectClass the type of aspect to apply retention to
* @param urn {@link Urn} for the entity
* @param retention the retention configuration
* @param largestVersion the largest version number for the aspect type
*/
protected abstract <ASPECT extends RecordTemplate> void applyVersionBasedRetention(@Nonnull Class<ASPECT> aspectClass,
@Nonnull URN urn, @Nonnull VersionBasedRetention retention, long largestVersion);
/**
* Applies time-based retention against a specific aspect type for an entity.
*
* @param aspectClass the type of aspect to apply retention to
* @param urn {@link Urn} for the entity
* @param retention the retention configuration
* @param currentTime the current timestamp
*/
protected abstract <ASPECT extends RecordTemplate> void applyTimeBasedRetention(@Nonnull Class<ASPECT> aspectClass,
@Nonnull URN urn, @Nonnull TimeBasedRetention retention, long currentTime);
/**
* Emits backfill MAE for the latest version of an aspect and also backfills SCSI (if it exists and is enabled).
*
* @param aspectClass the type of aspect to backfill
* @param urn urn for the entity
* @param <ASPECT> must be a supported aspect type in {@code ASPECT_UNION}.
* @return backfilled aspect
* @deprecated Use {@link #backfill(Set, Set)} instead
*/
@Nonnull
public <ASPECT extends RecordTemplate> Optional<ASPECT> backfill(@Nonnull Class<ASPECT> aspectClass, @Nonnull URN urn) {
return backfill(BackfillMode.BACKFILL_ALL, aspectClass, urn);
}
/**
* Similar to {@link #backfill(Class, URN)} but does a scoped backfill.
*
* @param mode backfill mode to scope the backfill process
*/
@Nonnull
private <ASPECT extends RecordTemplate> Optional<ASPECT> backfill(@Nonnull BackfillMode mode,
@Nonnull Class<ASPECT> aspectClass, @Nonnull URN urn) {
checkValidAspect(aspectClass);
Optional<ASPECT> aspect = get(aspectClass, urn, LATEST_VERSION);
aspect.ifPresent(value -> backfill(mode, value, urn));
return aspect;
}
/**
* Emits backfill MAE for the latest version of a set of aspects for a set of urns and also backfills SCSI (if it exists and is enabled).
*
* @param aspectClasses set of aspects to backfill
* @param urns set of urns to backfill
* @return map of urn to their backfilled aspect values
*/
@Nonnull
public Map<URN, Map<Class<? extends RecordTemplate>, Optional<? extends RecordTemplate>>> backfill(
@Nonnull Set<Class<? extends RecordTemplate>> aspectClasses, @Nonnull Set<URN> urns) {
return backfill(BackfillMode.BACKFILL_ALL, aspectClasses, urns);
}
/**
* Similar to {@link #backfill(Set, Set)} but does a scoped backfill.
*
* @param mode backfill mode to scope the backfill process
*/
@Nonnull
private Map<URN, Map<Class<? extends RecordTemplate>, Optional<? extends RecordTemplate>>> backfill(
@Nonnull BackfillMode mode, @Nonnull Set<Class<? extends RecordTemplate>> aspectClasses, @Nonnull Set<URN> urns) {
checkValidAspects(aspectClasses);
final Map<URN, Map<Class<? extends RecordTemplate>, Optional<? extends RecordTemplate>>> urnToAspects = get(aspectClasses, urns);
urnToAspects.forEach((urn, aspects) -> {
aspects.forEach((aspectClass, aspect) -> aspect.ifPresent(value -> backfill(mode, value, urn)));
});
return urnToAspects;
}
/**
* Emits backfill MAE for the latest version of a set of aspects for a set of urns
* and also backfills SCSI (if it exists and is enabled) depending on the backfill mode.
*
* @param mode backfill mode to scope the backfill process
* @param aspectClasses set of aspects to backfill
* @param urnClazz the type of urn to backfill - needed to list urns using SCSI
* @param lastUrn last urn of the previous backfilled page - needed to list urns using SCSI
* @param pageSize the number of entities to backfill
* @return map of urn to their backfilled aspect values
*/
@Nonnull
public Map<URN, Map<Class<? extends RecordTemplate>, Optional<? extends RecordTemplate>>> backfill(
@Nonnull BackfillMode mode, @Nonnull Set<Class<? extends RecordTemplate>> aspectClasses,
@Nonnull Class<URN> urnClazz, @Nullable URN lastUrn, int pageSize) {
final ListResult<URN> urnList = listUrns(urnClazz, lastUrn, pageSize);
return backfill(mode, aspectClasses, new HashSet(urnList.getValues()));
}
/**
* Emits backfill MAE for an aspect of an entity and/or backfills SCSI depending on the backfill mode.
*
* @param mode backfill mode
* @param aspect aspect to backfill
* @param urn {@link Urn} for the entity
* @param <ASPECT> must be a supported aspect type in {@code ASPECT_UNION}.
*/
private <ASPECT extends RecordTemplate> void backfill(@Nonnull BackfillMode mode, @Nonnull ASPECT aspect, @Nonnull URN urn) {
if (_enableLocalSecondaryIndex && (mode == BackfillMode.SCSI_ONLY || mode == BackfillMode.BACKFILL_ALL)) {
updateLocalIndex(urn, aspect, FIRST_VERSION);
}
if (mode == BackfillMode.MAE_ONLY || mode == BackfillMode.BACKFILL_ALL) {
_producer.produceMetadataAuditEvent(urn, aspect, aspect);
}
}
/**
* Paginates over all available versions of an aspect for an entity.
*
* @param aspectClass the type of the aspect to query
* @param urn {@link Urn} for the entity
* @param start the starting offset of the page
* @param pageSize the size of the page
* @param <ASPECT> must be a supported aspect type in {@code ASPECT_UNION}.
* @return a {@link ListResult} containing a list of version numbers and other pagination information
*/
@Nonnull
public abstract <ASPECT extends RecordTemplate> ListResult<Long> listVersions(@Nonnull Class<ASPECT> aspectClass,
@Nonnull URN urn, int start, int pageSize);
/**
* Paginates over all URNs for entities that have a specific aspect.
*
* @param aspectClass the type of the aspect to query
* @param start the starting offset of the page
* @param pageSize the size of the page
* @param <ASPECT> must be a supported aspect type in {@code ASPECT_UNION}.
* @return a {@link ListResult} containing a list of URN and other pagination information
*/
@Nonnull
public abstract <ASPECT extends RecordTemplate> ListResult<URN> listUrns(@Nonnull Class<ASPECT> aspectClass,
int start, int pageSize);
/**
* Paginates over all versions of an aspect for a specific Urn.
*
* @param aspectClass the type of the aspect to query
* @param urn {@link Urn} for the entity
* @param start the starting offset of the page
* @param pageSize the size of the page
* @param <ASPECT> must be a supported aspect type in {@code ASPECT_UNION}.
* @return a {@link ListResult} containing a list of aspects and other pagination information
*/
@Nonnull
public abstract <ASPECT extends RecordTemplate> ListResult<ASPECT> list(@Nonnull Class<ASPECT> aspectClass,
@Nonnull URN urn, int start, int pageSize);
/**
* Paginates over a specific version of a specific aspect for all Urns.
*
* @param aspectClass the type of the aspect to query
* @param version the version of the aspect
* @param start the starting offset of the page
* @param pageSize the size of the page
* @param <ASPECT> must be a supported aspect type in {@code ASPECT_UNION}.
* @return a {@link ListResult} containing a list of aspects and other pagination information
*/
@Nonnull
public abstract <ASPECT extends RecordTemplate> ListResult<ASPECT> list(@Nonnull Class<ASPECT> aspectClass,
long version, int start, int pageSize);
/**
* Paginates over the latest version of a specific aspect for all Urns.
*
* @param aspectClass the type of the aspect to query
* @param start the starting offset of the page
* @param pageSize the size of the page
* @param <ASPECT> must be a supported aspect type in {@code ASPECT_UNION}.
* @return a {@link ListResult} containing a list of aspects and other pagination information
*/
@Nonnull
public abstract <ASPECT extends RecordTemplate> ListResult<ASPECT> list(@Nonnull Class<ASPECT> aspectClass, int start,
int pageSize);
/**
* Batch retrieves metadata aspects along with {@link ExtraInfo} using multiple {@link AspectKey}s.
*
* @param keys set of keys for the metadata to retrieve
* @return a mapping of given keys to the corresponding metadata aspect and {@link ExtraInfo}.
*/
@Nonnull
public abstract Map<AspectKey<URN, ? extends RecordTemplate>, AspectWithExtraInfo<? extends RecordTemplate>> getWithExtraInfo(
@Nonnull Set<AspectKey<URN, ? extends RecordTemplate>> keys);
/**
* Similar to {@link #getWithExtraInfo(Set)} but only using only one {@link AspectKey}.
*/
@Nonnull
public <ASPECT extends RecordTemplate> Optional<AspectWithExtraInfo<ASPECT>> getWithExtraInfo(
@Nonnull AspectKey<URN, ASPECT> key) {
if (getWithExtraInfo(Collections.singleton(key)).containsKey(key)) {
return Optional.of((AspectWithExtraInfo<ASPECT>) getWithExtraInfo(Collections.singleton(key)).get(key));
}
return Optional.empty();
}
/**
* Similar to {@link #getWithExtraInfo(AspectKey)} but with each component of the key broken out as arguments.
*/
@Nonnull
public <ASPECT extends RecordTemplate> Optional<AspectWithExtraInfo<ASPECT>> getWithExtraInfo(
@Nonnull Class<ASPECT> aspectClass, @Nonnull URN urn, long version) {
return getWithExtraInfo(new AspectKey<>(aspectClass, urn, version));
}
/**
* Similar to {@link #getWithExtraInfo(Class, Urn, long)} but always retrieves the latest version.
*/
@Nonnull
public <ASPECT extends RecordTemplate> Optional<AspectWithExtraInfo<ASPECT>> getWithExtraInfo(
@Nonnull Class<ASPECT> aspectClass, @Nonnull URN urn) {
return getWithExtraInfo(aspectClass, urn, LATEST_VERSION);
}
/**
* Generates a new string ID that's guaranteed to be globally unique.
*/
@Nonnull
public String newStringId() {
return UUID.randomUUID().toString();
}
/**
* Generates a new numeric ID that's guaranteed to increase monotonically within the given namespace.
*/
public abstract long newNumericId(@Nonnull String namespace, int maxTransactionRetry);
/**
* Similar to {@link #newNumericId(String, int)} but uses default maximum transaction retry count.
*/
public long newNumericId(@Nonnull String namespace) {
return newNumericId(namespace, DEFAULT_MAX_TRANSACTION_RETRY);
}
/**
* Similar to {@link #newNumericId(String, int)} but uses a single global namespace.
*/
public long newNumericId() {
return newNumericId(DEFAULT_ID_NAMESPACE);
}
/**
* Validates a model against its schema.
*/
protected void validateAgainstSchema(@Nonnull RecordTemplate model) {
ValidationResult result = ValidateDataAgainstSchema.validate(model,
new ValidationOptions(RequiredMode.CAN_BE_ABSENT_IF_HAS_DEFAULT, CoercionMode.NORMAL,
UnrecognizedFieldMode.DISALLOW));
if (!result.isValid()) {
throw new ModelValidationException(result.getMessages().toString());
}
}
}