Skip to content

Commit 0d19fe0

Browse files
committed
Updates to clone request
1 parent 205aa7e commit 0d19fe0

File tree

11 files changed

+129
-105
lines changed

11 files changed

+129
-105
lines changed

.vscode/launch.json

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,4 @@
11
{
2-
// Use IntelliSense to learn about possible attributes.
3-
// Hover to view descriptions of existing attributes.
4-
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
52
"version": "0.2.0",
63
"configurations": [
74
{

src/_config_/cookieOptions.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/**
2-
* @module CookieOptions
2+
* @module cookieOptions
33
*
44
* The CookieOptions specifies the default options for the cookies. *
55
*/

src/_config_/defaultSettings.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,3 +39,10 @@ const defaultSettings = {
3939
};
4040

4141
export default defaultSettings;
42+
43+
// const defaultSettings = {
44+
// kv_namespace: 'OPTLY_HYBRID_AGENT_KV',
45+
// kv_key_optly_flagKeys: 'optly_flagKeys',
46+
// kv_key_optly_sdk_datafile: 'optly_sdk_datafile',
47+
// kv_namespace_user_profile: 'OPTLY_HYBRID_AGENT_UPS_KV',
48+
// };

src/_config_/requestConfig.js

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,14 @@ export default class RequestConfig {
110110
await this.loadRequestBody(request);
111111
}
112112

113+
if (!this.enableFlagsFromKV) {
114+
this.enableFlagsFromKV = this.settings.flagsFromKV;
115+
}
116+
117+
if (!this.enableDatafileFromKV) {
118+
this.enableDatafileFromKV = this.settings.datafileFromKV;
119+
}
120+
113121
// Set metadata properties if response metadata is enabled and values are available.
114122
if (this.sdkKey && this.settings.enableResponseMetadata) {
115123
this.configMetadata.sdkKey = this.sdkKey;
@@ -349,8 +357,8 @@ export default class RequestConfig {
349357
if (this.body.eventTags && this.settings.enableResponseMetadata) this.configMetadata.eventTagsFrom = 'body';
350358
this.enableResponseMetadata = this.enableResponseMetadata || this.body.enableResponseMetadata;
351359
this.forcedDecisions = this.body.forcedDecisions;
352-
this.enableFlagsFromKV = this.enableFlagsFromKV || this.body.enableFlagsFromKV;
353-
this.datafileFromKV = this.datafileFromKV || this.body.datafileFromKV;
360+
this.enableFlagsFromKV = this.enableFlagsFromKV || this.body.enableFlagsFromKV === true;
361+
this.datafileFromKV = this.datafileFromKV || this.body.datafileFromKV === true;
354362
this.decideAll = this.decideAll || this.body.decideAll;
355363
this.disableDecisionEvent = this.disableDecisionEvent || this.body.disableDecisionEvent;
356364
this.enabledFlagsOnly = this.enabledFlagsOnly || this.body.enabledFlagsOnly;

src/_helpers_/abstraction-classes/abstractRequest.js

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -448,7 +448,18 @@ export class AbstractRequest {
448448
case 'fastly':
449449
case 'vercel':
450450
// For these CDNs, the Fetch API's clone method should work.
451-
return request.clone();
451+
const newRequestInit = {
452+
method: request.method,
453+
headers: new Headers(request.headers), // Clone existing headers
454+
body: request.body,
455+
mode: request.mode,
456+
credentials: request.credentials,
457+
cache: request.cache,
458+
redirect: request.redirect,
459+
referrer: request.referrer,
460+
integrity: request.integrity,
461+
};
462+
return new Request(request.url, newRequestInit);
452463

453464
case 'cloudfront':
454465
// CloudFront Lambda@Edge specific cloning logic
@@ -659,6 +670,7 @@ export class AbstractRequest {
659670
* @returns {Promise<Response>} - The response from the fetch operation.
660671
*/
661672
static async fetchRequest(input, options = {}) {
673+
try {
662674
logger().debugExt('AbstractRequest - Making HTTP request [fetchRequest]');
663675
let url;
664676
let requestOptions = options;
@@ -707,7 +719,12 @@ export class AbstractRequest {
707719
case 'vercel':
708720
return await fetch(new Request(url, requestOptions));
709721
default:
710-
throw new Error('Unsupported CDN provider.');
722+
throw new Error('Unsupported CDN provider.');
723+
}
724+
} catch (error) {
725+
logger().error('Error fetching request:', error.message);
726+
const _asbstractionHelper = AbstractionHelper.getAbstractionHelper();
727+
return _asbstractionHelper.createResponse({ error: error.message }, 500);
711728
}
712729
}
713730

src/_helpers_/optimizelyHelper.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -497,6 +497,7 @@ export function getValidCookieDecisions(decisions, activeFlags) {
497497
return decisions.filter((decision) => activeFlagsSet.has(decision.flagKey));
498498
}
499499

500+
500501
/**
501502
* Serializes an array of decision objects into a string.
502503
* @param {Object[]} decisions - The array of decision objects.

src/_optimizely_/optimizelyProvider.js

Lines changed: 1 addition & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -22,37 +22,6 @@ let globalOptimizelyClient = undefined;
2222
let globalKVStore = undefined;
2323
let globalKVStoreUserProfile = undefined;
2424

25-
// const userProfileService = {
26-
// // Adapter that provides helpers to read and write from KV Store
27-
// UPS_LS_PREFIX: 'optly-ups-data',
28-
// kvStorageAdapter: {
29-
// read: async function(key) {
30-
// let userProfileData = await kvStore.get(key);
31-
// if (userProfileData) {
32-
// userProfileData = JSON.parse(userProfileData);
33-
// return optlyHelper.isValidObject(userProfileData, true);
34-
// }
35-
// return {};
36-
// },
37-
// write: async function(key, data) {
38-
// let userProfileData = optlyHelper.isValidObject(data, true);
39-
// await kvStore.put(key, JSON.stringify(userProfileData));
40-
// },
41-
// },
42-
// getUserKey: function (userId) {
43-
// return `${this.UPS_LS_PREFIX}-${userId}`;
44-
// },
45-
// // Perform user profile lookup
46-
// lookup: function(userId) {
47-
// return this.kvStorageAdapter.read(this.getUserKey(userId));
48-
// },
49-
// // Persist user profile
50-
// save: async function(userProfileMap) {
51-
// const userKey = this.getUserKey(userProfileMap.user_id);
52-
// await this.kvStorageAdapter.write(userKey, userProfileMap);
53-
// },
54-
// };
55-
5625
/**
5726
* The OptimizelyProvider class is a class that provides a common interface for handling Optimizely operations.
5827
* It is designed to be extended by other classes to provide specific implementations for handling Optimizely operations.
@@ -424,7 +393,7 @@ export default class OptimizelyProvider {
424393
return forcedDecisions.some((decision) => decision.flagKey === flagKey);
425394
}
426395

427-
/**
396+
/**+
428397
* Retrieves the decision for a flag.
429398
* @param {Object} flagObj - The flag object.
430399
* @param {boolean} [doForceDecision=false] - Whether to force the decision.

src/cdn-adapters/cloudflare/cloudflareAdapter.js

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ class CloudflareAdapter {
9797
this.eventListenersResult = await this.eventListeners.trigger(
9898
'beforeProcessingRequest',
9999
request,
100-
this.coreLogic.requestConfig,
100+
this.coreLogic.requestConfig
101101
);
102102
if (this.eventListenersResult && this.eventListenersResult.modifiedRequest) {
103103
preRequest = this.eventListenersResult.modifiedRequest;
@@ -114,7 +114,7 @@ class CloudflareAdapter {
114114
request,
115115
result.reqResponse,
116116
this.coreLogic.requestConfig,
117-
result,
117+
result
118118
);
119119
let postResponse = result.reqResponse;
120120
if (this.eventListenersResult && this.eventListenersResult.modifiedResponse) {
@@ -128,7 +128,7 @@ class CloudflareAdapter {
128128
'beforeResponse',
129129
request,
130130
result.reqResponse,
131-
result,
131+
result
132132
);
133133
}
134134

@@ -148,7 +148,7 @@ class CloudflareAdapter {
148148
'afterResponse',
149149
request,
150150
result.reqResponse,
151-
result,
151+
result
152152
);
153153
fetchResponse = this.eventListenersResult.modifiedResponse || result.reqResponse;
154154
return fetchResponse;
@@ -158,7 +158,7 @@ class CloudflareAdapter {
158158
if (httpMethod === 'GET' && (this.coreLogic.datafileOperation || this.coreLogic.configOperation)) {
159159
const fileType = this.coreLogic.datafileOperation ? 'datafile' : 'config file';
160160
this.logger.debug(
161-
`GET request detected. Returning current ${fileType} for SDK Key: ${this.coreLogic.sdkKey} [fetchHandler]`,
161+
`GET request detected. Returning current ${fileType} for SDK Key: ${this.coreLogic.sdkKey} [fetchHandler]`
162162
);
163163
return result.reqResponse;
164164
}
@@ -169,7 +169,7 @@ class CloudflareAdapter {
169169
fetchResponse = await this.fetchAndProcessRequest(request, originUrl, cdnSettings, ctx);
170170
} else {
171171
this.logger.debug(
172-
'No CDN settings found or CDN Response URL is undefined. Fetching directly from origin without caching.',
172+
'No CDN settings found or CDN Response URL is undefined. Fetching directly from origin without caching.'
173173
);
174174
fetchResponse = await this.fetchFromOriginOrCDN(request);
175175
}
@@ -187,7 +187,7 @@ class CloudflareAdapter {
187187
setFetchAndProcessLogs(validCDNSettings, cdnSettings) {
188188
if (!validCDNSettings) {
189189
this.logger.debug(
190-
'No CDN settings found or CDN Response URL is undefined. Fetching directly from origin without caching [fetchHandler]',
190+
'No CDN settings found or CDN Response URL is undefined. Fetching directly from origin without caching [fetchHandler]'
191191
);
192192
} else {
193193
}
@@ -196,7 +196,7 @@ class CloudflareAdapter {
196196
this.logger.debug(
197197
`Fetching content from origin in CDN Adapter [fetchHandler -> fetchAndProcessRequest] - `,
198198
`shouldCacheResponse is ${this.shouldCacheResponse} and validCDNSettings is ${validCDNSettings} and `,
199-
`cdnSettings.forwardRequestToOrigin is ${cdnSettings.forwardRequestToOrigin}`,
199+
`cdnSettings.forwardRequestToOrigin is ${cdnSettings.forwardRequestToOrigin}`
200200
);
201201
}
202202
}
@@ -230,7 +230,7 @@ class CloudflareAdapter {
230230
'beforeRequest',
231231
newRequest,
232232
this.reqResponse,
233-
this.result,
233+
this.result
234234
);
235235
if (this.eventListenersResult && this.eventListenersResult.modifiedRequest) {
236236
newRequest = this.eventListenersResult.modifiedRequest;
@@ -309,7 +309,7 @@ class CloudflareAdapter {
309309
'beforeReadingCache',
310310
request,
311311
this.requestConfig,
312-
this.result,
312+
this.result
313313
);
314314
if (!this.coreLogic.requestConfig.overrideCache) {
315315
response = await cache.match(cacheKey);
@@ -319,7 +319,7 @@ class CloudflareAdapter {
319319
request,
320320
response,
321321
this.requestConfig,
322-
this.result,
322+
this.result
323323
);
324324
if (this.eventListenersResult && this.eventListenersResult.modifiedResponse) {
325325
response = this.eventListenersResult.modifiedResponse;
@@ -339,7 +339,7 @@ class CloudflareAdapter {
339339
'afterCacheResponse',
340340
request,
341341
response,
342-
this.result,
342+
this.result
343343
);
344344
if (this.eventListenersResult && this.eventListenersResult.modifiedResponse) {
345345
response = this.eventListenersResult.modifiedResponse;
@@ -448,7 +448,7 @@ class CloudflareAdapter {
448448
'beforeCacheResponse',
449449
this.request,
450450
responseToCache,
451-
this.result,
451+
this.result
452452
);
453453
if (this.eventListenersResult && this.eventListenersResult.modifiedResponse) {
454454
response = this.eventListenersResult.modifiedResponse;
@@ -483,7 +483,7 @@ class CloudflareAdapter {
483483
ctx.waitUntil(
484484
this.dispatchAllEventsToOptimizely(defaultSettings.optimizelyEventsEndpoint, allEvents).catch((err) => {
485485
this.logger.error('Failed to dispatch event:', err);
486-
}),
486+
})
487487
);
488488
} catch (error) {
489489
this.logger.error('Error during event consolidation or dispatch:', error);
@@ -538,7 +538,7 @@ class CloudflareAdapter {
538538
{
539539
status: 500,
540540
statusText: 'Internal Server Error',
541-
},
541+
}
542542
);
543543
}
544544
}
@@ -674,15 +674,15 @@ class CloudflareAdapter {
674674
const response = await this.fetchFromOriginOrCDN(eventRequest);
675675
const operationResult = !!response.ok;
676676
this.logger.debug(
677-
`Events were dispatched to Optimizely [dispatchAllEventsToOptimizely] - Operation Result: ${operationResult}`,
677+
`Events were dispatched to Optimizely [dispatchAllEventsToOptimizely] - Operation Result: ${operationResult}`
678678
);
679679

680680
this.eventListenersResult = this.eventListeners.trigger(
681681
'afterDispatchingEvents',
682682
eventRequest,
683683
response,
684684
modifiedEvents,
685-
operationResult,
685+
operationResult
686686
);
687687

688688
if (!operationResult) {
@@ -1156,15 +1156,15 @@ class CloudflareAdapter {
11561156
setMultipleResponseHeaders(response, headers) {
11571157
this.logger.debugExt(`Setting multiple headers [setMultipleResponseHeaders]:`, headers);
11581158
// Clone the original response
1159-
const newResponse = this.cloneResponse(response);
1159+
// const newResponse = this.cloneResponse(response);
11601160
// const newResponse = response;
11611161

11621162
// Update the headers with new values
11631163
Object.entries(headers).forEach(([name, value]) => {
1164-
this.abstractionHelper.abstractResponse.setHeaderInResponse(newResponse, name, value);
1164+
this.abstractionHelper.abstractResponse.setHeaderInResponse(response, name, value);
11651165
});
11661166
this.logger.debug(`Headers set in response [setMultipleResponseHeaders]`);
1167-
return newResponse;
1167+
return response;
11681168
}
11691169

11701170
/**

0 commit comments

Comments
 (0)