Skip to content

Commit 3bb2165

Browse files
committed
[update] Update frontend CI.
1 parent 588446b commit 3bb2165

6 files changed

Lines changed: 288 additions & 5 deletions

File tree

‎.github/workflows/ui-release.yml‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
name: UI Release
2+
3+
on:
4+
push:
5+
tags:
6+
- "ui-v*"
7+
8+
permissions:
9+
contents: write
10+
11+
jobs:
12+
build:
13+
runs-on: ubuntu-latest
14+
defaults:
15+
run:
16+
working-directory: ui
17+
18+
steps:
19+
- name: Checkout
20+
uses: actions/checkout@v4
21+
22+
- name: Setup Node
23+
uses: actions/setup-node@v4
24+
with:
25+
node-version: 20
26+
cache: yarn
27+
cache-dependency-path: ui/yarn.lock
28+
29+
- name: Install Yarn
30+
run: npm install -g yarn@1.22.22
31+
32+
- name: Install dependencies
33+
run: yarn install --frozen-lockfile
34+
35+
- name: Build UI
36+
run: yarn build
37+
38+
- name: Pack dist
39+
run: tar -czf loopai-ui-dist.tar.gz -C dist .
40+
41+
- name: Create GitHub release
42+
run: gh release create "$GITHUB_REF_NAME" loopai-ui-dist.tar.gz --title "$GITHUB_REF_NAME" --notes "LoopAI UI build." --verify-tag
43+
env:
44+
GH_TOKEN: ${{ github.token }}

‎api/.gitignore‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,4 +45,5 @@ Thumbs.db
4545

4646
app_config.json
4747
*sqlite*
48-
db/
48+
db/
49+
dist/

