|
| 1 | +import gzip |
| 2 | +import os |
| 3 | +import sqlite3 |
| 4 | +import tempfile |
| 5 | +import time |
| 6 | +from typing import Any, cast |
| 7 | + |
| 8 | +from botocore.exceptions import ClientError |
| 9 | +from mypy_boto3_s3 import S3Client |
| 10 | +from sqlalchemy import Engine, create_engine |
| 11 | + |
| 12 | +from api.models import Base |
| 13 | + |
| 14 | + |
| 15 | +class Database: |
| 16 | + """Database wrapper.""" |
| 17 | + |
| 18 | + def __init__( |
| 19 | + self, |
| 20 | + db_url: str, |
| 21 | + connect_kwargs: dict[str, Any] | None = None, |
| 22 | + ): |
| 23 | + self.db_url = db_url |
| 24 | + self.connect_kwargs = connect_kwargs or {} |
| 25 | + |
| 26 | + @property |
| 27 | + def engine(self) -> Engine: |
| 28 | + if hasattr(self, "_engine"): |
| 29 | + return cast(Engine, self._engine) # type: ignore[has-type] |
| 30 | + retries = 0 |
| 31 | + while True: |
| 32 | + try: |
| 33 | + engine = create_engine(self.db_url, connect_args=self.connect_kwargs) |
| 34 | + # Attempt to create a connection or perform any necessary operations |
| 35 | + engine.connect() |
| 36 | + self._engine = engine |
| 37 | + return engine # Connection successful |
| 38 | + except Exception as e: |
| 39 | + if retries >= 10: |
| 40 | + raise RuntimeError(f"Could not create engine: {str(e)}") |
| 41 | + retries += 1 |
| 42 | + time.sleep(60) |
| 43 | + |
| 44 | + def create(self) -> None: |
| 45 | + """Create database tables.""" |
| 46 | + Base.metadata.create_all(bind=self.engine) |
| 47 | + |
| 48 | + def backup(self) -> bool: |
| 49 | + """Backup the database. To be implemented by subclasses if supported.""" |
| 50 | + return False |
| 51 | + |
| 52 | + def empty(self) -> None: |
| 53 | + """Empty the database by dropping and recreating all tables.""" |
| 54 | + Base.metadata.drop_all(bind=self.engine) |
| 55 | + Base.metadata.create_all(bind=self.engine) |
| 56 | + |
| 57 | + |
| 58 | +class SqliteDatabase(Database): |
| 59 | + """SQLite database wrapper with optional S3 backup support.""" |
| 60 | + |
| 61 | + BACKUP_KEY = "userapi_sqlite_backup/backup.db.gz" |
| 62 | + |
| 63 | + def __init__( |
| 64 | + self, |
| 65 | + db_url: str, |
| 66 | + s3_client: S3Client | None = None, |
| 67 | + s3_bucket: str | None = None, |
| 68 | + ): |
| 69 | + if not db_url.startswith("sqlite:///"): |
| 70 | + raise ValueError(f"SQLiteRDSJobQueue requires SQLite DB URL, got: {db_url}") |
| 71 | + if not ((s3_client is None) == (s3_bucket is None)): |
| 72 | + raise ValueError( |
| 73 | + "Both s3_client and s3_bucket must be provided for S3 backup/restore, or both must be None." |
| 74 | + ) |
| 75 | + self.s3_client = s3_client |
| 76 | + self.s3_bucket = s3_bucket |
| 77 | + super().__init__(db_url, connect_kwargs={"check_same_thread": False}) |
| 78 | + |
| 79 | + def create(self) -> None: |
| 80 | + self._restore_database() |
| 81 | + super().create() |
| 82 | + |
| 83 | + @property |
| 84 | + def db_path(self) -> str: |
| 85 | + return self.db_url[len("sqlite:///") :] |
| 86 | + |
| 87 | + def backup(self) -> bool: |
| 88 | + """Backup the SQLite database to S3.""" |
| 89 | + if not self.s3_bucket or not self.s3_client: |
| 90 | + return False |
| 91 | + |
| 92 | + with tempfile.TemporaryDirectory() as temp_dir: |
| 93 | + tmp_backup_path = os.path.join(temp_dir, "backup.db") |
| 94 | + tmp_gzip_path = os.path.join(temp_dir, "backup.db.gz") |
| 95 | + with sqlite3.connect(self.db_path) as source_conn: |
| 96 | + with sqlite3.connect(tmp_backup_path) as backup_conn: |
| 97 | + source_conn.backup(backup_conn) |
| 98 | + |
| 99 | + with open(tmp_backup_path, "rb") as f_in: |
| 100 | + with gzip.open(tmp_gzip_path, "wb") as f_out: |
| 101 | + f_out.writelines(f_in) |
| 102 | + self.s3_client.upload_file(tmp_gzip_path, self.s3_bucket, self.BACKUP_KEY) |
| 103 | + return True |
| 104 | + |
| 105 | + def _restore_database(self) -> bool: |
| 106 | + """Restore the SQLite database from S3.""" |
| 107 | + if not self.s3_bucket or not self.s3_client: |
| 108 | + return False |
| 109 | + |
| 110 | + try: |
| 111 | + self.s3_client.head_object(Bucket=self.s3_bucket, Key=self.BACKUP_KEY) |
| 112 | + except ClientError as e: |
| 113 | + if e.response["Error"]["Code"] == "404": |
| 114 | + return False |
| 115 | + raise |
| 116 | + |
| 117 | + with tempfile.TemporaryDirectory() as temp_dir: |
| 118 | + tmp_gzip_path = os.path.join(temp_dir, "backup.db.gz") |
| 119 | + tmp_backup_path = os.path.join(temp_dir, "backup.db") |
| 120 | + self.s3_client.download_file(self.s3_bucket, self.BACKUP_KEY, tmp_gzip_path) |
| 121 | + with gzip.open(tmp_gzip_path, "rb") as f_in: |
| 122 | + with open(tmp_backup_path, "wb") as f_out: |
| 123 | + f_out.write(f_in.read()) |
| 124 | + os.makedirs(os.path.dirname(self.db_path), exist_ok=True) |
| 125 | + os.rename(tmp_backup_path, self.db_path) |
| 126 | + return True |
0 commit comments