sync: 鍚屾灞€鍩熺綉鏈€鏂颁唬鐮?(source master @ b69568e4)
This commit is contained in:
1 parent
4f7f07504a
commit
8bc8b0e082
1651 files changed
+278599
-11416
No files matched your search
+26
@@ -0,0 +1,26 @@
|
||||
"""Force-situation task detail persistence(力量态势任务详情)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from deerflow.persistence.force_situation.base import ForceSituationStore
|
||||
from deerflow.persistence.force_situation.memory import MemoryForceSituationStore
|
||||
from deerflow.persistence.force_situation.model import (
|
||||
ForceSituationDetailRow,
|
||||
ForceSituationDetailVersionRow,
|
||||
)
|
||||
from deerflow.persistence.force_situation.sql import ForceSituationRepository
|
||||
|
||||
__all__ = [
|
||||
"ForceSituationDetailRow",
|
||||
"ForceSituationDetailVersionRow",
|
||||
"ForceSituationRepository",
|
||||
"ForceSituationStore",
|
||||
"MemoryForceSituationStore",
|
||||
"make_force_situation_store",
|
||||
]
|
||||
|
||||
|
||||
def make_force_situation_store(session_factory):
|
||||
if session_factory is None:
|
||||
return MemoryForceSituationStore()
|
||||
return ForceSituationRepository(session_factory)
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
"""Persistence contract for force-situation task details(力量态势任务详情).
|
||||
|
||||
Each task owns one shared JSON document; the store never inspects the payload
|
||||
structure — fields are owned by the front-end and may evolve freely.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Any
|
||||
|
||||
|
||||
class ForceSituationStore(ABC):
|
||||
"""Shared force-situation detail store (no user-level partitioning)."""
|
||||
|
||||
@abstractmethod
|
||||
async def get_detail(self, task_id: str) -> dict[str, Any] | None:
|
||||
"""Return ``{task_id, detail, updated_at, ...}`` or ``None`` when absent."""
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
async def upsert_detail(
|
||||
self,
|
||||
task_id: str,
|
||||
detail: dict[str, Any],
|
||||
*,
|
||||
updated_by: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Replace the task's detail document wholesale; create when absent.
|
||||
|
||||
Every write also appends one version row(时间轴刻度).
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
async def list_versions(self, task_id: str, *, limit: int = 100) -> list[dict[str, Any]]:
|
||||
"""Version list for the timeline, ascending by version
|
||||
(``[{version, created_at, updated_by}]``), newest last."""
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
async def get_version(self, task_id: str, version: int) -> dict[str, Any] | None:
|
||||
"""Return one historical version record or ``None`` when absent."""
|
||||
raise NotImplementedError
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
"""In-memory force-situation detail store (tests / no-database mode)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from deerflow.persistence.force_situation.base import ForceSituationStore
|
||||
|
||||
|
||||
def _now_iso() -> str:
|
||||
return datetime.now(UTC).astimezone().isoformat(timespec="seconds")
|
||||
|
||||
|
||||
class MemoryForceSituationStore(ForceSituationStore):
|
||||
def __init__(self) -> None:
|
||||
self._rows: dict[str, dict[str, Any]] = {}
|
||||
self._versions: dict[str, list[dict[str, Any]]] = {}
|
||||
|
||||
async def get_detail(self, task_id: str) -> dict[str, Any] | None:
|
||||
row = self._rows.get(task_id)
|
||||
return dict(row) if row else None
|
||||
|
||||
async def upsert_detail(
|
||||
self,
|
||||
task_id: str,
|
||||
detail: dict[str, Any],
|
||||
*,
|
||||
updated_by: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
now = _now_iso()
|
||||
row = self._rows.get(task_id)
|
||||
if row is None:
|
||||
row = {"task_id": task_id, "created_at": now}
|
||||
self._rows[task_id] = row
|
||||
row.update(
|
||||
{
|
||||
"detail": detail,
|
||||
"updated_by": updated_by,
|
||||
"updated_at": now,
|
||||
}
|
||||
)
|
||||
versions = self._versions.setdefault(task_id, [])
|
||||
versions.append(
|
||||
{
|
||||
"version": len(versions) + 1,
|
||||
"detail": detail,
|
||||
"updated_by": updated_by,
|
||||
"created_at": now,
|
||||
}
|
||||
)
|
||||
return dict(row)
|
||||
|
||||
async def list_versions(self, task_id: str, *, limit: int = 100) -> list[dict[str, Any]]:
|
||||
versions = self._versions.get(task_id, [])
|
||||
trimmed = versions[-limit:] if limit else versions
|
||||
return [{key: row.get(key) for key in ("version", "created_at", "updated_by")} for row in trimmed]
|
||||
|
||||
async def get_version(self, task_id: str, version: int) -> dict[str, Any] | None:
|
||||
for row in self._versions.get(task_id, []):
|
||||
if row.get("version") == version:
|
||||
return dict(row)
|
||||
return None
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
"""ORM model for force-situation task details(力量态势任务详情).
|
||||
|
||||
新类型任务的详情文档:一个任务一份自由 JSON(含时间轴、任务衔接、页面单块内容等),
|
||||
结构由前端与产出方约定、后续可变,数据库不定死字段(整体存 ``detail_json``)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from sqlalchemy import String
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from deerflow.persistence.base import Base
|
||||
from deerflow.persistence.types import BeijingDateTime, PortableLongText
|
||||
|
||||
|
||||
class ForceSituationDetailRow(Base):
|
||||
"""One free-form JSON detail document per external task id (current state)."""
|
||||
|
||||
__tablename__ = "force_situation_details"
|
||||
|
||||
task_id: Mapped[str] = mapped_column(String(128), primary_key=True)
|
||||
detail_json: Mapped[str] = mapped_column(PortableLongText, nullable=False, default="{}")
|
||||
updated_by: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(BeijingDateTime(), nullable=False, default=lambda: datetime.now(UTC))
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
BeijingDateTime(),
|
||||
nullable=False,
|
||||
default=lambda: datetime.now(UTC),
|
||||
onupdate=lambda: datetime.now(UTC),
|
||||
)
|
||||
|
||||
|
||||
class ForceSituationDetailVersionRow(Base):
|
||||
"""Version history for one task's detail document(时间轴 = 每次写入的版本).
|
||||
|
||||
Every PUT appends one version row; ``version`` is a 1-based sequence per task.
|
||||
"""
|
||||
|
||||
__tablename__ = "force_situation_detail_versions"
|
||||
|
||||
id: Mapped[int] = mapped_column(autoincrement=True, primary_key=True)
|
||||
task_id: Mapped[str] = mapped_column(String(128), nullable=False, index=True)
|
||||
version: Mapped[int] = mapped_column(nullable=False, default=1)
|
||||
detail_json: Mapped[str] = mapped_column(PortableLongText, nullable=False, default="{}")
|
||||
updated_by: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(BeijingDateTime(), nullable=False, default=lambda: datetime.now(UTC))
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
"""SQL repository for force-situation task details."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
|
||||
|
||||
from deerflow.persistence.force_situation.base import ForceSituationStore
|
||||
from deerflow.persistence.force_situation.model import (
|
||||
ForceSituationDetailRow,
|
||||
ForceSituationDetailVersionRow,
|
||||
)
|
||||
|
||||
|
||||
def _to_record(row: ForceSituationDetailRow) -> dict[str, Any]:
|
||||
try:
|
||||
detail = json.loads(row.detail_json or "{}")
|
||||
except json.JSONDecodeError:
|
||||
detail = {}
|
||||
return {
|
||||
"task_id": row.task_id,
|
||||
"detail": detail,
|
||||
"updated_by": row.updated_by,
|
||||
"created_at": row.created_at.isoformat() if row.created_at else None,
|
||||
"updated_at": row.updated_at.isoformat() if row.updated_at else None,
|
||||
}
|
||||
|
||||
|
||||
def _version_record(row: ForceSituationDetailVersionRow, *, with_detail: bool = False) -> dict[str, Any]:
|
||||
record: dict[str, Any] = {
|
||||
"version": row.version,
|
||||
"created_at": row.created_at.isoformat() if row.created_at else None,
|
||||
"updated_by": row.updated_by,
|
||||
}
|
||||
if with_detail:
|
||||
try:
|
||||
record["detail"] = json.loads(row.detail_json or "{}")
|
||||
except json.JSONDecodeError:
|
||||
record["detail"] = {}
|
||||
return record
|
||||
|
||||
|
||||
class ForceSituationRepository(ForceSituationStore):
|
||||
def __init__(self, session_factory: async_sessionmaker[AsyncSession]) -> None:
|
||||
self._session_factory = session_factory
|
||||
|
||||
async def get_detail(self, task_id: str) -> dict[str, Any] | None:
|
||||
async with self._session_factory() as session:
|
||||
row = await session.get(ForceSituationDetailRow, task_id)
|
||||
return _to_record(row) if row else None
|
||||
|
||||
async def upsert_detail(
|
||||
self,
|
||||
task_id: str,
|
||||
detail: dict[str, Any],
|
||||
*,
|
||||
updated_by: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
async with self._session_factory() as session:
|
||||
row = await session.get(ForceSituationDetailRow, task_id)
|
||||
if row is None:
|
||||
row = ForceSituationDetailRow(task_id=task_id, updated_by=updated_by)
|
||||
session.add(row)
|
||||
detail_json = json.dumps(detail, ensure_ascii=False)
|
||||
row.detail_json = detail_json
|
||||
row.updated_by = updated_by
|
||||
# 版本历史:每次写入追加一条(时间轴刻度)。
|
||||
max_version = (
|
||||
await session.execute(
|
||||
select(func.max(ForceSituationDetailVersionRow.version)).where(
|
||||
ForceSituationDetailVersionRow.task_id == task_id
|
||||
)
|
||||
)
|
||||
).scalar() or 0
|
||||
session.add(
|
||||
ForceSituationDetailVersionRow(
|
||||
task_id=task_id,
|
||||
version=int(max_version) + 1,
|
||||
detail_json=detail_json,
|
||||
updated_by=updated_by,
|
||||
)
|
||||
)
|
||||
await session.commit()
|
||||
await session.refresh(row)
|
||||
return _to_record(row)
|
||||
|
||||
async def list_versions(self, task_id: str, *, limit: int = 100) -> list[dict[str, Any]]:
|
||||
async with self._session_factory() as session:
|
||||
rows = (
|
||||
(
|
||||
await session.execute(
|
||||
select(ForceSituationDetailVersionRow)
|
||||
.where(ForceSituationDetailVersionRow.task_id == task_id)
|
||||
.order_by(ForceSituationDetailVersionRow.version.desc())
|
||||
.limit(limit)
|
||||
)
|
||||
)
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
return [_version_record(row) for row in reversed(rows)]
|
||||
|
||||
async def get_version(self, task_id: str, version: int) -> dict[str, Any] | None:
|
||||
async with self._session_factory() as session:
|
||||
row = (
|
||||
(
|
||||
await session.execute(
|
||||
select(ForceSituationDetailVersionRow).where(
|
||||
ForceSituationDetailVersionRow.task_id == task_id,
|
||||
ForceSituationDetailVersionRow.version == version,
|
||||
)
|
||||
)
|
||||
)
|
||||
.scalars()
|
||||
.first()
|
||||
)
|
||||
return _version_record(row, with_detail=True) if row else None
|
||||
Reference in new issue
Block a user