Skip to content

fix(emulators:functions): buffer stdout/stderr independently and preserve multibyte UTF-8 across chunks - #11525

Open
anjalimishra-0007 wants to merge 1 commit into
firebase:mainfrom
anjalimishra-0007:fix/functions-emulator-stream-buffers
Open

anjalimishra-0007 wants to merge 1 commit into
firebase:mainfrom
anjalimishra-0007:fix/functions-emulator-stream-buffers

Conversation

@anjalimishra-0007

Copy link
Copy Markdown
Contributor

Description

Fixes #11522

In src/emulator/functionsRuntimeWorker.ts, RuntimeWorker previously passed both childProc.stdout and childProc.stderr chunks into a single shared stdBuffer, decoding each buffer chunk independently with s.toString(). This led to two issues:

  1. Multi-byte UTF-8 characters split across pipe/stream chunk boundaries (such as 3-byte characters straddling the 64 KiB pipe buffer) were decoded into \uFFFD replacement characters because decoder state was not preserved across chunks.
  2. Incomplete stdout writes without trailing newlines were concatenated with stderr output into the shared buffer, merging separate log streams.

This PR:

  • Separates stdBuffer into distinct stdoutBuffer and stderrBuffer per worker.
  • Uses StringDecoder('utf8') per stream to buffer incomplete UTF-8 byte sequences until following chunks arrive.
  • Flushes remaining buffer contents on stream end and child process exit.

Scenarios Tested

  • Added regression tests in src/emulator/functionsRuntimeWorker.spec.ts:
    • buffers stdout and stderr independently
    • decodes multi-byte UTF-8 split across chunks without replacement characters
    • flushes remaining buffer on stream end and process exit
  • All 11 tests in src/emulator/functionsRuntimeWorker.spec.ts pass.
  • ESLint and Prettier checks pass.

…erve multibyte UTF-8 across chunks

Fixes firebase#11522

Signed-off-by: Anjali Mishra <[email protected]>

@gemini-code-assist gemini-code-assist Bot left a comment

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.

Code Review

This pull request updates the functions emulator runtime worker to buffer stdout and stderr independently and correctly decode multi-byte UTF-8 characters split across chunks using StringDecoder. It also ensures that any remaining buffered data is flushed upon stream end and process exit, supported by new unit tests. The review feedback recommends removing unnecessary 'any' type assertions in both the source code and tests, and suggests extracting a unified helper function to reduce duplication in stream setup and buffer flushing.

Comment on lines 1 to +3
import * as http from "http";
import { randomUUID } from "crypto";
import { StringDecoder } from "node:string_decoder";

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.

medium

Import Readable from node:stream to provide proper typing for the stream setup helper, avoiding any or Serializable for stream data.

Suggested change
import * as http from "http";
import { randomUUID } from "crypto";
import { StringDecoder } from "node:string_decoder";
import * as http from "http";
import { randomUUID } from "crypto";
import { StringDecoder } from "node:string_decoder";
import { Readable } from "node:stream";
References
  1. Never use any or unknown as an escape hatch. Define proper interfaces/types or use type guards. (link)

