backend: 交付网站后端 + 本地自助管理后台 + 测试工程(已脱敏)

Browse Source
范围由店主圈定:网页后端 / 自助后端、本地的自助管理后台、
用于测试的 Blender 工程、以及部署层的反代片段。

出站纪律:所有指向真实环境的值(域名/端口/盘符路径/IP/账户名)已替换为占位;
代码里本来就没有硬编码凭据(令牌走文件与环境变量)。
Blender 工程因内嵌绝对路径,做了等长替换(文件字节数未变,结构完好)。

两份交接文档各含《我们的思路与方法》,并要求对方回:
问题分析 + 改正意见 + 他改了什么(含是否动到接口/字段/数据格式)。
This commit is contained in:
Suda
2026-10-05 18:52:33 +08:00
parent 1903daafc3
commit 1d67fda9d5
30 changed files with 8486 additions and 0 deletions
+663
View File
@@ -0,0 +1,663 @@
# -*- coding: utf-8 -*-
"""
金钻工坊 · 渲染下单 —— 宿主机渲染机(worker)
开机启动后自动干活:
心跳上报 → 拉一单 → 下载皮肤 → 用 Blender 按模板出图 → 回传服务器 → 永久留档
留档(金钻要求:时间 / 序号 / 兑换码 / 皮肤 / 成图):
<ARCHIVE_DIR>
模板.blend、_assets\\skin.png、<模板名>.png、订单信息.json
只在需要时连服务器(出站),服务器从不主动连你。
"""
import base64, json, os, re, shutil, signal, socket, subprocess, sys, threading, time, traceback
import urllib.request, urllib.error
from datetime import datetime
HERE = os.path.dirname(os.path.abspath(__file__))
# ---- 成品命名(金钻 2026-09-30 定稿,和 make_order.py 必须一致)----
# 默认 1000 → <模板名>.png + <模板名>无压缩.png
# 其它 N → <模板名>N.png + <模板名>N无压缩.png
DEFAULT_RES = 1000
UNC_SUFFIX = "无压缩"
# 服务条款版本 —— 与网页 index.html / 后端 server.py 必须一致(2026-09-30 金钻定)
TERMS_VERSION = "2026-10-01.1"
# ---------------------------------------------------------------- 配置
CFG = {
"server": "http<WIN-PATH>",
"token": "",
"tpl_root": r"<ARCHIVE_DIR>",
"make_order": r"<TOOLS_DIR>\make_order.py",
"archive": r"<ARCHIVE_DIR>",
"blender": "", # 留空 = 自动查找
"res": DEFAULT_RES, # 出图分辨率;文件名规则见上
"poll": 20
}
TEMPLATES = { # key 必须和下单页一致
"stand": "1站立正反.blend",
"standb": "2站立正反加虚化.blend",
"wheat": "3麦田萤火.blend",
"beach": "4海边自拍.blend",
"boom": "5不看爆炸.blend",
"sakura": "6飞跃樱花林.blend",
"airship": "7空艇巡游.blend",
}
def tpl_base(tpl_key):
"""模板中文名(去掉文件名开头的序号):3麦田萤火.blend → 麦田萤火"""
return re.sub(r"^\d+", "", os.path.splitext(TEMPLATES.get(tpl_key, tpl_key))[0])
def out_base(tpl_key, res):
res = int(res or DEFAULT_RES)
b = tpl_base(tpl_key)
return b if res == DEFAULT_RES else "%s%d" % (b, res)
def deliver_names(tpl_key, res):
b = out_base(tpl_key, res)
return b + ".png", b + UNC_SUFFIX + ".png"
def prepare_out_dir(root, tpl_key, res, skin_path):
"""建成品文件夹并**先把皮肤放进去**(金钻 2026-09-30)。
文件夹名 = 成品名(`飞跃樱花林` / `飞跃樱花林1080`);重名加 -2/-3,
同一个模板被买两次不能互相覆盖。返回 (文件夹, 成品基名)。"""
base = out_base(tpl_key, res)
d = os.path.join(root, base)
n = 2
while os.path.exists(d):
d = os.path.join(root, "%s-%d" % (base, n))
n += 1
os.makedirs(d, exist_ok=True)
if skin_path and os.path.exists(skin_path):
dst = os.path.join(d, os.path.basename(skin_path))
if os.path.abspath(dst) != os.path.abspath(skin_path):
shutil.copy2(skin_path, dst)
return d, base
LOCK_PORT = 8083 # 单实例锁
LOG = os.path.join(HERE, "worker.log")
def log(*a):
line = "[%s] %s" % (datetime.now().strftime("%Y-%m-%d %H:%M:%S"), " ".join(str(x) for x in a))
print(line, flush=True)
try:
if os.path.exists(LOG) and os.path.getsize(LOG) > 2 * 1024 * 1024:
shutil.move(LOG, LOG + ".old")
with open(LOG, "a", encoding="utf-8") as f:
f.write(line + "\n")
except OSError:
pass
def load_cfg():
p = os.path.join(HERE, "config.json")
if os.path.exists(p):
try:
CFG.update(json.load(open(p, encoding="utf-8")))
except Exception as e:
log("config.json 读取失败:%r(用默认值继续)" % e)
# ---------------------------------------------------------------- HTTP
def http(path, obj=None, raw=False, timeout=120, tries=1, gap=5):
"""调服务器。tries>1 时网络抖动会自己重试。
⚠️ 2026-09-30 晚实踩:原来只接 HTTPError,**网络层的异常直接抛出去**。
那次是无压缩(约 10MB)回传时 TLS 断了一下(`EOF occurred in violation of protocol`),
异常一路冒到轮询循环 → 这一单**剩下的模板全没渲**,还得等 45 分钟退回重来。
所以:网络异常要么在重试里消化掉,要么返回「失败」让调用方按普通失败处理。
"""
url = CFG["server"].rstrip("/") + path
data = json.dumps(obj).encode("utf-8") if obj is not None else None
req = urllib.request.Request(url, data=data, method="POST" if data else "GET")
req.add_header("Content-Type", "application/json")
req.add_header("X-Worker-Token", CFG.get("token") or "")
last = None
for i in range(max(1, tries)):
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
body = r.read()
return (r.status, body if raw else json.loads(body))
except urllib.error.HTTPError as e:
return (e.code, e.read() if raw else {"ok": False, "error": "HTTP %d" % e.code})
except (urllib.error.URLError, OSError, ValueError) as e:
last = e
if i < tries - 1:
log("网络异常,%ds 后重试(第 %d/%d 次):%r" % (gap, i + 1, tries, e))
time.sleep(gap)
return (0, {"ok": False, "error": "网络异常 %r" % last})
# ---------------------------------------------------------------- Blender
def find_blender():
if CFG.get("blender") and os.path.exists(CFG["blender"]):
return CFG["blender"]
cands = []
for base in (r"<PROGRAM_DIR>", r"<PROGRAM_DIR>",
r"<PROGRAM_DIR>", r"<WIN_DIR>", r"<WIN_DIR>"):
if os.path.isdir(base):
for d in sorted(os.listdir(base), reverse=True):
p = os.path.join(base, d, "blender.exe")
if os.path.exists(p):
cands.append(p)
cands.append(os.path.join(base, d, "blender-launcher.exe"))
for p in cands:
if p.lower().endswith("blender.exe") and os.path.exists(p):
return p
return ""
# ===== 序号登记(金钻 2026-09-30:专门用一个文件存,不依赖文件夹)=====
# ⚠️ 以前靠扫文件夹名推序号 —— 文件夹一改名/挪地方序号就乱。
# 现在序号写在登记文件里,文件夹怎么动都不影响连续性。
SEQ_FILE_NAME = "_序号登记.json"
def seq_file():
return os.path.join(CFG["archive"], SEQ_FILE_NAME)
def _seed_seq_from_folders():
"""登记文件第一次用(或丢了)时,从老文件夹名估个起点,别从 001 重来。"""
n = 0
try:
for name in os.listdir(CFG["archive"]):
m = re.fullmatch(r"(\d{3})", name)
if m:
n = max(n, int(m.group(1)))
except OSError:
pass
return n
def next_seq(rec=None):
"""领一个新序号,写进登记文件。返回整数序号。
登记明细里记下:时间 / 来源 / 订单号 / 兑换码 / 模板 / 成品文件夹 / 分辨率 ——
「看号就知道是第几单、谁的单、出的哪个模板」。
写文件用 tmp + os.replace 原子替换,断电也不会写坏。
"""
os.makedirs(CFG["archive"], exist_ok=True)
p = seq_file()
d = {}
if os.path.exists(p):
try:
with open(p, encoding="utf-8") as f:
d = json.load(f) or {}
except Exception as e:
log("⚠️ 序号登记文件读不动(%r),按 0 起算" % e)
d = {}
if not isinstance(d.get("last"), int):
d["last"] = _seed_seq_from_folders()
d["_起点说明"] = "首次创建:按已有文件夹名估的起点"
n = int(d["last"]) + 1
d["last"] = n
r = dict(rec or {})
r.setdefault("序号", n)
r.setdefault("时间", time.strftime("%Y-%m-%d %H:%M:%S"))
d.setdefault("明细", []).append(r)
d["明细"] = d["明细"][-1000:] # 只留最近 1000 条,别把文件撑大
tmp = p + ".tmp"
try:
with open(tmp, "w", encoding="utf-8") as f:
json.dump(d, f, ensure_ascii=False, indent=1)
os.replace(tmp, p)
except OSError as e:
log("⚠️ 序号登记写失败:%r" % e)
return n
# ===== Blender 看门狗(金钻 2026-09-30:卡到十分钟就关掉重开再渲)=====
BLENDER_TIMEOUT = 600 # 单张 10 分钟;4096 实测 ~10 分钟内,够用
BLENDER_RETRY = 1 # 卡住就杀掉重开一次;再卡就判失败,别死循环
def _kill_tree(proc):
"""连子进程一起杀。Blender 会开子进程,只杀父进程会留孤儿继续吃 GPU。
Windows 用 taskkill /T 杀整棵树;其它平台 fallback 到 proc.kill()
—— 这样在 Linux 上也能跑测试。
"""
if os.name == "nt":
try:
subprocess.run(["taskkill", "/F", "/T", "/PID", str(proc.pid)],
capture_output=True, timeout=30)
return
except Exception as e:
log("⚠️ taskkill 失败 pid=%s:%r(改用 proc.kill)" % (proc.pid, e))
# POSIX:连**整个进程组**一起杀。
# 只 kill 父进程的话,子进程还活着占着 stdout 管道 → communicate() 白等 30 秒(实测踩过)
try:
os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
except Exception:
try:
proc.kill()
except Exception as e:
log("⚠️ 杀进程失败 pid=%s:%r" % (proc.pid, e))
SKIN_DIAG = [] # 最近几次渲染里"皮肤节点认了谁"的日志 —— 回传服务器,云端直接查
# (2026-10-01:空艇模板渲染出默认皮肤,只能远程到宿主翻日志才知道它挑了谁)
def note_skin_diag(tpl_key, out):
"""从 Blender 输出里挑出与"皮肤节点判定"有关的几行,留着回传。"""
for ln in (out or "").splitlines():
s = ln.strip()
if ("皮肤节点" in s) or ("贴图节点候选" in s) or s.startswith("皮肤 "):
SKIN_DIAG.append("[%s] %s" % (tpl_key, s[:220]))
if len(SKIN_DIAG) > 12:
del SKIN_DIAG[:-12]
# 从 Blender 的一行输出里抠进度:`Sample 12/128`、`Rendered 3/8 Tiles`… 抠不到就返回 None
_PCT_RES = [
re.compile(r"(?:Sample|Path Tracing Sample|Rendered|Rendering|Tiles)\D{0,20}?(\d+)\s*/\s*(\d+)"),
re.compile(r"(\d+)\s*/\s*(\d+)\s*(?:tiles|samples)", re.I),
]
def blender_pct(line):
"""Blender 那行输出 → 百分比;认不出来就 None(金钻 2026-10-04:进度要给买家看)。"""
if not line or "/" not in line:
return None
for rx in _PCT_RES:
m = rx.search(line)
if not m:
continue
try:
a, b = int(m.group(1)), int(m.group(2))
except ValueError:
continue
if b > 0 and 0 <= a <= b:
return int(a * 100.0 / b)
return None
def run_blender(cmd, timeout=None, retry=None, on_progress=None):
"""带超时看门狗的渲染。返回 (ok, 输出尾巴, 耗时秒, 说明)。
「关掉重新打开」= 直接重跑同一条命令 —— 工程每次都是**从干净模板新复制的副本**,
所以重开等于全新开始,能救掉偶发卡死(GPU 驱动抽风、贴图读挂等)。
on_progress(pct):渲的过程中有进度就回调(金钻 2026-10-04)。它在**读输出的线程**上跑,
所以:不许抛异常、不许阻塞太久(回调里已经有节流 + 超时)。
"""
timeout = timeout or BLENDER_TIMEOUT
retry = BLENDER_RETRY if retry is None else retry
t_all = time.time()
last = ""
for attempt in range(retry + 1):
try:
kw = {}
if os.name != "nt":
kw["start_new_session"] = True # 自成进程组,超时能整组杀干净
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True, encoding="utf-8", errors="replace", bufsize=1, **kw)
except OSError as e:
return False, "", time.time() - t_all, "启动 Blender 失败:%r" % e
# 输出交给**独立线程**读:一边攒全文,一边挑进度行回调。
# 主线程只负责等它结束 / 超时 —— 超时看门狗的行为和以前完全一样。
buf = []
def _pump():
try:
tail = ""
while True:
chunk = p.stdout.read(512)
if not chunk:
break
tail += chunk
# ⚠️ Blender 的进度条是**回车原地刷新**的(`... Sample 4/128\r`),
# 按"行"读(for line in stdout)压根读不到 —— 2026-10-04 金钻要
# 「按 blender 的完成度」才发现。所以这里 \n 和 \r 都当分隔符切。
while True:
cuts = [i for i in (tail.find("\n"), tail.find("\r")) if i >= 0]
if not cuts:
break
i = min(cuts)
line, tail = tail[:i + 1], tail[i + 1:]
buf.append(line)
if on_progress:
pct = blender_pct(line)
if pct is not None:
try:
on_progress(pct)
except Exception:
pass
if tail:
buf.append(tail)
except Exception:
pass
th = threading.Thread(target=_pump, daemon=True)
th.start()
try:
p.wait(timeout=timeout)
th.join(timeout=15)
out = "".join(buf)
if p.returncode == 0:
return True, out or "", time.time() - t_all, ""
# ⚠️ 以前只留 400 字,结果失败时看不到自己打的 FATAL 行(2026-10-01 查空艇报错时踩到)
_txt = (out or "").strip()
_keys = [ln.strip() for ln in _txt.splitlines()
if any(k in ln for k in ("FATAL", "MAKE-ORDER", "Error", "Traceback", "错误"))]
last = "Blender 退出码 %s:%s" % (
p.returncode,
(" | ".join(_keys[-6:]) + " | " if _keys else "") + _txt[-1200:])
log("渲染失败:%s" % last)
except subprocess.TimeoutExpired:
log("⚠️ 渲染卡住超过 %d 秒 —— 杀掉,重新打开再渲" % timeout)
_kill_tree(p)
try:
p.wait(timeout=10) # 收尸;整组杀过就该立刻返回
except Exception:
pass
last = "渲染卡住超过 %d 秒(已杀掉重开)" % timeout
if attempt < retry:
log("↻ 重开渲染(第 %d 次尝试)" % (attempt + 2))
return False, "", time.time() - t_all, last
def render_one(tpl_key, skin_path, order_meta, res=DEFAULT_RES, arm="auto", on_progress=None):
"""渲染一张,返回 (成功?, png路径 或 错误信息)
arm:这张皮肤的臂型(auto/classic/slim)。多皮肤单里**每张皮肤各自一个臂型**,
由调用方从服务器给的皮肤清单里带下来(金钻 2026-10-01:以前压根没传,买家手改无效)。
"""
fname = TEMPLATES.get(tpl_key)
if not fname:
return False, "未知模板 key:%s" % tpl_key
tpl = os.path.join(CFG["tpl_root"], fname)
if not os.path.exists(tpl):
return False, "模板文件不存在:%s" % tpl
blender = find_blender()
if not blender:
return False, "找不到 blender.exe(请在 config.json 里指定 blender 路径)"
if not os.path.exists(CFG["make_order"]):
return False, "找不到 make_order.py:%s" % CFG["make_order"]
out_name = tpl_base(tpl_key)
# 文件夹用成品名,皮肤先放进去;工程走临时目录,渲完删(金钻:不留 .blend)
order_dir, base = prepare_out_dir(CFG["archive"], tpl_key, res, skin_path)
cmd = [blender, "-b", "--factory-startup", "--python", CFG["make_order"], "--",
"--template", tpl, "--skin", skin_path, "--arm", arm or "auto",
"--orders-dir", CFG["archive"], "--out-dir", order_dir, "--res", str(int(res))]
# 某个模板的皮肤材质名固定不下来时,可以在 config.json 里钉死:
# "skin_materials": {"airship": "材质名"}
# (2026-10-01:空艇模板自动找皮肤节点找错,先留好这个后门口子)
_sm = (CFG.get("skin_materials") or {}).get(tpl_key)
if _sm:
cmd += ["--skin-material", _sm]
log("渲染 %s(模板 %s,臂型 %s)" % (tpl_key, fname, arm or "auto"))
okr, tail, dt, note = run_blender(cmd, on_progress=on_progress)
note_skin_diag(tpl_key, tail) # 不管成没成,先把"皮肤节点认了谁"记下来
if not okr:
return False, note
# 找成品:优先 <名称>.png(命名规则见 out_base),其次目录里最新的 png
cand = os.path.join(order_dir, base + ".png")
if not os.path.exists(cand):
pngs = [f for f in os.listdir(order_dir) if f.lower().endswith(".png")]
pngs = [f for f in pngs if "无压缩" not in f and f != "1000.png"] or pngs
if not pngs:
return False, "渲染完成但没找到 png(看 %s)" % order_dir
cand = os.path.join(order_dir, sorted(pngs, key=lambda f: os.path.getmtime(
os.path.join(order_dir, f)))[-1])
# 渲染成功才领序号(失败的图不占号),并登记进专门的文件
seq = next_seq({
"来源": "网页订单",
"订单号": order_meta.get("oid"),
"兑换码": order_meta.get("codes") or [],
"模板": out_name,
"成品文件夹": os.path.basename(order_dir),
"分辨率": res,
"耗时秒": round(dt, 1),
})
# 金钻要的留档:时间 / 序号 / 兑换码
info = {
"序号": seq,
"订单号": order_meta.get("oid"),
"兑换码": order_meta.get("codes") or [],
"模板": out_name,
"模板key": tpl_key,
"成品文件夹": os.path.basename(order_dir),
"分辨率": res,
"皮肤文件": "skin.png",
"客户提交时间": order_meta.get("created"),
"渲染完成时间": datetime.now().isoformat(timespec="seconds"),
"渲染耗时秒": round(dt, 1),
"手臂规格": (arm if arm and arm != "auto" else order_meta.get("arm")),
"条款版本": order_meta.get("terms_v") or TERMS_VERSION,
}
try:
with open(os.path.join(order_dir, "订单信息.json"), "w", encoding="utf-8") as f:
json.dump(info, f, ensure_ascii=False, indent=1)
except OSError as e:
log("写 订单信息.json 失败:%r" % e)
# 无压缩版(make_order 默认就会生成):<名称>无压缩版.png
unc = os.path.join(order_dir, out_base(tpl_key, res) + UNC_SUFFIX + ".png")
if not os.path.exists(unc):
cands = [f for f in sorted(os.listdir(order_dir))
if f.lower().endswith(".png") and UNC_SUFFIX in f]
unc = os.path.join(order_dir, cands[0]) if cands else None
if not unc or not os.path.exists(unc):
unc = None
log("⚠️ 无压缩版没生成,这次只交标准版")
log("完成 %s → %s(序号 %03d,%.1fs,%s)" % (tpl_key, cand, seq, dt, "两张" if unc else "一张"))
return True, {"std": cand, "unc": unc, "seq": seq, "sec": round(dt, 1)}
# seq = 留档序号(小票/订单信息里印);sec = 这张渲了多久(服务器拿它估下一单的时间)
def deliver_names_for(skin_i, tk, res, dedup=True):
"""第 skin_i 张皮肤、模板 tk 的交付名。
⚠️ 只有**同一个模板被多张皮肤用到**时才需要加 -2/-3(不加会在服务器同一个目录里互相覆盖)。
不同皮肤用不同模板(金钻的常见用法:A 出麦田、B 出樱花)就保持干净的名字。
"""
sn, un = deliver_names(tk, res)
if skin_i <= 0 or not dedup:
return sn, un
k = "-%d" % (skin_i + 1)
def ins(n):
return (n[:-4] + k + ".png") if n.lower().endswith(".png") else (n + k)
return ins(sn), ins(un)
def handle_order(o):
oid = o["oid"]
tpls = o.get("templates") or []
order_res = int(o.get("res") or CFG.get("res") or DEFAULT_RES)
log("领到订单 %s:%d 张 %s" % (oid, len(tpls), ",".join(tpls)))
# ---- 皮肤清单(金钻 2026-10-01:多皮肤单 = **每张皮肤 × 每个模板**出图)----
# 服务器在 /claim 里把清单带下来:[{id,fileName,arm}]。老单没有就按 1 张算。
skins = o.get("skins") or [{"id": "s1", "fileName": "skin.png", "arm": "auto"}]
tpls = o.get("templates") or []
order_res = int(o.get("res") or CFG.get("res") or DEFAULT_RES)
# 只重渲勾选的那几张(金钻 2026-10-04:「不需要重渲的就不用再重渲了,费力不讨好」)
# 服务器给了清单就只干这几个模板 —— 换皮肤时清单是空的,那就还是整单重出。
redo_tpls = [t for t in (o.get("redo_tpls") or []) if t]
if redo_tpls:
for sk in skins:
sk["tpls"] = [t for t in (sk.get("tpls") or tpls) if t in redo_tpls]
log("这一单只重渲:%s" % "、".join(redo_tpls))
# ⚠️ 张数 = **各皮肤自己挑的模板加起来**(金钻 2026-10-01:不是乘法)
# ⚠️ 只重渲一部分时,total 要**加上保留下来的那几张** —— 服务器是按 total 判断"收满了"的,
# 少了这个数就会在最后一张还没传完时提前标完成(2026-10-04 自测踩到,少了一张无压缩版)。
_keep = int(o.get("keep_n") or 0) if redo_tpls else 0
plan = _keep + sum(len(sk.get("tpls") or tpls) for sk in skins) * 2
log("领到订单 %s:%d 张皮肤,共 %d 张图(%s)"
% (oid, len(skins), plan // 2,
"; ".join("%s→%s" % (sk.get("fileName") or "?", "、".join(sk.get("tpls") or tpls))
for sk in skins)))
work = os.path.join(HERE, "work")
os.makedirs(work, exist_ok=True)
# 同一个模板被多张皮肤用到 → 交付名才加 -2/-3(不同模板就保持干净名字)
cnt = {}
for _sk in skins:
for _tk in (_sk.get("tpls") or tpls):
cnt[_tk] = cnt.get(_tk, 0) + 1
dup_tpls = set(k for k, n in cnt.items() if n > 1)
# ---- 进度上报(金钻 2026-10-04:买家要看得见渲到哪了)----
# 报进度**绝不能影响出图**:节流 2 秒一次,失败一律吞掉。
def report_progress(idx, total, pct, tpl=""):
try:
http("/progress", {"oid": oid, "idx": idx, "total": total,
"pct": pct, "tpl": tpl}, timeout=20)
except Exception:
pass
ok_n, errs = 0, []
img_i = 0
for si, sk in enumerate(skins):
sid = sk.get("id") or ("s%d" % (si + 1))
# 每张皮肤各自下载、各自臂型(A 可能粗臂、B 可能细臂)
skin = os.path.join(work, "skin_%s_%s.png" % (oid, sid))
st, data = http("/skin/%s/%s" % (oid, sid), raw=True, timeout=60)
if st != 200 or not data:
errs.append("皮肤 %s:服务器取皮肤失败 HTTP %s" % (sid, st))
log("皮肤 %s 取不下来 HTTP %s" % (sid, st))
continue
with open(skin, "wb") as f:
f.write(data)
arm = (sk.get("arm") or "auto")
# 这张皮肤**只出它自己挑的模板**(没写就退回订单级那份,兼容老单)
for tk in (sk.get("tpls") or tpls):
img_i += 1
_last = [0.0]
def _prog(pct, _tk=tk, _i=img_i, _last=_last):
t = time.time()
if pct < 100 and t - _last[0] < 2.0: # 节流:2 秒最多报一次
return
_last[0] = t
report_progress(_i, plan // 2, pct, _tk)
report_progress(img_i, plan // 2, 0, tk) # 这张开始了
try:
ok, res = render_one(tk, skin, o, order_res, arm=arm, on_progress=_prog)
except subprocess.TimeoutExpired:
ok, res = False, "渲染超时(看门狗已重开过一次仍卡住)"
except Exception as e:
ok, res = False, "异常 %r" % e
if not ok:
errs.append("%s(皮肤%d):%s" % (tk, si + 1, res))
log("失败 %s" % res)
continue
# 一张模板交两个文件:标准压缩 + 无压缩版(金钻:两张都发顾客)
sn, un = deliver_names_for(si, tk, order_res, dedup=(tk in dup_tpls))
files = [("标准压缩", sn, res.get("std")),
("无压缩(16bit)", un, res.get("unc"))]
for kind, name, path in files:
if not path:
continue
try:
with open(path, "rb") as f:
png = base64.b64encode(f.read()).decode()
except OSError as e:
errs.append("%s(%s):读图失败 %r" % (tk, kind, e))
continue
# 一次一个文件回传;total = 这一单最终会交回的文件总数
# tries=3:图上一次上传要几 MB~十几 MB,网络抖一下很常见,别为这个白渲一遍
st, j = http("/finish", {"oid": oid, "total": plan,
"results": [{"tpl": tk, "name": name, "png": png,
"kind": kind, "skin": sid,
# 耗时只跟「标准压缩」报一次:两个文件报两遍会把样本记重
"sec": (res.get("sec") if kind == "标准压缩" else None),
"seq": res.get("seq")}]},
timeout=300, tries=3, gap=8)
if st == 200 and j.get("ok"):
log("回传 %s 皮肤%s [%s](服务器已收 %s / 计划 %d)"
% (tk, sid, kind, j.get("n"), plan))
else:
errs.append("%s-%s:回传失败 %s" % (tk, kind, (j or {}).get("error")))
ok_n += 1
if ok_n == 0:
http("/fail", {"oid": oid, "note": ("全部渲染失败:" + ";".join(errs))[:280],
"diag": SKIN_DIAG[:8], "log_tail": "\n".join(errs)[-3800:]})
log("订单 %s 全部失败" % oid)
return
# ⚠️ 有失败时必须有始有终:否则 files < total,单子会永远卡在 working,
# 45 分钟后被当成"渲染机中断"退回队列 → 无限重试。这里显式收单。
http("/finish", {"oid": oid, "close": True, "diag": SKIN_DIAG[:8],
"note": ("部分失败:" + ";".join(errs))[:280] if errs else "",
"results": []}, tries=3, gap=8)
log("订单 %s 处理完毕:成功 %d/%d%s" % (oid, ok_n, len(tpls), "(有失败)" if errs else ""))
def single_instance():
s = socket.socket()
try:
s.bind(("localhost", LOCK_PORT))
s.listen(1)
return s
except OSError:
return None
def main():
load_cfg()
once = "--once" in sys.argv # 只跑一轮就退出(手动补单 / 测试用)
if not once:
lock = single_instance()
if not lock:
log("已经有一个 worker 在跑了,这次退出")
return
log("渲染机上线 | 服务器 %s | 模板目录 %s | 留档 %s"
% (CFG["server"], CFG["tpl_root"], CFG["archive"]))
host = socket.gethostname()
# 心跳(在线检查)与领单**分开计时**:
# 心跳 = 服务器判断"渲染机还在不在"的唯一依据,也是唯一会造成误判的地方;
# 领单 = 买家体验,慢一分钟买家就多等一分钟。
# 默认心跳 **600 秒(10 分钟)**(金钻 9-30:有人来了网页会立刻查一次,所以不用频繁上报)。
# ⚠️ 代价:渲染机真的挂了,最长要 25 分钟才判定为离线(见服务器 OFFLINE_AFTER)。
# 启动时会立刻发一次心跳,所以"金钻刚开机"这种情形是即时准的。
hb_every = int(CFG.get("hb_every") or 600) # 在线检查 10 分钟一次(金钻 9-30 定)
poll = int(CFG.get("poll") or 20)
# ⚠️⚠️ 心跳必须**自己一个线程**(金钻 2026-10-01 反馈:「开着电脑还显示设备离线,刷几次才正常」)。
# 原来心跳和领单/渲染挤在同一个循环里 —— 一渲就是几十秒到十几分钟(4096 要 10 分钟),
# 这期间心跳发不出去;要是连着几单、或某次上传卡住,超过服务器 OFFLINE_AFTER(1500 秒)
# 就被判「离线」,**电脑明明开着、还在干活**。
def hb_loop():
while True:
try:
st, j = http("/hb", {"host": host}, timeout=30)
if st != 200:
log("心跳失败 HTTP %s" % st)
except Exception:
log("心跳异常:\n" + traceback.format_exc()[-400:])
time.sleep(hb_every)
threading.Thread(target=hb_loop, daemon=True).start()
while True:
try:
st, o = http("/claim", {}, timeout=60)
if st == 403:
log("令牌不对(config.json 里的 token 要跟服务器 worker_token 一致)")
time.sleep(300)
continue
if st == 200 and o.get("order"):
handle_order(o["order"])
except Exception:
log("轮询异常:\n" + traceback.format_exc()[-800:])
if once:
log("--once:跑完这一轮就退出")
return
time.sleep(poll)
if __name__ == "__main__":
main()