Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
18 changes: 18 additions & 0 deletions packages/core/src/egg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,24 @@ export class EggCore extends KoaApplication {
this.lifecycle.registerBeforeClose(fn, name);
}

/**
* Trigger snapshotWillSerialize lifecycle hooks on all boots in reverse order.
* Called by the build script before V8 serializes the heap.
* Cleans up non-serializable resources: file handles, timers, listeners, connections.
*/
async triggerSnapshotWillSerialize(): Promise<void> {
return this.lifecycle.triggerSnapshotWillSerialize();
}

/**
* Trigger snapshotDidDeserialize lifecycle hooks on all boots in forward order.
* Called by the restore entry after V8 deserializes the heap.
* Restores non-serializable resources and resumes the lifecycle from configDidLoad.
*/
async triggerSnapshotDidDeserialize(): Promise<void> {
return this.lifecycle.triggerSnapshotDidDeserialize();
}

/**
* Close all, it will close
* - callbacks registered by beforeClose
Expand Down
102 changes: 101 additions & 1 deletion packages/core/src/lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,23 @@ export interface ILifecycleBoot {
* when the application is started with metadataOnly: true.
*/
loadMetadata?(): Promise<void> | void;

/**
* Called before V8 serializes the heap for startup snapshot.
* Clean up non-serializable resources: close file handles, clear timers,
* remove process listeners, close network connections.
* Executed in REVERSE registration order (like beforeClose).
*/
snapshotWillSerialize?(): Promise<void> | void;

/**
* Called after V8 deserializes the heap from a startup snapshot.
* Restore non-serializable resources: reopen file handles, recreate timers,
* re-register process listeners, reinitialize connections.
* Executed in FORWARD registration order (like configWillLoad).
* After all hooks complete, the normal lifecycle resumes from configDidLoad.
*/
snapshotDidDeserialize?(): Promise<void> | void;
}

export type BootImplClass<T = ILifecycleBoot> = new (...args: any[]) => T;
Expand Down Expand Up @@ -89,6 +106,7 @@ export class Lifecycle extends EventEmitter {
#boots: ILifecycleBoot[];
#isClosed: boolean;
#metadataOnly: boolean;
#snapshotBuilding: boolean;
#closeFunctionSet: Set<FunWithFullPath>;
loadReady: Ready;
bootReady: Ready;
Expand All @@ -105,6 +123,7 @@ export class Lifecycle extends EventEmitter {
this.#closeFunctionSet = new Set();
this.#isClosed = false;
this.#metadataOnly = false;
this.#snapshotBuilding = false;
this.#init = false;

this.timing.start(`${this.options.app.type} Start`);
Expand Down Expand Up @@ -264,8 +283,12 @@ export class Lifecycle extends EventEmitter {
// Snapshot mode: stop AFTER configWillLoad, BEFORE configDidLoad.
// SDKs typically execute during configDidLoad hooks — these open connections
// and start timers which are not serializable in V8 startup snapshots.
// Start loadReady so registerBeforeStart callbacks (e.g. load()) can complete
// and drive readiness — callers can simply `await app.ready()` without
// needing to distinguish snapshot from normal mode.
debug('snapshot mode: stopping after configWillLoad, skipping configDidLoad and later phases');
this.ready(true);
this.#snapshotBuilding = true;
this.loadReady.start();
return;
}
this.triggerConfigDidLoad();
Expand Down Expand Up @@ -380,6 +403,80 @@ export class Lifecycle extends EventEmitter {
this.ready(firstError ?? true);
}

/**
* Trigger snapshotWillSerialize on all boots in REVERSE order.
* Called by the build script before V8 serializes the heap.
*/
async triggerSnapshotWillSerialize(): Promise<void> {
debug('trigger snapshotWillSerialize start');
const boots = [...this.#boots].reverse();
for (const boot of boots) {
if (typeof boot.snapshotWillSerialize !== 'function') {
continue;
}
const fullPath = boot.fullPath ?? 'unknown';
debug('trigger snapshotWillSerialize at %o', fullPath);
const timingKey = `Snapshot Will Serialize in ${utils.getResolvedFilename(fullPath, this.app.baseDir)}`;
this.timing.start(timingKey);
try {
await utils.callFn(boot.snapshotWillSerialize.bind(boot));
} catch (err) {
debug('trigger snapshotWillSerialize error at %o, error: %s', fullPath, err);
this.emit('error', err);
}
this.timing.end(timingKey);
}
debug('trigger snapshotWillSerialize end');
}

/**
* Trigger snapshotDidDeserialize on all boots in FORWARD order.
* Called by the restore entry after V8 deserializes the heap.
* After all hooks complete, resets the ready state and resumes the normal
* lifecycle from configDidLoad. The returned promise resolves when the
* full lifecycle (configDidLoad → didLoad → willReady) has completed.
*/
async triggerSnapshotDidDeserialize(): Promise<void> {
debug('trigger snapshotDidDeserialize start');
for (const boot of this.#boots) {
if (typeof boot.snapshotDidDeserialize !== 'function') {
continue;
}
const fullPath = boot.fullPath ?? 'unknown';
debug('trigger snapshotDidDeserialize at %o', fullPath);
const timingKey = `Snapshot Did Deserialize in ${utils.getResolvedFilename(fullPath, this.app.baseDir)}`;
this.timing.start(timingKey);
try {
await utils.callFn(boot.snapshotDidDeserialize.bind(boot));
} catch (err) {
debug('trigger snapshotDidDeserialize error at %o, error: %s', fullPath, err);
this.emit('error', err);
}
this.timing.end(timingKey);
}
debug('trigger snapshotDidDeserialize end');

// Reset ready state for the resumed lifecycle.
// In snapshot mode, ready(true) was called when loadReady completed,
// resolving the ready promise early. We need fresh ready objects so the
// resumed lifecycle (didLoad → willReady → didReady) can track properly.
// Note: keep options.snapshot = true so the constructor's stale ready
// callback (which may fire asynchronously) correctly skips triggerDidReady.
this.#snapshotBuilding = false;
this.#readyObject = new ReadyObject();
this.#initReady();
this.ready((err) => {
void this.triggerDidReady(err);
debug('app ready after snapshot deserialize');
});

// Resume the normal lifecycle from configDidLoad
this.triggerConfigDidLoad();

// Wait for the full resumed lifecycle to complete
await this.ready();
}

#initReady(): void {
debug('loadReady init');
this.loadReady = new Ready({ timeout: this.readyTimeout, lazyStart: true });
Expand All @@ -389,6 +486,9 @@ export class Lifecycle extends EventEmitter {
debug('trigger didLoad end');
if (err) {
this.ready(err);
} else if (this.#snapshotBuilding) {
// Snapshot build: skip willReady/bootReady phases, signal ready directly
this.ready(true);
} else {
this.triggerWillReady();
}
Expand Down
Loading
Loading