forked from swisspost/gateleen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHookHandler.java
executable file
·1495 lines (1285 loc) · 61.4 KB
/
HookHandler.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
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package org.swisspush.gateleen.hook;
import io.vertx.core.Handler;
import io.vertx.core.MultiMap;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.eventbus.Message;
import io.vertx.core.http.*;
import io.vertx.core.json.DecodeException;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import org.joda.time.LocalDateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.swisspush.gateleen.core.http.HttpRequest;
import org.swisspush.gateleen.core.logging.LoggableResource;
import org.swisspush.gateleen.core.logging.RequestLogger;
import org.swisspush.gateleen.core.storage.ResourceStorage;
import org.swisspush.gateleen.core.util.CollectionContentComparator;
import org.swisspush.gateleen.core.util.HttpRequestHeader;
import org.swisspush.gateleen.core.util.StatusCode;
import org.swisspush.gateleen.hook.queueingstrategy.*;
import org.swisspush.gateleen.hook.reducedpropagation.ReducedPropagationManager;
import org.swisspush.gateleen.logging.LoggingResourceManager;
import org.swisspush.gateleen.monitoring.MonitoringHandler;
import org.swisspush.gateleen.queue.expiry.ExpiryCheckHandler;
import org.swisspush.gateleen.queue.queuing.QueueClient;
import org.swisspush.gateleen.queue.queuing.RequestQueue;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.swisspush.gateleen.core.util.HttpRequestHeader.CONTENT_LENGTH;
/**
* The HookHandler is responsible for un- and registering hooks (listener, as well as routes). He also
* handles forwarding requests to listeners / routes.
*
* @author https://github.com/ljucam [Mario Ljuca]
*/
public class HookHandler implements LoggableResource {
public static final String HOOKED_HEADER = "x-hooked";
public static final String HOOK_ROUTES_LISTED = "x-hook-routes-listed";
public static final String HOOKS_LISTENERS_URI_PART = "/_hooks/listeners/";
public static final String LISTENER_QUEUE_PREFIX = "listener-hook";
private static final String LISTENER_HOOK_TARGET_PATH = "listeners/";
public static final String HOOKS_ROUTE_URI_PART = "/_hooks/route";
private static final String HOOK_STORAGE_PATH = "registrations/";
private static final String HOOK_LISTENER_STORAGE_PATH = HOOK_STORAGE_PATH + "listeners/";
private static final String HOOK_ROUTE_STORAGE_PATH = HOOK_STORAGE_PATH + "routes/";
private static final String SAVE_LISTENER_ADDRESS = "gateleen.hook-listener-insert";
private static final String REMOVE_LISTENER_ADDRESS = "gateleen.hook-listener-remove";
private static final String SAVE_ROUTE_ADDRESS = "gateleen.hook-route-insert";
private static final String REMOVE_ROUTE_ADDRESS = "gateleen.hook-route-remove";
private static final int DEFAULT_HOOK_STORAGE_EXPIRE_AFTER_TIME = 1 * 60 * 60; // 1h in seconds
private static final int DEFAULT_HOOK_LISTENERS_EXPIRE_AFTER_TIME = 30; // 30 seconds
private static final int DEFAULT_CLEANUP_TIME = 15000; // 15 seconds
public static final String REQUESTURL = "requesturl";
public static final String EXPIRATION_TIME = "expirationTime";
public static final String HOOK = "hook";
public static final String EXPIRE_AFTER = "expireAfter";
public static final String QUEUE_EXPIRE_AFTER = "queueExpireAfter";
public static final String STATIC_HEADERS = "staticHeaders";
public static final String FULL_URL = "fullUrl";
public static final String DISCARD_PAYLOAD = "discardPayload";
public static final String HOOK_TRIGGER_TYPE = "type";
public static final String LISTABLE = "listable";
public static final String COLLECTION = "collection";
private final Comparator<String> collectionContentComparator;
private Logger log = LoggerFactory.getLogger(HookHandler.class);
private Vertx vertx;
private final ResourceStorage userProfileStorage;
private final ResourceStorage hookStorage;
private MonitoringHandler monitoringHandler;
private LoggingResourceManager loggingResourceManager;
private final HttpClient selfClient;
private String userProfilePath;
private String hookRootUri;
private boolean listableRoutes;
private ListenerRepository listenerRepository;
private RouteRepository routeRepository;
private RequestQueue requestQueue;
private ReducedPropagationManager reducedPropagationManager;
private boolean logHookConfigurationResourceChanges = false;
private Handler<Void> doneHandler;
/**
* Creates a new HookHandler.
*
* @param vertx vertx
* @param selfClient selfClient
* @param storage storage
* @param loggingResourceManager loggingResourceManager
* @param monitoringHandler monitoringHandler
* @param userProfilePath userProfilePath
* @param hookRootUri hookRootUri
*/
public HookHandler(Vertx vertx, HttpClient selfClient, final ResourceStorage storage,
LoggingResourceManager loggingResourceManager, MonitoringHandler monitoringHandler,
String userProfilePath, String hookRootUri) {
this(vertx,selfClient, storage, loggingResourceManager, monitoringHandler, userProfilePath, hookRootUri,
new QueueClient(vertx, monitoringHandler));
}
/**
* Creates a new HookHandler.
* @param vertx vertx
* @param selfClient selfClient
* @param storage storage
* @param loggingResourceManager loggingResourceManager
* @param monitoringHandler monitoringHandler
* @param userProfilePath userProfilePath
* @param hookRootUri hookRootUri
* @param requestQueue requestQueue
*/
public HookHandler(Vertx vertx, HttpClient selfClient, final ResourceStorage storage,
LoggingResourceManager loggingResourceManager, MonitoringHandler monitoringHandler,
String userProfilePath, String hookRootUri, RequestQueue requestQueue) {
this(vertx, selfClient,storage, loggingResourceManager, monitoringHandler, userProfilePath, hookRootUri,
requestQueue, false);
}
public HookHandler(Vertx vertx, HttpClient selfClient, final ResourceStorage storage,
LoggingResourceManager loggingResourceManager, MonitoringHandler monitoringHandler,
String userProfilePath, String hookRootUri, RequestQueue requestQueue, boolean listableRoutes) {
this(vertx, selfClient,storage, loggingResourceManager, monitoringHandler, userProfilePath, hookRootUri,
requestQueue, false, null);
}
/**
* Creates a new HookHandler.
*
* @param vertx vertx
* @param selfClient selfClient
* @param storage storage
* @param loggingResourceManager loggingResourceManager
* @param monitoringHandler monitoringHandler
* @param userProfilePath userProfilePath
* @param hookRootUri hookRootUri
* @param requestQueue requestQueue
* @param listableRoutes listableRoutes
* @param reducedPropagationManager reducedPropagationManager
*/
public HookHandler(Vertx vertx, HttpClient selfClient, final ResourceStorage storage,
LoggingResourceManager loggingResourceManager, MonitoringHandler monitoringHandler,
String userProfilePath, String hookRootUri, RequestQueue requestQueue, boolean listableRoutes,
ReducedPropagationManager reducedPropagationManager) {
this(vertx, selfClient,storage, loggingResourceManager, monitoringHandler, userProfilePath, hookRootUri,
requestQueue, listableRoutes, reducedPropagationManager, null, storage);
}
/**
* Creates a new HookHandler.
*
* @param vertx vertx
* @param selfClient selfClient
* @param userProfileStorage userProfileStorage - where the user profiles are stored
* @param loggingResourceManager loggingResourceManager
* @param monitoringHandler monitoringHandler
* @param userProfilePath userProfilePath
* @param hookRootUri hookRootUri
* @param requestQueue requestQueue
* @param listableRoutes listableRoutes
* @param reducedPropagationManager reducedPropagationManager
* @param doneHandler doneHandler
* @param hookStorage hookStorage - where the hooks are stored
*/
public HookHandler(Vertx vertx, HttpClient selfClient, final ResourceStorage userProfileStorage,
LoggingResourceManager loggingResourceManager, MonitoringHandler monitoringHandler,
String userProfilePath, String hookRootUri, RequestQueue requestQueue, boolean listableRoutes,
ReducedPropagationManager reducedPropagationManager, Handler doneHandler, ResourceStorage hookStorage) {
log.debug("Creating HookHandler ...");
this.vertx = vertx;
this.selfClient = selfClient;
this.userProfileStorage = userProfileStorage;
this.loggingResourceManager = loggingResourceManager;
this.monitoringHandler = monitoringHandler;
this.userProfilePath = userProfilePath;
this.hookRootUri = hookRootUri;
this.requestQueue = requestQueue;
this.listableRoutes = listableRoutes;
this.reducedPropagationManager = reducedPropagationManager;
listenerRepository = new LocalListenerRepository();
routeRepository = new LocalRouteRepository();
collectionContentComparator = new CollectionContentComparator();
this.doneHandler = doneHandler;
this.hookStorage = hookStorage;
}
public void init() {
// add all init methods here (!)
final List<Consumer<Handler<Void>>> initMethods = new ArrayList<>();
initMethods.add(this::registerListenerRegistrationHandler);
initMethods.add(this::registerRouteRegistrationHandler);
initMethods.add(this::loadStoredListeners);
initMethods.add(this::loadStoredRoutes);
initMethods.add(this::registerCleanupHandler);
// ready handler, calls the doneHandler when everything is done and the HookHandler is ready to use
Handler<Void> readyHandler = new Handler<Void>() {
// count of methods with may return an OK (ready)
private AtomicInteger readyCounter = new AtomicInteger(initMethods.size());
@Override
public void handle(Void aVoid) {
if ( readyCounter.decrementAndGet() == 0 ) {
log.info("HookHandler is ready!");
if ( doneHandler != null ) {
doneHandler.handle(null);
}
}
}
};
initMethods.forEach( handlerConsumer -> handlerConsumer.accept(readyHandler) );
}
@Override
public void enableResourceLogging(boolean resourceLoggingEnabled) {
this.logHookConfigurationResourceChanges = resourceLoggingEnabled;
}
/**
* Registers a cleanup timer
*
* @param readyHandler - the ready handler
*/
private void registerCleanupHandler(Handler<Void> readyHandler) {
vertx.setPeriodic(DEFAULT_CLEANUP_TIME, new Handler<Long>() {
public void handle(Long timerID) {
log.trace("Running hook cleanup ...");
LocalDateTime nowAsTime = ExpiryCheckHandler.getActualTime();
// Loop through listeners first
for (Listener listener : listenerRepository.getListeners()) {
if (listener.getHook().getExpirationTime().isBefore(nowAsTime)) {
log.debug("Listener " + listener.getListenerId() + " expired at " + listener.getHook().getExpirationTime() + " and actual time is " + nowAsTime);
listenerRepository.removeListener(listener.getListenerId());
routeRepository.removeRoute(hookRootUri + LISTENER_HOOK_TARGET_PATH + listener.getListenerId());
}
}
// Loop through routes
Map<String, Route> routes = routeRepository.getRoutes();
for (String key : routes.keySet()) {
Route route = routes.get(key);
if (route.getHook().getExpirationTime().isBefore(nowAsTime)) {
routeRepository.removeRoute(key);
}
}
log.trace("done");
}
});
// method done / no async processing pending
readyHandler.handle(null);
}
/**
* Loads the stored routes
* from the resource hookStorage,
* if any are available.
*
* @param readyHandler - the ready handler
*/
private void loadStoredRoutes(Handler<Void> readyHandler) {
log.debug("loadStoredRoutes");
// load the names of the routes from the hookStorage
final String routeBase = hookRootUri + HOOK_ROUTE_STORAGE_PATH;
hookStorage.get(routeBase, buffer -> {
if (buffer != null) {
JsonObject listOfRoutes = new JsonObject(buffer.toString());
JsonArray routeNames = listOfRoutes.getJsonArray("routes");
Iterator<String> keys = routeNames.getList().iterator();
final AtomicInteger storedRoutesCount = new AtomicInteger(routeNames.getList().size());
// go through the routes ...
while( keys.hasNext() ) {
final String key = keys.next();
// ... and load each one
hookStorage.get(routeBase + key, routeBody -> {
if ( routeBody != null ) {
registerRoute(routeBody);
}
else {
log.warn("Could not get URL '" + routeBase + key + "' (getting hook route).");
}
// send a ready flag
if ( storedRoutesCount.decrementAndGet() == 0 ) {
readyHandler.handle( null );
}
});
}
} else {
log.warn("Could not get URL '" + routeBase + "' (getting hook route).");
// send a ready flag
readyHandler.handle( null );
}
});
}
/**
* Loads the stored listeners
* from the resource hookStorage, if
* any are available.
* @param readyHandler - the ready handler
*/
private void loadStoredListeners(final Handler<Void> readyHandler) {
log.debug("loadStoredListeners");
// load the names of the listener from the hookStorage
final String listenerBase = hookRootUri + HOOK_LISTENER_STORAGE_PATH;
hookStorage.get(listenerBase, buffer -> {
if (buffer != null) {
JsonObject listOfListeners = new JsonObject(buffer.toString());
JsonArray listenerNames = listOfListeners.getJsonArray("listeners");
Iterator<String> keys = listenerNames.getList().iterator();
final AtomicInteger storedListenerCount = new AtomicInteger(listenerNames.getList().size());
// go through the listeners ...
while( keys.hasNext() ) {
final String key = keys.next();
// ... and load each one
hookStorage.get(listenerBase + key, listenerBody -> {
if ( listenerBody != null ) {
registerListener(listenerBody);
}
else {
log.warn("Could not get URL '" + listenerBase + key + "' (getting hook listener).");
}
// send a ready flag
if ( storedListenerCount.decrementAndGet() == 0 ) {
readyHandler.handle( null );
}
});
}
} else {
log.warn("Could not get URL '" + listenerBase + "' (getting hook listener).");
// send a ready flag
readyHandler.handle( null );
}
});
}
/**
* Registers all needed handlers for the
* route registration / unregistration.
*
* @param readyHandler - the ready handler
*/
private void registerRouteRegistrationHandler(Handler<Void> readyHandler) {
// Receive listener insert notifications
vertx.eventBus().consumer(SAVE_ROUTE_ADDRESS, new Handler<Message<String>>() {
@Override
public void handle(final Message<String> event) {
hookStorage.get(event.body(), buffer -> {
if (buffer != null) {
registerRoute(buffer);
} else {
log.warn("Could not get URL '" + (event.body() == null ? "<null>" : event.body()) + "' (getting hook route).");
}
});
}
});
// Receive listener remove notifications
vertx.eventBus().consumer(REMOVE_ROUTE_ADDRESS, new Handler<Message<String>>() {
@Override
public void handle(final Message<String> event) {
unregisterRoute(event.body());
}
});
// method done / no async processing pending
readyHandler.handle(null);
}
/**
* Registers all needed handlers for the
* listener registration / unregistration.
*/
public void registerListenerRegistrationHandler(Handler<Void> readyHandler) {
// Receive listener insert notifications
vertx.eventBus().consumer(SAVE_LISTENER_ADDRESS, new Handler<Message<String>>() {
@Override
public void handle(final Message<String> event) {
hookStorage.get(event.body(), buffer -> {
if (buffer != null) {
registerListener(buffer);
} else {
log.warn("Could not get URL '" + (event.body() == null ? "<null>" : event.body()) + "' (getting hook listener).");
}
});
}
});
// Receive listener remove notifications
vertx.eventBus().consumer(REMOVE_LISTENER_ADDRESS, new Handler<Message<String>>() {
@Override
public void handle(final Message<String> event) {
unregisterListener(event.body());
}
});
// method done / no async processing pending
readyHandler.handle(null);
}
/**
* Handles requests, which are either listener or
* route related.
* Takes on:
* <ul>
* <li>hook un-/registration</li>
* <li>enqueueing a request for the registred listeners</li>
* <li>forwarding a request to the reistred listeners</li>
* <li>creating a self request for the original request (if necessary)</li>
* </ul>
*
* @param request request
* @return true if a request is processed by the handler, otherwise false
*/
public boolean handle(final HttpServerRequest request) {
boolean consumed = false;
/*
* 1) Un- / Register Listener / Routes
*/
if (isHookListenerRegistration(request)) {
handleListenerRegistration(request);
return true;
}
if (isHookListenerUnregistration(request)) {
handleListenerUnregistration(request);
return true;
}
if (isHookRouteRegistration(request)) {
handleRouteRegistration(request);
return true;
}
if (isHookRouteUnregistration(request)) {
handleRouteUnregistration(request);
return true;
}
/*
* 2) Check if we have to queue a request for listeners
*/
final List<Listener> listeners = listenerRepository.findListeners(request.uri(), request.method().name());
if (!listeners.isEmpty() && !isRequestAlreadyHooked(request)) {
installBodyHandler(request, listeners);
consumed = true;
}
if (!consumed) {
consumed = routeRequestIfNeeded(request);
if (!consumed) {
return createListingIfRequested(request);
}
return consumed;
} else {
return true;
}
}
/**
* Create a listing of routes in the given parent. This happens
* only if we have a GET request, the routes are listable and
* the request is not marked as already listed (x-hook-routes-listed:true).
*
* @param request request
* @return true if a listing was performed (consumed), otherwise false.
*/
private boolean createListingIfRequested(final HttpServerRequest request) {
String routesListedHeader = request.headers().get(HOOK_ROUTES_LISTED);
boolean routesListed = routesListedHeader != null && routesListedHeader.equals("true");
// GET request / routes not yet listed
if ( request.method().equals(HttpMethod.GET) && ! routesListed ) {
// route collection available for parent?
final List<String> collections = new ArrayList<String>(routeRepository.getCollections(request.uri()));
if ( ! collections.isEmpty() ) {
String parentUri = request.uri().contains("?") ? request.uri().substring(0, request.uri().indexOf('?')) : request.uri();
final String parentCollection = getCollectionName(parentUri);
// sort the result array
collections.sort(collectionContentComparator);
if ( log.isTraceEnabled() ) {
log.trace("createListingIfRequested > (parentUri) {}, (parentCollection) {}", parentUri, parentCollection);
}
HttpClientRequest selfRequest = selfClient.request(request.method(), request.uri(), response -> {
request.response().setStatusCode(response.statusCode());
request.response().setStatusMessage(response.statusMessage());
request.response().setChunked(true);
request.response().headers().addAll(response.headers());
request.response().headers().remove(CONTENT_LENGTH.getName());
request.response().headers().remove(HOOK_ROUTES_LISTED);
// if everything is fine, we add the listed collections to the given array
if ( response.statusCode() == StatusCode.OK.getStatusCode() ) {
if ( log.isTraceEnabled() ) {
log.trace("createListingIfRequested > use existing array");
}
response.handler(data -> {
JsonObject responseObject = new JsonObject(data.toString());
// we only got an array back, if we perform a simple request
if (responseObject.getValue(parentCollection) instanceof JsonArray) {
JsonArray parentCollectionArray = responseObject.getJsonArray(parentCollection);
// add the listed routes
collections.forEach(parentCollectionArray::add);
}
if ( log.isTraceEnabled() ) {
log.trace("createListingIfRequested > response: {}", responseObject.toString() );
}
// write the response
request.response().write(Buffer.buffer(responseObject.toString()));
});
}
// if nothing is found, we create a new array
else if ( response.statusCode() == StatusCode.NOT_FOUND.getStatusCode() ) {
if ( log.isTraceEnabled() ) {
log.trace("createListingIfRequested > creating new array");
}
response.handler(data -> {
// override status message and code
request.response().setStatusCode(StatusCode.OK.getStatusCode());
request.response().setStatusMessage(StatusCode.OK.getStatusMessage());
JsonObject responseObject = new JsonObject();
JsonArray parentCollectionArray = new JsonArray();
responseObject.put(parentCollection, parentCollectionArray);
// add the listed routes
collections.forEach(parentCollectionArray::add);
if ( log.isTraceEnabled() ) {
log.trace("createListingIfRequested > response: {}", responseObject.toString() );
}
// write the response
request.response().write(Buffer.buffer(responseObject.toString()));
});
}
// something's wrong ...
else {
log.debug("createListingIfRequested - got response - ERROR");
response.handler(data -> request.response().write(data));
}
response.endHandler(v -> request.response().end());
});
if (request.headers() != null && !request.headers().isEmpty()) {
selfRequest.headers().setAll(request.headers());
}
// mark request as already listed
selfRequest.headers().add(HOOK_ROUTES_LISTED, "true");
selfRequest.exceptionHandler(exception -> log.warn("HookHandler: listing of collections (routes) failed: " + request.uri() + ": " + exception.getMessage()));
selfRequest.setTimeout(120000); // avoids blocking other requests
selfRequest.end();
// consumed
return true;
}
}
// not consumed
return false;
}
private String getCollectionName(String url) {
if ( url.endsWith("/") ) {
url = url.substring(0, url.lastIndexOf("/"));
}
return url.substring(url.lastIndexOf("/") + 1, url.length());
}
private boolean routeRequestIfNeeded(HttpServerRequest request) {
Route route = routeRepository.getRoute(request.uri());
if (route != null && (route.getHook().getMethods().isEmpty() || route.getHook().getMethods().contains(request.method().name()))) {
log.debug("Forward request " + request.uri());
route.forward(request);
return true;
} else {
return false;
}
}
private void installBodyHandler(final HttpServerRequest request, final List<Listener> listeners) {
// Read the original request and queue a new one for every listener
request.bodyHandler(buffer -> {
// Create separate lists with filtered listeners
List<Listener> beforeListener = getFilteredListeners(listeners, HookTriggerType.BEFORE);
List<Listener> afterListener = getFilteredListeners(listeners, HookTriggerType.AFTER);
// Create handlers for before/after - cases
Handler<Void> afterHandler = installAfterHandler(request, buffer, afterListener);
Handler<Void> beforeHandler = installBeforeHandler(request, buffer, beforeListener, afterHandler);
// call the listeners (before)
callListener(request, buffer, beforeListener, beforeHandler);
});
}
/**
* Calls the passed listeners and passes the given handler to the enqueued listener requests.
*
* @param request original request
* @param buffer buffer
* @param filteredListeners all listeners which should be called
* @param handler the handler, which should handle the requests
*/
private void callListener(final HttpServerRequest request, final Buffer buffer, final List<Listener> filteredListeners, final Handler<Void> handler) {
for (Listener listener : filteredListeners) {
log.debug("Enqueue request matching " + request.method() + " " + listener.getMonitoredUrl() + " with listener " + listener.getListener());
/*
* url suffix (path) after monitored url
* => monitored url = http://a/b/c
* => request.uri() = http://a/b/c/d/e.x
* => url suffix = /d/e.x
*/
String path = request.uri();
if (!listener.getHook().isFullUrl()) {
path = request.uri().replace(listener.getMonitoredUrl(), "");
}
String targetUri;
// internal
if (listener.getHook().getDestination().startsWith("/")) {
targetUri = listener.getListener() + path;
log.debug(" > internal target: " + targetUri);
}
// external
else {
targetUri = hookRootUri + LISTENER_HOOK_TARGET_PATH + listener.getListener() + path;
log.debug(" > external target: " + targetUri);
}
String queue = LISTENER_QUEUE_PREFIX + "-" + listener.getListenerId();
// Create a new multimap, copied from the original request,
// so that the original request is not overridden with the new values.
MultiMap queueHeaders = new CaseInsensitiveHeaders();
queueHeaders.addAll(request.headers());
if (ExpiryCheckHandler.getExpireAfter(queueHeaders) == null) {
ExpiryCheckHandler.setExpireAfter(queueHeaders, listener.getHook().getExpireAfter());
}
if(ExpiryCheckHandler.getQueueExpireAfter(queueHeaders) == null && listener.getHook().getQueueExpireAfter() != -1 ) {
ExpiryCheckHandler.setQueueExpireAfter(queueHeaders, listener.getHook().getQueueExpireAfter());
}
// update request headers with static headers (if available)
updateHeadersWithStaticHeaders(queueHeaders, listener.getHook().getStaticHeaders());
// in order not to block the queue because one client returns a creepy response,
// we translate all status codes of the listeners to 200.
// Therefor we set the header x-translate-status-4xx
queueHeaders.add("x-translate-status-4xx", "200");
QueueingStrategy queueingStrategy = listener.getHook().getQueueingStrategy();
if(queueingStrategy instanceof DefaultQueueingStrategy){
requestQueue.enqueue(new HttpRequest(request.method(), targetUri, queueHeaders, buffer.getBytes()), queue, handler);
} else if(queueingStrategy instanceof DiscardPayloadQueueingStrategy){
if(HttpRequestHeader.containsHeader(queueHeaders, CONTENT_LENGTH)) {
queueHeaders.set(CONTENT_LENGTH.getName(), "0");
}
requestQueue.enqueue(new HttpRequest(request.method(), targetUri, queueHeaders, null), queue, handler);
} else if(queueingStrategy instanceof ReducedPropagationQueueingStrategy){
if(reducedPropagationManager != null) {
reducedPropagationManager.processIncomingRequest(request.method(), targetUri, queueHeaders, buffer,
queue, ((ReducedPropagationQueueingStrategy) queueingStrategy).getPropagationIntervalMs(), handler);
} else {
log.error("ReducedPropagationQueueingStrategy without configured ReducedPropagationManager. Not going to handle (enqueue) anything!");
}
} else {
log.error("QueueingStrategy '"+queueingStrategy.getClass().getSimpleName()+"' is not handled. Could be an error, check the source code!");
}
}
// if for e.g. the beforListeners are empty,
// we have to ensure, that the original request
// is executed. This way the after handler will
// also be called properly.
if ( filteredListeners.isEmpty() && handler != null ) {
handler.handle(null);
}
}
/**
* This handler is called after the self request (original request) is performed
* successfully.
* The handler calls all listener (after), so this requests happen AFTER the original
* request is performed.
*
* @param request original request
* @param buffer buffer
* @param afterListener list of listeners which should be called after the original request
* @return the after handler
*/
private Handler<Void> installAfterHandler(final HttpServerRequest request, final Buffer buffer, final List<Listener> afterListener) {
Handler<Void> afterHandler = event -> callListener(request, buffer, afterListener, null);
return afterHandler;
}
/**
* This handler is called by the queueclient
* for each listener (before).
* The request happens BEFORE the original request is
* performed.
* @param request original request
* @param buffer buffer
* @param beforeListener list of listeners which should be called before the original request
* @param afterHandler the handler for listeners which have to be called after the original request
* @return the before handler
*/
private Handler<Void> installBeforeHandler(final HttpServerRequest request, final Buffer buffer, final List<Listener> beforeListener, final Handler<Void> afterHandler) {
Handler<Void> beforeHandler = new Handler<Void>() {
private AtomicInteger currentCount = new AtomicInteger(0);
private boolean sent = false;
@Override
public void handle(Void event) {
// If the last queued request is performed
// the original request will be triggered.
// Because this handler is called async. we
// have to secure, that it is only executed
// once.
if ( ( currentCount.incrementAndGet() == beforeListener.size() || beforeListener.isEmpty() ) && !sent) {
sent = true;
/*
* we should find exactly one or none route (first match rtl)
* routes will only be found for requests coming from
* enqueueing through the listener and only for external
* requests.
*/
Route route = routeRepository.getRoute(request.uri());
if (route != null && (route.getHook().getMethods().isEmpty() || route.getHook().getMethods().contains(request.method().name()))) {
log.debug("Forward request (consumed) " + request.uri());
route.forward(request, buffer);
} else {
// mark the original request as hooked
request.headers().add(HOOKED_HEADER, "true");
/*
* self requests are only made for original
* requests which were consumed during the
* enqueueing process, therefore it is
* imperative to use isRequestAlreadyHooked(HttpServerRequest request)
* before calling the handle method of
* this class!
*/
createSelfRequest(request, buffer, afterHandler);
}
}
}
};
return beforeHandler;
}
/**
* Returns a list with listeners which fires before / after the original request.
*
* @param listeners all listeners
* @return filtered listeners
*/
private List<Listener> getFilteredListeners(final List<Listener> listeners, final HookTriggerType hookTriggerType) {
return listeners.stream()
.filter(listener -> listener.getHook().getHookTriggerType().equals(hookTriggerType))
.collect(Collectors.toList());
}
/**
* Updates (and overrides) the given headers with the static headers (if they are available).
*
* @param queueHeaders the headers for the request to be enqueued
* @param staticHeaders the static headers for the given hook
*/
private void updateHeadersWithStaticHeaders(final MultiMap queueHeaders, final Map<String, String> staticHeaders) {
if (staticHeaders != null) {
for (Map.Entry<String, String> entry : staticHeaders.entrySet()) {
String entryValue = entry.getValue();
if (entryValue != null && entryValue.length() > 0 ) {
queueHeaders.set(entry.getKey(), entry.getValue());
} else {
queueHeaders.remove(entry.getKey());
}
}
}
}
/**
* This method is called after an incoming route
* unregistration is detected.
* This method deletes the route from the resource
* hookStorage.
*
* @param request request
*/
private void handleRouteUnregistration(final HttpServerRequest request) {
log.debug("handleRouteUnregistration > " + request.uri());
// eg. /server/hooks/v1/registrations/+my+storage+id+
final String routeStorageUri = hookRootUri + HOOK_ROUTE_STORAGE_PATH + getStorageIdentifier(request.uri());
hookStorage.delete(routeStorageUri, status -> {
/*
* In case of an unregistration, it does not matter,
* if the route is still stored in the resource
* storage or not. It may even be the case, that the
* route has already expired and therefore vanished
* from the resource storage, but the cleanup job for the
* in-memory storage hasn't run yet.
* Even the service which calls the unregistration
* doesn't have to be notified if an unregistration
* 'fails', therefore always an OK status is sent.
*/
vertx.eventBus().publish(REMOVE_ROUTE_ADDRESS, request.uri());
request.response().end();
});
}
/**
* This method is called after an incoming route
* registration is detected.
* This method puts the registration request to the
* resource storage, so it can be reloaded even after
* a restart of the communication service.
* The request will be consumed in this process!
*
* @param request request
*/
private void handleRouteRegistration(final HttpServerRequest request) {
log.debug("handleRouteRegistration > " + request.uri());
request.bodyHandler(hookData -> {
// eg. /server/hooks/v1/registrations/+my+storage+id+
final String routeStorageUri = hookRootUri + HOOK_ROUTE_STORAGE_PATH + getStorageIdentifier(request.uri());
// Extract expireAfter from the registration header.
Integer expireAfter = ExpiryCheckHandler.getExpireAfter(request.headers());
if (expireAfter == null) {
expireAfter = DEFAULT_HOOK_STORAGE_EXPIRE_AFTER_TIME;
}
// Update the PUT header
ExpiryCheckHandler.setExpireAfter(request, expireAfter);
// calculate the expiration time for the listener / routes
LocalDateTime expirationTime = ExpiryCheckHandler.getExpirationTime(expireAfter);
/*
* Create a new json object containing the request url
* and the hook itself.
* {
* "requesturl" : "http://...",
* "expirationTime" : "...",
* "hook" : { ... }
* }
*/
JsonObject storageObject = new JsonObject();
storageObject.put(REQUESTURL, request.uri());
storageObject.put(EXPIRATION_TIME, ExpiryCheckHandler.printDateTime(expirationTime));
JsonObject hook;
try {
hook = new JsonObject(hookData.toString());
} catch (DecodeException e) {
request.response().setStatusCode(400);
final String msg = "Cannot decode JSON";
request.response().setStatusMessage(msg);
request.response().end(msg);
return;
}
if(hook.getString("destination")==null) {
request.response().setStatusCode(400);
final String msg = "Property 'destination' must be set";
request.response().setStatusMessage(msg);
request.response().end(msg);
return;
}
storageObject.put(HOOK, hook);
Buffer buffer = Buffer.buffer(storageObject.toString());
hookStorage.put(routeStorageUri, request.headers(), buffer, status -> {
if (status == StatusCode.OK.getStatusCode()) {
if(logHookConfigurationResourceChanges){
RequestLogger.logRequest(vertx.eventBus(), request, status, buffer);
}
vertx.eventBus().publish(SAVE_ROUTE_ADDRESS, routeStorageUri);
} else {
request.response().setStatusCode(status);
}
request.response().end();
});
});
}
/**
* Returns the identifier of the hook (only route) used in the
* resource storage.
* For listener identifiere take a look at <code>getUniqueListenerId(...)</code>.
*
* @param url
* @return identifier
*/
private String getStorageIdentifier(String url) {
return url.replace("/", "+");
}
/**
* This method is called after an incoming listener
* unregistration is detected.
* This method deletes the listener from the resource
* storage.
*
* @param request request
*/
private void handleListenerUnregistration(final HttpServerRequest request) {
log.debug("handleListenerUnregistration > " + request.uri());
// eg. /server/hooks/v1/registrations/listeners/http+myservice+1
final String listenerStorageUri = hookRootUri + HOOK_LISTENER_STORAGE_PATH + getUniqueListenerId(request.uri());
hookStorage.delete(listenerStorageUri, status -> {
/*
* In case of an unregistration, it does not matter,
* if the listener is still stored in the resource
* storage or not. It may even be the case, that the
* listener has already expired and therefore vanished
* from the resource storage, but the cleanup job for the
* in-memory storage hasn't run yet.
* Even the service which calls the unregistration
* doesn't have to be notified if an unregistration
* 'fails', therefore always an OK status is sent.
*/
vertx.eventBus().publish(REMOVE_LISTENER_ADDRESS, request.uri());
request.response().end();
});
}
/**
* This method is called after an incoming listener
* registration is detected.
* This method puts the registration request to the
* resource storage, so it can be reloaded even after