Skip to content
This repository was archived by the owner on Nov 15, 2026. It is now read-only.
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
20 changes: 17 additions & 3 deletions docs/preview-notes.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,26 @@
# Modsim 2.0.0a3 preview
# Modsim 2.0.0a4 preview

Remote models and scenarios load directly from a site such as ModioHub:

```sh
uvx --prerelease allow modsim==2.0.0a4 --config https://example.org/device.tm.json \
--scenario https://example.org/device.sim.json --bind 127.0.0.1 --port 5020
```

HTTPS requests identify themselves as `modsim/<version>`, because some CDNs reject
the default Python agent. `--scenario` accepts an HTTPS URL; a remote scenario
cannot name a behavior script. This preview still pins modpoll-wot 0.2.0a4.

### Previous preview

#### Modsim 2.0.0a3


This preview pins modpoll-wot 0.2.0a4. A local TCP simulator can load a full
profile 0.2 TM with an audit plan or its independently derived public audit TM.
Tests seed the same known values and verify the public model exposes only the
selected read spans.

### Previous preview

#### Modsim 2.0.0a2

This candidate uses published modpoll-wot 0.2.0a2 and immutable modbus-models-v1
Expand Down
2 changes: 1 addition & 1 deletion modsim/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "2.0.0a3"
__version__ = "2.0.0a4"
16 changes: 12 additions & 4 deletions modsim/deployment.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from jsonschema import Draft7Validator # type: ignore[import-untyped]
from modpoll_wot.loading import load_document # type: ignore[import-untyped]

from .sources import local_path
from .sources import is_remote, local_path, remote_document


def obj(properties: dict, required: tuple = ()) -> dict:
Expand Down Expand Up @@ -68,15 +68,23 @@ def obj(properties: dict, required: tuple = ()) -> dict:


def document(path: str, schema: dict) -> dict:
source = Path(local_path(Path.cwd(), path))
value = load_document(source)
source: str | Path
if is_remote(path):
source = path
value = remote_document(path)
# Behavior scripts are local code; never resolve them from a download.
if isinstance(value, dict) and "script" in value:
raise ValueError(f"{path}: remote scenarios cannot reference scripts")
else:
source = Path(local_path(Path.cwd(), path))
value = load_document(source)
errors = sorted(
Draft7Validator(schema).iter_errors(value), key=lambda error: str(error.path)
)
if errors:
error = errors[0]
raise ValueError(f"{source}: {'/'.join(map(str, error.path))}: {error.message}")
return value # type: ignore[no-any-return]
return value


def apply_scenario(args: Any) -> None:
Expand Down
31 changes: 23 additions & 8 deletions modsim/sources.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
"""Bounded local JSON and HTTPS model loading."""
"""Bounded local JSON and HTTPS model and scenario loading."""

import tempfile
from pathlib import Path
from urllib.parse import urlparse
from urllib.request import urlopen
from urllib.request import Request, urlopen

from modpoll_wot.loading import MAX_BYTES, load_document # type: ignore[import-untyped]

from . import __version__

# Some CDNs reject the default Python-urllib agent; identify the tool instead.
USER_AGENT = f"modsim/{__version__}"


def is_remote(value: str) -> bool:
return bool(urlparse(value).scheme) and not Path(value).is_absolute()


def local_path(base: Path, value: str) -> str:
if urlparse(value).scheme and not Path(value).is_absolute():
Expand All @@ -15,23 +24,29 @@ def local_path(base: Path, value: str) -> str:


def model_document(source: str) -> dict:
url = urlparse(source)
if Path(source).is_absolute() or not url.scheme:
if not is_remote(source):
return load_document(source) # type: ignore[no-any-return]
return remote_document(source)


