From b436ce858dfa6e1a4311b3bcb976319678e27d6a Mon Sep 17 00:00:00 2001 From: Till Faelligen Date: Thu, 2 Jun 2022 16:47:14 +0200 Subject: [PATCH] Make Setting state twice is idempotent pass --- clientapi/routing/sendevent.go | 44 ++++++++++++++++++++++++++++++++-- 1 file changed, 42 insertions(+), 2 deletions(-) diff --git a/clientapi/routing/sendevent.go b/clientapi/routing/sendevent.go index 70bf72f88..4e64f3419 100644 --- a/clientapi/routing/sendevent.go +++ b/clientapi/routing/sendevent.go @@ -19,6 +19,7 @@ import ( "encoding/json" "fmt" "net/http" + "reflect" "sync" "time" @@ -96,14 +97,21 @@ func SendEvent( mutex.(*sync.Mutex).Lock() defer mutex.(*sync.Mutex).Unlock() - startedGeneratingEvent := time.Now() - var r map[string]interface{} // must be a JSON object resErr := httputil.UnmarshalJSONRequest(req, &r) if resErr != nil { return *resErr } + if stateKey != nil { + // If the existing/new state content are equal, return the existing event id -> making the request idempotent. + if resp := stateEqual(req.Context(), rsAPI, eventType, *stateKey, roomID, r); resp != nil { + return *resp + } + } + + startedGeneratingEvent := time.Now() + // If we're sending a membership update, make sure to strip the authorised // via key if it is present, otherwise other servers won't be able to auth // the event if the room is set to the "restricted" join rule. @@ -208,6 +216,38 @@ func SendEvent( return res } +// stateEqual compares the new and the existing state event content. If they are equal, returns a *util.JSONResponse +// with the existing event_ID -> making this an idempotent request. +func stateEqual(ctx context.Context, rsAPI api.ClientRoomserverAPI, eventType, stateKey, roomID string, newContent map[string]interface{}) *util.JSONResponse { + stateRes := api.QueryCurrentStateResponse{} + tuple := gomatrixserverlib.StateKeyTuple{ + EventType: eventType, + StateKey: stateKey, + } + err := rsAPI.QueryCurrentState(ctx, &api.QueryCurrentStateRequest{ + RoomID: roomID, + StateTuples: []gomatrixserverlib.StateKeyTuple{tuple}, + }, &stateRes) + if err != nil { + return nil + } + if len(stateRes.StateEvents) > 0 { + existingEvent := stateRes.StateEvents[tuple] + var existingContent map[string]interface{} + if err = json.Unmarshal(existingEvent.Content(), &existingContent); err != nil { + return nil + } + if reflect.DeepEqual(existingContent, newContent) { + return &util.JSONResponse{ + Code: http.StatusOK, + JSON: sendEventResponse{existingEvent.EventID()}, + } + } + + } + return nil +} + func generateSendEvent( ctx context.Context, r map[string]interface{},