forked from VRAutomatize/browser-use
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
222 lines (196 loc) · 6.61 KB
/
database.py
File metadata and controls
222 lines (196 loc) · 6.61 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
from sqlalchemy import create_engine, Column, Integer, String, DateTime, Float, TypeDecorator
from sqlalchemy.orm import declarative_base, sessionmaker, Session
from sqlalchemy.dialects.postgresql import JSONB, UUID
import os
from dotenv import load_dotenv
import logging
from logging_config import setup_logging, log_info, log_error, log_debug
from datetime import datetime
from sqlalchemy.sql import select
from contextlib import contextmanager
import json
import uuid
# Logging configuration
logger = logging.getLogger('browser-use.database')
load_dotenv()
# Database configuration
DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./browser_use.db")
log_info(logger, "Initializing database connection", {
"database_url": DATABASE_URL,
"type": "SQLite"
})
# Database setup
engine = create_engine(
DATABASE_URL
# connect_args={"check_same_thread": False} # Required for SQLite
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
# Classes to convert JSON to string and vice versa (required for SQLite)
class JSONEncodedDict(TypeDecorator):
impl = String
cache_ok = True
def process_bind_param(self, value, dialect):
if value is not None:
return json.dumps(value)
return None
def process_result_value(self, value, dialect):
if value is not None:
return json.loads(value)
return None
# Models
class Task(Base):
__tablename__ = "tasks"
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
task = Column(String, nullable=False)
config = Column(JSONB, nullable=True) # Using JSONEncodedDict
status = Column(String, nullable=False)
result = Column(JSONB, nullable=True) # Using JSONEncodedDict
error = Column(String, nullable=True)
user_id = Column(String, nullable=True)
created_at = Column(DateTime, nullable=False)
started_at = Column(DateTime, nullable=True)
completed_at = Column(DateTime, nullable=True)
class Metric(Base):
__tablename__ = "metrics"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, nullable=False)
value = Column(Float, nullable=False)
created_at = Column(DateTime, nullable=False)
class Session(Base):
__tablename__ = "sessions"
id = Column(Integer, primary_key=True, index=True)
task_id = Column(Integer, nullable=False)
start_time = Column(DateTime, nullable=False)
end_time = Column(DateTime, nullable=True)
status = Column(String, nullable=False)
error = Column(String, nullable=True)
created_at = Column(DateTime, nullable=False)
# Function to get database session
@contextmanager
def get_db():
db = SessionLocal()
try:
yield db
db.commit()
except Exception as e:
db.rollback()
raise
finally:
db.close()
# Function to initialize database
def init_db():
log_info(logger, "Initializing database")
try:
Base.metadata.create_all(bind=engine)
log_info(logger, "Database tables created successfully")
except Exception as e:
log_error(logger, "Error initializing database", {
"error": str(e)
}, exc_info=True)
raise
# CRUD functions for Task (synchronous version)
def create_task(db: Session, task_data: dict) -> Task:
try:
task = Task(
task=task_data["task"],
config=task_data.get("config"),
status="pending",
created_at=datetime.utcnow()
)
db.add(task)
db.commit()
db.refresh(task)
return task
except Exception as e:
log_error(logger, "Error creating task", {
"error": str(e)
}, exc_info=True)
raise
def get_task(db: Session, task_id: int) -> Task:
try:
return db.query(Task).filter(Task.id == task_id).first()
except Exception as e:
log_error(logger, "Error getting task", {
"task_id": task_id,
"error": str(e)
}, exc_info=True)
raise
def update_task(db: Session, task_id: int, task_data: dict) -> Task:
try:
task = get_task(db, task_id)
if task:
for key, value in task_data.items():
setattr(task, key, value)
db.commit()
db.refresh(task)
return task
except Exception as e:
log_error(logger, "Error updating task", {
"task_id": task_id,
"error": str(e)
}, exc_info=True)
raise
def get_tasks(db: Session, skip: int = 0, limit: int = 100) -> list[Task]:
try:
return db.query(Task).offset(skip).limit(limit).all()
except Exception as e:
log_error(logger, "Error listing tasks", {
"error": str(e)
}, exc_info=True)
raise
def get_pending_tasks(db: Session, skip: int = 0, limit: int = 100) -> list[Task]:
try:
return db.query(Task).where(Task.status == "pending").offset(skip).limit(limit).all()
except Exception as e:
log_error(logger, "Error listing tasks", {
"error": str(e)
}, exc_info=True)
raise
# Functions for Session
def get_sessions(db: Session, skip: int = 0, limit: int = 100) -> list[Session]:
"""List all sessions with pagination"""
try:
result = db.query(Session).offset(skip).limit(limit).all()
return result
except Exception as e:
log_error(logger, "Error listing sessions", {
"error": str(e)
}, exc_info=True)
raise
def get_session(db: Session, session_id: int) -> Session:
"""Get a session by ID"""
try:
return db.query(Session).filter(Session.id == session_id).first()
except Exception as e:
log_error(logger, "Error getting session", {
"session_id": session_id,
"error": str(e)
}, exc_info=True)
raise
def get_task_sessions(db: Session, task_id: int) -> list[Session]:
"""Get all sessions for a task"""
try:
result = db.query(Session).filter(Session.task_id == task_id).all()
return result
except Exception as e:
log_error(logger, "Error getting task sessions", {
"task_id": task_id,
"error": str(e)
}, exc_info=True)
raise
def delete_task(db: Session, task_id: int) -> bool:
"""Remove a task from database"""
try:
task = get_task(db, task_id)
if task:
db.delete(task)
db.commit()
return True
return False
except Exception as e:
log_error(logger, "Error deleting task", {
"task_id": task_id,
"error": str(e)
}, exc_info=True)
raise