Simplified service worker

This commit is contained in:
Eduard Urbach 2019-04-18 23:44:45 +09:00
parent 45643bdd92
commit 08186a9c92
2 changed files with 344 additions and 366 deletions

View File

@ -49,6 +49,7 @@ export default class Application {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let request = new XMLHttpRequest() let request = new XMLHttpRequest()
request.timeout = 20000
request.onerror = () => reject(new Error("You are either offline or the requested page doesn't exist.")) request.onerror = () => reject(new Error("You are either offline or the requested page doesn't exist."))
request.ontimeout = () => reject(new Error("The page took too much time to respond.")) request.ontimeout = () => reject(new Error("The page took too much time to respond."))
request.onload = () => { request.onload = () => {

View File

@ -32,60 +32,72 @@
// E-Tags that we served for a given URL // E-Tags that we served for a given URL
// const ETAGS = new Map<string, string>() // const ETAGS = new Map<string, string>()
// MyServiceWorker is the process that controls all the tabs in a browser. // MyCache is the cache used by the service worker.
class MyServiceWorker { class MyCache {
cache: MyCache version: string
reloads: Map<string, Promise<Response>>
excludeCache: Set<string>
constructor() { constructor(version: string) {
this.cache = new MyCache("v-6") this.version = version
this.reloads = new Map<string, Promise<Response>>()
// When these patterns are matched for the request URL, we exclude them from being
// served cache-first and instead serve them via a network request.
// Note that the service worker URL is automatically excluded from fetch events
// and therefore doesn't need to be added here.
this.excludeCache = new Set<string>([
// API requests
"/api/",
// PayPal stuff
"/paypal/",
// List imports
"/import/",
// Infinite scrolling
"/from/",
// 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) => 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)))
} }
async onInstall(evt: InstallEvent) { clear() {
return caches.delete(this.version)
}
async store(request: RequestInfo, response: Response) {
try {
// This can fail if the disk space quota has been exceeded.
let cache = await caches.open(this.version)
await cache.put(request, response)
} catch(err) {
console.log("Disk quota exceeded, can't store in cache:", request, response, err)
}
}
async serve(request: RequestInfo): Promise<Response> {
let cache = await caches.open(this.version)
let matching = await cache.match(request)
if(matching) {
return matching
}
return Promise.reject("no-match")
}
}
// Globals
let cache = new MyCache("v-7")
let reloads = new Map<string, Promise<Response>>()
// When these patterns are matched for the request URL, we exclude them from being
// served cache-first and instead serve them via a network request.
// Note that the service worker URL is automatically excluded from fetch events
// and therefore doesn't need to be added here.
let excludeCache = new Set<string>([
"/api/", // API requests
"/paypal/", // PayPal stuff
"/import/", // List imports
"/from/", // Infinite scrolling
"chrome-extension", // Chrome extension
// Authorization paths /auth/ and /logout are not listed here because they are handled in a special way.
])
// onInstall
async function onInstall(evt: InstallEvent) {
console.log("service worker install") console.log("service worker install")
await self.skipWaiting() await self.skipWaiting()
await this.installCache() await installCache()
} }
onActivate(evt: any) { // onActivate
function onActivate(evt: any) {
console.log("service worker activate") console.log("service worker activate")
// Only keep current version of the cache and delete old caches // Only keep current version of the cache and delete old caches
let cacheWhitelist = [this.cache.version] let cacheWhitelist = [cache.version]
let deleteOldCache = caches.keys().then(keyList => { let deleteOldCache = caches.keys().then(keyList => {
return Promise.all(keyList.map(key => { return Promise.all(keyList.map(key => {
@ -102,12 +114,12 @@ class MyServiceWorker {
deleteOldCache, deleteOldCache,
immediateClaim immediateClaim
]) ])
} }
// onRequest intercepts all browser requests. // onRequest intercepts all browser requests.
// Simply returning, without calling evt.respondWith(), // Simply returning, without calling evt.respondWith(),
// will let the browser deal with the request normally. // will let the browser deal with the request normally.
async onRequest(evt: FetchEvent) { async function onRequest(evt: FetchEvent) {
let request = evt.request as Request let request = evt.request as Request
// If it's not a GET request, fetch it normally. // If it's not a GET request, fetch it normally.
@ -117,12 +129,6 @@ class MyServiceWorker {
return return
} }
// DevTools opening will trigger these "only-if-cached" requests.
// https://bugs.chromium.org/p/chromium/issues/detail?id=823392
if((request.cache as string) === "only-if-cached" && request.mode !== "same-origin") {
return
}
// Video files are always loaded over the network. // Video files are always loaded over the network.
// We are defaulting to the normal browser handler here // We are defaulting to the normal browser handler here
// so we can see the HTTP 206 partial responses in DevTools // so we can see the HTTP 206 partial responses in DevTools
@ -131,7 +137,7 @@ class MyServiceWorker {
return return
} }
return evt.respondWith(fetch(request)) return //evt.respondWith(fetch(request))
// // Exclude certain URLs from being cached. // // Exclude certain URLs from being cached.
// for(let pattern of this.excludeCache.keys()) { // for(let pattern of this.excludeCache.keys()) {
@ -228,23 +234,23 @@ class MyServiceWorker {
// // Serve via network first and fallback to cache. // // Serve via network first and fallback to cache.
// evt.respondWith(this.networkFirst(request, refresh, onResponse)) // evt.respondWith(this.networkFirst(request, refresh, onResponse))
// return refresh // return refresh
} }
// onMessage is called when the service worker receives a message from a client (browser tab). // onMessage is called when the service worker receives a message from a client (browser tab).
async onMessage(evt: ServiceWorkerMessageEvent) { async function onMessage(evt: ServiceWorkerMessageEvent) {
let message = JSON.parse(evt.data) let message = JSON.parse(evt.data)
let clientId = (evt.source as any).id let clientId = (evt.source as any).id
let client = await MyClient.get(clientId) let client = await MyClient.get(clientId)
client.onMessage(message) client.onMessage(message)
} }
// onPush is called on push events and requires the payload to contain JSON information about the notification. // onPush is called on push events and requires the payload to contain JSON information about the notification.
onPush(evt: PushEvent) { function onPush(evt: PushEvent) {
var payload = evt.data ? evt.data.json() : {} var payload = evt.data ? evt.data.json() : {}
// Notify all clients about the new notification so they can update their notification counter // Notify all clients about the new notification so they can update their notification counter
this.broadcast({ broadcast({
type: "new notification" type: "new notification"
}) })
@ -253,11 +259,11 @@ class MyServiceWorker {
body: payload.message, body: payload.message,
icon: payload.icon, icon: payload.icon,
data: payload.link, data: payload.link,
badge: "https://media.notify.moe/images/brand/64.png" badge: "https://media.notify.moe/images/brand/256.png"
}) })
} }
onPushSubscriptionChange(evt: any) { function onPushSubscriptionChange(evt: any) {
return self.registration.pushManager.subscribe(evt.oldSubscription.options) return self.registration.pushManager.subscribe(evt.oldSubscription.options)
.then(async subscription => { .then(async subscription => {
console.log("send subscription to server...") console.log("send subscription to server...")
@ -291,10 +297,10 @@ class MyServiceWorker {
body: JSON.stringify(pushSubscription) body: JSON.stringify(pushSubscription)
}) })
}) })
} }
// onNotificationClick is called when the user clicks on a notification. // onNotificationClick is called when the user clicks on a notification.
onNotificationClick(evt: NotificationEvent) { function onNotificationClick(evt: NotificationEvent) {
let notification = evt.notification let notification = evt.notification
notification.close() notification.close()
@ -314,10 +320,10 @@ class MyServiceWorker {
// Otherwise open a new window // Otherwise open a new window
return self.clients.openWindow("https://notify.moe") return self.clients.openWindow("https://notify.moe")
}) })
} }
// Broadcast sends a message to all clients (open tabs etc.) // Broadcast sends a message to all clients (open tabs etc.)
broadcast(msg: object) { function broadcast(msg: object) {
const msgText = JSON.stringify(msg) const msgText = JSON.stringify(msg)
self.clients.matchAll().then(function(clientList) { self.clients.matchAll().then(function(clientList) {
@ -325,10 +331,10 @@ class MyServiceWorker {
client.postMessage(msgText) client.postMessage(msgText)
} }
}) })
} }
// installCache is called when the service worker is installed for the first time. // installCache is called when the service worker is installed for the first time.
async installCache() { async function installCache() {
let urls = [ let urls = [
"/", "/",
"/scripts", "/scripts",
@ -345,16 +351,16 @@ class MyServiceWorker {
mode: "cors" mode: "cors"
}) })
let promise = fetch(request).then(response => this.cache.store(request, response)) let promise = fetch(request).then(response => cache.store(request, response))
promises.push(promise) promises.push(promise)
} }
return Promise.all(promises) return Promise.all(promises)
} }
// Serve network first. // Serve network first.
// Fall back to cache. // Fall back to cache.
async networkFirst(request: Request, network: Promise<Response>, onResponse: (r: Response) => Response): Promise<Response> { async function networkFirst(request: Request, network: Promise<Response>, onResponse: (r: Response) => Response): Promise<Response> {
let response: Response | null let response: Response | null
try { try {
@ -364,22 +370,22 @@ class MyServiceWorker {
// console.log("Network MISS:", request.url, error) // console.log("Network MISS:", request.url, error)
try { try {
response = await this.cache.serve(request) response = await cache.serve(request)
} catch(error) { } catch(error) {
return Promise.reject(error) return Promise.reject(error)
} }
} }
return onResponse(response) return onResponse(response)
} }
// Serve cache first. // Serve cache first.
// Fall back to network. // Fall back to network.
async cacheFirst(request: Request, network: Promise<Response>, onResponse: (r: Response) => Response): Promise<Response> { async function cacheFirst(request: Request, network: Promise<Response>, onResponse: (r: Response) => Response): Promise<Response> {
let response: Response | null let response: Response | null
try { try {
response = await this.cache.serve(request) response = await cache.serve(request)
// console.log("Cache HIT:", request.url) // console.log("Cache HIT:", request.url)
} catch(error) { } catch(error) {
// console.log("Cache MISS:", request.url, error) // console.log("Cache MISS:", request.url, error)
@ -392,41 +398,6 @@ class MyServiceWorker {
} }
return onResponse(response) return onResponse(response)
}
}
// MyCache is the cache used by the service worker.
class MyCache {
version: string
constructor(version: string) {
this.version = version
}
clear() {
return caches.delete(this.version)
}
async store(request: RequestInfo, response: Response) {
try {
// This can fail if the disk space quota has been exceeded.
let cache = await caches.open(this.version)
await cache.put(request, response)
} catch(err) {
console.log("Disk quota exceeded, can't store in cache:", request, response, err)
}
}
async serve(request: RequestInfo): Promise<Response> {
let cache = await caches.open(this.version)
let matching = await cache.match(request)
if(matching) {
return matching
}
return Promise.reject("no-match")
}
} }
// MyClient represents a single tab in the browser. // MyClient represents a single tab in the browser.
@ -462,7 +433,7 @@ class MyClient {
case "broadcast": case "broadcast":
message.type = message.realType message.type = message.realType
delete message.realType delete message.realType
serviceWorker.broadcast(message) broadcast(message)
break break
} }
} }
@ -488,5 +459,11 @@ function trimPrefix(text, prefix) {
return text return text
} }
// Initialize the service worker // Register event listeners
const serviceWorker = new MyServiceWorker() self.addEventListener("install", (evt: InstallEvent) => evt.waitUntil(onInstall(evt)))
self.addEventListener("activate", (evt: any) => evt.waitUntil(onActivate(evt)))
self.addEventListener("fetch", (evt: FetchEvent) => evt.waitUntil(onRequest(evt)))
self.addEventListener("message", (evt: any) => evt.waitUntil(onMessage(evt)))
self.addEventListener("push", (evt: PushEvent) => evt.waitUntil(onPush(evt)))
self.addEventListener("pushsubscriptionchange", (evt: any) => evt.waitUntil(onPushSubscriptionChange(evt)))
self.addEventListener("notificationclick", (evt: NotificationEvent) => evt.waitUntil(onNotificationClick(evt)))