-
-
Notifications
You must be signed in to change notification settings - Fork 173
Expand file tree
/
Copy pathHandlerService.cfc
More file actions
751 lines (660 loc) · 27 KB
/
HandlerService.cfc
File metadata and controls
751 lines (660 loc) · 27 KB
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
/**
* Copyright Since 2005 ColdBox Framework by Luis Majano and Ortus Solutions, Corp
* www.ortussolutions.com
* ---
* This service takes care of all event handling in ColdBox
*/
component extends="coldbox.system.web.services.BaseService" accessors="true" {
/**
* Handler cache metadata dictionary
*/
property name="handlerCacheDictionary" type="struct";
/**
* Event caching metadata dictionary
*/
property name="eventCacheDictionary" type="struct";
/**
* Flag to denote handler caching
*/
property name="handlerCaching" type="boolean";
/**
* Flag to denote event caching
*/
property name="eventCaching" type="boolean";
/**
* Handler bean cache dictionary
*/
property name="handlerBeanCacheDictionary" type="struct";
/**
* Constructor
*
* @controller ColdBox Controller
*/
function init( required controller ){
// controlle + wirebox references
variables.controller = arguments.controller;
// Setup the Event Handler Cache Dictionary
variables.handlerCacheDictionary = {};
// Setup the Event Cache Dictionary
variables.eventCacheDictionary = {};
// Setup the Handler Bean Cache Dictionary
variables.handlerBeanCacheDictionary = {};
return this;
}
/**
* Once configuration file loads setup the services with app specific variables
*/
function onConfigurationLoad(){
// local logger
variables.log = variables.controller.getLogBox().getLogger( this );
// execute the handler registrations after configurations loaded
registerHandlers();
// Configuration data and dependencies
variables.eventAction = variables.controller.getColdBoxSetting( "EventAction" );
variables.registeredHandlers = variables.controller.getSetting( "RegisteredHandlers" );
variables.registeredExternalHandlers = variables.controller.getSetting( "RegisteredExternalHandlers" );
variables.eventName = variables.controller.getSetting( "EventName" );
variables.invalidEventHandler = variables.controller.getSetting( "invalidEventHandler" );
variables.handlerCaching = variables.controller.getSetting( "HandlerCaching" );
variables.eventCaching = variables.controller.getSetting( "EventCaching" );
variables.handlersInvocationPath = variables.controller.getSetting( "HandlersInvocationPath" );
variables.handlersExternalLocation = variables.controller.getSetting( "HandlersExternalLocation" );
variables.templateCache = variables.controller.getCache( "template" );
variables.modules = variables.controller.getSetting( "modules" );
variables.interceptorService = variables.controller.getInterceptorService();
variables.wirebox = variables.controller.getWireBox();
}
/**
* Builds a handler according to the passed handler bean modeling data via WireBox.
*
* @ehBean The handler bean that simulates the executions
*
* @return EventHandler - A handler Instance matching the ehBean signature
*/
function newHandler( required ehBean ){
// If it's a module, then use the module's injector, else the root injector
var injector = arguments.ehBean.isModule() ? variables.modules[ arguments.ehBean.getModule() ].injector : variables.wirebox;
var handlerPath = arguments.ehBean.getRunnable();
// Check if handler already mapped in the injector
if ( NOT injector.getBinder().mappingExists( handlerPath ) ) {
// lazy load checks for wirebox
injectorSeedBaseClasses( injector );
// feed this handler to wirebox with virtual inheritance just in case, use registerNewInstance so its thread safe
var mapping = injector
.registerNewInstance( name = handlerPath, instancePath = handlerPath )
.setVirtualInheritance( "coldbox.system.EventHandler" )
.setThreadSafe( true )
.setScope( variables.handlerCaching ? "singleton" : "NoScope" )
.setCacheProperties( key = "handlers-#handlerPath#" )
// extra attributes added to mapping so they are relayed by events
.setExtraAttributes( { handlerPath : handlerPath, isHandler : true } );
}
// retrieve, build and wire from wirebox
var handler = injector.getInstance( handlerPath );
// Is this a rest handler by annotation? If so, incorporate it's methods
if (
injector
.getBinder()
.getMapping( handlerPath )
.getObjectMetadata()
.keyExists( "restHandler" )
&&
!structKeyExists( handler, "restHandler" )
) {
structEach( variables.wirebox.getInstance( "coldbox.system.RestHandler" ), function( functionName, functionTarget ){
if ( !structKeyExists( handler, functionName ) ) {
handler[ functionName ] = functionTarget;
}
} );
}
return handler;
}
/**
* Get a validated handler instance using an event handler bean and context. This is called
* once event execution is in progress.
* Before returning this method verifies method of execution, event caching, invalid events and stores metadata
*
* @ehBean The event handler bean representation
* @requestContext The request context object
*
* @return The event handler object represented by the ehBean
*/
function getHandler( required ehBean, required requestContext ){
var oRequestContext = arguments.requestContext;
var oEventURLFacade = variables.templateCache.getEventURLFacade();
// Create Runnable Object via WireBox
var oEventHandler = newHandler( arguments.ehBean );
// Process An Invalid Event logic, which is reused
var processInvalidEvent = function(){
// The handler exists but the action requested does not, let's go into invalid execution mode
var targetInvalidEvent = invalidEvent( ehBean.getFullEvent(), ehBean );
// If we get here, then the invalid event kicked in and exists, else an exception is thrown above
// set the invalid event handler as the current event
oRequestContext.overrideEvent( targetInvalidEvent );
// Go retrieve the handler that will handle the invalid event so it can execute.
return getHandler( getHandlerBean( targetInvalidEvent ), oRequestContext );
};
/* ::::::::::::::::::::::::::::::::::::::::: EVENT METHOD TESTING :::::::::::::::::::::::::::::::::::::::::::: */
// Does requested method/action of execution exist in handler?
if ( NOT oEventHandler._actionExists( arguments.ehBean.getMethod() ) ) {
// Check if the handler has an onMissingAction() method, virtual Events
if ( oEventHandler._actionExists( "onMissingAction" ) ) {
// Override the method of execution
arguments.ehBean.setMissingAction( arguments.ehBean.getMethod() );
// Let's go execute our missing action
return oEventHandler;
}
// Test for Implicit View Dispatch
if (
controller.getSetting( "ImplicitViews" ) AND
isViewDispatch( arguments.ehBean.getFullEvent(), arguments.ehBean )
) {
return oEventHandler;
}
// Invalid Event processing
return processInvalidEvent();
}
// method check finalized.
// Store metadata in execution bean
if ( !variables.handlerCaching || !arguments.ehBean.isMetadataLoaded() ) {
arguments.ehBean
.setActionMetadata( oEventHandler._actionMetadata( arguments.ehBean.getMethod() ) )
.setHandlerMetadata( getMetadata( oEventHandler ) );
}
// Are they trying to execute an internal ColdBox method?
if ( arguments.ehBean.actionMetadataExists( "cbMethod" ) ) {
// Invalid Event processing
return processInvalidEvent();
}
/* ::::::::::::::::::::::::::::::::::::::::: EVENT CACHING :::::::::::::::::::::::::::::::::::::::::::: */
// Event Caching Routines, if using caching, NOT a private event and we are executing the main event
if (
variables.eventCaching AND
!arguments.ehBean.getIsPrivate() AND
arguments.ehBean.getFullEvent() EQ oRequestContext.getCurrentEvent()
) {
// Get event action caching metadata
var eventDictionaryEntry = getEventCachingMetadata( arguments.ehBean, oEventHandler );
// Do we need to cache this event's output after it executes??
if ( eventDictionaryEntry.cacheable ) {
// Create caching data structure according to MD, as the cache key can be dynamic by execution.
var eventCachingData = {};
structAppend( eventCachingData, eventDictionaryEntry, true );
// Create the Cache Key to save
eventCachingData.cacheKey = oEventURLFacade.buildEventKey(
targetEvent = arguments.ehBean.getFullEvent(),
targetContext = oRequestContext,
eventDictionary = eventDictionaryEntry
);
// Event is cacheable and we need to flag it so the Renderer caches it
oRequestContext.setEventCacheableEntry( eventCachingData );
}
// end if md says that this event is cacheable
}
// end if event caching.
// return the tested and validated event handler
return oEventHandler;
}
/**
* Parse the incoming event string into an event handler bean that is used for the current execution context
*
* @event The full event string
*
* @return coldbox.system.web.context.EventHandlerBean
*/
function getHandlerBean( required string event ){
// bean already in cache?
if ( variables.handlerCaching && structKeyExists( variables.handlerBeanCacheDictionary, arguments.event ) ) {
return variables.handlerBeanCacheDictionary[ arguments.event ];
}
// New event, prepare it
var handlersList = variables.registeredHandlers;
var handlersExternalList = variables.registeredExternalHandlers;
var oHandlerBean = new coldbox.system.web.context.EventHandlerBean( variables.handlersInvocationPath );
var moduleSettings = variables.modules;
// Rip the handler and method
var handlerReceived = listLast( reReplace( arguments.event, "\.[^.]*$", "" ), ":" );
var methodReceived = listLast( arguments.event, "." );
// Verify if this is a module call
if ( find( ":", arguments.event ) ) {
var moduleReceived = listFirst( arguments.event, ":" );
// Does this module exist?
if ( structKeyExists( moduleSettings, moduleReceived ) ) {
// Verify handler in module handlers
var handlerIndex = listFindNoCase(
moduleSettings[ moduleReceived ].registeredHandlers,
handlerReceived
);
if ( handlerIndex ) {
// Prepare bean data
oHandlerBean
.setInvocationPath( moduleSettings[ moduleReceived ].handlerInvocationPath )
.setHandler(
listGetAt( moduleSettings[ moduleReceived ].registeredHandlers, handlerIndex )
)
.setMethod( methodReceived )
.setModule( moduleReceived );
// put bean in cache if enabled
if ( variables.handlerCaching ) {
variables.handlerBeanCacheDictionary[ arguments.event ] = oHandlerBean;
}
return oHandlerBean;
} else {
variables.log.error(
"Invalid Module (#moduleReceived#) Handler: #handlerReceived#. Valid handlers are #moduleSettings[ moduleReceived ].registeredHandlers#"
);
}
}
// Log Error
variables.log.error(
"Invalid Module Event Called: #arguments.event#. The module: #moduleReceived# is not valid. Valid Modules are: #structKeyList( moduleSettings )#"
);
} else {
// Try to do list localization in the registry for full event string.
var handlerIndex = listFindNoCase( handlersList, handlerReceived );
// Check for conventions location
if ( handlerIndex ) {
// Prepare bean data
oHandlerBean.setHandler( listGetAt( handlersList, handlerIndex ) ).setMethod( MethodReceived );
// put bean in cache if enabled
if ( variables.handlerCaching ) {
variables.handlerBeanCacheDictionary[ arguments.event ] = oHandlerBean;
}
return oHandlerBean;
}
// Check for external location
handlerIndex = listFindNoCase( handlersExternalList, handlerReceived );
if ( handlerIndex ) {
// Prepare bean data
oHandlerBean
.setInvocationPath( variables.handlersExternalLocation )
.setHandler( listGetAt( handlersExternalList, handlerIndex ) )
.setMethod( MethodReceived );
// put bean in cache if enabled
if ( variables.handlerCaching ) {
variables.handlerBeanCacheDictionary[ arguments.event ] = oHandlerBean;
}
return oHandlerBean;
}
}
// end else
// Do View Dispatch Check Procedures
if ( isViewDispatch( arguments.event, oHandlerBean ) ) {
// put bean in cache if enabled
if ( variables.handlerCaching ) {
variables.handlerBeanCacheDictionary[ arguments.event ] = oHandlerBean;
}
return oHandlerBean;
}
// Run invalid event procedures, handler not found as a module or in all lists
arguments.event = invalidEvent( arguments.event, oHandlerBean );
// If we get here, then invalid event handler is active and we need to
// return an event handler bean that matches it
return getHandlerBean( arguments.event );
}
/**
* Do a default action checks on the incoming event string. This method matches it against
* the internal handlers list. If found, then we append the default action to the event.
*
* @event The request context
*
* @return HandlerService
*/
function defaultActionCheck( required event ){
var handlersList = variables.registeredHandlers;
var handlersExternalList = variables.registeredExternalHandlers;
var currentEvent = arguments.event.getCurrentEvent();
var modulesConfig = variables.modules;
// Module Check?
if ( find( ":", currentEvent ) ) {
var module = listFirst( currentEvent, ":" );
if (
structKeyExists( modulesConfig, module ) AND
listFindNoCase(
modulesConfig[ module ].registeredHandlers,
reReplaceNoCase( currentEvent, "^([^:.]*):", "" )
)
) {
// Append the default event action
currentEvent = currentEvent & "." & variables.eventAction;
// Save it as the current Event
event.setValue( variables.eventName, currentEvent );
}
return this;
}
// Do a Default Action Test First, if default action desired.
if (
listFindNoCase( handlersList, currentEvent ) OR
listFindNoCase( handlersExternalList, currentEvent )
) {
// Append the default event action
currentEvent = currentEvent & "." & variables.eventAction;
// Save it as the current Event now with the default action
event.setValue( variables.eventName, currentEvent );
}
return this;
}
/**
* Check if the incoming event has a matching implicit view to dispatch. This is usually called
* when there is no existing handler found.
*
* @event The event string
* @ehBean The event handler bean
*/
boolean function isViewDispatch( required string event, required ehBean ){
// Cleanup for modules
var cEvent = reReplaceNoCase( arguments.event, "^([^:.]*):", "" );
var renderer = controller.getRenderer();
var targetView = "";
var targetModule = getToken( arguments.event, 1, ":" );
// Cleanup of . to / for lookups for path locating
cEvent = lCase( replace( cEvent, ".", "/", "all" ) );
// module?
if ( find( ":", arguments.event ) ) {
// Validate that it is a valid module, else it is an invalid view.
if ( structKeyExists( variables.modules, targetModule ) ) {
targetView = renderer.locateModuleView( cEvent, targetModule );
} else {
return false;
}
} else {
targetView = renderer.locateView( cEvent );
}
// CFML View
if ( fileExists( expandPath( targetView ) ) ) {
arguments.ehBean.setViewDispatch( true );
return true;
}
return false;
}
/**
* Invalid Event procedures. An invalid event is detected, so this method
* will verify if the application has an invalidEventHandler or an interceptor
* listening to `onInvalidEvent` modifies the handler bean. Then this method will
* either return the invalid event handler event, or set an exception to be captured.
*
* @event The event that was found to be invalid
* @ehBean The event handler bean representing the invalid event
*
* @return The string event that should be executed as the invalid event handler or throws an EventHandlerNotRegisteredException
*
* @throws EventHandlerNotRegisteredException ,InvalidEventHandlerException
*/
string function invalidEvent( required string event, required ehBean ){
// Announce it
var iData = {
"invalidEvent" : arguments.event,
"ehBean" : arguments.ehBean,
"override" : false
};
variables.interceptorService.announce( "onInvalidEvent", iData );
// If the override was changed by the interceptors then they updated the ehBean of execution
if ( iData.override ) {
return arguments.ehBean.getFullEvent();
}
// Param our last invalid event just incase
param request._lastInvalidEvent = "";
// If invalidEventHandler is registered, use it
if ( len( variables.invalidEventHandler ) ) {
// Test for invalid Event Error as well so we don't go in an endless error loop
if (
compareNoCase( arguments.event, request._lastInvalidEvent ) eq 0
&&
!structKeyExists( variables.controller, "mockController" ) // Verify this is a real and not a mock controller.
) {
var exceptionMessage = "The invalidEventHandler event (#variables.invalidEventHandler#) is also invalid: #arguments.event#";
// Extra Debugging for illusive CI/Tests exceptions: Remove at one point if discovered.
variables.log.error(
exceptionMessage,
{
event : arguments.event,
requestEvent : request._lastInvalidEvent ?: "NONE",
registeredHandlers : variables.registeredHandlers,
fullEvent : ehBean.getFullEvent(),
callStack : callStackGet(),
routedURL : variables.controller
.getRequestService()
.getContext()
.getCurrentRoutedURL(),
route : variables.controller
.getRequestService()
.getContext()
.getCurrentRoute()
}
);
// Now throw the exception
throw( message: exceptionMessage, type: "HandlerService.InvalidEventHandlerException" );
}
// we save off this event in case there is problem matching our invalidEventHandler.
// This way we can catch infinite loops instead of having a Stack Overflow error.
request._lastInvalidEvent = arguments.event;
// Store Invalid Event in PRC
controller
.getRequestService()
.getContext()
.setPrivateValue( "invalidevent", arguments.event );
// Override Event With On invalid handler event
return variables.invalidEventHandler;
}
// end invalidEventHandler found
// If we got here, we have an invalid event and no override, throw a 404 ERROR
controller
.getRequestService()
.getContext()
.setHTTPHeader( statusCode = 404 );
// Invalid Event Detected, log it in the Application log, not a coldbox log but an app log
variables.log.error(
"Invalid Event detected: #arguments.event#. Path info: #CGI.PATH_INFO#, query string: #CGI.QUERY_STRING#"
);
// Throw Exception
throw(
message: "The event: #arguments.event# is not a valid registered event.",
type : "EventHandlerNotRegisteredException"
);
}
/**
* Register's application event handlers according to convention and external paths
*
* @return HandlerService
*
* @throws HandlersDirectoryNotFoundException
*/
function registerHandlers(){
var handlersPath = variables.controller.getSetting( "handlersPath" );
var handlersExternalLocationPath = variables.controller.getSetting( "handlersExternalLocationPath" );
var handlersExternalArray = [];
/* ::::::::::::::::::::::::::::::::::::::::: HANDLERS BY CONVENTION :::::::::::::::::::::::::::::::::::::::::::: */
// Get recursive Array listing
var handlerArray = getHandlerListing( handlersPath );
// Set registered Handlers
variables.registeredHandlers = arrayToList( handlerArray );
variables.controller.setSetting( name = "registeredHandlers", value = variables.registeredHandlers );
/* ::::::::::::::::::::::::::::::::::::::::: EXTERNAL HANDLERS :::::::::::::::::::::::::::::::::::::::::::: */
if ( len( handlersExternalLocationPath ) ) {
// Check for handlers Directory Location
if ( !directoryExists( handlersExternalLocationPath ) ) {
throw(
message = "The external handlers directory: #HandlersExternalLocationPath# does not exist please check your application structure.",
type = "HandlersDirectoryNotFoundException"
);
}
// Get recursive Array listing
handlersExternalArray = getHandlerListing( handlersExternalLocationPath );
}
// Set registered External Handlers
variables.registeredExternalHandlers = arrayToList( handlersExternalArray );
variables.controller.setSetting(
name = "registeredExternalHandlers",
value = variables.registeredExternalHandlers
);
return this;
}
/**
* Clear the internal cache dictionaries
*
* @return HandlerService
*/
function clearDictionaries(){
variables.eventCacheDictionary = {};
return this;
}
/**
* Get an event string's metadata entry. If not found, then you will get a new metadata entry using the `getNewMDEntry()` method.
*
* @targetEvent The event to match for metadata.
*/
struct function getEventMetadataEntry( required targetEvent ){
if ( NOT structKeyExists( variables.eventCacheDictionary, arguments.targetEvent ) ) {
return getNewMDEntry();
}
return variables.eventCacheDictionary[ arguments.targetEvent ];
}
/**
* Retrieve handler listings from disk
*
* @directory The path to retrieve
*/
array function getHandlerListing( required directory ){
// Convert windows \ to java /
arguments.directory = replace( arguments.directory, "\", "/", "all" );
return directoryList(
arguments.directory,
true,
"array",
"*.cfc|*.bx"
).map( function( item ){
var thisAbsolutePath = replace( item, "\", "/", "all" );
var cleanHandler = replaceNoCase( thisAbsolutePath, directory, "", "all" );
// Clean OS separators to dot notation.
cleanHandler = removeChars(
replaceNoCase( cleanHandler, "/", ".", "all" ),
1,
1
);
// Clean Extension
return variables.controller.getUtil().ripExtension( cleanhandler );
} );
}
/************************************ PRIVATE ************************************/
/**
* Verifies setup of base handler classes in WireBox
*
* @injector The injector to seed and verify
*
* @return HandlerService
*/
private function injectorSeedBaseClasses( required injector ){
if ( NOT arguments.injector.getBinder().mappingExists( "coldbox.system.EventHandler" ) ) {
arguments.injector
.registerNewInstance(
name : "coldbox.system.EventHandler",
instancePath: "coldbox.system.EventHandler"
)
.setScope( "singleton" );
}
if ( NOT arguments.injector.getBinder().mappingExists( "coldbox.system.RestHandler" ) ) {
arguments.injector
.registerNewInstance(
name : "coldbox.system.RestHandler",
instancePath: "coldbox.system.RestHandler"
)
.setScope( "singleton" );
}
return this;
}
/**
* Return a new metadata struct object
*
* @return { cacheable:boolean, timeout, lastAccessTimeout, cacheKey, suffix }
*/
private struct function getNewMDEntry(){
return {
"cacheable" : false,
"timeout" : "",
"lastAccessTimeout" : "",
"cacheKey" : "",
"suffix" : "",
"provider" : "template",
"cacheInclude" : "*",
"cacheExclude" : "",
"cacheFilter" : ""
};
}
/**
* Return the event caching metadata for an action execution context.
*
* @ehBean The event handler bean
* @oEventHandler The event handler to execute
*
* @return strc
*/
private struct function getEventCachingMetadata( required ehBean, required oEventHandler ){
var cacheKey = arguments.ehBean.getFullEvent();
// Double lock for race conditions
if ( !structKeyExists( variables.eventCacheDictionary, cacheKey ) ) {
lock
name ="handlerservice.#controller.getAppHash()#.eventcachingmd.#cacheKey#"
type ="exclusive"
throwontimeout="true"
timeout ="10" {
if ( !structKeyExists( variables.eventCacheDictionary, cacheKey ) ) {
// Get New Default MD Entry
var mdEntry = getNewMDEntry();
// Cache Entries for timeout and last access timeout
if ( arguments.ehBean.getActionMetadata( "cache", false ) ) {
mdEntry.cacheable = true;
mdEntry.timeout = arguments.ehBean.getActionMetadata( "cacheTimeout", "" );
mdEntry.lastAccessTimeout = arguments.ehBean.getActionMetadata(
"cacheLastAccessTimeout",
""
);
mdEntry.provider = arguments.ehBean.getActionMetadata( "cacheProvider", "template" );
mdEntry.cacheInclude = arguments.ehBean.getActionMetadata( "cacheInclude", "*" );
mdEntry.cacheExclude = arguments.ehBean.getActionMetadata( "cacheExclude", "" );
mdEntry.cacheFilter = arguments.ehBean.getActionMetadata( "cacheFilter", "" );
// Handler Event Cache Key Suffix, this is global to the event
if (
isClosure( arguments.oEventHandler.EVENT_CACHE_SUFFIX ) ||
isCustomFunction( arguments.oEventHandler.EVENT_CACHE_SUFFIX )
) {
mdEntry.suffix = oEventHandler.EVENT_CACHE_SUFFIX( arguments.ehBean );
} else {
mdEntry.suffix = arguments.oEventHandler.EVENT_CACHE_SUFFIX;
}
// if the cacheFilter has a length and is a method, then we need to verify and store the resulting closure
if ( len( mdEntry.cacheFilter ) ) {
// if the method doesn't exist, then throw an exception
if ( !arguments.oEventHandler._actionExists( mdEntry.cacheFilter ) ) {
throw(
message = "CacheFilter expected a private method '#mdEntry.cacheFilter#'",
type = "HandlerInvalidCacheFilterException",
detail = "CacheFilter method '#mdEntry.cacheFilter#' does not exist in handler '#getMetaData( oEventHandler ).name#'. Please verify your cacheFilter annotation."
);
}
mdEntry.cacheFilter = arguments.oEventHandler._privateInvoker( mdEntry.cacheFilter, {} );
// if the cacheFilter isn't a closure, throw an exception
// We check for isClosure and isCustomFunction for ACF/Lucee compatibility
if (
!isClosure( mdEntry.cacheFilter ) &&
!isCustomFunction( mdEntry.cacheFilter )
) {
throw(
message = "CacheFilter expected a closure.",
type = "HandlerInvalidCacheFilterException",
detail = "Please verify your cacheFilter annotation in handler '#getMetaData( oEventHandler ).name# to ensure it returns a closure."
);
}
}
}
// end cache metadata is true
// Save md Entry in dictionary
variables.eventCacheDictionary[ cacheKey ] = mdEntry;
}
// end of md cache dictionary.
}
// end lock
}
// end if
return variables.eventCacheDictionary[ cacheKey ];
}
}