active_session_service.py
5.13 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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
from __future__ import annotations
import json
import logging
from dataclasses import dataclass
from datetime import datetime
from app.infrastructure.time import china_now
from typing import Callable, Optional
from sqlalchemy.orm import Session as SASession
from app.infrastructure.session_store import SessionStore
from app.model.session import Session
logger = logging.getLogger(__name__)
def _utcnow_iso() -> str:
return china_now().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_factory: Optional[Callable[[], SASession]] = None) -> None:
self.store = store or SessionStore()
self._db_factory = db_factory
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:
# SessionBuffer 可能预创建 session 但不带 room_id,这里补上
if room_id and not existing.get("room_id"):
existing["room_id"] = room_id
self.store.set(session_id, 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_factory:
try:
with self._db_factory() as db:
db_sess = db.query(Session).filter(
Session.session_id == session_id
).first()
# with 块结束 → db 关闭、连接归还池
except Exception:
logger.exception("Failed to cold-recover session %s from DB, 降级新建", session_id)
db_sess = None
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:
if not self._db_factory:
logger.warning("[save_to_db] session=%s db_factory 为 None,跳过持久化", session_id)
return
data = self.store.get(session_id)
if not data:
logger.warning("[save_to_db] session=%s KV 中无数据,跳过持久化", session_id)
return
history = data.get("conversation_history") or []
logger.info(
"[save_to_db] session=%s conversation_history 长度=%d",
session_id, len(history),
)
try:
with self._db_factory() as db:
existing = 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
),
)
db.add(db_sess)
db.commit()
except Exception:
logger.exception("Failed to persist session %s to DB", session_id)