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
92 changes: 78 additions & 14 deletions api/src/org/labkey/api/cache/CacheManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
import org.labkey.api.collections.CollectionUtils;
import org.labkey.api.data.Container;
import org.labkey.api.data.Project;
import org.labkey.api.exp.property.Domain;
import org.labkey.api.exp.property.DomainProperty;
import org.labkey.api.mbean.LabKeyManagement;
import org.labkey.api.security.User;
import org.labkey.api.util.GUID;
Expand All @@ -35,6 +37,8 @@
import java.lang.reflect.Field;
import java.lang.reflect.InaccessibleObjectException;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
Expand All @@ -45,7 +49,9 @@
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Supplier;

public class CacheManager
{
Expand Down Expand Up @@ -194,13 +200,44 @@ public static <K, V> void validate(String debugName, K key, @Nullable V value)
LOG.error("{} attempted to cache {}, which could be mutated by callers, at key {}", debugName, valueDescription, key);
}

// Flag values that hold a Container or User object
analyzeValue(value, debugName, null, 1);
// Flag values that hold a Container, User, or domain object
analyzeValue(value, debugName, null, 1, CLASSES, LOG::error);
}

private static final int MAX_DEPTH = 4;

private static void analyzeValue(@Nullable Object value, String cacheName, @Nullable String fieldPath, int depth)
// Domains go stale when saved, and domain saves don't clear other caches
private static final List<Class<?>> DOMAIN_TYPES = List.of(Domain.class, DomainProperty.class);
private static final List<Class<?>> UNSAFE_TYPES = List.of(Container.class, User.class, Project.class, Domain.class, DomainProperty.class);

/** Returns the unsafe type a field declares, or the domain type it declares as a type argument (e.g., List&lt;DomainProperty&gt;), or null */
private static @Nullable Class<?> getUnsafeType(Field field)
{
boolean exempt = field.isAnnotationPresent(InvalidatedOnDomainSave.class);
Class<?> type = field.getType();
if (UNSAFE_TYPES.stream().anyMatch(u -> u.isAssignableFrom(type)) && !(exempt && isDomainType(type)))
return type;

// Type arguments are checked for domain types only: Supplier<Container> and the user cache's maps are safe
if (!exempt && field.getGenericType() instanceof ParameterizedType pt)
{
for (Type arg : pt.getActualTypeArguments())
{
Type raw = arg instanceof ParameterizedType p ? p.getRawType() : arg;
if (raw instanceof Class<?> c && isDomainType(c))
return c;
}
}

return null;
}

private static boolean isDomainType(Class<?> type)
{
return DOMAIN_TYPES.stream().anyMatch(u -> u.isAssignableFrom(type));
}

