Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fs: improve readFileSync with file descriptors #49691

Merged
merged 2 commits into from
Sep 25, 2023
Merged
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: 15 additions & 3 deletions benchmark/fs/readFileSync.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,21 @@ const fs = require('fs');
const bench = common.createBenchmark(main, {
encoding: ['undefined', 'utf8'],
path: ['existing', 'non-existing'],
n: [60e1],
hasFileDescriptor: ['true', 'false'],
n: [1e4],
});

function main({ n, encoding, path }) {
function main({ n, encoding, path, hasFileDescriptor }) {
const enc = encoding === 'undefined' ? undefined : encoding;
const file = path === 'existing' ? __filename : '/tmp/not-found';
let file;
let shouldClose = false;

if (hasFileDescriptor === 'true') {
shouldClose = path === 'existing';
file = path === 'existing' ? fs.openSync(__filename) : -1;
} else {
file = path === 'existing' ? __filename : '/tmp/not-found';
}
bench.start();
for (let i = 0; i < n; ++i) {
try {
Expand All @@ -21,4 +30,7 @@ function main({ n, encoding, path }) {
}
}
bench.end(n);
if (shouldClose) {
fs.closeSync(file);
}
}
10 changes: 4 additions & 6 deletions lib/fs.js
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ const {
CHAR_BACKWARD_SLASH,
} = require('internal/constants');
const {
isUint32,
isInt32,
parseFileMode,
validateBoolean,
validateBuffer,
Expand Down Expand Up @@ -201,7 +201,7 @@ function makeStatsCallback(cb) {
};
}

const isFd = isUint32;
const isFd = isInt32;

function isFileType(stats, fileType) {
// Use stats array directly to avoid creating an fs.Stats instance just for
Expand Down Expand Up @@ -437,13 +437,11 @@ function tryReadSync(fd, isUserFd, buffer, pos, len) {
function readFileSync(path, options) {
options = getOptions(options, { flag: 'r' });

const isUserFd = isFd(path); // File descriptor ownership

// TODO(@anonrig): Do not handle file descriptor ownership for now.
if (!isUserFd && (options.encoding === 'utf8' || options.encoding === 'utf-8')) {
if (options.encoding === 'utf8' || options.encoding === 'utf-8') {
return syncFs.readFileUtf8(path, options.flag);
}

const isUserFd = isFd(path); // File descriptor ownership
const fd = isUserFd ? path : fs.openSync(path, options.flag, 0o666);

const stats = tryStatSync(fd, isUserFd);
Expand Down
6 changes: 4 additions & 2 deletions lib/internal/fs/sync.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const {
getStatFsFromBinding,
getValidatedFd,
} = require('internal/fs/utils');
const { parseFileMode } = require('internal/validators');
const { parseFileMode, isInt32 } = require('internal/validators');

const binding = internalBinding('fs');

Expand All @@ -19,7 +19,9 @@ const binding = internalBinding('fs');
* @return {string}
*/
function readFileUtf8(path, flag) {
path = pathModule.toNamespacedPath(getValidatedPath(path));
if (!isInt32(path)) {
path = pathModule.toNamespacedPath(getValidatedPath(path));
}
return binding.readFileUtf8(path, stringToFlags(flag));
}

Expand Down
47 changes: 29 additions & 18 deletions src/node_file.cc
Original file line number Diff line number Diff line change
Expand Up @@ -2155,7 +2155,7 @@ static void OpenSync(const FunctionCallbackInfo<Value>& args) {
uv_fs_t req;
auto make = OnScopeLeave([&req]() { uv_fs_req_cleanup(&req); });
FS_SYNC_TRACE_BEGIN(open);
int err = uv_fs_open(nullptr, &req, *path, flags, mode, nullptr);
auto err = uv_fs_open(nullptr, &req, *path, flags, mode, nullptr);
FS_SYNC_TRACE_END(open);
if (err < 0) {
return env->ThrowUVException(err, "open", nullptr, path.out());
Expand Down Expand Up @@ -2546,30 +2546,41 @@ static void ReadFileUtf8(const FunctionCallbackInfo<Value>& args) {

CHECK_GE(args.Length(), 2);

BufferValue path(env->isolate(), args[0]);
CHECK_NOT_NULL(*path);

CHECK(args[1]->IsInt32());
const int flags = args[1].As<Int32>()->Value();

if (CheckOpenPermissions(env, path, flags).IsNothing()) return;

uv_file file;
uv_fs_t req;
auto defer_req_cleanup = OnScopeLeave([&req]() { uv_fs_req_cleanup(&req); });

FS_SYNC_TRACE_BEGIN(open);
uv_file file = uv_fs_open(nullptr, &req, *path, flags, 438, nullptr);
FS_SYNC_TRACE_END(open);
if (req.result < 0) {
// req will be cleaned up by scope leave.
return env->ThrowUVException(req.result, "open", nullptr, path.out());
bool is_fd = args[0]->IsInt32();

// Check for file descriptor
if (is_fd) {
file = args[0].As<Int32>()->Value();
} else {
BufferValue path(env->isolate(), args[0]);
CHECK_NOT_NULL(*path);
if (CheckOpenPermissions(env, path, flags).IsNothing()) return;

FS_SYNC_TRACE_BEGIN(open);
file = uv_fs_open(nullptr, &req, *path, flags, O_RDONLY, nullptr);
FS_SYNC_TRACE_END(open);
if (req.result < 0) {
uv_fs_req_cleanup(&req);
// req will be cleaned up by scope leave.
return env->ThrowUVException(req.result, "open", nullptr, path.out());
}
}

auto defer_close = OnScopeLeave([file]() {
uv_fs_t close_req;
CHECK_EQ(0, uv_fs_close(nullptr, &close_req, file, nullptr));
uv_fs_req_cleanup(&close_req);
auto defer_close = OnScopeLeave([file, is_fd, &req]() {
if (!is_fd) {
FS_SYNC_TRACE_BEGIN(close);
CHECK_EQ(0, uv_fs_close(nullptr, &req, file, nullptr));
FS_SYNC_TRACE_END(close);
}
uv_fs_req_cleanup(&req);
Copy link
Member

Choose a reason for hiding this comment

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

For correctness reasons this ought to be done after the uv_fs_read() call on line 2590. It works okay now because libuv doesn't allocate for a single buffer (i.e. this cleanup call is a no-op) but that's a lucky accident.

Copy link
Member Author

Choose a reason for hiding this comment

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

Does that mean that on every while loop iteration (for uv_fs_read), we need to call uv_fs_req_cleanup?

Copy link
Member

Choose a reason for hiding this comment

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

Yes.

});

std::string result{};
char buffer[8192];
uv_buf_t buf = uv_buf_init(buffer, sizeof(buffer));
Expand All @@ -2580,7 +2591,7 @@ static void ReadFileUtf8(const FunctionCallbackInfo<Value>& args) {
if (req.result < 0) {
FS_SYNC_TRACE_END(read);
// req will be cleaned up by scope leave.
return env->ThrowUVException(req.result, "read", nullptr, path.out());
return env->ThrowUVException(req.result, "read", nullptr);
}
if (r <= 0) {
break;
Expand Down