-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcoreLogic.js
1167 lines (1075 loc) · 47.3 KB
/
coreLogic.js
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
/**
* @module coreLogic
*/
import * as optlyHelper from './_helpers_/optimizelyHelper';
import RequestConfig from './_config_/requestConfig';
import defaultSettings from './_config_/defaultSettings';
import EventListeners from './_event_listeners_/eventListeners';
/**
* Optimizely Feature Variable Name for Settings: "cdnVariationSettings"
*
* This variable is crucial for configuring the behavior of GET requests during feature tests or targeted deliveries.
*
* cdnVariationSettings: {
* // The URL to match for GET requests to determine which experiment to apply, whether to return content directly
* // or forward the request to the origin.
* cdnExperimentURL: 'https://www.expedge.com/page/1',
*
* // The URL from which to fetch the variation content. This content can be served from origin or cache depending
* // on the cache configuration.
* cdnResponseURL: 'https://www.expedge.com/page/2',
*
* // Specifies the cache key for GET requests. Using "VARIATION_KEY" employs the combination of flagKey and
* // variationKey to create a unique cache key. If a custom value is provided, it will be used as the cache key.
* // Cache keys are constructed by appending a path segment to the fully qualified domain name of the request URL.
* cacheKey: 'VARIATION_KEY',
*
* // If true for GET requests, decisions made by Optimizely (e.g., which variation to serve) are forwarded to the
* // origin server as part of the request, encapsulated in cookies or headers. If the cdnResponseURL is a valid URL,
* // the request is forwarded to this URL instead of the original request URL.
* forwardRequestToOrigin: 'true',
*
* // If set to true, any requests that are forwarded to the origin are cached, optimizing subsequent requests for
* // the same content and reducing load on the origin server.
* cacheRequestToOrigin: 'true',
*
* // Indicates whether the settings being used are for the control group in an A/B test. When false, it implies that
* // the variation is experimental.
* isControlVariation: 'false'
* },
*/
/**
* The CoreLogic class is the core logic class for processing requests and managing Optimizely decisions.
* CoreLogic is shared across all CDN Adapters. CoreLogic utilizes the AbstractionHelper to abstract the request and response objects.
* It implements the following methods:
* - setCdnAdapter(cdnAdapter) - Sets the CDN provider for the instance.
* - getCdnAdapter() - Retrieves the current CDN provider.
* - processRequest(request, env, ctx) - Processes the incoming request, initializes configurations, and determines response based on
* operation type.
* - findMatchingConfig(requestURL, decisions, ignoreQueryParameters) - Searches for a CDN configuration that matches a given URL within an
* array of decision objects.
* - prepareDecisions(optlyResponse, flagsToForce, validStoredDecisions, requestConfig) - Prepares the decisions for the final response.
* - prepareFinalResponse(allDecisions, visitorId, requestConfig, serializedDecisions) - Prepares the final response based on the decisions.
* - shouldReturnJsonResponse() - Checks if the response should be returned in JSON format.
* - getIsDecideOperation(pathName) - Checks if the pathname indicates a decide operation.
* - getVisitorId(request, requestConfig) - Retrieves the visitor ID from the request.
* - retrieveDatafile(requestConfig, env) - Retrieves the datafile from the Optimizely CDN.
* - initializeOptimizely(datafile, visitorId, requestConfig, userAgent) - Initializes Optimizely with the retrieved datafile.
* - determineFlagsToDecide(requestConfig) - Determines which flags to force and which to decide based on the request.
* - optimizelyExecute(filteredFlagsToDecide, flagsToForce, requestConfig) - Executes the Optimizely logic and returns the decisions.
* - updateMetadata(requestConfig, flagsToForce, validStoredDecisions) - Updates the metadata for the request.
* - deleteAllUserContexts(decisions) - Deletes the userContext key from each decision object in the given array.
* - extractCdnSettings(decisions) - Maps an array of decisions to a new array of objects containing specific CDN settings.
* - getConfigForDecision(decisions, flagKey, variationKey) - Filters a provided array of decision settings to find a specific CDN
* configuration for an indivdual experiment
* based on flagKey and variationKey, then returns the specific variation's configuration.
*
*/
export default class CoreLogic {
/**
* Creates an instance of CoreLogic.
* @param {*} cdnAdapter - The CDN provider.
* @param {*} optimizelyProvider - The Optimizely provider.
*/
constructor(optimizelyProvider, env, ctx, sdkKey, abstractionHelper, kvStore, kvStoreUserProfile, logger) {
this.logger = logger;
this.logger.info(`CoreLogic instance created for SDK Key: ${sdkKey}`);
this.env = env;
this.ctx = ctx;
this.kvStore = kvStore || undefined;
this.sdkKey = sdkKey;
this.logger = logger;
this.abstractionHelper = abstractionHelper;
this.optimizelyProvider = optimizelyProvider;
this.kvStoreUserProfile = kvStoreUserProfile;
this.eventListeners = EventListeners.getInstance();
this.cdnAdapter = undefined;
this.reqResponseObjectType = 'response';
this.allDecisions = undefined;
this.serializedDecisions = undefined;
this.cdnExperimentSettings = undefined;
this.cdnExperimentURL = undefined;
this.cdnResponseURL = undefined;
this.forwardRequestToOrigin = undefined;
this.cacheKey = undefined;
this.isDecideOperation = undefined;
this.isPostMethod = undefined;
this.isGetMethod = undefined;
this.forwardToOrigin = undefined;
this.activeFlags = undefined;
this.savedCookieDecisions = undefined;
this.validCookiedDecisions = undefined;
this.invalidCookieDecisions = undefined;
this.datafileOperation = false;
this.configOperation = false;
this.request = undefined;
this.env = undefined;
this.ctx = undefined;
}
/**
* Sets the CDN provider for the instance.
* @param {string} provider - The name of the CDN provider to set.
*/
setCdnAdapter(cdnAdapter) {
this.cdnAdapter = cdnAdapter;
}
/**
* Retrieves the current CDN provider.
* @returns {string} The current CDN provider.
*/
getCdnAdapter() {
return this.setCdnAdapter;
}
/**
* Deletes the userContext key from each decision object in the given array.
* @param {Object[]} decisions - Array of decision objects.
*/
deleteAllUserContexts(decisions) {
return decisions;
if (this.requestConfig.trimmedDecisions === true) {
decisions.forEach((decision) => {
delete decision.userContext;
});
}
return decisions;
}
/**
* Maps an array of decisions to a new array of objects containing specific CDN settings.
* Each object includes the flagKey, variationKey, and nested CDN variables.
* @param {Object[]} decisions - Array of decision objects.
* @returns {Object[]} An array of objects structured by flagKey and variationKey with CDN settings.
*/
extractCdnSettings(decisions) {
this.logger.debugExt('Extracting CDN settings from decisions', decisions);
const result = decisions.map((decision) => {
const { flagKey, variationKey, variables } = decision;
const settings = variables.cdnVariationSettings || {};
const result = {
[flagKey]: {
[variationKey]: {
cdnExperimentURL: settings.cdnExperimentURL || undefined,
cdnResponseURL: settings.cdnResponseURL || undefined,
cacheKey: settings.cacheKey || undefined,
forwardRequestToOrigin:
(settings.forwardRequestToOrigin && settings.forwardRequestToOrigin === 'true') || false,
cacheRequestToOrigin: (settings.cacheRequestToOrigin && settings.cacheRequestToOrigin === 'true') || false,
isControlVariation: (settings.isControlVariation && settings.isControlVariation === 'true') || false,
},
},
};
return result;
});
this.logger.debugExt('CDN settings extracted: ', result);
return result;
}
/**
* Filters a provided array of decision settings to find a specific CDN configuration for an indivdual experiment
* based on flagKey and variationKey, then returns the specific variation's configuration.
* @param {Object[]} decisions - Array of decision objects structured by flagKey and variationKey.
* @param {string} flagKey - The flag key to filter by.
* @param {string} variationKey - The variation key to filter by.
* @returns {Object|undefined} The specific variation configuration or undefined if not found.
*/
async getConfigForDecision(decisions, flagKey, variationKey) {
const filtered = decisions.find(
(decision) => decision.hasOwnProperty(flagKey) && decision[flagKey].hasOwnProperty(variationKey)
);
return filtered ? filtered[flagKey][variationKey] : undefined;
}
/**
* Processes an array of decision objects by removing the userContext and extracting CDN settings.
* This method first deletes the userContext from each decision object, then extracts specific CDN settings
* based on the presence of the cdnVariationSettings variable.
* @param {Object[]} decisions - Array of decision objects.
* @returns {Object[]} An array of objects structured by flagKey and variationKey with CDN settings.
*/
processDecisions(decisions) {
let result = this.deleteAllUserContexts(decisions); // Remove userContext from all decision objects
result = this.extractCdnSettings(result); // Extract and return CDN settings
return result; // Extract and return CDN settings
}
/**
* Sets the class properties based on the CDN configuration found.
* @param {Object} cdnConfig - The CDN configuration object.
* @param {string} flagKey - The flag key associated with the configuration.
* @param {string} variationKey - The variation key associated with the configuration.
*/
setCdnConfigProperties(cdnConfig, flagKey, variationKey) {
this.cdnExperimentURL = cdnConfig.cdnExperimentURL;
this.cdnResponseURL = cdnConfig.cdnResponseURL;
this.cacheKey = cdnConfig.cacheKey;
this.forwardRequestToOrigin = cdnConfig.forwardRequestToOrigin;
this.activeVariation = variationKey;
this.activeFlag = flagKey;
cdnConfig.flagKey = flagKey;
cdnConfig.variationKey = variationKey;
}
/**
* Removes extra slashes from the URL.
* @param {string} url - The URL to remove extra slashes from.
* @returns {string} The URL with extra slashes removed.
*/
removeExtraSlashes(url) {
// Keep https:// intact, then replace any occurrence of multiple slashes with a single slash
return url.replace(/(https?:\/\/)|(\/)+/g, '$1$2');
}
/**
* Searches for a CDN configuration that matches a given URL within an array of decision objects.
* It compares the request URL against each cdnExperimentURL, optionally ignoring query parameters based on the flag.
* Efficiently compares URLs and caches matched configuration data for quick access.
* @param {string} requestURL - The URL to match against cdnExperimentURLs in the decisions data.
* @param {Array} decisions - The array of decision objects to search within.
* @param {boolean} [ignoreQueryParameters=true] - Whether to ignore query parameters in the URL during comparison.
* @returns {Object|null} The first matching CDN configuration object, or null if no match is found.
*/
async findMatchingConfig(requestURL, decisions, ignoreQueryParameters = true) {
this.logger.debug(`Searching for matching CDN configuration for URL: ${requestURL}`);
// Process decisions to prepare them for comparison
const processedDecisions = this.processDecisions(decisions);
const url = this.abstractionHelper.abstractRequest.getNewURL(requestURL);
// Ensure the URL uses HTTPS
if (url.protocol !== 'https:') {
url.protocol = 'https:';
}
const testFlagKey =
this.env.LOG_LEVEL === 'debug' && this.env.TESTING_FLAG_DEBUG && this.env.TESTING_FLAG_DEBUG.trim() !== ''
? this.env.TESTING_FLAG_DEBUG.trim()
: null;
// Remove query parameters if needed
if (ignoreQueryParameters) {
url.search = '';
}
// Normalize the pathname by removing a trailing '/' if present
const normalizedPathname = url.pathname.endsWith('/') ? url.pathname.slice(0, -1) : url.pathname;
// Construct a comparison URL string and remove extra slashes
const compareOriginAndPath = this.removeExtraSlashes(url.origin + normalizedPathname);
// Log the normalized URL to be compared
this.logger.debug(`Normalized URL for comparison: ${compareOriginAndPath}`);
// Iterate through decisions to find a matching CDN configuration
for (let decision of processedDecisions) {
for (let flagKey in decision) {
for (let variationKey in decision[flagKey]) {
const cdnConfig = decision[flagKey][variationKey];
if (cdnConfig && cdnConfig.cdnExperimentURL) {
// Normalize the CDN URL for comparison
const cdnUrl = this.abstractionHelper.abstractRequest.getNewURL(cdnConfig.cdnExperimentURL);
if (ignoreQueryParameters) {
cdnUrl.search = '';
}
const cdnNormalizedPathname = cdnUrl.pathname.endsWith('/')
? cdnUrl.pathname.slice(0, -1)
: cdnUrl.pathname;
// Remove extra slashes from the target URL
const targetUrl = this.removeExtraSlashes(cdnUrl.origin + cdnNormalizedPathname);
// Update cdnConfig with normalized URLs
cdnConfig.cdnExperimentURL = this.removeExtraSlashes(cdnConfig.cdnExperimentURL);
if (cdnConfig.cdnResponseURL) {
cdnConfig.cdnResponseURL = this.removeExtraSlashes(cdnConfig.cdnResponseURL);
}
// Log the comparison details
this.logger.debug('Comparing URL: ' + compareOriginAndPath + ' with ' + targetUrl);
// Compare the normalized URLs
if (compareOriginAndPath === targetUrl || (testFlagKey && testFlagKey === flagKey)) {
this.logger.debug(
`Match found for URL: ${requestURL}. Flag Key: ${flagKey}, Variation Key: ${variationKey}, CDN Config: ${cdnConfig}`
);
this.setCdnConfigProperties(cdnConfig, flagKey, variationKey);
return cdnConfig;
}
}
}
}
}
// Return null if no matching configuration is found
this.logger.debug('No matching configuration found in cdnVariationSettings [findMatchingConfig]');
return null;
}
/**
* Processes the incoming request, initializes configurations, and determines response based on operation type.
* Handles both POST and GET requests differently based on the decision operation flag.
* @param {Request} request - The incoming request object.
* @param {Object} env - The environment configuration.
* @param {Object} ctx - Context for execution.
* @returns {Promise<Object>} - A promise that resolves to an object containing the response and any CDN experiment settings.
*/
async processRequest(request, env, ctx) {
this.eventListeners = EventListeners.getInstance();
this.logger.info('Entering processRequest [coreLogic.js]');
try {
let reqResponse;
this.env = this.abstractionHelper.env;
this.ctx = this.abstractionHelper.ctx;
this.request = this.abstractionHelper.abstractRequest.request;
// Initialize request configuration and check operation type
const requestConfig = new RequestConfig(
this.request,
this.env,
this.ctx,
this.cdnAdapter,
this.abstractionHelper
);
this.logger.debug('RequestConfig initialized');
await requestConfig.initialize(request);
// this.logger.debugExt('RequestConfig: ', requestConfig);
this.requestConfig = requestConfig;
// Get the pathname and check if it starts with "//"
this.pathName = requestConfig.url.pathname.toLowerCase();
this.href = requestConfig.url.href.toLowerCase();
if (this.pathName.startsWith('//')) {
this.pathName = this.pathName.substring(1);
}
// Check the operation type
const isDecideOperation = this.getIsDecideOperation(this.pathName);
this.logger.debug(`Is Decide Operation: ${isDecideOperation}`);
this.datafileOperation = this.pathName === '/v1/datafile';
this.configOperation = this.pathName === '/v1/config';
this.httpMethod = request.method;
this.isPostMethod = this.httpMethod === 'POST';
this.isGetMethod = this.httpMethod === 'GET';
// Clone the request
// this.request = this.abstractionHelper.abstractRequest.cloneRequest(request);
// Get visitor ID, datafile, and user agent
const visitorId = await this.getVisitorId(request, requestConfig);
const datafile = await this.retrieveDatafile(requestConfig, env);
// If datafile is null, return origin content immediately
if (!datafile) {
this.logger.debug('Datafile is null. Returning origin content.');
return {
reqResponse: 'NO_MATCH',
cdnExperimentSettings: undefined,
reqResponseObjectType: 'response',
forwardRequestToOrigin: true,
errorMessage: 'Datafile retrieval failed',
isError: false,
isPostMethod: this.isPostMethod,
isGetMethod: this.isGetMethod,
isDecideOperation: this.isDecideOperation,
isDatafileOperation: this.datafileOperation,
isConfigOperation: this.configOperation,
flagsToDecide: [],
flagsToForce: [],
validStoredDecisions: [],
href: this.href,
pathName: this.pathName,
};
}
const userAgent = requestConfig.getHeader('User-Agent');
// Initialize Optimizely with the retrieved datafile
const initSuccess = await this.initializeOptimizely(datafile, visitorId, requestConfig, userAgent);
if (!initSuccess) throw new Error('Failed to initialize Optimizely');
this.eventListenersResult = await this.eventListeners.trigger(
'beforeDetermineFlagsToDecide',
request,
requestConfig
);
// Process decision flags if required
let flagsToForce, filteredFlagsToDecide, validStoredDecisions;
if (isDecideOperation) {
({ flagsToForce, filteredFlagsToDecide, validStoredDecisions } = await this.determineFlagsToDecide(
requestConfig
));
this.logger.debugExt(
'Flags to decide:',
filteredFlagsToDecide,
'Flags to force:',
flagsToForce,
'Valid stored decisions:',
validStoredDecisions
);
}
this.eventListenersResult = await this.eventListeners.trigger(
'afterDetermineFlagsToDecide',
request,
requestConfig,
flagsToForce,
filteredFlagsToDecide,
validStoredDecisions
);
// Execute Optimizely logic and prepare responses based on the request method
this.logger.debug('Executing Optimizely logic and preparing responses based on the request method');
const optlyResponse = await this.optimizelyExecute(filteredFlagsToDecide, flagsToForce, requestConfig);
this.logger.debug(`Optimizely processing completed [optimizelyExecute]`);
this.logger.debugExt('Optimizely response: ', optlyResponse);
// Prepare the response based on the operation type
if (this.shouldReturnJsonResponse(this) && !isDecideOperation) {
// Datafile or config operation
reqResponse = await this.cdnAdapter.getNewResponseObject(optlyResponse, 'application/json', true);
this.reqResponseObjectType = 'response';
} else if (this.isPostMethod && !isDecideOperation) {
// POST method without decide operation
reqResponse = await this.cdnAdapter.getNewResponseObject(optlyResponse, 'application/json', true);
this.cdnExperimentSettings = undefined;
this.reqResponseObjectType = 'response';
} else if (this.isDecideOperation) {
// Update metadata if enabled
if (isDecideOperation) this.updateMetadata(requestConfig, flagsToForce, validStoredDecisions);
// Look for a matching configuration in the cdnVariationSettings variable since this is a GET request
if (this.isGetMethod && isDecideOperation)
this.cdnExperimentSettings = await this.findMatchingConfig(
request.url,
optlyResponse,
defaultSettings.urlIgnoreQueryParameters
);
if (this.isGetMethod && isDecideOperation && !this.cdnExperimentSettings) {
reqResponse = 'NO_MATCH';
} else {
// Prepare decisions and final response
this.serializedDecisions = await this.prepareDecisions(
optlyResponse,
flagsToForce,
validStoredDecisions,
requestConfig
);
reqResponse = await this.prepareFinalResponse(
this.allDecisions,
visitorId,
requestConfig,
this.serializedDecisions
);
}
}
// Package the final response
return {
reqResponse,
cdnExperimentSettings: this.cdnExperimentSettings,
reqResponseObjectType: this.reqResponseObjectType,
forwardRequestToOrigin: this.forwardRequestToOrigin,
errorMessage: undefined,
isError: false,
isPostMethod: this.isPostMethod,
isGetMethod: this.isGetMethod,
isDecideOperation: this.isDecideOperation,
isDatafileOperation: this.datafileOperation,
isConfigOperation: this.configOperation,
flagsToDecide: filteredFlagsToDecide,
flagsToForce: flagsToForce,
validStoredDecisions: validStoredDecisions,
href: this.href,
pathName: this.pathName,
};
} catch (error) {
// Handle any errors during the process, returning a server error response
this.logger.error('Error processing request:', error.message);
return {
reqResponse: await this.cdnAdapter.getNewResponseObject(
`Internal Server Error: ${error.message}`,
'text/html',
false,
500
),
cdnExperimentSettings: undefined,
reqResponseObjectType: 'response',
forwardRequestToOrigin: this.forwardRequestToOrigin,
errorMessage: error.message,
isError: true,
};
}
}
shouldReturnJsonResponse() {
return (
(this.datafileOperation || this.configOperation || this.trackOperation || this.sendOdpEventOperation) &&
!this.isDecideOperation
);
}
/**
* Handles POST decisions based on the request URL path.
* @param {string[]} flagsToDecide - An array of flags to decide.
* @param {RequestConfig} requestConfig - The request configuration object.
* @returns {Promise<Object|null>} - The decisions object or null.
*/
async handlePostOperations(flagsToDecide, flagsToForce, requestConfig) {
switch (this.pathName) {
case '/v1/decide':
this.eventListenersResult = await this.eventListeners.trigger(
'beforeDecide',
this.request,
requestConfig,
flagsToDecide,
flagsToForce
);
this.logger.debug('POST operation [/v1/decide]: Decide');
let result = await this.optimizelyProvider.decide(flagsToDecide, flagsToForce, requestConfig.forcedDecisions);
this.eventListenersResult = await this.eventListeners.trigger(
'afterDecide',
this.request,
requestConfig,
result
);
return result;
case '/v1/track':
this.logger.debug('POST operation [/v1/track]: Track');
this.trackOperation = true;
if (requestConfig.eventKey && typeof requestConfig.eventKey === 'string') {
let result = await this.optimizelyProvider.track(
requestConfig.eventKey,
requestConfig.attributes,
requestConfig.eventTags
);
if (!result) {
result = {
message: 'Conversion event was dispatched to Optimizely.',
attributes: requestConfig.attributes,
eventTags: requestConfig.eventTags,
status: 200,
};
return result;
}
result = {
message: 'An unknown internal error has occurred.',
status: 500,
};
return result;
} else {
return await this.cdnAdapter.getNewResponseObject(
'Invalid or missing event key. An event key is required for tracking conversions.',
'text/html',
false,
400
);
}
case '/v1/datafile':
this.logger.debug('POST operation [/v1/datafile]: Datafile');
const datafileObj = await this.optimizelyProvider.datafile();
this.datafileOperation = true;
if (requestConfig.enableResponseMetadata) {
return { datafile: datafileObj, metadata: requestConfig.configMetadata };
}
return datafileObj;
case '/v1/config':
this.logger.debug('POST operation [/v1/config]: Config');
const configObj = await this.optimizelyProvider.config();
this.configOperation = true;
if (requestConfig.enableResponseMetadata) {
return { config: configObj, metadata: requestConfig.configMetadata };
}
return { config: configObj };
case '/v1/batch':
this.logger.debug('POST operation [/v1/batch]: Batch');
await this.optimizelyProvider.batch();
this.batchOperation = true;
return null;
case '/v1/send-odp-event':
this.logger.debug('POST operation [/v1/send-odp-event]: Send ODP Event');
await this.optimizelyProvider.sendOdpEvent();
this.sendOdpEventOperation = true;
return null;
default:
throw new Error(`URL Endpoint Not Found: ${this.pathName}`);
}
}
/**
* Executes decisions for the flags.
* @param {string[]} flagsToDecide - An array of flags to decide.
* @param {RequestConfig} requestConfig - The request configuration object.
* @returns {Promise<Object>} - The decisions object.
*/
async optimizelyExecute(flagsToDecide, flagsToForce, requestConfig) {
if (this.httpMethod === 'POST' || this.datafileOperation || this.configOperation) {
this.logger.debug('Handling POST operations [handlePostOperations]');
return await this.handlePostOperations(flagsToDecide, flagsToForce, requestConfig);
} else {
this.logger.debug('Handling GET operations [optimizelyExecute]');
return await this.optimizelyProvider.decide(flagsToDecide, flagsToForce);
}
}
/**
* Retrieves the Optimizely datafile from KV storage or CDN based on configuration.
* This function attempts to retrieve the datafile first from KV storage if enabled, and falls back to CDN if not found or not enabled.
*
* @param {Object} requestConfig - Configuration object containing settings and metadata for retrieval.
* @param {Object} env - The environment object, typically including access to storage and other resources.
* @returns {Promise<string>} A promise that resolves to the datafile string, or throws an error if unable to retrieve.
*/
async retrieveDatafile(requestConfig, env) {
this.logger.debug('Retrieving datafile [retrieveDatafile]');
try {
// Prioritize KV storage if enabled in settings
if (requestConfig.datafileFromKV) {
const datafile = await this.cdnAdapter.getDatafileFromKV(requestConfig.sdkKey, this.kvStore);
if (datafile) {
this.logger.debug('Datafile retrieved from KV storage');
if (requestConfig.enableResponseMetadata) {
requestConfig.configMetadata.datafileFrom = 'KV Storage';
}
return datafile;
}
this.logger.error('Datafile not found in KV Storage; falling back to CDN.');
}
// Fallback to CDN if KV storage is not enabled or datafile is not found
const datafileFromCDN = await this.cdnAdapter.getDatafile(requestConfig.sdkKey, 600);
if (datafileFromCDN) {
this.logger.debug('Datafile retrieved from CDN');
if (requestConfig.enableResponseMetadata) {
requestConfig.configMetadata.datafileFrom = 'CDN';
}
return datafileFromCDN;
} else {
this.logger.error(`Failed to retrieve datafile from CDN with sdkKey: ${requestConfig.sdkKey}`);
throw new Error('Unable to retrieve the required datafile.');
}
} catch (error) {
// Log and rethrow error to be handled by the caller
this.logger.error('Error retrieving datafile:', error.message);
return null;
//throw new Error(`Datafile retrieval error: ${error.message}`);
}
}
/**
* Initializes the Optimizely instance.
* @param {Object} datafile - The Optimizely datafile object.
* @param {string} visitorId - The visitor ID.
* @param {RequestConfig} requestConfig - The request configuration object.
* @param {string} userAgent - The user agent string.
* @returns {Promise<boolean>} - True if initialization was successful, false otherwise.
*/
async initializeOptimizely(datafile, visitorId, requestConfig, userAgent) {
return await this.optimizelyProvider.initializeOptimizely(
datafile,
visitorId,
requestConfig.decideOptions,
requestConfig.attributes,
requestConfig.eventTags,
requestConfig.datafileAccessToken,
userAgent,
this.sdkKey
);
}
getIsDecideOperation(pathName) {
if (this.isDecideOperation !== undefined) return this.isDecideOperation;
const result = !['/v1/config', '/v1/datafile', '/v1/track', '/v1/batch'].includes(pathName);
this.isDecideOperation = result;
return result;
}
/**
* Determines the flags to decide and handles stored decisions.
* @param {RequestConfig} requestConfig - The request configuration object.
* @returns {Promise<{flagsToDecide: string[], validStoredDecisions: Object[]}>}
*/
async determineFlagsToDecide(requestConfig) {
this.logger.debug('Determining flags to decide [determineFlagsToDecide]');
try {
const flagKeys = (await this.retrieveFlagKeys(requestConfig)) || (await this.optimizelyProvider.getActiveFlags());
const activeFlags = await this.optimizelyProvider.getActiveFlags();
const isDecideOperation = this.getIsDecideOperation(this.pathName);
if (!isDecideOperation) {
return;
}
const decisions = await this.handleCookieDecisions(requestConfig, activeFlags, this.httpMethod);
const { validStoredDecisions } = decisions;
if (!isDecideOperation) return;
const flagsToDecide = this.calculateFlagsToDecide(requestConfig, flagKeys, validStoredDecisions, activeFlags);
// spread operator for returning { flagsToForce, filteredFlagsToDecide };
return { ...flagsToDecide, validStoredDecisions };
} catch (error) {
this.logger.error('Error in determineFlagsToDecide:', error);
throw error;
}
}
/**
* Handle cookie-based decisions from request.
*/
async handleCookieDecisions(requestConfig, activeFlags, httpMethod) {
this.logger.debug('Handling cookie decisions [handleCookieDecisions]');
let savedCookieDecisions = [];
let validStoredDecisions = [];
let invalidCookieDecisions = [];
if (httpMethod === 'POST') {
return { savedCookieDecisions, validStoredDecisions, invalidCookieDecisions };
}
this.eventListenersResult = await this.eventListeners.trigger(
'beforeReadingCookie',
this.request,
requestConfig.headerCookiesString
);
if (requestConfig.headerCookiesString && !this.isPostMethod) {
try {
const tempCookie = optlyHelper.getCookieValueByName(
requestConfig.headerCookiesString,
requestConfig.settings.decisionsCookieName
);
savedCookieDecisions = optlyHelper.deserializeDecisions(tempCookie);
validStoredDecisions = optlyHelper.getValidCookieDecisions(savedCookieDecisions, activeFlags);
invalidCookieDecisions = optlyHelper.getInvalidCookieDecisions(savedCookieDecisions, activeFlags);
} catch (error) {
this.logger.error('Error while handling stored cookie decisions:', error);
}
}
this.eventListenersResult = await this.eventListeners.trigger(
'afterReadingCookie',
this.request,
savedCookieDecisions,
validStoredDecisions,
invalidCookieDecisions
);
if (this.eventListenersResult) {
savedCookieDecisions = this.eventListenersResult.savedCookieDecisions || savedCookieDecisions;
validStoredDecisions = this.eventListenersResult.validStoredDecisions || validStoredDecisions;
invalidCookieDecisions = this.eventListenersResult.invalidCookieDecisions || invalidCookieDecisions;
}
return { savedCookieDecisions, validStoredDecisions, invalidCookieDecisions };
}
/**
* Calculate flags to decide based on request config and stored decisions.
*/
calculateFlagsToDecide(requestConfig, flagKeys, validStoredDecisions, activeFlags) {
this.logger.debug('Calculating flags to decide [calculateFlagsToDecide]');
const validFlagKeySet = new Set(flagKeys);
let flagsToForce = requestConfig.overrideVisitorId
? []
: validStoredDecisions.filter((decision) => validFlagKeySet.has(decision.flagKey));
let filteredFlagsToDecide = flagKeys.filter((flag) => activeFlags.includes(flag));
if (requestConfig.decideAll || (flagKeys.length === 0 && flagsToForce.length === 0)) {
filteredFlagsToDecide = [...activeFlags];
}
return { flagsToForce, filteredFlagsToDecide };
}
/**
* Filters valid decisions from the result flags.
* @param {Object[]} validCookieDecisions - An array of valid stored decisions.
* @param {string[]} filteredFlagsToDecide - An array of flags that need a new decision.
* @param {boolean} isPostMethod - Whether the request method is POST.
* @returns {string[]} - An array of valid flags to decide.
*/
filterValidDecisions(validCookieDecisions, filteredFlagsToDecide, isPostMethod) {
if (
isPostMethod ||
!optlyHelper.arrayIsValid(validCookieDecisions) ||
!optlyHelper.arrayIsValid(filteredFlagsToDecide)
) {
return filteredFlagsToDecide;
}
const validFlagSet = new Set(validCookieDecisions.map((decision) => decision.flagKey));
return filteredFlagsToDecide.filter((flag) => !validFlagSet.has(flag));
}
/**
* Updates the request configuration metadata.
* @param {RequestConfig} requestConfig - The request configuration object.
* @param {string[]} flagsToDecide - An array of flags to decide.
* @param {Object[]} validStoredDecisions - An array of valid stored decisions.
*/
updateMetadata(requestConfig, flagsToDecide, validStoredDecisions, cdnVariationSettings) {
if (requestConfig.enableResponseMetadata) {
requestConfig.configMetadata.flagKeysDecided = flagsToDecide;
requestConfig.configMetadata.savedCookieDecisions = validStoredDecisions;
requestConfig.configMetadata.agentServerMode = requestConfig.method === 'POST';
requestConfig.configMetadata.pathName = requestConfig.url.pathname.toLowerCase();
requestConfig.configMetadata.cdnVariationSettings = cdnVariationSettings;
}
}
/**
* Prepares the decisions for the response.
* @param {Object[]} decisions - The decisions object array.
* @param {Object[]} flagsToForce - An array of stored flag keys and corresponding decisions that must be forced as user profile.
* @param {Object[]} validStoredDecisions - An array of valid stored decisions.
* @param {RequestConfig} requestConfig - The request configuration object.
* @returns {Promise<string|null>} - The serialized decisions string or null.
*/
async prepareDecisions(decisions, flagsToForce, validStoredDecisions, requestConfig) {
this.logger.debug(`Preparing decisions for response with method: ${this.httpMethod}`);
if (decisions) {
this.allDecisions = optlyHelper.getSerializedArray(
decisions,
// flagsToForce,
requestConfig.excludeVariables,
requestConfig.includeReasons,
requestConfig.enabledFlagsOnly,
requestConfig.trimmedDecisions,
this.httpMethod
);
}
if (optlyHelper.arrayIsValid(this.allDecisions)) {
// if (validStoredDecisions) this.allDecisions = this.allDecisions.concat(validStoredDecisions);
let serializedDecisions = optlyHelper.serializeDecisions(this.allDecisions);
if (serializedDecisions) {
serializedDecisions = optlyHelper.safelyStringifyJSON(serializedDecisions);
}
this.logger.debugExt('Serialized decisions [prepareDecisions]: ', serializedDecisions);
return serializedDecisions;
}
return null;
}
/**
* Retrieves flag keys from various sources based on request configuration.
* The method prioritizes KV storage, then URL query parameters, and lastly the request body for POST methods.
*
* @param {Object} requestConfig - Configuration object containing settings and metadata.
* @returns {Promise<Array>} - A promise that resolves to an array of flag keys.
*/
async retrieveFlagKeys(requestConfig) {
this.logger.debug('Retrieving flag keys [retrieveFlagKeys]');
try {
let flagKeys = [];
// Retrieve flags from KV storage if configured
if (this.kvStore && (requestConfig.settings.flagsFromKV || requestConfig.enableFlagsFromKV)) {
const flagsFromKV = await this.cdnAdapter.getFlagsFromKV(this.kvStore);
if (flagsFromKV) {
this.logger.debug('Flag keys retrieved from KV storage');
flagKeys = await optlyHelper.splitAndTrimArray(flagsFromKV);
if (requestConfig.enableResponseMetadata) {
requestConfig.configMetadata.flagKeysFrom = 'KV Storage';
}
}
}
// Fallback to URL query parameters if no valid flags from KV
if (!optlyHelper.arrayIsValid(flagKeys)) {
flagKeys = requestConfig.flagKeys || [];
this.logger.debug('Flag keys retrieved from URL query parameters');
if (requestConfig.enableResponseMetadata && flagKeys.length > 0) {
requestConfig.configMetadata.flagKeysFrom = 'Query Parameters';
}
}
// Check for flag keys in request body if POST method and no valid flags from previous sources
if (
requestConfig.method === 'POST' &&
!optlyHelper.arrayIsValid(flagKeys) &&
requestConfig.body?.flagKeys?.length > 0
) {
flagKeys = await optlyHelper.trimStringArray(requestConfig.body.flagKeys);
this.logger.debug('Flag keys retrieved from request body');
if (requestConfig.enableResponseMetadata) {
requestConfig.configMetadata.flagKeysFrom = 'Body';
}
}
this.logger.debug(`Flag keys retrieved [retrieveFlagKeys]: ${flagKeys}`);
return flagKeys;
} catch (error) {
this.logger.error('Error retrieving flag keys [retrieveFlagKeys]:', error);
throw new Error(`Failed to retrieve flag keys: ${error.message}`);
}
}
/**
* Retrieves the visitor ID from the request, cookie, or generates a new one.
* Additionally, tracks the source of the visitor ID and stores this information
* in the configuration metadata.
* @param {Request} request - The incoming request object.
* @param {RequestConfig} requestConfig - The request configuration object.
* @returns {Promise<string>} - The visitor ID.
*/
async getVisitorId(request, requestConfig) {
this.logger.debug('Retrieving visitor ID [getVisitorId]');
let visitorId = requestConfig.visitorId;
let visitorIdSource = 'request-visitor'; // Default source
if (requestConfig.overrideVisitorId) {
this.logger.debug('Overriding visitor ID');
const result = await this.overrideVisitorId(requestConfig);
this.logger.debug(`Visitor ID overridden to: ${result}`);
return result;
}
if (!visitorId) {
[visitorId, visitorIdSource] = await this.retrieveOrGenerateVisitorId(request, requestConfig);
}
this.storeVisitorIdMetadata(requestConfig, visitorId, visitorIdSource);
this.logger.debug(`Visitor ID retrieved: ${visitorId}`);
return visitorId;
}
/**
* Overrides the visitor ID by generating a new UUID.
* @param {RequestConfig} requestConfig - The request configuration object.
* @returns {Promise<string>} - The new visitor ID.
*/
async overrideVisitorId(requestConfig) {
const visitorId = await optlyHelper.generateUUID();
requestConfig.configMetadata.visitorId = visitorId;
requestConfig.configMetadata.visitorIdFrom = 'override-visitor';
return visitorId;
}
/**
* Retrieves a visitor ID from a cookie or generates a new one if not found.
* @param {Request} request - The request object.
* @param {RequestConfig} requestConfig - The request configuration object.
* @returns {Promise<[string, string]>} - A tuple of the visitor ID and its source.
*/
async retrieveOrGenerateVisitorId(request, requestConfig) {
let visitorId = this.cdnAdapter.getRequestCookie(request, requestConfig.settings.visitorIdCookieName);
let visitorIdSource = visitorId ? 'cookie-visitor' : 'cdn-generated-visitor';
if (!visitorId) {
visitorId = await optlyHelper.generateUUID();
}
return [visitorId, visitorIdSource];
}
/**
* Stores visitor ID and its source in the configuration metadata if enabled.
* @param {RequestConfig} requestConfig - The request configuration object.
* @param {string} visitorId - The visitor ID.
* @param {string} visitorIdSource - The source from which the visitor ID was retrieved or generated.
*/
storeVisitorIdMetadata(requestConfig, visitorId, visitorIdSource) {
if (requestConfig.enableResponseMetadata) {
requestConfig.configMetadata.visitorId = visitorId;
requestConfig.configMetadata.visitorIdFrom = visitorIdSource;
}
}
/**
* Prepares the response object with decisions and headers/cookies.
* @param {Object|string} decisions - The decisions object or a string.
* @param {string} visitorId - The visitor ID.
* @param {string} serializedDecisions - The serialized decisions string.
* @param {RequestConfig} requestConfig - The request configuration object.
* @returns {Promise<Response>} - The response object.
*/
async prepareResponse(decisions, visitorId, serializedDecisions, requestConfig) {
this.logger.debug('Preparing response [prepareResponse]');
try {
const isEmpty = Array.isArray(decisions) && decisions.length === 0;
const responseDecisions = isEmpty ? 'NO_DECISIONS' : decisions;
if (this.shouldForwardToOrigin()) {
this.logger.debug('Forwarding request to origin [prepareResponse]');
return this.handleOriginForwarding(visitorId, serializedDecisions, requestConfig);
} else {
this.logger.debug('Preparing local response [prepareResponse]');
this.reqResponseObjectType = 'response';
return this.prepareLocalResponse(responseDecisions, visitorId, serializedDecisions, requestConfig);
}
} catch (error) {
this.logger.error('Error in prepareResponse:', error);
throw error;
}
}