pystepmap 0.1.0__py3-none-any.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.
- pystepmap-0.1.0.dist-info/METADATA +54 -0
- pystepmap-0.1.0.dist-info/RECORD +26 -0
- pystepmap-0.1.0.dist-info/WHEEL +4 -0
- pystepmap-0.1.0.dist-info/entry_points.txt +2 -0
- pystepmap-0.1.0.dist-info/licenses/LICENSE +21 -0
- pystepmap_server/__init__.py +3 -0
- pystepmap_server/api.py +890 -0
- pystepmap_server/app.py +151 -0
- pystepmap_server/cli.py +138 -0
- pystepmap_server/flows.py +542 -0
- pystepmap_server/live.py +151 -0
- pystepmap_server/locks.py +139 -0
- pystepmap_server/mcp_server.py +216 -0
- pystepmap_server/mcp_tools.py +1901 -0
- pystepmap_server/procinfo.py +61 -0
- pystepmap_server/requirements_view.py +63 -0
- pystepmap_server/runner.py +673 -0
- pystepmap_server/shared.py +198 -0
- pystepmap_server/sources.py +126 -0
- pystepmap_server/status.py +116 -0
- pystepmap_server/store.py +1091 -0
- pystepmap_server/testflows.py +648 -0
- pystepmap_server/web/assets/index-CkPpOJq9.js +1748 -0
- pystepmap_server/web/assets/index-NTWdqvqI.css +1 -0
- pystepmap_server/web/index.html +14 -0
- pystepmap_server/worker.py +303 -0
pystepmap_server/app.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"""组装平台的 FastAPI 应用:/api 下是接口(api.py),/ 是打包好的前端页面。
|
|
2
|
+
|
|
3
|
+
平台数据目录默认 ~/.pystepmap,可用环境变量 PYSTEPMAP_HOME 改;库文件是其中的 pystepmap.db。
|
|
4
|
+
前端先取包里的 pystepmap_server/web/(发布的包打包时放进去的,见 server/hatch_build.py),没有时取仓库里的 web/dist
|
|
5
|
+
(npm run build 的产物,从源码仓库运行时),可用环境变量 PYSTEPMAP_WEB_DIST 指定;没有打包好的前端时,/ 返回一段中文
|
|
6
|
+
说明怎么打包,接口照常可用。
|
|
7
|
+
|
|
8
|
+
收尾(lifespan):开始服务时删掉上次被强杀的服务留下的运行临时目录(<数据目录>/runs/tmp-…);正常退出时取消并等完
|
|
9
|
+
正在跑的测试(runner.stop_all:结束它们的进程组,这些运行记成已取消,项目锁放掉)。服务被强杀时由 runner 的看门狗
|
|
10
|
+
结束测试的进程组。
|
|
11
|
+
|
|
12
|
+
只接受本机:服务只监听 127.0.0.1;另外 Host 头必须是 127.0.0.1、localhost 或 ::1(带不带端口都行),挡住 DNS 重绑定
|
|
13
|
+
(别的网站把自己的域名解析到 127.0.0.1,再用浏览器调接口);POST / PUT / DELETE 等修改请求带了 Origin 头时,它的主机
|
|
14
|
+
也必须是这几个之一,挡住别的网页发来的跨站请求。不带 Origin 的请求(curl、脚本、测试)照常放行。都返回 403
|
|
15
|
+
{"error": "中文说明"}。Vite 开发服务器的代理(changeOrigin 开或不开)发来的 Host / Origin 都是本机地址,照常放行。
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import html
|
|
21
|
+
import os
|
|
22
|
+
from collections.abc import AsyncIterator
|
|
23
|
+
from contextlib import asynccontextmanager
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
from urllib.parse import urlsplit
|
|
26
|
+
|
|
27
|
+
from fastapi import FastAPI, Request
|
|
28
|
+
from fastapi.concurrency import run_in_threadpool
|
|
29
|
+
from fastapi.exception_handlers import http_exception_handler
|
|
30
|
+
from fastapi.responses import HTMLResponse, JSONResponse
|
|
31
|
+
from fastapi.staticfiles import StaticFiles
|
|
32
|
+
from starlette.datastructures import Headers
|
|
33
|
+
from starlette.exceptions import HTTPException as StarletteHTTPException
|
|
34
|
+
from starlette.types import ASGIApp, Receive, Scope, Send
|
|
35
|
+
|
|
36
|
+
from . import runner
|
|
37
|
+
from .api import api_http_error, create_api
|
|
38
|
+
from .store import DB_NAME, Store, default_home
|
|
39
|
+
|
|
40
|
+
__all__ = ["DB_NAME", "create_app", "default_home"] # DB_NAME、default_home 在 store.py(pystepmap mcp 不导入这里),这里照旧能取
|
|
41
|
+
_PACKAGED_WEB = Path(__file__).resolve().parent / "web" # 发布的包里带的前端
|
|
42
|
+
_REPO_WEB_DIST = Path(__file__).resolve().parents[3] / "web" / "dist" # server/src/pystepmap_server/app.py → 仓库根
|
|
43
|
+
|
|
44
|
+
_NO_FRONTEND = """<!doctype html>
|
|
45
|
+
<html lang="zh-CN"><head><meta charset="utf-8"><title>pystepmap</title>
|
|
46
|
+
<style>body{{background:#16181d;color:#d6d9e0;font:15px/1.7 -apple-system,"PingFang SC",sans-serif;
|
|
47
|
+
max-width:720px;margin:12vh auto;padding:0 16px}}code{{background:#262a33;padding:2px 6px;border-radius:4px}}</style>
|
|
48
|
+
</head><body>
|
|
49
|
+
<h2>pystepmap 平台已启动,但前端还没有打包</h2>
|
|
50
|
+
<p>在 pystepmap 仓库的 <code>web</code> 目录下运行 <code>npm install && npm run build</code>,然后重启
|
|
51
|
+
<code>pystepmap serve</code>。不是从源码仓库运行时,装 PyPI 上发布的 <code>pystepmap</code>(带界面):
|
|
52
|
+
<code>pip install -U pystepmap</code>。</p>
|
|
53
|
+
<p>找的位置:<code>{dist}</code>(可用环境变量 <code>PYSTEPMAP_WEB_DIST</code> 指定别的目录)。</p>
|
|
54
|
+
<p>接口照常可用:<code>/api/health</code>。</p>
|
|
55
|
+
</body></html>
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def default_web_dist() -> Path:
|
|
60
|
+
custom = os.environ.get("PYSTEPMAP_WEB_DIST")
|
|
61
|
+
if custom:
|
|
62
|
+
return Path(custom).expanduser()
|
|
63
|
+
return _PACKAGED_WEB if (_PACKAGED_WEB / "index.html").is_file() else _REPO_WEB_DIST
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
LOCAL_HOSTS = frozenset({"127.0.0.1", "localhost", "::1"})
|
|
67
|
+
_SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _host_name(value: str) -> str:
|
|
71
|
+
"""Host 头里的主机名(去掉端口,IPv6 去掉方括号),小写。"""
|
|
72
|
+
try:
|
|
73
|
+
return (urlsplit(f"//{value.strip()}").hostname or "").lower()
|
|
74
|
+
except ValueError:
|
|
75
|
+
return ""
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class LocalOnly:
|
|
79
|
+
"""只接受本机的 Host 和 Origin(见模块说明)。和 Starlette 的 TrustedHostMiddleware 一样按去掉端口的主机名比较,
|
|
80
|
+
另外查修改请求的 Origin,被拒绝时回中文的 {"error": …}。"""
|
|
81
|
+
|
|
82
|
+
def __init__(self, app: ASGIApp):
|
|
83
|
+
self.app = app
|
|
84
|
+
|
|
85
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
86
|
+
if scope["type"] != "http":
|
|
87
|
+
await self.app(scope, receive, send)
|
|
88
|
+
return
|
|
89
|
+
headers = Headers(scope=scope)
|
|
90
|
+
host = headers.get("host", "")
|
|
91
|
+
message = None
|
|
92
|
+
if _host_name(host) not in LOCAL_HOSTS:
|
|
93
|
+
message = f"只接受用本机地址访问(127.0.0.1 或 localhost),这次的 Host 是 {host or '空的'}"
|
|
94
|
+
elif scope["method"] not in _SAFE_METHODS and "origin" in headers:
|
|
95
|
+
origin = headers["origin"]
|
|
96
|
+
try:
|
|
97
|
+
origin_host = (urlsplit(origin).hostname or "").lower()
|
|
98
|
+
except ValueError:
|
|
99
|
+
origin_host = ""
|
|
100
|
+
if origin_host not in LOCAL_HOSTS:
|
|
101
|
+
message = f"只接受本机页面发来的修改请求,这次来自 {origin}"
|
|
102
|
+
if message is None:
|
|
103
|
+
await self.app(scope, receive, send)
|
|
104
|
+
return
|
|
105
|
+
await JSONResponse({"error": message}, status_code=403)(scope, receive, send)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
async def _outer_http_error(request: Request, exc: StarletteHTTPException):
|
|
109
|
+
"""/api 下没有对应接口的路径(含 /api 本身)回中文的 {"error": …},挂着前端页面时也一样;接口以外的路径
|
|
110
|
+
(前端页面、静态文件)找不到、方法不对时同样回中文的 {"error": …},不是框架默认的 {"detail": "Not Found"}。"""
|
|
111
|
+
path = request.url.path
|
|
112
|
+
if path == "/api" or path.startswith("/api/"):
|
|
113
|
+
return await api_http_error(request, exc)
|
|
114
|
+
if exc.status_code in (204, 304): # 没有响应体的状态码照框架的处理
|
|
115
|
+
return await http_exception_handler(request, exc)
|
|
116
|
+
if exc.status_code == 404:
|
|
117
|
+
message = f"没有这个页面:{path}"
|
|
118
|
+
elif exc.status_code == 405:
|
|
119
|
+
message = f"这个地址不支持 {request.method}:{path}"
|
|
120
|
+
else:
|
|
121
|
+
message = str(exc.detail)
|
|
122
|
+
return JSONResponse({"error": message}, status_code=exc.status_code, headers=getattr(exc, "headers", None))
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def create_app(home: Path, web_dist: Path | None = None) -> FastAPI:
|
|
126
|
+
"""home:平台数据目录(不存在时创建)。web_dist:打包好的前端目录,省略时见 default_web_dist。"""
|
|
127
|
+
store = Store(Path(home) / DB_NAME)
|
|
128
|
+
|
|
129
|
+
@asynccontextmanager
|
|
130
|
+
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
|
|
131
|
+
# 开始服务时:删掉上次被强杀的服务(和没来得及收尾的看门狗)留下的运行临时目录。同一个数据目录只能开一个
|
|
132
|
+
# pystepmap serve,所以这时不会有别的运行在用它们
|
|
133
|
+
runner.clean_leftovers(Path(home))
|
|
134
|
+
yield
|
|
135
|
+
# 正常退出(Ctrl+C、SIGTERM,uvicorn 先收尾再走到这里):结束在跑的测试进程组,等它们记下"已取消"、放开锁
|
|
136
|
+
await run_in_threadpool(runner.stop_all, Path(home))
|
|
137
|
+
|
|
138
|
+
app = FastAPI(title="pystepmap", docs_url=None, redoc_url=None, openapi_url=None, lifespan=lifespan)
|
|
139
|
+
app.state.store = store
|
|
140
|
+
app.state.home = Path(home)
|
|
141
|
+
app.add_middleware(LocalOnly)
|
|
142
|
+
app.add_exception_handler(StarletteHTTPException, _outer_http_error)
|
|
143
|
+
app.mount("/api", create_api(store)) # 先挂接口:/api 下的路径不会落到静态文件上
|
|
144
|
+
dist = Path(web_dist) if web_dist is not None else default_web_dist()
|
|
145
|
+
if (dist / "index.html").is_file():
|
|
146
|
+
app.mount("/", StaticFiles(directory=dist, html=True), name="web")
|
|
147
|
+
else:
|
|
148
|
+
page = _NO_FRONTEND.format(dist=html.escape(str(dist)))
|
|
149
|
+
# 不用 @app.get 装饰器:引擎会把它认成一个接口入口,pystepmap 自己的图上就多出一条只返回说明页的功能线
|
|
150
|
+
app.add_api_route("/", lambda: page, methods=["GET"], response_class=HTMLResponse, include_in_schema=False)
|
|
151
|
+
return app
|
pystepmap_server/cli.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""pystepmap serve:在 127.0.0.1 上启动平台。core 的命令行(pystepmap.cli)在用户运行 serve 时才导入这里,所以 core
|
|
2
|
+
不依赖 FastAPI。
|
|
3
|
+
|
|
4
|
+
先自己绑好端口再交给 uvicorn:端口被占用时能给出明确的中文提示(退出码 2),绑定和监听也没有空档。
|
|
5
|
+
同一个数据目录只允许一个服务进程:启动时对 <数据目录>/pystepmap.lock 加文件锁(flock,进程退出时系统自动释放),
|
|
6
|
+
已经被别的 pystepmap serve 锁着时提示并退出码 2。pystepmap mcp 不拿这把锁,和服务同时用一个数据目录;同一个项目的
|
|
7
|
+
分析靠项目级的锁(locks.py,<数据目录>/locks/)在进程之间互斥,库的写入靠 SQLite 的写锁。
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
import socket
|
|
14
|
+
import stat
|
|
15
|
+
import sys
|
|
16
|
+
import threading
|
|
17
|
+
import time
|
|
18
|
+
import webbrowser
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
import uvicorn
|
|
22
|
+
|
|
23
|
+
from .app import create_app, default_home
|
|
24
|
+
from .store import StoreError, private_dir
|
|
25
|
+
|
|
26
|
+
HOST = "127.0.0.1" # 只监听本机
|
|
27
|
+
DEFAULT_PORT = 5179
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
LOCK_NAME = "pystepmap.lock"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class PortInUse(Exception):
|
|
34
|
+
pass
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class HomeInUse(Exception):
|
|
38
|
+
def __init__(self, holder: str):
|
|
39
|
+
super().__init__(holder)
|
|
40
|
+
self.holder = holder
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _lock_home(home: Path, port: int = 0) -> int:
|
|
44
|
+
"""对数据目录加独占的文件锁,返回锁文件的描述符(服务结束前一直开着);已经被别的进程锁着时抛 HomeInUse。
|
|
45
|
+
锁文件里写两行:进程号、监听的端口(pystepmap mcp 请平台运行测试时按它找到平台,见 store.serve_port)。"""
|
|
46
|
+
try:
|
|
47
|
+
import fcntl
|
|
48
|
+
except ImportError: # Windows:没有 flock,不加锁
|
|
49
|
+
return -1
|
|
50
|
+
private_dir(home) # 0700;以前建的更宽的目录收紧
|
|
51
|
+
fd = os.open(home / LOCK_NAME, os.O_RDWR | os.O_CREAT, 0o600)
|
|
52
|
+
if stat.S_IMODE(os.fstat(fd).st_mode) != 0o600: # 以前建的锁文件是 0644
|
|
53
|
+
os.fchmod(fd, 0o600)
|
|
54
|
+
try:
|
|
55
|
+
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
56
|
+
except OSError:
|
|
57
|
+
holder = os.read(fd, 100).decode("utf-8", "replace").strip().split("\n")[0]
|
|
58
|
+
os.close(fd)
|
|
59
|
+
raise HomeInUse(holder) from None
|
|
60
|
+
os.ftruncate(fd, 0)
|
|
61
|
+
os.write(fd, f"{os.getpid()}\n{port}\n".encode())
|
|
62
|
+
return fd
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _bind(port: int) -> socket.socket:
|
|
66
|
+
"""在 127.0.0.1:port 上绑一个监听用的套接字;被占用时抛 PortInUse。"""
|
|
67
|
+
# 先连一下:别的进程监听着 0.0.0.0:port 时,macOS 上带 SO_REUSEADDR 的 bind 也可能成功,连得上就算被占用
|
|
68
|
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:
|
|
69
|
+
probe.settimeout(0.5)
|
|
70
|
+
if probe.connect_ex((HOST, port)) == 0:
|
|
71
|
+
raise PortInUse
|
|
72
|
+
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
73
|
+
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # 和 uvicorn 一样:刚停掉的服务留下的 TIME_WAIT 不算占用
|
|
74
|
+
try:
|
|
75
|
+
sock.bind((HOST, port))
|
|
76
|
+
except OSError:
|
|
77
|
+
sock.close()
|
|
78
|
+
raise PortInUse from None
|
|
79
|
+
return sock
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _open_when_started(server: uvicorn.Server, url: str) -> None:
|
|
83
|
+
for _ in range(200): # 最多等 10 秒
|
|
84
|
+
if server.started:
|
|
85
|
+
webbrowser.open(url)
|
|
86
|
+
return
|
|
87
|
+
if server.should_exit:
|
|
88
|
+
return
|
|
89
|
+
time.sleep(0.05)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def serve(port: int = DEFAULT_PORT, open_browser: bool = True, home: Path | None = None) -> int:
|
|
93
|
+
"""启动平台,直到 Ctrl+C。返回退出码:0 正常停止,2 端口被占用、数据目录已被另一个服务占用或打不开。"""
|
|
94
|
+
home = Path(home) if home is not None else default_home()
|
|
95
|
+
try:
|
|
96
|
+
sock = _bind(port)
|
|
97
|
+
except PortInUse:
|
|
98
|
+
print(f"端口 {port} 已被占用:可能 pystepmap serve 已经在运行(打开 http://{HOST}:{port}/ 看看),"
|
|
99
|
+
f"或者用 --port 换一个端口", file=sys.stderr)
|
|
100
|
+
return 2
|
|
101
|
+
try:
|
|
102
|
+
lock = _lock_home(home, port)
|
|
103
|
+
except HomeInUse as e:
|
|
104
|
+
sock.close()
|
|
105
|
+
who = f"(进程 {e.holder})" if e.holder else ""
|
|
106
|
+
print(f"数据目录 {home} 已经有一个 pystepmap serve 在用{who}:同一个数据目录只能开一个服务。"
|
|
107
|
+
f"先停掉它,或者用环境变量 PYSTEPMAP_HOME 换一个数据目录", file=sys.stderr)
|
|
108
|
+
return 2
|
|
109
|
+
except OSError as e:
|
|
110
|
+
sock.close()
|
|
111
|
+
print(f"无法打开平台数据目录 {home}:{e.strerror or e}", file=sys.stderr)
|
|
112
|
+
return 2
|
|
113
|
+
try:
|
|
114
|
+
app = create_app(home)
|
|
115
|
+
except StoreError as e:
|
|
116
|
+
sock.close()
|
|
117
|
+
_unlock(lock)
|
|
118
|
+
print(f"无法打开平台数据目录:{e}", file=sys.stderr)
|
|
119
|
+
return 2
|
|
120
|
+
url = f"http://{HOST}:{port}/"
|
|
121
|
+
print(f"pystepmap 平台已启动:{url}\n数据目录:{home}\n按 Ctrl+C 停止", flush=True)
|
|
122
|
+
server = uvicorn.Server(uvicorn.Config(app, log_level="warning", access_log=False))
|
|
123
|
+
if open_browser:
|
|
124
|
+
threading.Thread(target=_open_when_started, args=(server, url), daemon=True).start()
|
|
125
|
+
try:
|
|
126
|
+
server.run(sockets=[sock])
|
|
127
|
+
except KeyboardInterrupt: # uvicorn 正常收尾之后会把 Ctrl+C 再抛出来:这是用户要停,不是出错
|
|
128
|
+
pass
|
|
129
|
+
finally:
|
|
130
|
+
sock.close()
|
|
131
|
+
_unlock(lock)
|
|
132
|
+
print("pystepmap 平台已停止", flush=True)
|
|
133
|
+
return 0
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _unlock(fd: int) -> None:
|
|
137
|
+
if fd >= 0:
|
|
138
|
+
os.close(fd) # 关掉描述符就释放了 flock;锁文件留着,下次启动接着用
|