egg
Version:
A web application framework for Node.js
58 lines (57 loc) • 2.1 kB
JavaScript
import { startEgg } from "./start.js";
import v8 from "node:v8";
//#region src/lib/snapshot.ts
/**
* Build a V8 startup snapshot of an egg application.
*
* Call this from the snapshot entry script passed to
* `node --snapshot-blob=snapshot.blob --build-snapshot snapshot_entry.js`.
*
* It loads all metadata (plugins, configs, extensions, services, controllers,
* router, tegg modules), triggers snapshotWillSerialize hooks to clean up
* non-serializable resources (file handles, timers, process listeners),
* then registers a V8 deserialize callback to stash the app for later restore.
*
* Example snapshot entry script:
* ```ts
* import { buildSnapshot } from 'egg';
* await buildSnapshot({ baseDir: __dirname });
* ```
*
* Example restoring from snapshot:
* ```ts
* import { restoreSnapshot } from 'egg';
* const app = await restoreSnapshot();
* // app is fully restored with resources recreated, ready for server creation
* ```
*/
async function buildSnapshot(options = {}) {
const app = await startEgg({
...options,
snapshot: true
});
if (app.agent) await app.agent.triggerSnapshotWillSerialize();
await app.triggerSnapshotWillSerialize();
v8.startupSnapshot.setDeserializeMainFunction((snapshotData) => {
globalThis.__egg_snapshot_app = snapshotData.app;
}, { app });
}
/**
* Restore an egg application from a V8 startup snapshot.
*
* Triggers the snapshotDidDeserialize lifecycle hooks to recreate
* non-serializable resources (messenger, loggers, process listeners)
* and resumes the lifecycle from configDidLoad through didReady.
*
* Returns the fully restored Application instance with all metadata
* pre-loaded (plugins, configs, extensions, services, controllers, router).
*/
async function restoreSnapshot() {
const app = globalThis.__egg_snapshot_app;
if (!app) throw new Error("No egg application found in snapshot. Ensure the process was started from a snapshot built with buildSnapshot().");
if (app.agent) await app.agent.triggerSnapshotDidDeserialize();
await app.triggerSnapshotDidDeserialize();
return app;
}
//#endregion
export { buildSnapshot, restoreSnapshot };