From 40543edb188a213b4fd2e1432574b7045d2d1148 Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Thu, 29 Oct 2026 14:03:34 -0700 Subject: [PATCH 1/2] Convert stdio to TypeScript Writes to the stdio file descriptors through node:fs are line-buffered and logged through globalThis.console.log by StdioFile in C++. With the TS_STDIO autogate enabled, that is done by node-internal:internal_fs_stdio instead, which node:fs calls for fds 0-2 before reaching native code. The C++ implementation is retained for rollback. FileSystemModule gains tsStdio(), which reports the autogate, and stdioPrefix(), since the configured logging prefixes are not otherwise visible to TypeScript. fs-stdio-test.js runs under a C++ cell and a TypeScript cell, each asserting which implementation it runs, and the stdio golden-output tests gain @all-autogates variants. With the autogate enabled, behaviour matches the C++ implementation, except that a partial line flushed outside a request is logged (StdioFile drops it) and no warning is logged to the server when console.log is missing. Neither changes the API surface exposed to Workers. --- src/node/internal/filesystem.d.ts | 3 + src/node/internal/internal_fs_callback.ts | 6 +- src/node/internal/internal_fs_stdio.ts | 113 ++++++++++++++++++ src/node/internal/internal_fs_sync.ts | 3 + src/workerd/api/filesystem.c++ | 11 ++ src/workerd/api/filesystem.h | 8 ++ src/workerd/api/node/tests/BUILD.bazel | 55 +++++++++ .../api/node/tests/fs-stdio-cpp.wd-test | 18 +++ src/workerd/api/node/tests/fs-stdio-test.js | 89 ++++++++++++++ .../api/node/tests/fs-stdio-ts.wd-test | 19 +++ .../api/node/tests/test_process_stdio.sh | 3 +- src/workerd/util/autogate.h | 4 + 12 files changed, 330 insertions(+), 2 deletions(-) create mode 100644 src/node/internal/internal_fs_stdio.ts create mode 100644 src/workerd/api/node/tests/fs-stdio-cpp.wd-test create mode 100644 src/workerd/api/node/tests/fs-stdio-test.js create mode 100644 src/workerd/api/node/tests/fs-stdio-ts.wd-test diff --git a/src/node/internal/filesystem.d.ts b/src/node/internal/filesystem.d.ts index dc3078037e2..98e7cb12c03 100644 --- a/src/node/internal/filesystem.d.ts +++ b/src/node/internal/filesystem.d.ts @@ -48,6 +48,9 @@ export function open( export function close(fd: number): void; +export function tsStdio(): boolean; +export function stdioPrefix(fd: number): string; + export function write( fd: number, buffers: ArrayBufferView[], diff --git a/src/node/internal/internal_fs_callback.ts b/src/node/internal/internal_fs_callback.ts index bd4bfa20e8d..dcc34c1ff3c 100644 --- a/src/node/internal/internal_fs_callback.ts +++ b/src/node/internal/internal_fs_callback.ts @@ -24,6 +24,7 @@ // USE OR OTHER DEALINGS IN THE SOFTWARE. import * as fssync from 'node-internal:internal_fs_sync'; import { default as cffs } from 'cloudflare-internal:filesystem'; +import { isStdioFd, writeStdio } from 'node-internal:internal_fs_stdio'; import type { FStatOptions, MkdirTempSyncOptions, @@ -1347,7 +1348,10 @@ export function writeFile( } = validateWriteFileArgs(path, data, options); callWithSingleArgCallback( - () => cffs.writeAll(validatedPath, validatedData, { append, exclusive }), + () => + isStdioFd(validatedPath) + ? writeStdio(validatedPath, [validatedData]) + : cffs.writeAll(validatedPath, validatedData, { append, exclusive }), callback ); } diff --git a/src/node/internal/internal_fs_stdio.ts b/src/node/internal/internal_fs_stdio.ts new file mode 100644 index 00000000000..5c1f79965e2 --- /dev/null +++ b/src/node/internal/internal_fs_stdio.ts @@ -0,0 +1,113 @@ +// Copyright (c) 2026 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 + +// Writes to the stdio file descriptors (0, 1, 2) are line-buffered and logged +// through globalThis.console.log, which gives them inspector reporting and +// structured logging. Writes to stdin are discarded. Synchronous writes join +// into one line; a partial line is flushed in a microtask. + +import { default as cffs } from 'cloudflare-internal:filesystem'; + +const MAX_WRITE_SIZE = 16 * 1024; +const MAX_LINE_BUFFER_SIZE = 4096; +const NEWLINE = 0x0a; + +const decoder = new TextDecoder('utf-8', { ignoreBOM: true }); + +class StdioStream { + readonly #fd: number; + #pending: Uint8Array = new Uint8Array(0); + #scheduled = false; + + constructor(fd: number) { + this.#fd = fd; + } + + write(bytes: Uint8Array): void { + let pos = 0; + while (pos < bytes.length) { + const nl = bytes.indexOf(NEWLINE, pos); + if (nl === -1) { + this.#buffer(bytes.subarray(pos)); + return; + } + const line = bytes.subarray(pos, nl); + pos = nl + 1; + if (this.#pending.length > 0) { + const head = this.#pending; + this.#pending = new Uint8Array(0); + this.#log(concat(head, line)); + } else { + this.#log(line); + } + } + } + + // Keeps the last MAX_LINE_BUFFER_SIZE bytes of the partial line. + #buffer(rest: Uint8Array): void { + const all = concat(this.#pending, rest); + this.#pending = all.subarray( + Math.max(0, all.length - MAX_LINE_BUFFER_SIZE) + ); + if (this.#scheduled) return; + this.#scheduled = true; + queueMicrotask(() => { + this.#scheduled = false; + if (this.#pending.length === 0) return; + const line = this.#pending; + this.#pending = new Uint8Array(0); + this.#log(line); + }); + } + + #log(line: Uint8Array): void { + const console = globalThis.console as unknown; + if (typeof console !== 'object' || console === null) return; + const log = (console as { log?: unknown }).log; + if (typeof log !== 'function') return; + const prefix = cffs.stdioPrefix(this.#fd); + const text = decoder.decode(line); + let msg = text; + if (text.length === 0) msg = prefix; + else if (prefix.length > 0) msg = `${prefix} ${text}`; + log.call(console, msg); + } +} + +function concat(a: Uint8Array, b: Uint8Array): Uint8Array { + const out = new Uint8Array(a.length + b.length); + out.set(a); + out.set(b, a.length); + return out; +} + +const streams = [null, new StdioStream(1), new StdioStream(2)]; + +const enabled = cffs.tsStdio(); + +// When false, writes to the stdio file descriptors go to the native file +// system, which line-buffers and logs them itself. +export function isStdioFd(fd: number | URL): fd is number { + return enabled && (fd === 0 || fd === 1 || fd === 2); +} + +// Returns the number of bytes accepted: each buffer is truncated to +// MAX_WRITE_SIZE. +export function writeStdio( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[] +): number { + const chunks = buffers.map((b) => { + const n = Math.min(b.byteLength, MAX_WRITE_SIZE); + return n === 0 + ? new Uint8Array(0) + : new Uint8Array(b.buffer, b.byteOffset, n).slice(); + }); + let total = 0; + for (const chunk of chunks) { + streams[fd]?.write(chunk); + total += chunk.length; + } + return total; +} diff --git a/src/node/internal/internal_fs_sync.ts b/src/node/internal/internal_fs_sync.ts index 185c4380f26..f3dfeed6436 100644 --- a/src/node/internal/internal_fs_sync.ts +++ b/src/node/internal/internal_fs_sync.ts @@ -87,6 +87,7 @@ import { } from 'node-internal:internal_fs_constants'; import { Dir, Dirent } from 'node-internal:internal_fs'; import { default as cffs } from 'cloudflare-internal:filesystem'; +import { isStdioFd, writeStdio } from 'node-internal:internal_fs_stdio'; import { Buffer } from 'node-internal:internal_buffer'; import { @@ -819,6 +820,7 @@ export function writeFileSync( exclusive, } = validateWriteFileArgs(path, data, options); + if (isStdioFd(validatedPath)) return writeStdio(validatedPath, [actualData]); return cffs.writeAll(validatedPath, actualData, { append, exclusive }); } @@ -851,6 +853,7 @@ export function writevSync( return 0; } + if (isStdioFd(fd)) return writeStdio(fd, buffers); return cffs.write(fd, buffers, { position }); } diff --git a/src/workerd/api/filesystem.c++ b/src/workerd/api/filesystem.c++ index f16a2274a74..f168e64789e 100644 --- a/src/workerd/api/filesystem.c++ +++ b/src/workerd/api/filesystem.c++ @@ -7,7 +7,9 @@ #include #include #include +#include #include +#include namespace workerd::api { @@ -494,6 +496,15 @@ void FileSystemModule::close(jsg::Lock& js, int fd) { vfs.closeFd(js, fd); } +bool FileSystemModule::tsStdio() { + return util::Autogate::isEnabled(util::AutogateKey::TS_STDIO); +} + +kj::StringPtr FileSystemModule::stdioPrefix(jsg::Lock& js, int fd) { + auto& isolate = Worker::Isolate::from(js); + return fd == 1 ? isolate.getStdoutPrefix() : isolate.getStderrPrefix(); +} + uint32_t FileSystemModule::write( jsg::Lock& js, int fd, kj::Array> data, WriteOptions options) { auto& vfs = workerd::VirtualFileSystem::current(js); diff --git a/src/workerd/api/filesystem.h b/src/workerd/api/filesystem.h index 5cde464f192..da7b41a6289 100644 --- a/src/workerd/api/filesystem.h +++ b/src/workerd/api/filesystem.h @@ -104,6 +104,12 @@ class FileSystemModule final: public jsg::Object { int open(jsg::Lock& js, FilePath path, OpenOptions options); void close(jsg::Lock& js, int fd); + // Whether writes to the stdio file descriptors are line-buffered and logged + // in TypeScript (the TS_STDIO autogate) rather than by StdioFile. + bool tsStdio(); + // The logging prefix for stdout (fd 1) or stderr (fd 2). + kj::StringPtr stdioPrefix(jsg::Lock& js, int fd); + struct WriteOptions { kj::Maybe position; JSG_STRUCT(position); @@ -205,6 +211,8 @@ class FileSystemModule final: public jsg::Object { JSG_METHOD(getFdHandle); JSG_METHOD(cp); JSG_METHOD(openAsBlob); + JSG_METHOD(tsStdio); + JSG_METHOD(stdioPrefix); } private: diff --git a/src/workerd/api/node/tests/BUILD.bazel b/src/workerd/api/node/tests/BUILD.bazel index 96721068733..3c0da447a07 100644 --- a/src/workerd/api/node/tests/BUILD.bazel +++ b/src/workerd/api/node/tests/BUILD.bazel @@ -365,6 +365,25 @@ sh_test( ], ) +sh_test( + name = "process-stdio-sh-test@all-autogates", + srcs = ["test_process_stdio.sh"], + args = [ + "$(location //src/workerd/server:workerd)", + "$(location process-stdio-nodejs-test.wd-test)", + "$(location process-stdio-nodejs-test.expected_stdout)", + "$(location process-stdio-nodejs-test.expected_stderr)", + "--all-autogates", + ], + data = [ + "process-stdio-nodejs-test.expected_stderr", + "process-stdio-nodejs-test.expected_stdout", + "process-stdio-nodejs-test.js", + "process-stdio-nodejs-test.wd-test", + "//src/workerd/server:workerd", + ], +) + sh_test( name = "process-stdio-fs-sh-test", srcs = ["test_process_stdio.sh"], @@ -383,6 +402,25 @@ sh_test( ], ) +sh_test( + name = "process-stdio-fs-sh-test@all-autogates", + srcs = ["test_process_stdio.sh"], + args = [ + "$(location //src/workerd/server:workerd)", + "$(location process-stdio-fs-nodejs-test.wd-test)", + "$(location process-stdio-fs-nodejs-test.expected_stdout)", + "$(location process-stdio-fs-nodejs-test.expected_stderr)", + "--all-autogates", + ], + data = [ + "process-stdio-fs-nodejs-test.expected_stderr", + "process-stdio-fs-nodejs-test.expected_stdout", + "process-stdio-fs-nodejs-test.js", + "process-stdio-fs-nodejs-test.wd-test", + "//src/workerd/server:workerd", + ], +) + wd_test( src = "querystring-nodejs-test.wd-test", args = ["--experimental"], @@ -664,6 +702,23 @@ wd_test( data = ["fs-access-test.js"], ) +# The stdio suite runs the same module under a C++ and a TypeScript cell. The +# C++ cell disables the @all-autogates variant: enabling every autogate enables +# TS_STDIO, which swaps in the TypeScript implementation under a cell whose +# USING_TS_IMPL binding says C++. +wd_test( + src = "fs-stdio-cpp.wd-test", + args = ["--experimental"], + data = ["fs-stdio-test.js"], + generate_all_autogates_variant = False, +) + +wd_test( + src = "fs-stdio-ts.wd-test", + args = ["--experimental"], + data = ["fs-stdio-test.js"], +) + wd_test( src = "fs-chown-chmod-test.wd-test", args = ["--experimental"], diff --git a/src/workerd/api/node/tests/fs-stdio-cpp.wd-test b/src/workerd/api/node/tests/fs-stdio-cpp.wd-test new file mode 100644 index 00000000000..b36e88661e7 --- /dev/null +++ b/src/workerd/api/node/tests/fs-stdio-cpp.wd-test @@ -0,0 +1,18 @@ +using Workerd = import "/workerd/workerd.capnp"; + +# Runs fs-stdio-test.js against the C++ implementation +# (StdioFile in io/worker-fs.c++). + +const unitTests :Workerd.Config = ( + services = [ + ( name = "fs-stdio-cpp", + worker = ( + modules = [ + (name = "worker", esModule = embed "fs-stdio-test.js") + ], + compatibilityFlags = ["nodejs_compat", "experimental", "enable_nodejs_fs_module"], + bindings = [(name = "USING_TS_IMPL", json = "false")], + ) + ), + ], +); diff --git a/src/workerd/api/node/tests/fs-stdio-test.js b/src/workerd/api/node/tests/fs-stdio-test.js new file mode 100644 index 00000000000..6777d2d6f4b --- /dev/null +++ b/src/workerd/api/node/tests/fs-stdio-test.js @@ -0,0 +1,89 @@ +// Copyright (c) 2026 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 + +// Line buffering of writes to the stdio file descriptors. The same module +// runs under the C++ implementation (fs-stdio-cpp.wd-test) and the TypeScript +// one (fs-stdio-ts.wd-test). The TS_STDIO autogate, which user code cannot +// read, selects between them, so each cell says which one it is meant to run +// through its USING_TS_IMPL binding. + +import { env } from 'cloudflare:workers'; +import { Buffer } from 'node:buffer'; +import { writeSync } from 'node:fs'; +import { deepStrictEqual, strictEqual } from 'node:assert'; + +const usingTsImpl = env.USING_TS_IMPL === true; + +// Runs fn with console.log replaced, returning the lines it logged with any +// stdio prefix removed, and the stack of the first call. +async function capture(fn) { + const lines = []; + let stack; + const log = console.log; + console.log = (msg) => { + stack ??= new Error().stack; + lines.push(String(msg).replace(/^std(out|err): ?/, '')); + }; + try { + fn(); + // Lets a pending partial line flush. + await new Promise((resolve) => setTimeout(resolve, 0)); + } finally { + console.log = log; + } + return { lines, stack }; +} + +export const whichImpl = { + async test() { + const { stack } = await capture(() => writeSync(1, 'x\n')); + strictEqual(stack.includes('internal_fs_stdio'), usingTsImpl); + }, +}; + +export const splitsLines = { + async test() { + for (const fd of [1, 2]) { + const { lines } = await capture(() => writeSync(fd, 'a\nb\n\nc\n')); + deepStrictEqual(lines, ['a', 'b', '', 'c']); + } + }, +}; + +export const joinsPartialLines = { + async test() { + const { lines } = await capture(() => { + writeSync(1, 'a'); + writeSync(1, 'b\nc'); + writeSync(1, 'd\n'); + }); + deepStrictEqual(lines, ['ab', 'cd']); + }, +}; + +export const flushesPartialLine = { + async test() { + const { lines } = await capture(() => writeSync(1, 'tail')); + deepStrictEqual(lines, ['tail']); + }, +}; + +export const limitsWriteSize = { + async test() { + let n; + const { lines } = await capture(() => { + n = writeSync(1, Buffer.alloc(20000, 'a')); + }); + strictEqual(n, 16384); + // Only the last 4 KiB of a partial line are kept. + deepStrictEqual(lines, ['a'.repeat(4096)]); + }, +}; + +export const discardsStdin = { + async test() { + const { lines } = await capture(() => writeSync(0, 'ignored\n')); + deepStrictEqual(lines, []); + }, +}; diff --git a/src/workerd/api/node/tests/fs-stdio-ts.wd-test b/src/workerd/api/node/tests/fs-stdio-ts.wd-test new file mode 100644 index 00000000000..07200b7b8b8 --- /dev/null +++ b/src/workerd/api/node/tests/fs-stdio-ts.wd-test @@ -0,0 +1,19 @@ +using Workerd = import "/workerd/workerd.capnp"; + +# Runs fs-stdio-test.js against the TypeScript implementation +# (src/node/internal/internal_fs_stdio.ts, under the TS_STDIO autogate). + +const unitTests :Workerd.Config = ( + services = [ + ( name = "fs-stdio-ts", + worker = ( + modules = [ + (name = "worker", esModule = embed "fs-stdio-test.js") + ], + compatibilityFlags = ["nodejs_compat", "experimental", "enable_nodejs_fs_module"], + bindings = [(name = "USING_TS_IMPL", json = "true")], + ) + ), + ], + autogates = ["workerd-autogate-ts-stdio"], +); diff --git a/src/workerd/api/node/tests/test_process_stdio.sh b/src/workerd/api/node/tests/test_process_stdio.sh index d3bbeeb6ee5..7150f744580 100755 --- a/src/workerd/api/node/tests/test_process_stdio.sh +++ b/src/workerd/api/node/tests/test_process_stdio.sh @@ -8,6 +8,7 @@ WORKERD_BINARY="$1" TEST_CONFIG="$2" EXPECTED_STDOUT="$3" EXPECTED_STDERR="$4" +shift 4 # Any remaining arguments are passed to workerd. # Run the workerd test and capture stdout and stderr ACTUAL_STDOUT=$(mktemp) @@ -16,7 +17,7 @@ FILTERED_STDOUT=$(mktemp) FILTERED_STDERR=$(mktemp) trap "rm -f $ACTUAL_STDOUT $ACTUAL_STDERR $FILTERED_STDOUT $FILTERED_STDERR" EXIT -"$WORKERD_BINARY" test "$TEST_CONFIG" --experimental >"$ACTUAL_STDOUT" 2>"$ACTUAL_STDERR" --compat-date 2025-05-01 +"$WORKERD_BINARY" test "$TEST_CONFIG" --experimental >"$ACTUAL_STDOUT" 2>"$ACTUAL_STDERR" --compat-date 2025-05-01 "$@" # Remove [ PASS ] [ TEST ] [ FAIL ] lines from stderr, and the warning logged when V8 rejects the # per-isolate bootstrap's compile cache. Builds that generate the cache for other V8 flags diff --git a/src/workerd/util/autogate.h b/src/workerd/util/autogate.h index ec5c2087b3c..ebd402c4a31 100644 --- a/src/workerd/util/autogate.h +++ b/src/workerd/util/autogate.h @@ -122,6 +122,10 @@ namespace workerd::util { instead of the C++ implementation. The C++ implementation is retained \ for rollback. */ \ V(NODEJS_I18N_RUST) \ + /* Writes to the stdio file descriptors (0, 1, 2) through node:fs are line-buffered and \ + logged by the TypeScript implementation (src/node/internal/internal_fs_stdio.ts) rather \ + than by StdioFile in io/worker-fs.c++. The C++ implementation is retained for rollback. */ \ + V(TS_STDIO) \ /* JSG converts a JS number to an integer of up to 32 bits by truncating it toward zero \ before the range check, as Web IDL's [EnforceRange] and V8's kEnforceRangeBit fast API \ arguments do, so that a fraction just past a range limit (2 ** 31 - 0.5 as int, -0.5 as \ From 2bff94a24fe95bb1e5f3a687e9e3c44f3f776340 Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Sun, 1 Nov 2026 08:03:23 -0800 Subject: [PATCH 2/2] Test writeFile and appendFile to stdio under both implementations writeFileSync, appendFileSync and callback writeFile reach stdio through their own branches in node:fs, separate from writeSync's. --- src/workerd/api/node/tests/fs-stdio-test.js | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/workerd/api/node/tests/fs-stdio-test.js b/src/workerd/api/node/tests/fs-stdio-test.js index 6777d2d6f4b..18341e88437 100644 --- a/src/workerd/api/node/tests/fs-stdio-test.js +++ b/src/workerd/api/node/tests/fs-stdio-test.js @@ -10,7 +10,7 @@ import { env } from 'cloudflare:workers'; import { Buffer } from 'node:buffer'; -import { writeSync } from 'node:fs'; +import { appendFileSync, writeFile, writeFileSync, writeSync } from 'node:fs'; import { deepStrictEqual, strictEqual } from 'node:assert'; const usingTsImpl = env.USING_TS_IMPL === true; @@ -87,3 +87,17 @@ export const discardsStdin = { deepStrictEqual(lines, []); }, }; + +export const writeFileToStdio = { + async test() { + const { lines } = await capture(() => { + writeFileSync(1, 'a\n'); + appendFileSync(2, 'b\n'); + }); + deepStrictEqual(lines, ['a', 'b']); + const done = Promise.withResolvers(); + const cb = await capture(() => writeFile(1, 'c\n', done.resolve)); + strictEqual(await done.promise, null); + deepStrictEqual(cb.lines, ['c']); + }, +};