task_db.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. """
  2. MinerU Tianshu - SQLite Task Database Manager
  3. 天枢任务数据库管理器
  4. 负责任务的持久化存储、状态管理和原子性操作
  5. """
  6. import sqlite3
  7. import json
  8. import uuid
  9. from contextlib import contextmanager
  10. from typing import Optional, List, Dict
  11. from pathlib import Path
  12. class TaskDB:
  13. """任务数据库管理类"""
  14. def __init__(self, db_path='mineru_tianshu.db'):
  15. self.db_path = db_path
  16. self._init_db()
  17. def _get_conn(self):
  18. """获取数据库连接(每次创建新连接,避免 pickle 问题)"""
  19. conn = sqlite3.connect(
  20. self.db_path,
  21. check_same_thread=False,
  22. timeout=30.0
  23. )
  24. conn.row_factory = sqlite3.Row
  25. return conn
  26. @contextmanager
  27. def get_cursor(self):
  28. """上下文管理器,自动提交和错误处理"""
  29. conn = self._get_conn()
  30. cursor = conn.cursor()
  31. try:
  32. yield cursor
  33. conn.commit()
  34. except Exception as e:
  35. conn.rollback()
  36. raise e
  37. finally:
  38. conn.close() # 关闭连接
  39. def _init_db(self):
  40. """初始化数据库表"""
  41. with self.get_cursor() as cursor:
  42. cursor.execute('''
  43. CREATE TABLE IF NOT EXISTS tasks (
  44. task_id TEXT PRIMARY KEY,
  45. file_name TEXT NOT NULL,
  46. file_path TEXT,
  47. status TEXT DEFAULT 'pending',
  48. priority INTEGER DEFAULT 0,
  49. backend TEXT DEFAULT 'pipeline',
  50. options TEXT,
  51. result_path TEXT,
  52. error_message TEXT,
  53. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  54. started_at TIMESTAMP,
  55. completed_at TIMESTAMP,
  56. worker_id TEXT,
  57. retry_count INTEGER DEFAULT 0
  58. )
  59. ''')
  60. # 创建索引加速查询
  61. cursor.execute('CREATE INDEX IF NOT EXISTS idx_status ON tasks(status)')
  62. cursor.execute('CREATE INDEX IF NOT EXISTS idx_priority ON tasks(priority DESC)')
  63. cursor.execute('CREATE INDEX IF NOT EXISTS idx_created_at ON tasks(created_at)')
  64. cursor.execute('CREATE INDEX IF NOT EXISTS idx_worker_id ON tasks(worker_id)')
  65. def create_task(self, file_name: str, file_path: str,
  66. backend: str = 'pipeline', options: dict = None,
  67. priority: int = 0) -> str:
  68. """
  69. 创建新任务
  70. Args:
  71. file_name: 文件名
  72. file_path: 文件路径
  73. backend: 处理后端 (pipeline/vlm-transformers/vlm-vllm-engine)
  74. options: 处理选项 (dict)
  75. priority: 优先级,数字越大越优先
  76. Returns:
  77. task_id: 任务ID
  78. """
  79. task_id = str(uuid.uuid4())
  80. with self.get_cursor() as cursor:
  81. cursor.execute('''
  82. INSERT INTO tasks (task_id, file_name, file_path, backend, options, priority)
  83. VALUES (?, ?, ?, ?, ?, ?)
  84. ''', (task_id, file_name, file_path, backend, json.dumps(options or {}), priority))
  85. return task_id
  86. def get_next_task(self, worker_id: str) -> Optional[Dict]:
  87. """
  88. 获取下一个待处理任务(原子操作,防止并发冲突)
  89. Args:
  90. worker_id: Worker ID
  91. Returns:
  92. task: 任务字典,如果没有任务返回 None
  93. """
  94. with self.get_cursor() as cursor:
  95. # 使用事务确保原子性
  96. cursor.execute('BEGIN IMMEDIATE')
  97. # 按优先级和创建时间获取任务
  98. cursor.execute('''
  99. SELECT * FROM tasks
  100. WHERE status = 'pending'
  101. ORDER BY priority DESC, created_at ASC
  102. LIMIT 1
  103. ''')
  104. task = cursor.fetchone()
  105. if task:
  106. # 立即标记为 processing
  107. cursor.execute('''
  108. UPDATE tasks
  109. SET status = 'processing',
  110. started_at = CURRENT_TIMESTAMP,
  111. worker_id = ?
  112. WHERE task_id = ?
  113. ''', (worker_id, task['task_id']))
  114. return dict(task)
  115. return None
  116. def update_task_status(self, task_id: str, status: str,
  117. result_path: str = None, error_message: str = None):
  118. """
  119. 更新任务状态
  120. Args:
  121. task_id: 任务ID
  122. status: 新状态 (pending/processing/completed/failed/cancelled)
  123. result_path: 结果路径(可选)
  124. error_message: 错误信息(可选)
  125. """
  126. with self.get_cursor() as cursor:
  127. updates = ['status = ?']
  128. params = [status]
  129. if status == 'completed':
  130. updates.append('completed_at = CURRENT_TIMESTAMP')
  131. if result_path:
  132. updates.append('result_path = ?')
  133. params.append(result_path)
  134. if status == 'failed' and error_message:
  135. updates.append('error_message = ?')
  136. params.append(error_message)
  137. updates.append('completed_at = CURRENT_TIMESTAMP')
  138. params.append(task_id)
  139. cursor.execute(f'''
  140. UPDATE tasks SET {', '.join(updates)}
  141. WHERE task_id = ?
  142. ''', params)
  143. def get_task(self, task_id: str) -> Optional[Dict]:
  144. """
  145. 查询任务详情
  146. Args:
  147. task_id: 任务ID
  148. Returns:
  149. task: 任务字典,如果不存在返回 None
  150. """
  151. with self.get_cursor() as cursor:
  152. cursor.execute('SELECT * FROM tasks WHERE task_id = ?', (task_id,))
  153. task = cursor.fetchone()
  154. return dict(task) if task else None
  155. def get_queue_stats(self) -> Dict[str, int]:
  156. """
  157. 获取队列统计信息
  158. Returns:
  159. stats: 各状态的任务数量
  160. """
  161. with self.get_cursor() as cursor:
  162. cursor.execute('''
  163. SELECT status, COUNT(*) as count
  164. FROM tasks
  165. GROUP BY status
  166. ''')
  167. stats = {row['status']: row['count'] for row in cursor.fetchall()}
  168. return stats
  169. def get_tasks_by_status(self, status: str, limit: int = 100) -> List[Dict]:
  170. """
  171. 根据状态获取任务列表
  172. Args:
  173. status: 任务状态
  174. limit: 返回数量限制
  175. Returns:
  176. tasks: 任务列表
  177. """
  178. with self.get_cursor() as cursor:
  179. cursor.execute('''
  180. SELECT * FROM tasks
  181. WHERE status = ?
  182. ORDER BY created_at DESC
  183. LIMIT ?
  184. ''', (status, limit))
  185. return [dict(row) for row in cursor.fetchall()]
  186. def cleanup_old_tasks(self, days: int = 7):
  187. """
  188. 清理旧任务记录
  189. Args:
  190. days: 保留最近N天的任务
  191. """
  192. with self.get_cursor() as cursor:
  193. cursor.execute('''
  194. DELETE FROM tasks
  195. WHERE completed_at < datetime('now', '-' || ? || ' days')
  196. AND status IN ('completed', 'failed')
  197. ''', (days,))
  198. deleted_count = cursor.rowcount
  199. return deleted_count
  200. def reset_stale_tasks(self, timeout_minutes: int = 60):
  201. """
  202. 重置超时的 processing 任务为 pending
  203. Args:
  204. timeout_minutes: 超时时间(分钟)
  205. """
  206. with self.get_cursor() as cursor:
  207. cursor.execute('''
  208. UPDATE tasks
  209. SET status = 'pending',
  210. worker_id = NULL,
  211. retry_count = retry_count + 1
  212. WHERE status = 'processing'
  213. AND started_at < datetime('now', '-' || ? || ' minutes')
  214. ''', (timeout_minutes,))
  215. reset_count = cursor.rowcount
  216. return reset_count
  217. if __name__ == '__main__':
  218. # 测试代码
  219. db = TaskDB('test_tianshu.db')
  220. # 创建测试任务
  221. task_id = db.create_task(
  222. file_name='test.pdf',
  223. file_path='/tmp/test.pdf',
  224. backend='pipeline',
  225. options={'lang': 'ch', 'formula_enable': True},
  226. priority=1
  227. )
  228. print(f"Created task: {task_id}")
  229. # 查询任务
  230. task = db.get_task(task_id)
  231. print(f"Task details: {task}")
  232. # 获取统计
  233. stats = db.get_queue_stats()
  234. print(f"Queue stats: {stats}")
  235. # 清理测试数据库
  236. Path('test_tianshu.db').unlink(missing_ok=True)
  237. print("Test completed!")