Harden portal deploy path: chunked .next upload and observability docs.

Avoid remote pnpm build overload; document health/ntfy/Kuma anchors for miniprogram smoke.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-09-29 01:18:12 -05:00
parent 9f8fec1723
commit c90670a1f7
6 changed files with 303 additions and 20 deletions

View File

@ -145,4 +145,12 @@ python deploy/observability/_upload_next_deploy.py
## 部署
生产机:`82.157.112.245`。细节见 [`deploy/README.md`](./deploy/README.md)。**仅在本地 PC/H5 + 三端小程序验收通过后再上。**
生产机:`82.157.112.245` · 目录 `/var/www/nomadro.cn` · 服务 `nomadro.service`。细节见 [`deploy/README.md`](./deploy/README.md)。
```bash
pnpm build
python deploy/observability/_upload_next_chunked.py
```
线上冒烟:https://nomadro.cn/api/health · `/api/config` · `/admin/analytics` · `/vip/ebook/read#00-preface`。
小程序测支付/鉴权:`https://api.nomadro.cn`(后端已独立部署)。

View File

@ -30,33 +30,37 @@
`www.nomadro.com` 会自动 301 跳转到 `nomadro.com`。
## 日常更新(门户 Next)
推荐(Windows 本地 build → 分块上传 `.next`,避免在服务器跑 `pnpm build` 把机器打满):
```bash
pnpm build
python deploy/observability/_upload_next_chunked.py
```
备选:`python deploy/observability/_upload_next_deploy.py`(会先 `git pull pre1`;打包会跳过 `.next/dev`)。
冒烟清单:`/api/health` `/api/config` `/book/read` `/vip/ebook/read` `/admin`;小程序依赖 `https://nomadro.cn/api/config` + `https://api.nomadro.cn`。
观测 / ntfy / Umami / Kuma:见 [`observability/README.md`](./observability/README.md)。
## 首次部署
```bash
ssh ubuntu@82.157.112.245
# 目录与仓库以现网为准,示例:
cd /var/www/nomadro # 或现网实际路径
cd /var/www/nomadro.cn
git fetch && git checkout pre1 && git pull
pnpm install && pnpm build
# 按现网用 PM2 / systemd 重启 Next 与 FastAPI
```
## 日常更新
```bash
ssh ubuntu@82.157.112.245
cd /var/www/nomadro # 现网路径
git pull origin pre1
pnpm install && pnpm build
# 重启对应进程后冒烟:/ /nav /book /community /vip /admin
pnpm install && pnpm build # 仅首次或机器空闲时;日常优先本地 build+上传
sudo systemctl restart nomadro.service
```
## 服务管理
```bash
# 以现网进程管理器为准,例如:
pm2 status
# 或
systemctl status nomadro caddy nginx
systemctl status nomadro
journalctl -u nomadro -f
# 观测健康脚本
sudo bash /var/www/nomadro.cn/deploy/observability/healthcheck.sh
```

View File

