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
|
# Copyright (C) 2025 John Turner
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import asyncio
import zstandard
import aiosqlite
from aiosqlite import DatabaseError
from pypaste.server import Storage, Paste, Key, StorageError
from pypaste.server.s3.bucket import Bucket, BucketError
from dataclasses import dataclass
from typing import Optional
@dataclass
class S3(Storage):
connection: aiosqlite.Connection
def __init__(
self,
connection: aiosqlite.Connection,
endpoint: str,
region: str,
bucket: str,
access_key: str,
secret_key: str,
):
self.connection = connection
self.bucket = Bucket(endpoint, region, bucket, access_key, secret_key)
async def setup(self) -> None:
await self.connection.execute("create table if not exists s3(key blob)")
await self.connection.commit()
async def insert(self, paste: Paste, key: Key) -> None:
def compress():
return zstandard.compress(paste.text.encode())
compressed = await asyncio.to_thread(compress)
await self.connection.execute(
"insert into pastes values(?, ?, ?, ?, ?)",
(key.data, key.length, paste.dt.isoformat(), len(compressed), paste.syntax),
)
await self.connection.execute("insert into s3 values(?)", (key.data,))
try:
await self.bucket.put(key.data.hex(), compressed)
await self.connection.commit()
except BucketError as e:
await self.connection.rollback()
raise StorageError(str(e))
except DatabaseError as e:
await self.connection.rollback()
raise StorageError(str(e))
async def retrieve(self, key: Key) -> Optional[Paste]:
if not await self.exists(key):
return None
info = await self.read_paste_info(key)
assert info is not None
data = await self.bucket.get(key.data.hex())
assert data is not None
def decompress() -> str:
return zstandard.decompress(data).decode()
text = await asyncio.to_thread(decompress)
return Paste(info.dt, info.syntax, text)
async def delete(self, key: Key) -> None:
await self.connection.execute("begin")
await self.connection.execute("delete from pastes where key=?", (key.data,))
await self.connection.execute("delete from s3 where key=?", (key.data,))
try:
await self.bucket.delete(key.data.hex())
await self.connection.commit()
except BucketError as e:
await self.connection.rollback()
raise StorageError(str(e))
except DatabaseError as e:
await self.connection.rollback()
raise StorageError(str(e))
async def exists(self, key: Key) -> bool:
async with self.connection.execute(
"select 1 from s3 where key=?", (key.data,)
) as cursor:
return await cursor.fetchone() is not None
async def storage_use(self) -> Optional[int]:
async with self.connection.execute(
(
"select sum(pastes.size) from pastes "
"inner join s3 on s3.key=pastes.key"
)
) as cursor:
match await cursor.fetchone():
case [int(use)]:
return use
case None:
return None
case _:
raise Exception("unreachable")
async def oldest(self) -> Optional[Key]:
async with self.connection.execute(
(
"select pastes.key,pastes.key_length from pastes "
"inner join s3 on s3.key=pastes.key "
"order by pastes.datetime"
)
) as cursor:
match await cursor.fetchone():
case [bytes(data), int(length)]:
return Key(data, length)
case None:
return None
case _:
raise Exception("unreachable")
async def vacuum(self, max: int) -> None:
while True:
if (use := await self.storage_use()) is None:
return
if (oldest := await self.oldest()) is None:
return
if use > max:
await self.delete(oldest)
else:
return
|