Improved CSS reloads in service worker

This commit is contained in:
Eduard Urbach 2017-10-19 04:36:05 +02:00
parent d72543b31e
commit 24914cb6ff
2 changed files with 263 additions and 210 deletions

View File

@ -250,6 +250,10 @@ export class AnimeNotifier {
}
break
case "reload page":
location.reload(true)
break
}
}

View File

@ -1,6 +1,5 @@
// pack:ignore
const CACHE = "v-3"
const RELOADS = new Map<string, Promise<Response>>()
const ETAGS = new Map<string, string>()
const CACHEREFRESH = new Map<string, Promise<void>>()
@ -18,24 +17,55 @@ const EXCLUDECACHE = new Set<string>([
"/from/",
// Chrome extension
"chrome-extension"
"chrome-extension",
// Authorization paths /auth/ and /logout are not listed here because they are handled in a special way.
])
self.addEventListener("install", (evt: InstallEvent) => {
class MyCache {
version: string
constructor(version: string) {
this.version = version
}
store(request: RequestInfo, response: Response) {
return caches.open(this.version).then(cache => {
return cache.put(request, response)
})
}
}
class MyServiceWorker {
cache: MyCache
currentCSP: string
constructor() {
this.cache = new MyCache("v-3")
this.currentCSP = ""
self.addEventListener("install", (evt: InstallEvent) => evt.waitUntil(this.onInstall(evt)))
self.addEventListener("activate", (evt: any) => evt.waitUntil(this.onActivate(evt)))
self.addEventListener("fetch", (evt: FetchEvent) => evt.waitUntil(this.onRequest(evt)))
self.addEventListener("message", (evt: any) => evt.waitUntil(this.onMessage(evt)))
self.addEventListener("push", (evt: PushEvent) => evt.waitUntil(this.onPush(evt)))
self.addEventListener("pushsubscriptionchange", (evt: any) => evt.waitUntil(this.onPushSubscriptionChange(evt)))
self.addEventListener("notificationclick", (evt: NotificationEvent) => evt.waitUntil(this.onNotificationClick(evt)))
}
onInstall(evt: InstallEvent) {
console.log("service worker install")
evt.waitUntil(
(self as any).skipWaiting().then(() => {
return installCache()
})
)
return (self as any).skipWaiting().then(() => {
return this.installCache()
})
}
self.addEventListener("activate", (evt: any) => {
onActivate(evt: any) {
console.log("service worker activate")
// Delete old cache
let cacheWhitelist = [CACHE]
// Only keep current version of the cache and delete old caches
let cacheWhitelist = [this.cache.version]
let deleteOldCache = caches.keys().then(keyList => {
return Promise.all(keyList.map(key => {
@ -45,125 +75,49 @@ self.addEventListener("activate", (evt: any) => {
}))
})
// Immediate claim helps us gain control over a new client immediately
let immediateClaim = (self as any).clients.claim()
// Immediate claim
evt.waitUntil(
Promise.all([
return Promise.all([
deleteOldCache,
immediateClaim
])
)
})
// controlling service worker
self.addEventListener("message", (evt: any) => {
let message = JSON.parse(evt.data)
let url = message.url
let refresh = RELOADS.get(url)
let servedETag = ETAGS.get(url)
// If the user requests a sub-page we should prefetch the full page, too.
if(url.includes("/_/")) {
let fullPage = new Request(url.replace("/_/", "/"))
fetch(fullPage, {
credentials: "same-origin"
})
.then(response => {
// Save the new version of the resource in the cache
let cacheRefresh = caches.open(CACHE).then(cache => {
return cache.put(fullPage, response)
})
CACHEREFRESH.set(fullPage.url, cacheRefresh)
return cacheRefresh
})
}
if(!refresh || !servedETag) {
return
}
evt.waitUntil(
refresh.then((response: Response) => {
// If the fresh copy was used to serve the request instead of the cache,
// we don"t need to tell the client to do a refresh.
if(response.bodyUsed) {
return
}
let eTag = response.headers.get("ETag")
if(eTag === servedETag) {
return
}
ETAGS.set(url, eTag)
let message = {
type: "new content",
url
}
let cacheRefresh = CACHEREFRESH.get(url)
if(!cacheRefresh) {
console.log("forcing reload, cache refresh null")
return evt.source.postMessage(JSON.stringify(message))
}
return cacheRefresh.then(() => {
console.log("forcing reload after cache refresh")
evt.source.postMessage(JSON.stringify(message))
})
})
)
})
self.addEventListener("fetch", async (evt: FetchEvent) => {
onRequest(evt: FetchEvent) {
let request = evt.request as Request
let isAuth = request.url.includes("/auth/") || request.url.includes("/logout")
let ignoreCache = false
// console.log("fetch:", request.url)
// If it's not a GET request, fetch it normally
if(request.method !== "GET") {
return evt.respondWith(fetch(request))
}
// Clear cache on authentication and fetch it normally
if(request.url.includes("/auth/") || request.url.includes("/logout")) {
return caches.delete(this.cache.version).then(() => evt.respondWith(fetch(request)))
}
// Exclude certain URLs from being cached
for(let pattern of EXCLUDECACHE.keys()) {
if(request.url.includes(pattern)) {
ignoreCache = true
break
return evt.respondWith(fetch(request))
}
}
// Delete existing cache on authentication
if(isAuth) {
caches.delete(CACHE)
}
// Do not use cache in some cases
if(request.method !== "GET" || isAuth || ignoreCache) {
return evt.waitUntil(evt.respondWith(fetch(request)))
}
// Forced cache response?
// If the request included the header "X-CacheOnly", return a cache-only response.
// This is used in reloads to avoid generating a 2nd request after a cache refresh.
if(request.headers.get("X-CacheOnly") === "true") {
// console.log("forced cache response")
return evt.waitUntil(fromCache(request))
return this.fromCache(request)
}
let servedETag = undefined
// Start fetching the request
let refresh = fetch(request).then(response => {
// console.log(response)
let clone = response.clone()
// Save the new version of the resource in the cache
let cacheRefresh = caches.open(CACHE).then(cache => {
return cache.put(request, clone)
})
let cacheRefresh = this.cache.store(request, clone)
CACHEREFRESH.set(request.url, cacheRefresh)
@ -174,44 +128,108 @@ self.addEventListener("fetch", async (evt: FetchEvent) => {
RELOADS.set(request.url, refresh)
// Forced reload
if(request.headers.get("X-Reload") === "true") {
return evt.waitUntil(evt.respondWith(refresh.then(response => {
let servedETag = undefined
let onResponse = response => {
servedETag = response.headers.get("ETag")
ETAGS.set(request.url, servedETag)
return response
})))
}
if(request.headers.get("X-Reload") === "true") {
return evt.respondWith(refresh.then(onResponse))
}
// Try to serve cache first and fall back to network response
let networkOrCache = fromCache(request).then(response => {
// console.log("served from cache:", request.url)
servedETag = response.headers.get("ETag")
ETAGS.set(request.url, servedETag)
return response
}).catch(error => {
let networkOrCache = this.fromCache(request).then(onResponse).catch(error => {
// console.log("Cache MISS:", request.url)
return refresh
})
return evt.waitUntil(evt.respondWith(networkOrCache))
return evt.respondWith(networkOrCache)
}
onMessage(evt: any) {
let message = JSON.parse(evt.data)
let url = message.url
let refresh = RELOADS.get(url)
let servedETag = ETAGS.get(url)
// If the user requests a sub-page we should prefetch the full page, too.
if(url.includes("/_/")) {
let fullPage = new Request(url.replace("/_/", "/"))
let fullPageRefresh = fetch(fullPage, {
credentials: "same-origin"
}).then(response => {
// Save the new version of the resource in the cache
let cacheRefresh = caches.open(this.cache.version).then(cache => {
return cache.put(fullPage, response)
})
self.addEventListener("push", (evt: PushEvent) => {
CACHEREFRESH.set(fullPage.url, cacheRefresh)
return response
})
// Save in map
RELOADS.set(fullPage.url, fullPageRefresh)
}
if(!refresh || !servedETag) {
return Promise.resolve()
}
return refresh.then((response: Response) => {
// If the fresh copy was used to serve the request instead of the cache,
// we don"t need to tell the client to do a refresh.
if(response.bodyUsed) {
return
}
// Get ETag
let eTag = response.headers.get("ETag")
// Update ETag
ETAGS.set(url, eTag)
// Get CSP
let oldCSP = this.currentCSP
let csp = response.headers.get("Content-Security-Policy")
if(csp != oldCSP) {
this.currentCSP = csp
if(oldCSP !== "") {
return this.forceClientReloadPage(url, evt.source)
}
}
// If the ETag changed, we need to do a reload.
// If the CSP and therefore the sha-1 hash of the CSS changed, we need to do a reload.
if(eTag !== servedETag) {
return this.forceClientReloadContent(url, evt.source)
}
// Do nothing
return Promise.resolve()
})
}
onPush(evt: PushEvent) {
var payload = evt.data ? evt.data.json() : {}
evt.waitUntil(
(self as any).registration.showNotification(payload.title, {
return (self as any).registration.showNotification(payload.title, {
body: payload.message,
icon: payload.icon,
image: payload.image,
data: payload.link,
badge: "https://notify.moe/brand/64"
})
)
badge: "https://notify.moe/brand/64.png"
})
}
self.addEventListener("pushsubscriptionchange", (evt: any) => {
evt.waitUntil((self as any).registration.pushManager.subscribe(evt.oldSubscription.options)
onPushSubscriptionChange(evt: any) {
return (self as any).registration.pushManager.subscribe(evt.oldSubscription.options)
.then(async subscription => {
console.log("send subscription to server...")
@ -242,15 +260,14 @@ self.addEventListener("pushsubscriptionchange", (evt: any) => {
credentials: "same-origin",
body: JSON.stringify(pushSubscription)
})
}))
})
}
self.addEventListener("notificationclick", (evt: NotificationEvent) => {
onNotificationClick(evt: NotificationEvent) {
let notification = evt.notification
notification.close()
evt.waitUntil(
(self as any).clients.matchAll().then(function(clientList) {
return (self as any).clients.matchAll().then(function(clientList) {
// If we have a link, use that link to open a new window.
let url = notification.data
@ -266,11 +283,40 @@ self.addEventListener("notificationclick", (evt: NotificationEvent) => {
// Otherwise open a new window
return (self as any).clients.openWindow("https://notify.moe")
})
)
})
}
function installCache() {
return caches.open(CACHE).then(cache => {
forceClientReloadContent(url: string, eventSource: any) {
let message = {
type: "new content",
url
}
this.postMessageAfterPromise(message, CACHEREFRESH.get(url), eventSource)
}
forceClientReloadPage(url: string, eventSource: any) {
let message = {
type: "reload page",
url
}
this.postMessageAfterPromise(message, RELOADS.get(url.replace("/_/", "/")), eventSource)
}
postMessageAfterPromise(message: any, promise: Promise<any>, eventSource: any) {
if(!promise) {
console.log("forcing reload, cache refresh null")
return eventSource.postMessage(JSON.stringify(message))
}
return promise.then(() => {
console.log("forcing reload after cache refresh")
eventSource.postMessage(JSON.stringify(message))
})
}
installCache() {
return caches.open(this.cache.version).then(cache => {
return cache.addAll([
"./",
"./scripts",
@ -279,8 +325,8 @@ function installCache() {
})
}
function fromCache(request) {
return caches.open(CACHE).then(cache => {
fromCache(request) {
return caches.open(this.cache.version).then(cache => {
return cache.match(request).then(matching => {
if(matching) {
// console.log("Cache HIT:", request.url)
@ -291,3 +337,6 @@ function fromCache(request) {
})
})
}
}
const serviceWorker = new MyServiceWorker()