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

Add forward extremities endpoint to rooms admin API #9062

Merged
merged 18 commits into from
Jan 26, 2021
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/9062.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add admin API for getting and deleting forward extremities for a room.
53 changes: 53 additions & 0 deletions docs/admin_api/rooms.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
* [Response](#response)
* [Undoing room shutdowns](#undoing-room-shutdowns)
- [Make Room Admin API](#make-room-admin-api)
- [Forward Extremities Admin API](#forward-extremities-admin-api)

# List Room API

Expand Down Expand Up @@ -511,3 +512,55 @@ optionally be specified, e.g.:
"user_id": "@foo:example.com"
}
```

# Forward Extremities Admin API

Enables querying and deleting forward extremities from rooms. When a lot of forward
extremities accumulate in a room, performance can become degraded.
jaywink marked this conversation as resolved.
Show resolved Hide resolved

When using this API endpoint to delete any extra forward extremities for a room,
the server does not need to be restarted as the relevant caches will be cleared
in the API call.
jaywink marked this conversation as resolved.
Show resolved Hide resolved

## Check for forward extremities

To check the status of forward extremities for a room:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What sort of situations would you use this in? Is the state group useful?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, probably not particularly, except maybe for developers. I did think of returning just a count, but it felt that since the information "is there", it felt unnecessary to not return results as well.

My understanding of the needs for this API endpoint from an operational point of view is mainly to see the count, though I would maybe check with the EMS ops team first to confirm.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suspect that's just internal state then and not worth returning. @erikjohnston do you see any value in returning those?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've sometimes used the state group as a proxy for how big the state difference was between extremities were, but it's a bad heuristic. I think a more useful one would probably be depth and received_ts, as that'll give you a better way of looking for stuck extremities

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we consider those to be useful in this admin API? I guess the options are:

  1. keep as is
  2. remove state_group
  3. remove state_group, add depth and received_ts
  4. remove everything, just return a count
  5. something else? :)

I don't have enough experience on the extremities to vote really.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think adding depth and received_ts is probably the right thing


```
GET /_synapse/admin/v1/rooms/<room_id_or_alias>/forward_extremities
```

A response as follows will be returned:

```json
{
"count": 1,
"results": [
{
"event_id": "$M5SP266vsnxctfwFgFLNceaCo3ujhRtg_NiiHabcdfgh",
"state_group": 439
}
]
}
```

## Deleting forward extremities

In the event a room has lots of forward extremities, the extra can be
deleted as follows:
jaywink marked this conversation as resolved.
Show resolved Hide resolved

```
DELETE /_synapse/admin/v1/rooms/<room_id_or_alias>/forward_extremities
```

A response as follows will be returned, indicating the amount of forward extremities
that were deleted.

```json
{
"deleted": 1
}
```

The cache `get_latest_event_ids_in_room` will be invalidated, if any forward extremities
were deleted.
jaywink marked this conversation as resolved.
Show resolved Hide resolved
2 changes: 2 additions & 0 deletions synapse/rest/admin/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
from synapse.rest.admin.purge_room_servlet import PurgeRoomServlet
from synapse.rest.admin.rooms import (
DeleteRoomRestServlet,
ForwardExtremitiesRestServlet,
JoinRoomAliasServlet,
ListRoomRestServlet,
MakeRoomAdminRestServlet,
Expand Down Expand Up @@ -230,6 +231,7 @@ def register_servlets(hs, http_server):
EventReportsRestServlet(hs).register(http_server)
PushersRestServlet(hs).register(http_server)
MakeRoomAdminRestServlet(hs).register(http_server)
ForwardExtremitiesRestServlet(hs).register(http_server)


def register_servlets_for_client_rest_resource(hs, http_server):
Expand Down
57 changes: 57 additions & 0 deletions synapse/rest/admin/rooms.py
Original file line number Diff line number Diff line change
Expand Up @@ -499,3 +499,60 @@ async def on_POST(self, request, room_identifier):
)

return 200, {}


class ForwardExtremitiesRestServlet(RestServlet):
"""Allows a server admin to get or clear forward extremities.

Clearing does not require restarting the server.

Clear forward extremities:
DELETE /_synapse/admin/v1/rooms/<room_id_or_alias>/forward_extremities

Get forward_extremities:
GET /_synapse/admin/v1/rooms/<room_id_or_alias>/forward_extremities
"""

PATTERNS = admin_patterns("/rooms/(?P<room_identifier>[^/]*)/forward_extremities")

def __init__(self, hs: "HomeServer"):
self.hs = hs
self.auth = hs.get_auth()
self.room_member_handler = hs.get_room_member_handler()
self.store = hs.get_datastore()

async def resolve_room_id(self, room_identifier: str) -> str:
"""Resolve to a room ID, if necessary."""
if RoomID.is_valid(room_identifier):
resolved_room_id = room_identifier
elif RoomAlias.is_valid(room_identifier):
room_alias = RoomAlias.from_string(room_identifier)
room_id, _ = await self.room_member_handler.lookup_room_alias(room_alias)
resolved_room_id = room_id.to_string()
else:
raise SynapseError(
400, "%s was not legal room ID or room alias" % (room_identifier,)
)
if not resolved_room_id:
raise SynapseError(
400, "Unknown room ID or room alias %s" % room_identifier
)
return resolved_room_id

async def on_DELETE(self, request, room_identifier):
requester = await self.auth.get_user_by_req(request)
await assert_user_is_admin(self.auth, requester.user)

room_id = await self.resolve_room_id(room_identifier)

deleted_count = await self.store.delete_forward_extremities_for_room(room_id)
return 200, {"deleted": deleted_count}

async def on_GET(self, request, room_identifier):
requester = await self.auth.get_user_by_req(request)
await assert_user_is_admin(self.auth, requester.user)

room_id = await self.resolve_room_id(room_identifier)

extremities = await self.store.get_forward_extremities_for_room(room_id)
return 200, {"count": len(extremities), "results": extremities}
2 changes: 2 additions & 0 deletions synapse/storage/databases/main/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
from .event_federation import EventFederationStore
from .event_push_actions import EventPushActionsStore
from .events_bg_updates import EventsBackgroundUpdatesStore
from .events_forward_extremities import EventForwardExtremitiesStore
from .filtering import FilteringStore
from .group_server import GroupServerStore
from .keys import KeyStore
Expand Down Expand Up @@ -118,6 +119,7 @@ class DataStore(
UIAuthStore,
CacheInvalidationWorkerStore,
ServerMetricsStore,
EventForwardExtremitiesStore,
):
def __init__(self, database: DatabasePool, db_conn, hs):
self.hs = hs
Expand Down
92 changes: 92 additions & 0 deletions synapse/storage/databases/main/events_forward_extremities.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import logging
jaywink marked this conversation as resolved.
Show resolved Hide resolved
from typing import Dict, List

from synapse.api.errors import SynapseError
from synapse.storage._base import SQLBaseStore

logger = logging.getLogger(__name__)


class EventForwardExtremitiesStore(SQLBaseStore):
async def delete_forward_extremities_for_room(self, room_id: str) -> int:
"""Delete any extra forward extremities for a room.

Invalidates the "get_latest_event_ids_in_room" cache if any forward
extremities were deleted.

Returns count deleted.
"""

def delete_forward_extremities_for_room_txn(txn):
# First we need to get the event_id to not delete
sql = (
"SELECT "
jaywink marked this conversation as resolved.
Show resolved Hide resolved
" last_value(event_id) OVER w AS event_id"
" FROM event_forward_extremities"
" NATURAL JOIN events"
" where room_id = ?"
" WINDOW w AS ("
" PARTITION BY room_id"
" ORDER BY stream_ordering"
" range between unbounded preceding and unbounded following"
" )"
" ORDER BY stream_ordering"
clokep marked this conversation as resolved.
Show resolved Hide resolved
)
txn.execute(sql, (room_id,))
rows = txn.fetchall()
try:
event_id = rows[0][0]
logger.debug(
"Found event_id %s as the forward extremity to keep for room %s",
event_id,
room_id,
)
except KeyError:
msg = "No forward extremity event found for room %s" % room_id
logger.warning(msg)
raise SynapseError(400, msg)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we usually try to not raise synapse errors from the database layer, but I'm not finding a much better solution at the moment.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah I felt annoyed at this too, but didn't feel there was much to do, without separating the queries into separate transactions at least. I guess one thing could be raising some non-http error and then catching that in the servlet to raise a SynapseError? I didn't do it since I saw some other places use the SynapseError in db code.


# Now delete the extra forward extremities
sql = (
"DELETE FROM event_forward_extremities "
"WHERE"
" event_id != ?"
" AND room_id = ?"
)

txn.execute(sql, (event_id, room_id))
logger.info(
"Deleted %s extra forward extremities for room %s",
txn.rowcount,
room_id,
)

if txn.rowcount > 0:
# Invalidate the cache
self._invalidate_cache_and_stream(
txn, self.get_latest_event_ids_in_room, (room_id,),
)

return txn.rowcount

return await self.db_pool.runInteraction(
"delete_forward_extremities_for_room",
delete_forward_extremities_for_room_txn,
)

async def get_forward_extremities_for_room(self, room_id: str) -> List[Dict]:
"""Get list of forward extremities for a room."""

def get_forward_extremities_for_room_txn(txn):
sql = (
"SELECT event_id, state_group FROM event_forward_extremities NATURAL JOIN event_to_state_groups "
"WHERE room_id = ?"
)

txn.execute(sql, (room_id,))
rows = txn.fetchall()
return [{"event_id": row[0], "state_group": row[1]} for row in rows]
jaywink marked this conversation as resolved.
Show resolved Hide resolved

return await self.db_pool.runInteraction(
"get_forward_extremities_for_room", get_forward_extremities_for_room_txn,
)