private static void analyzeValue(@Nullable Object value, String cacheName, @Nullable String fieldPath, int depth, Set<Class<?>> analyzed, BiConsumer<String, Object[]> error)
{
if (value != null && depth < MAX_DEPTH)
{
Expand All @@ -211,42 +248,46 @@ private static void analyzeValue(@Nullable Object value, String cacheName, @Null
m.entrySet().stream()
.findFirst()
.ifPresent(entry -> {
analyzeValue(entry.getKey(), cacheName, safeAppend(fieldPath, "Map", "_key"), depth + 1);
analyzeValue(entry.getValue(), cacheName, safeAppend(fieldPath, "Map", "_value"), depth + 1);
analyzeValue(entry.getKey(), cacheName, safeAppend(fieldPath, "Map", "_key"), depth + 1, analyzed, error);
analyzeValue(entry.getValue(), cacheName, safeAppend(fieldPath, "Map", "_value"), depth + 1, analyzed, error);
});
}
else if (value instanceof Collection<?> coll)
{
coll.stream()
.findFirst()
.ifPresent(element -> analyzeValue(element, cacheName, safeAppend(fieldPath, coll.getClass().getSimpleName(), "get(0)"), depth + 1));
.ifPresent(element -> analyzeValue(element, cacheName, safeAppend(fieldPath, coll.getClass().getSimpleName(), "get(0)"), depth + 1, analyzed, error));
}
else if (clazz.isArray() && Array.getLength(value) > 0)
{
analyzeValue(Array.get(value, 0), cacheName, safeAppend(fieldPath, "Array", "[0]"), depth + 1);
analyzeValue(Array.get(value, 0), cacheName, safeAppend(fieldPath, "Array", "[0]"), depth + 1, analyzed, error);
}
else if (value instanceof Reference<?> ref)
{
analyzeValue(ref, cacheName, fieldPath, depth + 1);
analyzeValue(ref, cacheName, fieldPath, depth + 1, analyzed, error);
}
else if (isDomainType(clazz))
{
error.accept("Cached value is an unsafe object - {}: {} ({})", new Object[]{cacheName, fieldPath, clazz.getName()});
}
else if (CLASSES.add(clazz))
else if (analyzed.add(clazz))
{
for (Field field : getAllInstanceFields(clazz))
{
String newFieldPath = safeAppend(fieldPath, clazz.getSimpleName(), field.getName());
Class<?> type = field.getType();
Class<?> unsafeType = getUnsafeType(field);

if (Container.class.isAssignableFrom(type) || User.class.isAssignableFrom(type) || Project.class.isAssignableFrom(type))
if (unsafeType != null)
{
LOG.error("Cached value holds an unsafe object - {}: {} field {} ({})", cacheName, clazz.getName(), newFieldPath, field.getType().getName());
error.accept("Cached value holds an unsafe object - {}: {} field {} ({})", new Object[]{cacheName, clazz.getName(), newFieldPath, unsafeType.getName()});
}
else
else if (!field.isAnnotationPresent(InvalidatedOnDomainSave.class))
{
try
{
field.setAccessible(true);
Object val = field.get(value);
analyzeValue(val, cacheName, newFieldPath, depth + 1);
analyzeValue(val, cacheName, newFieldPath, depth + 1, analyzed, error);
}
catch (InaccessibleObjectException e)
{
Expand Down Expand Up @@ -291,6 +332,29 @@ public interface Sealable

public static class TestCase extends Assert
{
private record HoldsDomain(Domain domain) {}
private record HoldsProperties(List<DomainProperty> properties) {}
private record HoldsInvalidatedDomain(@InvalidatedOnDomainSave("test") Domain domain) {}
private record HoldsContainerSupplier(Supplier<Container> container) {}
private record HoldsUsers(List<User> users) {}

@Test
public void testDomainHoldersFlagged()
{
record Case(Object value, boolean flagged) {}
for (Case c : List.of(
new Case(new HoldsDomain(null), true),
new Case(new HoldsProperties(List.of()), true),
new Case(new HoldsInvalidatedDomain(null), false),
new Case(new HoldsContainerSupplier(null), false),
new Case(new HoldsUsers(List.of()), false)))
{
List<Object[]> errors = new ArrayList<>();
analyzeValue(c.value(), "test", null, 1, new HashSet<>(), (_, args) -> errors.add(args));
assertEquals(c.value().getClass().getSimpleName(), c.flagged(), !errors.isEmpty());
}
}

@Test
public void testContainerKeyRejected()
{
Expand Down
33 changes: 33 additions & 0 deletions api/src/org/labkey/api/cache/InvalidatedOnDomainSave.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* Copyright (c) 2026 LabKey Corporation
*
* 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.labkey.api.cache;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
* Exempts a Domain or DomainProperty field from CacheManager's cached-value check. Domain saves don't clear other
* caches, so use this only when the owning cache is evicted on save, typically from DomainKind.invalidate().
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface InvalidatedOnDomainSave
{
/** The code that evicts the cached holder when its domain is saved */
String value();
}
42 changes: 28 additions & 14 deletions api/src/org/labkey/api/data/CacheReplayCommitTask.java
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,18 @@ private record Op(@NotNull Object cache, @NotNull Kind kind, @Nullable Object ke
// Insertion order is replay order; a duplicate keeps the first one's position
private final Map<Op, Runnable> _operations = new LinkedHashMap<>();
private final Map<Object, Integer> _reloadCounts = new HashMap<>();
private final @Nullable DbScope _scope;

private CacheReplayCommitTask(@Nullable DbScope scope)
{
_scope = scope;
}

/** The replay task already queued in the transaction, or a newly queued one */
static CacheReplayCommitTask get(Transaction transaction)
{
return transaction.addCommitTask(new CacheReplayCommitTask(), DbScope.CommitTaskOption.POSTCOMMIT);
DbScope scope = transaction instanceof DbScope.TransactionImpl impl ? impl.getScope() : null;
return transaction.addCommitTask(new CacheReplayCommitTask(scope), DbScope.CommitTaskOption.POSTCOMMIT);
}

/** Queues the reload unless the cache already has limit reloads queued */
Expand Down Expand Up @@ -112,7 +119,14 @@ public void run()
{
// Copy guards against concurrent modification only: when commitAndKeepConnection() runs on a transaction that
// isn't the innermost, a reload registers operations here that never run, since clearCommitTasks() discards them
List.copyOf(_operations.values()).forEach(Runnable::run);
List<Runnable> operations = List.copyOf(_operations.values());

// Reload loaders query the transaction's scope, so they share one held borrow; removals and clears touch only memory
Runnable replay = () -> operations.forEach(Runnable::run);
if (null != _scope && _operations.keySet().stream().anyMatch(op -> op.kind() == Kind.RELOAD))
_scope.runHoldingThreadConnection(replay);
else
replay.run();
}

@Override
Expand Down Expand Up @@ -152,7 +166,7 @@ private List<String> run(CacheReplayCommitTask task)
@Test
public void runsOperationsInFirstRegistrationOrder()
{
CacheReplayCommitTask task = new CacheReplayCommitTask();
CacheReplayCommitTask task = new CacheReplayCommitTask(null);
task.remove("c1", "a", op("remove a"));
task.reload("c1", "b", 10, op("reload b"));
task.clear("c2", op("clear c2"));
Expand All @@ -163,7 +177,7 @@ public void runsOperationsInFirstRegistrationOrder()
@Test
public void capsReloadsPerCache()
{
CacheReplayCommitTask task = new CacheReplayCommitTask();
CacheReplayCommitTask task = new CacheReplayCommitTask(null);
task.reload("c1", "a", 2, op("1a"));
task.reload("c1", "a", 2, op("1a again")); // Duplicate doesn't count against the limit
task.reload("c1", "b", 2, op("1b"));
Expand All @@ -175,7 +189,7 @@ public void capsReloadsPerCache()
@Test
public void removalDropsEarlierReloadOfTheKey()
{
CacheReplayCommitTask task = new CacheReplayCommitTask();
CacheReplayCommitTask task = new CacheReplayCommitTask(null);
task.reload("c1", "a", 10, op("reload a"));
task.reload("c1", "b", 10, op("reload b"));
task.reload("c2", "a", 10, op("reload c2 a"));
Expand All @@ -187,7 +201,7 @@ public void removalDropsEarlierReloadOfTheKey()
@Test
public void repeatedRemovalDropsReloadBetweenAndKeepsFirstPosition()
{
CacheReplayCommitTask task = new CacheReplayCommitTask();
CacheReplayCommitTask task = new CacheReplayCommitTask(null);
task.remove("c1", "a", op("remove a"));
task.reload("c1", "b", 10, op("reload b"));
task.reload("c1", "a", 10, op("reload a"));
Expand All @@ -198,7 +212,7 @@ public void repeatedRemovalDropsReloadBetweenAndKeepsFirstPosition()
@Test
public void operationRegisteredDuringReplayDoesNotRun()
{
CacheReplayCommitTask task = new CacheReplayCommitTask();
CacheReplayCommitTask task = new CacheReplayCommitTask(null);
task.reload("c1", "a", 10, () -> {
_log.add("reload a");
task.reload("c1", "b", 10, op("reload b"));
Expand All @@ -211,7 +225,7 @@ public void operationRegisteredDuringReplayDoesNotRun()
@Test
public void droppedReloadFreesItsSlot()
{
CacheReplayCommitTask task = new CacheReplayCommitTask();
CacheReplayCommitTask task = new CacheReplayCommitTask(null);
task.reload("c1", "a", 1, op("reload a"));
task.remove("c1", "a", op("remove a"));
task.reload("c1", "b", 1, op("reload b"));
Expand All @@ -221,7 +235,7 @@ public void droppedReloadFreesItsSlot()
@Test
public void filterDropsEarlierMatchingReloads()
{
CacheReplayCommitTask task = new CacheReplayCommitTask();
CacheReplayCommitTask task = new CacheReplayCommitTask(null);
task.reload("c1", "a1", 2, op("reload a1"));
task.reload("c1", "b1", 2, op("reload b1"));
task.reload("c2", "a1", 2, op("reload c2 a1"));
Expand All @@ -233,7 +247,7 @@ public void filterDropsEarlierMatchingReloads()
@Test
public void clearReplacesTheCachesOperationsAtItsEarliestInvalidation()
{
CacheReplayCommitTask task = new CacheReplayCommitTask();
CacheReplayCommitTask task = new CacheReplayCommitTask(null);
task.reload("c1", "a", 1, op("reload a"));
task.remove("c1", "b", op("remove b"));
task.removeUsingFilter("c1", (String key) -> false, op("filter"));
Expand All @@ -248,7 +262,7 @@ public void clearReplacesTheCachesOperationsAtItsEarliestInvalidation()
@Test
public void clearNeverRunsAfterAReloadQueuedBehindAnEarlierInvalidation()
{
CacheReplayCommitTask task = new CacheReplayCommitTask();
CacheReplayCommitTask task = new CacheReplayCommitTask(null);
task.clear("c1", op("clear c1"));
task.reload("c2", "x", 10, op("reload c2 x"));
task.clear("c1", op("clear c1 again"));
Expand All @@ -261,7 +275,7 @@ public void clearNeverRunsAfterAReloadQueuedBehindAnEarlierInvalidation()
@Test
public void clearIsAppendedWhenTheCacheHasNoEarlierInvalidation()
{
CacheReplayCommitTask task = new CacheReplayCommitTask();
CacheReplayCommitTask task = new CacheReplayCommitTask(null);
task.reload("c1", "a", 1, op("reload a"));
task.remove("c2", "b", op("remove c2 b"));
task.clear("c1", op("clear"));
Expand All @@ -271,8 +285,8 @@ public void clearIsAppendedWhenTheCacheHasNoEarlierInvalidation()
@Test
public void allInstancesAreEqual()
{
assertEquals(new CacheReplayCommitTask(), new CacheReplayCommitTask());
assertEquals(new CacheReplayCommitTask().hashCode(), new CacheReplayCommitTask().hashCode());
assertEquals(new CacheReplayCommitTask(null), new CacheReplayCommitTask(null));
assertEquals(new CacheReplayCommitTask(null).hashCode(), new CacheReplayCommitTask(null).hashCode());
}
}
}
Loading