node-mantis 0.1.0__py3-none-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,125 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from dataclasses import dataclass
5
+ from typing import Literal
6
+ from urllib.error import HTTPError
7
+ from urllib.request import Request, urlopen
8
+
9
+ from ._async import blocking
10
+ from ._constants import NODEMANTIS_API_URL
11
+ from .browser import check_chrome
12
+ from .config import resolve_config
13
+
14
+ NodeMantisPreflightCheckName = Literal["service", "apiKey", "usage", "browser"]
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class NodeMantisPreflightCheck:
19
+ name: NodeMantisPreflightCheckName
20
+ ok: bool
21
+ message: str
22
+ skipped: bool = False
23
+ details: object | None = None
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class NodeMantisPreflightResult:
28
+ ok: bool
29
+ has_api_key: bool
30
+ checks: tuple[NodeMantisPreflightCheck, ...]
31
+
32
+
33
+ async def preflight(
34
+ *,
35
+ api_key: str | None = None,
36
+ check_browser_launch: bool = True,
37
+ timeout_seconds: float = 5,
38
+ ) -> NodeMantisPreflightResult:
39
+ resolved = resolve_config(api_key=api_key)
40
+ checks: list[NodeMantisPreflightCheck] = []
41
+
42
+ try:
43
+ details = await blocking(_get_json,"/health", timeout_seconds=timeout_seconds)
44
+ checks.append(NodeMantisPreflightCheck("service", True, "Hosted Node Mantis API is reachable.", details=details))
45
+ except Exception as exc: # noqa: BLE001 - diagnostic boundary.
46
+ checks.append(NodeMantisPreflightCheck("service", False, "Hosted Node Mantis API is not reachable.", details=str(exc)))
47
+
48
+ if not resolved.api_key:
49
+ checks.append(
50
+ NodeMantisPreflightCheck(
51
+ "apiKey",
52
+ False,
53
+ "Missing API key. Set api_key, NODEMANTIS_API_KEY, NODEMANTIS_AUTH_TOKEN, or configure a user key.",
54
+ )
55
+ )
56
+ checks.append(NodeMantisPreflightCheck("usage", True, "Skipped usage check because API key is missing.", skipped=True))
57
+ else:
58
+ checks.append(NodeMantisPreflightCheck("apiKey", True, "API key is configured."))
59
+ try:
60
+ details = await blocking(_get_json,
61
+ "/v2/usage",
62
+ api_key=resolved.api_key,
63
+ timeout_seconds=timeout_seconds,
64
+ )
65
+ balance = details.get("balanceUsd") if isinstance(details, dict) else None
66
+ has_balance = not isinstance(balance, (int, float)) or balance > 0
67
+ message = (
68
+ f"Account balance is ${balance:.4f}"
69
+ if isinstance(balance, (int, float))
70
+ else "Usage endpoint returned successfully."
71
+ )
72
+ checks.append(NodeMantisPreflightCheck("usage", has_balance, message, details=details))
73
+ except Exception as exc: # noqa: BLE001 - diagnostic boundary.
74
+ checks.append(NodeMantisPreflightCheck("usage", False, "Usage check failed.", details=str(exc)))
75
+
76
+ if not check_browser_launch:
77
+ checks.append(NodeMantisPreflightCheck("browser", True, "Browser check skipped.", skipped=True))
78
+ else:
79
+ browser_result = await check_chrome()
80
+ checks.append(
81
+ NodeMantisPreflightCheck(
82
+ "browser",
83
+ browser_result.available,
84
+ "Google Chrome launched successfully."
85
+ if browser_result.available
86
+ else "Google Chrome launch failed.",
87
+ details=browser_result.error,
88
+ )
89
+ )
90
+
91
+ return NodeMantisPreflightResult(
92
+ ok=all(check.ok for check in checks),
93
+ has_api_key=bool(resolved.api_key),
94
+ checks=tuple(checks),
95
+ )
96
+
97
+
98
+ def _get_json(
99
+ path: str,
100
+ *,
101
+ api_key: str | None = None,
102
+ timeout_seconds: float,
103
+ ) -> object | None:
104
+ headers = {"authorization": f"Bearer {api_key}"} if api_key else {}
105
+ request = Request(f"{NODEMANTIS_API_URL}{path}", headers=headers)
106
+
107
+ try:
108
+ with urlopen(request, timeout=timeout_seconds) as response:
109
+ body = response.read()
110
+ if response.status < 200 or response.status >= 300:
111
+ raise RuntimeError(f"HTTP {response.status}")
112
+ except HTTPError as exc:
113
+ try:
114
+ body = exc.read(500).decode("utf-8", errors="replace")
115
+ finally:
116
+ exc.close()
117
+ raise RuntimeError(f"HTTP {exc.code}{': ' + body if body else ''}") from exc
118
+
119
+ if not body:
120
+ return None
121
+ return json.loads(body)
122
+
123
+ # Compatibility names for callers of earlier package versions.
124
+ PreflightCheck = NodeMantisPreflightCheck
125
+ PreflightResult = NodeMantisPreflightResult
nodemantis/py.typed ADDED
@@ -0,0 +1 @@
1
+
nodemantis/runtime.py ADDED
@@ -0,0 +1,74 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import platform
5
+ import subprocess
6
+ import sys
7
+ from dataclasses import dataclass
8
+
9
+
10
+ @dataclass(frozen=True)
11
+ class RuntimePlatformInfo:
12
+ os_name: str
13
+ arch: str
14
+ tag: str
15
+
16
+
17
+ SUPPORTED_PLATFORMS = {
18
+ ("linux", "x64"): "linux-x64",
19
+ ("windows", "x64"): "win32-x64",
20
+ ("darwin", "x64"): "darwin-x64",
21
+ ("darwin", "arm64"): "darwin-arm64",
22
+ }
23
+
24
+
25
+ class UnsupportedPlatformError(RuntimeError):
26
+ def __init__(self, os_name: str, arch: str) -> None:
27
+ super().__init__(
28
+ "NodeMantis supports Linux x64, Windows x64, macOS x64, and macOS arm64. "
29
+ f"Current platform is {os_name}/{arch}."
30
+ )
31
+ self.os_name = os_name
32
+ self.arch = arch
33
+
34
+
35
+ def runtime_platform_info(
36
+ os_name: str | None = None,
37
+ machine: str | None = None,
38
+ ) -> RuntimePlatformInfo:
39
+ normalized_os = _normalize_os(os_name or platform.system())
40
+ normalized_arch = _normalize_arch(machine or platform.machine())
41
+ tag = SUPPORTED_PLATFORMS.get((normalized_os, normalized_arch))
42
+ if not tag:
43
+ raise UnsupportedPlatformError(normalized_os, normalized_arch)
44
+ return RuntimePlatformInfo(os_name=normalized_os, arch=normalized_arch, tag=tag)
45
+
46
+
47
+ def broker_hello() -> dict[str, str]:
48
+ """Run the wheel's installation self-check, never a selectable product runtime."""
49
+ runtime_platform_info()
50
+ command = [sys.executable, "-m", "nodemantis.runtime_broker", "hello"]
51
+ result = subprocess.run(command, check=True, capture_output=True, text=True)
52
+ return json.loads(result.stdout)
53
+
54
+
55
+ def _normalize_os(value: str) -> str:
56
+ lowered = value.lower()
57
+ if lowered.startswith("msys") or lowered.startswith("mingw"):
58
+ return "windows"
59
+ if lowered == "windows":
60
+ return "windows"
61
+ if lowered == "darwin":
62
+ return "darwin"
63
+ if lowered == "linux":
64
+ return "linux"
65
+ return lowered
66
+
67
+
68
+ def _normalize_arch(value: str) -> str:
69
+ lowered = value.lower()
70
+ if lowered in {"x86_64", "amd64", "x64"}:
71
+ return "x64"
72
+ if lowered in {"arm64", "aarch64"}:
73
+ return "arm64"
74
+ return lowered
@@ -0,0 +1,25 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import sys
5
+
6
+ from .runtime import runtime_platform_info
7
+
8
+
9
+ def main(argv: list[str] | None = None) -> int:
10
+ argv = argv or sys.argv[1:]
11
+ if argv != ["hello"]:
12
+ print("usage: python -m nodemantis.runtime_broker hello", file=sys.stderr)
13
+ return 2
14
+
15
+ info = runtime_platform_info()
16
+ print(json.dumps({
17
+ "runtime": "nodemantis-python-broker",
18
+ "runtimeVersion": "0.1.0",
19
+ "platform": info.tag,
20
+ }))
21
+ return 0
22
+
23
+
24
+ if __name__ == "__main__":
25
+ raise SystemExit(main())