-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase_manager.py
More file actions
286 lines (249 loc) · 10.4 KB
/
Copy pathdatabase_manager.py
File metadata and controls
286 lines (249 loc) · 10.4 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
"""
DynamoDB database manager for MCP MUD Game
"""
import boto3
import json
from typing import Dict, List, Optional, Any
from datetime import datetime
from botocore.exceptions import ClientError
from config import DYNAMODB_REGION, DYNAMODB_ENDPOINT, TABLES
class DatabaseManager:
def __init__(self):
"""Initialize DynamoDB connection"""
self.dynamodb = boto3.resource(
'dynamodb',
region_name=DYNAMODB_REGION,
endpoint_url=DYNAMODB_ENDPOINT
)
self.tables = {}
self._initialize_tables()
def _initialize_tables(self):
"""Initialize DynamoDB tables"""
# Players table
self._create_table_if_not_exists(
TABLES["players"],
[
{'AttributeName': 'player_id', 'KeyType': 'HASH'}
],
[
{'AttributeName': 'player_id', 'AttributeType': 'S'}
]
)
# Rooms table
self._create_table_if_not_exists(
TABLES["rooms"],
[
{'AttributeName': 'room_id', 'KeyType': 'HASH'}
],
[
{'AttributeName': 'room_id', 'AttributeType': 'S'}
]
)
# Game state table
self._create_table_if_not_exists(
TABLES["game_state"],
[
{'AttributeName': 'game_id', 'KeyType': 'HASH'}
],
[
{'AttributeName': 'game_id', 'AttributeType': 'S'}
]
)
# Action queue table
self._create_table_if_not_exists(
TABLES["action_queue"],
[
{'AttributeName': 'action_id', 'KeyType': 'HASH'}
],
[
{'AttributeName': 'action_id', 'AttributeType': 'S'},
{'AttributeName': 'timestamp', 'AttributeType': 'N'}
],
global_secondary_indexes=[
{
'IndexName': 'timestamp-index',
'KeySchema': [
{'AttributeName': 'timestamp', 'KeyType': 'HASH'}
],
'Projection': {'ProjectionType': 'ALL'},
'ProvisionedThroughput': {'ReadCapacityUnits': 5, 'WriteCapacityUnits': 5}
}
]
)
# Store table references
for table_name in TABLES.values():
self.tables[table_name] = self.dynamodb.Table(table_name)
def _create_table_if_not_exists(self, table_name: str, key_schema: List[Dict],
attribute_definitions: List[Dict],
global_secondary_indexes: Optional[List[Dict]] = None):
"""Create DynamoDB table if it doesn't exist"""
try:
table = self.dynamodb.Table(table_name)
table.load()
print(f"Table {table_name} already exists")
except ClientError as e:
if e.response['Error']['Code'] == 'ResourceNotFoundException':
print(f"Creating table {table_name}")
table_config = {
'TableName': table_name,
'KeySchema': key_schema,
'AttributeDefinitions': attribute_definitions,
'ProvisionedThroughput': {
'ReadCapacityUnits': 5,
'WriteCapacityUnits': 5
}
}
if global_secondary_indexes:
table_config['GlobalSecondaryIndexes'] = global_secondary_indexes
table = self.dynamodb.create_table(**table_config)
table.wait_until_exists()
print(f"Table {table_name} created successfully")
else:
raise e
# Player operations
def create_player(self, player_data: Dict[str, Any]) -> bool:
"""Create a new player character"""
try:
player_data['created_at'] = datetime.utcnow().isoformat()
player_data['updated_at'] = datetime.utcnow().isoformat()
self.tables[TABLES["players"]].put_item(
Item=player_data,
ConditionExpression='attribute_not_exists(player_id)'
)
return True
except ClientError as e:
if e.response['Error']['Code'] == 'ConditionalCheckFailedException':
print(f"Player {player_data['player_id']} already exists")
return False
raise e
def get_player(self, player_id: str) -> Optional[Dict[str, Any]]:
"""Get player data by ID"""
try:
response = self.tables[TABLES["players"]].get_item(
Key={'player_id': player_id}
)
return response.get('Item')
except ClientError as e:
print(f"Error getting player {player_id}: {e}")
return None
def update_player(self, player_id: str, updates: Dict[str, Any]) -> bool:
"""Update player data"""
try:
updates['updated_at'] = datetime.utcnow().isoformat()
update_expression = "SET "
expression_attribute_values = {}
for key, value in updates.items():
update_expression += f"{key} = :{key}, "
expression_attribute_values[f":{key}"] = value
update_expression = update_expression.rstrip(", ")
self.tables[TABLES["players"]].update_item(
Key={'player_id': player_id},
UpdateExpression=update_expression,
ExpressionAttributeValues=expression_attribute_values
)
return True
except ClientError as e:
print(f"Error updating player {player_id}: {e}")
return False
# Room operations
def create_room(self, room_data: Dict[str, Any]) -> bool:
"""Create a new room"""
try:
room_data['created_at'] = datetime.utcnow().isoformat()
room_data['updated_at'] = datetime.utcnow().isoformat()
self.tables[TABLES["rooms"]].put_item(Item=room_data)
return True
except ClientError as e:
print(f"Error creating room: {e}")
return False
def get_room(self, room_id: str) -> Optional[Dict[str, Any]]:
"""Get room data by ID"""
try:
response = self.tables[TABLES["rooms"]].get_item(
Key={'room_id': room_id}
)
return response.get('Item')
except ClientError as e:
print(f"Error getting room {room_id}: {e}")
return None
def update_room(self, room_id: str, updates: Dict[str, Any]) -> bool:
"""Update room data"""
try:
updates['updated_at'] = datetime.utcnow().isoformat()
update_expression = "SET "
expression_attribute_values = {}
for key, value in updates.items():
update_expression += f"{key} = :{key}, "
expression_attribute_values[f":{key}"] = value
update_expression = update_expression.rstrip(", ")
self.tables[TABLES["rooms"]].update_item(
Key={'room_id': room_id},
UpdateExpression=update_expression,
ExpressionAttributeValues=expression_attribute_values
)
return True
except ClientError as e:
print(f"Error updating room {room_id}: {e}")
return False
def get_all_rooms(self) -> List[Dict[str, Any]]:
"""Get all rooms from the database"""
try:
response = self.tables[TABLES["rooms"]].scan()
return response.get('Items', [])
except ClientError as e:
print(f"Error getting all rooms: {e}")
return []
# Game state operations
def get_game_state(self, game_id: str = "main") -> Optional[Dict[str, Any]]:
"""Get current game state"""
try:
response = self.tables[TABLES["game_state"]].get_item(
Key={'game_id': game_id}
)
return response.get('Item')
except ClientError as e:
print(f"Error getting game state: {e}")
return None
def update_game_state(self, updates: Dict[str, Any], game_id: str = "main") -> bool:
"""Update game state"""
try:
updates['updated_at'] = datetime.utcnow().isoformat()
update_expression = "SET "
expression_attribute_values = {}
for key, value in updates.items():
update_expression += f"{key} = :{key}, "
expression_attribute_values[f":{key}"] = value
update_expression = update_expression.rstrip(", ")
self.tables[TABLES["game_state"]].update_item(
Key={'game_id': game_id},
UpdateExpression=update_expression,
ExpressionAttributeValues=expression_attribute_values
)
return True
except ClientError as e:
print(f"Error updating game state: {e}")
return False
# Action queue operations
def add_action(self, action_data: Dict[str, Any]) -> bool:
"""Add action to queue"""
try:
action_data['timestamp'] = int(datetime.utcnow().timestamp() * 1000) # milliseconds
action_data['created_at'] = datetime.utcnow().isoformat()
self.tables[TABLES["action_queue"]].put_item(Item=action_data)
return True
except ClientError as e:
print(f"Error adding action to queue: {e}")
return False
def get_pending_actions(self, limit: int = 10) -> List[Dict[str, Any]]:
"""Get pending actions from queue"""
try:
response = self.tables[TABLES["action_queue"]].scan(
FilterExpression='attribute_exists(action_id) AND #status = :status',
ExpressionAttributeNames={'#status': 'status'},
ExpressionAttributeValues={':status': 'pending'},
Limit=limit
)
return response.get('Items', [])
except ClientError as e:
print(f"Error getting pending actions: {e}")
return []