Skip to content
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

Cache Playground assets to enable offline support #1535

Merged
merged 134 commits into from
Jul 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
134 commits
Select commit Hold shift + click to select a range
6d9e165
ZIP WP assets
bgrgicak Jun 20, 2024
75bc2bb
Add afterWordPressInstall hook to boot
bgrgicak Jun 21, 2024
6c2b0ad
Download assets after WordPress is installed
bgrgicak Jun 21, 2024
57daebb
Merge branch 'trunk' into add/wp-static-asset-zip
bgrgicak Jun 21, 2024
42be4fc
Use getWordPressVersionFromPhp
bgrgicak Jun 21, 2024
be0aa0e
Add offline testing instructions
bgrgicak Jun 21, 2024
19da646
Add fetch caching
bgrgicak Jun 21, 2024
1170ab5
Fix manifests
bgrgicak Jun 21, 2024
9df228d
Remove caching from remote
bgrgicak Jun 21, 2024
fd8dc13
PHP-wasm caching TODO clean up code
bgrgicak Jun 21, 2024
8beee0c
Remove bootWordPress hook
bgrgicak Jun 24, 2024
6cf5fef
Use wordPressSiteUrl
bgrgicak Jun 24, 2024
1f2347e
Stream static asset response instead of awaiting
bgrgicak Jun 24, 2024
f1e2784
Use request handler to get document root
bgrgicak Jun 24, 2024
dbb43aa
Merge branch 'add/wp-static-asset-zip' into add/fetch-caching
bgrgicak Jun 24, 2024
1ec9d62
Preload worker
bgrgicak Jun 24, 2024
df506d1
Prevent worker update error when offline
bgrgicak Jun 24, 2024
3c98912
Add warning if assets weren't downloaded
bgrgicak Jun 25, 2024
e703eff
Merge branch 'trunk' into add/wp-static-asset-zip
bgrgicak Jun 25, 2024
2e3910c
Async fetch
bgrgicak Jun 25, 2024
d2ca9c2
Update error messages
bgrgicak Jun 25, 2024
4a1f8d0
Use wpVersionToStaticAssetsDirectory
bgrgicak Jun 25, 2024
efb4b57
Use getLoadedWordPressVersion
bgrgicak Jun 25, 2024
b2ba22b
downloadWordPressAssets on load
bgrgicak Jun 26, 2024
1aad0d0
Remove logs
bgrgicak Jun 26, 2024
db8c25f
Merge branch 'trunk' into add/wp-static-asset-zip
bgrgicak Jun 26, 2024
d7d10fb
Merge branch 'add/wp-static-asset-zip' into add/fetch-caching
bgrgicak Jun 26, 2024
de6e819
Preload assets when offline
bgrgicak Jun 27, 2024
2ac8e60
Update progress bar
bgrgicak Jun 27, 2024
782d222
Add cache versioning
bgrgicak Jun 27, 2024
c34fd37
Don't assume that referrer is a valid url
bgrgicak Jun 27, 2024
5e4d336
Remove cache full check
bgrgicak Jun 27, 2024
aa68518
Precache all assets
bgrgicak Jun 27, 2024
e5993f8
Add missing resources to precache
bgrgicak Jun 27, 2024
149cd34
Fix linter issue
bgrgicak Jun 27, 2024
d0254b8
Preload remote assets
bgrgicak Jun 27, 2024
67c3893
Move cache to one file
bgrgicak Jun 27, 2024
de206a1
Merge branch 'trunk' into add/wp-static-asset-zip
bgrgicak Jun 28, 2024
265088c
Merge branch 'add/wp-static-asset-zip' into add/fetch-caching
bgrgicak Jun 28, 2024
a6f20bd
Empty remote asset paths after done instead of deleting it, update co…
bgrgicak Jun 28, 2024
06c4a2f
Merge branch 'add/wp-static-asset-zip' into add/fetch-caching
bgrgicak Jun 28, 2024
42e2913
Linter errors
bgrgicak Jun 28, 2024
e568b9e
Use cache version
bgrgicak Jun 28, 2024
2b09fad
Update method name to backfillStaticFilesRemovedFromMinifiedBuild
bgrgicak Jun 28, 2024
d4dd04c
Move cache file generation to plugin
bgrgicak Jul 1, 2024
ebfa224
Merge branch 'trunk' into add/wp-static-asset-zip
bgrgicak Jul 1, 2024
44c2d8e
Merge branch 'add/wp-static-asset-zip' into add/fetch-caching
bgrgicak Jul 1, 2024
8ecc3ad
Add preload paths TODO static asset path
bgrgicak Jul 1, 2024
37c0b91
Update packages/playground/remote/src/lib/worker-thread.ts
bgrgicak Jul 2, 2024
e1961cc
Fix static asset regex
bgrgicak Jul 2, 2024
ee044ae
Linter fixes
bgrgicak Jul 2, 2024
a01cb3b
Merge branch 'add/wp-static-asset-zip' into add/fetch-caching
bgrgicak Jul 2, 2024
f8dab44
Build static assets
bgrgicak Jul 2, 2024
ff10c52
Merge branch 'add/wp-static-asset-zip' into add/fetch-caching
bgrgicak Jul 2, 2024
5a6b574
Linter fix
bgrgicak Jul 2, 2024
6f48337
Use unzipFile
bgrgicak Jul 4, 2024
d34f066
Fix dependencies
bgrgicak Jul 4, 2024
cad7fb0
Merge branch 'add/wp-static-asset-zip' into add/fetch-caching
bgrgicak Jul 4, 2024
ba75171
Use request as cache key and ignoreSearch when matching
bgrgicak Jul 4, 2024
b9ec8c3
Send startup options as message
bgrgicak Jul 4, 2024
1feb41a
Update static asset zips
bgrgicak Jul 4, 2024
03b0138
Merge branch 'add/wp-static-asset-zip' into add/fetch-caching
bgrgicak Jul 4, 2024
a2a8d86
Load service worker after startup options are sent
bgrgicak Jul 4, 2024
f3fe08d
Merge branch 'trunk' into add/wp-static-asset-zip
bgrgicak Jul 4, 2024
cca0db5
Linter fixes
bgrgicak Jul 4, 2024
966f7bf
Generate a list assets to cache for offline support
bgrgicak Jul 4, 2024
eba73a6
Merge branch 'add/vite-cache-paths-plugin' into add/fetch-caching
bgrgicak Jul 4, 2024
14f3eb1
Send startup options as message
bgrgicak Jul 4, 2024
24f2eeb
Load service worker after startup options are sent
bgrgicak Jul 4, 2024
1182acb
Merge branch 'update/set-startup-options-with-messages' into add/fetc…
bgrgicak Jul 4, 2024
15717aa
Linter fix
bgrgicak Jul 4, 2024
83d4c5d
Merge branch 'update/set-startup-options-with-messages' into add/fetc…
bgrgicak Jul 4, 2024
da7fad9
Remove comment
bgrgicak Jul 4, 2024
7c69b09
Await for params in worker-utils
bgrgicak Jul 5, 2024
9aff520
Merge branch 'update/set-startup-options-with-messages' into add/fetc…
bgrgicak Jul 5, 2024
97d95f3
Set web worker startup options with messages instead of query strings…
bgrgicak Jul 9, 2024
f0378d0
Remove unused zip delete
bgrgicak Jul 10, 2024
7c205fa
Update remote asset PR comment
bgrgicak Jul 10, 2024
e03c9ad
Merge branch 'trunk' into add/wp-static-asset-zip
bgrgicak Jul 10, 2024
9f2d128
Merge branch 'add/wp-static-asset-zip' into add/vite-cache-paths-plugin
bgrgicak Jul 10, 2024
9f1ad7c
Remove unused manifest
bgrgicak Jul 10, 2024
7c886d4
Remove worker url params
bgrgicak Jul 10, 2024
e23cbb8
Merge branch 'trunk' into add/vite-cache-paths-plugin
bgrgicak Jul 10, 2024
946a6d7
Merge branch 'add/vite-cache-paths-plugin' into add/fetch-caching
bgrgicak Jul 10, 2024
a746657
Update filter to exclude files instead include
bgrgicak Jul 10, 2024
33dc880
Merge branch 'add/vite-cache-paths-plugin' into add/fetch-caching
bgrgicak Jul 10, 2024
2567903
Apply suggestions from code review
bgrgicak Jul 10, 2024
29f7868
Revert "Set web worker startup options with messages instead of query…
bgrgicak Jul 12, 2024
bdb6d41
Reset spawnPHPWorkerThread
bgrgicak Jul 12, 2024
194f7e9
Update patternsToNotCache list and document why files are excluded
bgrgicak Jul 12, 2024
da4b2d1
Apply suggestions from code review
bgrgicak Jul 15, 2024
0746125
Rename plugin and make file name configurable
bgrgicak Jul 15, 2024
2110676
Add distDirectoriesToList
bgrgicak Jul 15, 2024
83499b5
Rename to absoluteDirPath
bgrgicak Jul 15, 2024
9657274
Merge branch 'trunk' into add/vite-cache-paths-plugin
bgrgicak Jul 15, 2024
733ab4a
Merge branch 'add/vite-cache-paths-plugin' into add/fetch-caching
bgrgicak Jul 15, 2024
8f858d1
Remove backfill code
bgrgicak Jul 15, 2024
e7d7f81
Fix small bugs
bgrgicak Jul 15, 2024
c50cc9e
Merge branch 'trunk' into add/fetch-caching
bgrgicak Jul 16, 2024
b37f835
Merge branch 'trunk' into add/fetch-caching
bgrgicak Jul 16, 2024
d5b8198
Update asset list
bgrgicak Jul 16, 2024
973e88d
Remove manifest changes
bgrgicak Jul 16, 2024
34b481c
Fix manifest paths
bgrgicak Jul 16, 2024
4adaffa
Fix dev server manifest
bgrgicak Jul 16, 2024
7eb35d7
Add development mode to wasm-wordpress-net build
bgrgicak Jul 16, 2024
6fecfc1
Merge branch 'trunk' into fix/manifest-json-domains
bgrgicak Jul 16, 2024
f1e34ec
Move to a plugin
bgrgicak Jul 16, 2024
038982f
Update readme
bgrgicak Jul 16, 2024
b321514
Get url from env variable
bgrgicak Jul 17, 2024
1245978
Reset project.json
bgrgicak Jul 17, 2024
ec9d917
Run generateManifestJson only when needed
bgrgicak Jul 17, 2024
61d4d23
Update docblock
bgrgicak Jul 17, 2024
13ee2f0
Update packages/vite-extensions/vite-manifest.ts
bgrgicak Jul 17, 2024
582b722
Merge branch 'trunk' into fix/manifest-json-domains
bgrgicak Jul 17, 2024
a6a1555
Merge branch 'fix/manifest-json-domains' into add/fetch-caching
bgrgicak Jul 17, 2024
ef533dc
Update README.md
bgrgicak Jul 17, 2024
fbe1c65
Move caching to Remote
bgrgicak Jul 17, 2024
cb3e05c
Remove cacheVersion
bgrgicak Jul 17, 2024
ec6a38d
Update packages/vite-extensions/vite-manifest.ts
bgrgicak Jul 18, 2024
7e82e58
Document caching
bgrgicak Jul 18, 2024
b316de4
Update README.md
bgrgicak Jul 18, 2024
ac95c5e
Merge branch 'fix/manifest-json-domains' into add/fetch-caching
bgrgicak Jul 18, 2024
353522c
Merge branch 'trunk' into add/fetch-caching
bgrgicak Jul 18, 2024
5eee778
Merge branch 'trunk' into add/fetch-caching
bgrgicak Jul 19, 2024
b888b97
Cache the current hostname
bgrgicak Jul 22, 2024
a6462e0
Merge branch 'trunk' into add/fetch-caching
bgrgicak Jul 22, 2024
c8796d6
Rename method to shouldCacheUrl
bgrgicak Jul 22, 2024
f0d00e8
Merge branch 'trunk' into add/fetch-caching
bgrgicak Jul 23, 2024
8003609
Rename OfflineModeCache class and update warning
bgrgicak Jul 23, 2024
60c8c60
Fix sw update warning
bgrgicak Jul 23, 2024
c4533d9
Swallow the registration.update() error, add a few comments
adamziel Jul 23, 2024
77a813f
Address feedback
bgrgicak Jul 24, 2024
26abb6b
Support offline mode after the first Playground page load (#1643)
adamziel Jul 24, 2024
fa8c800
Merge branch 'trunk' into add/fetch-caching
bgrgicak Jul 24, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,35 @@ PHP=7.4 npx @php-wasm/cli -v
npx @php-wasm/cli phpcbf
```

### Test offline support

To test the offline support you need to build the website and run a local server:

```bash
PLAYGROUND_URL=http://localhost:9999 npx nx run playground-website:build:wasm-wordpress-net
```

Then you can run a local server:

```bash
php -S localhost:9999 -t dist/packages/playground/wasm-wordpress-net
```

or using Docker:

```bash
docker run --rm -p 9999:80 -v $(pwd)/dist/packages/playground/wasm-wordpress-net:/usr/share/nginx/html:ro nginx:alpine
```

#### Using the browser to test the offline support

1. Open the browser and go to `http://localhost:9999`.
2. Open the browser's developer tools.
3. Go to the "Network" tab.
4. Select "Offline" in the throttling dropdown menu.
5. Refresh the page.


## How can I contribute?

WordPress Playground is an open-source project and welcomes all contributors from code to design, and from documentation to triage. If the feature you need is missing, you are more than welcome to start a discussion, open an issue, and even propose a Pull Request to implement it.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,6 @@ export async function broadcastMessageExpectReply(message: any, scope: string) {
}

interface ServiceWorkerConfiguration {
cacheVersion: string;
handleRequest?: (event: FetchEvent) => Promise<Response> | undefined;
}

Expand Down
4 changes: 3 additions & 1 deletion packages/php-wasm/web-service-worker/tsconfig.lib.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
"declaration": true,
"types": ["node"]
},
"include": ["src/**/*.ts"],
"include": [
"src/**/*.ts",
],
"exclude": ["jest.config.ts", "src/**/*.spec.ts", "src/**/*.test.ts"]
}
11 changes: 10 additions & 1 deletion packages/php-wasm/web/src/lib/register-service-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { PHPWorker } from '@php-wasm/universal';
import { PhpWasmError } from '@php-wasm/util';
import { responseTo } from '@php-wasm/web-service-worker';
import { Remote } from 'comlink';
import { logger } from '@php-wasm/logger';

