-
Notifications
You must be signed in to change notification settings - Fork 258
WS-1396: Lite site caching PoC #13255
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
LukasFrm
wants to merge
7
commits into
latest
Choose a base branch
from
WS-1396-spike-lite-site-homepage-caching-in-offline-mode
base: latest
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
699effa
Lite site caching PoC
LukasFrm 7495dae
test commit
LukasFrm bf04823
add cacheMostReadStories
LukasFrm bebe390
remove redundant offlinePageUrl
LukasFrm 70136f1
add sw improvements
LukasFrm b3fb262
Potential fix for code scanning alert no. 258: Use of externally-cont…
DmitryGron f1a0d0f
Merge branch 'latest' into WS-1396-spike-lite-site-homepage-caching-i…
DmitryGron File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -3,18 +3,40 @@ | |
| /* eslint-disable no-unused-vars */ | ||
| /* eslint-disable no-undef */ | ||
| /* eslint-disable no-restricted-globals */ | ||
| const version = 'v0.3.0'; | ||
| const version = 'v0.3.1'; | ||
| const cacheName = 'simorghCache_v1'; | ||
|
|
||
| const service = self.location.pathname.split('/')[1]; | ||
| const hasOfflinePageFunctionality = false; | ||
| const OFFLINE_PAGE = `/${service}/offline`; | ||
| const hasOfflinePageFunctionality = true; | ||
| const OFFLINE_PAGE = `/${service}.lite`; | ||
| const isLocalEnv = self.location.hostname === 'localhost'; | ||
| let appEnv; | ||
| if (isLocalEnv) { | ||
| appEnv = 'local'; | ||
| } else if (self.location.hostname.includes('test')) { | ||
| appEnv = 'test'; | ||
| } else { | ||
| appEnv = 'live'; | ||
| } | ||
|
|
||
| self.addEventListener('install', event => { | ||
| event.waitUntil(async () => { | ||
| const cache = await caches.open(cacheName); | ||
| if (hasOfflinePageFunctionality) await cache.add(OFFLINE_PAGE); | ||
| function logToClients(message) { | ||
| self.clients.matchAll().then(clients => { | ||
| clients.forEach(client => { | ||
| client.postMessage(message); | ||
| }); | ||
| }); | ||
| } | ||
|
|
||
| self.addEventListener('install', event => { | ||
| event.waitUntil( | ||
| (async () => { | ||
| const cache = await caches.open(cacheName); | ||
| if (hasOfflinePageFunctionality) { | ||
| await cache.add(OFFLINE_PAGE); | ||
| await cacheMostReadStories(cache); | ||
| } | ||
| })(), | ||
| ); | ||
| }); | ||
|
|
||
| const CACHEABLE_FILES = [ | ||
|
|
@@ -73,6 +95,18 @@ const fetchEventHandler = async event => { | |
| return response; | ||
| })(), | ||
| ); | ||
| } else if (isRequestForMostRead) { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. where is this variable defined? I can't find it anywhere on the diff? |
||
| event.respondWith( | ||
| (async () => { | ||
| const cache = await caches.open(cacheName); | ||
| let response = await cache.match(event.request); | ||
| if (!response) { | ||
| response = await fetch(event.request); | ||
| cache.put(event.request, response.clone()); | ||
| } | ||
| return response; | ||
| })(), | ||
| ); | ||
| } else if (hasOfflinePageFunctionality && event.request.mode === 'navigate') { | ||
| event.respondWith(async () => { | ||
| try { | ||
|
|
@@ -93,3 +127,39 @@ const fetchEventHandler = async event => { | |
| }; | ||
|
|
||
| onfetch = fetchEventHandler; | ||
|
|
||
| self.addEventListener('message', async event => { | ||
| logToClients(`[SW] Received message: ${event.data?.type}`); | ||
| if (event.data && event.data.type === 'CACHE_HOME_PAGE_AND_MOST_READ') { | ||
| if (!navigator.serviceWorker.controller) { | ||
| logToClients( | ||
| '[SW] Service worker is not active. Skipping caching logic.', | ||
| ); | ||
| return; | ||
| } | ||
| const { homePageUrl, mostReadUrls } = event.data; | ||
|
|
||
| try { | ||
| const cache = await caches.open('simorghCache_v1'); | ||
| // Most read URLs by default are canonical--> Append ".lite" to each URL and cache all | ||
| if (homePageUrl && mostReadUrls && Array.isArray(mostReadUrls)) { | ||
| const liteUrls = mostReadUrls.map(url => `${url}.lite`); | ||
| await Promise.all( | ||
| liteUrls.map(async url => { | ||
| try { | ||
| await cache.add(url); | ||
| // eslint-disable-next-line no-console | ||
| console.log(`[SW] Cached most read URL: ${url}`); | ||
| } catch (err) { | ||
| // eslint-disable-next-line no-console | ||
| console.error('[SW] Failed to cache most read URL: %s', url, err); | ||
| } | ||
| }), | ||
| ); | ||
| } | ||
| } catch (err) { | ||
| // eslint-disable-next-line no-console | ||
| console.error('[SW] Failed to cache URLs:', err); | ||
| } | ||
| } | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,11 +2,14 @@ | |
| /* @jsxFrag React.Fragment */ | ||
| import React, { use } from 'react'; | ||
| import { jsx } from '@emotion/react'; | ||
| import { getMostReadEndpoint } from '#app/lib/utilities/getUrlHelpers/getMostReadUrls'; | ||
| import VisuallyHiddenText from '#app/components/VisuallyHiddenText'; | ||
| import useOptimizelyVariation, { | ||
| ExperimentType, | ||
| } from '#app/hooks/useOptimizelyVariation'; | ||
| import OptimizelyPageMetrics from '#app/components/OptimizelyPageMetrics'; | ||
| import { getEnvConfig } from '#app/lib/utilities/getEnvConfig'; | ||
| import isLocal from '#app/lib/utilities/isLocal'; | ||
| import ATIAnalytics from '../../components/ATIAnalytics'; | ||
| import { | ||
| Curation, | ||
|
|
@@ -74,6 +77,54 @@ const HomePage = ({ pageData }: HomePageProps) => { | |
| } | ||
|
|
||
| const itemList = getItemList({ curations, name: brandName }); | ||
| const MOST_READ_URL = `${getEnvConfig().SIMORGH_BASE_URL}${getMostReadEndpoint( | ||
| { | ||
| service: use(ServiceContext).service, | ||
| variant: null, | ||
| isBff: !isLocal(), | ||
| }, | ||
| )}`; | ||
| const HOME_PAGE_URL = `${getEnvConfig().SIMORGH_BASE_URL}/${service}`; | ||
|
|
||
| const fetchMostReadItems = async () => { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. why can't this request be made from within the service worker? |
||
| try { | ||
| const response = await fetch(MOST_READ_URL, { | ||
| method: 'GET', | ||
| headers: { | ||
| 'Content-Type': 'application/json', | ||
| }, | ||
| }); | ||
|
|
||
| const { data } = await response.json(); | ||
|
|
||
| return ( | ||
| data?.items?.map((item: { href: string; title: string }) => ({ | ||
| href: item.href, | ||
| title: item.title, | ||
| })) || [] | ||
| ); | ||
| } catch (error) { | ||
| // eslint-disable-next-line no-console | ||
| console.error('Error fetching most read items:', error); | ||
| return []; | ||
| } | ||
| }; | ||
|
|
||
| fetchMostReadItems().then((items: { href: string; title: string }[]) => { | ||
| const MOST_READ_URLS = items.map(({ href }) => href); | ||
|
|
||
| if (navigator.serviceWorker.controller) { | ||
| navigator.serviceWorker.controller.postMessage({ | ||
| type: 'CACHE_HOME_PAGE_AND_MOST_READ', | ||
| HOME_PAGE_URL, | ||
| MOST_READ_URLS, | ||
| }); | ||
| } | ||
|
|
||
| items.forEach(({ href }) => { | ||
| return href; | ||
| }); | ||
| }); | ||
|
|
||
| return ( | ||
| <> | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
where is this function defined?