-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathFPC.js
1693 lines (1535 loc) · 59.5 KB
/
FPC.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
// IMPORTANT: Either A Key/Value Namespace must be bound to this worker script
// using the variable name KV. or the API parameters below should be
// configured. KV is recommended if possible since it can purge just the HTML
// instead of the full cache.
// Separate cache for the mobile devices
var MOBILECACHE_DIFFERENT = false;
var KV_CONFIG_LAST_SYNC = null;
var KV_CONFIG_CHECK = [];
var KV_CONFIG = [];
var JSON_CONFIG = {};
var IP_count = [];
//KV Config doesn't make sens. ENV var change automatically deploys new Worker version
var KV_CONFIG_ENABLED = false;
//limited to 128 MB
var WORKER_CACHE_STORAGE = [];
var WORKER_CACHE_STAT = [];
// API settings if KV isn't being used
var CLOUDFLARE_API = {
email: "", // From https://dash.cloudflare.com/profile
key: "", // Global API Key from https://dash.cloudflare.com/profile
zone: "" // "Zone ID" from the API section of the dashboard overview page https://dash.cloudflare.com/
};
// No cache values
var CACHE_CONTROL_NO_CACHE = [
'no-cache',
'no-store'
];
// Default cookie prefixes for logged-in users
var VERSION_COOKIES = [
"X-Magento-Vary"
];
// Default cookie prefixes for bypass
var DEFAULT_BYPASS_COOKIES = [
'admin'
//"X-Magento-Vary"
];
var R2_CAHE_LOGGEDIN_USERS = false;
const USER_COOKIES = [
'X-Magento-Vary'
];
const FORM_KEY = 'form_key';
const CSPRO_HEADER = 'content-security-policy-report-only';
var CSPRO_REMOVE = true;
var ADMIN_URL = null;
var BODY_MIN_SIZE = 3 * 1024;
// Filtered get parameters
var FILTER_GET = [
// Facebook related
'fbclid',
'fb_ad',
'fb_adid',
'fb_adset',
'fb_campaign',
'fb_adsetid',
'fb_campaignid',
'utm_id',
'utm_source',
'matchtype',
'addisttype',
'adposition',
'gad_source',
'utm_term',
'utm_medium',
'utm_cam',
'utm_campaign',
'utm_content',
'utm_creative',
'utm_adcontent',
'utm_adgroupid',
'wbraid',
'epik',
'_hsenc',
'_hsmi',
'__hstc',
'affiliate_code',
'referring_service',
'hsa_cam',
'hsa_acc',
'msclkid',
'hsa_grp',
'hsa_ad',
'hsa_src',
'hsa_net',
'hsa_ver',
'dm_i',
'dm_t',
'ref',
'trk',
'uuid',
'dicbo',
'adgroupid',
// google related
'g_keywordid',
'g_keyword',
'g_campaignid',
'g_campaign',
'g_network',
'g_adgroupid',
'g_adtype',
'g_acctid',
'g_adid',
'cq_plac',
'cq_net',
'cq_pos',
'cq_med',
'cq_plt',
'b_adgroup',
'b_adgroupid',
'b_adid',
'b_campaign',
'b_campaignid',
'b_isproduct',
'b_productid',
'b_term',
'b_termid',
'msclkid',
'gbraid',
'gclid',
'gclsrc',
'customer-service',
'terms-of-service',
'_ga',
'_gl',
'add',
'srsltid', //new google parameter
// worker specific
'click',
'gtm_debug',
'cf-cdn',
'r2-cdn',
'cf-delete',
'cf-ttl',
'cf-revalidate'
];
var CACHE_STATUSES = [
200,
301,
//302, Bots creats a lot of riddirects of this type.
//404
];
var ALLOWED_GET_ONLY = false;
//Whitelisted GET parameters
var ALLOWED_GET = [
'product_list_order',
'p',
'product_list_limit',
'q',
'fpc',
'price',
'id',
'limit',
'order',
'mode'
];
// URLs will not be cached
var BYPASS_URL = [
'order',
'onestepcheckout',
'admin',
'checkout',
'catalogsearch',
'paypal',
'cart',
'static/',
'media/',
'api',
'rest/',
'ajax',
'frontend_action',
'searchspring',
'customer',
'compare',
'tracking',
'account',
'feedonomics',
'estimateddeliverydate',
'original-page'
];
// URL will always be cached no matter what
var CACHE_ALWAYS = [
'customer-service',
'banner/ajax/load'
]
//Some legacy stuff. Bots doesn't have it and produces cache MISSES
var ACCEPT_CONTENT_HEADER = 'Accept';
// Config variables will be assigned in the main loop.
var DEBUG;
var CUSTOM_CORS;
var CUSTOM_PRELOAD;
var CUSTOM_SPECULATION;
var SPECULATION_ENABLED;
var SPECULATION_CACHED_ONLY;
var ENABLE_ESI_BLOCKS = false;
// Prevent any cache invalidations - 100% static
var GOD_MOD;
// Revalidate the cache every N secs
// User will receive old/stale version
var REVALIDATE_AGE;
var R2_STALE = true;
// Send R2 and Server response semultaniosly and use which one will be recieved first
var R2_SERVER_RACE = true;
var TEST;
var HTML_CACHE_VERSION = false;
var PWA_SPECULATION_VERSION = 1;
var PWA_ENABLED = true;
var PWA_IMAGE = "data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz48IS0tIFVwbG9hZGVkIHRvOiBTVkcgUmVwbywgd3d3LnN2Z3JlcG8uY29tLCBHZW5lcmF0b3I6IFNWRyBSZXBvIE1peGVyIFRvb2xzIC0tPgo8c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKYXJpYS1sYWJlbD0iQ2xvdWRmbGFyZSIgcm9sZT0iaW1nIgp2aWV3Qm94PSIwIDAgNTEyIDUxMiI+PHJlY3QKd2lkdGg9IjUxMiIgaGVpZ2h0PSI1MTIiCnJ4PSIxNSUiCmZpbGw9IiNmZmZmZmYiLz48cGF0aCBmaWxsPSIjZjM4MDIwIiBkPSJNMzMxIDMyNmMxMS0yNi00LTM4LTE5LTM4bC0xNDgtMmMtNCAwLTQtNiAxLTdsMTUwLTJjMTctMSAzNy0xNSA0My0zMyAwIDAgMTAtMjEgOS0yNGE5NyA5NyAwIDAgMC0xODctMTFjLTM4LTI1LTc4IDktNjkgNDYtNDggMy02NSA0Ni02MCA3MiAwIDEgMSAyIDMgMmgyNzRjMSAwIDMtMSAzLTN6Ii8+PHBhdGggZmlsbD0iI2ZhYWU0MCIgZD0iTTM4MSAyMjRjLTQgMC02LTEtNyAxbC01IDIxYy01IDE2IDMgMzAgMjAgMzFsMzIgMmM0IDAgNCA2LTEgN2wtMzMgMWMtMzYgNC00NiAzOS00NiAzOSAwIDIgMCAzIDIgM2gxMTNsMy0yYTgxIDgxIDAgMCAwLTc4LTEwMyIvPjwvc3ZnPg=="
var PWA_MANIFEST = { "theme_color": "#ffffff", "background_color": "#ffffff", "icons": [{ "sizes": "any", "src": PWA_IMAGE, "type": "image/svg+xml" }], "orientation": "any", "display": "standalone", "dir": "auto", "lang": "en-US", "id": "https://your-domain.com/", "start_url": "/", "scope": "https://your-domain.com/", "description": "Cloud Flare Magento PWA", "name": "Magento PWA", "short_name": "M2 PWA", "prefer_related_applications": false };
processConfig();
/**
* Main worker entry point.
*/
addEventListener("fetch", async event => {
let startWorkerTime = Date.now();
let startConfigTime = Date.now();
let endConfigTime = Date.now();
console.log('Config Processing Time: ' + (endConfigTime - startConfigTime).toString()); // 0
console.log(event.request);
let context = {
event: event,
promise: null,
'r2-race': R2_SERVER_RACE,
'r2-stale': false,
'r2-cache': false,
'r2-server-first': false,
'r2-use-stale': false,
'CDN-miss': false, // emulate cache miss on CDN
'CDN-ttl': 99999999999, // ttl to test revalidation
'R2-miss': false, // Emulate cache miss on Page Reserve
'CDN-delete': false, // Delete page for test
'CDN-revalidate': false,
'set-version': "",
'speculation': false,
url: null,
cookies: "",
bypassCookies: false,
bypassCache: false,
bypassUrl: false,
error: "",
country: "",
serverPromise: null
}
const request0 = event.request;
const cacheUrl = new URL(request0.url);
if (PWA_ENABLED && typeof ENV_PWA_MANIFEST === 'undefined') {
PWA_MANIFEST.scope = cacheUrl.origin;
PWA_MANIFEST.id = cacheUrl.origin;
}
const bypassCookies = shouldBypassEdgeCache(event.request);
const bypassUrl = shouldBypassURL(request0);
const IP = event.request.headers.get('CF-Connecting-IP');
if (typeof event.request.cf.botManagement !== 'undefined') {
// Requires enterprise plan
const botScore = event.request.cf.botManagement.score;
console.log("BOT score: " + botScore.toString());
}
if (typeof event.request.cf.country !== 'undefined') {
context.country = event.request.cf.country;
console.log("Country: " + context.country);
}
// Saving worker specific GET parameters to context before URL normalization
if (bypassUrl || cacheUrl.searchParams.get('cfw') === "false" || bypassCookies) {
console.log("bypass worker");
event.passThroughOnException();
let headers = [{ name: "bypass-worker", value: "true" }, { name: "cf-cache-status", value: "BYPASS,WORKER,MISS" }];
if (bypassCookies) {
headers.push({ name: "bypass-cookies", value: "true" });
}
event.respondWith(fetchAndModifyHeaders(request0, headers));
return true;
}
// Speculation rule Controller ;)
if (cacheUrl.toString().indexOf('rules/speculation.json') >= 0) {
console.log("Speculation Rule");
event.passThroughOnException();
event.respondWith(new Response(JSON.stringify(CUSTOM_SPECULATION), {
headers: new Headers({ 'Content-Type': 'application/speculationrules+json', "Cache-Control": "public, max-age=604800" }), status: 200
}));
return true;
}
if (cacheUrl.toString().indexOf('cf/manifesto.json') >= 0) {
console.log("Manifest Rule");
event.passThroughOnException();
event.respondWith(new Response(JSON.stringify(PWA_MANIFEST), {
headers: new Headers({ 'Content-Type': 'application/manifest+json', "Cache-Control": "public, max-age=604800" }), status: 200
}));
return true;
}
if (cacheUrl.searchParams.get('cf-cdn') === "false") {
context["CDN-miss"] = true;
cacheUrl.searchParams.delete('cf-cdn');
}
if (cacheUrl.searchParams.get('r2-cdn') === "false") {
context["R2-miss"] = true;
cacheUrl.searchParams.delete('r2-cdn');
}
if (cacheUrl.searchParams.get('cf-version') !== null) {
context["set-version"] = cacheUrl.searchParams.get('cf-version');
cacheUrl.searchParams.delete('set-version');
}
if (cacheUrl.searchParams.get('cf-delete') === "true") {
context["CDN-delete"] = true;
cacheUrl.searchParams.delete('cf-delete');
}
if (cacheUrl.searchParams.get('cf-revalidate') === "true") {
context["CDN-revalidate"] = true;
cacheUrl.searchParams.delete('cf-revalidate');
}
if (cacheUrl.searchParams.get('cf-ttl')) {
context["CDN-ttl"] = parseInt(cacheUrl.searchParams.get('cf-ttl'));;
cacheUrl.searchParams.delete('cf-ttl');
}
if (cacheUrl.searchParams.get('r2-race')) {
context["r2-race"] = parseBoolean(cacheUrl.searchParams.get('r2-race'));
R2_SERVER_RACE = parseBoolean(cacheUrl.searchParams.get('r2-race'));
cacheUrl.searchParams.delete('r2-race');
}
// Hostname for a different zone
if (typeof OTHER_HOST !== 'undefined') {
console.log("Other Host: " + OTHER_HOST);
cacheUrl.hostname = OTHER_HOST;
}
// Remove marketing GET parameters from the URL
let normalizedUrl = normalizeUrl(cacheUrl);
context.url = normalizedUrl;
const request = new Request(normalizedUrl.toString(), request0);
console.log(request);
let upstreamCache = request.headers.get('x-HTML-Edge-Cache');
context.cookies = request.headers.get('cookie');
let specalationRequest = request.headers.get('Sec-Purpose');
if (specalationRequest) {
context['speculation'] = true;
}
// Only process requests if KV store is set up and there is no
// HTML edge cache in front of this worker (only the outermost cache
// should handle HTML caching in case there are varying levels of support).
let configured = false;
if (typeof R2 !== 'undefined') {
console.log('R2 is working!!');
} else {
console.log('R2 is not working!!');
}
if (typeof KV !== 'undefined') {
console.log('KV is working!!');
configured = true;
} else if (CLOUDFLARE_API.email.length && CLOUDFLARE_API.key.length && CLOUDFLARE_API.zone.length) {
configured = true;
} else {
context.error += "KV is not configured";
console.log(context.error);
}
// temporary
configured = true;
// Bypass processing of image requests (for everything except Firefox which doesn't use image/*)
const accept = request.headers.get(ACCEPT_CONTENT_HEADER);
let isImage = false;
if (accept && (accept.indexOf('image/*') !== -1)) {
isImage = true;
}
if (configured && !isImage && upstreamCache === null) {
event.passThroughOnException();
let resultResponse = processRequest(request, context);
event.respondWith(resultResponse);
console.log(context);
}
});
/**
* Process every request coming through to add the edge-cache header,
* watch for purge responses and possibly cache HTML GET requests.
*
* @param {Request} originalRequest - Original request
* @param {Object} context - Original event context (for additional async waiting)
*/
async function processRequest(originalRequest, context) {
let startWorkerTime = Date.now();
let event = context.event;
let cfCacheStatus = null;
let originTimeStart = 0;
let originTimeEnd = 0;
const accept = originalRequest.headers.get(ACCEPT_CONTENT_HEADER);
let isHTML = true;//(accept && accept.indexOf('text/html') >= 0);
console.log("isHTML: " + isHTML);
//Cache everything by default
//ToDo: exclude some mime types
isHTML = true;
let getCachedTimeStart = Date.now();
let { response, cacheVer, status, bypassCache, needsRevalidate, cacheAlways } = await getCachedResponse(originalRequest.clone(), context);
let getCachedTimeEnd = Date.now();
// if revalidate request
if (context['CDN-revalidate']) {
response = null;
status += ",Revalidate,";
}
// Request to purge cache by Adding Version
if (originalRequest.url.indexOf('cf-purge') >= 0) {
console.log("Clearing the cache");
if (!GOD_MOD) {
let newCacheVersion = await purgeCache(cacheVer, event);
status += ',Purged,';
return new Response("Cache Purged (NEW VERSION: " + (cacheVer + 1) + ") Successfully!!", {
headers: new Headers({ 'cache-version': newCacheVersion }), status: 222
});
} else {
status += ',GODMOD,';
return new Response("Cache NOT Purged (NEW VERSION: GODMOD) Successfully!!", {
headers: new Headers({ 'cache-version': "GODMOD" }), status: 222
});
}
}
// Restore version after test.
if (context['set-version'] !== "") {
console.log("set-version");
if (isNaN(context['set-version'])) {
return new Response("(NEW VERSION " + context['set-version'] + ") Set Error NaN!!", {
headers: new Headers({ 'cache-version': context['set-version'] }), status: 553
});
}
await KV.put('html_cache_version', context['set-version']);
let newCacheVersion = context['set-version'];
return new Response("(NEW VERSION " + newCacheVersion + ") Set Successfully!!", {
headers: new Headers({ 'cache-version': newCacheVersion }), status: 223
});
}
if (response === null) {
if (context['speculation'] === true && SPECULATION_CACHED_ONLY) {
return new Response("Speculation only from the CDN cache", { headers: new Headers({ "Cache-Control": "no-store,private" }), status: 406 });
}
console.log("Not From Cache");
// Clone the request, add the edge-cache header and send it through.
let request = new Request(originalRequest.clone(), {
headers: {
...Object.fromEntries(originalRequest.headers.entries()),
"Accept-Encoding": "br, gzip", // Request both Brotli and Gzip support
},
});
request.headers.set('x-HTML-Edge-Cache', 'supports=cache|purgeall|bypass-cookies');
status += ',FetchedOrigin,';
originTimeStart = Date.now();
// if we still have promise from R2...
if (context.serverPromise !== null) {
response = await context.serverPromise;
if(context['r2-server-first']){
// if server respond first considering it is from cache
cfCacheStatus = "HIT";
}
}
if (!response) {
// Fetch it from origin
response = await fetch(request, {
cf: {
// Always cache this fetch regardless of content type
// for a max of 15 seconds before revalidating the resource
// cacheTtl: 15,
// cacheEverything: true
},
});
}
const compression = response.headers.get("Content-Encoding");
console.log("Compres: " + compression);
originTimeEnd = Date.now();
if (originTimeEnd - originTimeStart > 0) {
console.log("Origin-Time:" + (originTimeEnd - originTimeStart).toString());
}
if (ENABLE_ESI_BLOCKS) {
let newBody = await processESI(response, context);
response = new Response(newBody, response);
}
if (PWA_ENABLED) {
let newBody = await processManifesto(response, context);
response = new Response(newBody, response);
}
//ToDo: Seams redundant refactor
if (response) {
console.log("Origin CF Cache Status: " + response.headers.get('cf-cache-status'));
if (response.headers.get('cf-cache-status') === "HIT") {
status += ',CF-HIT,';
}
console.log("response from Origin ");
const options = getResponseOptions(response);
console.log('URL path: ' + request.url);
if (options && options.purge) {
console.log("Clearing the cache");
await purgeCache(cacheVer, event);
status += ',Purged,';
}
bypassCache = context.bypassCache; //|| shouldBypassEdgeCache(request, response);
console.log("bypassCache: " + bypassCache);
console.log("options: " + options);
//Cache everything by default
//if(options === null) options.cache = true;
// We also need check HEAD because of the curl issue.
if ((!options || options.cache) && isHTML &&
['GET', 'HEAD'].includes(originalRequest.method) && CACHE_STATUSES.includes(response.status) &&
!bypassCache) {
console.log("Caching...");
status += ",Caching Async,";
event.waitUntil(cacheResponse(cacheVer, originalRequest, response, context, cacheAlways));
console.log("Status: " + status);
} else {
console.log("Bypass The cache:" + request.url);
status += ",Bypassed,";
}
}
} else if (response && context['r2-cache'] === "r2-null-server") {
console.log("R2 optimised race fetch from server");
} else {
// If the origin didn't send the control header we will send the cached response but update
// the cached copy asynchronously (stale-while-revalidate). This commonly happens with
// a server-side disk cache that serves the HTML directly from disk.
// ToDo: Code variables to disable this feature.
cfCacheStatus = 'HIT';
console.log("Cache HIT!!!");
console.log(response);
// Nen revalidate when fetched previous version
if (needsRevalidate) {
status += ',Stale,';
console.log("Hit from the previous version Needs Revalidate: Current V: " + cacheVer + " Previous: " + (cacheVer - 1))
}
if (['GET', 'HEAD'].includes(originalRequest.method) && CACHE_STATUSES.includes(response.status) && isHTML) {
bypassCache = bypassCache || context.bypassCookies;
if (needsRevalidate || !bypassCache) {
const options = getResponseOptions(response);
if (needsRevalidate || !options) {
let age = parseInt(response.headers.get('age'));
// If the cache is new, don't send the backend request
if (needsRevalidate || age > context["CDN-ttl"] || age > REVALIDATE_AGE) {
status += ',Refreshed,';
console.log("Refresh Cache");
// In service workers, waitUntil() tells the browser that work is ongoing until
// the promise settles, and it shouldn't terminate the service worker if it wants that work to be complete.
event.waitUntil(updateCache(originalRequest, cacheVer, event, cacheAlways));
} else {
status += ',Stale_' + age + ',';
}
}
}
}
}
if (response && status !== null && ['GET', 'HEAD'].includes(originalRequest.method) && CACHE_STATUSES.includes(response.status) && isHTML) {
let cloneStart = Date.now();
response = new Response(response.clone().body, response);
let cloneEnd = Date.now();
response.headers.append('Server-Timing', 'clone-response;desc="Clone Main Response";dur=' + (cloneEnd - cloneStart).toString());
response.headers.set('Origin-Time', (originTimeEnd - originTimeStart).toString());
response.headers.append('Server-Timing', 'fetch-origin;desc="Fetch From Origin";dur=' + (originTimeEnd - originTimeStart).toString());
if (['r2-null-server', 'server-first', 'miss'].includes(context['r2-cache'])) {
// If Server was used insead of R2
response.headers.set('R2-cache', context['r2-cache']);
}
if (context.error !== "") {
response.headers.set('CFW-Error', context.error);
}
if (needsRevalidate) {
response.headers.set('Stale', 'true');
}
if (context['CDN-ttl'] < 9999) {
response.headers.set('Custom-TTL', context['CDN-ttl'].toString());
}
if (context['CDN-revalidate']) {
response.headers.set('CDN-Revalidate', "1");
}
if (context.serverPromise !== null) {
response.headers.set('R2-promise', "1");
}
let getCacheTime = getCachedTimeEnd - getCachedTimeStart;
response.headers.set('Cache-Time', getCacheTime.toString());
response.headers.append('Server-Timing', 'get-cache;desc="Get CF CDN CACHE";dur=' + getCacheTime.toString());
status = status.replaceAll(",,", ",");
status = status.replaceAll(" ", "");
if (DEBUG)
response.headers.set('x-HTML-Edge-Cache-Status', status);
if (cacheVer !== null) {
if (DEBUG)
response.headers.set('x-HTML-Edge-Cache-Version', cacheVer.toString());
}
if (cfCacheStatus) {
if (DEBUG)
response.headers.set('CF-Cache-Status', cfCacheStatus);
response.headers.set('CF-Loc', btoa(cfCacheStatus));
response.headers.set('Cache-Control', 'max-age=0, must-revalidate');
}
// Hide default CF values
if (!DEBUG && cfCacheStatus) {
response.headers.delete('CF-Cache-Status');
response.headers.delete('Age');
response.headers.set('CF-Cache-Status', 'DYNAMIC');
response.headers.set('X-Magento-Cache-Debug', 'MIS');
response.headers.set('X-Varnish', Date.now() + " " + (Date.now() - 999));
}
if (context['r2-stale']) {
response.headers.set('R2-stale', "true");
}
let endWorkerTime = Date.now();
console.log("Worker-Time: " + (endWorkerTime - startWorkerTime).toString());
response.headers.set("Worker-Time", (endWorkerTime - startWorkerTime).toString());
response.headers.append('Server-Timing', 'worker-time;desc="Total Worker Time";dur=' + (endWorkerTime - startWorkerTime).toString());
let jsTime = ((endWorkerTime - startWorkerTime) - (originTimeEnd - originTimeStart) - getCacheTime).toString()
response.headers.set("JS-Time", jsTime);
response.headers.append('Server-Timing', 'js-time;desc="JS Execution Time";dur=' + jsTime);
console.log("JS-Time: " + jsTime);
if (CSPRO_REMOVE) {
response.headers.delete(CSPRO_HEADER);
}
if (CUSTOM_PRELOAD.length != 0) {
CUSTOM_PRELOAD.forEach((preload) => {
response.headers.set("Link", preload);
})
}
if (SPECULATION_ENABLED && !bypassCache) {
response.headers.set("Speculation-Rules", "\"/rules/speculation.json?v=" + PWA_SPECULATION_VERSION + "\"");
}
}
console.log("Return Response");
//console.log("HTML:" + await response.clone().text());
//console.log("HTML size:" + (await response.clone().arrayBuffer()).byteLength / 1000 + "Kb");
//hash(await response.text(), context);
//new Error("Error");
return response;
}
/**
* Determine if the cache should be bypassed for the given request/response pair.
* Specifically, if the request includes a cookie that the response flags for bypass.
* Can be used on cache lookups to determine if the request needs to go to the origin and
* origin responses to determine if they should be written to cache.
* @param {Request} request - Request
* @param {Response} response - Response
* @returns {bool} true if the cache should be bypassed
*/
function shouldBypassEdgeCache(request, response = null) {
let bypassCache = false;
if (request /*&& response*/) {
const options = false; // = getResponseOptions(response);
const cookieHeader = request.headers.get('cookie');
let bypassCookies = DEFAULT_BYPASS_COOKIES;
//CAHE_LOGGEDIN_USERS
bypassCache = checkCookies(cookieHeader, bypassCookies);
}
return bypassCache;
}
/**
* Check if some cookies is set
*
* @param {String} cookieHeader
* @param {array} bypassCookies
*/
function checkCookies(cookieHeader, bypassCookies) {
let bypassCache = false;
if (cookieHeader && cookieHeader.length && bypassCookies.length) {
const cookies = cookieHeader.split(';');
for (let cookie of cookies) {
// See if the cookie starts with any of the cookies
// Example: token=29281ed8-3981-4840-a91e-382f9bd50dd2"
// = is added to match full cookie name
for (let prefix of bypassCookies) {
if (cookie.trim().startsWith(prefix + "=")) {
bypassCache = true;
break;
}
}
if (bypassCache) {
break;
}
}
}
return bypassCache;
}
/**
* Check if we should bypass url
* bypass if url contains any of BYPASS_URL
*
* @param {Request} request - original request
* @returns {boolean}
*/
function shouldBypassURL(request) {
let bypassCache = false;
let url = new URL(request.url);
//ignoring host name
let searchUrl = url.pathname + url.search;
if (BYPASS_URL && BYPASS_URL.length) {
//console.log(BYPASS_URL);
for (let pass of BYPASS_URL) {
// See if the URL starts with any of the logged-in user prefixes
//console.log("check: " + pass);
if (searchUrl.indexOf(pass) >= 0) {
console.log("Should Bypass URL:" + pass);
bypassCache = true;
break;
}
}
}
return bypassCache;
}
const CACHE_HEADERS = ['Cache-Control', 'Expires', 'Pragma'];
/**
* Check for cached HTML GET requests.
*
* @param {Request} request - Original request
* @param {Object} context - context container object
*/
async function getCachedResponse(request, context) {
let response = null;
let event = context.event;
let cacheVer = null;
let bypassCache = false;
let byPassUrl = false;
let status = '';
let cacheAlways = false;
let fromR2 = false;
let R2check = true;
let R2StaleUsed = false;
let cachedResponse = null;
let staleCachePromise = null;
// Only check for HTML GET requests (saves on reading from KV unnecessarily)
// and not when there are cache-control headers on the request (refresh)
const accept = request.headers.get(ACCEPT_CONTENT_HEADER);
const cacheControl = request.headers.get('Cache-Control');
for (let url of CACHE_ALWAYS) {
if (request.url.indexOf(url) >= 0) {
console.log("Always Cache URL:" + url + " in " + request.url);
cacheAlways = true;
status += ',AlwaysCache,';
break;
}
}
// Always cache some URLs
if (!cacheAlways) {
byPassUrl = context.bypassUrl; //|| shouldBypassURL(request);
// Bypass static files
if (byPassUrl) {
status += ',BypassURL,';
console.log(status + " : " + request.url);
bypassCache = true;
} else {
// Check to see if the response needs to be bypassed because of a cookie
bypassCache = context.bypassCookies; //|| shouldBypassEdgeCache(request, null);
if (bypassCache)
status += ',BypassCookie,';
}
}
let noCache = false;
let needsRevalidate = false;
/*if (cacheControl && cacheControl.indexOf('no-cache') !== -1) {
noCache = true;
bypassCache = true;
status = 'No-Cache';
}*/
if (!bypassCache && !noCache && ['GET', 'HEAD'].includes(request.method) /*&& accept && accept.indexOf('text/html') >= 0*/) {
// Build the versioned URL for checking the cache
cacheVer = await getCurrentCacheVersion(cacheVer);
console.log("Getting from cache:");
const cacheKeyRequest = GenerateCacheRequestUrlKey(request, cacheVer, cacheAlways);
const staleCacheKeyRequest = GenerateCacheRequestUrlKey(request, cacheVer - 1, cacheAlways);
console.log(cacheKeyRequest);
// in case of debugging uncomment this
//status += "[" + cacheKeyRequest.url.toString() + "]";
// See if there is a request match in the cache
try {
let cache = caches.default;
let deleted = false;
// Delete page from local CDN for tests purposes
// But not deleted from Cache Reserve page is still in cache
if (context["CDN-delete"]) {
let deleteStatus = await cache.delete(cacheKeyRequest);
status += ",Deleted,";
let headers = new Headers();
headers.set("Deleted", "true");
headers.set("Delete-Status", "" + deleteStatus);
cachedResponse = new Response("Deleted URL: " + cacheKeyRequest.url, {
headers: headers, status: 211
});
deleted = true;
}
let cacheGetStart = 0;
let cacheGetEnd = 0;
if (!deleted) {
cacheGetStart = Date.now();
// check the previous version of the cache before purge and soft revalidate
// requestin in advance to save time
staleCachePromise = cache.match(staleCacheKeyRequest);
cachedResponse = await cache.match(cacheKeyRequest);
if (!cachedResponse) {
// Return the previous version of the cache ...
cachedResponse = await staleCachePromise;
needsRevalidate = true;
}
cacheGetEnd = Date.now();
}
let requestUrl = new URL(request.url);
// Bypass just CDN cache for test purpuses to imulate cache miss
// like from another location/POP
if (context['CDN-miss']) {
cachedResponse = null;
staleCachePromise = null;
}
if (cachedResponse) {
console.log("From CDN EDGE cache");
}
let useStale = true;
if (cachedResponse) {
console.log("Status: " + String(cachedResponse.status));
console.log(cachedResponse);
// Copy Response object so that we can edit headers.
cachedResponse = new Response(cachedResponse.body, cachedResponse);
cachedResponse.headers.append('Server-Timing', 'cache-get-time;desc="Get Local CDN CACHE";dur=' + (cacheGetEnd - cacheGetStart).toString());
if (needsRevalidate) {
cachedResponse.headers.set('stale-version', (cacheVer - 1).toString());
}
if (R2StaleUsed) {
cachedResponse.headers.set('r2-stale', "true");
context['r2-stale'] = true;
}
if (context['r2-cache'] === "server-first") {
cachedResponse.headers.set('r2', "server");
}
if (!R2StaleUsed && needsRevalidate) {
cachedResponse.headers.set('cdn-stale', "true");
}
if (DEBUG)
cachedResponse.headers.set("Key", cacheKeyRequest.url.toString());
// ToDo: bypassCache is always false inside this IF. Refactor needed
// Copy the original cache headers back and clean up any control headers
status += ',Hit,';
console.log(status);
cachedResponse.headers.delete('Cache-Control');
if (cachedResponse.headers.get('R2-Status')) {
cachedResponse.status = parseInt(cachedResponse.headers.get('R2-Status'));
}
if (!fromR2) {
cachedResponse.headers.delete('R2-Status');
cachedResponse.headers.delete('R2-Time');
}
cachedResponse.headers.delete('x-HTML-Edge-Cache-Status');
for (let header of CACHE_HEADERS) {
let value = cachedResponse.headers.get('x-HTML-Edge-Cache-Header-' + header);
if (value) {
cachedResponse.headers.delete('x-HTML-Edge-Cache-Header-' + header);
cachedResponse.headers.set(header, value);
}
}
if (DEBUG)
cachedResponse.headers.set("VARNISH", "[" + cacheKeyRequest.url.toString() + "]");
response = cachedResponse;
} else {
status += ',Miss,';
console.log(status);
}
} catch (err) {
// Send the exception back in the response header for debugging
status += ",Cache Read Exception: " + err.message + ",";
}
}
return { response, cacheVer, status, bypassCache, needsRevalidate, cacheAlways };
}
/**
* Asynchronously purge the HTML cache.
* @param {Int} cacheVer - Current cache version (if retrieved)
* @param {Event} event - Original event
*/
async function purgeCache(cacheVer, event) {
if (typeof KV !== 'undefined') {
// Purge the KV cache by bumping the version number
cacheVer = await getCurrentCacheVersion(cacheVer);
cacheVer++;
event.waitUntil(KV.put('html_cache_version', cacheVer.toString()));
} else {
// Purge everything using the API
const url = "https://api.cloudflare.com/client/v4/zones/" + CLOUDFLARE_API.zone + "/purge_cache";
event.waitUntil(fetch(url, {
method: 'POST',
headers: {
'X-Auth-Email': CLOUDFLARE_API.email,
'X-Auth-Key': CLOUDFLARE_API.key,
'Content-Type': 'application/json'
},
body: JSON.stringify({ purge_everything: true })
}));
}
return cacheVer;
}
/**
* Update the cached copy of the given page
* @param {Request} originalRequest - Original Request
* @param {String} cacheVer - Cache Version
* @param {Event} event - Original event
*/
async function updateCache(originalRequest, cacheVer, event, cacheAlways) {
// Clone the request, add the edge-cache header and send it through.
let request = new Request(originalRequest.clone());
let status = "";
request.headers.set('x-HTML-Edge-Cache', 'supports=cache|purgeall|bypass-cookies');
let response = await fetch(request);
// We need duplicate this logic when invalidating the cache
if (ENABLE_ESI_BLOCKS) {
let newBody = await processESI(response, null);
response = new Response(newBody, response);
}
if (PWA_ENABLED) {
let newBody = await processManifesto(response, null);
response = new Response(newBody, response);
}
if (response) {
status += ',Fetched,';
const options = getResponseOptions(response);
if (options && options.purge) {
await purgeCache(cacheVer, event);