Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
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
228 changes: 97 additions & 131 deletions announcements/src/org/labkey/announcements/AnnouncementsController.java

Large diffs are not rendered by default.

39 changes: 19 additions & 20 deletions api/src/org/labkey/api/action/ApiQueryResponse.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,14 @@
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.labkey.api.collections.ResultSetRowMapFactory;
import org.labkey.api.data.ColumnInfo;
import org.labkey.api.data.Container;
import org.labkey.api.data.ContainerFilter;
import org.labkey.api.data.ContainerManager;
import org.labkey.api.data.DataRegion;
import org.labkey.api.data.DetailsColumn;
Expand All @@ -40,6 +41,7 @@
import org.labkey.api.data.UpdateColumn;
import org.labkey.api.exp.PropertyColumn;
import org.labkey.api.query.FieldKey;
import org.labkey.api.query.QueryParam;
import org.labkey.api.query.QueryService;
import org.labkey.api.query.QuerySettings;
import org.labkey.api.query.QueryView;
Expand Down Expand Up @@ -801,11 +803,12 @@ public static class TestCase extends Assert
{
private static final String FOLDER_NAME = "ApiQueryResponseTest";

private User _user;
private Container _folder;
private static User _user;
private static Container _folder;

@Before
public void setUp() throws Exception
// The tests only read, so one fixture serves the class
@BeforeClass
public static void setUp()
{
_user = TestContext.get().getUser();
Container testContainer = JunitUtil.getTestContainer();
Expand All @@ -817,17 +820,18 @@ public void setUp() throws Exception
ContainerManager.createContainer(_folder, "child2", _user);
}

@After
public void tearDown() throws Exception
@AfterClass
public static void tearDown()
{
if (null != _folder)
ContainerManager.deleteAll(_folder, _user);
}

/** Each pair renders the same rows streamed and through the map-based writeRow */
@Test
public void testStreamedRowsMatchMap() throws Exception
{
assertRowsMatch(view -> new ApiQueryResponse(view, false, true, "core", "Containers", 0, null, false, true, true, true),
assertRowsMatch("ApiQueryResponse", view -> new ApiQueryResponse(view, false, true, "core", "Containers", 0, null, false, true, true, true),
view -> new ApiQueryResponse(view, false, true, "core", "Containers", 0, null, false, true, true, true)
{
@Override
Expand All @@ -836,12 +840,7 @@ protected void writeRow(ApiResponseWriter writer) throws IOException
writer.writeListEntry(getRow());
}
});
}

@Test
public void testStreamedExtendedRowsMatchMap() throws Exception
{
assertRowsMatch(view -> configure(new ExtendedApiQueryResponse(view, false, true, "core", "Containers", 0, null, false, true, true)),
assertRowsMatch("ExtendedApiQueryResponse", view -> configure(new ExtendedApiQueryResponse(view, false, true, "core", "Containers", 0, null, false, true, true)),
view -> configure(new ExtendedApiQueryResponse(view, false, true, "core", "Containers", 0, null, false, true, true)
{
@Override
Expand All @@ -859,19 +858,19 @@ private static ApiQueryResponse configure(ExtendedApiQueryResponse response)
return response;
}

private void assertRowsMatch(Function<QueryView, ApiQueryResponse> streamed, Function<QueryView, ApiQueryResponse> mapped) throws Exception
private void assertRowsMatch(String name, Function<QueryView, ApiQueryResponse> streamed, Function<QueryView, ApiQueryResponse> mapped) throws Exception
{
JSONArray expected = render(mapped);
assertEquals("Expected the folder and its two children", 3, expected.length());
assertEquals(expected.toList(), render(streamed).toList());
assertEquals(name + ": expected the folder and its two children", 3, expected.length());
assertEquals(name, expected.toList(), render(streamed).toList());
}

private JSONArray render(Function<QueryView, ApiQueryResponse> factory) throws Exception
{
UserSchema schema = QueryService.get().getUserSchema(_user, _folder, "core");
MutablePropertyValues mpv = new MutablePropertyValues();
mpv.addPropertyValue("query.queryName", "Containers");
mpv.addPropertyValue("query" + DataRegion.CONTAINER_FILTER_NAME, "CurrentAndSubfolders");
mpv.addPropertyValue("query." + QueryParam.queryName, "Containers");
mpv.addPropertyValue("query" + DataRegion.CONTAINER_FILTER_NAME, ContainerFilter.Type.CurrentAndSubfolders.name());
mpv.addPropertyValue("query.sort", "RowId");
QuerySettings settings = schema.getSettings(mpv, "query");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.json.JSONObject;
import org.labkey.api.audit.AbstractAuditTypeProvider;
import org.labkey.api.audit.AuditLogService;
import org.labkey.api.audit.TransactionAuditProvider;
import org.junit.After;
Expand Down Expand Up @@ -335,7 +336,7 @@ private static PendingFileAudit audit(String comment, FileLike file)

private static List<FileSystemAuditProvider.FileSystemAuditEvent> selectEvents(String comment)
{
SimpleFilter filter = new SimpleFilter(FieldKey.fromParts("Comment"), comment);
SimpleFilter filter = new SimpleFilter(FieldKey.fromParts(AbstractAuditTypeProvider.COLUMN_NAME_COMMENT), comment);
return AuditLogService.get().getAuditEvents(JunitUtil.getTestContainer(), TestContext.get().getUser(), FileSystemAuditProvider.EVENT_TYPE, filter, null);
}
}
Expand Down
4 changes: 2 additions & 2 deletions api/src/org/labkey/api/cache/BlockingCache.java
Original file line number Diff line number Diff line change
Expand Up @@ -315,7 +315,7 @@ private CacheLoader<Integer, Integer> createLoader(final AtomicInteger calls, fi
public void testBlockingGet()
{
final AtomicInteger calls = new AtomicInteger();
final BlockingCache<Integer,Integer> bc = new BlockingCache<>(_cache, createLoader(calls, 1000));
final BlockingCache<Integer,Integer> bc = new BlockingCache<>(_cache, createLoader(calls, 200));
final CountDownLatch start = new CountDownLatch(1);
Runnable r = () -> {
Random r1 = new Random();
Expand Down Expand Up @@ -348,7 +348,7 @@ private void createAndStartThreads(Runnable r, CountDownLatch start, int count)
public void testTimeout()
{
final AtomicInteger calls = new AtomicInteger();
final BlockingCache<Integer, Integer> bc = new BlockingCache<>(_cache, createLoader(calls, 5000), 1000);
final BlockingCache<Integer, Integer> bc = new BlockingCache<>(_cache, createLoader(calls, 3000), 1000);

final AtomicInteger timeouts = new AtomicInteger();
final CountDownLatch start = new CountDownLatch(1);
Expand Down
3 changes: 2 additions & 1 deletion api/src/org/labkey/api/cache/CacheManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import org.labkey.api.cache.ehcache.EhCacheProvider;
import org.labkey.api.collections.CollectionUtils;
import org.labkey.api.data.Container;
import org.labkey.api.data.ContainerManager;
import org.labkey.api.data.Project;
import org.labkey.api.mbean.LabKeyManagement;
import org.labkey.api.security.User;
Expand Down Expand Up @@ -296,7 +297,7 @@ public void testContainerKeyRejected()
{
try (Cache<Object, String> cache = getTemporaryCache(Object.class, 10, MINUTE, "Container key test", null))
{
Container c = new Container(null, "", GUID.makeGUID(), 1, 1, null, 0, false);
Container c = ContainerManager.createFakeContainer("CacheKeyTest", null);
assertThrows(IllegalArgumentException.class, () -> cache.put(c, "value"));
assertThrows(IllegalArgumentException.class, () -> cache.put(c, "value", MINUTE));
assertThrows(IllegalArgumentException.class, () -> cache.get(c, null, (key, argument) -> "loaded"));
Expand Down
55 changes: 30 additions & 25 deletions api/src/org/labkey/api/data/AsyncQueryRequest.java
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ public class AsyncQueryRequest<T>
private static final String CLIENT_DISCONNECTED_TAG = "labkey.client_disconnected";
private static final String ELAPSED_TAG = "labkey.async_query.ms";
private static final long WORKER_EXIT_TIMEOUT_MS = 10_000;
private static volatile long _workerExitTimeoutMs = WORKER_EXIT_TIMEOUT_MS;

/** Cancelled workers whose requests stopped waiting for them, re-cancelled by the request timeout sweep until they finish */
private static final Set<AsyncQueryRequest<?>> _detached = ConcurrentHashMap.newKeySet();
Expand Down Expand Up @@ -308,13 +309,14 @@ synchronized public T waitForResult(final Callable<T> callable) throws SQLExcept
*/
synchronized private void awaitWorkerAfterInterrupt(Thread worker)
{
long deadline = System.currentTimeMillis() + WORKER_EXIT_TIMEOUT_MS;
long timeout = _workerExitTimeoutMs;
long deadline = System.currentTimeMillis() + timeout;
while (!_finished)
{
long remaining = deadline - System.currentTimeMillis();
if (remaining <= 0)
{
_log.warn("Async query thread '{}' still running {} ms after its request was interrupted", worker.getName(), WORKER_EXIT_TIMEOUT_MS);
_log.warn("Async query thread '{}' still running {} ms after its request was interrupted", worker.getName(), timeout);
// The worker still holds this thread's connection. Detaching keeps the thread's next request off it; marking
// discards it even if this request's cleanup releases it while the worker is still using it.
ConnectionWrapper.getConnectionsByScopeForEffectiveThread(Thread.currentThread()).values().forEach(c -> c.forEach(ConnectionWrapper::markCancelled));
Expand Down Expand Up @@ -559,16 +561,8 @@ public void testInterruptReleasesConnection() throws Exception
}
}, "AsyncQueryRequest interrupt test " + i);

long start = System.currentTimeMillis();
requestThread.start();
while (ConnectionWrapper.getConnectionsByScopeForEffectiveThread(requestThread).isEmpty() && System.currentTimeMillis() - start < 10_000)
{
//noinspection BusyWait
Thread.sleep(50);
}
// Let the statement reach the server
Thread.sleep(300);
ConnectionWrapper.getConnectionsByScopeForEffectiveThread(requestThread).values().forEach(c -> c.forEach(w -> spids.add(w.getSPID())));
RequestTestUtil.awaitStatementStarted(requestThread).values().forEach(c -> c.forEach(w -> spids.add(w.getSPID())));

requestThread.interrupt();
requestThread.join(30_000);
Expand All @@ -578,7 +572,7 @@ public void testInterruptReleasesConnection() throws Exception
assertTrue("Request thread's connection holder is still referenced", holderReleased.get());
assertNull("Next query on the request thread failed", nextQueryFailure.get());
assertFalse("Interrupted query had no connections", spids.isEmpty());
assertEquals("Cancelled session went back to the pool", 0, RequestCancellation.TestCase.countLiveBackends(scope, spids));
assertEquals("Cancelled session went back to the pool", 0, RequestTestUtil.countLiveBackends(scope, spids));
}
}

Expand Down Expand Up @@ -643,7 +637,7 @@ public void testStuckWorkerDetached() throws Exception
}
}, "AsyncQueryRequest stuck worker test");

try
try (AutoCloseable _ = overrideWorkerExitTimeout())
{
requestThread.start();
assertTrue("Worker never got a connection", holding.await(10, TimeUnit.SECONDS));
Expand All @@ -663,7 +657,7 @@ public void testStuckWorkerDetached() throws Exception

assertTrue("Worker didn't finish", workerDone.await(10, TimeUnit.SECONDS));
assertNull("Worker's connection release failed", workerFailure.get());
assertEquals("Stuck worker's session went back to the pool", 0, RequestCancellation.TestCase.countLiveBackends(scope, Set.of(workerSpid.get())));
assertEquals("Stuck worker's session went back to the pool", 0, RequestTestUtil.countLiveBackends(scope, Set.of(workerSpid.get())));
}

/** A query that reaches the database only after its request stopped waiting, where Statement.cancel() can't stop it, must still be cancelled */
Expand Down Expand Up @@ -719,17 +713,28 @@ public void testDetachedWorkerCancelled() throws Exception
}
}, "AsyncQueryRequest detached worker test");

requestThread.start();
assertTrue("Worker never registered its statement", registered.await(10, TimeUnit.SECONDS));
requestThread.interrupt();
requestThread.join(WORKER_EXIT_TIMEOUT_MS + 10_000);
assertFalse("Request thread didn't exit", requestThread.isAlive());
assertTrue("Expected an aborted request, got " + failure.get(), failure.get() instanceof AbortedRequestException);

// The sweep's 5 s interval, with slack
assertTrue("Worker didn't finish", workerDone.await(20, TimeUnit.SECONDS));
assertTrue("Query wasn't cancelled: " + queryFailure.get(), queryFailure.get() instanceof SQLException e && SqlDialect.isCancelException(e));
assertTrue("Cancel took too long: " + queryMs.get() + " ms", queryMs.get() < 15_000);
try (AutoCloseable _ = overrideWorkerExitTimeout();
AutoCloseable _ = TransactionFilter.shortenSweepInterval())
{
requestThread.start();
assertTrue("Worker never registered its statement", registered.await(10, TimeUnit.SECONDS));
requestThread.interrupt();
requestThread.join(WORKER_EXIT_TIMEOUT_MS + 10_000);
assertFalse("Request thread didn't exit", requestThread.isAlive());
assertTrue("Expected an aborted request, got " + failure.get(), failure.get() instanceof AbortedRequestException);

// The sweep's interval, with slack
assertTrue("Worker didn't finish", workerDone.await(20, TimeUnit.SECONDS));
assertTrue("Query wasn't cancelled: " + queryFailure.get(), queryFailure.get() instanceof SQLException e && SqlDialect.isCancelException(e));
assertTrue("Cancel took too long: " + queryMs.get() + " ms", queryMs.get() < 15_000);
}
}

/** Shortens the wait for a stuck worker server-wide; close the result to restore it */
private static AutoCloseable overrideWorkerExitTimeout()
{
_workerExitTimeoutMs = 1_000;
return () -> _workerExitTimeoutMs = WORKER_EXIT_TIMEOUT_MS;
}
}
}
25 changes: 5 additions & 20 deletions api/src/org/labkey/api/data/ConnectionUsage.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.function.ThrowingRunnable;
import org.labkey.api.util.JunitUtil;

