@@ -37,6 +37,9 @@ class MySQLiteYStore(SQLiteYStore):
37
37
lock : Lock
38
38
db_initialized : Event | None
39
39
_db : Connection
40
+ # Optional callbacks for compressing and decompressing data, default: no compression
41
+ _compress : Callable [[bytes ], bytes ] | None = None
42
+ _decompress : Callable [[bytes ], bytes ] | None = None
40
43
41
44
def __init__ (
42
45
self ,
@@ -149,6 +152,14 @@ async def _init_db(self):
149
152
assert self .db_initialized is not None
150
153
self .db_initialized .set ()
151
154
155
+ def register_compression_callbacks (
156
+ self , compress : Callable [[bytes ], bytes ], decompress : Callable [[bytes ], bytes ]
157
+ ) -> None :
158
+ if not callable (compress ) or not callable (decompress ):
159
+ raise TypeError ("Both compress and decompress must be callable." )
160
+ self ._compress = compress
161
+ self ._decompress = decompress
162
+
152
163
async def read (self ) -> AsyncIterator [tuple [bytes , bytes , float ]]:
153
164
"""Async iterator for reading the store content.
154
165
@@ -168,6 +179,11 @@ async def read(self) -> AsyncIterator[tuple[bytes, bytes, float]]:
168
179
(self .path ,),
169
180
)
170
181
for update , metadata , timestamp in await cursor .fetchall ():
182
+ if self ._decompress :
183
+ try :
184
+ update = self ._decompress (update )
185
+ except Exception :
186
+ pass
171
187
found = True
172
188
yield update , metadata , timestamp
173
189
if not found :
@@ -209,15 +225,19 @@ async def write(self, data: bytes) -> None:
209
225
await cursor .execute ("DELETE FROM yupdates WHERE path = ?" , (self .path ,))
210
226
# insert squashed updates
211
227
squashed_update = ydoc .get_update ()
228
+ compressed_update = (
229
+ self ._compress (squashed_update ) if self ._compress else squashed_update
230
+ )
212
231
metadata = await self .get_metadata ()
213
232
await cursor .execute (
214
233
"INSERT INTO yupdates VALUES (?, ?, ?, ?)" ,
215
- (self .path , squashed_update , metadata , time .time ()),
234
+ (self .path , compressed_update , metadata , time .time ()),
216
235
)
217
236
218
237
# finally, write this update to the DB
219
238
metadata = await self .get_metadata ()
239
+ compressed_data = self ._compress (data ) if self ._compress else data
220
240
await cursor .execute (
221
241
"INSERT INTO yupdates VALUES (?, ?, ?, ?)" ,
222
- (self .path , data , metadata , time .time ()),
242
+ (self .path , compressed_data , metadata , time .time ()),
223
243
)
0 commit comments