active_session_service.py
4.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
from __future__ import annotations
import json
import logging
from dataclasses import dataclass
from datetime import datetime, timezone
from typing import Optional
from app.infrastructure.session_store import SessionStore
from app.model.session import Session
logger = logging.getLogger(__name__)
def _utcnow_iso() -> str:
return datetime.now(timezone.utc).isoformat()
@dataclass(frozen=True)
class ActiveSessionInfo:
id: str
session_id: str
channel: str
room_id: str
status: str = "active"
class ActiveSessionService:
def __init__(self, store: Optional[SessionStore] = None, db=None) -> None:
self.store = store or SessionStore()
self._db = db
def get_or_create_session(
self,
session_id: str,
room_id: str = "",
channel: str = "wechat_group",
) -> ActiveSessionInfo:
# 1. 先查内存(热路径)
existing = self.store.get(session_id)
if existing:
return ActiveSessionInfo(
id=session_id,
session_id=session_id,
channel=existing.get("channel", channel),
room_id=existing.get("room_id", room_id),
)
# 2. 查 DB(冷恢复)
if self._db:
db_sess = self._db.query(Session).filter(
Session.session_id == session_id
).first()
if db_sess:
payload = {
"session_id": db_sess.session_id,
"channel": db_sess.channel,
"room_id": db_sess.room_id,
"conversation_history": json.loads(
db_sess.conversation_history or "[]"
),
"context_entities": {},
"created_at": (
db_sess.created_at.isoformat()
if db_sess.created_at else _utcnow_iso()
),
"updated_at": _utcnow_iso(),
}
self.store.set(session_id, payload)
return ActiveSessionInfo(
id=session_id,
session_id=session_id,
channel=db_sess.channel,
room_id=db_sess.room_id,
)
# 3. 都没有,创建新 session
payload = {
"session_id": session_id,
"channel": channel,
"room_id": room_id,
"conversation_history": [],
"context_entities": {},
"created_at": _utcnow_iso(),
"updated_at": _utcnow_iso(),
}
self.store.set(session_id, payload)
return ActiveSessionInfo(
id=session_id,
session_id=session_id,
channel=channel,
room_id=room_id,
)
def save_to_db(self, session_id: str) -> None:
"""将内存中的 session 持久化到 DB。"""
if not self._db:
return
data = self.store.get(session_id)
if not data:
return
try:
existing = self._db.query(Session).filter(
Session.session_id == session_id
).first()
if existing:
existing.room_id = data.get("room_id", "")
existing.channel = data.get("channel", "wechat_group")
existing.conversation_history = json.dumps(
data.get("conversation_history", []), ensure_ascii=False
)
else:
db_sess = Session(
session_id=session_id,
room_id=data.get("room_id", ""),
channel=data.get("channel", "wechat_group"),
conversation_history=json.dumps(
data.get("conversation_history", []), ensure_ascii=False
),
)
self._db.add(db_sess)
self._db.commit()
except Exception:
self._db.rollback()
logger.exception("Failed to persist session %s to DB", session_id)