/*
 * Copyright 2017 Red Hat, Inc. and/or its affiliates
 * and other contributors as indicated by the @author tags.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.keycloak.models.sessions.infinispan.changes.sessions;

import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.jboss.logging.Logger;
import org.keycloak.common.util.Time;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.session.UserSessionPersisterProvider;
import org.keycloak.models.utils.SessionTimeoutHelper;

/**
 * The store is supposed to do periodic bulk update of lastSessionRefresh times of all userSessions, which were refreshed during some period
 * of time. The updates are sent to UserSessionPersisterProvider (DB)
 *
 * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
 */
public class PersisterLastSessionRefreshStore extends AbstractLastSessionRefreshStore {

    protected static final Logger logger = Logger.getLogger(PersisterLastSessionRefreshStore.class);

    private final boolean offline;

    protected PersisterLastSessionRefreshStore(int maxIntervalBetweenMessagesSeconds, int maxCount, boolean offline) {
        super(maxIntervalBetweenMessagesSeconds, maxCount);
        this.offline = offline;
    }


    protected void sendMessage(KeycloakSession kcSession, Map<String, SessionData> refreshesToSend) {
        Map<String, Set<String>> sessionIdsByRealm =
                refreshesToSend.entrySet().stream().collect(
                        Collectors.groupingBy(entry -> entry.getValue().getRealmId(),
                                Collectors.mapping(Map.Entry::getKey, Collectors.toSet())));

        // Update DB with a bit lower value than current time to ensure 'revokeRefreshToken' will work correctly taking server
        int lastSessionRefresh = Time.currentTime() - SessionTimeoutHelper.PERIODIC_TASK_INTERVAL_SECONDS;

        if (logger.isDebugEnabled()) {
            logger.debugf("Updating %d userSessions with lastSessionRefresh: %d", refreshesToSend.size(), lastSessionRefresh);
        }

        UserSessionPersisterProvider persister = kcSession.getProvider(UserSessionPersisterProvider.class);

        for (Map.Entry<String, Set<String>> entry : sessionIdsByRealm.entrySet()) {
            RealmModel realm = kcSession.realms().getRealm(entry.getKey());

            // Case when realm was deleted in the meantime. UserSessions were already deleted as well (callback for realm deletion)
            if (realm == null) {
                continue;
            }

            Set<String> userSessionIds = entry.getValue();

            persister.updateLastSessionRefreshes(realm, lastSessionRefresh, userSessionIds, offline);
        }
    }
}

@@ -780,16 +780,42 @@
 il.Set;%0A
+import java.util.TreeSet;%0A
 import j
@@ -1058,24 +1058,77 @@
 erProvider;%0A
+import org.keycloak.models.utils.KeycloakModelUtils;%0A
 import org.k
@@ -2725,193 +2725,393 @@
     
-UserSessionPersisterProvider persister = kcSession.getProvider(UserSessionPersisterProvider.class);%0A%0A        for (Map.Entry%3CString, Set%3CString%3E%3E entry : sessionIdsByRealm.entrySet()) %7B%0A
+// Separate transaction for each bulk update request to avoid deadlocks%0A        for (Map.Entry%3CString, Set%3CString%3E%3E entry : sessionIdsByRealm.entrySet()) %7B%0A            KeycloakModelUtils.runJobInTransaction(kcSession.getKeycloakSessionFactory(), (kcSession2) -%3E %7B%0A                UserSessionPersisterProvider persister = kcSession2.getProvider(UserSessionPersisterProvider.class);%0A    
     
@@ -3146,16 +3146,17 @@
 cSession
+2
 .realms(
@@ -3200,20 +3200,46 @@
     
-// Case when
+    // If realm is null, it means that
  rea
@@ -3350,24 +3350,28 @@
             
+    
 if (realm ==
@@ -3368,17 +3368,17 @@
  (realm 
-=
+!
 = null) 
@@ -3393,39 +3393,8 @@
     
-    
-  continue;%0A            %7D%0A%0A
     
@@ -3399,18 +3399,16 @@
         
-  
 Set%3CStri
@@ -3428,16 +3428,30 @@
 onIds = 
+new TreeSet%3C%3E(
 entry.ge
@@ -3458,19 +3458,28 @@
 tValue()
+)
 ;%0A%0A
+        
         
@@ -3572,16 +3572,50 @@
 fline);%0A
+                %7D%0A            %7D);%0A
         

Use separate transactions for each bulk update of offline sessions in PersisterLastSessionRefreshStore to avoid deadlocks closes #13684