@@ -33,11 +33,145 @@ def __init__(self):
3333 self ._lock = threading .Lock ()
3434 self ._id_counter = 1 # ID计数器
3535 logger .debug ("SessionBodyFieldManager initialized" )
36+ # 从数据库加载已有的会话字段
37+ self ._load_from_database ()
3638
3739 def _get_db (self ):
3840 """获取请求头数据库连接"""
3941 return DataStore .header_db
4042
43+ def _load_from_database (self ):
44+ """从数据库加载所有未过期的会话Body字段"""
45+ try :
46+ db = self ._get_db ()
47+ if db is None :
48+ logger .debug ("Database not available, skipping load from database" )
49+ return
50+
51+ # 获取当前时间
52+ current_time = datetime .now ().strftime ('%Y-%m-%d %H:%M:%S' )
53+
54+ # 查询所有未过期的会话字段
55+ cursor = db .only_execute ("""
56+ SELECT id, client_ip, field_name, field_value, match_strategy, match_pattern,
57+ replace_strategy, content_types, priority, is_active,
58+ expires_at, created_at, updated_at, scope_config
59+ FROM session_body_fields
60+ WHERE expires_at > ?
61+ """ , (current_time ,))
62+
63+ if cursor is None :
64+ logger .debug ("No cursor returned from database" )
65+ return
66+
67+ loaded_count = 0
68+ max_id = 0
69+
70+ for row in cursor :
71+ try :
72+ (field_id , client_ip , field_name , field_value , match_strategy_str , match_pattern ,
73+ replace_strategy_str , content_types_json , priority , is_active ,
74+ expires_at_str , created_at_str , updated_at_str , scope_config_json ) = row
75+
76+ # 跟踪最大ID
77+ if field_id and field_id > max_id :
78+ max_id = field_id
79+
80+ # 解析匹配策略
81+ try :
82+ match_strategy = MatchStrategy (match_strategy_str )
83+ except ValueError :
84+ match_strategy = MatchStrategy .KEYWORD
85+
86+ # 解析替换策略
87+ try :
88+ replace_strategy = ReplaceStrategy (replace_strategy_str )
89+ except ValueError :
90+ replace_strategy = ReplaceStrategy .REPLACE
91+
92+ # 解析content_types
93+ content_types = None
94+ if content_types_json :
95+ try :
96+ content_types = json .loads (content_types_json )
97+ except json .JSONDecodeError :
98+ content_types = None
99+
100+ # 解析expires_at
101+ expires_at = None
102+ if expires_at_str :
103+ try :
104+ expires_at = datetime .strptime (expires_at_str , '%Y-%m-%d %H:%M:%S' )
105+ except ValueError :
106+ expires_at = None
107+
108+ # 解析created_at
109+ created_at = None
110+ if created_at_str :
111+ try :
112+ created_at = datetime .strptime (created_at_str , '%Y-%m-%d %H:%M:%S' )
113+ except ValueError :
114+ created_at = datetime .now ()
115+
116+ # 解析updated_at
117+ updated_at = None
118+ if updated_at_str :
119+ try :
120+ updated_at = datetime .strptime (updated_at_str , '%Y-%m-%d %H:%M:%S' )
121+ except ValueError :
122+ updated_at = None
123+
124+ # 解析scope_config
125+ scope = None
126+ if scope_config_json :
127+ try :
128+ from model .HeaderScope import HeaderScope
129+ scope_dict = json .loads (scope_config_json )
130+ scope = HeaderScope .from_dict (scope_dict )
131+ except (json .JSONDecodeError , Exception ) as e :
132+ logger .debug (f"Failed to parse scope config: { e } " )
133+ scope = None
134+
135+ # 创建 SessionBodyField 对象
136+ session_field = SessionBodyField (
137+ id = field_id ,
138+ field_name = field_name ,
139+ field_value = field_value ,
140+ match_strategy = match_strategy ,
141+ match_pattern = match_pattern ,
142+ replace_strategy = replace_strategy ,
143+ content_types = content_types ,
144+ priority = priority or 50 ,
145+ is_active = bool (is_active ),
146+ expires_at = expires_at ,
147+ created_at = created_at ,
148+ updated_at = updated_at ,
149+ source_ip = client_ip ,
150+ scope = scope
151+ )
152+
153+ # 加载到内存
154+ if client_ip not in self ._session_body_fields :
155+ self ._session_body_fields [client_ip ] = {}
156+ self ._session_body_fields [client_ip ][field_name ] = session_field
157+ loaded_count += 1
158+
159+ except Exception as e :
160+ logger .error (f"Failed to load session body field from row: { e } " )
161+ continue
162+
163+ # 更新ID计数器
164+ if max_id > 0 :
165+ self ._id_counter = max_id + 1
166+
167+ if loaded_count > 0 :
168+ logger .info (f"Loaded { loaded_count } session body fields from database" )
169+ else :
170+ logger .debug ("No active session body fields found in database" )
171+
172+ except Exception as e :
173+ logger .error (f"Failed to load session body fields from database: { e } " )
174+
41175 def _generate_id (self ) -> int :
42176 """生成唯一ID"""
43177 self ._id_counter += 1
0 commit comments