export interface Client extends Remote<PHPWorker> {}

Expand Down Expand Up @@ -65,7 +66,15 @@ export async function registerServiceWorker(scope: string, scriptUrl: string) {

// Check if there's a new service worker available and, if so, enqueue
// the update:
await registration.update();
try {
await registration.update();
} catch (e) {
// registration.update() throws if it can't reach the server.
// We're swallowing the error to keep the app working in offline mode
// or when playground.wordpress.net is down. We can be sure we have a functional
// service worker at this point because sw.register() succeeded.
logger.error('Failed to update service worker.', e);
}

// Proxy the service worker messages to the web worker:
navigator.serviceWorker.addEventListener(
Expand Down
9 changes: 9 additions & 0 deletions packages/playground/client/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import { join } from 'path';
import ignoreWasmImports from '../ignore-wasm-imports';
// eslint-disable-next-line @nx/enforce-module-boundaries
import { viteTsConfigPaths } from '../../vite-extensions/vite-ts-config-paths';
// eslint-disable-next-line @nx/enforce-module-boundaries
import { buildVersionPlugin } from '../../vite-extensions/vite-build-version';

export default defineConfig({
cacheDir: '../../../node_modules/.vite/playground-client',
Expand All @@ -18,6 +20,13 @@ export default defineConfig({
tsconfigPath: join(__dirname, 'tsconfig.lib.json'),
}),
ignoreWasmImports(),

// @wp-playground/client doesn't actually use the remote-config virtual module,
// @wp-playground/remote package does.
// @wp-playground/client imports a few things from @wp-playground/remote and,
// even though it doesn't involve the remote-config virtual module, the bundler
// still needs to know what to do when it sees `import from "virtual:remote-config"`.
buildVersionPlugin('remote-config'),
],

// Configuration for building your library.
Expand Down
97 changes: 94 additions & 3 deletions packages/playground/remote/service-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

declare const self: ServiceWorkerGlobalScope;

import { getURLScope, removeURLScope } from '@php-wasm/scopes';
import { getURLScope, isURLScoped, removeURLScope } from '@php-wasm/scopes';
import { applyRewriteRules } from '@php-wasm/universal';
import {
awaitReply,
Expand All @@ -14,7 +14,7 @@ import {
import { wordPressRewriteRules } from '@wp-playground/wordpress';
import { reportServiceWorkerMetrics } from '@php-wasm/logger';

import { buildVersion } from 'virtual:remote-config';
import { OfflineModeCache } from './src/lib/offline-mode-cache';

if (!(self as any).document) {
// Workaround: vite translates import.meta.url
Expand All @@ -25,10 +25,101 @@ if (!(self as any).document) {
self.document = {};
}

/**
* Ensures the very first Playground load is controlled by this service worker.
*
* This is necessary because service workers don't control any pages loaded
* before they are activated. This includes the page that actually registers
* the service worker. You need to reload it before `navigator.serviceWorker.controller`
* is set and the fetch() requests are intercepted here.
*
* However, the initial Playground load already downloads a few large assets,
* like a 12MB wordpress-static.zip file. We need to cache them these requests.
* Otherwise they'll be fetched again on the next page load.
*
* client.claim() only affects pages loaded before the initial servie worker
* registration. It shouldn't have unwanted side effects in our case. All these
* pages would get controlled eventually anyway.
*
* See:
* * The service worker lifecycle https://web.dev/articles/service-worker-lifecycle
* * Clients.claim() docs https://developer.mozilla.org/en-US/docs/Web/API/Clients/claim
*/
self.addEventListener('activate', function (event) {
event.waitUntil(self.clients.claim());
});

/**
* Handle fetch() caching:
*
* * Put the initial fetch response in the cache
* * Serve the subsequent requests from the cache
*/
self.addEventListener('fetch', (event) => {
const url = new URL(event.request.url);

/**
* Don't cache requests to the service worker script itself.
*/
if (url.pathname.startsWith(self.location.pathname)) {
return;
}

/**
* Don't cache requests to scoped URLs or if the referrer URL is scoped.
*
* These requests are made to the PHP Worker Thread and are not static assets.
*/
if (isURLScoped(url)) {
return;
}

let referrerUrl;
try {
referrerUrl = new URL(event.request.referrer);
} catch (e) {
// ignore
}

if (referrerUrl && isURLScoped(referrerUrl)) {
return;
}

/**
* Respond with cached assets if available.
* If the asset is not cached, fetch it from the network and cache it.
*/
event.respondWith(
cachePromise.then((cache) => cache.cachedFetch(event.request))
);
});

reportServiceWorkerMetrics(self);

const cachePromise = OfflineModeCache.getInstance().then((cache) => {
/**
* For offline mode to work we need to cache all required assets.
*
* These assets are listed in the `/assets-required-for-offline-mode.json` file
* and contain JavaScript, CSS, and other assets required to load the site without
* making any network requests.
*/
cache.cacheOfflineModeAssets();

/**
* Remove outdated files from the cache.
*
* We cache data based on `buildVersion` which is updated whenever Playground is built.
* So when a new version of Playground is deployed, the service worker will remove the old cache and cache the new assets.
*
* If your build version doesn't change while developing locally check `buildVersionPlugin` for more details on how it's generated.
*/
cache.removeOutdatedFiles();

return cache;
});

initializeServiceWorker({
cacheVersion: buildVersion,
handleRequest(event) {
const fullUrl = new URL(event.request.url);
let scope = getURLScope(fullUrl);
Expand Down
58 changes: 40 additions & 18 deletions packages/playground/remote/src/lib/boot-playground-remote.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,10 +208,19 @@ export async function bootPlaygroundRemote() {

/**
* Download WordPress assets.
* @see backfillStaticFilesRemovedFromMinifiedBuild in the worker-thread.ts
*/
async backfillStaticFilesRemovedFromMinifiedBuild() {
await phpApi.backfillStaticFilesRemovedFromMinifiedBuild();
},

/**
* Checks whether we have the missing WordPress assets readily
* available in the request cache.
*/
async hasCachedStaticFilesRemovedFromMinifiedBuild() {
return await phpApi.hasCachedStaticFilesRemovedFromMinifiedBuild();
},
};

await phpApi.isConnected();
Expand Down Expand Up @@ -244,30 +253,43 @@ export async function bootPlaygroundRemote() {
}

/**
* When WordPress is loaded from a minified bundle, some assets are removed to reduce the bundle size.
* This function backfills the missing assets. If WordPress is loaded from a non-minified bundle,
* we don't need to backfill because the assets are already included.
* When we're running WordPress from a minified bundle, we're missing some static assets.
* The section below backfills them if needed. It doesn't do anything if the assets are already
* in place, or when WordPress is loaded from a non-minified bundle.
*
* Minified bundles are shipped without most static assets to reduce the bundle size and
* the loading time. When WordPress loads for the first time, the browser parses all the
* <script src="">, <link href="">, etc. tags and fetches the missing assets from the server.
*
* If the browser is online we download the WordPress assets asynchronously to speed up the boot process.
* Missing assets will be fetched on demand from the Playground server until they are downloaded.
* Unfortunately, fetching these assets on demand wouldn't work in an offline mode.
*
* If the browser is offline, we await the backfill or WordPress assets
* from cache to ensure Playground is fully functional before boot finishes.
* Below we're downloading a zipped bundle of the missing assets.
*/
if (window.navigator.onLine) {
if (await webApi.hasCachedStaticFilesRemovedFromMinifiedBuild()) {
/**
* If we already have the static assets in the cache, the backfilling only
* involves unzipping the archive. This is fast. Let's do it before the first
* render.
*
* Why?
*
* Because otherwise the initial offline page render would lack CSS.
* Without the static assets in /wordpress/wp-content, the browser would
* attempt to fetch them from the server. However, we're in an offline mode
* so nothing would be fetched.
*/
await webApi.backfillStaticFilesRemovedFromMinifiedBuild();
} else {
/**
* If we don't have the static assets in the cache, we need to fetch them.
*
* Let's wait for the initial page load before we start the backfilling.
* The static assets are 12MB+ in size. Starting the download before
* Playground is loaded would noticeably delay the first paint.
*/
wpFrame.addEventListener('load', () => {
webApi.backfillStaticFilesRemovedFromMinifiedBuild();
});
} else {
// Note this will run even if the static files are already in place, e.g. when running
// a non-minified build or an offline site. It doesn't seem like a big problem worth introducing
// a new API method like `webApi.needsBackfillingStaticFilesRemovedFromMinifiedBuild().
webApi.setProgress({
caption: 'Downloading WordPress assets',
isIndefinite: false,
visible: true,
});
await webApi.backfillStaticFilesRemovedFromMinifiedBuild();
}

/*
Expand Down
Loading
Loading