|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +# Copyright 2021 The Matrix.org Foundation C.I.C. |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | +import json |
| 16 | +import logging |
| 17 | +from typing import List, Optional, Sequence, Set, Tuple |
| 18 | + |
| 19 | +import attr |
| 20 | + |
| 21 | +import synapse.util.stringutils as stringutils |
| 22 | +from synapse.api.errors import StoreError |
| 23 | +from synapse.storage._base import SQLBaseStore, db_to_json |
| 24 | +from synapse.storage.database import LoggingTransaction |
| 25 | + |
| 26 | +logger = logging.getLogger(__name__) |
| 27 | + |
| 28 | + |
| 29 | +@attr.s(slots=True, frozen=True, auto_attribs=True) |
| 30 | +class _PaginationSession: |
| 31 | + """The information that is stored for pagination.""" |
| 32 | + |
| 33 | + # The queue of rooms which are still to process as packed _RoomQueueEntry tuples. |
| 34 | + room_queue: List[Tuple[str, Sequence[str], int]] |
| 35 | + # A set of rooms which have been processed. |
| 36 | + processed_rooms: Set[str] |
| 37 | + |
| 38 | + |
| 39 | +class RoomSummaryStore(SQLBaseStore): |
| 40 | + """ |
| 41 | + Manage user interactive authentication sessions. |
| 42 | + """ |
| 43 | + |
| 44 | + async def create_room_hierarchy_pagination_session( |
| 45 | + self, |
| 46 | + room_id: str, |
| 47 | + suggested_only: bool, |
| 48 | + max_depth: Optional[int], |
| 49 | + room_queue: List[Tuple[str, Sequence[str], int]], |
| 50 | + processed_rooms: Set[str], |
| 51 | + ) -> str: |
| 52 | + """ |
| 53 | + Creates a new pagination session for the room hierarchy endpoint. |
| 54 | +
|
| 55 | + Args: |
| 56 | + room_id: The room ID the pagination session is for. |
| 57 | + suggested_only: Whether we should only return children with the |
| 58 | + "suggested" flag set. |
| 59 | + max_depth: The maximum depth in the tree to explore, must be a |
| 60 | + non-negative integer. |
| 61 | + room_queue: |
| 62 | + The queue of rooms which are still to process. |
| 63 | + processed_rooms: |
| 64 | + A set of rooms which have been processed. |
| 65 | +
|
| 66 | + Returns: |
| 67 | + The newly created session ID. |
| 68 | +
|
| 69 | + Raises: |
| 70 | + StoreError if a unique session ID cannot be generated. |
| 71 | + """ |
| 72 | + pagination_state = json.dumps( |
| 73 | + { |
| 74 | + "room_queue": room_queue, |
| 75 | + "processed_rooms": list(processed_rooms), |
| 76 | + } |
| 77 | + ) |
| 78 | + |
| 79 | + # autogen a session ID and try to create it. We may clash, so just |
| 80 | + # try a few times till one goes through, giving up eventually. |
| 81 | + attempts = 0 |
| 82 | + while attempts < 5: |
| 83 | + session_id = stringutils.random_string(24) |
| 84 | + |
| 85 | + try: |
| 86 | + await self.db_pool.simple_insert( |
| 87 | + table="room_hierarchy_pagination_sessions", |
| 88 | + values={ |
| 89 | + "session_id": session_id, |
| 90 | + "room_id": room_id, |
| 91 | + "suggested_only": suggested_only, |
| 92 | + "max_depth": max_depth, |
| 93 | + "pagination_state": pagination_state, |
| 94 | + "creation_time": self.hs.get_clock().time_msec(), |
| 95 | + }, |
| 96 | + desc="create_room_hierarchy_pagination_session", |
| 97 | + ) |
| 98 | + logger.debug( |
| 99 | + "Persisted room hierarchy pagination session: %s for room %s (suggested: %s, max_depth: %s)", |
| 100 | + session_id, |
| 101 | + room_id, |
| 102 | + suggested_only, |
| 103 | + max_depth, |
| 104 | + ) |
| 105 | + |
| 106 | + return session_id |
| 107 | + except self.db_pool.engine.module.IntegrityError: |
| 108 | + attempts += 1 |
| 109 | + raise StoreError(500, "Couldn't generate a session ID.") |
| 110 | + |
| 111 | + async def get_room_hierarchy_pagination_session( |
| 112 | + self, |
| 113 | + room_id: str, |
| 114 | + suggested_only: bool, |
| 115 | + max_depth: Optional[int], |
| 116 | + session_id: str, |
| 117 | + ) -> _PaginationSession: |
| 118 | + """ |
| 119 | + Retrieve data stored with set_session_data |
| 120 | +
|
| 121 | + Args: |
| 122 | + room_id: The room ID the pagination session is for. |
| 123 | + suggested_only: Whether we should only return children with the |
| 124 | + "suggested" flag set. |
| 125 | + max_depth: The maximum depth in the tree to explore, must be a |
| 126 | + non-negative integer. |
| 127 | + session_id: The pagination session ID. |
| 128 | +
|
| 129 | + Raises: |
| 130 | + StoreError if the session cannot be found. |
| 131 | + """ |
| 132 | + logger.debug( |
| 133 | + "Fetch room hierarchy pagination session: %s for room %s (suggested: %s, max_depth: %s)", |
| 134 | + session_id, |
| 135 | + room_id, |
| 136 | + suggested_only, |
| 137 | + max_depth, |
| 138 | + ) |
| 139 | + result = await self.db_pool.simple_select_one( |
| 140 | + table="room_hierarchy_pagination_sessions", |
| 141 | + keyvalues={ |
| 142 | + "session_id": session_id, |
| 143 | + "room_id": room_id, |
| 144 | + "suggested_only": suggested_only, |
| 145 | + }, |
| 146 | + retcols=( |
| 147 | + "max_depth", |
| 148 | + "pagination_state", |
| 149 | + ), |
| 150 | + desc="get_room_hierarchy_pagination_sessions", |
| 151 | + ) |
| 152 | + # Check the value of max_depth separately since null != null. |
| 153 | + if result["max_depth"] != max_depth: |
| 154 | + raise StoreError(404, "No row found (room_hierarchy_pagination_sessions)") |
| 155 | + |
| 156 | + pagination_state = db_to_json(result["pagination_state"]) |
| 157 | + |
| 158 | + return _PaginationSession( |
| 159 | + room_queue=pagination_state["room_queue"], |
| 160 | + processed_rooms=set(pagination_state["processed_rooms"]), |
| 161 | + ) |
| 162 | + |
| 163 | + async def delete_old_room_hierarchy_pagination_sessions( |
| 164 | + self, expiration_time: int |
| 165 | + ) -> None: |
| 166 | + """ |
| 167 | + Remove sessions which were last used earlier than the expiration time. |
| 168 | +
|
| 169 | + Args: |
| 170 | + expiration_time: The latest time that is still considered valid. |
| 171 | + This is an epoch time in milliseconds. |
| 172 | +
|
| 173 | + """ |
| 174 | + await self.db_pool.runInteraction( |
| 175 | + "delete_old_room_hierarchy_pagination_sessions", |
| 176 | + self._delete_old_room_hierarchy_pagination_sessions_txn, |
| 177 | + expiration_time, |
| 178 | + ) |
| 179 | + |
| 180 | + def _delete_old_room_hierarchy_pagination_sessions_txn( |
| 181 | + self, txn: LoggingTransaction, expiration_time: int |
| 182 | + ): |
| 183 | + # Get the expired sessions. |
| 184 | + sql = "DELETE FROM room_hierarchy_pagination_sessions WHERE creation_time <= ?" |
| 185 | + txn.execute(sql, [expiration_time]) |
0 commit comments