def remote_document(source: str) -> dict:
"""Load bounded JSON from an HTTPS URL with the shared loader's rules."""
url = urlparse(source)
if url.scheme != "https":
raise ValueError("model URLs must use HTTPS")
raise ValueError("model and scenario URLs must use HTTPS")
if url.hostname == "github.com":
parts = url.path.strip("/").split("/")
if len(parts) >= 5 and parts[2] == "blob":
source = "https://raw.githubusercontent.com/" + "/".join(
parts[:2] + parts[3:]
)
with urlopen(source, timeout=15) as response:
request = Request(source, headers={"User-Agent": USER_AGENT})
with urlopen(request, timeout=15) as response:
if urlparse(response.geturl()).scheme != "https":
raise ValueError("model redirect must use HTTPS")
raise ValueError("redirect must use HTTPS")
payload = response.read(MAX_BYTES + 1)
if len(payload) > MAX_BYTES:
raise ValueError(f"model exceeds {MAX_BYTES} bytes")
raise ValueError(f"document exceeds {MAX_BYTES} bytes")
# Reuse all bounded JSON parsing rules from the public shared loader.
with tempfile.TemporaryDirectory(prefix="modsim-model-") as directory:
path = Path(directory) / "model.json"
Expand Down
4 changes: 3 additions & 1 deletion modsim/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ def get_parser() -> argparse.ArgumentParser:
)
sources = parser.add_mutually_exclusive_group()
sources.add_argument("--config", help="Profile 0.2 TM/TD local path or HTTPS URL")
parser.add_argument("--scenario", help="Local scenario JSON for --config")
parser.add_argument(
"--scenario", help="Scenario JSON local path or HTTPS URL for --config"
)
parser.add_argument("--script", help="Local Python behavior for --config")
parser.add_argument(
"--allow-scripts",
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "modsim"
version = "2.0.0a3"
version = "2.0.0a4"
description = "A Simple Modbus TCP Device Simulator used for modpoll tool"
authors = [{ name = "Ying Shaodong", email = "helloysd@gmail.com" }]
readme = "README.md"
Expand Down
2 changes: 1 addition & 1 deletion tests/test_deployment.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ def geturl(self):
== "0.2"
)
assert (
request.call_args.args[0]
request.call_args.args[0].full_url
== "https://raw.githubusercontent.com/top-maker/modsim/v2/device.json"
)
with patch("modsim.sources.urlopen", return_value=Response(b'{"a":1,"a":2}')):
Expand Down
43 changes: 43 additions & 0 deletions tests/test_remote_sources.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
"""HTTPS model and scenario sources."""

from io import BytesIO
import json
from unittest.mock import patch

import pytest

from modsim import __version__, deployment, sources


class Response(BytesIO):
def __init__(self, payload, url="https://example.invalid/file.json"):
super().__init__(payload)
self.url = url

def geturl(self):
return self.url


def test_remote_documents_identify_modsim():
payload = json.dumps({"version": "1", "tick": 0.5}).encode()
with patch.object(sources, "urlopen", return_value=Response(payload)) as remote:
scenario = deployment.document(
"https://example.invalid/device.sim.json", deployment.SCENARIO
)
assert scenario == {"version": "1", "tick": 0.5}
request = remote.call_args.args[0]
assert request.full_url == "https://example.invalid/device.sim.json"
assert request.get_header("User-agent") == f"modsim/{__version__}"


def test_remote_scenarios_reject_scripts_and_plain_http():
payload = json.dumps({"version": "1", "script": "behavior.py"}).encode()
with patch.object(sources, "urlopen", return_value=Response(payload)):
with pytest.raises(ValueError, match="cannot reference scripts"):
deployment.document("https://example.invalid/s.json", deployment.SCENARIO)
with pytest.raises(ValueError, match="must use HTTPS"):
deployment.document("http://example.invalid/s.json", deployment.SCENARIO)
redirected = Response(b"{}", url="http://example.invalid/s.json")
with patch.object(sources, "urlopen", return_value=redirected):
with pytest.raises(ValueError, match="redirect must use HTTPS"):
sources.model_document("https://example.invalid/m.json")
2 changes: 1 addition & 1 deletion uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading