Single file deno (#478)

* Singlefile runs under Deno 2.8.3; browser leftovers are reaped.

single-file-cli is designed for Deno.  Under node 18 (Debian 12/RPi OS) it
cannot reach the browser CDP on IPv6-enabled hosts ("localhost" resolves to
::1 first with no IPv4 fallback) and it never exits after a successful save,
blocking the download worker forever.

The native path and the Archive docker container now run single-file with
"deno run".  Deno is pinned at v2.8.3 everywhere because yt-dlp 2026.06.09
requires at least 2.3.0 (our node is Debian's v18, below yt-dlp's v22
minimum).  Deno >= 2.3 kills the browser single-file spawns (piped stderr
that single-file never reads), so the browser is run through
singlefile_browser_wrapper.sh which discards its stderr.

Commands are run in their own process group which is killed when they
finish, reaping the browser single-file leaves behind.  The Archive
downloader now has a ten minute timeout.  Install scripts install Deno
(previously only upgrade.sh and the image builds did).

* Singlefile writes to a file instead of dumping to stdout.

Deno >= 2.3 truncates large --dump-content output at exit; compressed
(SingleFileZ) singlefiles of large pages lost their ZIP tail, failed the
compression check in write_archive_files, and were destroyed by the HTML
prettifier (blank white archives).  single-file now writes its result to a
temporary file which WROLPi reads back.

As insurance, a singlefile marked compressed (<html data-sfz) whose ZIP is
unreadable is now stored verbatim instead of being prettified.

* Compressed Archive screenshots and readability images are no longer broken.

The index.html inside a compressed (SingleFileZ) singlefile references its
resources by relative ZIP paths.  Screenshots are now taken from the fully
extracted ZIP so those references resolve.  Readability images are inlined
as data URIs read from the ZIP (readability-extractor absolutizes relative
srcs against the page URL, so both forms are matched).

* Compressed Archives are created by converting the uncompressed capture.

The page is always captured uncompressed; readability, screenshot, and
title come from that canonical page (its images are inline data URIs, so
no ZIP extraction or image inlining is needed).  When compress_singlefile
is set, a second single-file run converts the captured file into a
compressed (SingleFileZ) self-extracting file.  The conversion is a local
file:// operation - the page is not fetched again, and single-file
preserves the original URL header when re-saving its own pages.  If the
conversion fails, the uncompressed singlefile is stored instead.

* Consolidating duplicate compressed-singlefile tests.

The write_archive_files tests (verbatim write, title fallback, broken-ZIP
guard, readability inlining) are combined into one test; the helper probes
and the setting-plumbing tests are each merged into one.  The do_singlefile
compression-failure scenario and the timeout constant are folded into the
main do_singlefile test, which shared their setup.

* Addressing review comments: removeprefix, PermissionError when killing.

* Bumping version to 0.24.1-beta.

* Install scripts assert the deno.zip hash to avoid malicious or invalid files.

The hashes are the official sha256sum assets of the Deno v2.8.3 release,
per architecture.

* Archive Dockerfile asserts the deno.zip hash to avoid malicious or invalid files.

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
lrnselfreliance 2026-06-12 17:07:10 -06:00 • committed by Roland
parent 65513eab82
commit 1acb148c90
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
18 changed files with 598 additions and 112 deletions

View file

@ -67,8 +67,8 @@ BROWSERSLIST_IGNORE_OLD_DATA=true npm run build
npm i -g serve@12.0.1 single-file-cli@2.0.73 readability-extractor@0.0.6
# Install Deno runtime. Hash pinned to detect tampering of the upstream release artifact.
DENO_VERSION="v2.2.4"
DENO_SHA256="9a260a624cab6e61f7603957f94f638d68739d8c6ac8c38bc337521266603a7c"
DENO_VERSION="v2.8.3"
DENO_SHA256="30455b845ffa6082209c3590269c910ad3b7efdf28c9879afd4006c47ae54197"
curl -fsSL "https://github.com/denoland/deno/releases/download/${DENO_VERSION}/deno-x86_64-unknown-linux-gnu.zip" -o /tmp/deno.zip
echo "${DENO_SHA256} /tmp/deno.zip" | sha256sum -c -
unzip /tmp/deno.zip -d /usr/local/bin/

View file

@ -5,17 +5,37 @@ WORKDIR /app
# Install Python for main.py
ENV PYTHONUNBUFFERED=1
RUN apt update && apt install -y python3 python3-dev python3-venv curl && ln -sf python3 /usr/bin/python
RUN apt update && apt install -y python3 python3-dev python3-venv curl unzip && ln -sf python3 /usr/bin/python
RUN python3 -m venv /app/venv
RUN . /app/venv/bin/activate
# Install a newer singlefile and Readability.
RUN npm install -g single-file-cli@2.0.73 readability-extractor@0.0.6
# Install Deno; single-file-cli is designed for it (under node 18 it cannot reach the browser CDP
# on IPv6-enabled hosts and never exits). Match the version pinned in scripts/upgrade.sh.
RUN DENO_VERSION="v2.8.3" \
&& ARCH=$(uname -m) \
&& if [ "$ARCH" = "aarch64" ]; then \
DENO_ARCH="aarch64-unknown-linux-gnu"; \
DENO_SHA256="d4589cc1ffcbf1995c92a0127d932aaf832ac70cfdcc6d5b7bf38043cf303575"; \
else \
DENO_ARCH="x86_64-unknown-linux-gnu"; \
DENO_SHA256="30455b845ffa6082209c3590269c910ad3b7efdf28c9879afd4006c47ae54197"; \
fi \
&& curl -fsSL "https://github.com/denoland/deno/releases/download/${DENO_VERSION}/deno-${DENO_ARCH}.zip" -o /tmp/deno.zip \
# Assert the hash to avoid malicious or invalid files.
&& echo "${DENO_SHA256} /tmp/deno.zip" | sha256sum -c - \
&& unzip -o /tmp/deno.zip -d /usr/local/bin/ \
&& chmod +x /usr/local/bin/deno \
&& rm /tmp/deno.zip \
&& deno --version
# Install the Python wrapper and it's requirements.
COPY docker/archive/requirements.txt /app/requirements.txt
RUN /app/venv/bin/pip3 install -r /app/requirements.txt
COPY docker/archive /app
COPY scripts/singlefile_browser_wrapper.sh /app/singlefile_browser_wrapper.sh
# Launch Archive app in the virtual environment.
ENTRYPOINT [ "/app/venv/bin/python3", "/app/main.py"]

View file

@ -8,8 +8,10 @@ import gzip
import io
import json
import logging
import os
import os.path
import pathlib
import signal
import subprocess
import sys
import tempfile
@ -28,13 +30,43 @@ formatter = logging.Formatter('[%(asctime)s] [%(name)s] [%(levelname)s] %(messag
ch.setFormatter(formatter)
logger.addHandler(ch)
SINGLEFILE_PATH = pathlib.Path('/usr/src/app/node_modules/single-file-cli/single-file')
if not SINGLEFILE_PATH.is_file():
SINGLEFILE_PATH = pathlib.Path('/usr/src/app/node_modules/single-file/cli/single-file')
if not SINGLEFILE_PATH.is_file():
SINGLEFILE_PATH = pathlib.Path('/usr/src/.nvm/versions/node/v18.19.0/bin/single-file')
if not SINGLEFILE_PATH.is_file():
raise FileNotFoundError("Can't find single-file executable!")
def find_singlefile_deno_script() -> pathlib.Path:
"""Find the Deno entry script of the single-file-cli package.
single-file-cli is designed for Deno; the npm bin (single-file-node.js) runs under node which
cannot reach the browser CDP on IPv6-enabled hosts and never exits after a successful save."""
candidates = (
'/usr/src/app/node_modules/single-file-cli/single-file',
'/usr/local/lib/node_modules/single-file-cli/single-file',
'/usr/lib/node_modules/single-file-cli/single-file',
# Resolve the bin symlink back to the package directory.
'/usr/src/.nvm/versions/node/v18.19.0/bin/single-file',
'/usr/local/bin/single-file',
)
for candidate in candidates:
path = pathlib.Path(candidate)
if path.is_file():
script = path.resolve().parent / 'single-file'
try:
with script.open('rb') as fh:
if b'deno run' in fh.readline():
return script
except OSError:
pass
raise FileNotFoundError("Can't find single-file Deno script!")
SINGLEFILE_PATH = find_singlefile_deno_script()
DENO_PATH = pathlib.Path('/usr/local/bin/deno')
if not DENO_PATH.is_file():
raise FileNotFoundError("Can't find deno executable!")
# single-file pipes the browser's stderr but never reads it; under Deno >= 2.3 that kills the
# browser during startup. The wrapper discards the browser's stderr.
BROWSER_WRAPPER = pathlib.Path('/app/singlefile_browser_wrapper.sh')
if not BROWSER_WRAPPER.is_file():
raise FileNotFoundError("Can't find singlefile_browser_wrapper.sh!")
BROWSER_EXEC = pathlib.Path('/usr/bin/google-chrome')
if not BROWSER_EXEC.is_file():
@ -72,7 +104,10 @@ async def index(_):
async def check_output(cmd, always_log_stderr: bool = False, cwd=None, timeout: float = None):
proc = None
try:
proc = await asyncio.create_subprocess_shell(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd)
# start_new_session so the whole process group can be killed; single-file does not close
# the browser it spawns.
proc = await asyncio.create_subprocess_shell(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd,
start_new_session=True)
stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=timeout)
if always_log_stderr is True or proc.returncode != 0:
# Always log when requested, or when the call failed.
@ -83,29 +118,69 @@ async def check_output(cmd, always_log_stderr: bool = False, cwd=None, timeout:
proc.kill()
await proc.wait() # Wait for the process to fully terminate
raise TimeoutError(f"Command '{cmd}' timed out after {timeout} seconds")
finally:
if proc is not None:
# Kill anything the command left behind (e.g. the browser single-file spawns).
try:
os.killpg(proc.pid, signal.SIGKILL)
logger.info(f'Killed lingering process group {proc.pid}')
except ProcessLookupError:
pass # Nothing left behind; the common case.
except PermissionError as e:
# Do not let the kill mask the real failure (e.g. a TimeoutError in flight).
logger.error(f'Failed to kill process group {proc.pid}', exc_info=e)
async def call_single_file(url, compress: bool = False) -> bytes:
async def run_single_file(input_url: str, output_path: pathlib.Path, compress: bool):
"""Run single-file, return (return_code, output_bytes, stderr).
single-file writes the result to a file; Deno >= 2.3 truncates large --dump-content output
at exit, which corrupted compressed (ZIP) singlefiles."""
cmd = f'WROLPI_BROWSER={BROWSER_EXEC}' \
f' {DENO_PATH} run --node-modules-dir=manual' \
' --allow-read --allow-write --allow-net --allow-env --allow-run' \
f' {SINGLEFILE_PATH}' \
f' --browser-executable-path {BROWSER_WRAPPER}' \
f'{" --compress-content " if compress else ""}' \
f' "{input_url}"' \
f' "{output_path}"'
logger.debug(f'archive cmd: {cmd}')
stdout, stderr, return_code = await check_output(cmd, always_log_stderr=True, timeout=3 * 60)
output = output_path.read_bytes() if output_path.is_file() else b''
return return_code, output, stderr
async def call_single_file(url, compress: bool = False) -> (bytes, bytes):
"""
Call the CLI command for SingleFile.
Call the CLI command for SingleFile. Returns (singlefile, page_html): the singlefile to
store, and the uncompressed page for readability/screenshot.
The page is always captured uncompressed; when compress is set, a second single-file run
converts the captured file into a compressed (SingleFileZ) self-extracting file (a local
file:// operation, the page is not fetched again). If the conversion fails, the
uncompressed singlefile is returned instead.
See https://github.com/gildas-lormeau/SingleFile
"""
logger.info(f'archiving {url}')
# --compress-content creates a compressed (SingleFileZ) self-extracting HTML file.
cmd = f'{SINGLEFILE_PATH}' \
r' --dump-content ' \
f'{" --compress-content " if compress else ""}' \
f' "{url}"'
logger.debug(f'archive cmd: {cmd}')
stdout, stderr, return_code = await check_output(cmd, always_log_stderr=True, timeout=3 * 60)
if return_code != 0 or not stdout:
if stderr:
for line in stderr.splitlines():
logger.error(line.decode())
raise RuntimeError(f'Failed to single-file {url} got the following error: {stderr}')
with tempfile.TemporaryDirectory(prefix='singlefile-') as tmp_dir:
page_path = pathlib.Path(tmp_dir) / 'page.html'
return_code, page_html, stderr = await run_single_file(url, page_path, compress=False)
if return_code != 0 or not page_html:
raise RuntimeError(f'Failed to single-file {url} got the following error: {stderr}')
singlefile = page_html
if compress:
compressed_path = pathlib.Path(tmp_dir) / 'compressed.html'
return_code, compressed, stderr = await run_single_file(
f'file://{page_path}', compressed_path, compress=True)
if return_code == 0 and zipfile.is_zipfile(io.BytesIO(compressed)):
singlefile = compressed
else:
logger.error(f'Failed to compress singlefile ({return_code=}), storing it uncompressed: {url}')
logger.debug(f'done archiving for {url}')
return stdout
return singlefile, page_html
async def extract_readability(path: str, url: str) -> dict:
@ -255,17 +330,23 @@ async def post_archive(request: Request):
singlefile = base64.b64decode(singlefile) if singlefile else None
compress = bool(request.json.get('compress'))
# Use provided singlefile, or fetch and create from the internet.
singlefile = singlefile or await call_single_file(url, compress=compress)
if singlefile:
# A provided singlefile may be compressed (SingleFileZ); readability and screenshot
# must use the extracted index.html.
page_html = None
else:
# Fetch and create from the internet; readability/screenshot use the uncompressed page.
singlefile, page_html = await call_single_file(url, compress=compress)
# Use html suffix so chrome screenshot recognizes it as an HTML file.
with tempfile.TemporaryDirectory() as tmp_dir:
singlefile_path = pathlib.Path(tmp_dir) / 'singlefile.html'
singlefile_path.write_bytes(singlefile)
# A compressed (SingleFileZ) singlefile contains the uncompressed page; readability and
# screenshot must use the extracted index.html.
extractable = extract_compressed_singlefile(singlefile, tmp_dir) or str(singlefile_path)
page_path = pathlib.Path(tmp_dir) / 'page.html'
if page_html:
page_path.write_bytes(page_html)
extractable = str(page_path)
else:
page_path.write_bytes(singlefile)
extractable = extract_compressed_singlefile(singlefile, tmp_dir) or str(page_path)
readability = None
try:

View file

@ -1,6 +1,8 @@
import asyncio
import json
import os
import pathlib
import tempfile
from abc import ABC
from dataclasses import dataclass
from typing import Callable, List, Optional, Tuple, Iterable
@ -8,7 +10,7 @@ from typing import Callable, List, Optional, Tuple, Iterable
from sqlalchemy import not_
from sqlalchemy.orm import Session
from wrolpi.cmd import SINGLE_FILE_BIN, CHROMIUM, FIREFOX
from wrolpi.cmd import SINGLE_FILE_BIN, CHROMIUM, FIREFOX, DENO_BIN, SINGLE_FILE_DENO_SCRIPT
from wrolpi.collections import Collection
from wrolpi.common import logger, register_modeler, register_refresh_cleanup, limit_concurrent, split_lines_by_length, \
slow_logger, get_title_from_html, TRACE_LEVEL
@ -16,7 +18,7 @@ from wrolpi.db import get_db_session
from wrolpi.downloader import Downloader, Download, DownloadContext, DownloadResult
from wrolpi.errors import UnrecoverableDownloadError
from wrolpi.files.models import FileGroup
from wrolpi.vars import PYTEST, DOCKERIZED, DOWNLOAD_USER_AGENT
from wrolpi.vars import PYTEST, DOCKERIZED, DOWNLOAD_USER_AGENT, PROJECT_DIR
from . import lib
from .api import archive_bp # noqa
from .errors import InvalidArchive
@ -52,6 +54,9 @@ class ExecutedArchive:
class ArchiveDownloader(Downloader, ABC):
name = 'archive'
pretty_name = 'Archive'
# A page that has not finished archiving after this long is hung; the config-level
# download_timeout still takes precedence when set.
timeout = 10 * 60
def __repr__(self):
return f'<ArchiveDownloader>'
@ -86,8 +91,11 @@ class ArchiveDownloader(Downloader, ABC):
artifacts = SinglefileArtifacts(url=prepared.url, singlefile=singlefile,
readability=readability, screenshot=screenshot)
else:
singlefile_bytes = await self.do_singlefile(prepared, ctx, download=download)
artifacts = await extract_singlefile_artifacts(singlefile_bytes)
singlefile_bytes, page_html = await self.do_singlefile(prepared, ctx, download=download)
# Readability/screenshot/title come from the uncompressed page; only the stored
# singlefile may be compressed.
artifacts = await extract_singlefile_artifacts(page_html)
artifacts.singlefile = singlefile_bytes
written = write_archive_files(artifacts.url, artifacts.singlefile, artifacts.readability,
artifacts.screenshot, destination=prepared.destination)
@ -113,9 +121,16 @@ class ArchiveDownloader(Downloader, ABC):
return DownloadResult(success=True, location=archive.location)
async def do_singlefile(self, prepared: PreparedArchive, ctx: DownloadContext,
download: Download = None) -> bytes:
download: Download = None) -> Tuple[bytes, bytes]:
"""Create a Singlefile from the archive's URL.
Returns (singlefile, page_html): the singlefile to store, and the uncompressed page used
for readability/screenshot/title. The page is always captured uncompressed; when
compress_singlefile is set, a second single-file run converts the captured file into a
compressed (SingleFileZ) self-extracting file (single-file preserves the original URL
header when re-saving its own pages). If the conversion fails, the uncompressed
singlefile is stored instead.
download is the original Download row when called via the manager dispatch; tests
may omit it and a stub is built so process_runner has a url for log messages.
"""
@ -137,41 +152,83 @@ class ArchiveDownloader(Downloader, ABC):
browser_args = config.browser_args or '["--no-sandbox"]'
user_agent = config.user_agent or DOWNLOAD_USER_AGENT
cmd = ('/usr/bin/nice', '-n15', # Nice above map importing, but very low priority.
str(SINGLE_FILE_BIN),
'--browser-executable-path', str(browser),
'--browser-args', browser_args,
'--user-agent', user_agent,
'--dump-content',
'--load-deferred-images-dispatch-scroll-event',
# Create a compressed (SingleFileZ) self-extracting HTML file.
*(('--compress-content',) if prepared.settings.get('compress_singlefile') else ()),
prepared.url,
)
env = None
browser_wrapper = PROJECT_DIR / 'scripts/singlefile_browser_wrapper.sh'
if DENO_BIN and SINGLE_FILE_DENO_SCRIPT and browser_wrapper.is_file():
# single-file-cli is designed for Deno. Under node 18 (Debian 12/RPi OS) it cannot
# reach the browser CDP on IPv6-enabled hosts ("localhost" resolves to ::1 first with
# no IPv4 fallback) and it never exits after a successful save.
runtime = (str(DENO_BIN), 'run', '--node-modules-dir=manual',
'--allow-read', '--allow-write', '--allow-net', '--allow-env', '--allow-run',
str(SINGLE_FILE_DENO_SCRIPT))
# single-file pipes the browser's stderr but never reads it; under Deno >= 2.3 that
# kills the browser during startup. The wrapper discards the browser's stderr.
env = {**os.environ, 'WROLPI_BROWSER': str(browser)}
browser = browser_wrapper
else:
logger.warning('deno not found, running single-file under node. Upgrade this WROLPi to install deno.')
runtime = (str(SINGLE_FILE_BIN),)
# node 18 has no IPv4 fallback when "localhost" resolves to ::1 first; without this
# single-file cannot reach the browser CDP and fails with "fetch failed".
env = {**os.environ, 'NODE_OPTIONS': '--enable-network-family-autoselection'}
cwd = pathlib.Path('/home/wrolpi')
cwd = cwd if cwd.is_dir() else None
# cancel_wrapper reads cancellation from ctx; the Download is forwarded so
# the real download id is used for unkill cleanup and log attribution.
result = await self.process_runner(download or Download(url=prepared.url),
cmd, cwd, ctx=ctx)
download = download or Download(url=prepared.url)
stderr = result.stderr.decode()
# stdout may be a binary ZIP when --compress-content is used.
log_output = stderr or result.stdout.decode(errors='replace') or 'No stderr or stdout!'
async def run_single_file(input_url: str, output_path: pathlib.Path, compress: bool):
cmd = ('/usr/bin/nice', '-n15', # Nice above map importing, but very low priority.
*runtime,
'--browser-executable-path', str(browser),
'--browser-args', browser_args,
'--user-agent', user_agent,
'--load-deferred-images-dispatch-scroll-event',
# Create a compressed (SingleFileZ) self-extracting HTML file.
*(('--compress-content',) if compress else ()),
input_url,
str(output_path),
)
# cancel_wrapper reads cancellation from ctx; the Download is forwarded so
# the real download id is used for unkill cleanup and log attribution.
# start_new_session reaps the browser single-file leaves behind (it does not close it).
result = await self.process_runner(download, cmd, cwd, env=env, start_new_session=True, ctx=ctx)
stderr = result.stderr.decode()
log_output = stderr or result.stdout.decode(errors='replace') or 'No stderr or stdout!'
output = output_path.read_bytes() if output_path.is_file() else b''
return result.return_code, output, log_output
if result.return_code != 0:
e = ChildProcessError(log_output[:1000])
raise RuntimeError(f'singlefile exited with {result.return_code}') from e
# single-file writes the result to a file; Deno >= 2.3 truncates large --dump-content
# output at exit, which corrupted compressed (ZIP) singlefiles.
with tempfile.TemporaryDirectory(prefix='wrolpi-singlefile-') as tmp_dir:
page_path = pathlib.Path(tmp_dir) / 'page.html'
return_code, page_html, log_output = await run_single_file(prepared.url, page_path, compress=False)
if not result.stdout:
e = ChildProcessError(log_output[:1000])
raise RuntimeError(f'Singlefile created was empty: {prepared.url}') from e
if return_code != 0:
e = ChildProcessError(log_output[:1000])
raise RuntimeError(f'singlefile exited with {return_code}') from e
if SINGLEFILE_HEADER.encode() not in result.stdout:
e = ChildProcessError(log_output[:1000])
raise RuntimeError(f'Singlefile created was invalid: {prepared.url}') from e
if not page_html:
e = ChildProcessError(log_output[:1000])
raise RuntimeError(f'Singlefile created was empty: {prepared.url}') from e
return result.stdout
if SINGLEFILE_HEADER.encode() not in page_html:
e = ChildProcessError(log_output[:1000])
raise RuntimeError(f'Singlefile created was invalid: {prepared.url}') from e
singlefile = page_html
if prepared.settings.get('compress_singlefile'):
# Convert the captured page into a compressed (SingleFileZ) self-extracting file.
# This is a local (file://) operation; the page is not fetched again.
compressed_path = pathlib.Path(tmp_dir) / 'compressed.html'
return_code, compressed, log_output = await run_single_file(
f'file://{page_path}', compressed_path, compress=True)
if return_code == 0 and lib.is_compressed_singlefile(compressed):
singlefile = compressed
else:
logger.error(f'Failed to compress singlefile ({return_code=}), '
f'storing it uncompressed: {prepared.url}\n{log_output[:1000]}')
return singlefile, page_html
archive_downloader = ArchiveDownloader()

View file

@ -118,12 +118,15 @@ def compressed_singlefile_factory():
'--><meta charset=windows-1252><title></title>'
index_html = '<html><!--\n Page saved with SingleFile \n' \
f' url: {url} \n' \
f'-->\n<head><title>{title}</title></head><body>test compressed singlefile</body></html>'
f'-->\n<head><title>{title}</title></head>' \
'<body>test compressed singlefile<img src="images/0.png" srcset="images/0.png 1x"></body>' \
'</html>'
buf = io.BytesIO()
buf.write(prelude.encode())
# Deflate like the real single-file CLI; the page must not be readable as plain text.
with zipfile.ZipFile(buf, 'a', compression=zipfile.ZIP_DEFLATED) as zip_:
zip_.writestr('index.html', index_html)
zip_.writestr('images/0.png', b'\x89PNG fake image bytes')
zip_.writestr('manifest.json', '{}')
return buf.getvalue()

View file

@ -24,7 +24,7 @@ from wrolpi.cmd import READABILITY_BIN, run_command
from wrolpi.collections import Collection
from wrolpi.common import get_media_directory, get_relative_to_media_directory, logger, extract_domain, \
escape_file_name, aiohttp_post, format_html_string, split_lines_by_length, get_html_soup, get_title_from_html, \
get_wrolpi_config, html_screenshot, ConfigFile, trim_file_name
get_wrolpi_config, html_screenshot, html_file_screenshot, ConfigFile, trim_file_name
from wrolpi.dates import now, Seconds
from wrolpi.db import get_db_session, get_db_curs
from wrolpi.errors import UnknownArchive, InvalidOrderBy, InvalidDatetime
@ -748,7 +748,12 @@ def write_archive_files(url: str, singlefile: str | bytes, readability: Optional
if readability:
# Write the readability parts to their own files. Write what is left after pops to the JSON file.
with archive_files.readability.open('wt') as fp:
content = format_html_string(readability.pop('content'))
content = readability.pop('content')
if compressed:
# Readability extracted from the ZIP's index.html references images by relative
# ZIP paths; inline them so the readability file is self-contained.
content = inline_compressed_singlefile_resources(content, singlefile, url)
content = format_html_string(content)
fp.write(content)
with archive_files.readability_txt.open('wt') as fp:
readability_txt = readability.pop('textContent')
@ -762,6 +767,11 @@ def write_archive_files(url: str, singlefile: str | bytes, readability: Optional
if compressed:
# A compressed (SingleFileZ) singlefile is a binary ZIP; prettifying would corrupt it.
archive_files.singlefile.write_bytes(singlefile)
elif isinstance(singlefile, bytes) and b'<html data-sfz' in singlefile[:200]:
# Marked as compressed but the ZIP is unreadable (e.g. truncated); prettifying would
# destroy whatever remains, so store it verbatim.
logger.warning(f'Singlefile of {url} is marked compressed but is not a valid ZIP!')
archive_files.singlefile.write_bytes(singlefile)
else:
singlefile = format_html_string(singlefile)
archive_files.singlefile.write_text(singlefile)
@ -1035,6 +1045,40 @@ def read_singlefile_html(path: pathlib.Path) -> bytes:
return contents
def inline_compressed_singlefile_resources(html: str, singlefile: bytes, url: str) -> str:
"""Inline the images of a compressed (SingleFileZ) singlefile into the provided HTML.
The index.html inside a compressed singlefile references its resources by relative ZIP paths
(e.g. images/0.jpg); HTML extracted from it (readability) dangles those references — either
still relative, or absolutized against the page URL by readability-extractor
(https://example.com/images/0.jpg). Replace them with data URIs read from the ZIP, like an
uncompressed singlefile would contain."""
import mimetypes
from urllib.parse import urljoin, unquote
# readability-extractor resolves relative srcs against the page URL.
url_base = urljoin(url, '.')
soup = get_html_soup(html)
with zipfile.ZipFile(io.BytesIO(singlefile)) as zip_:
names = set(zip_.namelist())
changed = False
for img in soup.find_all('img'):
src = img.get('src') or ''
name = src.removeprefix('./')
if src.startswith(url_base):
name = unquote(src[len(url_base):])
if not name or name not in names:
continue
mimetype = mimetypes.guess_type(name)[0] or 'application/octet-stream'
img['src'] = f'data:{mimetype};base64,{base64.b64encode(zip_.read(name)).decode()}'
# The ZIP-path srcset entries are dangling too; the inlined src replaces them.
if img.get('srcset'):
del img['srcset']
changed = True
return str(soup) if changed else html
def get_url_from_singlefile(html: bytes | str) -> str:
"""Extract URL from SingleFile contents."""
# Ignore decode errors; a compressed singlefile has a plain-text prelude but a binary ZIP tail.
@ -1530,7 +1574,14 @@ async def extract_singlefile_artifacts(singlefile: bytes) -> SinglefileArtifacts
screenshot = None
try:
logger.debug(f'extract_singlefile_artifacts creating screenshot: {url}')
screenshot = html_screenshot(extractable)
if compressed:
# Extract the whole ZIP so the page's relative resources (images, fonts) render.
with tempfile.TemporaryDirectory(prefix='wrolpi-singlefile-screenshot-') as tmp_dir:
with zipfile.ZipFile(io.BytesIO(singlefile)) as zip_:
zip_.extractall(tmp_dir)
screenshot = html_file_screenshot(pathlib.Path(tmp_dir) / COMPRESSED_SINGLEFILE_INDEX)
else:
screenshot = html_screenshot(extractable)
except Exception as e:
logger.error(f'Failed to extract screenshot from: {url}', exc_info=e)
@ -1671,8 +1722,13 @@ async def generate_archive_screenshot(archive_id: int) -> pathlib.Path:
logger.debug(f'Generating screenshot locally for Archive {archive_id}')
singlefile_contents = singlefile_path.read_bytes()
if is_compressed_singlefile(singlefile_contents):
singlefile_contents = get_compressed_singlefile_index(singlefile_contents)
screenshot_bytes = html_screenshot(singlefile_contents)
# Extract the whole ZIP so the page's relative resources (images, fonts) render.
with tempfile.TemporaryDirectory(prefix='wrolpi-singlefile-screenshot-') as tmp_dir:
with zipfile.ZipFile(io.BytesIO(singlefile_contents)) as zip_:
zip_.extractall(tmp_dir)
screenshot_bytes = html_file_screenshot(pathlib.Path(tmp_dir) / COMPRESSED_SINGLEFILE_INDEX)
else:
screenshot_bytes = html_screenshot(singlefile_contents)
if not screenshot_bytes:
raise RuntimeError(f'Failed to generate screenshot for Archive {archive_id}')

View file

@ -5,6 +5,7 @@ isolation. None of them use async_client or test_download_manager — that's th
whole point of the refactor.
"""
import asyncio
import pathlib
import pytest
@ -98,6 +99,115 @@ async def test_execute_cancels_via_ctx(test_session, test_directory, monkeypatch
assert 'cancel' in (result.error or '').lower()
def make_process_runner_recorder(singlefile: bytes, compressed: bytes = None):
"""Stub Downloader.process_runner: record the call, write the singlefile to the output file
(the last argument of the command, like single-file does), return a successful CommandResult.
Capture runs (no --compress-content) write `singlefile`; conversion runs write `compressed`
(or nothing, when compressed is None, to simulate a failed conversion)."""
from wrolpi.cmd import CommandResult
calls = []
async def process_runner(download, cmd, cwd, **kwargs):
calls.append(dict(cmd=cmd, cwd=cwd, **kwargs))
if '--compress-content' not in cmd:
pathlib.Path(cmd[-1]).write_bytes(singlefile)
elif compressed is not None:
pathlib.Path(cmd[-1]).write_bytes(compressed)
return CommandResult(return_code=0, cancelled=False, stdout=b'', stderr=b'', elapsed=1)
return process_runner, calls
@pytest.mark.asyncio
async def test_do_singlefile_uses_deno(test_session, test_directory, monkeypatch, compressed_singlefile_factory):
"""single-file is run under Deno (it is designed for it; under node it cannot reach the
browser CDP on IPv6-enabled hosts and never exits). The page is captured uncompressed,
then converted to a compressed (SingleFileZ) file with a second local single-file run."""
import modules.archive
singlefile = b'<html><!--\n Page saved with SingleFile \n url: https://example.com \n--></html>'
compressed = compressed_singlefile_factory()
process_runner, calls = make_process_runner_recorder(singlefile, compressed)
monkeypatch.setattr(modules.archive, 'DENO_BIN', '/usr/local/bin/deno')
monkeypatch.setattr(modules.archive, 'SINGLE_FILE_DENO_SCRIPT',
'/usr/local/lib/node_modules/single-file-cli/single-file')
monkeypatch.setattr(modules.archive, 'CHROMIUM', '/usr/bin/chromium')
monkeypatch.setattr(archive_downloader, 'process_runner', process_runner)
prepared = PreparedArchive(url='https://example.com', destination=None,
settings={'compress_singlefile': True})
result, page_html = await archive_downloader.do_singlefile(prepared, make_test_ctx())
# The compressed file is stored; the uncompressed page is used for readability/screenshot.
assert result == compressed
assert page_html == singlefile
capture, convert = calls
cmd = capture['cmd']
assert cmd[2:9] == ('/usr/local/bin/deno', 'run', '--node-modules-dir=manual',
'--allow-read', '--allow-write', '--allow-net', '--allow-env')
assert '/usr/local/lib/node_modules/single-file-cli/single-file' in cmd
# The capture is always uncompressed.
assert '--compress-content' not in cmd
# The singlefile is written to a file; Deno >= 2.3 truncates large --dump-content output.
assert '--dump-content' not in cmd
assert cmd[-2] == 'https://example.com'
assert cmd[-1].endswith('page.html')
# The browser single-file leaves behind is reaped with the process group.
assert capture['start_new_session'] is True
# The browser runs via the stderr-discarding wrapper (Deno >= 2.3 kills it otherwise).
wrapper = cmd[cmd.index('--browser-executable-path') + 1]
assert wrapper.endswith('scripts/singlefile_browser_wrapper.sh')
assert capture['env']['WROLPI_BROWSER'] == '/usr/bin/chromium'
# The conversion is a local (file://) operation; the page is not fetched again.
cmd = convert['cmd']
assert '--compress-content' in cmd
assert cmd[-2].startswith('file://') and cmd[-2].endswith('page.html')
assert cmd[-1].endswith('compressed.html')
# Without the compress setting there is one run, and the page is stored as-is.
calls.clear()
prepared = PreparedArchive(url='https://example.com', destination=None, settings={})
result, page_html = await archive_downloader.do_singlefile(prepared, make_test_ctx())
assert result == page_html == singlefile
assert len(calls) == 1
# When the compression run fails, the uncompressed singlefile is stored instead.
process_runner, calls = make_process_runner_recorder(singlefile, compressed=None) # Conversion writes nothing.
monkeypatch.setattr(archive_downloader, 'process_runner', process_runner)
prepared = PreparedArchive(url='https://example.com', destination=None,
settings={'compress_singlefile': True})
result, page_html = await archive_downloader.do_singlefile(prepared, make_test_ctx())
assert len(calls) == 2 # The conversion was attempted.
assert result == page_html == singlefile
# A page that has not finished archiving in ten minutes is hung; the timeout reaps it.
assert archive_downloader.timeout == 10 * 60
@pytest.mark.asyncio
async def test_do_singlefile_node_fallback(test_session, test_directory, monkeypatch):
"""Without Deno, single-file runs under node with the IPv4-fallback fix."""
import modules.archive
singlefile = b'<html><!--\n Page saved with SingleFile \n url: https://example.com \n--></html>'
process_runner, calls = make_process_runner_recorder(singlefile)
monkeypatch.setattr(modules.archive, 'DENO_BIN', None)
monkeypatch.setattr(modules.archive, 'SINGLE_FILE_DENO_SCRIPT', None)
monkeypatch.setattr(modules.archive, 'SINGLE_FILE_BIN', '/usr/local/bin/single-file')
monkeypatch.setattr(modules.archive, 'CHROMIUM', '/usr/bin/chromium')
monkeypatch.setattr(archive_downloader, 'process_runner', process_runner)
prepared = PreparedArchive(url='https://example.com', destination=None, settings={})
await archive_downloader.do_singlefile(prepared, make_test_ctx())
call, = calls
assert call['cmd'][2] == '/usr/local/bin/single-file'
# node 18 has no IPv4 fallback when "localhost" resolves to ::1 first.
assert call['env']['NODE_OPTIONS'] == '--enable-network-family-autoselection'
assert call['start_new_session'] is True
@pytest.mark.asyncio
async def test_finalize_adds_tags(async_client, test_session, test_directory, tag_factory):
"""finalize_download applies download.tag_names to the registered Archive.

View file

@ -4,6 +4,7 @@ A compressed singlefile is a self-extracting HTML file which is also a valid ZIP
uncompressed page as index.html. Only the singlefile .html is compressed; readability files are
always written uncompressed.
"""
import base64
import pathlib
import zipfile
@ -16,6 +17,7 @@ from modules.archive.lib import (
is_compressed_singlefile,
get_compressed_singlefile_index,
get_url_from_singlefile,
inline_compressed_singlefile_resources,
is_singlefile_file,
write_archive_files,
)
@ -26,8 +28,9 @@ from wrolpi.files.models import FileGroup
from wrolpi.schema import DownloadRequest
def test_is_compressed_singlefile(compressed_singlefile_factory, singlefile_contents_factory):
compressed = compressed_singlefile_factory()
def test_compressed_singlefile_helpers(compressed_singlefile_factory, singlefile_contents_factory):
"""Compressed singlefiles are detected, and their page/URL can be extracted."""
compressed = compressed_singlefile_factory(url='https://wrolpi.org/some-article')
assert is_compressed_singlefile(compressed) is True
# A regular singlefile is not compressed.
@ -40,10 +43,7 @@ def test_is_compressed_singlefile(compressed_singlefile_factory, singlefile_cont
assert b'test compressed singlefile' in index
assert b'<title>compressed title</title>' in index
def test_get_url_from_compressed_singlefile(compressed_singlefile_factory):
"""The URL can be extracted from the plain-text prelude despite the binary ZIP tail."""
compressed = compressed_singlefile_factory(url='https://wrolpi.org/some-article')
# The URL can be extracted from the plain-text prelude despite the binary ZIP tail.
assert get_url_from_singlefile(compressed) == 'https://wrolpi.org/some-article'
@ -71,42 +71,80 @@ def test_compressed_singlefile_mimetype(make_files_structure, compressed_singlef
assert get_mimetype(path) == 'text/html'
def find_singlefile_path(written):
return next(i for i in written.paths if i.suffix == '.html' and '.readability' not in i.name)
def test_write_archive_files_compressed(test_directory, test_session, image_bytes_factory,
compressed_singlefile_factory):
"""The compressed singlefile is written verbatim (prettifying would corrupt the ZIP);
readability files are written uncompressed."""
readability files are written uncompressed, with their ZIP image references inlined."""
compressed = compressed_singlefile_factory()
readability = dict(content='<html>readability content</html>', textContent='readability text', title='a title')
readability = dict(content='<html><img src="images/0.png">readability content</html>',
textContent='readability text', title='a title')
destination = test_directory / 'archive/example.com'
destination.mkdir(parents=True)
written = write_archive_files('https://example.com', compressed, readability, image_bytes_factory(),
destination=destination)
singlefile_path = next(i for i in written.paths if i.suffix == '.html' and '.readability' not in i.name)
singlefile_path = find_singlefile_path(written)
# The file on disk is unchanged, and still a valid ZIP.
assert singlefile_path.read_bytes() == compressed
assert zipfile.is_zipfile(singlefile_path)
# Readability files are plain text, not compressed.
# Readability files are plain text, not compressed; their ZIP image references are inlined.
readability_path = next(i for i in written.paths if i.name.endswith('.readability.html'))
assert 'readability content' in readability_path.read_text()
readability_text = readability_path.read_text()
assert 'readability content' in readability_text
assert 'data:image/png;base64,' in readability_text
assert 'src="images/0.png"' not in readability_text
readability_txt_path = next(i for i in written.paths if i.name.endswith('.readability.txt'))
assert 'readability text' in readability_txt_path.read_text()
def test_write_archive_files_compressed_title_fallback(test_directory, test_session, compressed_singlefile_factory):
"""Without a readability title, the title comes from the ZIP's index.html."""
# Without a readability title, the title comes from the ZIP's index.html.
compressed = compressed_singlefile_factory(title='the fallback title')
destination = test_directory / 'archive/example.com'
destination.mkdir(parents=True)
written = write_archive_files('https://example.com', compressed, None, None, destination=destination)
singlefile_path = next(i for i in written.paths if i.suffix == '.html' and '.readability' not in i.name)
singlefile_path = find_singlefile_path(written)
assert 'the fallback title' in singlefile_path.name
assert singlefile_path.read_bytes() == compressed
# A singlefile marked compressed (<html data-sfz) whose ZIP is unreadable (e.g. truncated) is
# stored verbatim; prettifying would destroy whatever remains.
broken = b'<!DOCTYPE html> <html data-sfz><!--\n Page saved with SingleFile \n' \
b' url: https://example.com \n--><body hidden></body></html>' \
b'PK\x03\x04truncated zip data without a central directory'
written = write_archive_files('https://example.com', broken, None, None, destination=destination)
assert find_singlefile_path(written).read_bytes() == broken
def test_inline_compressed_singlefile_resources(compressed_singlefile_factory):
"""Readability extracted from a compressed singlefile references images by relative ZIP paths;
they are inlined as data URIs so the readability file is self-contained.
Relative and absolutized ZIP paths are inlined; data/external URLs and unknown paths are
left alone. readability-extractor absolutizes relative srcs against the page URL."""
compressed = compressed_singlefile_factory()
expected_data_uri = 'data:image/png;base64,' + base64.b64encode(b'\x89PNG fake image bytes').decode()
content = '<html><body>' \
'<img src="images/0.png" srcset="images/0.png 1x">' \
'<img src="./images/0.png">' \
'<img src="../images/0.png">' \
'<img src="https://example.com/images/0.png">' \
'<img src="https://other.com/remote.png">' \
'<img src="data:image/png;base64,QUJD">' \
'<img src="images/does-not-exist.png">' \
'<p>article text</p></body></html>'
inlined = inline_compressed_singlefile_resources(content, compressed, 'https://example.com/page')
assert inlined.count(expected_data_uri) == 3 # The relative, ./-relative, and absolutized forms.
assert 'srcset' not in inlined
# A path outside the ZIP directory must not match a ZIP entry.
assert '../images/0.png' in inlined
assert 'https://other.com/remote.png' in inlined
assert 'data:image/png;base64,QUJD' in inlined
assert 'images/does-not-exist.png' in inlined
@pytest.mark.asyncio
async def test_execute_download_compressed(test_session, test_directory, monkeypatch, compressed_singlefile_factory):
@ -158,8 +196,11 @@ async def test_model_archive_compressed(async_client, test_session, test_directo
assert archive.collection.name == 'example.com'
def test_download_request_compress_singlefile():
"""compress_singlefile=True survives DownloadRequest settings validation."""
def test_compress_singlefile_setting_flow(test_session):
"""compress_singlefile survives DownloadRequest settings validation, and the RSSDownloader
passes it on to the child archive downloads."""
from wrolpi.downloader import rss_downloader, ExecutedRSS
request = DownloadRequest(
urls=['https://example.com'],
downloader='archive',
@ -167,11 +208,6 @@ def test_download_request_compress_singlefile():
)
assert request.settings['compress_singlefile'] is True
def test_rss_forwards_compress_singlefile(test_session):
"""RSSDownloader passes compress_singlefile on to the child archive downloads."""
from wrolpi.downloader import rss_downloader, ExecutedRSS
download = Download(
url='https://example.com/feed',
downloader='rss',

View file

@ -28,7 +28,7 @@ sed -i 's/port =.*/port = 5432/' /etc/postgresql/15/main/postgresql.conf
npm i -g serve@12.0.1 single-file-cli@2.0.73 readability-extractor@0.0.6
# Install Deno runtime.
DENO_VERSION="v2.2.4"
DENO_VERSION="v2.8.3"
curl -fsSL "https://github.com/denoland/deno/releases/download/${DENO_VERSION}/deno-aarch64-unknown-linux-gnu.zip" -o /tmp/deno.zip
unzip /tmp/deno.zip -d /usr/local/bin/
chmod +x /usr/local/bin/deno

View file

@ -16,6 +16,26 @@ npm -v
# Install serve, and archiving tools.
single-file --version || sudo npm i -g serve@12.0.1 single-file-cli@2.0.73 readability-extractor@0.0.6
# Install Deno runtime; single-file runs under it.
command -v deno || {
DENO_VERSION="v2.8.3"
ARCH=$(uname -m)
if [ "$ARCH" = "aarch64" ]; then
DENO_ARCH="aarch64-unknown-linux-gnu"
DENO_SHA256="d4589cc1ffcbf1995c92a0127d932aaf832ac70cfdcc6d5b7bf38043cf303575"
else
DENO_ARCH="x86_64-unknown-linux-gnu"
DENO_SHA256="30455b845ffa6082209c3590269c910ad3b7efdf28c9879afd4006c47ae54197"
fi
curl -fsSL "https://github.com/denoland/deno/releases/download/${DENO_VERSION}/deno-${DENO_ARCH}.zip" -o /tmp/deno.zip
# Assert the hash to avoid malicious or invalid files.
echo "${DENO_SHA256} /tmp/deno.zip" | sha256sum -c -
unzip -o /tmp/deno.zip -d /usr/local/bin/
chmod +x /usr/local/bin/deno
rm /tmp/deno.zip
}
deno --version
# Build React app in background job.
cd /opt/wrolpi/app || exit 5
npm install || npm install || npm install || npm install # try install multiple times :(

View file

@ -16,6 +16,26 @@ npm -v
# Install serve, and archiving tools.
single-file --version || sudo npm i -g serve@12.0.1 single-file-cli@2.0.73 readability-extractor@0.0.6
# Install Deno runtime; single-file runs under it.
command -v deno || {
DENO_VERSION="v2.8.3"
ARCH=$(uname -m)
if [ "$ARCH" = "aarch64" ]; then
DENO_ARCH="aarch64-unknown-linux-gnu"
DENO_SHA256="d4589cc1ffcbf1995c92a0127d932aaf832ac70cfdcc6d5b7bf38043cf303575"
else
DENO_ARCH="x86_64-unknown-linux-gnu"
DENO_SHA256="30455b845ffa6082209c3590269c910ad3b7efdf28c9879afd4006c47ae54197"
fi
curl -fsSL "https://github.com/denoland/deno/releases/download/${DENO_VERSION}/deno-${DENO_ARCH}.zip" -o /tmp/deno.zip
# Assert the hash to avoid malicious or invalid files.
echo "${DENO_SHA256} /tmp/deno.zip" | sha256sum -c -
unzip -o /tmp/deno.zip -d /usr/local/bin/
chmod +x /usr/local/bin/deno
rm /tmp/deno.zip
}
deno --version
# Build React app in background job.
cd /opt/wrolpi/app || exit 5
npm install || npm install || npm install || npm install # try install multiple times :(

View file

@ -0,0 +1,8 @@
#!/bin/sh
# Runs the browser for single-file with stderr discarded.
#
# single-file spawns the browser with piped stderr that it never reads; under Deno >= 2.3 this
# kills the browser during startup (the CDP port never opens and single-file fails with
# "tcp connect error: Connection refused"). WROLPi passes this wrapper as the
# --browser-executable-path and provides the real browser via WROLPI_BROWSER.
exec "${WROLPI_BROWSER}" "$@" 2>/dev/null

View file

@ -44,7 +44,7 @@ npm install || npm install || npm install || npm install # try install multiple
# Install/upgrade Deno runtime.
upgrade_deno() {
DENO_VERSION="v2.2.4"
DENO_VERSION="v2.8.3"
ARCH=$(uname -m)
if [ "$ARCH" = "aarch64" ]; then
DENO_ARCH="aarch64-unknown-linux-gnu"

View file

@ -5,6 +5,7 @@ import os
import pathlib
import shlex
import shutil
import signal
import tempfile
from asyncio import CancelledError
from pathlib import Path
@ -75,6 +76,28 @@ SINGLE_FILE_BIN = which('single-file',
'/usr/bin/single-file', # rpi os
'/usr/local/bin/single-file', # debian
)
DENO_BIN = which('deno', '/usr/local/bin/deno')
def _find_single_file_deno_script() -> Optional[Path]:
"""Find the Deno entry script of the single-file-cli package.
npm's `single-file` bin is a symlink to the package's single-file-node.js; the Deno script
(`single-file`, shebang `deno run`) lives next to it. single-file-cli is designed for Deno —
under node 18 it cannot reach the browser CDP on IPv6-enabled hosts and never exits."""
if not SINGLE_FILE_BIN:
return None
script = SINGLE_FILE_BIN.resolve().parent / 'single-file'
try:
with script.open('rb') as fh:
if b'deno run' in fh.readline():
return script
except OSError:
pass
return None
SINGLE_FILE_DENO_SCRIPT = _find_single_file_deno_script()
CHROMIUM = which('chromium-browser', 'chromium',
'/usr/bin/chromium-browser', # rpi os
'/usr/bin/chromium', # debian
@ -160,7 +183,8 @@ TESTING_RUN_COMMAND_RESULT = None
async def run_command(cmd: tuple[str | pathlib.Path, ...], cwd: pathlib.Path | str = None,
timeout: int = 600, log_command: bool = True,
stdout_callback: callable = None, env: dict = None) -> CommandResult:
stdout_callback: callable = None, env: dict = None,
start_new_session: bool = False) -> CommandResult:
"""Run a shell command, return the results (stdout/stderr/return code).
When stdout_callback is provided, stdout is piped and each line is passed to the callback
@ -169,6 +193,9 @@ async def run_command(cmd: tuple[str | pathlib.Path, ...], cwd: pathlib.Path | s
:param log_command: Enable debug logging.
:param stdout_callback: Called with each decoded stdout line (str). May be None.
:param env: Environment variables for the subprocess. If None, inherits the current environment.
:param start_new_session: Run the command in its own session/process group; when it finishes
(or is killed by timeout/cancel), the whole group is killed. Use for commands that may
leave children behind (e.g. single-file's browser).
"""
if not isinstance(cmd, (list, tuple)):
raise RuntimeError('Command must be a list or tuple')
@ -192,6 +219,7 @@ async def run_command(cmd: tuple[str | pathlib.Path, ...], cwd: pathlib.Path | s
stdout_file = None
reader_task = None
stdout_buf = None
pid = None
if streaming:
stdout_arg = asyncio.subprocess.PIPE
@ -208,6 +236,7 @@ async def run_command(cmd: tuple[str | pathlib.Path, ...], cwd: pathlib.Path | s
stderr=stderr_fh,
cwd=cwd,
env=env,
start_new_session=start_new_session,
)
pid = proc.pid
@ -297,5 +326,15 @@ async def run_command(cmd: tuple[str | pathlib.Path, ...], cwd: pathlib.Path | s
pid=pid,
)
finally:
if start_new_session and pid:
# The command was its own session/group leader; kill anything it left behind
# (e.g. the browser single-file spawns but fails to close).
try:
os.killpg(pid, signal.SIGKILL)
logger.info(f'run_command: killed lingering process group {pid}')
except ProcessLookupError:
pass # Nothing left behind; the common case.
except PermissionError as e:
logger.error(f'run_command: failed to kill process group {pid}', exc_info=e)
if stdout_fh:
stdout_fh.close()

View file

@ -300,6 +300,7 @@ __all__ = [
'get_title_from_html',
'get_warn_once',
'get_wrolpi_config',
'html_file_screenshot',
'html_screenshot',
'insert_parameter',
'iterify',
@ -2542,8 +2543,10 @@ def format_html_file(file: pathlib.Path):
replace_file(file, pretty)
def html_screenshot(html: bytes | str) -> bytes:
"""Return a PNG screenshot of the provided HTML."""
def html_file_screenshot(path: pathlib.Path | str) -> bytes:
"""Return a PNG screenshot of the HTML file at `path`.
Relative resources (images, fonts) next to the file are rendered too."""
from wrolpi import cmd # Avoid circular import.
# Set Chromium to headless. Use a wide window size so that screenshot will be the "desktop" version of the page.
@ -2556,15 +2559,19 @@ def html_screenshot(html: bytes | str) -> bytes:
# linux/aarch64 (Raspberry Pi).
service = webdriver.ChromeService(executable_path=str(cmd.CHROMEDRIVER_BIN)) if cmd.CHROMEDRIVER_BIN else None
with webdriver.Chrome(options=options, service=service) as driver:
driver.get(f'file://{path}')
driver.set_window_size(1280, 720)
screenshot = driver.get_screenshot_as_png()
return screenshot
def html_screenshot(html: bytes | str) -> bytes:
"""Return a PNG screenshot of the provided HTML."""
with tempfile.NamedTemporaryFile('wb', suffix='.html') as fh:
fh.write(html.encode() if isinstance(html, str) else html)
fh.flush()
with webdriver.Chrome(options=options, service=service) as driver:
driver.get(f'file://{fh.name}')
driver.set_window_size(1280, 720)
screenshot = driver.get_screenshot_as_png()
return screenshot
return html_file_screenshot(fh.name)
def chain(iterable: Union[List, Tuple], length: int) -> List:

View file

@ -481,6 +481,7 @@ class Downloader:
async def process_runner(self, download: Download, cmd: Tuple[str | pathlib.Path, ...], cwd: pathlib.Path,
timeout: int = None, debug: bool = True,
stdout_callback: callable = None, env: dict = None,
start_new_session: bool = False,
ctx: 'DownloadContext' = None) -> CommandResult:
"""
Run a subprocess using the provided arguments. This process can be killed by the Download Manager.
@ -502,7 +503,8 @@ class Downloader:
elif timeout is None:
timeout = self.timeout
coro = ctx.run_command(cmd, cwd=cwd, timeout=timeout, log_command=debug,
stdout_callback=stdout_callback, env=env)
stdout_callback=stdout_callback, env=env,
start_new_session=start_new_session)
result = await self.cancel_wrapper(coro, download, ctx=ctx)
if __debug__ and logger.isEnabledFor(TRACE_LEVEL):

View file

@ -53,6 +53,33 @@ async def test_run_command_timeout(test_directory):
assert result.elapsed >= 2
async def test_run_command_start_new_session_reaps_children(test_directory):
"""Children left behind by the command are killed with its process group.
single-file does not close the browser it spawns; the process group kill reaps it."""
script = test_directory / 'leaky.sh'
# The grandchild sleeps long after the script exits.
script.write_text('#!/bin/sh\nsleep 60 &\necho $! > leaked.pid\n')
result = await cmd.run_command(('sh', 'leaky.sh'), cwd=test_directory, timeout=10, start_new_session=True)
assert result.return_code == 0
leaked_pid = int((test_directory / 'leaked.pid').read_text().strip())
# The kill is delivered asynchronously; the killed process may linger as a zombie briefly.
for _ in range(20):
if not cmd.pid_is_running(leaked_pid):
break
await asyncio.sleep(0.1)
assert not cmd.pid_is_running(leaked_pid), 'The leaked child should have been killed with the process group'
# Without start_new_session the child survives (and must be cleaned up by the test).
result = await cmd.run_command(('sh', 'leaky.sh'), cwd=test_directory, timeout=10)
assert result.return_code == 0
leaked_pid = int((test_directory / 'leaked.pid').read_text().strip())
assert cmd.pid_is_running(leaked_pid)
os.kill(leaked_pid, 9)
async def test_run_command_cancel(test_directory):
"""Run a command, cancel it and test that it was cancelled."""
task = asyncio.create_task(cmd.run_command(('sleep', '10')))

View file

@ -1 +1 @@
0.24.0-beta
0.24.1-beta