初始化
This commit is contained in:
1 parent
34474bd5fc
commit
b638b541d0
3008 files changed
+837699
No files matched your search
+35
@@ -0,0 +1,35 @@
|
||||
"""Planning-session persistence public API."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from deerflow.persistence.workflow_planning.base import (
|
||||
WorkflowPlanningConflictError,
|
||||
WorkflowPlanningProposalNotFoundError,
|
||||
WorkflowPlanningSessionNotFoundError,
|
||||
WorkflowPlanningStore,
|
||||
)
|
||||
from deerflow.persistence.workflow_planning.memory import MemoryWorkflowPlanningStore
|
||||
from deerflow.persistence.workflow_planning.model import (
|
||||
WorkflowPlanningProposalRow,
|
||||
WorkflowPlanningSessionRow,
|
||||
)
|
||||
from deerflow.persistence.workflow_planning.sql import SqlWorkflowPlanningStore
|
||||
|
||||
__all__ = [
|
||||
"MemoryWorkflowPlanningStore",
|
||||
"SqlWorkflowPlanningStore",
|
||||
"WorkflowPlanningConflictError",
|
||||
"WorkflowPlanningProposalNotFoundError",
|
||||
"WorkflowPlanningProposalRow",
|
||||
"WorkflowPlanningSessionNotFoundError",
|
||||
"WorkflowPlanningSessionRow",
|
||||
"WorkflowPlanningStore",
|
||||
"make_workflow_planning_store",
|
||||
]
|
||||
|
||||
|
||||
def make_workflow_planning_store(session_factory):
|
||||
if session_factory is None:
|
||||
return MemoryWorkflowPlanningStore()
|
||||
return SqlWorkflowPlanningStore(session_factory)
|
||||
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
"""Durable planning-session storage for conversational workflow proposals.
|
||||
|
||||
A planning session exists *before* a workflow run. It holds several proposed
|
||||
graphs, lets the owner select and edit one, and records the final run once it
|
||||
has been confirmed. Keeping this state outside ``workflow_runs`` means a
|
||||
user can explore plans without creating/cancelling fake executions.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Any
|
||||
|
||||
|
||||
class WorkflowPlanningSessionNotFoundError(Exception):
|
||||
def __init__(self, session_id: str) -> None:
|
||||
super().__init__(f"workflow planning session not found: {session_id}")
|
||||
self.session_id = session_id
|
||||
|
||||
|
||||
class WorkflowPlanningProposalNotFoundError(Exception):
|
||||
def __init__(self, session_id: str, proposal_id: str) -> None:
|
||||
super().__init__(f"workflow planning proposal not found: {session_id}/{proposal_id}")
|
||||
self.session_id = session_id
|
||||
self.proposal_id = proposal_id
|
||||
|
||||
|
||||
class WorkflowPlanningConflictError(Exception):
|
||||
"""Raised for stale graph edits or a session that has already been confirmed."""
|
||||
|
||||
def __init__(self, session_id: str, message: str, *, current_revision: int | None = None) -> None:
|
||||
super().__init__(message)
|
||||
self.session_id = session_id
|
||||
self.current_revision = current_revision
|
||||
|
||||
|
||||
class WorkflowPlanningStore(ABC):
|
||||
@abstractmethod
|
||||
async def create_session(self, data: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Persist a new session with its initial list of proposals."""
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
async def get_session(self, session_id: str) -> dict[str, Any] | None:
|
||||
"""Return a session with proposals ordered by ``position``."""
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
async def update_proposal(
|
||||
self,
|
||||
session_id: str,
|
||||
proposal_id: str,
|
||||
*,
|
||||
graph: dict[str, Any],
|
||||
canvas_schema: str | None,
|
||||
validation: dict[str, Any] | None,
|
||||
expected_revision: int,
|
||||
) -> dict[str, Any]:
|
||||
"""CAS-update an editable proposal graph and return the session."""
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
async def select_proposal(self, session_id: str, proposal_id: str) -> dict[str, Any]:
|
||||
"""Select a proposal. Selection is reversible until confirmation."""
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
async def confirm_proposal(
|
||||
self,
|
||||
session_id: str,
|
||||
proposal_id: str,
|
||||
*,
|
||||
run_id: str,
|
||||
) -> dict[str, Any]:
|
||||
"""Bind the selected proposal to its newly-created durable run."""
|
||||
raise NotImplementedError
|
||||
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
"""In-memory planning-session store for tests and no-DB deployments."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import copy
|
||||
import uuid
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from deerflow.persistence.workflow_planning.base import (
|
||||
WorkflowPlanningConflictError,
|
||||
WorkflowPlanningProposalNotFoundError,
|
||||
WorkflowPlanningSessionNotFoundError,
|
||||
WorkflowPlanningStore,
|
||||
)
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return datetime.now(UTC).isoformat()
|
||||
|
||||
|
||||
class MemoryWorkflowPlanningStore(WorkflowPlanningStore):
|
||||
def __init__(self) -> None:
|
||||
self._sessions: dict[str, dict[str, Any]] = {}
|
||||
self._proposals: dict[str, dict[str, Any]] = {}
|
||||
self._lock = asyncio.Lock()
|
||||
|
||||
def _session(self, session_id: str) -> dict[str, Any]:
|
||||
session = self._sessions.get(session_id)
|
||||
if session is None:
|
||||
raise WorkflowPlanningSessionNotFoundError(session_id)
|
||||
return session
|
||||
|
||||
def _proposal(self, session_id: str, proposal_id: str) -> dict[str, Any]:
|
||||
proposal = self._proposals.get(proposal_id)
|
||||
if proposal is None or proposal["session_id"] != session_id:
|
||||
raise WorkflowPlanningProposalNotFoundError(session_id, proposal_id)
|
||||
return proposal
|
||||
|
||||
def _public(self, session: dict[str, Any]) -> dict[str, Any]:
|
||||
proposals = [p for p in self._proposals.values() if p["session_id"] == session["id"]]
|
||||
proposals.sort(key=lambda item: item["position"])
|
||||
return copy.deepcopy({**session, "proposals": proposals})
|
||||
|
||||
async def create_session(self, data: dict[str, Any]) -> dict[str, Any]:
|
||||
async with self._lock:
|
||||
now = _now()
|
||||
session_id = str(data.get("id") or f"wps_{uuid.uuid4().hex[:16]}")
|
||||
session = {
|
||||
"id": session_id,
|
||||
"workflow_id": str(data["workflow_id"]),
|
||||
"owner_id": str(data["owner_id"]),
|
||||
"query": str(data["query"]),
|
||||
"status": "proposed",
|
||||
"source_draft_revision": data.get("source_draft_revision"),
|
||||
"selected_proposal_id": None,
|
||||
"confirmed_run_id": None,
|
||||
"created_at": now,
|
||||
"updated_at": now,
|
||||
}
|
||||
self._sessions[session_id] = session
|
||||
for position, raw in enumerate(data.get("proposals") or []):
|
||||
proposal_id = str(raw.get("id") or f"wpp_{uuid.uuid4().hex[:16]}")
|
||||
self._proposals[proposal_id] = {
|
||||
"id": proposal_id,
|
||||
"session_id": session_id,
|
||||
"position": int(raw.get("position", position)),
|
||||
"status": "proposed",
|
||||
"strategy": str(raw.get("strategy") or "collaborative"),
|
||||
"title": str(raw.get("title") or "候选流程"),
|
||||
"summary": str(raw.get("summary") or ""),
|
||||
"rationale": str(raw.get("rationale") or ""),
|
||||
"estimated_duration_seconds": raw.get("estimated_duration_seconds"),
|
||||
"graph": copy.deepcopy(raw.get("graph") or {}),
|
||||
"canvas_schema": str(raw.get("canvas_schema") or "{}"),
|
||||
"validation": copy.deepcopy(raw.get("validation") or {}),
|
||||
"graph_revision": int(raw.get("graph_revision") or 0),
|
||||
"created_at": now,
|
||||
"updated_at": now,
|
||||
}
|
||||
return self._public(session)
|
||||
|
||||
async def get_session(self, session_id: str) -> dict[str, Any] | None:
|
||||
async with self._lock:
|
||||
session = self._sessions.get(session_id)
|
||||
return self._public(session) if session is not None else None
|
||||
|
||||
async def update_proposal(
|
||||
self,
|
||||
session_id: str,
|
||||
proposal_id: str,
|
||||
*,
|
||||
graph: dict[str, Any],
|
||||
canvas_schema: str | None,
|
||||
validation: dict[str, Any] | None,
|
||||
expected_revision: int,
|
||||
) -> dict[str, Any]:
|
||||
async with self._lock:
|
||||
session = self._session(session_id)
|
||||
if session["status"] == "confirmed":
|
||||
raise WorkflowPlanningConflictError(session_id, "候选流程已经确认,不能继续编辑")
|
||||
proposal = self._proposal(session_id, proposal_id)
|
||||
if proposal["graph_revision"] != expected_revision:
|
||||
raise WorkflowPlanningConflictError(
|
||||
session_id,
|
||||
"候选流程已被其他修改更新,请刷新后重试",
|
||||
current_revision=proposal["graph_revision"],
|
||||
)
|
||||
proposal["graph"] = copy.deepcopy(graph)
|
||||
if canvas_schema is not None:
|
||||
proposal["canvas_schema"] = canvas_schema
|
||||
if validation is not None:
|
||||
proposal["validation"] = copy.deepcopy(validation)
|
||||
proposal["graph_revision"] += 1
|
||||
proposal["updated_at"] = _now()
|
||||
session["updated_at"] = proposal["updated_at"]
|
||||
return self._public(session)
|
||||
|
||||
async def select_proposal(self, session_id: str, proposal_id: str) -> dict[str, Any]:
|
||||
async with self._lock:
|
||||
session = self._session(session_id)
|
||||
if session["status"] == "confirmed":
|
||||
raise WorkflowPlanningConflictError(session_id, "规划会话已经确认")
|
||||
self._proposal(session_id, proposal_id)
|
||||
for proposal in self._proposals.values():
|
||||
if proposal["session_id"] == session_id:
|
||||
proposal["status"] = "selected" if proposal["id"] == proposal_id else "proposed"
|
||||
proposal["updated_at"] = _now()
|
||||
session["selected_proposal_id"] = proposal_id
|
||||
session["status"] = "selected"
|
||||
session["updated_at"] = _now()
|
||||
return self._public(session)
|
||||
|
||||
async def confirm_proposal(
|
||||
self,
|
||||
session_id: str,
|
||||
proposal_id: str,
|
||||
*,
|
||||
run_id: str,
|
||||
) -> dict[str, Any]:
|
||||
async with self._lock:
|
||||
session = self._session(session_id)
|
||||
self._proposal(session_id, proposal_id)
|
||||
if session["status"] == "confirmed":
|
||||
if session["selected_proposal_id"] == proposal_id and session["confirmed_run_id"] == run_id:
|
||||
return self._public(session)
|
||||
raise WorkflowPlanningConflictError(session_id, "规划会话已经确认到另一条运行")
|
||||
if session["selected_proposal_id"] != proposal_id:
|
||||
raise WorkflowPlanningConflictError(session_id, "请先选择该候选流程")
|
||||
session["status"] = "confirmed"
|
||||
session["confirmed_run_id"] = run_id
|
||||
session["updated_at"] = _now()
|
||||
for proposal in self._proposals.values():
|
||||
if proposal["session_id"] == session_id:
|
||||
proposal["status"] = "confirmed" if proposal["id"] == proposal_id else "proposed"
|
||||
proposal["updated_at"] = session["updated_at"]
|
||||
return self._public(session)
|
||||
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
"""ORM rows for pre-run workflow planning sessions and candidate graphs."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from sqlalchemy import ForeignKey, Integer, String, Text, UniqueConstraint
|
||||
from sqlalchemy import text as sa_text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from deerflow.persistence.base import Base
|
||||
from deerflow.persistence.types import BeijingDateTime, PortableJSON, PortableLongText
|
||||
|
||||
|
||||
class WorkflowPlanningSessionRow(Base):
|
||||
__tablename__ = "workflow_planning_sessions"
|
||||
|
||||
id: Mapped[str] = mapped_column(String(64), primary_key=True)
|
||||
workflow_id: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
|
||||
owner_id: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
|
||||
query: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
# proposed | selected | confirmed | expired
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default="proposed", index=True)
|
||||
source_draft_revision: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
selected_proposal_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
confirmed_run_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
|
||||
created_at: Mapped[datetime] = mapped_column(BeijingDateTime(), default=lambda: datetime.now(UTC))
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
BeijingDateTime(),
|
||||
default=lambda: datetime.now(UTC),
|
||||
onupdate=lambda: datetime.now(UTC),
|
||||
)
|
||||
|
||||
|
||||
class WorkflowPlanningProposalRow(Base):
|
||||
__tablename__ = "workflow_planning_proposals"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("session_id", "position", name="uq_workflow_planning_proposals_position"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(String(64), primary_key=True)
|
||||
session_id: Mapped[str] = mapped_column(
|
||||
String(64),
|
||||
ForeignKey("workflow_planning_sessions.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
position: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
# proposed | selected | confirmed
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default="proposed", index=True)
|
||||
strategy: Mapped[str] = mapped_column(String(64), nullable=False, default="collaborative")
|
||||
title: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
summary: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
rationale: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
estimated_duration_seconds: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
graph_json: Mapped[dict] = mapped_column(PortableJSON(), default=dict)
|
||||
# The opaque Coze document is kept beside the executable graph so an
|
||||
# editable candidate never needs to overwrite the user's workflow draft.
|
||||
canvas_schema_json: Mapped[str] = mapped_column(PortableLongText(), default="{}", nullable=False)
|
||||
validation_json: Mapped[dict] = mapped_column(PortableJSON(), default=dict)
|
||||
graph_revision: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=sa_text("0"))
|
||||
created_at: Mapped[datetime] = mapped_column(BeijingDateTime(), default=lambda: datetime.now(UTC))
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
BeijingDateTime(),
|
||||
default=lambda: datetime.now(UTC),
|
||||
onupdate=lambda: datetime.now(UTC),
|
||||
)
|
||||
|
||||
+222
@@ -0,0 +1,222 @@
|
||||
"""SQLAlchemy planning-session repository."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
|
||||
|
||||
from deerflow.persistence.workflow_planning.base import (
|
||||
WorkflowPlanningConflictError,
|
||||
WorkflowPlanningProposalNotFoundError,
|
||||
WorkflowPlanningSessionNotFoundError,
|
||||
WorkflowPlanningStore,
|
||||
)
|
||||
from deerflow.persistence.workflow_planning.model import (
|
||||
WorkflowPlanningProposalRow,
|
||||
WorkflowPlanningSessionRow,
|
||||
)
|
||||
|
||||
|
||||
def _iso(value: datetime | None) -> str | None:
|
||||
return value.isoformat() if isinstance(value, datetime) else None
|
||||
|
||||
|
||||
def _proposal_dict(row: WorkflowPlanningProposalRow) -> dict[str, Any]:
|
||||
return {
|
||||
"id": row.id,
|
||||
"session_id": row.session_id,
|
||||
"position": row.position,
|
||||
"status": row.status,
|
||||
"strategy": row.strategy,
|
||||
"title": row.title,
|
||||
"summary": row.summary or "",
|
||||
"rationale": row.rationale or "",
|
||||
"estimated_duration_seconds": row.estimated_duration_seconds,
|
||||
"graph": row.graph_json or {},
|
||||
"canvas_schema": row.canvas_schema_json or "{}",
|
||||
"validation": row.validation_json or {},
|
||||
"graph_revision": row.graph_revision,
|
||||
"created_at": _iso(row.created_at),
|
||||
"updated_at": _iso(row.updated_at),
|
||||
}
|
||||
|
||||
|
||||
def _session_dict(row: WorkflowPlanningSessionRow, proposals: list[WorkflowPlanningProposalRow]) -> dict[str, Any]:
|
||||
return {
|
||||
"id": row.id,
|
||||
"workflow_id": row.workflow_id,
|
||||
"owner_id": row.owner_id,
|
||||
"query": row.query,
|
||||
"status": row.status,
|
||||
"source_draft_revision": row.source_draft_revision,
|
||||
"selected_proposal_id": row.selected_proposal_id,
|
||||
"confirmed_run_id": row.confirmed_run_id,
|
||||
"created_at": _iso(row.created_at),
|
||||
"updated_at": _iso(row.updated_at),
|
||||
"proposals": [_proposal_dict(proposal) for proposal in proposals],
|
||||
}
|
||||
|
||||
|
||||
class SqlWorkflowPlanningStore(WorkflowPlanningStore):
|
||||
def __init__(self, session_factory: async_sessionmaker[AsyncSession]) -> None:
|
||||
self._sf = session_factory
|
||||
|
||||
async def _proposals(self, session: AsyncSession, session_id: str, *, lock: bool = False) -> list[WorkflowPlanningProposalRow]:
|
||||
stmt = (
|
||||
select(WorkflowPlanningProposalRow)
|
||||
.where(WorkflowPlanningProposalRow.session_id == session_id)
|
||||
.order_by(WorkflowPlanningProposalRow.position.asc())
|
||||
)
|
||||
if lock:
|
||||
stmt = stmt.with_for_update()
|
||||
result = await session.execute(stmt)
|
||||
return list(result.scalars())
|
||||
|
||||
async def create_session(self, data: dict[str, Any]) -> dict[str, Any]:
|
||||
now = datetime.now(UTC)
|
||||
session_row = WorkflowPlanningSessionRow(
|
||||
id=str(data.get("id") or f"wps_{uuid.uuid4().hex[:16]}"),
|
||||
workflow_id=str(data["workflow_id"]),
|
||||
owner_id=str(data["owner_id"]),
|
||||
query=str(data["query"]),
|
||||
status="proposed",
|
||||
source_draft_revision=data.get("source_draft_revision"),
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
proposals: list[WorkflowPlanningProposalRow] = []
|
||||
for position, raw in enumerate(data.get("proposals") or []):
|
||||
proposals.append(
|
||||
WorkflowPlanningProposalRow(
|
||||
id=str(raw.get("id") or f"wpp_{uuid.uuid4().hex[:16]}"),
|
||||
session_id=session_row.id,
|
||||
position=int(raw.get("position", position)),
|
||||
status="proposed",
|
||||
strategy=str(raw.get("strategy") or "collaborative"),
|
||||
title=str(raw.get("title") or "候选流程"),
|
||||
summary=str(raw.get("summary") or ""),
|
||||
rationale=str(raw.get("rationale") or ""),
|
||||
estimated_duration_seconds=raw.get("estimated_duration_seconds"),
|
||||
graph_json=raw.get("graph") or {},
|
||||
canvas_schema_json=str(raw.get("canvas_schema") or "{}"),
|
||||
validation_json=raw.get("validation") or {},
|
||||
graph_revision=int(raw.get("graph_revision") or 0),
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
)
|
||||
async with self._sf() as session:
|
||||
session.add(session_row)
|
||||
# These rows only carry scalar foreign-key values, not an ORM
|
||||
# relationship. Flush the parent explicitly before staging its
|
||||
# proposals so SQLite/MySQL/Postgres all see the referenced
|
||||
# planning-session row during the child insert.
|
||||
await session.flush()
|
||||
session.add_all(proposals)
|
||||
await session.flush()
|
||||
result = _session_dict(session_row, proposals)
|
||||
await session.commit()
|
||||
return result
|
||||
|
||||
async def get_session(self, session_id: str) -> dict[str, Any] | None:
|
||||
async with self._sf() as session:
|
||||
row = await session.get(WorkflowPlanningSessionRow, session_id)
|
||||
if row is None:
|
||||
return None
|
||||
return _session_dict(row, await self._proposals(session, session_id))
|
||||
|
||||
async def update_proposal(
|
||||
self,
|
||||
session_id: str,
|
||||
proposal_id: str,
|
||||
*,
|
||||
graph: dict[str, Any],
|
||||
canvas_schema: str | None,
|
||||
validation: dict[str, Any] | None,
|
||||
expected_revision: int,
|
||||
) -> dict[str, Any]:
|
||||
async with self._sf() as session:
|
||||
row = await session.get(WorkflowPlanningSessionRow, session_id, with_for_update=True)
|
||||
if row is None:
|
||||
raise WorkflowPlanningSessionNotFoundError(session_id)
|
||||
if row.status == "confirmed":
|
||||
raise WorkflowPlanningConflictError(session_id, "候选流程已经确认,不能继续编辑")
|
||||
proposals = await self._proposals(session, session_id, lock=True)
|
||||
proposal = next((item for item in proposals if item.id == proposal_id), None)
|
||||
if proposal is None:
|
||||
raise WorkflowPlanningProposalNotFoundError(session_id, proposal_id)
|
||||
if proposal.graph_revision != expected_revision:
|
||||
raise WorkflowPlanningConflictError(
|
||||
session_id,
|
||||
"候选流程已被其他修改更新,请刷新后重试",
|
||||
current_revision=proposal.graph_revision,
|
||||
)
|
||||
proposal.graph_json = graph
|
||||
if canvas_schema is not None:
|
||||
proposal.canvas_schema_json = canvas_schema
|
||||
if validation is not None:
|
||||
proposal.validation_json = validation
|
||||
proposal.graph_revision += 1
|
||||
row.updated_at = datetime.now(UTC)
|
||||
await session.flush()
|
||||
result = _session_dict(row, proposals)
|
||||
await session.commit()
|
||||
return result
|
||||
|
||||
async def select_proposal(self, session_id: str, proposal_id: str) -> dict[str, Any]:
|
||||
async with self._sf() as session:
|
||||
row = await session.get(WorkflowPlanningSessionRow, session_id, with_for_update=True)
|
||||
if row is None:
|
||||
raise WorkflowPlanningSessionNotFoundError(session_id)
|
||||
if row.status == "confirmed":
|
||||
raise WorkflowPlanningConflictError(session_id, "规划会话已经确认")
|
||||
proposals = await self._proposals(session, session_id, lock=True)
|
||||
if not any(proposal.id == proposal_id for proposal in proposals):
|
||||
raise WorkflowPlanningProposalNotFoundError(session_id, proposal_id)
|
||||
now = datetime.now(UTC)
|
||||
row.status = "selected"
|
||||
row.selected_proposal_id = proposal_id
|
||||
row.updated_at = now
|
||||
for proposal in proposals:
|
||||
proposal.status = "selected" if proposal.id == proposal_id else "proposed"
|
||||
proposal.updated_at = now
|
||||
await session.flush()
|
||||
result = _session_dict(row, proposals)
|
||||
await session.commit()
|
||||
return result
|
||||
|
||||
async def confirm_proposal(
|
||||
self,
|
||||
session_id: str,
|
||||
proposal_id: str,
|
||||
*,
|
||||
run_id: str,
|
||||
) -> dict[str, Any]:
|
||||
async with self._sf() as session:
|
||||
row = await session.get(WorkflowPlanningSessionRow, session_id, with_for_update=True)
|
||||
if row is None:
|
||||
raise WorkflowPlanningSessionNotFoundError(session_id)
|
||||
proposals = await self._proposals(session, session_id, lock=True)
|
||||
if not any(proposal.id == proposal_id for proposal in proposals):
|
||||
raise WorkflowPlanningProposalNotFoundError(session_id, proposal_id)
|
||||
if row.status == "confirmed":
|
||||
if row.selected_proposal_id == proposal_id and row.confirmed_run_id == run_id:
|
||||
return _session_dict(row, proposals)
|
||||
raise WorkflowPlanningConflictError(session_id, "规划会话已经确认到另一条运行")
|
||||
if row.selected_proposal_id != proposal_id:
|
||||
raise WorkflowPlanningConflictError(session_id, "请先选择该候选流程")
|
||||
now = datetime.now(UTC)
|
||||
row.status = "confirmed"
|
||||
row.confirmed_run_id = run_id
|
||||
row.updated_at = now
|
||||
for proposal in proposals:
|
||||
proposal.status = "confirmed" if proposal.id == proposal_id else "proposed"
|
||||
proposal.updated_at = now
|
||||
await session.flush()
|
||||
result = _session_dict(row, proposals)
|
||||
await session.commit()
|
||||
return result
|
||||
Reference in new issue
Block a user