Skip to content

Cache Playground assets to enable offline support #1535

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

Merged
merged 134 commits into from
Jul 24, 2024
Merged
Show file tree
Hide file tree
Changes from 124 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
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,26 @@ 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
```

## 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 @@ -175,7 +175,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: 9 additions & 2 deletions 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,8 +66,14 @@ 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) {
logger.warn(
'Failed to update service worker. Check if you are online.',
e
);
}
// Proxy the service worker messages to the web worker:
navigator.serviceWorker.addEventListener(
'message',
Expand Down
63 changes: 61 additions & 2 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 @@ -15,6 +15,7 @@ import { wordPressRewriteRules } from '@wp-playground/wordpress';
import { reportServiceWorkerMetrics } from '@php-wasm/logger';

import { buildVersion } from 'virtual:remote-config';
import { WorkerCache } from './src/lib/worker-caching';

if (!(self as any).document) {
// Workaround: vite translates import.meta.url
Expand All @@ -27,8 +28,66 @@ if (!(self as any).document) {

reportServiceWorkerMetrics(self);

const cache = new WorkerCache(buildVersion);

/**
* 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.
Copy link
Collaborator

@adamziel adamziel Jul 23, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's make it clear we skipped the await on purpose.

*/
cache.cacheOfflineModeAssets();

/**
* Cleanup old 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.cleanup();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The .cleanup() name make it seem like we're evicting the assets we just requested, how about calling it .removeOutdatedFiles() and calling if before .cacheOfflineModeAssets()?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, let's make it clear we've skipped the await on purpose


/**
* Handle fetch events and respond with cached assets if available.
*/
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(cache.cachedFetch(event.request));
});
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the future, we could merge the fetch lister from initializeServiceWorker with this one.

I didn't want to do it now because I'm not sure if removing initializeServiceWorker will break backwards compatibility.


initializeServiceWorker({
cacheVersion: buildVersion,
handleRequest(event) {
const fullUrl = new URL(event.request.url);
let scope = getURLScope(fullUrl);
Expand Down
92 changes: 92 additions & 0 deletions packages/playground/remote/src/lib/worker-caching.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { isURLScoped } from '@php-wasm/scopes';

export class WorkerCache {
readonly cacheNamePrefix = 'playground-cache';

private cacheName: string;

constructor(cacheVersion: string) {
this.cacheName = `${this.cacheNamePrefix}-${cacheVersion}`;
}

addCache = async (key: Request, response: Response) => {
const clonedResponse = response.clone();
const cache = await caches.open(this.cacheName);
await cache.put(key, clonedResponse);
};

getCache = async (key: Request) => {
const cache = caches.open(this.cacheName);
return await cache.then((c) => c.match(key, { ignoreSearch: true }));
};

isValidHostname = (url: URL) => {
/**
* The development environment uses Vite which doesn't work offline because it dynamically generates assets.
* Check the README for offline development instructions.
*/
if (
url.href.startsWith('http://127.0.0.1:5400/') ||
url.pathname.startsWith('/website-server/')
) {
return false;
}

/**
* Scoped URLs are requests made to the PHP Worker Thread.
* These requests are not cached because they are not static assets.
*/
if (isURLScoped(url)) {
return false;
}

/**
* Don't cache PHP files because they are dynamic.
*/
if (url.pathname.endsWith('.php')) {
return false;
}
return ['playground.wordpress.net', '127.0.0.1', 'localhost'].includes(
url.hostname
);
};

cleanup = async () => {
const keys = await caches.keys();
const oldKeys = keys.filter(
(key) =>
key.startsWith(this.cacheNamePrefix) && key !== this.cacheName
);
return Promise.all(oldKeys.map((key) => caches.delete(key)));
};

cachedFetch = async (request: Request): Promise<Response> => {
const url = new URL(request.url);
if (!this.isValidHostname(url)) {
return await fetch(request);
}
const cacheKey = request;
const cache = await this.getCache(cacheKey);
if (cache) {
return cache;
}
const response = await fetch(request);
await this.addCache(cacheKey, response);
return response;
};

cacheOfflineModeAssets = async (): Promise<any> => {
if (!this.isValidHostname(new URL(location.href))) {
return;
}

const cache = await caches.open(this.cacheName);

// Get the cache manifest and add all the files to the cache
const manifestResponse = await fetch(
'/assets-required-for-offline-mode.json'
);
const websiteUrls = await manifestResponse.json();
await cache.addAll([...websiteUrls, ...['/']]);
};
}
6 changes: 3 additions & 3 deletions packages/playground/remote/src/lib/worker-thread.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,11 @@ import {
journalFSEvents,
replayFSJournal,
} from '@php-wasm/fs-journal';
/** @ts-ignore */
/* @ts-ignore */
import transportFetch from './playground-mu-plugin/playground-includes/wp_http_fetch.php?raw';
/** @ts-ignore */
/* @ts-ignore */
import transportDummy from './playground-mu-plugin/playground-includes/wp_http_dummy.php?raw';
/** @ts-ignore */
/* @ts-ignore */
import playgroundWebMuPlugin from './playground-mu-plugin/0-playground.php?raw';
import { PHP, PHPWorker } from '@php-wasm/universal';
import {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const patternsToNotCache = [
'/index.d.ts',
/\/lib\/.*/, // Remote lib files
/\/test-fixtures\/.*/, // Test fixtures
'/index.js',
/**
* WordPress assets removed from the minified builds, for example:
*
Expand Down
Loading