-
Notifications
You must be signed in to change notification settings - Fork 227
/
RequestScope.java
482 lines (411 loc) · 17.6 KB
/
RequestScope.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
/*
* Copyright 2016, Yahoo Inc.
* Licensed under the Apache License, Version 2.0
* See LICENSE file in project root for terms.
*/
package com.yahoo.elide.core;
import static com.yahoo.elide.annotation.LifeCycleHookBinding.ALL_OPERATIONS;
import com.yahoo.elide.ElideSettings;
import com.yahoo.elide.annotation.LifeCycleHookBinding;
import com.yahoo.elide.core.audit.AuditLogger;
import com.yahoo.elide.core.datastore.DataStoreTransaction;
import com.yahoo.elide.core.dictionary.EntityDictionary;
import com.yahoo.elide.core.exceptions.InvalidAttributeException;
import com.yahoo.elide.core.filter.expression.FilterExpression;
import com.yahoo.elide.core.lifecycle.CRUDEvent;
import com.yahoo.elide.core.lifecycle.LifecycleHookInvoker;
import com.yahoo.elide.core.request.EntityProjection;
import com.yahoo.elide.core.request.route.Route;
import com.yahoo.elide.core.security.ChangeSpec;
import com.yahoo.elide.core.security.PermissionExecutor;
import com.yahoo.elide.core.security.User;
import com.yahoo.elide.core.security.executors.ActivePermissionExecutor;
import com.yahoo.elide.core.security.executors.MultiplexPermissionExecutor;
import com.yahoo.elide.core.type.Type;
import lombok.Getter;
import lombok.Setter;
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.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.function.Function;
/**
* Request scope object for relaying request-related data to various subsystems.
*/
public class RequestScope implements com.yahoo.elide.core.security.RequestScope {
protected Route route;
@Getter private final DataStoreTransaction transaction;
@Getter private final User user;
@Getter protected final EntityDictionary dictionary;
@Getter private final AuditLogger auditLogger;
@Getter private final PermissionExecutor permissionExecutor;
@Getter private final ObjectEntityCache objectEntityCache;
@Getter private final Set<PersistentResource> newPersistentResources;
@Getter private final LinkedHashSet<PersistentResource> dirtyResources;
@Getter private final LinkedHashSet<PersistentResource> deletedResources;
private final ElideSettings elideSettings;
@Getter private final Map<String, Set<String>> sparseFields;
//TODO - this ought to be read only and set in the constructor.
@Getter @Setter private EntityProjection entityProjection;
protected Function<RequestScope, EntityProjection> entityProjectionResolver;
@Getter private final UUID requestId;
protected Map<String, FilterExpression> expressionsByType;
private final Map<String, Object> metadata;
private LinkedHashSet<CRUDEvent> eventQueue;
/* Used to filter across heterogeneous types during the first load */
protected FilterExpression globalFilterExpression;
/**
* Create a new RequestScope.
*
* @param route the route
* @param transaction current transaction
* @param user request user
* @param requestId request ID
* @param entityProjection entity projection
*/
public RequestScope(Route route,
DataStoreTransaction transaction,
User user,
UUID requestId,
ElideSettings elideSettings,
Function<RequestScope, EntityProjection> entityProjection
) {
this.route = route;
this.eventQueue = new LinkedHashSet<>();
this.transaction = transaction;
this.user = user;
this.dictionary = elideSettings.getEntityDictionary();
this.auditLogger = elideSettings.getAuditLogger();
this.elideSettings = elideSettings;
this.globalFilterExpression = null;
this.expressionsByType = new LinkedHashMap<>();
this.objectEntityCache = new ObjectEntityCache();
this.newPersistentResources = new LinkedHashSet<>();
this.dirtyResources = new LinkedHashSet<>();
this.deletedResources = new LinkedHashSet<>();
this.requestId = requestId;
this.metadata = new LinkedHashMap<>();
this.sparseFields = parseSparseFields(getRoute().getParameters());
this.entityProjectionResolver = entityProjection;
if (this.entityProjectionResolver != null) {
this.entityProjection = this.entityProjectionResolver.apply(this);
}
Function<RequestScope, PermissionExecutor> permissionExecutorGenerator = elideSettings.getPermissionExecutor();
this.permissionExecutor = new MultiplexPermissionExecutor(
dictionary.buildPermissionExecutors(this),
(permissionExecutorGenerator == null)
? new ActivePermissionExecutor(this)
: permissionExecutorGenerator.apply(this),
dictionary
);
}
public RequestScope(RequestScope copy) {
this.route = copy.route;
this.transaction = copy.transaction;
this.user = copy.user;
this.dictionary = copy.dictionary;
this.auditLogger = copy.auditLogger;
this.objectEntityCache = copy.objectEntityCache;
this.newPersistentResources = copy.newPersistentResources;
this.dirtyResources = copy.dirtyResources;
this.deletedResources = copy.deletedResources;
this.elideSettings = copy.elideSettings;
this.sparseFields = copy.sparseFields;
this.requestId = copy.requestId;
this.expressionsByType = copy.expressionsByType;
this.metadata = copy.metadata;
this.eventQueue = copy.eventQueue;
this.globalFilterExpression = copy.globalFilterExpression;
this.permissionExecutor = copy.permissionExecutor;
this.entityProjectionResolver = copy.entityProjectionResolver;
if (this.entityProjectionResolver != null) {
this.entityProjection = this.entityProjectionResolver.apply(this);
}
}
public Set<com.yahoo.elide.core.security.PersistentResource> getNewResources() {
return (Set) newPersistentResources;
}
public boolean isNewResource(Object entity) {
return newPersistentResources.stream().anyMatch(r -> r.getObject() == entity);
}
/**
* Parses queryParams and produces sparseFields map.
* @param queryParams The request query parameters
* @return Parsed sparseFields map
*/
public static Map<String, Set<String>> parseSparseFields(Map<String, List<String>> queryParams) {
Map<String, Set<String>> result = new LinkedHashMap<>();
for (Map.Entry<String, List<String>> kv : queryParams.entrySet()) {
String key = kv.getKey();
if (key.startsWith("fields[") && key.endsWith("]")) {
String type = key.substring(7, key.length() - 1);
LinkedHashSet<String> filters = new LinkedHashSet<>();
for (String filterParams : kv.getValue()) {
Collections.addAll(filters, filterParams.split(","));
}
if (!filters.isEmpty()) {
result.put(type, filters);
}
}
}
return result;
}
/**
* Get filter expression for a specific collection type.
* @param type The name of the type
* @return The filter expression for the given type
*/
public Optional<FilterExpression> getFilterExpressionByType(String type) {
return Optional.ofNullable(expressionsByType.get(type));
}
/**
* Get filter expression for a specific collection type.
* @param entityClass The class to lookup
* @return The filter expression for the given type
*/
public Optional<FilterExpression> getFilterExpressionByType(Type<?> entityClass) {
return Optional.ofNullable(expressionsByType.get(dictionary.getJsonAliasFor(entityClass)));
}
/**
* Get the global/cross-type filter expression.
* @param loadClass Entity class
* @return The global filter expression evaluated at the first load
*/
public Optional<FilterExpression> getLoadFilterExpression(Type<?> loadClass) {
Optional<FilterExpression> filterExpression;
if (globalFilterExpression == null) {
String typeName = dictionary.getJsonAliasFor(loadClass);
filterExpression = getFilterExpressionByType(typeName);
} else {
filterExpression = Optional.of(globalFilterExpression);
}
return filterExpression;
}
/**
* Get the filter expression for a particular relationship.
* @param parentType The parent type which has the relationship
* @param relationName The relationship name
* @return A type specific filter expression for the given relationship
*/
public Optional<FilterExpression> getExpressionForRelation(Type<?> parentType, String relationName) {
final Type<?> entityClass = dictionary.getParameterizedType(parentType, relationName);
if (entityClass == null) {
throw new InvalidAttributeException(relationName, dictionary.getJsonAliasFor(parentType));
}
final String valType = dictionary.getJsonAliasFor(entityClass);
return getFilterExpressionByType(valType);
}
/**
* Extracts any query params that start with 'filter'.
* @param queryParams request query params
* @return extracted filter params
*/
private static Map<String, List<String>> getFilterParams(Map<String, List<String>> queryParams) {
Map<String, List<String>> returnMap = new LinkedHashMap<>();
queryParams.entrySet()
.stream()
.filter(entry -> entry.getKey().startsWith("filter"))
.forEach(entry -> returnMap.put(entry.getKey(), entry.getValue()));
return returnMap;
}
private void notifySubscribers(
LifeCycleHookBinding.Operation operation,
LifeCycleHookBinding.TransactionPhase phase
) {
LifecycleHookInvoker invoker = new LifecycleHookInvoker(dictionary, operation, phase);
this.eventQueue.stream()
.filter(event -> event.getEventType().equals(operation))
.forEach(event -> {
invoker.onNext(event);
});
}
/**
* Run queued pre-security lifecycle triggers.
*/
public void runQueuedPreSecurityTriggers() {
notifySubscribers(LifeCycleHookBinding.Operation.CREATE, LifeCycleHookBinding.TransactionPhase.PRESECURITY);
}
/**
* Run queued pre-flush lifecycle triggers.
*/
public void runQueuedPreFlushTriggers() {
runQueuedPreFlushTriggers(ALL_OPERATIONS);
}
/**
* Run queued pre-flush lifecycle triggers.
* @param operations List of operations to run pre-flush triggers for.
*/
public void runQueuedPreFlushTriggers(LifeCycleHookBinding.Operation[] operations) {
for (LifeCycleHookBinding.Operation op : operations) {
notifySubscribers(op, LifeCycleHookBinding.TransactionPhase.PREFLUSH);
}
}
/**
* Run queued pre-commit lifecycle triggers.
*/
public void runQueuedPreCommitTriggers() {
for (LifeCycleHookBinding.Operation op : ALL_OPERATIONS) {
notifySubscribers(op, LifeCycleHookBinding.TransactionPhase.PRECOMMIT);
}
}
/**
* Run queued post-commit lifecycle triggers.
*/
public void runQueuedPostCommitTriggers() {
for (LifeCycleHookBinding.Operation op : ALL_OPERATIONS) {
notifySubscribers(op, LifeCycleHookBinding.TransactionPhase.POSTCOMMIT);
}
}
/**
* Publishes a lifecycle event to all listeners.
*
* @param resource Resource on which to execute trigger
* @param crudAction CRUD action
*/
protected void publishLifecycleEvent(PersistentResource<?> resource, LifeCycleHookBinding.Operation crudAction) {
publishLifecycleEvent(new CRUDEvent(crudAction, resource, PersistentResource.CLASS_NO_FIELD, Optional.empty()));
}
/**
* Publishes a lifecycle event to all listeners.
*
* @param resource Resource on which to execute trigger
* @param fieldName Field name for which to specify trigger
* @param crudAction CRUD Action
* @param changeSpec Optional ChangeSpec to pass to the lifecycle hook
*/
protected void publishLifecycleEvent(PersistentResource<?> resource,
String fieldName,
LifeCycleHookBinding.Operation crudAction,
Optional<ChangeSpec> changeSpec) {
publishLifecycleEvent(new CRUDEvent(crudAction, resource, fieldName, changeSpec));
}
protected void publishLifecycleEvent(CRUDEvent event) {
if (! eventQueue.contains(event)) {
if (event.getEventType().equals(LifeCycleHookBinding.Operation.DELETE)
|| event.getEventType().equals(LifeCycleHookBinding.Operation.UPDATE)) {
LifecycleHookInvoker invoker = new LifecycleHookInvoker(dictionary,
event.getEventType(),
LifeCycleHookBinding.TransactionPhase.PRESECURITY);
invoker.onNext(event);
}
eventQueue.add(event);
}
}
public void saveOrCreateObjects() {
dirtyResources.removeAll(newPersistentResources);
// Delete has already been called on these objects
dirtyResources.removeAll(deletedResources);
newPersistentResources
.stream()
.map(PersistentResource::getObject)
.forEach(s -> transaction.createObject(s, this));
dirtyResources.stream().map(PersistentResource::getObject).forEach(obj -> transaction.save(obj, this));
}
public String getUUIDFor(Object o) {
return objectEntityCache.getUUID(o);
}
public Object getObjectById(Type<?> type, String id) {
Type<?> boundType = dictionary.lookupBoundClass(type);
Object result = objectEntityCache.get(boundType.getName(), id);
// Check inheritance too
Iterator<Type<?>> it = dictionary.getSubclassingEntities(boundType).iterator();
while (result == null && it.hasNext()) {
String newType = getInheritanceKey(it.next().getName(), boundType.getName());
result = objectEntityCache.get(newType, id);
}
return result;
}
public void setUUIDForObject(Type<?> type, String id, Object object) {
Type<?> boundType = dictionary.lookupBoundClass(type);
objectEntityCache.put(boundType.getName(), id, object);
// Insert for all inherited entities as well
dictionary.getSuperClassEntities(type).stream()
.map(i -> getInheritanceKey(boundType.getName(), i.getName()))
.forEach(newType -> objectEntityCache.put(newType, id, object));
}
private String getInheritanceKey(String subClass, String superClass) {
return subClass + "!" + superClass;
}
@Override
public void setMetadataField(String property, Object value) {
metadata.put(property, value);
}
@Override
public Optional<Object> getMetadataField(String property) {
return Optional.ofNullable(metadata.getOrDefault(property, null));
}
@Override
public Set<String> getMetadataFields() {
return metadata.keySet();
}
@Override
public Route getRoute() {
return this.route;
}
@Override
public ElideSettings getElideSettings() {
return this.elideSettings;
}
/**
* Returns a mutable {@link RequestScopeBuilder} for building {@link RequestScope}.
*
* @return the builder
*/
public static RequestScopeBuilder builder() {
return new RequestScopeBuilder();
}
/**
* A mutable builder for building {@link RequestScope}.
*/
public static class RequestScopeBuilder {
protected Route route;
protected DataStoreTransaction dataStoreTransaction;
protected User user;
protected UUID requestId;
protected ElideSettings elideSettings;
protected Function<RequestScope, EntityProjection> entityProjection;
protected void applyDefaults() {
if (this.requestId == null) {
this.requestId = UUID.randomUUID();
}
}
public RequestScope build() {
applyDefaults();
return new RequestScope(this.route, this.dataStoreTransaction, this.user, this.requestId,
this.elideSettings, this.entityProjection);
}
public RequestScopeBuilder route(Route route) {
this.route = route;
return this;
}
public RequestScopeBuilder dataStoreTransaction(DataStoreTransaction transaction) {
this.dataStoreTransaction = transaction;
return this;
}
public RequestScopeBuilder user(User user) {
this.user = user;
return this;
}
public RequestScopeBuilder requestId(UUID requestId) {
this.requestId = requestId;
return this;
}
public RequestScopeBuilder elideSettings(ElideSettings elideSettings) {
this.elideSettings = elideSettings;
return this;
}
public RequestScopeBuilder entityProjection(Function<RequestScope, EntityProjection> entityProjection) {
this.entityProjection = entityProjection;
return this;
}
public RequestScopeBuilder entityProjection(EntityProjection entityProjection) {
this.entityProjection = requestScope -> entityProjection;
return this;
}
}
}