Skip to content
Closed
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
29 changes: 29 additions & 0 deletions bench/fs-cp/cp.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,35 @@ recursiveCopyBench(`fs.promises.cp recursive (${totalFiles} files, tree contains
promises.cp(symlinkSrc, dest, { recursive: true }),
);

// One small file: most of the time is cpSync's checks of the two paths. The
// destination two directories away has two more folders above it to check.
const fileSrc = join(root, "file-src.txt");
writeFileSync(fileSrc, data);
const nearDest = join(root, "file-dest.txt");
const farDest = join(root, "far", "away", "file-dest.txt");
mkdirSync(join(root, "far", "away"), { recursive: true });

// Each copy makes a new file: the computed parameter removes the last one
// without counting towards the measured time.
function singleFileBench(label, dest, options) {
bench(label, function* () {
yield {
[0]() {
rmSync(dest, { force: true });
return dest;
},
bench(dest) {
return cpSync(fileSrc, dest, options);
},
};
});
}

singleFileBench("cpSync single file (dest in the same directory)", nearDest);
singleFileBench("cpSync single file (dest two directories away)", farDest);
singleFileBench("cpSync single file (with a filter)", nearDest, { filter: () => true });
bench("cpSync single file (over an existing file)", () => cpSync(fileSrc, nearDest));

try {
await run();
} finally {
Expand Down
120 changes: 56 additions & 64 deletions src/js/internal/fs/cp-sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,14 @@
// Also hosts the option validation and SystemError construction shared with
// internal/fs/cp (async) and the fs.cpSync/fs.cp/fs.promises.cp dispatchers,
// ported from node lib/internal/fs/utils.js and lib/internal/errors.js.
const { validateObject, validateBoolean, validateFunction, validateInteger } = require("internal/validators");
const {
validateObject,
validateBoolean,
validateFunction,
validateInteger,
validateString,
} = require("internal/validators");
const binding = require("internal/fs/binding");
const {
chmodSync,
copyFileSync,
Expand All @@ -16,7 +23,7 @@ const {
unlinkSync,
utimesSync,
} = require("node:fs");
const { dirname, isAbsolute, join, parse, resolve, sep } = require("node:path");
const { dirname, isAbsolute, join, resolve, sep } = require("node:path");

const { EEXIST, EISDIR, EINVAL, ENOTDIR } = $processBindingConstants.os.errno;

Expand Down Expand Up @@ -178,6 +185,8 @@ function isSrcSubdir(src: string, dest: string) {
type Stats = $Node.Stats;
type BigIntStats = $Node.BigIntStats;
type AnyStats = Stats | BigIntStats;
// The walker only asks whether dest is there, and `cpSyncFn` knows that much of the path it was given.
type DestinationStats = BigIntStats | boolean | null | undefined;

interface CpOptions {
dereference: boolean;
Expand All @@ -204,8 +213,6 @@ interface SkippedPaths {
skipped: true;
}

function checkPathsSync(src: string, dest: string, opts: CpOptions & { filter: undefined }): CheckedPaths;
function checkPathsSync(src: string, dest: string, opts: CpOptions): CheckedPaths | SkippedPaths;
function checkPathsSync(src: string, dest: string, opts: CpOptions): CheckedPaths | SkippedPaths {
if (opts.filter) {
const shouldCopy = opts.filter(src, dest);
Expand Down Expand Up @@ -273,29 +280,6 @@ function getStatsSync(src: string, dest: string, opts: CpOptions) {
return { srcStat, destStat };
}

function checkParentPathsSync(src: string, srcStat: BigIntStats, dest: string) {
const srcParent = resolve(dirname(src));
const destParent = resolve(dirname(dest));
if (destParent === srcParent || destParent === parse(destParent).root) return;
let destStat: BigIntStats;
try {
destStat = statSync(destParent, { bigint: true });
} catch (err: any) {
if (err.code === "ENOENT") return;
throw err;
}
if (areIdentical(srcStat, destStat)) {
throw fsCpEinvalError({
message: `cannot copy ${src} to a subdirectory of self ${dest}`,
path: dest,
syscall: "cp",
errno: EINVAL,
code: "EINVAL",
});
}
return checkParentPathsSync(src, srcStat, destParent);
}

// The native recursive copy (a single clonefile() on macOS) copies symlinks
// verbatim and clones special files, while node rewrites relative symlink
// targets against the source tree and raises ERR_FS_CP_SOCKET /
Expand Down Expand Up @@ -325,54 +309,63 @@ function treeContainsOnlyFilesAndDirsSync(root: string) {
return true;
}

// node-correct validation before handing off to the native fast path
// (which performs the copy but does not implement node's cp error codes).
function tryNativeFastPathSync(src: string, dest: string, opts: CpOptions & { filter: undefined }) {
const checked = checkPathsSync(src, dest, opts);
const { srcStat, destStat } = checked;
checkParentPathsSync(src, srcStat, dest);
if (srcStat.isDirectory() && !opts.recursive) {
throw fsEisdirError({
message: `${src} is a directory (not copied)`,
path: src,
syscall: "cp",
errno: EISDIR,
code: "EISDIR",
});
// What `binding.cpSyncCheckPaths` answers: `CpSyncPaths::bits` in src/runtime/node/node_fs.rs.
const kSrcIsDirectory = 1 << 0;
const kSrcIsFile = 1 << 1;
const kDestExists = 1 << 2;
const kDestIsFile = 1 << 3;
Comment thread
robobun marked this conversation as resolved.
Resolved

// Whether `binding.cpSync` does the copy. It reads none of the options tested here.
function copiesNatively(paths: number, src: string, opts: CpOptions) {
if (
opts.filter ||
opts.dereference ||
opts.preserveTimestamps ||
opts.verbatimSymlinks ||
opts.mode ||
opts.errorOnExist ||
!opts.force
) {
return false;
}
if (srcStat.isDirectory()) {
if (paths & kSrcIsDirectory) {
// On macOS the native path clones the whole tree with a single
// clonefile(). Only take it when the result is indistinguishable from
// node's walker: dest must not exist (no merge semantics) and the tree
// must contain only regular files and directories.
return {
ok: process.platform === "darwin" && !destStat && treeContainsOnlyFilesAndDirsSync(src),
checked,
};
return process.platform === "darwin" && !(paths & kDestExists) && treeContainsOnlyFilesAndDirsSync(src);
}
// The single-file native copy is only node-equivalent for regular-file ->
// regular-file (or missing dest). Symlinks (node resolves relative link
// targets) and special files (node-specific error codes) must go through
// the ported implementation.
return { ok: srcStat.isFile() && (!destStat || destStat.isFile()), checked };
// A regular file onto a regular file or onto nothing. The native copy writes into a dest that is there, where the walker unlinks it first.
return (paths & kSrcIsFile) !== 0 && (!(paths & kDestExists) || (paths & kDestIsFile) !== 0);
}

function cpSyncFn(src: string, dest: string, opts: CpOptions, checked?: CheckedPaths) {
// `checked` carries the stats from a preceding tryNativeFastPathSync so the
// fallback doesn't re-run the same checkPaths/checkParentPaths syscalls.
const { srcStat, destStat, skipped } = checked ?? checkPathsSync(src, dest, opts);
if (skipped) return;
if (checked === undefined) checkParentPathsSync(src, srcStat, dest);
return checkParentDir(destStat, src, dest, opts);
// https://github.com/nodejs/node/blob/v26.12.1/lib/internal/fs/cp/cp-sync.js#L41-L59
function cpSyncFn(src: string, dest: string, opts: CpOptions) {
if (opts.filter) {
const shouldCopy = opts.filter(src, dest);
if ($isPromise(shouldCopy)) {
throw $ERR_INVALID_RETURN_VALUE("boolean", "filter", shouldCopy);
}
if (!shouldCopy) return;
}
// Throws as node's C++ does, where the walker below throws a SystemError: `NodeFS::cp_sync_check_paths` in src/runtime/node/node_fs.rs.
const paths = binding.cpSyncCheckPaths(src, dest, opts.dereference, opts.recursive);
// The walker joins and resolves its paths with node:path, which takes strings.
validateString(src, "src");
validateString(dest, "dest");
Comment thread
robobun marked this conversation as resolved.
Resolved
if (copiesNatively(paths, src, opts)) {
return binding.cpSync(src, dest, opts.recursive, false, true, 0);
}
return checkParentDir((paths & kDestExists) !== 0, src, dest, opts);
}

function checkParentDir(destStat: BigIntStats | null | undefined, src: string, dest: string, opts: CpOptions) {
function checkParentDir(destStat: DestinationStats, src: string, dest: string, opts: CpOptions) {
const destParent = dirname(dest);
if (!existsSync(destParent)) mkdirSync(destParent, { recursive: true });
return getStats(destStat, src, dest, opts);
}

function getStats(destStat: BigIntStats | null | undefined, src: string, dest: string, opts: CpOptions) {
function getStats(destStat: DestinationStats, src: string, dest: string, opts: CpOptions) {
const statSyncFn = opts.dereference ? statSync : lstatSync;
const srcStat = statSyncFn(src);

Expand Down Expand Up @@ -416,7 +409,7 @@ function getStats(destStat: BigIntStats | null | undefined, src: string, dest: s
});
}

function onFile(srcStat: Stats, destStat: BigIntStats | null | undefined, src: string, dest: string, opts: CpOptions) {
function onFile(srcStat: Stats, destStat: DestinationStats, src: string, dest: string, opts: CpOptions) {
if (!destStat) return copyFile(srcStat, src, dest, opts);
return mayCopyFile(srcStat, src, dest, opts);
}
Expand Down Expand Up @@ -470,7 +463,7 @@ function setDestTimestamps(src: string, dest: string) {
return utimesSync(dest, updatedSrcStat.atime, updatedSrcStat.mtime);
}

function onDir(srcStat: Stats, destStat: BigIntStats | null | undefined, src: string, dest: string, opts: CpOptions) {
function onDir(srcStat: Stats, destStat: DestinationStats, src: string, dest: string, opts: CpOptions) {
if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts);
if (opts.errorOnExist && !opts.force) {
throw fsCpEExistError({
Expand Down Expand Up @@ -500,7 +493,7 @@ function copyDir(src: string, dest: string, opts: CpOptions) {
}
}

function onLink(destStat: BigIntStats | null | undefined, src: string, dest: string, opts: CpOptions) {
function onLink(destStat: DestinationStats, src: string, dest: string, opts: CpOptions) {
let resolvedSrc = readlinkSync(src);
if (!opts.verbatimSymlinks && !isAbsolute(resolvedSrc)) {
resolvedSrc = resolve(dirname(src), resolvedSrc);
Expand Down Expand Up @@ -559,7 +552,6 @@ function copyLink(resolvedSrc: string, dest: string) {
export default {
cpSyncFn,
validateCpOptions,
tryNativeFastPathSync,
errno: { EEXIST, EISDIR, EINVAL, ENOTDIR },
fsCpDirToNonDirError,
fsCpEExistError,
Expand Down
10 changes: 1 addition & 9 deletions src/js/node/fs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -998,19 +998,11 @@ realpathSync.native = fs.realpathNativeSync.bind(fs);
// and on MacOS, simple cases of recursive directory trees can be done in a single `clonefile()`
// using filter and other options uses a lazily loaded js fallback ported from node.js
function cpSync(src, dest, options?) {
const { cpSyncFn, validateCpOptions, tryNativeFastPathSync } = require("internal/fs/cp-sync");
const { cpSyncFn, validateCpOptions } = require("internal/fs/cp-sync");
const { getValidatedFsPath } = require("internal/validators");
options = validateCpOptions(options);
src = getValidatedFsPath(src, "src");
dest = getValidatedFsPath(dest, "dest");
const { filter, dereference, preserveTimestamps, verbatimSymlinks, mode, errorOnExist, force, recursive } = options;
if (!filter && !dereference && !preserveTimestamps && !verbatimSymlinks && !mode && !errorOnExist && force) {
const { ok, checked } = tryNativeFastPathSync(src, dest, options);
if (ok) {
return fs.cpSync(src, dest, recursive, errorOnExist, force, mode);
}
return cpSyncFn(src, dest, options, checked);
}
return cpSyncFn(src, dest, options);
}

Expand Down
7 changes: 7 additions & 0 deletions src/js/private.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1974,6 +1974,13 @@ declare namespace $Node {
force: boolean,
mode: number,
): void;
/** The checks `fs.cpSync` makes of its two paths, which throw. The answer is read by `cpSyncFn` in internal/fs/cp-sync. */
cpSyncCheckPaths(
source: string | Uint8Array,
destination: string | Uint8Array,
dereference: boolean,
recursive: boolean,
): number;
existsSync(path: PathLike): boolean;
fchmodSync(fd: number, mode: number | string): void;
fchownSync(fd: number, uid: number, gid: number): void;
Expand Down
8 changes: 8 additions & 0 deletions src/runtime/node/Stat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,14 @@ impl Stats {
}
}

/// What the system call read.
pub(crate) fn posix(&self) -> &PosixStat {
match self {
Stats::Big(v) => &v.value,
Stats::Small(v) => &v.value,
}
}

// A `to_js` method is intentionally omitted to force callers toward
// `to_js_newly_created` — misuse is a hard "no method named `to_js`"
// compile error.
Expand Down
Loading
Loading