Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
perf: hashed build chunks are served from the cache, and cached a year by nginx
Duarte Santoscd217c214d4b
diff --git a/frontend/public/sw.js b/frontend/public/sw.jsindex f6822658d..ec092ab15 100644--- a/frontend/public/sw.js+++ b/frontend/public/sw.js@@ -252,6 +252,17 @@ const API = (() => { try { return new URL('api/', location.href).pathname } catc// How long a request for the app itself waits on the network before a cached copy answers it.const NET_WAIT_MS = 3000+// The build's own chunks and stylesheets (assets/<name>-<hash>.js|css): the name changes whenever+// the content does, so a copy in this build's cache is the file, and a start serves them from+// here instead of asking the network about each of them again (40-odd round trips before Home).+const isHashedAsset = p => /\/assets\/[^/]+-[A-Za-z0-9_-]{8}\.(?:js|css)$/.test(p)+const cacheFirst = e => caches.match(e.request, { ignoreSearch: true }).then(hit => hit || fetch(e.request).then(res => {+ // Only a real answer is kept: an auth proxy's login page would otherwise stand in for the chunk+ // for the rest of this build.+ if (res.ok && !res.redirected) { const copy = res.clone(); caches.open(CACHE).then(c => c.put(e.request, copy)).catch(() => {}) }+ return res+}))+self.addEventListener('fetch', e => {const url = new URL(e.request.url)if (e.request.method !== 'GET' || url.origin !== location.origin) return@@ -261,6 +272,10 @@ self.addEventListener('fetch', e => {e.respondWith(media(e))return}+ if (isHashedAsset(url.pathname)) {+ e.respondWith(cacheFirst(e))+ return+ }// Network first; the copy for the cache is cloned before the response is handed to the page —// cloning later, once the page has started reading the body, throws and caches nothing, which// is why the shell never used to survive an offline reload.diff --git a/frontend/src/lib/api-base.test.js b/frontend/src/lib/api-base.test.jsindex 070575a51..87c4b2951 100644--- a/frontend/src/lib/api-base.test.js+++ b/frontend/src/lib/api-base.test.js@@ -77,12 +77,33 @@ describe('the cache lifetime nginx gives an image', () => {it('is said once, by the explicit header, with no expires beside it', () => {expect(NGINX.replace(/#.*$/gm, '')).not.toMatch(/\bexpires\b/)// the exercise media's own block and every other image's- const media = blocksOf(NGINX).filter(b => /\bimmutable\b/.test(b))+ const media = blocksOf(NGINX).filter(b => /\bimmutable\b/.test(b) && !/31536000/.test(b))expect(media.length).toBe(2)for (const b of media) expect(b).toMatch(/\badd_header\s+Cache-Control\s+"public, max-age=2592000, immutable"\s*;/)})})+// A build chunk's name carries its content hash: kept a year without asking again. The shell,+// sw.js, the manifest and anything without a hash in its name still revalidate every time.+describe('the cache lifetime nginx gives a build chunk', () => {+ const at = NGINX.indexOf('location ~* /assets/')+ it('is a year, immutable, with the same security headers, ahead of the shell rule', () => {+ expect(at).toBeGreaterThan(-1)+ expect(at).toBeLessThan(NGINX.indexOf('location ~* \\.(js|css|json|html)$'))+ const [block] = blocksOf(NGINX.slice(at))+ expect(block).toMatch(/\badd_header\s+Cache-Control\s+"public, max-age=31536000, immutable"\s*;/)+ expect(block).toMatch(/\badd_header\s+Content-Security-Policy\s+"X"\s+always\s*;/)+ expect(block).toMatch(/\badd_header\s+X-Content-Type-Options\s+"nosniff"\s+always\s*;/)+ })+ it('matches hashed chunks only', () => {+ const re = new RegExp(/location ~\* (\S+) \{/.exec(NGINX.slice(at))[1], 'i')+ for (const u of ['/assets/index-DdAX9ec6.js', '/gym/assets/rolldown-runtime-QTnfLwEv.js', '/assets/index-zMZnqmc9.css', '/assets/pt-BR-p55Y2oCC.js'])+ expect(re.test(u), u).toBe(true)+ for (const u of ['/sw.js', '/index.html', '/manifest.json', '/assets/index.js', '/icon-180.png'])+ expect(re.test(u), u).toBe(false)+ })+})+// The exercise media are licensed for openGym only: Cross-Origin-Resource-Policy keeps another// site from embedding them, on every answer under /exercise-media/, at the site root and under a// BASE_PATH alike. An add_header in a block replaces the inherited ones, so the nested block@@ -174,14 +195,14 @@ describe('what nginx forwards to the API', () => {// to @root, and @root sent it back to /g+ym/, forever; the assets and images 404'd.describe('the file nginx looks for under BASE_PATH', () => {const REWRITE = /\brewrite\s+(\S+)\s+(\S+)\s+break\s*;/g- // All five rewrites (the app's prefix block, the two cache blocks, and the exercise media's+ // All six rewrites (the app's prefix block, the three cache blocks, and the exercise media's// block and its nested cache block) give the same answer.function onDisk(base, uri) {const got = [...render(base).matchAll(REWRITE)].map(([, pattern, to]) => {const m = new RegExp(quoted(pattern)).exec(uri)return m ? to.replace(/\$(\d)/g, (_, i) => m[i]) : uri})- expect(got.length).toBe(5)+ expect(got.length).toBe(6)expect(new Set(got).size).toBe(1)return got[0]}diff --git a/frontend/src/lib/sw-offline-launch.test.js b/frontend/src/lib/sw-offline-launch.test.jsindex 3b6a57884..4a8832139 100644--- a/frontend/src/lib/sw-offline-launch.test.js+++ b/frontend/src/lib/sw-offline-launch.test.js@@ -136,9 +136,10 @@ describe('service worker offline cold-launch (issue #274)', () => {it('a script whose body is still arriving after 3 s reaches the page whole, and is cached', async () => {const net = slowBody('export const pack = {', ' hello: "Hallo" }')const { listeners, cache, clock } = loadServiceWorker({ fetchImpl: net.fetch })- await cache.put('https://gym.example/assets/de-abc.js', new Response('the copy from the last build'))+ // Not a hashed build chunk (those are served from the cache once they are in it, below).+ await cache.put('https://gym.example/locale/de.js', new Response('the copy from the last build'))- const e = makeFetchEvent('https://gym.example/assets/de-abc.js', 'cors')+ const e = makeFetchEvent('https://gym.example/locale/de.js', 'cors')listeners.fetch(e)const res = await e.responseawait clock.advance(3000)@@ -146,7 +147,7 @@ describe('service worker offline cold-launch (issue #274)', () => {expect(await res.text()).toBe('export const pack = { hello: "Hallo" }')await settle()- expect(await (await cache.match('https://gym.example/assets/de-abc.js')).text()).toBe('export const pack = { hello: "Hallo" }')+ expect(await (await cache.match('https://gym.example/locale/de.js')).text()).toBe('export const pack = { hello: "Hallo" }')})it('a request the cache cannot answer waits for a slow network past 3 s instead of failing', async () => {@@ -182,4 +183,31 @@ describe('service worker offline cold-launch (issue #274)', () => {await clock.advance(3000)expect(await (await e.response).text()).toBe('cached-shell')})++ // A hashed chunk never changes under its name, so a start does not ask the network about it.+ it('a hashed build chunk in the cache is answered from it without the network', async () => {+ let asked = 0+ const { listeners, cache } = loadServiceWorker({ fetchImpl: () => { asked++; return Promise.resolve(new Response('net')) } })+ await cache.put('https://gym.example/assets/Stats-Be9GntYl.js', new Response('cached chunk'))+ const e = makeFetchEvent('https://gym.example/assets/Stats-Be9GntYl.js', 'cors')+ listeners.fetch(e)+ expect(await (await e.response).text()).toBe('cached chunk')+ expect(asked).toBe(0)+ })++ it('a hashed chunk not cached yet comes from the network and is kept, a redirected answer is not', async () => {+ const answers = [new Response('export default 1'), Object.assign(new Response('<html>login</html>'), {})]+ Object.defineProperty(answers[1], 'redirected', { value: true })+ const { listeners, cache } = loadServiceWorker({ fetchImpl: () => Promise.resolve(answers.shift()) })+ const e = makeFetchEvent('https://gym.example/gym/assets/index-DdAX9ec6.js', 'cors')+ listeners.fetch(e)+ expect(await (await e.response).text()).toBe('export default 1')+ await settle()+ expect(await (await cache.match('https://gym.example/gym/assets/index-DdAX9ec6.js')).text()).toBe('export default 1')+ const e2 = makeFetchEvent('https://gym.example/assets/sheets-ficOiT8i.js', 'cors')+ listeners.fetch(e2)+ await e2.response+ await settle()+ expect(await cache.match('https://gym.example/assets/sheets-ficOiT8i.js')).toBeUndefined()+ })})diff --git a/web/nginx.conf.template b/web/nginx.conf.templateindex a9641d0c7..d7cedec89 100644--- a/web/nginx.conf.template+++ b/web/nginx.conf.template@@ -133,6 +133,19 @@ server {return 302 ${BASE_PATH}/$is_args$args;}+ # The build's chunks and stylesheets carry a hash of their content in the name (Vite's+ # assets/<name>-<hash>.js), so a new build is new names: cache them hard, no revalidation.+ # Before the shell rule below, since the first matching regex location wins. (No {8} for the+ # hash: a brace in an unquoted nginx regex opens a block.)+ location ~* /assets/[^/]+-[A-Za-z0-9_-]+\.(js|css)$ {+ rewrite ^\Q${BASE_PATH}\E/(.*)$ /$1 break;+ add_header Cache-Control "public, max-age=31536000, immutable";+ add_header X-Frame-Options "DENY" always;+ add_header X-Content-Type-Options "nosniff" always;+ add_header Referrer-Policy "same-origin" always;+ add_header Content-Security-Policy "${CONTENT_SECURITY_POLICY}" always;+ }+# App shell: always revalidate so updates show up immediatelylocation ~* \.(js|css|json|html)$ {# A regex location wins over the prefix block above, so it never saw its rewrite and