/
CachingValidationSupport.java
387 lines (330 loc) 路 13.8 KB
/
CachingValidationSupport.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
package org.hl7.fhir.common.hapi.validation.support;
import ca.uhn.fhir.context.BaseRuntimeChildDefinition;
import ca.uhn.fhir.context.support.ConceptValidationOptions;
import ca.uhn.fhir.context.support.IValidationSupport;
import ca.uhn.fhir.context.support.LookupCodeRequest;
import ca.uhn.fhir.context.support.TranslateConceptResults;
import ca.uhn.fhir.context.support.ValidationSupportContext;
import ca.uhn.fhir.context.support.ValueSetExpansionOptions;
import ca.uhn.fhir.sl.cache.Cache;
import ca.uhn.fhir.sl.cache.CacheFactory;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.apache.commons.lang3.time.DateUtils;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.hl7.fhir.instance.model.api.IPrimitiveType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import static org.apache.commons.lang3.ObjectUtils.defaultIfNull;
import static org.apache.commons.lang3.StringUtils.defaultIfBlank;
import static org.apache.commons.lang3.StringUtils.defaultString;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
@SuppressWarnings("unchecked")
public class CachingValidationSupport extends BaseValidationSupportWrapper implements IValidationSupport {
private static final Logger ourLog = LoggerFactory.getLogger(CachingValidationSupport.class);
public static final ValueSetExpansionOptions EMPTY_EXPANSION_OPTIONS = new ValueSetExpansionOptions();
private final Cache<String, Object> myCache;
private final Cache<String, Object> myValidateCodeCache;
private final Cache<TranslateCodeRequest, Object> myTranslateCodeCache;
private final Cache<String, Object> myLookupCodeCache;
private final ThreadPoolExecutor myBackgroundExecutor;
private final Map<Object, Object> myNonExpiringCache;
private final Cache<String, Object> myExpandValueSetCache;
private final boolean myIsEnabledValidationForCodingsLogicalAnd;
/**
* Constructor with default timeouts
*
* @param theWrap The validation support module to wrap
*/
public CachingValidationSupport(IValidationSupport theWrap) {
this(theWrap, CacheTimeouts.defaultValues(), false);
}
public CachingValidationSupport(IValidationSupport theWrap, boolean theIsEnabledValidationForCodingsLogicalAnd) {
this(theWrap, CacheTimeouts.defaultValues(), theIsEnabledValidationForCodingsLogicalAnd);
}
public CachingValidationSupport(IValidationSupport theWrap, CacheTimeouts theCacheTimeouts) {
this(theWrap, theCacheTimeouts, false);
}
/**
* Constructor with configurable timeouts
*
* @param theWrap The validation support module to wrap
* @param theCacheTimeouts The timeouts to use
*/
public CachingValidationSupport(
IValidationSupport theWrap,
CacheTimeouts theCacheTimeouts,
boolean theIsEnabledValidationForCodingsLogicalAnd) {
super(theWrap.getFhirContext(), theWrap);
myExpandValueSetCache = CacheFactory.build(theCacheTimeouts.getExpandValueSetMillis(), 100);
myValidateCodeCache = CacheFactory.build(theCacheTimeouts.getValidateCodeMillis(), 5000);
myLookupCodeCache = CacheFactory.build(theCacheTimeouts.getLookupCodeMillis(), 5000);
myTranslateCodeCache = CacheFactory.build(theCacheTimeouts.getTranslateCodeMillis(), 5000);
myCache = CacheFactory.build(theCacheTimeouts.getMiscMillis(), 5000);
myNonExpiringCache = Collections.synchronizedMap(new HashMap<>());
LinkedBlockingQueue<Runnable> executorQueue = new LinkedBlockingQueue<>(1000);
BasicThreadFactory threadFactory = new BasicThreadFactory.Builder()
.namingPattern("CachingValidationSupport-%d")
.daemon(false)
.priority(Thread.NORM_PRIORITY)
.build();
myBackgroundExecutor = new ThreadPoolExecutor(
1, 1, 0L, TimeUnit.MILLISECONDS, executorQueue, threadFactory, new ThreadPoolExecutor.DiscardPolicy());
myIsEnabledValidationForCodingsLogicalAnd = theIsEnabledValidationForCodingsLogicalAnd;
}
@Override
public List<IBaseResource> fetchAllConformanceResources() {
String key = "fetchAllConformanceResources";
return loadFromCacheWithAsyncRefresh(myCache, key, t -> super.fetchAllConformanceResources());
}
@Override
public <T extends IBaseResource> List<T> fetchAllStructureDefinitions() {
String key = "fetchAllStructureDefinitions";
return loadFromCacheWithAsyncRefresh(myCache, key, t -> super.fetchAllStructureDefinitions());
}
@Nullable
@Override
public <T extends IBaseResource> List<T> fetchAllSearchParameters() {
String key = "fetchAllSearchParameters";
return loadFromCacheWithAsyncRefresh(myCache, key, t -> super.fetchAllSearchParameters());
}
@Override
public <T extends IBaseResource> List<T> fetchAllNonBaseStructureDefinitions() {
String key = "fetchAllNonBaseStructureDefinitions";
return loadFromCacheWithAsyncRefresh(myCache, key, t -> super.fetchAllNonBaseStructureDefinitions());
}
@Override
public IBaseResource fetchCodeSystem(String theSystem) {
return loadFromCache(myCache, "fetchCodeSystem " + theSystem, t -> super.fetchCodeSystem(theSystem));
}
@Override
public IBaseResource fetchValueSet(String theUri) {
return loadFromCache(myCache, "fetchValueSet " + theUri, t -> super.fetchValueSet(theUri));
}
@Override
public IBaseResource fetchStructureDefinition(String theUrl) {
return loadFromCache(
myCache, "fetchStructureDefinition " + theUrl, t -> super.fetchStructureDefinition(theUrl));
}
@Override
public byte[] fetchBinary(String theBinaryKey) {
return loadFromCache(myCache, "fetchBinary " + theBinaryKey, t -> super.fetchBinary(theBinaryKey));
}
@Override
public <T extends IBaseResource> T fetchResource(@Nullable Class<T> theClass, String theUri) {
return loadFromCache(
myCache, "fetchResource " + theClass + " " + theUri, t -> super.fetchResource(theClass, theUri));
}
@Override
public boolean isCodeSystemSupported(ValidationSupportContext theValidationSupportContext, String theSystem) {
String key = "isCodeSystemSupported " + theSystem;
Boolean retVal = loadFromCacheReentrantSafe(
myCache, key, t -> super.isCodeSystemSupported(theValidationSupportContext, theSystem));
assert retVal != null;
return retVal;
}
@Override
public ValueSetExpansionOutcome expandValueSet(
ValidationSupportContext theValidationSupportContext,
ValueSetExpansionOptions theExpansionOptions,
@Nonnull IBaseResource theValueSetToExpand) {
if (!theValueSetToExpand.getIdElement().hasIdPart()) {
return super.expandValueSet(theValidationSupportContext, theExpansionOptions, theValueSetToExpand);
}
ValueSetExpansionOptions expansionOptions = defaultIfNull(theExpansionOptions, EMPTY_EXPANSION_OPTIONS);
String key = "expandValueSet " + theValueSetToExpand.getIdElement().getValue()
+ " " + expansionOptions.isIncludeHierarchy()
+ " " + expansionOptions.getFilter()
+ " " + expansionOptions.getOffset()
+ " " + expansionOptions.getCount();
return loadFromCache(
myExpandValueSetCache,
key,
t -> super.expandValueSet(theValidationSupportContext, theExpansionOptions, theValueSetToExpand));
}
@Override
public CodeValidationResult validateCode(
@Nonnull ValidationSupportContext theValidationSupportContext,
@Nonnull ConceptValidationOptions theOptions,
String theCodeSystem,
String theCode,
String theDisplay,
String theValueSetUrl) {
String key = "validateCode " + theCodeSystem + " " + theCode + " " + defaultString(theDisplay) + " "
+ defaultIfBlank(theValueSetUrl, "NO_VS");
return loadFromCache(
myValidateCodeCache,
key,
t -> super.validateCode(
theValidationSupportContext, theOptions, theCodeSystem, theCode, theDisplay, theValueSetUrl));
}
@Override
public LookupCodeResult lookupCode(
ValidationSupportContext theValidationSupportContext, @Nonnull LookupCodeRequest theLookupCodeRequest) {
String key = "lookupCode " + theLookupCodeRequest.getSystem() + " "
+ theLookupCodeRequest.getCode()
+ " " + defaultIfBlank(theLookupCodeRequest.getDisplayLanguage(), "NO_LANG")
+ " " + theLookupCodeRequest.getPropertyNames().toString();
return loadFromCache(
myLookupCodeCache, key, t -> super.lookupCode(theValidationSupportContext, theLookupCodeRequest));
}
@Override
public IValidationSupport.CodeValidationResult validateCodeInValueSet(
ValidationSupportContext theValidationSupportContext,
ConceptValidationOptions theValidationOptions,
String theCodeSystem,
String theCode,
String theDisplay,
@Nonnull IBaseResource theValueSet) {
BaseRuntimeChildDefinition urlChild =
myCtx.getResourceDefinition(theValueSet).getChildByName("url");
Optional<String> valueSetUrl = urlChild.getAccessor().getValues(theValueSet).stream()
.map(t -> ((IPrimitiveType<?>) t).getValueAsString())
.filter(t -> isNotBlank(t))
.findFirst();
if (valueSetUrl.isPresent()) {
String key =
"validateCodeInValueSet " + theValidationOptions.toString() + " " + defaultString(theCodeSystem)
+ " " + defaultString(theCode) + " " + defaultString(theDisplay) + " " + valueSetUrl.get();
return loadFromCache(
myValidateCodeCache,
key,
t -> super.validateCodeInValueSet(
theValidationSupportContext,
theValidationOptions,
theCodeSystem,
theCode,
theDisplay,
theValueSet));
}
return super.validateCodeInValueSet(
theValidationSupportContext, theValidationOptions, theCodeSystem, theCode, theDisplay, theValueSet);
}
@Override
public TranslateConceptResults translateConcept(TranslateCodeRequest theRequest) {
return loadFromCache(myTranslateCodeCache, theRequest, k -> super.translateConcept(theRequest));
}
@SuppressWarnings("OptionalAssignedToNull")
@Nullable
private <S, T> T loadFromCache(Cache<S, Object> theCache, S theKey, Function<S, T> theLoader) {
ourLog.trace("Fetching from cache: {}", theKey);
Function<S, Optional<T>> loaderWrapper = key -> Optional.ofNullable(theLoader.apply(theKey));
Optional<T> result = (Optional<T>) theCache.get(theKey, loaderWrapper);
assert result != null;
// UGH! Animal sniffer :(
if (!result.isPresent()) {
ourLog.debug(
"Invalidating cache entry for key: {} since the result of the underlying query is empty", theKey);
theCache.invalidate(theKey);
}
return result.orElse(null);
}
/**
* The Caffeine cache uses ConcurrentHashMap which is not reentrant, so if we get unlucky and the hashtable
* needs to grow at the same time as we are in a reentrant cache lookup, the thread will deadlock. Use this
* method in place of loadFromCache in situations where a cache lookup calls another cache lookup within its lambda
*/
@Nullable
private <S, T> T loadFromCacheReentrantSafe(Cache<S, Object> theCache, S theKey, Function<S, T> theLoader) {
ourLog.trace("Reentrant fetch from cache: {}", theKey);
Optional<T> result = (Optional<T>) theCache.getIfPresent(theKey);
if (result != null && result.isPresent()) {
return result.get();
}
T value = theLoader.apply(theKey);
assert value != null;
theCache.put(theKey, Optional.of(value));
return value;
}
private <S, T> T loadFromCacheWithAsyncRefresh(Cache<S, Object> theCache, S theKey, Function<S, T> theLoader) {
T retVal = (T) theCache.getIfPresent(theKey);
if (retVal == null) {
retVal = (T) myNonExpiringCache.get(theKey);
if (retVal != null) {
Runnable loaderTask = () -> {
T loadedItem = loadFromCache(theCache, theKey, theLoader);
myNonExpiringCache.put(theKey, loadedItem);
};
myBackgroundExecutor.execute(loaderTask);
return retVal;
}
}
retVal = loadFromCache(theCache, theKey, theLoader);
myNonExpiringCache.put(theKey, retVal);
return retVal;
}
@Override
public void invalidateCaches() {
myExpandValueSetCache.invalidateAll();
myLookupCodeCache.invalidateAll();
myCache.invalidateAll();
myValidateCodeCache.invalidateAll();
myNonExpiringCache.clear();
}
/**
* @since 5.4.0
*/
public static class CacheTimeouts {
private long myTranslateCodeMillis;
private long myLookupCodeMillis;
private long myValidateCodeMillis;
private long myMiscMillis;
private long myExpandValueSetMillis;
public long getExpandValueSetMillis() {
return myExpandValueSetMillis;
}
public CacheTimeouts setExpandValueSetMillis(long theExpandValueSetMillis) {
myExpandValueSetMillis = theExpandValueSetMillis;
return this;
}
public long getTranslateCodeMillis() {
return myTranslateCodeMillis;
}
public CacheTimeouts setTranslateCodeMillis(long theTranslateCodeMillis) {
myTranslateCodeMillis = theTranslateCodeMillis;
return this;
}
public long getLookupCodeMillis() {
return myLookupCodeMillis;
}
public CacheTimeouts setLookupCodeMillis(long theLookupCodeMillis) {
myLookupCodeMillis = theLookupCodeMillis;
return this;
}
public long getValidateCodeMillis() {
return myValidateCodeMillis;
}
public CacheTimeouts setValidateCodeMillis(long theValidateCodeMillis) {
myValidateCodeMillis = theValidateCodeMillis;
return this;
}
public long getMiscMillis() {
return myMiscMillis;
}
public CacheTimeouts setMiscMillis(long theMiscMillis) {
myMiscMillis = theMiscMillis;
return this;
}
public static CacheTimeouts defaultValues() {
return new CacheTimeouts()
.setLookupCodeMillis(10 * DateUtils.MILLIS_PER_MINUTE)
.setExpandValueSetMillis(1 * DateUtils.MILLIS_PER_MINUTE)
.setTranslateCodeMillis(10 * DateUtils.MILLIS_PER_MINUTE)
.setValidateCodeMillis(10 * DateUtils.MILLIS_PER_MINUTE)
.setMiscMillis(10 * DateUtils.MILLIS_PER_MINUTE);
}
}
public boolean isEnabledValidationForCodingsLogicalAnd() {
return myIsEnabledValidationForCodingsLogicalAnd;
}
}