8000 fix: initial implementation of memory-safe streaming by shawkins · Pull Request #49028 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Draft
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package org.keycloak.models.cache.infinispan;

import java.util.HashMap;

import org.keycloak.connections.jpa.support.EntityManagers;

public class Managed<T> {

HashMap<String, T> map = new HashMap<>();

public T get(String key) {
return map.get(key);
}

public boolean containsKey(String key) {
return map.containsKey(key);
}

public void put(String id, T value) {
if (EntityManagers.isBatchMode()) {
return;
}
map.put(id, value);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -161,9 +161,9 @@ public class RealmCacheSession implements CacheRealmProvider {
protected boolean setRollbackOnly;

protected Map<String, RealmAdapter> managedRealms = new HashMap<>();
protected Map<String, ClientModel> managedApplications = new HashMap<>();
protected Managed<ClientModel> managedApplications = new Managed<>();
protected Map<String, ClientScopeAdapter> managedClientScopes = new HashMap<>();
protected Map<String, RoleAdapter> managedRoles = new HashMap<>();
protected Managed<RoleAdapter> managedRoles = new Managed<>();
protected Map<String, GroupAdapter> managedGroups = new HashMap<>();
protected Set<String> listInvalidations = new HashSet<>();
protected Set<String> invalidations = new HashSet<>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
package org.keycloak.models.cache.infinispan;

import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
Expand All @@ -31,7 +30,6 @@
import org.keycloak.cluster.ClusterProvider;
import org.keycloak.common.constants.ServiceAccountConstants;
import org.keycloak.component.ComponentModel;
import org.keycloak.connections.jpa.support.EntityManagers;
import org.keycloak.credential.CredentialInput;
import org.keycloak.models.ClientModel;
import org.keycloak.models.ClientScopeModel;
Expand Down Expand Up @@ -106,7 +104,7 @@ public class UserCacheSession implements UserCache, OnCreateComponent, OnUpdateC
protected Set<String> invalidations = new HashSet<>();
protected Set<String> realmInvalidations = new HashSet<>();
protected Set<InvalidationEvent> invalidationEvents = new HashSet<>(); // Events to be sent across cluster
protected Map<String, UserModel> managedUsers = new HashMap<>();
protected Managed<UserModel> managedUsers = new Managed<>();
private StoreManagers datastoreProvider;

public UserCacheSession(UserCacheManager cache, KeycloakSession session) {
Expand Down Expand Up @@ -928,9 +926,6 @@ public UserModel addUser(RealmModel realm, String id, String username, boolean a
}

private void addManagedUser(String id, UserModel user) {
if (EntityManagers.isBatchMode()) {
return;
}
managedUsers.put(id, user);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import jakarta.ws.rs.core.Response;

import org.keycloak.authorization.fgap.AdminPermissionsSchema;
import org.keycloak.connections.jpa.support.EntityManagers;
import org.keycloak.events.admin.OperationType;
import org.keycloak.events.admin.ResourceType;
import org.keycloak.events.admin.v2.AdminEventV2Builder;
Expand Down Expand Up @@ -134,11 +135,12 @@ public Stream<BaseClientRepresentation> getClients(@Nonnull RealmModel realm,
// When disabled, we fall back to in-memory filtering by VIEW_CLIENTS role.
boolean canView = AdminPermissionsSchema.SCHEMA.isAdminPermissionsEnabled(realm) || permissions.clients().canView();
try {
return realm.getClientsStream()
Supplier<Stream<BaseClientRepresentation>> supplier = () -> realm.getClientsStream()
.filter(client -> canView || permissions.clients().canView(client))
.filter(client -> client.getProtocol() != null)
.map(client -> getMapper(client.getProtocol()).fromModel(client, projectionOptions.getFields()))
.filter(java.util.Objects::nonNull);
return EntityManagers.streamInBatch(session, supplier, 100);
} catch (ModelException e) {
throw new ServiceException(e.getMessage(), Response.Status.BAD_REQUEST);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Stream;

import jakarta.persistence.EntityManager;
Expand Down Expand Up @@ -135,4 +137,42 @@ public static void runInBatch(KeycloakSession session, Runnable runnable, boolea
}
}

/**
* For read-only operations.
*
* The presumed usage is for top-level jax-rs methods, so there's no nesting logic
*/
public static <T> Stream<T> streamInBatch(KeycloakSession session, Supplier<Stream<T>> streamSupplier, int clearInterval) {
// TODO: not necessary if read-only
flush(session, false); // make sure the state entering the batch processing is committed

// TODO: hibnerate does support a read-only SessionImpl. it's not easily accessible to control that, but can be done with a nested entity manager
// so perhaps underneath the overall Session txn we could consider nesting a read-only Session to enforce that the business logic of endpoints are read-only

boolean isBatched = isBatchMode();
batchMode.set(true);
Runnable done = () -> {
if (!isBatched) {
batchMode.remove();
}
};
boolean success = false;
try {
Stream<T> result = streamSupplier.get();
AtomicInteger counter = new AtomicInteger();
result = result.map(value -> {
if (counter.incrementAndGet() % clearInterval == 0) {
forEachEntityManager(session, EntityManager::clear);
}
return value;
}).onClose(done);
success = true;
return result;
} finally {
if (!success) {
done.run();
}
}
}

}
0