Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
10 changes: 10 additions & 0 deletions docs/browser.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ and `cjFileBlob(path)` also work.
has no environment otherwise. Under Node, Java sees the host's environment.
- `preloadProgress(done, total)` reports the bytes of the runtime downloaded at start.
`total` is 0 while the server has not sent a length; the last call has `done === total`.
- `cheerpjInit({ warmSnapshot: true })` saves a library VM once its calls have warmed it up (see below).
- A file Java closes under `/files/downloads/` is downloaded by the browser.
`/files/uploads/` exists for files the page adds there.
- The browser console gets whole lines, so two `print` calls and a `println` log one
Expand Down Expand Up @@ -126,3 +127,12 @@ After a VM boots, the worker keeps a snapshot of it, in memory and in
IndexedDB (the 4 most recently used). Later runs with the same class path and
`cheerpjInit` options start from it instead of booting, in this page and in
later visits.

With `warmSnapshot: true`, `cheerpjRunLibrary` also saves its VM after a call
returns once its calls have loaded at least 200 classes since boot (one javac
compile loads over a thousand) and no library handles are live. Later library
starts with the same class path restore that image, after checking that the
files, missing paths and directory listings those calls used are unchanged; the
first javac compile after it took 2.7 s instead of 5.3 s in Chromium on a
Raspberry Pi 5. An image is about 18 MB. IndexedDB keeps the 2 most recent warm images separately
from boot snapshots.
11 changes: 11 additions & 0 deletions docs/node.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ resolves to the exit code. Its options:
- `fetch`: sockets stay inside the VM, and `http:` requests go to this `fetch`, as in the browser

- `snapshotDir`: where boot snapshots are kept, or `null` for none (see below)
- `warmSnapshot: true`: save a library VM once its calls have warmed it up (see below)

`startLibrary(options)` starts a VM in library mode, and `libraryOf(vm)` is its
`lib`, used as `cheerpjRunLibrary`'s result is in the browser. `vm.halt(0)`
Expand All @@ -67,3 +68,13 @@ reads all of them. The snapshots, about 1 MB each, are kept in
`$XDG_CACHE_HOME/java-web/snapshots` (`~/.cache/java-web/snapshots`), the 16
most recently used. Set `JAVA_WEB_SNAPSHOT_DIR` to keep them elsewhere, or to
an empty value to turn them off.

Set `warmSnapshot: true` in `startLibrary` options to save the VM after a call
returns once its calls have loaded at least 200 classes since boot (one javac
compile loads over a thousand) and no library handles are live. A later library
start with the same class path and working directory restores it, after
checking that the files, missing paths and directory listings those calls used
are unchanged; a javac compile from it takes about 1 s instead of 6 s on a
Raspberry Pi 5. An image is about 18 MB; warm snapshots share the snapshot
directory and keep the 2 most recent. They build on boot snapshots, so with
`snapshotDir: null` there are none.
4 changes: 3 additions & 1 deletion src/browser/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ export interface InitOptions {
env?: string[];
// load the formats and names of locales other than English
localeData?: boolean;
// save and restore library VMs after their first idle call
warmSnapshot?: boolean;
// where java-web.js, the worker and jdk/ live; defaults to the script's directory
runtime?: string;
// receives output instead of the page console element
Expand Down Expand Up @@ -178,7 +180,7 @@ export function cheerpjInit(options: InitOptions = {}): Promise<void> {
};
});
natives = options.natives ?? {};
send({ type: "init", runtime, app: appBase, props, hostName: options.hostName, env, localeData: !!options.localeData, natives: Object.keys(natives), progress: !!options.preloadProgress });
send({ type: "init", runtime, app: appBase, props, hostName: options.hostName, env, localeData: !!options.localeData, warmSnapshot: !!options.warmSnapshot, natives: Object.keys(natives), progress: !!options.preloadProgress });
initStarted(ready);
return ready;
}
Expand Down
37 changes: 35 additions & 2 deletions src/browser/idb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@
// changes are written back in batches.

import type { MemoryBackend, MemoryEntry } from "../fs.ts";
import type { SnapshotImage } from "../snapshot.ts";
import type { SnapshotImage, WarmSnapshotImage } from "../snapshot.ts";

const DB = "java-web", STORE = "files";
// its own database, so adding it needs no version change that open pages would block
const SNAPSHOT_DB = "java-web-snapshots";
// snapshot keys, most recently used first
const ORDER = "#order";
const KEEP_SNAPSHOTS = 4;
const WARM_ORDER = "#warm-order";
const KEEP_SNAPSHOTS = 4, KEEP_WARM_SNAPSHOTS = 2;

