Skip to content
This repository was archived by the owner on Apr 26, 2024. It is now read-only.

Commit 9b90b94

Browse files
authored
Add type hints to media repository storage module (#11311)
1 parent 6f8f3d4 commit 9b90b94

File tree

4 files changed

+89
-62
lines changed

4 files changed

+89
-62
lines changed

changelog.d/11311.misc

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add type hints to storage classes.

mypy.ini

-1
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,6 @@ exclude = (?x)
3636
|synapse/storage/databases/main/events_bg_updates.py
3737
|synapse/storage/databases/main/events_worker.py
3838
|synapse/storage/databases/main/group_server.py
39-
|synapse/storage/databases/main/media_repository.py
4039
|synapse/storage/databases/main/metrics.py
4140
|synapse/storage/databases/main/monthly_active_users.py
4241
|synapse/storage/databases/main/presence.py

synapse/rest/media/v1/preview_url_resource.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@
4545
from synapse.rest.media.v1._base import get_filename_from_headers
4646
from synapse.rest.media.v1.media_storage import MediaStorage
4747
from synapse.rest.media.v1.oembed import OEmbedProvider
48-
from synapse.types import JsonDict
48+
from synapse.types import JsonDict, UserID
4949
from synapse.util import json_encoder
5050
from synapse.util.async_helpers import ObservableDeferred
5151
from synapse.util.caches.expiringcache import ExpiringCache
@@ -231,7 +231,7 @@ async def _async_render_GET(self, request: SynapseRequest) -> None:
231231
og = await make_deferred_yieldable(observable.observe())
232232
respond_with_json_bytes(request, 200, og, send_cors=True)
233233

234-
async def _do_preview(self, url: str, user: str, ts: int) -> bytes:
234+
async def _do_preview(self, url: str, user: UserID, ts: int) -> bytes:
235235
"""Check the db, and download the URL and build a preview
236236
237237
Args:
@@ -360,7 +360,7 @@ async def _do_preview(self, url: str, user: str, ts: int) -> bytes:
360360

361361
return jsonog.encode("utf8")
362362

363-
async def _download_url(self, url: str, user: str) -> MediaInfo:
363+
async def _download_url(self, url: str, user: UserID) -> MediaInfo:
364364
# TODO: we should probably honour robots.txt... except in practice
365365
# we're most likely being explicitly triggered by a human rather than a
366366
# bot, so are we really a robot?
@@ -450,7 +450,7 @@ async def _download_url(self, url: str, user: str) -> MediaInfo:
450450
)
451451

452452
async def _precache_image_url(
453-
self, user: str, media_info: MediaInfo, og: JsonDict
453+
self, user: UserID, media_info: MediaInfo, og: JsonDict
454454
) -> None:
455455
"""
456456
Pre-cache the image (if one exists) for posterity

synapse/storage/databases/main/media_repository.py

+84-57
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,25 @@
1313
# See the License for the specific language governing permissions and
1414
# limitations under the License.
1515
from enum import Enum
16-
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple
16+
from typing import (
17+
TYPE_CHECKING,
18+
Any,
19+
Collection,
20+
Dict,
21+
Iterable,
22+
List,
23+
Optional,
24+
Tuple,
25+
Union,
26+
)
1727

1828
from synapse.storage._base import SQLBaseStore
19-
from synapse.storage.database import DatabasePool
29+
from synapse.storage.database import (
30+
DatabasePool,
31+
LoggingDatabaseConnection,
32+
LoggingTransaction,
33+
)
34+
from synapse.types import JsonDict, UserID
2035

2136
if TYPE_CHECKING:
2237
from synapse.server import HomeServer
@@ -46,7 +61,12 @@ class MediaSortOrder(Enum):
4661

4762

4863
class MediaRepositoryBackgroundUpdateStore(SQLBaseStore):
49-
def __init__(self, database: DatabasePool, db_conn, hs: "HomeServer"):
64+
def __init__(
65+
self,
66+
database: DatabasePool,
67+
db_conn: LoggingDatabaseConnection,
68+
hs: "HomeServer",
69+
):
5070
super().__init__(database, db_conn, hs)
5171

5272
self.db_pool.updates.register_background_index_update(
@@ -102,13 +122,15 @@ def __init__(self, database: DatabasePool, db_conn, hs: "HomeServer"):
102122
self._drop_media_index_without_method,
103123
)
104124

105-
async def _drop_media_index_without_method(self, progress, batch_size):
125+
async def _drop_media_index_without_method(
126+
self, progress: JsonDict, batch_size: int
127+
) -> int:
106128
"""background update handler which removes the old constraints.
107129
108130
Note that this is only run on postgres.
109131
"""
110132

111-
def f(txn):
133+
def f(txn: LoggingTransaction) -> None:
112134
txn.execute(
113135
"ALTER TABLE local_media_repository_thumbnails DROP CONSTRAINT IF EXISTS local_media_repository_thumbn_media_id_thumbnail_width_thum_key"
114136
)
@@ -126,7 +148,12 @@ def f(txn):
126148
class MediaRepositoryStore(MediaRepositoryBackgroundUpdateStore):
127149
"""Persistence for attachments and avatars"""
128150

129-
def __init__(self, database: DatabasePool, db_conn, hs: "HomeServer"):
151+
def __init__(
152+
self,
153+
database: DatabasePool,
154+
db_conn: LoggingDatabaseConnection,
155+
hs: "HomeServer",
156+
):
130157
super().__init__(database, db_conn, hs)
131158
self.server_name = hs.hostname
132159

@@ -174,7 +201,9 @@ async def get_local_media_by_user_paginate(
174201
plus the total count of all the user's media
175202
"""
176203

177-
def get_local_media_by_user_paginate_txn(txn):
204+
def get_local_media_by_user_paginate_txn(
205+
txn: LoggingTransaction,
206+
) -> Tuple[List[Dict[str, Any]], int]:
178207

179208
# Set ordering
180209
order_by_column = MediaSortOrder(order_by).value
@@ -184,14 +213,14 @@ def get_local_media_by_user_paginate_txn(txn):
184213
else:
185214
order = "ASC"
186215

187-
args = [user_id]
216+
args: List[Union[str, int]] = [user_id]
188217
sql = """
189218
SELECT COUNT(*) as total_media
190219
FROM local_media_repository
191220
WHERE user_id = ?
192221
"""
193222
txn.execute(sql, args)
194-
count = txn.fetchone()[0]
223+
count = txn.fetchone()[0] # type: ignore[index]
195224

196225
sql = """
197226
SELECT
@@ -268,7 +297,7 @@ async def get_local_media_before(
268297
)
269298
sql += sql_keep
270299

271-
def _get_local_media_before_txn(txn):
300+
def _get_local_media_before_txn(txn: LoggingTransaction) -> List[str]:
272301
txn.execute(sql, (before_ts, before_ts, size_gt))
273302
return [row[0] for row in txn]
274303

@@ -278,13 +307,13 @@ def _get_local_media_before_txn(txn):
278307

279308
async def store_local_media(
280309
self,
281-
media_id,
282-
media_type,
283-
time_now_ms,
284-
upload_name,
285-
media_length,
286-
user_id,
287-
url_cache=None,
310+
media_id: str,
311+
media_type: str,
312+
time_now_ms: int,
313+
upload_name: Optional[str],
314+
media_length: int,
315+
user_id: UserID,
316+
url_cache: Optional[str] = None,
288317
) -> None:
289318
await self.db_pool.simple_insert(
290319
"local_media_repository",
@@ -315,7 +344,7 @@ async def get_url_cache(self, url: str, ts: int) -> Optional[Dict[str, Any]]:
315344
None if the URL isn't cached.
316345
"""
317346

318-
def get_url_cache_txn(txn):
347+
def get_url_cache_txn(txn: LoggingTransaction) -> Optional[Dict[str, Any]]:
319348
# get the most recently cached result (relative to the given ts)
320349
sql = (
321350
"SELECT response_code, etag, expires_ts, og, media_id, download_ts"
@@ -359,7 +388,7 @@ def get_url_cache_txn(txn):
359388

360389
async def store_url_cache(
361390
self, url, response_code, etag, expires_ts, og, media_id, download_ts
362-
):
391+
) -> None:
363392
await self.db_pool.simple_insert(
364393
"local_media_repository_url_cache",
365394
{
@@ -390,13 +419,13 @@ async def get_local_media_thumbnails(self, media_id: str) -> List[Dict[str, Any]
390419

391420
async def store_local_thumbnail(
392421
self,
393-
media_id,
394-
thumbnail_width,
395-
thumbnail_height,
396-
thumbnail_type,
397-
thumbnail_method,
398-
thumbnail_length,
399-
):
422+
media_id: str,
423+
thumbnail_width: int,
424+
thumbnail_height: int,
425+
thumbnail_type: str,
426+
thumbnail_method: str,
427+
thumbnail_length: int,
428+
) -> None:
400429
await self.db_pool.simple_upsert(
401430
table="local_media_repository_thumbnails",
402431
keyvalues={
@@ -430,14 +459,14 @@ async def get_cached_remote_media(
430459

431460
async def store_cached_remote_media(
432461
self,
433-
origin,
434-
media_id,
435-
media_type,
436-
media_length,
437-
time_now_ms,
438-
upload_name,
439-
filesystem_id,
440-
):
462+
origin: str,
463+
media_id: str,
464+
media_type: str,
465+
media_length: int,
466+
time_now_ms: int,
467+
upload_name: Optional[str],
468+
filesystem_id: str,
469+
) -> None:
441470
await self.db_pool.simple_insert(
442471
"remote_media_cache",
443472
{
@@ -458,7 +487,7 @@ async def update_cached_last_access_time(
458487
local_media: Iterable[str],
459488
remote_media: Iterable[Tuple[str, str]],
460489
time_ms: int,
461-
):
490+
) -> None:
462491
"""Updates the last access time of the given media
463492
464493
Args:
@@ -467,7 +496,7 @@ async def update_cached_last_access_time(
467496
time_ms: Current time in milliseconds
468497
"""
469498

470-
def update_cache_txn(txn):
499+
def update_cache_txn(txn: LoggingTransaction) -> None:
471500
sql = (
472501
"UPDATE remote_media_cache SET last_access_ts = ?"
473502
" WHERE media_origin = ? AND media_id = ?"
@@ -488,7 +517,7 @@ def update_cache_txn(txn):
488517

489518
txn.execute_batch(sql, ((time_ms, media_id) for media_id in local_media))
490519

491-
return await self.db_pool.runInteraction(
520+
await self.db_pool.runInteraction(
492521
"update_cached_last_access_time", update_cache_txn
493522
)
494523

@@ -542,15 +571,15 @@ async def get_remote_media_thumbnail(
542571

543572
async def store_remote_media_thumbnail(
544573
self,
545-
origin,
546-
media_id,
547-
filesystem_id,
548-
thumbnail_width,
549-
thumbnail_height,
550-
thumbnail_type,
551-
thumbnail_method,
552-
thumbnail_length,
553-
):
574+
origin: str,
575+
media_id: str,
576+
filesystem_id: str,
577+
thumbnail_width: int,
578+
thumbnail_height: int,
579+
thumbnail_type: str,
580+
thumbnail_method: str,
581+
thumbnail_length: int,
582+
) -> None:
554583
await self.db_pool.simple_upsert(
555584
table="remote_media_cache_thumbnails",
556585
keyvalues={
@@ -566,7 +595,7 @@ async def store_remote_media_thumbnail(
566595
desc="store_remote_media_thumbnail",
567596
)
568597

569-
async def get_remote_media_before(self, before_ts):
598+
async def get_remote_media_before(self, before_ts: int) -> List[Dict[str, str]]:
570599
sql = (
571600
"SELECT media_origin, media_id, filesystem_id"
572601
" FROM remote_media_cache"
@@ -602,26 +631,24 @@ async def get_expired_url_cache(self, now_ts: int) -> List[str]:
602631
" LIMIT 500"
603632
)
604633

605-
def _get_expired_url_cache_txn(txn):
634+
def _get_expired_url_cache_txn(txn: LoggingTransaction) -> List[str]:
606635
txn.execute(sql, (now_ts,))
607636
return [row[0] for row in txn]
608637

609638
return await self.db_pool.runInteraction(
610639
"get_expired_url_cache", _get_expired_url_cache_txn
611640
)
612641

613-
async def delete_url_cache(self, media_ids):
642+
async def delete_url_cache(self, media_ids: Collection[str]) -> None:
614643
if len(media_ids) == 0:
615644
return
616645

617646
sql = "DELETE FROM local_media_repository_url_cache WHERE media_id = ?"
618647

619-
def _delete_url_cache_txn(txn):
648+
def _delete_url_cache_txn(txn: LoggingTransaction) -> None:
620649
txn.execute_batch(sql, [(media_id,) for media_id in media_ids])
621650

622-
return await self.db_pool.runInteraction(
623-
"delete_url_cache", _delete_url_cache_txn
624-
)
651+
await self.db_pool.runInteraction("delete_url_cache", _delete_url_cache_txn)
625652

626653
async def get_url_cache_media_before(self, before_ts: int) -> List[str]:
627654
sql = (
@@ -631,19 +658,19 @@ async def get_url_cache_media_before(self, before_ts: int) -> List[str]:
631658
" LIMIT 500"
632659
)
633660

634-
def _get_url_cache_media_before_txn(txn):
661+
def _get_url_cache_media_before_txn(txn: LoggingTransaction) -> List[str]:
635662
txn.execute(sql, (before_ts,))
636663
return [row[0] for row in txn]
637664

638665
return await self.db_pool.runInteraction(
639666
"get_url_cache_media_before", _get_url_cache_media_before_txn
640667
)
641668

642-
async def delete_url_cache_media(self, media_ids):
669+
async def delete_url_cache_media(self, media_ids: Collection[str]) -> None:
643670
if len(media_ids) == 0:
644671
return
645672

646-
def _delete_url_cache_media_txn(txn):
673+
def _delete_url_cache_media_txn(txn: LoggingTransaction) -> None:
647674
sql = "DELETE FROM local_media_repository WHERE media_id = ?"
648675

649676
txn.execute_batch(sql, [(media_id,) for media_id in media_ids])
@@ -652,6 +679,6 @@ def _delete_url_cache_media_txn(txn):
652679

653680
txn.execute_batch(sql, [(media_id,) for media_id in media_ids])
654681

655-
return await self.db_pool.runInteraction(
682+
await self.db_pool.runInteraction(
656683
"delete_url_cache_media", _delete_url_cache_media_txn
657684
)

0 commit comments

Comments
 (0)