@ -0,0 +1,65 @@
#!/usr/bin/env python3
"""Kill stuck next build on server and restore nomadro.service."""
from __future__ import annotations
import sys
import time
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
def connect(retries=8):
last = None
for i in range(retries):
try:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
HOST,
username=USER,
password=PASS,
timeout=60,
allow_agent=False,
look_for_keys=False,
banner_timeout=120,
)
return c
except Exception as e:
last = e
print(f"connect fail {i+1}: {e}", flush=True)
time.sleep(8)
raise last # type: ignore
def main() -> int:
c = connect()
cmd = r"""
set +e
echo '--- before ---'
ps -eo pid,etime,cmd | grep -E 'next|node.*build|pnpm' | grep -v grep | head -30
# kill build children under /var/www/nomadro.cn
pkill -f 'next build' || true
pkill -f 'pnpm build' || true
# don't kill the running production next server if possible — restart service after
sleep 2
sudo systemctl restart nomadro.service
sleep 5
systemctl is-active nomadro.service
echo '--- after ---'
ps -eo pid,etime,cmd | grep -E 'next|node|pnpm' | grep -v grep | head -20
curl -s -o /dev/null -w 'local_root:%{http_code}\n' -m 15 http://127.0.0.1:4003/ || echo local_root:ERR
curl -s -o /dev/null -w 'local_health:%{http_code}\n' -m 15 http://127.0.0.1:4003/api/health || echo local_health:ERR
echo DONE
"""
_, stdout, _ = c.exec_command(cmd, timeout=120, get_pty=True)
print(stdout.read().decode("utf-8", "replace"), flush=True)
c.close()
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,70 @@
#!/usr/bin/env python3
"""Build portal on production server (when Windows→server SFTP is too slow)."""
from __future__ import annotations
import sys
import time
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
APP = "/var/www/nomadro.cn"
CMD = r"""
set -euo pipefail
cd /var/www/nomadro.cn
git log -1 --oneline
export CI=1
pnpm build
test -f .next/BUILD_ID
echo BUILD_ID=$(cat .next/BUILD_ID)
sudo systemctl restart nomadro.service
sleep 4
systemctl is-active nomadro.service
echo '--- local ---'
for p in / /api/health /api/config /nav /book /book/read /community /vip/ebook/read /admin; do
code=$(curl -s -o /dev/null -w '%{http_code}' -m 25 http://127.0.0.1:4003$p || echo ERR)
echo "$p -> $code"
done
echo '--- public ---'
for p in / /api/health /api/config /book/read /vip/ebook/read; do
code=$(curl -sk -o /dev/null -w '%{http_code}' -m 25 https://nomadro.cn$p || echo ERR)
echo "https://nomadro.cn$p -> $code"
done
if [ -x /usr/local/bin/notify-ntfy ]; then
/usr/local/bin/notify-ntfy "Nomadro deploy" "portal built on server $(date -u +%Y-%m-%dT%H:%MZ)" default "rocket,nomadro" || true
fi
echo DONE
"""
def main() -> int:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
HOST,
username=USER,
password=PASS,
timeout=30,
allow_agent=False,
look_for_keys=False,
banner_timeout=60,
)
print("starting remote build...", flush=True)
_, stdout, _ = c.exec_command(CMD, timeout=1200, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.1)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
print(f"\n[exit {code}]", flush=True)
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,123 @@
#!/usr/bin/env python3
"""Upload packed .next and restart — assumes source already on pre1."""
from __future__ import annotations
import os
import sys
import time
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
TAR = os.path.join(os.environ.get("TEMP", "/tmp"), "nomadro-next.tgz")
REMOTE = "/tmp/nomadro-next.tgz"
APP = "/var/www/nomadro.cn"
CHUNK = 256 * 1024
def connect():
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
HOST,
username=USER,
password=PASS,
timeout=60,
allow_agent=False,
look_for_keys=False,
banner_timeout=120,
)
t = c.get_transport()
if t:
t.set_keepalive(10)
return c
def run(c: paramiko.SSHClient, cmd: str, timeout: int = 300) -> int:
print(f"$ {cmd[:140]}", flush=True)
_, stdout, _ = c.exec_command(cmd, timeout=timeout, get_pty=True)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
time.sleep(0.05)
while stdout.channel.recv_ready():
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
code = stdout.channel.recv_exit_status()
print(f"[exit {code}]", flush=True)
return code
def main() -> int:
if not os.path.isfile(TAR):
print("missing", TAR)
return 1
size = os.path.getsize(TAR)
print(f"upload {size/1024/1024:.1f}MB from {TAR}", flush=True)
c = connect()
# light housekeeping first
run(
c,
"pkill -f 'next build' || true; pkill -f 'pnpm build' || true; "
"systemctl is-active nomadro.service || true",
60,
)
sftp = c.open_sftp()
with open(TAR, "rb") as f, sftp.file(REMOTE, "wb") as rf:
rf.set_pipelined(True)
sent = 0
t0 = time.time()
while True:
data = f.read(CHUNK)
if not data:
break
rf.write(data)
sent += len(data)
if sent % (2 * 1024 * 1024) < CHUNK:
rate = sent / max(time.time() - t0, 0.1) / 1024
print(f" {sent/1024/1024:.1f}/{size/1024/1024:.1f} MB ({rate:.0f} KB/s)", flush=True)
sftp.close()
print("uploaded ok", flush=True)
code = run(
c,
f"""
set -euo pipefail
cd {APP}
git fetch --depth 1 origin pre1
git reset --hard FETCH_HEAD
git log -1 --oneline
rm -rf .next
tar -xzf {REMOTE} -C {APP}
rm -f {REMOTE}
test -f .next/BUILD_ID
echo BUILD_ID=$(cat .next/BUILD_ID)
sudo systemctl restart nomadro.service
sleep 4
systemctl is-active nomadro.service
echo '--- local ---'
for p in / /api/health /api/config /nav /book /book/read /community /vip/ebook/read /admin; do
code=$(curl -s -o /dev/null -w '%{{http_code}}' -m 25 http://127.0.0.1:4003$p || echo ERR)
echo "$p -> $code"
done
echo '--- public ---'
for p in / /api/health /api/config /book/read /vip/ebook/read; do
code=$(curl -sk -o /dev/null -w '%{{http_code}}' -m 25 https://nomadro.cn$p || echo ERR)
echo "https://nomadro.cn$p -> $code"
done
if [ -x /usr/local/bin/notify-ntfy ]; then
/usr/local/bin/notify-ntfy "Nomadro deploy" "portal .next uploaded $(date -u +%Y-%m-%dT%H:%MZ)" default "rocket,nomadro" || true
fi
echo DONE
""",
240,
)
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -38,10 +38,23 @@ def main() -> int:
print("Missing local .next/BUILD_ID — run pnpm build first", flush=True)
return 1
print("Packing .next ...", flush=True)
print("Packing .next (production only, skip .next/dev) ...", flush=True)
tar_path = os.path.join(tempfile.gettempdir(), "nomadro-next.tgz")
def tar_filter(ti: tarfile.TarInfo) -> tarfile.TarInfo | None:
# Turbopack/dev cache mutates while `pnpm dev` runs and breaks tar on Windows
parts = ti.name.replace("\\", "/").split("/")
if ".next" in parts:
idx = parts.index(".next")
rest = parts[idx + 1 :]
if rest and rest[0] == "dev":
return None
if "cache" in rest and "turbopack" in rest:
return None
return ti
with tarfile.open(tar_path, "w:gz") as tar:
tar.add(NEXT_DIR, arcname=".next")
tar.add(NEXT_DIR, arcname=".next", filter=tar_filter)
size_mb = os.path.getsize(tar_path) / (1024 * 1024)
print(f"Packed {tar_path} ({size_mb:.1f} MB)", flush=True)