Some checks failed
build-images / web (push) Has been cancelled
vision2026-ci / Python SDK resource tests (push) Has been cancelled
build-images / api (push) Has been cancelled
build-images / worker-gpu (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Has been cancelled
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Has been cancelled
codeql / Analyze (javascript-typescript) (push) Has been cancelled
codeql / Analyze (python) (push) Has been cancelled
perf / API hot-path micro-smoke (budgeted) (push) Has been cancelled
perf / Desktop engine crates (release build check) (push) Has been cancelled
vision2026-ci / API phase modules (ruff + pytest) (push) Has been cancelled
vision2026-ci / Alembic upgrade + drift check (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Has been cancelled
Paid, hosted product at menivor.com, now retired as a company project. Fresh squashed history of the cleaned working tree (secret-scanned, no .env, no customer data, no outreach logs). Built on MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
278 lines
9.0 KiB
Python
278 lines
9.0 KiB
Python
import ast
|
||
import copy
|
||
import threading
|
||
from abc import ABC, abstractmethod
|
||
|
||
from app.config import config
|
||
from app.models import const
|
||
|
||
|
||
_PATCH_EXISTING_TASK_SCRIPT = """
|
||
if redis.call("EXISTS", KEYS[1]) == 0 then
|
||
return 0
|
||
end
|
||
|
||
for index = 1, #ARGV, 2 do
|
||
redis.call("HSET", KEYS[1], ARGV[index], ARGV[index + 1])
|
||
end
|
||
|
||
return 1
|
||
"""
|
||
|
||
|
||
# Base class for state management
|
||
class BaseState(ABC):
|
||
@abstractmethod
|
||
def update_task(self, task_id: str, state: int, progress: int = 0, **kwargs):
|
||
pass
|
||
|
||
@abstractmethod
|
||
def get_task(self, task_id: str):
|
||
pass
|
||
|
||
@abstractmethod
|
||
def get_all_tasks(self, page: int, page_size: int):
|
||
pass
|
||
|
||
@abstractmethod
|
||
def get_all_task_ids(self) -> list:
|
||
"""
|
||
返回当前所有任务 ID 的一次性稳定快照。
|
||
|
||
与 `get_all_tasks` 的分页接口不同,这个方法只扫描一次、不切页,
|
||
供需要“整批处理一次”的调用方(例如进程重启后的发布状态恢复)
|
||
使用,避免多次独立分页调用之间因为 key 增删导致的遗漏或重复。
|
||
"""
|
||
pass
|
||
|
||
@abstractmethod
|
||
def patch_task(self, task_id: str, **kwargs) -> bool:
|
||
"""只更新已有任务的指定字段;任务不存在时返回 False。"""
|
||
pass
|
||
|
||
|
||
# Memory state management
|
||
class MemoryState(BaseState):
|
||
def __init__(self):
|
||
self._tasks = {}
|
||
self._lock = threading.RLock()
|
||
|
||
def get_all_tasks(self, page: int, page_size: int):
|
||
start = (page - 1) * page_size
|
||
end = start + page_size
|
||
with self._lock:
|
||
tasks = [copy.deepcopy(task) for task in self._tasks.values()]
|
||
total = len(tasks)
|
||
return tasks[start:end], total
|
||
|
||
def get_all_task_ids(self) -> list:
|
||
with self._lock:
|
||
return list(self._tasks.keys())
|
||
|
||
def update_task(
|
||
self,
|
||
task_id: str,
|
||
state: int = const.TASK_STATE_PROCESSING,
|
||
progress: int = 0,
|
||
**kwargs,
|
||
):
|
||
progress = int(progress)
|
||
if progress > 100:
|
||
progress = 100
|
||
|
||
with self._lock:
|
||
self._tasks[task_id] = {
|
||
"task_id": task_id,
|
||
"state": state,
|
||
"progress": progress,
|
||
**kwargs,
|
||
}
|
||
|
||
def get_task(self, task_id: str):
|
||
with self._lock:
|
||
task = self._tasks.get(task_id, None)
|
||
return copy.deepcopy(task) if task is not None else None
|
||
|
||
def patch_task(self, task_id: str, **kwargs) -> bool:
|
||
# 异步发布只应补充发布状态,不能覆盖已经保存的视频、字幕等结果。
|
||
# 在同一把锁内完成存在性判断和字段合并,也可避免任务删除后
|
||
# 被后台线程重建。
|
||
with self._lock:
|
||
task = self._tasks.get(task_id)
|
||
if task is None:
|
||
return False
|
||
task.update(copy.deepcopy(kwargs))
|
||
return True
|
||
|
||
def delete_task(self, task_id: str):
|
||
with self._lock:
|
||
self._tasks.pop(task_id, None)
|
||
|
||
|
||
# Redis state management
|
||
class RedisState(BaseState):
|
||
"""
|
||
Redis-backed task state.
|
||
|
||
Trust boundary: Redis is expected to be private to this application. Task
|
||
values are written by MoneyPrinterTurbo and converted back from strings for
|
||
compatibility with existing state records. Do not expose this Redis database
|
||
to untrusted writers without replacing deserialization with a stricter
|
||
schema-based format.
|
||
"""
|
||
|
||
def __init__(self, host="localhost", port=6379, db=0, password=None):
|
||
import redis
|
||
|
||
self._redis = redis.StrictRedis(host=host, port=port, db=db, password=password)
|
||
|
||
def get_all_tasks(self, page: int, page_size: int):
|
||
start = (page - 1) * page_size
|
||
end = start + page_size
|
||
|
||
# Redis SCAN 不保证遍历顺序稳定:同一次 SCAN 内可能重复返回同一个
|
||
# key,哈希表 rehash 或 key 增删后,两次独立调用也可能看到完全不同
|
||
# 的遍历顺序。如果直接按批次累积切页(旧实现),分页结果会在两次
|
||
# 调用之间重复展示或漏掉某个任务(见 issue #1408:3 条任务、
|
||
# page_size=2,两次扫描顺序不同导致一条重复、一条遗漏)。
|
||
#
|
||
# 这里先用一次完整 SCAN 收集所有 Hash key 并去重,再按 key 排序得到
|
||
# 一个与 SCAN 遍历顺序无关的稳定顺序。只要任务集合在两次调用之间
|
||
# 没有变化,不同页的切片结果就完全一致、不重不漏;扫描期间新增或
|
||
# 删除的任务按惯例在下一次分页/恢复周期生效。
|
||
task_ids = self._scan_task_ids()
|
||
total = len(task_ids)
|
||
|
||
tasks = []
|
||
for key in task_ids[start:end]:
|
||
task_data = self._redis.hgetall(key)
|
||
if not task_data:
|
||
# key 在本次 SCAN 之后、HGETALL 之前被删除,跳过即可,
|
||
# 不应该让整页请求失败。
|
||
continue
|
||
task = {
|
||
k.decode("utf-8"): self._convert_to_original_type(v)
|
||
for k, v in task_data.items()
|
||
}
|
||
tasks.append(task)
|
||
return tasks, total
|
||
|
||
def get_all_task_ids(self) -> list:
|
||
"""返回一次完整 SCAN 得到的、去重排序后的任务 ID 字符串列表。"""
|
||
return [key.decode("utf-8") for key in self._scan_task_ids()]
|
||
|
||
# SCAN 的 COUNT 只是每批返回数量的提示,不影响正确性;用一个比常见
|
||
# page_size 更大的固定值,减少一次完整扫描所需的往返次数。
|
||
_SCAN_BATCH_HINT = 1000
|
||
|
||
def _scan_task_ids(self) -> list[bytes]:
|
||
"""对任务 Hash key 做一次完整 SCAN,去重并按稳定顺序排序。"""
|
||
seen: set[bytes] = set()
|
||
cursor = 0
|
||
while True:
|
||
# Redis 数据库中除了任务 Hash,还可能存在 RedisTaskManager 使用的
|
||
# List 队列。只扫描 Hash 可以避免对队列执行 HGETALL 时触发
|
||
# WRONGTYPE,同时保证 total 只统计真正的任务记录。
|
||
cursor, keys = self._redis.scan(
|
||
cursor,
|
||
count=self._SCAN_BATCH_HINT,
|
||
_type="HASH",
|
||
)
|
||
seen.update(keys)
|
||
if cursor == 0:
|
||
break
|
||
return sorted(seen)
|
||
|
||
def update_task(
|
||
self,
|
||
task_id: str,
|
||
state: int = const.TASK_STATE_PROCESSING,
|
||
progress: int = 0,
|
||
**kwargs,
|
||
):
|
||
progress = int(progress)
|
||
if progress > 100:
|
||
progress = 100
|
||
|
||
fields = {
|
||
"task_id": task_id,
|
||
"state": state,
|
||
"progress": progress,
|
||
**kwargs,
|
||
}
|
||
|
||
for field, value in fields.items():
|
||
self._redis.hset(task_id, field, str(value))
|
||
|
||
def get_task(self, task_id: str):
|
||
task_data = self._redis.hgetall(task_id)
|
||
if not task_data:
|
||
return None
|
||
|
||
task = {
|
||
key.decode("utf-8"): self._convert_to_original_type(value)
|
||
for key, value in task_data.items()
|
||
}
|
||
return task
|
||
|
||
def patch_task(self, task_id: str, **kwargs) -> bool:
|
||
if not kwargs:
|
||
return False
|
||
|
||
arguments = []
|
||
for field, value in kwargs.items():
|
||
arguments.extend((field, str(value)))
|
||
|
||
# EXISTS 和 HSET 如果分成两条命令,后台发布线程与删除请求并发时,
|
||
# HSET 可能在删除后重新创建一条残缺任务。Lua 脚本由 Redis 原子执行,
|
||
# 可以保证任务不存在时不写入,且不会改变现有字段之外的数据。
|
||
updated = self._redis.eval(
|
||
_PATCH_EXISTING_TASK_SCRIPT,
|
||
1,
|
||
task_id,
|
||
*arguments,
|
||
)
|
||
return bool(updated)
|
||
|
||
def delete_task(self, task_id: str):
|
||
self._redis.delete(task_id)
|
||
|
||
@staticmethod
|
||
def _convert_to_original_type(value):
|
||
"""
|
||
Convert values written by this application back to common Python types.
|
||
|
||
This compatibility parser assumes Redis is inside the application's
|
||
trust boundary. If Redis can be written by untrusted clients, task state
|
||
should move to a strict JSON/schema parser instead of open-ended literal
|
||
conversion.
|
||
"""
|
||
value_str = value.decode("utf-8")
|
||
|
||
try:
|
||
# try to convert byte string array to list
|
||
return ast.literal_eval(value_str)
|
||
except (ValueError, SyntaxError):
|
||
pass
|
||
|
||
if value_str.isdigit():
|
||
return int(value_str)
|
||
# Add more conversions here if needed
|
||
return value_str
|
||
|
||
|
||
# Global state
|
||
_enable_redis = config.app.get("enable_redis", False)
|
||
_redis_host = config.app.get("redis_host", "localhost")
|
||
_redis_port = config.app.get("redis_port", 6379)
|
||
_redis_db = config.app.get("redis_db", 0)
|
||
_redis_password = config.app.get("redis_password", None)
|
||
|
||
state = (
|
||
RedisState(
|
||
host=_redis_host, port=_redis_port, db=_redis_db, password=_redis_password
|
||
)
|
||
if _enable_redis
|
||
else MemoryState()
|
||
)
|