Skip to content
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
7 changes: 6 additions & 1 deletion .dockerignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,9 @@ tests
Dockerfile
.pre-commit-config.yaml
Makefile
install.sh
install.sh
install-docker.sh
CONTRIBUTING.md
CONTRIBUTING.ru.md
README.ru.md
openrot.spec
5 changes: 2 additions & 3 deletions .github/ISSUE_TEMPLATE/bug_report.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,8 @@ What breaks? One or two sentences.

## Logs and config

Run `openrot doctor` and paste the output (add `openrot status --json` too if
the issue is about the active level). Paste `config.yaml` as well, with any
secrets removed.
Run `openrot status --json` and paste the output. Paste `config.yaml` as well,
with any secrets removed.

## Environment

Expand Down
2 changes: 0 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,12 @@ repos:
entry: poetry run ruff format
language: system
types: [python]
pass_filenames: false

- id: ruff-lint
name: Check with Ruff
entry: poetry run ruff check
language: system
types: [python]
pass_filenames: false
always_run: true

- id: mypy
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

![Python 3.14+](https://img.shields.io/badge/Python-3.14%2B-blue)
![License: MIT](https://img.shields.io/badge/License-MIT-brightgreen)
![Coverage](https://img.shields.io/badge/Coverage-%3E85%25-brightgreen)
![Coverage](https://img.shields.io/badge/Coverage-%3E75%25-brightgreen)
![Built for opencode](https://img.shields.io/badge/Built%20for-opencode-7c3aed)

**English** · [Русский](README.ru.md)
Expand Down
12 changes: 12 additions & 0 deletions openrot/core/bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,18 @@ def do_POST(self) -> None: # noqa: D102
def do_OPTIONS(self) -> None: # noqa: D102
self._handle("OPTIONS")

def do_PUT(self) -> None: # noqa: D102
self._handle("PUT")

def do_DELETE(self) -> None: # noqa: D102
self._handle("DELETE")

def do_PATCH(self) -> None: # noqa: D102
self._handle("PATCH")

def do_HEAD(self) -> None: # noqa: D102
self._handle("HEAD")

def log_message(self, fmt: str, *args: object) -> None:
"""Log a request line to the events log."""
events.info("bridge %s", fmt % args)
Expand Down
6 changes: 5 additions & 1 deletion openrot/core/proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,10 @@ def stop_proxy(pid: int | None = None) -> bool:
return False
try:
os.kill(pid, signal.SIGTERM)
return True
except OSError:
return False
for _ in range(50):
if not is_running(pid):
return True
time.sleep(0.1)
return True

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

issue (bug_risk): After the 5-second polling loop, stop_proxy returns True even when is_running(pid) is still true, so callers proceed as though the proxy terminated and can start a replacement process while the old process still owns the proxy port.

Triggers: When the proxy ignores or delays SIGTERM for more than five seconds.

Suggested fix: Return False after the timeout, or perform an escalation and verify termination before returning True.

Suggested change
return True
return False

16 changes: 5 additions & 11 deletions openrot/core/singbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,21 +172,15 @@ def _free_port() -> int:
return s.getsockname()[1]


def _port_open(host: str, port: int) -> bool:
try:
with socket.create_connection((host, port), timeout=0.2):
return True
except OSError:
return False


def _wait_for_port(host: str, port: int, timeout: float, step: float = 0.05) -> bool:
"""Poll until `host:port` accepts connections or `timeout` elapses."""
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if _port_open(host, port):
return True
time.sleep(step)
try:
with socket.create_connection((host, port), timeout=0.2):
return True
except OSError:
time.sleep(step)
return False


Expand Down
2 changes: 1 addition & 1 deletion openrot/self_update.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ def _do_update(
progress_fn("extracting", 0, 1)

with tarfile.open(archive_path, "r:gz") as tar:
tar.extractall(tmp) # noqa: S202
tar.extractall(tmp, filter="data")

src_dir = Path(tmp)
inner = src_dir / "openrot"
Expand Down
Empty file added tests/__init__.py
Empty file.
Empty file added tests/integration/__init__.py
Empty file.
Empty file added tests/unit/__init__.py
Empty file.
Empty file added tests/unit/cli/__init__.py
Empty file.
Empty file added tests/unit/core/__init__.py
Empty file.
55 changes: 55 additions & 0 deletions tests/unit/core/test_cascade.py
Original file line number Diff line number Diff line change
Expand Up @@ -516,3 +516,58 @@ def test_commit_health() -> None:
reached, fails = cascade._commit_health(conf, "n1", True)
assert reached is False and fails == 0
assert node.fails == 0


def test_warp_health_loop_falls_back_to_node(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""When WARP drops, the loop stops the proxy and starts the node chain."""
call_count = {"n": 0}

def fake_sleep(s: float) -> None:
call_count["n"] += 1

def fake_load() -> Config:
return Config(update_interval=0, health_interval=1)

def fake_is_connected() -> bool:
return False

_patch_events(monkeypatch)
monkeypatch.setattr(cascade.time, "sleep", fake_sleep)
monkeypatch.setattr(cascade.cfg, "load_config", fake_load)
monkeypatch.setattr(cascade.warp, "is_connected", fake_is_connected)
monkeypatch.setattr(cascade.proxy, "stop_proxy", lambda: None)
monkeypatch.setattr(cascade, "start_node", lambda fg: None)

cascade.warp_health_loop()

assert call_count["n"] == 1


def test_warp_health_loop_continues_while_connected(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Loop keeps running while WARP is connected; exits via SystemExit."""
call_count = {"n": 0}

def fake_sleep(s: float) -> None:
call_count["n"] += 1
if call_count["n"] >= 2:
raise SystemExit(0)

def fake_load() -> Config:
return Config(update_interval=0, health_interval=1)

def fake_is_connected() -> bool:
return True

_patch_events(monkeypatch)
monkeypatch.setattr(cascade.time, "sleep", fake_sleep)
monkeypatch.setattr(cascade.cfg, "load_config", fake_load)
monkeypatch.setattr(cascade.warp, "is_connected", fake_is_connected)

with pytest.raises(SystemExit):
cascade.warp_health_loop()

assert call_count["n"] == 2
Empty file.
194 changes: 194 additions & 0 deletions tests/unit/test_self_update.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
from __future__ import annotations

import platform
from pathlib import Path
from unittest.mock import MagicMock

import httpx
import pytest

from openrot import self_update as su


class TestVersionTuple:
def test_strips_v_prefix(self) -> None:
assert su._version_tuple("v1.2.3") == (1, 2, 3)

def test_without_v(self) -> None:
assert su._version_tuple("0.1.1") == (0, 1, 1)

def test_truncates_on_non_int(self) -> None:
assert su._version_tuple("1.2.3-beta") == (1, 2)

def test_empty_string(self) -> None:
assert su._version_tuple("") == ()

def test_single_number(self) -> None:
assert su._version_tuple("v5") == (5,)


class TestCurrentOs:
def test_darwin(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(platform, "system", lambda: "Darwin")
assert su._current_os() == "macos"

def test_linux(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(platform, "system", lambda: "Linux")
assert su._current_os() == "linux"

def test_unsupported(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(platform, "system", lambda: "Windows")
with pytest.raises(RuntimeError, match="unsupported OS"):
su._current_os()


class TestCurrentArch:
def test_x86_64(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(platform, "machine", lambda: "x86_64")
assert su._current_arch() == "x86_64"

def test_amd64(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(platform, "machine", lambda: "amd64")
assert su._current_arch() == "x86_64"

def test_arm64(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(platform, "machine", lambda: "arm64")
assert su._current_arch() == "aarch64"

def test_aarch64(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(platform, "machine", lambda: "aarch64")
assert su._current_arch() == "aarch64"

def test_unsupported(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(platform, "machine", lambda: "mips")
with pytest.raises(RuntimeError, match="unsupported arch"):
su._current_arch()


class TestBinDir:
def test_returns_parent_of_executable(self) -> None:
result = su._bin_dir()
assert result.is_dir()


class TestCheckForUpdate:
def test_up_to_date(self) -> None:
client = MagicMock(spec=httpx.Client)
resp = MagicMock()
resp.json.return_value = {"tag_name": "v0.0.0"}
client.get.return_value = resp
result = su.check_for_update(client)
assert result.updated is False
assert "already up to date" in result.message

def test_update_available(self) -> None:
client = MagicMock(spec=httpx.Client)
resp = MagicMock()
resp.json.return_value = {"tag_name": "v99.0.0"}
client.get.return_value = resp
result = su.check_for_update(client)
assert result.updated is False
assert "update available" in result.message
assert result.latest == "99.0.0"

def test_network_error(self) -> None:
client = MagicMock(spec=httpx.Client)
client.get.side_effect = httpx.ConnectError("timeout")
result = su.check_for_update(client)
assert result.updated is False
assert "failed to check" in result.message


class TestPerformUpdate:
def test_already_up_to_date(self) -> None:
client = MagicMock(spec=httpx.Client)
resp = MagicMock()
resp.json.return_value = {"tag_name": "v0.0.0"}
client.get.return_value = resp
result = su.perform_update(client)
assert result.updated is False

def test_download_archive(self, tmp_path: Path) -> None:
dest = tmp_path / "test.tar.gz"
client = MagicMock(spec=httpx.Client)
stream_ctx = MagicMock()
stream_ctx.__enter__ = MagicMock(return_value=stream_ctx)
stream_ctx.__exit__ = MagicMock(return_value=False)
stream_ctx.raise_for_status = MagicMock()
stream_ctx.headers = {"content-length": "100"}
stream_ctx.iter_bytes = MagicMock(return_value=iter([b"chunk1", b"chunk2"]))
client.stream.return_value = stream_ctx

su._download_archive(client, "http://example.com/test.tar.gz", dest, None)
assert dest.exists()


class TestInstallExtracted:
def test_missing_binary(self, tmp_path: Path) -> None:
src = tmp_path / "src"
src.mkdir()
dest = tmp_path / "dest"
dest.mkdir()
err = su._install_extracted(src, dest, "1.0.0")
assert err is not None
assert "did not contain" in err

def test_copies_binary(self, tmp_path: Path) -> None:
src = tmp_path / "src"
src.mkdir()
(src / "openrot").write_text("#!/bin/sh\necho ok")
dest = tmp_path / "dest"
dest.mkdir()
err = su._install_extracted(src, dest, "1.0.0")
assert err is None
assert (dest / "openrot").exists()
assert (dest / "openrot").read_text() == "#!/bin/sh\necho ok"

def test_copies_internal_dir(self, tmp_path: Path) -> None:
src = tmp_path / "src"
src.mkdir()
(src / "openrot").write_text("#!/bin/sh\necho ok")
internal = src / "_internal"
internal.mkdir()
(internal / "lib.py").write_text("x = 1")
dest = tmp_path / "dest"
dest.mkdir()
err = su._install_extracted(src, dest, "1.0.0")
assert err is None
assert (dest / "_internal" / "lib.py").read_text() == "x = 1"

def test_removes_old_internal(self, tmp_path: Path) -> None:
src = tmp_path / "src"
src.mkdir()
(src / "openrot").write_text("new")
internal = src / "_internal"
internal.mkdir()
(internal / "new.py").write_text("new")
dest = tmp_path / "dest"
dest.mkdir()
old_internal = dest / "_internal"
old_internal.mkdir()
(old_internal / "old.py").write_text("old")
err = su._install_extracted(src, dest, "1.0.0")
assert err is None
assert not (dest / "_internal" / "old.py").exists()
assert (dest / "_internal" / "new.py").read_text() == "new"


class TestDoUpdate:
def test_up_to_date_returns_early(self) -> None:
client = MagicMock(spec=httpx.Client)
resp = MagicMock()
resp.json.return_value = {"tag_name": "v0.0.0"}
client.get.return_value = resp
result = su._do_update(client, None)
assert result.updated is False


class TestUpdateResult:
def test_fields(self) -> None:
r = su.UpdateResult(current="1.0.0", latest="2.0.0", updated=True, message="ok")
assert r.current == "1.0.0"
assert r.latest == "2.0.0"
assert r.updated is True
assert r.message == "ok"