function request<T>(r: IDBRequest<T>): Promise<T> {
return new Promise((resolve, reject) => {
Expand Down Expand Up @@ -108,3 +109,35 @@ export function saveSnapshot(image: SnapshotImage) {
export function dropSnapshot(key: string) {
useSnapshot(key, null).catch(() => {});
}

async function useWarmSnapshot(key: string, image?: WarmSnapshotImage | null) {
const db = await openSnapshots();
if (!db) return;
const store = db.transaction(STORE, "readwrite").objectStore(STORE);
const id = `warm:${key}`;
if (image) store.put(image, id);
const order = ((await request(store.get(WARM_ORDER))) as string[] | undefined ?? []).filter((k) => k !== id);
if (image !== null) order.unshift(id);
for (const k of [...order.slice(KEEP_WARM_SNAPSHOTS), ...(image === null ? [id] : [])]) store.delete(k);
store.put(order.slice(0, KEEP_WARM_SNAPSHOTS), WARM_ORDER);
}

export async function loadWarmSnapshot(key: string): Promise<WarmSnapshotImage | null> {
try {
const db = await openSnapshots();
if (!db) return null;
const id = `warm:${key}`;
const image = (await request(db.transaction(STORE, "readonly").objectStore(STORE).get(id))) as WarmSnapshotImage | undefined;
if (!image) return null;
useWarmSnapshot(key).catch(() => {});
return image;
} catch { return null; }
}

export function saveWarmSnapshot(image: WarmSnapshotImage) {
useWarmSnapshot(image.warmKey, image).catch(() => {});
}

export function dropWarmSnapshot(key: string) {
useWarmSnapshot(key, null).catch(() => {});
}
1 change: 1 addition & 0 deletions src/browser/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export interface InitMessage {
hostName?: string;
env: Record<string, string>;
localeData: boolean;
warmSnapshot: boolean;
// JNI names of natives the page implements
natives: string[];
// report the download of the runtime
Expand Down
34 changes: 30 additions & 4 deletions src/browser/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
import { MemoryBackend, VFS } from "../fs.ts";
import { JVM, SnapshotError } from "../jvm.ts";
import { HttpBackend, parsePack } from "./http.ts";
import { dropSnapshot, loadSnapshot, persist, saveSnapshot } from "./idb.ts";
import type { SnapshotImage } from "../snapshot.ts";
import { dropSnapshot, dropWarmSnapshot, loadSnapshot, loadWarmSnapshot, persist, saveSnapshot, saveWarmSnapshot } from "./idb.ts";
import type { SnapshotImage, WarmSnapshotImage } from "../snapshot.ts";
import type { LibraryError, LibraryReply } from "../library.ts";
import type { NativeReply } from "../bridge.ts";
import type { FromWorker, InitMessage, ToWorker } from "./protocol.ts";
Expand Down Expand Up @@ -113,6 +113,8 @@ declare const JAVA_WEB_BUILD: string;
// in IndexedDB for later loads. A VM changes the image it restores, so each
// gets a copy.
const snapshots = new Map<string, SnapshotImage>();
const warmSnapshots = new Map<string, WarmSnapshotImage>();
const droppedWarmSnapshots = new Set<string>();
const keep = (image: SnapshotImage) => {
snapshots.delete(image.key);
snapshots.set(image.key, image);
Expand Down Expand Up @@ -143,6 +145,29 @@ const snapshotCache = {
},
};

const warmSnapshotCache = {
load: async (key: string) => {
if (droppedWarmSnapshots.has(key)) return null;
const image = warmSnapshots.get(key) ?? await loadWarmSnapshot(key);
if (!image) return null;
warmSnapshots.delete(key);
warmSnapshots.set(key, image);
return structuredClone(image);
},
save: (image: WarmSnapshotImage) => {
droppedWarmSnapshots.delete(image.warmKey);
warmSnapshots.delete(image.warmKey);
warmSnapshots.set(image.warmKey, structuredClone(image));
for (const k of [...warmSnapshots.keys()].slice(0, -2)) warmSnapshots.delete(k);
saveWarmSnapshot(image);
},
drop: (key: string) => {
warmSnapshots.delete(key);
droppedWarmSnapshots.add(key);
dropWarmSnapshot(key);
},
};

// A snapshot that cannot be restored is dropped, and a second VM boots.
function retried<T>(start: () => Promise<T>): Promise<T> {
return start().catch((e) => {
Expand All @@ -152,9 +177,10 @@ function retried<T>(start: () => Promise<T>): Promise<T> {
});
}

function newVm(classpath: string[], vmId: number): JVM {
function newVm(classpath: string[], vmId: number, library = false): JVM {
return new JVM({
snapshots: snapshotCache,
...(library && config!.warmSnapshot ? { warmSnapshot: true, warmSnapshots: warmSnapshotCache } : {}),
fs: vfs!,
javaHome: "/jdk",
classpath,
Expand Down Expand Up @@ -226,7 +252,7 @@ self.onmessage = (e: MessageEvent<ToWorker>) => {
}
case "library": {
reply(m.id, retried(() => {
const vm = newVm(m.classpath, m.lib);
const vm = newVm(m.classpath, m.lib, true);
vms.set(m.lib, vm);
return vm.startLibrary();
}).then(() => ({ value: undefined })));
Expand Down
Loading
Loading
⌂ Proxy