import java.sql.Connection;
import java.util.ArrayList;
Expand Down Expand Up @@ -243,31 +245,14 @@ public void restore()
private static Snapshot measureOnNewThread(ThrowingRunnable block) throws Exception
{
AtomicReference<Snapshot> result = new AtomicReference<>();
AtomicReference<Throwable> failure = new AtomicReference<>();
Thread thread = new Thread(() -> {
JunitUtil.runOnNewThread("ConnectionUsage test", () -> {
Mark mark = mark();
try
{
block.run();
}
catch (Throwable t)
{
failure.set(t);
}
block.run();
result.set(measure(mark));
}, "ConnectionUsage test");
thread.start();
thread.join();
if (null != failure.get())
throw new AssertionError("Failure on test thread", failure.get());
});
return result.get();
}

private interface ThrowingRunnable
{
void run() throws Exception;
}

@Test
public void testConcurrentPooledBorrows() throws Exception
{
Expand Down
60 changes: 16 additions & 44 deletions api/src/org/labkey/api/data/RepeatedCommitTaskMonitor.java
Original file line number Diff line number Diff line change
Expand Up @@ -368,14 +368,6 @@ public void tallyIsPerQueue()

public static class IntegrationTestCase extends Assert
{
private record ValueTask(int i) implements Runnable
{
@Override
public void run()
{
}
}

private static class NoOpAccumulatingTask extends AccumulatingCommitTask<String, Integer>
{
NoOpAccumulatingTask()
Expand Down Expand Up @@ -417,44 +409,24 @@ private static int tallyTransactions(RepeatedTaskWarning key)
return tally != null ? tally.transactions() : 0;
}

@Test
public void warnsAtTheThreshold()
{
assertEquals(1, warningsFor(true, THRESHOLD, i -> scope().addCommitTask(TestCase.task(i), CommitTaskOption.POSTCOMMIT)));
}

@Test
public void silentBelowTheThreshold()
{
assertEquals(0, warningsFor(true, THRESHOLD - 1, i -> scope().addCommitTask(TestCase.task(i), CommitTaskOption.POSTCOMMIT)));
}
private record Case(String name, int expectedWarnings, boolean commit, int count, IntConsumer register) {}

@Test
public void silentForDedupedTasks()
{
assertEquals(0, warningsFor(true, THRESHOLD, i -> scope().addCommitTask(new ValueTask(0), CommitTaskOption.POSTCOMMIT)));
}

@Test
public void silentForAccumulatingTask()
{
assertEquals(0, warningsFor(true, THRESHOLD, i -> new NoOpAccumulatingTask().register(scope(), List.of(i), CommitTaskOption.POSTCOMMIT)));
}

@Test
public void warnsForEachQueue()
{
assertEquals(2, warningsFor(true, THRESHOLD, i -> {
scope().addCommitTask(TestCase.task(i), CommitTaskOption.PRECOMMIT);
scope().addCommitTask(TestCase.task(i), CommitTaskOption.POSTCOMMIT);
}));
}

@Test
public void warnsOnlyForTheQueueThatRuns()
{
assertEquals(0, warningsFor(false, THRESHOLD, i -> scope().addCommitTask(TestCase.task(i), CommitTaskOption.POSTCOMMIT)));
assertEquals(1, warningsFor(false, THRESHOLD, i -> scope().addCommitTask(TestCase.task(i), CommitTaskOption.POSTROLLBACK)));
public void testWarnings()
{
IntConsumer postCommit = i -> scope().addCommitTask(TestCase.task(i), CommitTaskOption.POSTCOMMIT);
for (Case c : List.of(
new Case("at the threshold", 1, true, THRESHOLD, postCommit),
new Case("below the threshold", 0, true, THRESHOLD - 1, postCommit),
new Case("deduped tasks", 0, true, THRESHOLD, _ -> scope().addCommitTask(new TestCase.KeyedTask(0), CommitTaskOption.POSTCOMMIT)),
new Case("accumulating task", 0, true, THRESHOLD, i -> new NoOpAccumulatingTask().register(scope(), List.of(i), CommitTaskOption.POSTCOMMIT)),
new Case("each queue", 2, true, THRESHOLD, i -> {
scope().addCommitTask(TestCase.task(i), CommitTaskOption.PRECOMMIT);
postCommit.accept(i);
}),
new Case("only the queue that runs", 0, false, THRESHOLD, postCommit),
new Case("rollback queue runs on rollback", 1, false, THRESHOLD, i -> scope().addCommitTask(TestCase.task(i), CommitTaskOption.POSTROLLBACK))))
assertEquals(c.name(), c.expectedWarnings(), warningsFor(c.commit(), c.count(), c.register()));
}

@Test
Expand Down
Loading