‎api/README.md‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,39 @@ curl http://localhost:8000/health
144144
打开浏览器访问: http://localhost:8000/docs
145145
```
146146

147+
### 前端 dist 发布和安装
148+
149+
FastAPI 会从 `api/dist` 托管前端:
150+
151+
- `GET /` 返回 `api/dist/index.html`
152+
- `GET /assets/*` 返回 Vite 构建后的静态资源
153+
- 生产环境前端请求同源 API 原路径,例如 `/train`、`/config/config`
154+
155+
推荐前端 release tag 使用 `ui-v*`,避免和 Python 包版本 tag 混在一起:
156+
157+
```bash
158+
cd ui
159+
yarn version --new-version 0.1.0 --no-git-tag-version
160+
git add package.json yarn.lock
161+
git commit -m "chore(ui): release 0.1.0"
162+
git tag ui-v0.1.0
163+
git push origin main ui-v0.1.0
164+
```
165+
166+
仓库里的 GitHub Actions 会在 `ui-v*` tag 推送后构建 `ui/`,创建 GitHub Release,并上传 `loopai-ui-dist.tar.gz`。
167+
168+
服务端安装最新公开前端 release:
169+
170+
```bash
171+
python scripts/download_ui_release.py
172+
```
173+
174+
如果 tag 前缀或仓库不同,可以显式指定:
175+
176+
```bash
177+
python scripts/download_ui_release.py --repo OpenDCAI/Dataflow-LoopAI --tag-prefix ui-v --output-dir api/dist
178+
```
179+
147180
## 📚 API 文档
148181

149182
### 1. 启动训练任务

‎api/app/main.py‎

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
1-
from fastapi import FastAPI
2-
from fastapi.responses import JSONResponse
1+
from fastapi import FastAPI, HTTPException
2+
from fastapi.responses import FileResponse, JSONResponse
3+
from fastapi.staticfiles import StaticFiles
34
from tortoise.contrib.fastapi import register_tortoise
45
from fastapi.middleware.cors import CORSMiddleware
56
from contextlib import asynccontextmanager
7+
from pathlib import Path
68

79
from .utils.starter.starter import starter_process
810

@@ -21,6 +23,7 @@
2123
LOGS_DIR = os.path.join(BASE_DIR, "logs")
2224
RUNS_DIR = os.path.join(BASE_DIR, "runs")
2325
DB_PATH = os.path.join(BASE_DIR, "db", "db.sqlite3")
26+
DIST_DIR = Path(BASE_DIR) / "dist"
2427

2528
os.makedirs(os.path.dirname(DB_PATH), exist_ok=True)
2629

@@ -63,8 +66,14 @@ async def lifespan(app: FastAPI):
6366
app.include_router(train_router, prefix="/train", tags=["train"])
6467
app.include_router(resource_router, prefix="/resource", tags=["resource"])
6568

69+
app.mount(
70+
"/assets",
71+
StaticFiles(directory=DIST_DIR / "assets", check_dir=False),
72+
name="frontend-assets",
73+
)
74+
6675

67-
@app.get("/")
76+
@app.get("/info")
6877
async def root():
6978
"""根路径"""
7079
return {
@@ -81,6 +90,20 @@ async def root():
8190
}
8291

8392

93+
@app.get("/", include_in_schema=False)
94+
async def frontend_root():
95+
index_path = DIST_DIR / "index.html"
96+
if index_path.is_file():
97+
return FileResponse(index_path)
98+
return JSONResponse(
99+
status_code=404,
100+
content={
101+
"message": "Frontend dist is not installed.",
102+
"hint": "Build ui/ or run scripts/download_ui_release.py to populate api/dist.",
103+
},
104+
)
105+
106+
84107
@app.get("/health")
85108
async def health_check():
86109
"""健康检查"""

‎scripts/download_ui_release.py‎

Lines changed: 182 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,182 @@
1+
#!/usr/bin/env python3
2+
"""Download the latest published LoopAI UI dist from GitHub Releases."""
3+
4+
from __future__ import annotations
5+
6+
import argparse
7+
import json
8+
import os
9+
import shutil
10+
import sys
11+
import tarfile
12+
import tempfile
13+
import urllib.error
14+
import urllib.request
15+
import zipfile
16+
from pathlib import Path
17+
18+
19+
DEFAULT_REPO = "OpenDCAI/Dataflow-LoopAI"
20+
DEFAULT_TAG_PREFIX = "ui-v"
21+
DEFAULT_ASSET_NAMES = ("loopai-ui-dist.tar.gz", "loopai-ui-dist.zip")
22+
ROOT_DIR = Path(__file__).resolve().parents[1]
23+
DEFAULT_OUTPUT_DIR = ROOT_DIR / "api" / "dist"
24+
25+
26+
def request_json(url: str, token: str | None) -> object:
27+
request = urllib.request.Request(
28+
url,
29+
headers={
30+
"Accept": "application/vnd.github+json",
31+
"User-Agent": "Dataflow-LoopAI-ui-release-downloader",
32+
**({"Authorization": f"Bearer {token}"} if token else {}),
33+
},
34+
)
35+
with urllib.request.urlopen(request, timeout=30) as response:
36+
return json.load(response)
37+
38+
39+
def download_file(url: str, target: Path, token: str | None) -> None:
40+
request = urllib.request.Request(
41+
url,
42+
headers={
43+
"Accept": "application/octet-stream",
44+
"User-Agent": "Dataflow-LoopAI-ui-release-downloader",
45+
**({"Authorization": f"Bearer {token}"} if token else {}),
46+
},
47+
)
48+
with urllib.request.urlopen(request, timeout=60) as response:
49+
with target.open("wb") as handle:
50+
shutil.copyfileobj(response, handle)
51+
52+
53+
def find_release(repo: str, tag_prefix: str, include_prerelease: bool, token: str | None) -> dict:
54+
releases = request_json(f"https://api.github.com/repos/{repo}/releases?per_page=100", token)
55+
if not isinstance(releases, list):
56+
raise RuntimeError("GitHub releases response is not a list")
57+
58+
for release in releases:
59+
if not isinstance(release, dict):
60+
continue
61+
tag_name = str(release.get("tag_name", ""))
62+
if tag_prefix and not tag_name.startswith(tag_prefix):
63+
continue
64+
if release.get("draft"):
65+
continue
66+
if release.get("prerelease") and not include_prerelease:
67+
continue
68+
return release
69+
70+
raise RuntimeError(f"No public release found for {repo} with tag prefix {tag_prefix!r}")
71+
72+
73+
def find_asset(release: dict, asset_names: tuple[str, ...]) -> dict:
74+
assets = release.get("assets", [])
75+
if not isinstance(assets, list):
76+
raise RuntimeError("Release assets response is not a list")
77+
78+
for asset_name in asset_names:
79+
for asset in assets:
80+
if isinstance(asset, dict) and asset.get("name") == asset_name:
81+
return asset
82+
83+
for asset in assets:
84+
if not isinstance(asset, dict):
85+
continue
86+
name = str(asset.get("name", ""))
87+
if "ui" in name and name.endswith((".tar.gz", ".tgz", ".zip")):
88+
return asset
89+
90+
names = ", ".join(str(asset.get("name", "")) for asset in assets if isinstance(asset, dict))
91+
raise RuntimeError(f"No UI dist asset found in release {release.get('tag_name')}. Assets: {names}")
92+
93+
94+
def extract_archive(archive_path: Path, extract_dir: Path) -> None:
95+
name = archive_path.name
96+
if name.endswith((".tar.gz", ".tgz")):
97+
with tarfile.open(archive_path, "r:gz") as archive:
98+
archive.extractall(extract_dir)
99+
return
100+
if name.endswith(".zip"):
101+
with zipfile.ZipFile(archive_path) as archive:
102+
archive.extractall(extract_dir)
103+
return
104+
raise RuntimeError(f"Unsupported archive type: {archive_path.name}")
105+
106+
107+
def locate_dist_dir(extract_dir: Path) -> Path:
108+
candidates = [extract_dir, *extract_dir.rglob("dist")]
109+
for candidate in candidates:
110+
if (candidate / "index.html").is_file():
111+
return candidate
112+
for candidate in extract_dir.rglob("index.html"):
113+
return candidate.parent
114+
raise RuntimeError("Downloaded archive does not contain index.html")
115+
116+
117+
def replace_dist(source_dir: Path, output_dir: Path) -> None:
118+
output_dir.parent.mkdir(parents=True, exist_ok=True)
119+
staging_dir = output_dir.with_name(f".{output_dir.name}.staging")
120+
backup_dir = output_dir.with_name(f".{output_dir.name}.backup")
121+
122+
if staging_dir.exists():
123+
shutil.rmtree(staging_dir)
124+
if backup_dir.exists():
125+
shutil.rmtree(backup_dir)
126+
127+
shutil.copytree(source_dir, staging_dir)
128+
if output_dir.exists():
129+
output_dir.rename(backup_dir)
130+
staging_dir.rename(output_dir)
131+
if backup_dir.exists():
132+
shutil.rmtree(backup_dir)
133+
134+
135+
def parse_args() -> argparse.Namespace:
136+
parser = argparse.ArgumentParser(description=__doc__)
137+
parser.add_argument("--repo", default=DEFAULT_REPO, help="GitHub repo in owner/name form")
138+
parser.add_argument("--tag-prefix", default=DEFAULT_TAG_PREFIX, help="Release tag prefix for UI builds")
139+
parser.add_argument(
140+
"--asset-name",
141+
action="append",
142+
dest="asset_names",
143+
help="Expected release asset name. Can be passed multiple times.",
144+
)
145+
parser.add_argument("--output-dir", default=str(DEFAULT_OUTPUT_DIR), help="Where to install the dist files")
146+
parser.add_argument("--include-prerelease", action="store_true", help="Allow prerelease UI builds")
147+
return parser.parse_args()
148+
149+
150+
def main() -> int:
151+
args = parse_args()
152+
token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")
153+
asset_names = tuple(args.asset_names or DEFAULT_ASSET_NAMES)
154+
output_dir = Path(args.output_dir).resolve()
155+
156+
try:
157+
release = find_release(args.repo, args.tag_prefix, args.include_prerelease, token)
158+
asset = find_asset(release, asset_names)
159+
download_url = asset.get("browser_download_url")
160+
if not download_url:
161+
raise RuntimeError(f"Asset {asset.get('name')} has no browser_download_url")
162+
163+
with tempfile.TemporaryDirectory(prefix="loopai-ui-dist-") as temp_dir_name:
164+
temp_dir = Path(temp_dir_name)
165+
archive_path = temp_dir / str(asset["name"])
166+
download_file(str(download_url), archive_path, token)
167+
168+
extract_dir = temp_dir / "extract"
169+
extract_dir.mkdir()
170+
extract_archive(archive_path, extract_dir)
171+
dist_dir = locate_dist_dir(extract_dir)
172+
replace_dist(dist_dir, output_dir)
173+
174+
print(f"Installed UI {release.get('tag_name')} from {asset.get('name')} into {output_dir}")
175+
return 0
176+
except (RuntimeError, urllib.error.URLError, urllib.error.HTTPError) as exc:
177+
print(f"download_ui_release.py: {exc}", file=sys.stderr)
178+
return 1
179+
180+
181+
if __name__ == "__main__":
182+
raise SystemExit(main())

‎ui/src/axios/config.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import axios from 'axios'
33
let ax = axios.create();
44

55
const devURL = '/api'
6-
const prodURL = '/api'
6+
const prodURL = '/'
77

88
const getBaseURL = () => {
99
if (process.env.NODE_ENV == 'production') {

0 commit comments

Comments
 (0)