From 0e97f92b5965cf1c3adfd75b7cf022d94f8de061 Mon Sep 17 00:00:00 2001 From: Izaak Gough Date: Fri, 2 Oct 2026 14:41:42 +0100 Subject: [PATCH] fix: wait for debug target before sending emulator requests In debug mode the Functions emulator sent the request as soon as the debug message was written to IPC, so it could run against the previous target. The runtime now confirms the message and the worker waits for it. --- CHANGELOG.md | 1 + .../functionsEmulatorRuntime.spec.ts | 20 ++++++++-- src/emulator/functionsEmulatorRuntime.ts | 9 ++++- src/emulator/functionsEmulatorShared.ts | 3 ++ src/emulator/functionsRuntimeWorker.spec.ts | 37 ++++++++++++++++++- src/emulator/functionsRuntimeWorker.ts | 29 +++++++++++++-- 6 files changed, 91 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f7662fc5c5..d237bf28952 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,3 +2,4 @@ - - [Fixed] Report the GCFv2-to-GCFv1 downgrade error during validation instead of a misleading CPU error (#5461). - Fixed `functions:delete` recreating an already-deleted Cloud Tasks queue for task queue functions. (#9305) - Batched function deletions across instances when uninstalling a Function Kit (#11189). +- Fixed the Functions emulator with `--inspect-functions` sometimes running the previously called function. diff --git a/scripts/emulator-tests/functionsEmulatorRuntime.spec.ts b/scripts/emulator-tests/functionsEmulatorRuntime.spec.ts index 4060fb771bb..dbefd970570 100644 --- a/scripts/emulator-tests/functionsEmulatorRuntime.spec.ts +++ b/scripts/emulator-tests/functionsEmulatorRuntime.spec.ts @@ -4,7 +4,7 @@ import * as http from "http"; import * as fs from "fs/promises"; import * as spawn from "cross-spawn"; import * as path from "path"; -import { ChildProcess } from "child_process"; +import { ChildProcess, Serializable } from "child_process"; import * as express from "express"; import { Change } from "firebase-functions"; @@ -12,11 +12,13 @@ import { DocumentSnapshot } from "firebase-functions/v1/firestore"; import { FunctionRuntimeBundles, TIMEOUT_LONG, MODULE_ROOT } from "./fixtures"; import { + DEBUG_MSG_HANDLED, FunctionsRuntimeBundle, getTemporarySocketPath, SignatureType, } from "../../src/emulator/functionsEmulatorShared"; import { streamToString } from "../../src/utils"; +import { EmulatorLog } from "../../src/emulator/types"; const FUNCTIONS_DIR = `./scripts/emulator-tests/functions`; const ADMIN_SDK_CONFIG = { @@ -179,8 +181,20 @@ async function sendReq(runtime: Runtime, opts: ReqOpts = {}): Promise { } async function sendDebugBundle(runtime: Runtime, debug: FunctionsRuntimeBundle["debug"]) { - return new Promise((resolve) => { - runtime.proc.send(JSON.stringify(debug), resolve); + return new Promise((resolve) => { + const onMessage = (message: Serializable) => { + const log = EmulatorLog.fromJSON(message.toString()); + if ( + log.level === "SYSTEM" && + log.type === "runtime-status" && + log.text === DEBUG_MSG_HANDLED + ) { + runtime.proc.off("message", onMessage); + resolve(); + } + }; + runtime.proc.on("message", onMessage); + runtime.proc.send(JSON.stringify(debug)); }); } diff --git a/src/emulator/functionsEmulatorRuntime.ts b/src/emulator/functionsEmulatorRuntime.ts index c563937cd68..657db042b41 100644 --- a/src/emulator/functionsEmulatorRuntime.ts +++ b/src/emulator/functionsEmulatorRuntime.ts @@ -9,7 +9,12 @@ import * as _ from "lodash"; import { EmulatorLog } from "./types"; import { getErrMsg, getErrStack } from "../error"; import { Constants } from "./constants"; -import { findModuleRoot, FunctionsRuntimeBundle, SignatureType } from "./functionsEmulatorShared"; +import { + DEBUG_MSG_HANDLED, + findModuleRoot, + FunctionsRuntimeBundle, + SignatureType, +} from "./functionsEmulatorShared"; import { compareVersionStrings, isLocalHost } from "./functionsEmulatorUtils"; import { EventUtils } from "./events/types"; @@ -800,6 +805,8 @@ async function handleMessage(message: string) { new EmulatorLog("WARN", "runtime-warning", "Expected debug payload while in debug mode."); } } + // The parent waits for this before sending a request, since IPC and HTTP are not ordered. + new EmulatorLog("SYSTEM", "runtime-status", DEBUG_MSG_HANDLED).log(); } async function main(): Promise { diff --git a/src/emulator/functionsEmulatorShared.ts b/src/emulator/functionsEmulatorShared.ts index 99e35e6e90b..51ab72a4654 100644 --- a/src/emulator/functionsEmulatorShared.ts +++ b/src/emulator/functionsEmulatorShared.ts @@ -59,6 +59,9 @@ export function getEventTenantId( */ export const EVENTARC_SOURCE_ENV = "EVENTARC_CLOUD_EVENT_SOURCE"; +/** Text of the runtime-status log a Node runtime sends once it has handled a debug message. */ +export const DEBUG_MSG_HANDLED = "debug-msg-handled"; + export type SignatureType = "http" | "event" | "cloudevent"; export interface ParsedTriggerDefinition { diff --git a/src/emulator/functionsRuntimeWorker.spec.ts b/src/emulator/functionsRuntimeWorker.spec.ts index 03dcdebccab..907dc3701de 100644 --- a/src/emulator/functionsRuntimeWorker.spec.ts +++ b/src/emulator/functionsRuntimeWorker.spec.ts @@ -6,7 +6,7 @@ import { expect } from "chai"; import { FunctionsRuntimeInstance, IPCConn } from "./functionsEmulator"; import { EventEmitter } from "events"; import { RuntimeWorker, RuntimeWorkerPool, RuntimeWorkerState } from "./functionsRuntimeWorker"; -import { EmulatedTriggerDefinition } from "./functionsEmulatorShared"; +import { DEBUG_MSG_HANDLED, EmulatedTriggerDefinition } from "./functionsEmulatorShared"; import { EmulatorLog, FunctionsExecutionMode } from "./types"; import { ChildProcess } from "child_process"; @@ -188,6 +188,41 @@ describe("FunctionsRuntimeWorker", () => { expect(counter.counts.FINISHED).to.eql(1); expect(counter.total).to.eql(5); }); + + it("sendDebugMsg resolves only after the runtime confirms it handled the message", async () => { + const runtime = new MockRuntimeInstance(); + runtime.process.send = ((msg: string, cb: (err: Error | null) => void) => { + cb(null); + return true; + }) as ChildProcess["send"]; + const worker = new RuntimeWorker("trigger", runtime, {}); + + let resolved = false; + const sent = worker + .sendDebugMsg({ functionTarget: "fn", functionSignature: "http" }) + .then(() => { + resolved = true; + }); + await new Promise((r) => setImmediate(r)); + expect(resolved).to.be.false; + + runtime.events.emit("log", new EmulatorLog("SYSTEM", "runtime-status", DEBUG_MSG_HANDLED)); + await sent; + expect(resolved).to.be.true; + }); + + it("sendDebugMsg rejects if the runtime exits before confirming", async () => { + const runtime = new MockRuntimeInstance(); + runtime.process.send = ((msg: string, cb: (err: Error | null) => void) => { + cb(null); + return true; + }) as ChildProcess["send"]; + const worker = new RuntimeWorker("trigger", runtime, {}); + + const sent = worker.sendDebugMsg({ functionTarget: "fn", functionSignature: "http" }); + runtime.process.emit("exit"); + await expect(sent).to.be.rejectedWith("exited before handling the debug message"); + }); }); describe("RuntimeWorkerPool", () => { diff --git a/src/emulator/functionsRuntimeWorker.ts b/src/emulator/functionsRuntimeWorker.ts index 15befa3f6d3..f77866b3133 100644 --- a/src/emulator/functionsRuntimeWorker.ts +++ b/src/emulator/functionsRuntimeWorker.ts @@ -3,7 +3,11 @@ import { randomUUID } from "crypto"; import { FunctionsRuntimeInstance } from "./functionsEmulator"; import { EmulatorLog, Emulators, FunctionsExecutionMode } from "./types"; -import { EmulatedTriggerDefinition, FunctionsRuntimeBundle } from "./functionsEmulatorShared"; +import { + DEBUG_MSG_HANDLED, + EmulatedTriggerDefinition, + FunctionsRuntimeBundle, +} from "./functionsEmulatorShared"; import { EventEmitter } from "events"; import { EmulatorLogger, ExtensionLogInfo } from "./emulatorLogger"; import { FirebaseError } from "../error"; @@ -117,11 +121,30 @@ export class RuntimeWorker { sendDebugMsg(debug: FunctionsRuntimeBundle["debug"]): Promise { return new Promise((resolve, reject) => { + const onLog = (log: EmulatorLog) => { + if ( + log.level === "SYSTEM" && + log.type === "runtime-status" && + log.text === DEBUG_MSG_HANDLED + ) { + cleanup(); + resolve(); + } + }; + const onExit = () => { + cleanup(); + reject(new FirebaseError("Functions runtime exited before handling the debug message.")); + }; + const cleanup = () => { + this.runtime.events.off("log", onLog); + this.runtime.process.off("exit", onExit); + }; + this.runtime.events.on("log", onLog); + this.runtime.process.once("exit", onExit); this.runtime.process.send(JSON.stringify(debug), (err) => { if (err) { + cleanup(); reject(err); - } else { - resolve(); } }); });