Comment on lines +69 to 105
let stdoutBuffer = "";
if (childProc.stdout) {
childProc.stdout.on("data", (data) => {
stdBuffer = this.processStream(data, stdBuffer);
const stdoutDecoder = new StringDecoder("utf8");
childProc.stdout.on("data", (data: Serializable) => {
const text = Buffer.isBuffer(data) ? stdoutDecoder.write(data) : data;
stdoutBuffer = this.processStream(text, stdoutBuffer);
});
childProc.stdout.on("end", () => {
const remaining = stdoutDecoder.end();
if (remaining) {
stdoutBuffer = this.processStream(remaining, stdoutBuffer);
}
if (stdoutBuffer) {
this.flushBuffer(stdoutBuffer);
stdoutBuffer = "";
}
});
}

let stderrBuffer = "";
if (childProc.stderr) {
childProc.stderr.on("data", (data) => {
stdBuffer = this.processStream(data, stdBuffer);
const stderrDecoder = new StringDecoder("utf8");
childProc.stderr.on("data", (data: Serializable) => {
const text = Buffer.isBuffer(data) ? stderrDecoder.write(data) : data;
stderrBuffer = this.processStream(text, stderrBuffer);
});
childProc.stderr.on("end", () => {
const remaining = stderrDecoder.end();
if (remaining) {
stderrBuffer = this.processStream(remaining, stderrBuffer);
}
if (stderrBuffer) {
this.flushBuffer(stderrBuffer);
stderrBuffer = "";
}
});
}

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.

medium

The logic for handling stdout and stderr streams is almost identical. We can extract a local helper function setupStream and a unified flushAndClear helper to reduce duplication, improve maintainability, and ensure correct typing of stream data as Buffer | string instead of Serializable.

    let stdoutBuffer = "";
    let stderrBuffer = "";

    const flushAndClear = (getBuffer: () => string, setBuffer: (val: string) => void) => {
      const buf = getBuffer();
      if (buf) {
        this.flushBuffer(buf);
        setBuffer("");
      }
    };

    const setupStream = (
      stream: Readable,
      getBuffer: () => string,
      setBuffer: (val: string) => void,
    ) => {
      const decoder = new StringDecoder("utf8");
      stream.on("data", (data: Buffer | string) => {
        const text = Buffer.isBuffer(data) ? decoder.write(data) : data;
        setBuffer(this.processStream(text, getBuffer()));
      });
      stream.on("end", () => {
        const remaining = decoder.end();
        if (remaining) {
          setBuffer(this.processStream(remaining, getBuffer()));
        }
        flushAndClear(getBuffer, setBuffer);
      });
    };

    if (childProc.stdout) {
      setupStream(childProc.stdout, () => stdoutBuffer, (val) => { stdoutBuffer = val; });
    }

    if (childProc.stderr) {
      setupStream(childProc.stderr, () => stderrBuffer, (val) => { stderrBuffer = val; });
    }
References
  1. Survey prior art & harmonize utilities: Extract and unify shared helpers when logic is duplicated across modules or warrants a new common utility. (link)

Comment on lines +116 to +127
if (stdoutBuffer) {
this.flushBuffer(stdoutBuffer);
stdoutBuffer = "";
}
if (stderrBuffer) {
this.flushBuffer(stderrBuffer);
stderrBuffer = "";
}
if (msgBuffer) {
this.flushBuffer(msgBuffer);
msgBuffer = "";
}

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.

medium

Use the unified flushAndClear helper to clean up and flush the buffers on process exit, reducing duplication and manual state clearing.

      flushAndClear(() => stdoutBuffer, (val) => { stdoutBuffer = val; });
      flushAndClear(() => stderrBuffer, (val) => { stderrBuffer = val; });
      flushAndClear(() => msgBuffer, (val) => { msgBuffer = val; });
References
  1. Survey prior art & harmonize utilities: Extract and unify shared helpers when logic is duplicated across modules or warrants a new common utility. (link)

Comment on lines +196 to +197
runtime.process.stdout = stdout as any;
runtime.process.stderr = stderr as any;

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.

medium

Avoid using as any as an escape hatch. Since PassThrough is a subclass of Readable and Writable, it is fully compatible with ChildProcess.stdout and ChildProcess.stderr types, making the type assertion unnecessary.

Suggested change
runtime.process.stdout = stdout as any;
runtime.process.stderr = stderr as any;
runtime.process.stdout = stdout;
runtime.process.stderr = stderr;
References
  1. Never use any or unknown as an escape hatch. Define proper interfaces/types or use type guards. (link)

it("decodes multi-byte UTF-8 split across chunks without replacement characters", () => {
const runtime = new MockRuntimeInstance();
const stdout = new PassThrough();
runtime.process.stdout = stdout as any;

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.

medium

Avoid using as any as an escape hatch. PassThrough is compatible with ChildProcess.stdout without type assertions.

Suggested change
runtime.process.stdout = stdout as any;
runtime.process.stdout = stdout;
References
  1. Never use any or unknown as an escape hatch. Define proper interfaces/types or use type guards. (link)

it("flushes remaining buffer on stream end and process exit", async () => {
const runtime = new MockRuntimeInstance();
const stdout = new PassThrough();
runtime.process.stdout = stdout as any;

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.

medium

Avoid using as any as an escape hatch. PassThrough is compatible with ChildProcess.stdout without type assertions.

Suggested change
runtime.process.stdout = stdout as any;
runtime.process.stdout = stdout;
References
  1. Never use any or unknown as an escape hatch. Define proper interfaces/types or use type guards. (link)

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Functions emulator decodes runtime output per chunk and shares one line buffer between stdout and stderr

1 participant