routes.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. """HTTP orchestration boundary for data-research ingestion jobs."""
  2. from __future__ import annotations
  3. import logging
  4. from flask import g, jsonify, request
  5. from app import db
  6. from app.api.data_development import bp
  7. from app.core.data_research.errors import DataResearchError
  8. from app.models.result import failed, success
  9. logger = logging.getLogger(__name__)
  10. def get_ingestion_service():
  11. from app.core.data_research.ingestion import IngestionService
  12. from app.core.data_research.repository import SqlAlchemyIngestionJobRepository
  13. return IngestionService(
  14. SqlAlchemyIngestionJobRepository(db.session),
  15. commit=db.session.commit,
  16. rollback=db.session.rollback,
  17. )
  18. def _identity():
  19. return getattr(g, "current_user", {}) or {}
  20. def _record(record):
  21. return {
  22. "uid": str(record.uid),
  23. "source_uid": str(record.source_uid),
  24. "artifact_uid": str(record.artifact_uid) if record.artifact_uid else None,
  25. "job_type": record.job_type,
  26. "parser_version": record.parser_version,
  27. "status": record.status,
  28. "parameters": dict(record.parameters or {}),
  29. "statistics": dict(record.statistics or {}),
  30. "last_error": record.last_error,
  31. "actor_uid": record.actor_uid,
  32. "created_at": record.created_at.isoformat() if record.created_at else None,
  33. "updated_at": record.updated_at.isoformat() if record.updated_at else None,
  34. "started_at": record.started_at.isoformat() if record.started_at else None,
  35. "finished_at": record.finished_at.isoformat() if record.finished_at else None,
  36. }
  37. def _error(error):
  38. if isinstance(error, DataResearchError):
  39. return (
  40. jsonify(
  41. failed(
  42. str(error),
  43. code=error.http_status,
  44. error={"code": error.code},
  45. )
  46. ),
  47. error.http_status,
  48. )
  49. logger.exception("data-research ingestion request failed")
  50. return (
  51. jsonify(
  52. failed(
  53. "数据采集任务处理失败",
  54. code=500,
  55. error={"code": "DATA_RESEARCH_ERROR"},
  56. )
  57. ),
  58. 500,
  59. )
  60. @bp.route("/ingestion-jobs", methods=["POST"])
  61. def create_ingestion_job():
  62. payload = request.get_json(silent=True) or {}
  63. try:
  64. record, created = get_ingestion_service().create_job(
  65. payload,
  66. actor_uid=_identity().get("id") or _identity().get("sub"),
  67. )
  68. return jsonify(success(_record(record))), 201 if created else 200
  69. except Exception as error:
  70. return _error(error)
  71. @bp.route("/ingestion-jobs", methods=["GET"])
  72. def list_ingestion_jobs():
  73. filters = {
  74. name: request.args.get(name)
  75. for name in ("status", "source_uid")
  76. if request.args.get(name)
  77. }
  78. try:
  79. records = get_ingestion_service().list_jobs(filters)
  80. return jsonify(
  81. success({"records": [_record(item) for item in records], "total": len(records)})
  82. ), 200
  83. except Exception as error:
  84. return _error(error)
  85. @bp.route("/ingestion-jobs/<job_uid>", methods=["GET"])
  86. def get_ingestion_job(job_uid):
  87. try:
  88. return jsonify(success(_record(get_ingestion_service().get_job(job_uid)))), 200
  89. except Exception as error:
  90. return _error(error)
  91. @bp.route("/ingestion-jobs/<job_uid>/retry", methods=["POST"])
  92. def retry_ingestion_job(job_uid):
  93. try:
  94. return jsonify(success(_record(get_ingestion_service().retry(job_uid)))), 200
  95. except Exception as error:
  96. return _error(error)
  97. @bp.route("/ingestion-jobs/<job_uid>/cancel", methods=["POST"])
  98. def cancel_ingestion_job(job_uid):
  99. try:
  100. service = get_ingestion_service()
  101. record = service.get_job(job_uid)
  102. identity = _identity()
  103. permissions = set(identity.get("permissions") or [])
  104. actor_uid = identity.get("id") or identity.get("sub")
  105. if record.actor_uid != actor_uid and "ingestion:admin" not in permissions:
  106. return jsonify(failed("权限不足", code=403)), 403
  107. return jsonify(success(_record(service.cancel(job_uid)))), 200
  108. except Exception as error:
  109. return _error(error)