From 6685981a94a4e0cffa60926d18200b5f5bb742d1 Mon Sep 17 00:00:00 2001 From: Eugene Kalinin Date: Fri, 30 Oct 2026 18:44:22 +0300 Subject: [PATCH 1/2] perf(nodeenv): unpack the node.js zip archive in parallel On Windows, scanners that check every new file made the one by one extractall of the node.js zip take hours. The zip branch of download_node_src now extracts the files with 32 threads, after creating every directory in the main thread: before Python 3.13 zipfile fails when two threads create the same directory. The first failing file stops the extraction and the files that have not started are dropped, and so does Ctrl+C. The main thread waits with a timeout, since before Python 3.14 Ctrl+C does not interrupt waiting on a lock on Windows. Tar archives are extracted as before. Fixes #366 --- CHANGES | 4 ++ nodeenv.py | 43 +++++++++++- tests/nodeenv_test.py | 160 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 205 insertions(+), 2 deletions(-) diff --git a/CHANGES b/CHANGES index bbb0888..9af9c79 100644 --- a/CHANGES +++ b/CHANGES @@ -4,6 +4,10 @@ Nodeenv changelog Version [unreleased] -------------------- +- On Windows, Cygwin and MSYS the node.js zip archive is extracted 32 files + at a time instead of one by one, so a security scanner that checks every + new file no longer makes the install wait for each file in turn + `#366 `_ - `--prebuilt` installs no longer mistake a cached source tree for a prebuilt archive, or fail when both trees remain in `src/` `#443 `_ diff --git a/nodeenv.py b/nodeenv.py index 118ce53..f7d2e1e 100644 --- a/nodeenv.py +++ b/nodeenv.py @@ -11,6 +11,7 @@ """ import base64 +import concurrent.futures import contextlib import io import json @@ -57,6 +58,9 @@ # Seconds to wait for a server to answer or to send more of the body, # so that a stalled download fails instead of hanging forever download_timeout = 60 +# Files of the node.js zip archive extracted at once: on Windows, scanners +# that check every new file make a one by one extraction slow +extract_workers = 32 # --------------------------------------------------------- # Utils @@ -862,6 +866,40 @@ def _download_node_file(node_url, n_attempt=3, delay=3): time.sleep(delay) +def _extract_zip(archive, path, names): + """ + Extract the names of a zip archive extract_workers files at a time + + Scanners that check every new file make a one by one extraction take + hours on Windows https://github.com/ekalinin/nodeenv/issues/366 + """ + # Create the directories first, so that threads never create the same + # one: before Python 3.13 zipfile fails if another thread did it first + files = [name for name in names if not name.endswith('/')] + dirs = set(name for name in names if name.endswith('/')) + dirs.update(name.rpartition('/')[0] + '/' for name in files + if '/' in name) + for name in sorted(dirs): + archive.extract(zipfile.ZipInfo(name), path) + + with concurrent.futures.ThreadPoolExecutor(extract_workers) as pool: + try: + pending = [pool.submit(archive.extract, name, path) + for name in files] + while pending: + # Wake up now and then: before Python 3.14 Ctrl+C does not + # interrupt waiting on a lock on Windows + done, pending = concurrent.futures.wait( + pending, timeout=0.1, + return_when=concurrent.futures.FIRST_EXCEPTION) + for future in done: + future.result() + except BaseException: + # Drop the files that have not started yet + pool.shutdown(cancel_futures=True) + raise + + def download_node_src(node_url, src_dir, args): """ Download source code @@ -888,8 +926,9 @@ def download_node_src(node_url, src_dir, args): for member in members(archive) if re.match(rexp_string, member_name(member)) is None ] - # filter= is a tarfile-only argument, zipfile has no such option - if sys.version_info >= (3, 12) and not (is_WIN or is_CYGWIN): + if is_WIN or is_CYGWIN: + _extract_zip(archive, src_dir, extract_list) + elif sys.version_info >= (3, 12): archive.extractall(src_dir, extract_list, filter="data") else: archive.extractall(src_dir, extract_list) diff --git a/tests/nodeenv_test.py b/tests/nodeenv_test.py index 0b90187..215e6f0 100644 --- a/tests/nodeenv_test.py +++ b/tests/nodeenv_test.py @@ -1,4 +1,5 @@ from shlex import quote as _quote +import _thread import contextlib import http.server import io @@ -13,6 +14,7 @@ import ssl import tarfile import threading +import time import zipfile from unittest import mock @@ -958,6 +960,164 @@ class args: assert not os.path.exists(os.path.join(node_dir, 'README.md')) +def _zip_tree(node_version, n_files, dir_entries=True): + """ + A zip shaped like the node.js Windows archive: nested directories, + many files in one directory and the docs that are not extracted. + Return the archive and the content of each file it should extract. + """ + top = 'node-v%s-win-x64/' % node_version + lib = top + 'node_modules/npm/lib/' + files = {top + 'node.exe': b'binary'} + for i in range(n_files - 1): + files[lib + 'f%03d.js' % i] = b'file %d' % i + buf = io.BytesIO() + with zipfile.ZipFile(buf, 'w') as zf: + if dir_entries: + for name in (top, top + 'node_modules/', top + 'node_modules/npm/', + lib, top + 'node_modules/npm/empty/'): + zf.writestr(name, '') + for name in ('README.md', 'CHANGELOG.md', 'LICENSE'): + zf.writestr(top + name, 'doc') + for name, data in files.items(): + zf.writestr(name, data) + return io.BytesIO(buf.getvalue()), files + + +def _extracted_tree(root): + """Map each file under root, as a `/`-separated path, to its content""" + tree = {} + for dirpath, _dirnames, filenames in os.walk(root): + for filename in filenames: + path = os.path.join(dirpath, filename) + with open(path, 'rb') as f: + tree[os.path.relpath(path, root).replace(os.sep, '/')] = \ + f.read() + return tree + + +def _on_zip_file(callback): + """ + Patch ZipFile.extract to call callback(name, path) before it extracts + a file; directories are extracted as is. + """ + extract = zipfile.ZipFile.extract + + def wrapper(self, member, path=None, pwd=None): + name = getattr(member, 'filename', member) + if not name.endswith('/'): + callback(name, path) + return extract(self, member, path, pwd) + return mock.patch.object(zipfile.ZipFile, 'extract', wrapper) + + +def _download_zip(tmpdir, archive): + class args: + node = '22.14.0' + + with mock.patch.object(nodeenv, 'is_WIN', True), \ + mock.patch.object(nodeenv, '_download_node_file', + return_value=archive): + nodeenv.download_node_src('https://dummy/node.zip', + tmpdir.strpath, args) + + +@pytest.mark.parametrize('dir_entries', [True, False], + ids=['dir-entries', 'no-dir-entries']) +def test_download_node_src_zip_tree(tmpdir, dir_entries): + """Every file of the zip is extracted, except the top-level docs #366""" + archive, files = _zip_tree('22.14.0', 100, dir_entries) + _download_zip(tmpdir, archive) + + assert _extracted_tree(tmpdir.strpath) == files + empty = os.path.join(tmpdir.strpath, 'node-v22.14.0-win-x64', + 'node_modules', 'npm', 'empty') + assert os.path.isdir(empty) == dir_entries + + +def test_download_node_src_zip_extract_workers_at_once(tmpdir): + """ + The zip files are extracted extract_workers at a time and never more, + each into a directory that already exists #366 + """ + workers = nodeenv.extract_workers + assert workers == 32 + archive, files = _zip_tree('22.14.0', 2 * workers, dir_entries=False) + # lets files through only when extract_workers of them run at once + barrier = threading.Barrier(workers, timeout=10) + lock = threading.Lock() + running = [] + most_running = [0] + no_parent = [] + + def on_file(name, path): + if not os.path.isdir(os.path.dirname(os.path.join(path, name))): + no_parent.append(name) + with lock: + running.append(name) + most_running[0] = max(most_running[0], len(running)) + barrier.wait() + # stay running, so that a file over the limit would be counted + time.sleep(0.05) + with lock: + running.remove(name) + + with _on_zip_file(on_file): + _download_zip(tmpdir, archive) + + assert most_running[0] == workers + assert no_parent == [] + assert _extracted_tree(tmpdir.strpath) == files + + +def test_download_node_src_zip_stops_on_error(tmpdir): + """ + A file that fails to extract fails the download, and the files that + have not started yet are not extracted #366 + """ + archive, _files = _zip_tree('22.14.0', 300) + lock = threading.Lock() + started = [] + + def on_file(name, path): + with lock: + started.append(name) + first = len(started) == 1 + if first: + raise OSError('cannot write %s' % name) + time.sleep(0.5) + + with _on_zip_file(on_file), pytest.raises(OSError, match='cannot write'): + _download_zip(tmpdir, archive) + + assert len(started) <= 2 * nodeenv.extract_workers + + +def test_download_node_src_zip_stops_on_interrupt(tmpdir): + """ + Ctrl+C stops the extraction without waiting for the files that have + not started yet #366 + """ + archive, _files = _zip_tree('22.14.0', 300) + lock = threading.Lock() + started = [] + + def on_file(name, path): + with lock: + started.append(name) + first = len(started) == 1 + if first: + # like Ctrl+C on Windows before Python 3.14, this does not + # wake up the main thread blocked on a lock + threading.Timer(0.1, _thread.interrupt_main).start() + time.sleep(0.5) + + with _on_zip_file(on_file), pytest.raises(KeyboardInterrupt): + _download_zip(tmpdir, archive) + + assert len(started) <= 2 * nodeenv.extract_workers + + def test_download_node_src_tar_keeps_data_filter(tmpdir): """The tar path must keep filter='data' (CVE-2007-4559 protection)""" class args: From 38290c274de6d217f2d5d521e874cf744e65e7c0 Mon Sep 17 00:00:00 2001 From: Eugene Kalinin Date: Fri, 30 Oct 2026 19:20:22 +0300 Subject: [PATCH 2/2] feat(nodeenv): add an option to turn off parallel zip extraction --no-parallel-extract, or parallel_extract = False in the [nodeenv] section of a config file, extracts the node.js zip archive with the old one by one extractall. --parallel-extract, the default, turns it back on over the config. The config also reaches pre-commit, which runs nodeenv with its own arguments. Tar archives are not affected. --- CHANGES | 4 +++- README.rst | 10 ++++++++++ nodeenv.py | 17 +++++++++++++++-- tests/nodeenv_test.py | 43 ++++++++++++++++++++++++++++++++++++++++++- 4 files changed, 70 insertions(+), 4 deletions(-) diff --git a/CHANGES b/CHANGES index 9af9c79..369fc68 100644 --- a/CHANGES +++ b/CHANGES @@ -6,7 +6,9 @@ Version [unreleased] - On Windows, Cygwin and MSYS the node.js zip archive is extracted 32 files at a time instead of one by one, so a security scanner that checks every - new file no longer makes the install wait for each file in turn + new file no longer makes the install wait for each file in turn. + `--no-parallel-extract`, or `parallel_extract = False` in `~/.nodeenvrc`, + extracts it one file at a time again `#366 `_ - `--prebuilt` installs no longer mistake a cached source tree for a prebuilt archive, or fail when both trees remain in `src/` diff --git a/README.rst b/README.rst index 21761eb..7f6df92 100644 --- a/README.rst +++ b/README.rst @@ -399,6 +399,15 @@ Installation options Keep "src" directory after installation. With ``--source`` it holds the downloaded source tree, so a repeated ``--force`` build reuses it. +``--parallel-extract`` + Extract the node.js zip archive on Windows, Cygwin and MSYS 32 files at + a time, so that a security scanner that checks every new file does not + hold up the whole install. This is the default. + +``--no-parallel-extract`` + Extract the zip archive one file at a time. Set + ``parallel_extract = False`` in ``~/.nodeenvrc`` to make this the default. + NPM options ^^^^^^^^^^^ @@ -495,6 +504,7 @@ These are the available options and their defaults:: prefer_system = False isolate_npm = False clean_src = True + parallel_extract = True Alternatives ------------ diff --git a/nodeenv.py b/nodeenv.py index f7d2e1e..0a2d741 100644 --- a/nodeenv.py +++ b/nodeenv.py @@ -87,6 +87,7 @@ class Config(object): prefer_system = False isolate_npm = False clean_src = True + parallel_extract = True @classmethod def _load(cls, configfiles, verbose=False): @@ -576,6 +577,17 @@ def make_parser(): action='store_false', help='Keep "src" directory after installation') + parser.add_argument( + '--parallel-extract', dest='parallel_extract', + action='store_true', default=Config.parallel_extract, + help='Extract the node.js zip archive on Windows, Cygwin and MSYS ' + '%d files at a time (default)' % extract_workers) + + parser.add_argument( + '--no-parallel-extract', dest='parallel_extract', + action='store_false', + help='Extract the node.js zip archive one file at a time') + parser.add_argument( '--force', dest='force', action='store_true', default=False, @@ -926,9 +938,10 @@ def download_node_src(node_url, src_dir, args): for member in members(archive) if re.match(rexp_string, member_name(member)) is None ] - if is_WIN or is_CYGWIN: + if (is_WIN or is_CYGWIN) and args.parallel_extract: _extract_zip(archive, src_dir, extract_list) - elif sys.version_info >= (3, 12): + # filter= is a tarfile-only argument, zipfile has no such option + elif sys.version_info >= (3, 12) and not (is_WIN or is_CYGWIN): archive.extractall(src_dir, extract_list, filter="data") else: archive.extractall(src_dir, extract_list) diff --git a/tests/nodeenv_test.py b/tests/nodeenv_test.py index 215e6f0..6a99142 100644 --- a/tests/nodeenv_test.py +++ b/tests/nodeenv_test.py @@ -947,6 +947,7 @@ def test_download_node_src_zip(tmpdir): """On Windows the archive is a zip, which has no extractall(filter=...)""" class args: node = '22.14.0' + parallel_extract = True with mock.patch.object(nodeenv, 'is_WIN', True), \ mock.patch.object(nodeenv, '_download_node_file', @@ -1011,10 +1012,11 @@ def wrapper(self, member, path=None, pwd=None): return mock.patch.object(zipfile.ZipFile, 'extract', wrapper) -def _download_zip(tmpdir, archive): +def _download_zip(tmpdir, archive, parallel_extract=True): class args: node = '22.14.0' + args.parallel_extract = parallel_extract with mock.patch.object(nodeenv, 'is_WIN', True), \ mock.patch.object(nodeenv, '_download_node_file', return_value=archive): @@ -1035,6 +1037,16 @@ def test_download_node_src_zip_tree(tmpdir, dir_entries): assert os.path.isdir(empty) == dir_entries +def test_download_node_src_zip_parallel_extract_off(tmpdir): + """--no-parallel-extract extracts the zip as before, one by one #366""" + archive, files = _zip_tree('22.14.0', 100) + with mock.patch.object(nodeenv, '_extract_zip') as extract_zip: + _download_zip(tmpdir, archive, parallel_extract=False) + + extract_zip.assert_not_called() + assert _extracted_tree(tmpdir.strpath) == files + + def test_download_node_src_zip_extract_workers_at_once(tmpdir): """ The zip files are extracted extract_workers at a time and never more, @@ -1547,6 +1559,35 @@ def test_parse_args_clean_src(): assert nodeenv.parse_args().clean_src is False +def test_parallel_extract_default(): + assert nodeenv.Config._default['parallel_extract'] is True + + +def test_parallel_extract_is_configurable(tmpdir): + rc = tmpdir.join('nodeenvrc') + rc.write('[nodeenv]\nparallel_extract = false\n') + try: + nodeenv.Config._load([str(rc)]) + assert nodeenv.Config.parallel_extract is False + finally: + nodeenv.Config.parallel_extract = True + + +def test_parse_args_parallel_extract(): + with mock.patch.object(sys, 'argv', ['nodeenv', 'env']): + assert nodeenv.parse_args().parallel_extract is True + with mock.patch.object( + sys, 'argv', ['nodeenv', '--no-parallel-extract', 'env']): + assert nodeenv.parse_args().parallel_extract is False + # the flag turns it back on over the config + with mock.patch.object(nodeenv.Config, 'parallel_extract', False): + with mock.patch.object(sys, 'argv', ['nodeenv', 'env']): + assert nodeenv.parse_args().parallel_extract is False + with mock.patch.object( + sys, 'argv', ['nodeenv', '--parallel-extract', 'env']): + assert nodeenv.parse_args().parallel_extract is True + + def _run_create_environment(tmpdir, extra): """ Run create_environment() in tmpdir without installing anything