Skip to content
Open
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
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);
Comment on lines +410 to +427
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Reject snapshot hook failures instead of only emitting them.

Both snapshot paths emit the error and keep going. That lets snapshot build/restore continue with half-torn-down or half-restored process state, even though these hooks are the only place non-serializable resources get cleaned up and recreated. Please propagate the first failure after emitting it so callers can abort the snapshot operation.

Also applies to: 433-449

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/src/lifecycle.ts` around lines 404 - 421, The snapshot hook
error handlers currently only emit errors and continue, which lets snapshot
operations proceed in an inconsistent state; update the catch blocks in
triggerSnapshotWillSerialize and triggerSnapshotDidDeserialize to rethrow the
caught error (after emitting it) so the Promise rejects and callers can abort;
specifically, inside the try/catch around await
utils.callFn(boot.snapshotWillSerialize.bind(boot)) and the analogous call to
boot.snapshotDidDeserialize, call this.emit('error', err) and then throw err
(ensuring timing.end still runs as needed or wrap timing.end in finally if
required) so the first hook failure propagates to the caller.

}
debug('trigger snapshotWillSerialize end');
Comment on lines +410 to +429
Copy link

Copilot AI Apr 1, 2026

Choose a reason for hiding this comment

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

triggerSnapshotWillSerialize() catches hook errors and only emits 'error', but still continues and ultimately resolves. For snapshot building, cleanup failures (e.g., failing to close a handle) should likely fail the build to avoid producing a snapshot with non-serializable resources. Consider collecting the first error and throwing/rejecting at the end (or rethrowing immediately after emit).

Copilot uses AI. Check for mistakes.
}

/**
* 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();
Comment on lines +410 to +477
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Guard these entrypoints so they only run in the snapshot flow.

triggerSnapshotDidDeserialize() currently resets #readyObject and reruns configDidLoaddidLoadwillReady with no options.snapshot or phase check. An accidental call on a normal app—or a second deserialize call—will duplicate boot side effects and beforeClose registrations. For example, the agent keepalive boot is driven from configDidLoad(), so a second pass can recreate runtime state unexpectedly. An early snapshot/one-shot assert would keep this public API from corrupting normal app state.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/src/lifecycle.ts` around lines 404 - 470, The
triggerSnapshotDidDeserialize entrypoint must only run in snapshot mode and must
be idempotent: add a guard at the top of triggerSnapshotDidDeserialize that (1)
checks an options snapshot flag (e.g. this.options.snapshot or
this.app.options.snapshot) and returns early (or throws) if not in snapshot
mode, and (2) checks/sets a private "already restored" flag (e.g.
this.#snapshotDeserialized or similar) so a second call is a no-op; ensure this
flag is set before resetting this.#readyObject, calling this.#initReady(),
this.ready(...)/this.triggerDidReady, and this.triggerConfigDidLoad to avoid
duplicate boot side-effects and beforeClose registrations.

}
Comment on lines +439 to +478
Copy link

Copilot AI Apr 1, 2026

Choose a reason for hiding this comment

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

triggerSnapshotDidDeserialize() similarly swallows hook errors by emitting 'error' and continuing, then proceeds to resume the lifecycle. If any deserialize hook fails, continuing may leave the process partially restored (e.g., missing listeners/timers) but still appear “ready”. Consider propagating errors (throw/reject) so callers can abort startup on restore failures.

Copilot uses AI. Check for mistakes.

#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