forked from dapr/python-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdapr_session_manager.py
More file actions
552 lines (436 loc) · 18.1 KB
/
Copy pathdapr_session_manager.py
File metadata and controls
552 lines (436 loc) · 18.1 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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
"""
Copyright 2026 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import json
import logging
from typing import Any, Dict, List, Literal, Optional, cast
from strands import _identifier
from strands.session.repository_session_manager import RepositorySessionManager
from strands.session.session_repository import SessionRepository
from strands.types.exceptions import SessionException
from strands.types.session import Session, SessionAgent, SessionMessage
from dapr.clients import DaprClient
from dapr.clients.grpc._state import Consistency, StateOptions
logger = logging.getLogger(__name__)
# Type-safe consistency constants
ConsistencyLevel = Literal['eventual', 'strong']
DAPR_CONSISTENCY_EVENTUAL: ConsistencyLevel = 'eventual'
DAPR_CONSISTENCY_STRONG: ConsistencyLevel = 'strong'
class DaprSessionManager(RepositorySessionManager, SessionRepository):
"""Dapr state store session manager for distributed storage.
Stores session data in Dapr state stores (Redis, PostgreSQL, MongoDB, Cosmos DB, etc.)
with support for TTL and consistency levels.
Key structure:
- `{session_id}:session` - Session metadata
- `{session_id}:agents:{agent_id}` - Agent metadata
- `{session_id}:messages:{agent_id}` - Message list (JSON array)
"""
def __init__(
self,
session_id: str,
state_store_name: str,
dapr_client: DaprClient,
ttl: Optional[int] = None,
consistency: ConsistencyLevel = DAPR_CONSISTENCY_EVENTUAL,
):
"""Initialize DaprSessionManager.
Args:
session_id: ID for the session.
ID is not allowed to contain path separators (e.g., a/b).
state_store_name: Name of the Dapr state store component.
dapr_client: DaprClient instance for state operations.
ttl: Optional time-to-live in seconds for state items.
consistency: Consistency level for state operations ("eventual" or "strong").
"""
self._state_store_name = state_store_name
self._dapr_client = dapr_client
self._ttl = ttl
self._consistency = consistency
self._owns_client = False
super().__init__(session_id=session_id, session_repository=self)
@classmethod
def from_address(
cls,
session_id: str,
state_store_name: str,
dapr_address: str = 'localhost:50001',
) -> 'DaprSessionManager':
"""Create DaprSessionManager from Dapr address.
Args:
session_id: ID for the session.
state_store_name: Name of the Dapr state store component.
dapr_address: Dapr gRPC endpoint (default: localhost:50001).
Returns:
DaprSessionManager instance with owned client.
"""
dapr_client = DaprClient(address=dapr_address)
manager = cls(session_id, state_store_name=state_store_name, dapr_client=dapr_client)
manager._owns_client = True
return manager
def _get_session_key(self, session_id: str) -> str:
"""Get session state key.
Args:
session_id: ID for the session.
Returns:
State store key for the session.
Raises:
ValueError: If session id contains a path separator.
"""
session_id = _identifier.validate(session_id, _identifier.Identifier.SESSION)
return f'{session_id}:session'
def _get_agent_key(self, session_id: str, agent_id: str) -> str:
"""Get agent state key.
Args:
session_id: ID for the session.
agent_id: ID for the agent.
Returns:
State store key for the agent.
Raises:
ValueError: If session id or agent id contains a path separator.
"""
session_id = _identifier.validate(session_id, _identifier.Identifier.SESSION)
agent_id = _identifier.validate(agent_id, _identifier.Identifier.AGENT)
return f'{session_id}:agents:{agent_id}'
def _get_messages_key(self, session_id: str, agent_id: str) -> str:
"""Get messages list state key.
Args:
session_id: ID for the session.
agent_id: ID for the agent.
Returns:
State store key for the messages list.
Raises:
ValueError: If session id or agent id contains a path separator.
"""
session_id = _identifier.validate(session_id, _identifier.Identifier.SESSION)
agent_id = _identifier.validate(agent_id, _identifier.Identifier.AGENT)
return f'{session_id}:messages:{agent_id}'
def _get_manifest_key(self, session_id: str) -> str:
"""Get session manifest key (tracks agent_ids for deletion)."""
session_id = _identifier.validate(session_id, _identifier.Identifier.SESSION)
return f'{session_id}:manifest'
def _get_read_metadata(self) -> Dict[str, str]:
"""Get metadata for read operations (consistency).
Returns:
Metadata dictionary for state reads.
"""
metadata: Dict[str, str] = {}
if self._consistency:
metadata['consistency'] = self._consistency
return metadata
def _get_write_metadata(self) -> Dict[str, str]:
"""Get metadata for write operations (TTL).
Returns:
Metadata dictionary for state writes.
"""
metadata: Dict[str, str] = {}
if self._ttl is not None:
metadata['ttlInSeconds'] = str(self._ttl)
return metadata
def _get_state_options(self) -> Optional[StateOptions]:
"""Get state options for write/delete operations (consistency).
Returns:
StateOptions for consistency or None.
"""
if self._consistency == DAPR_CONSISTENCY_STRONG:
return StateOptions(consistency=Consistency.strong)
elif self._consistency == DAPR_CONSISTENCY_EVENTUAL:
return StateOptions(consistency=Consistency.eventual)
return None
def _read_state(self, key: str) -> Optional[Dict[str, Any]]:
"""Read and parse JSON state from Dapr.
Args:
key: State store key.
Returns:
Parsed JSON dictionary or None if not found.
Raises:
SessionException: If state is corrupted or read fails.
"""
try:
response = self._dapr_client.get_state(
store_name=self._state_store_name,
key=key,
state_metadata=self._get_read_metadata(),
)
if not response.data:
return None
content = response.data.decode('utf-8')
return cast(Dict[str, Any], json.loads(content))
except json.JSONDecodeError as e:
raise SessionException(f'Invalid JSON in state key {key}: {e}') from e
except Exception as e:
raise SessionException(f'Failed to read state key {key}: {e}') from e
def _write_state(self, key: str, data: Dict[str, Any]) -> None:
"""Write JSON state to Dapr.
Args:
key: State store key.
data: Dictionary to serialize and store.
Raises:
SessionException: If write fails.
"""
try:
content = json.dumps(data, ensure_ascii=False)
self._dapr_client.save_state(
store_name=self._state_store_name,
key=key,
value=content,
state_metadata=self._get_write_metadata(),
options=self._get_state_options(),
)
except Exception as e:
raise SessionException(f'Failed to write state key {key}: {e}') from e
def _delete_state(self, key: str) -> None:
"""Delete state from Dapr.
Args:
key: State store key.
Raises:
SessionException: If delete fails.
"""
try:
self._dapr_client.delete_state(
store_name=self._state_store_name,
key=key,
options=self._get_state_options(),
)
except Exception as e:
raise SessionException(f'Failed to delete state key {key}: {e}') from e
def create_session(self, session: Session) -> Session:
"""Create a new session.
Args:
session: Session to create.
Returns:
Created session.
Raises:
SessionException: If session already exists or creation fails.
"""
session_key = self._get_session_key(session.session_id)
# Check if session already exists
existing = self.read_session(session.session_id)
if existing is not None:
raise SessionException(f'Session {session.session_id} already exists')
# Write session data
session_dict = session.to_dict()
self._write_state(session_key, session_dict)
return session
def read_session(self, session_id: str) -> Optional[Session]:
"""Read session data.
Args:
session_id: ID of the session to read.
Returns:
Session if found, None otherwise.
Raises:
SessionException: If read fails.
"""
session_key = self._get_session_key(session_id)
session_data = self._read_state(session_key)
if session_data is None:
return None
return Session.from_dict(session_data)
def delete_session(self, session_id: str) -> None:
"""Delete session and all associated data.
Uses a session manifest to discover agent IDs for cleanup.
"""
session_key = self._get_session_key(session_id)
manifest_key = self._get_manifest_key(session_id)
# Read manifest (may be missing if no agents created)
manifest = self._read_state(manifest_key)
agent_ids: list[str] = manifest.get('agents', []) if manifest else []
# Delete agent and message keys
for agent_id in agent_ids:
agent_key = self._get_agent_key(session_id, agent_id)
messages_key = self._get_messages_key(session_id, agent_id)
self._delete_state(agent_key)
self._delete_state(messages_key)
# Delete manifest and session
self._delete_state(manifest_key)
self._delete_state(session_key)
def create_agent(self, session_id: str, session_agent: SessionAgent) -> None:
"""Create a new agent in the session.
Args:
session_id: ID of the session.
session_agent: Agent to create.
Raises:
SessionException: If creation fails.
"""
agent_key = self._get_agent_key(session_id, session_agent.agent_id)
agent_dict = session_agent.to_dict()
self._write_state(agent_key, agent_dict)
# Initialize empty messages list
messages_key = self._get_messages_key(session_id, session_agent.agent_id)
self._write_state(messages_key, {'messages': []})
# Update manifest with this agent
manifest_key = self._get_manifest_key(session_id)
manifest = self._read_state(manifest_key) or {'agents': []}
if session_agent.agent_id not in manifest['agents']:
manifest['agents'].append(session_agent.agent_id)
self._write_state(manifest_key, manifest)
def read_agent(self, session_id: str, agent_id: str) -> Optional[SessionAgent]:
"""Read agent data.
Args:
session_id: ID of the session.
agent_id: ID of the agent.
Returns:
SessionAgent if found, None otherwise.
Raises:
SessionException: If read fails.
"""
agent_key = self._get_agent_key(session_id, agent_id)
agent_data = self._read_state(agent_key)
if agent_data is None:
return None
return SessionAgent.from_dict(agent_data)
def update_agent(self, session_id: str, session_agent: SessionAgent) -> None:
"""Update agent data.
Args:
session_id: ID of the session.
session_agent: Agent to update.
Raises:
SessionException: If agent doesn't exist or update fails.
"""
previous_agent = self.read_agent(session_id=session_id, agent_id=session_agent.agent_id)
if previous_agent is None:
raise SessionException(
f'Agent {session_agent.agent_id} in session {session_id} does not exist'
)
# Preserve creation timestamp
session_agent.created_at = previous_agent.created_at
agent_key = self._get_agent_key(session_id, session_agent.agent_id)
self._write_state(agent_key, session_agent.to_dict())
def create_message(
self,
session_id: str,
agent_id: str,
session_message: SessionMessage,
) -> None:
"""Create a new message for the agent.
Args:
session_id: ID of the session.
agent_id: ID of the agent.
session_message: Message to create.
Raises:
SessionException: If creation fails.
"""
messages_key = self._get_messages_key(session_id, agent_id)
# Read existing messages
messages_data = self._read_state(messages_key)
if messages_data is None:
messages_list = []
else:
messages_list = messages_data.get('messages', [])
if not isinstance(messages_list, list):
messages_list = []
# Append new message
messages_list.append(session_message.to_dict())
# Write back
self._write_state(messages_key, {'messages': messages_list})
def read_message(
self, session_id: str, agent_id: str, message_id: int
) -> Optional[SessionMessage]:
"""Read message data.
Args:
session_id: ID of the session.
agent_id: ID of the agent.
message_id: Index of the message.
Returns:
SessionMessage if found, None otherwise.
Raises:
ValueError: If message_id is not an integer.
SessionException: If read fails.
"""
if not isinstance(message_id, int):
raise ValueError(f'message_id=<{message_id}> | message id must be an integer')
messages_key = self._get_messages_key(session_id, agent_id)
messages_data = self._read_state(messages_key)
if messages_data is None:
return None
messages_list = messages_data.get('messages', [])
if not isinstance(messages_list, list):
messages_list = []
# Find message by ID
for msg_dict in messages_list:
if msg_dict.get('message_id') == message_id:
return SessionMessage.from_dict(msg_dict)
return None
def update_message(
self, session_id: str, agent_id: str, session_message: SessionMessage
) -> None:
"""Update message data.
Args:
session_id: ID of the session.
agent_id: ID of the agent.
session_message: Message to update.
Raises:
SessionException: If message doesn't exist or update fails.
"""
previous_message = self.read_message(
session_id=session_id, agent_id=agent_id, message_id=session_message.message_id
)
if previous_message is None:
raise SessionException(f'Message {session_message.message_id} does not exist')
# Preserve creation timestamp
session_message.created_at = previous_message.created_at
messages_key = self._get_messages_key(session_id, agent_id)
# Read existing messages
messages_data = self._read_state(messages_key)
if messages_data is None:
raise SessionException(
f'Messages not found for agent {agent_id} in session {session_id}'
)
messages_list = messages_data.get('messages', [])
if not isinstance(messages_list, list):
messages_list = []
# Find and update message
updated = False
for i, msg_dict in enumerate(messages_list):
if msg_dict.get('message_id') == session_message.message_id:
messages_list[i] = session_message.to_dict()
updated = True
break
if not updated:
raise SessionException(f'Message {session_message.message_id} not found in list')
# Write back
self._write_state(messages_key, {'messages': messages_list})
def list_messages(
self,
session_id: str,
agent_id: str,
limit: Optional[int] = None,
offset: int = 0,
) -> List[SessionMessage]:
"""List messages for an agent with pagination.
Args:
session_id: ID of the session.
agent_id: ID of the agent.
limit: Maximum number of messages to return.
offset: Number of messages to skip.
Returns:
List of SessionMessage objects.
Raises:
SessionException: If read fails.
"""
messages_key = self._get_messages_key(session_id, agent_id)
messages_data = self._read_state(messages_key)
if messages_data is None:
return []
messages_list = messages_data.get('messages', [])
if not isinstance(messages_list, list):
messages_list = []
# Apply pagination
if limit is not None:
messages_list = messages_list[offset : offset + limit]
else:
messages_list = messages_list[offset:]
# Convert to SessionMessage objects
return [SessionMessage.from_dict(msg_dict) for msg_dict in messages_list]
def close(self) -> None:
"""Close the Dapr client if owned by this manager."""
if self._owns_client:
self._dapr_client.close()