From 702ee5c87ab81216196f063082f7597e3e14ba06 Mon Sep 17 00:00:00 2001 From: Jason Loux Date: Tue, 24 Nov 2026 13:25:38 -0500 Subject: [PATCH 1/3] Initial commit --- .../daos/cache/FetchFunction.java | 8 - .../daos/cache/ProgramCache.java | 213 ------------------ .../daos/cache/ProgramCacheProvider.java | 22 -- .../TraitControllerIntegrationTest.java | 23 -- .../BrAPIServiceFilterIntegrationTest.java | 23 -- .../brapi/v2/ProgramCacheUnitTest.java | 205 ----------------- .../BrAPIGermplasmServiceUnitTest.java | 2 - 7 files changed, 496 deletions(-) delete mode 100644 src/main/java/org/breedinginsight/daos/cache/FetchFunction.java delete mode 100644 src/main/java/org/breedinginsight/daos/cache/ProgramCache.java delete mode 100644 src/main/java/org/breedinginsight/daos/cache/ProgramCacheProvider.java delete mode 100644 src/test/java/org/breedinginsight/brapi/v2/ProgramCacheUnitTest.java diff --git a/src/main/java/org/breedinginsight/daos/cache/FetchFunction.java b/src/main/java/org/breedinginsight/daos/cache/FetchFunction.java deleted file mode 100644 index d9e1dc992..000000000 --- a/src/main/java/org/breedinginsight/daos/cache/FetchFunction.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.breedinginsight.daos.cache; - -import org.brapi.client.v2.model.exceptions.ApiException; - -@FunctionalInterface -public interface FetchFunction { - R apply(T t) throws ApiException; -} diff --git a/src/main/java/org/breedinginsight/daos/cache/ProgramCache.java b/src/main/java/org/breedinginsight/daos/cache/ProgramCache.java deleted file mode 100644 index 213a7f6bc..000000000 --- a/src/main/java/org/breedinginsight/daos/cache/ProgramCache.java +++ /dev/null @@ -1,213 +0,0 @@ -/* - * See the NOTICE file distributed with this work for additional information - * regarding copyright ownership. - * - * 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.breedinginsight.daos.cache; - -import com.google.gson.Gson; -import io.micronaut.http.server.exceptions.InternalServerException; -import lombok.extern.slf4j.Slf4j; -import org.brapi.client.v2.JSON; -import org.brapi.client.v2.model.exceptions.ApiException; -import org.redisson.api.*; - -import javax.validation.constraints.NotNull; - -import java.util.*; -import java.util.concurrent.*; - -/** - * - * @param object - */ -@Slf4j -public class ProgramCache { - private final RedissonClient connection; - private final Gson gson; - private final FetchFunction> fetchMethod; - private Class type; - private final Executor executor = Executors.newCachedThreadPool(); - - public ProgramCache(RedissonClient connection, FetchFunction> fetchMethod, Class type) { - this.connection = connection; - this.gson = new JSON().getGson(); - this.fetchMethod = fetchMethod; - this.type = type; - } - - public void populate(List keys) { - for(UUID key : keys) { - populate(key); - } - } - - public void populate(@NotNull UUID key) { - String cacheKey = generateCacheKey(key); - log.debug("populate(UUID key) method called with key: " + cacheKey); - RSemaphore semaphore = connection.getSemaphore(cacheKey+":semaphore"); - semaphore.trySetPermits(1); - - RSemaphore queueSemaphore = connection.getSemaphore(cacheKey+":semaphore:queue"); - queueSemaphore.trySetPermits(1); - - boolean acquired = semaphore.tryAcquire(); - - boolean refresh = true; - if(!acquired) { - /* - put this thread in line to refresh once the current refresh finishes. - If there is already a thread in line, let this thread finish as the - next refresh will pick up data persisted by this thread - */ - if(queueSemaphore.tryAcquire()) { - log.debug("Attempting to refresh for: " + cacheKey); - try { - // block until we get the green light to refresh the cache - semaphore.acquire(); - // and let go of our hold on the refresh queue - log.debug("repopulating cache for " + cacheKey); - } catch (InterruptedException e) { - log.error("Error acquiring lock to refresh "+cacheKey, e); - throw new RuntimeException(e); - } finally { - log.debug("Released queue semaphore: "+cacheKey); - queueSemaphore.release(); - } - } else { - log.debug("A refresh is queued up for key: "+cacheKey+", leaving"); - refresh = false; - } - } - - if (refresh) { // if false, an update is already in progress and another one queued up, skip this one - // Start a refresh process asynchronously - executor.execute(() -> { - // Synchronous - try { - log.debug("loading cache for key: " + cacheKey); - connection.getAtomicLong(cacheKey+":refreshing").set(1); - Map values = fetchMethod.apply(key); - if(!values.isEmpty()) { - log.debug("Caching new values for key: " + cacheKey); - Map entryMap = new HashMap<>(); - for (Map.Entry val : values.entrySet()) { - String entryVal = gson.toJson(val.getValue()); - entryMap.put(val.getKey(), entryVal); - } - - RMap map = connection.getMap(cacheKey); - map.clear(); - map.putAll(entryMap); - } else { - log.debug("No values to cache for key: " + cacheKey); - } - log.debug("cache loading complete for key: " + cacheKey); - } catch (Exception e) { - log.error("cache loading error for key: " + cacheKey, e); - invalidate(key); - throw new InternalServerException(e.getMessage(), e); - } finally { - log.debug("Releasing semaphore: " + cacheKey); - connection.getAtomicLong(cacheKey+":refreshing").set(0); - log.debug("Fetched connection: " + cacheKey); - semaphore.release(); - log.debug("connection released"); - } - }); - } - } - - public void set(@NotNull UUID key, @NotNull String id, @NotNull R value) { - connection.getMap(generateCacheKey(key)).put(id, gson.toJson(value)); - } - - public void invalidate(@NotNull UUID key) { - connection.getMap(generateCacheKey(key)).delete(); - } - - public Map get(UUID key) throws ApiException { - String cacheKey = generateCacheKey(key); - log.debug("Getting for key: " + cacheKey); - if (!connection.getBucket(cacheKey).isExists()) { - RSemaphore semaphore = connection.getSemaphore(cacheKey + ":semaphore"); - try { - log.debug("cache miss, populating for key: " + cacheKey); - populate(key); - //block until any updates are done - semaphore.acquire(); - log.debug("Cache loading done!!!! - key: " + cacheKey); - } catch(Exception e){ - throw new ApiException(e); - } finally { - semaphore.release(); - } - } - - try { - return deserialize(connection.getMap(cacheKey)); - } catch (Exception e) { - throw new ApiException(e); - } - } - - private Map deserialize(Map cachedVals) { - Map retMap = new HashMap<>(); - cachedVals.forEach((key, value) -> retMap.put(key, gson.fromJson(value, type))); - return retMap; - } - - public List post(UUID key, Callable> postMethod) throws Exception { - log.debug("posting for key: " + generateCacheKey(key)); - Map response = null; - try { - response = postMethod.call(); - return postThese(key, response); - } catch (Exception e) { - log.error("Error posting data and populating the cache", e); - invalidate(key); - throw e; - } - } - - public List postThese(UUID key, Map toBePosted) throws Exception { - log.debug("posting for key: " + generateCacheKey(key)); - try { - String cacheKey = generateCacheKey(key); - RMap map = connection.getMap(cacheKey); - //temporarily populate the cache with the returned objects from the postMethod, so they show in immediate cache requests - for(Map.Entry obj : toBePosted.entrySet()) { - map.put(obj.getKey(), gson.toJson(obj.getValue())); - } - populate(key); - - return new ArrayList<>(toBePosted.values()); - } catch (Exception e) { - log.error("Error posting data and populating the cache", e); - invalidate(key); - throw e; - } - } - - public boolean isRefreshing(UUID key) { - RAtomicLong isRefreshing = connection.getAtomicLong(generateCacheKey(key) + ":refreshing"); - - return isRefreshing.get() == 1; - } - - private String generateCacheKey(UUID key) { - return key.toString() + ":" + type.getSimpleName().toLowerCase(); - } -} diff --git a/src/main/java/org/breedinginsight/daos/cache/ProgramCacheProvider.java b/src/main/java/org/breedinginsight/daos/cache/ProgramCacheProvider.java deleted file mode 100644 index 321aeb041..000000000 --- a/src/main/java/org/breedinginsight/daos/cache/ProgramCacheProvider.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.breedinginsight.daos.cache; - -import org.redisson.api.RedissonClient; - -import javax.inject.Inject; -import javax.inject.Singleton; -import java.util.Map; -import java.util.UUID; - -@Singleton -public class ProgramCacheProvider { - private final RedissonClient connection; - - @Inject - public ProgramCacheProvider(RedissonClient connection) { - this.connection = connection; - } - - public ProgramCache getProgramCache(FetchFunction> fetchMethod, Class type) { - return new ProgramCache<>(connection, fetchMethod, type); - } -} diff --git a/src/test/java/org/breedinginsight/api/v1/controller/TraitControllerIntegrationTest.java b/src/test/java/org/breedinginsight/api/v1/controller/TraitControllerIntegrationTest.java index 08c7edd37..43b87e00e 100644 --- a/src/test/java/org/breedinginsight/api/v1/controller/TraitControllerIntegrationTest.java +++ b/src/test/java/org/breedinginsight/api/v1/controller/TraitControllerIntegrationTest.java @@ -57,9 +57,6 @@ import org.breedinginsight.dao.db.tables.pojos.ProgramEntity; import org.breedinginsight.dao.db.tables.pojos.TraitEntity; import org.breedinginsight.daos.UserDAO; -import org.breedinginsight.daos.cache.FetchFunction; -import org.breedinginsight.daos.cache.ProgramCache; -import org.breedinginsight.daos.cache.ProgramCacheProvider; import org.breedinginsight.model.*; import org.breedinginsight.services.SpeciesService; import org.breedinginsight.utilities.Utilities; @@ -102,14 +99,6 @@ public class TraitControllerIntegrationTest extends BrAPITest { @Inject private RedissonClient redissonClient; - @Inject - private ProgramCacheProvider programCacheProvider; - - @MockBean(ProgramCacheProvider.class) - ProgramCacheProvider programCacheProvider() { - return mock(ProgramCacheProvider.class); - } - private Species validSpecies; private List validTraits; private Program validProgram; @@ -129,23 +118,11 @@ ProgramCacheProvider programCacheProvider() { @BeforeEach public void beforeEach() { fetchException = new AtomicReference<>(Optional.empty()); - when(programCacheProvider.getProgramCache(isA(FetchFunction.class), any(Class.class))).thenAnswer((Answer) invocation -> { - FetchFunction fetchFunction = invocation.getArgument(0); - return new ProgramCache(redissonClient, uuid -> { - try { - return fetchFunction.apply(uuid); - } catch (Exception e) { - fetchException.set(Optional.of(e)); - throw e; - } - }, invocation.getArgument(1)); - }); } @AfterEach public void afterEach() { redissonClient.getKeys().deleteByPattern("*:trait"); - reset(programCacheProvider); } @BeforeAll diff --git a/src/test/java/org/breedinginsight/api/v1/controller/brapi/BrAPIServiceFilterIntegrationTest.java b/src/test/java/org/breedinginsight/api/v1/controller/brapi/BrAPIServiceFilterIntegrationTest.java index 0fbfe4035..8b3264d71 100644 --- a/src/test/java/org/breedinginsight/api/v1/controller/brapi/BrAPIServiceFilterIntegrationTest.java +++ b/src/test/java/org/breedinginsight/api/v1/controller/brapi/BrAPIServiceFilterIntegrationTest.java @@ -41,9 +41,6 @@ import org.breedinginsight.dao.db.tables.pojos.TraitEntity; import org.breedinginsight.daos.ProgramDAO; import org.breedinginsight.daos.UserDAO; -import org.breedinginsight.daos.cache.FetchFunction; -import org.breedinginsight.daos.cache.ProgramCache; -import org.breedinginsight.daos.cache.ProgramCacheProvider; import org.breedinginsight.daos.impl.ProgramDAOImpl; import org.breedinginsight.model.ProgramBrAPIEndpoints; import org.breedinginsight.model.User; @@ -54,7 +51,6 @@ import org.jooq.Configuration; import org.jooq.DSLContext; import org.junit.jupiter.api.*; -import org.mockito.stubbing.Answer; import org.redisson.api.RedissonClient; import javax.inject.Inject; @@ -82,13 +78,6 @@ public class BrAPIServiceFilterIntegrationTest extends DatabaseTest { @Inject private RedissonClient redissonClient; - @Inject - private ProgramCacheProvider programCacheProvider; - - @MockBean(ProgramCacheProvider.class) - ProgramCacheProvider programCacheProvider() { - return mock(ProgramCacheProvider.class); - } @Inject private ProgramService programService; @@ -154,18 +143,6 @@ public void beforeEach() { urlCheck = new AtomicReference<>(Optional.empty()); brAPIClient = spy(new BrAPIClient()); - when(programCacheProvider.getProgramCache(isA(FetchFunction.class), any(Class.class))).thenAnswer((Answer) invocation -> { - FetchFunction fetchFunction = invocation.getArgument(0); - return new ProgramCache(redissonClient, uuid -> { - try { - return fetchFunction.apply(uuid); - } catch (Exception e) { - fetchException.set(Optional.of(e)); - throw e; - } - }, invocation.getArgument(1)); - }); - doAnswer(invocation -> { BrAPIClient executingBrAPIClient = (BrAPIClient) invocation.getMock(); // fetch the url that's set in the client diff --git a/src/test/java/org/breedinginsight/brapi/v2/ProgramCacheUnitTest.java b/src/test/java/org/breedinginsight/brapi/v2/ProgramCacheUnitTest.java deleted file mode 100644 index 284c83c06..000000000 --- a/src/test/java/org/breedinginsight/brapi/v2/ProgramCacheUnitTest.java +++ /dev/null @@ -1,205 +0,0 @@ -package org.breedinginsight.brapi.v2; - -import io.micronaut.test.annotation.MockBean; -import lombok.SneakyThrows; -import org.brapi.client.v2.model.exceptions.ApiException; -import org.brapi.v2.model.germ.BrAPIGermplasm; -import org.breedinginsight.DatabaseTest; -import org.breedinginsight.brapi.v2.dao.BrAPIGermplasmDAO; -import org.breedinginsight.daos.cache.ProgramCache; -import org.junit.jupiter.api.*; - -import javax.inject.Inject; -import java.time.LocalDateTime; -import java.util.*; -import java.util.concurrent.Callable; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.stream.Collectors; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.mock; - - -@TestInstance(TestInstance.Lifecycle.PER_CLASS) -@TestMethodOrder(MethodOrderer.OrderAnnotation.class) -public class ProgramCacheUnitTest extends DatabaseTest { - - // TODO: Tests - // POSTing skips refresh if one is already queued - // POSTing refresh tracking separate for each program - // Cache refresh failure invalidates cache - - AtomicInteger fetchCount = new AtomicInteger(0); - Integer waitTime = 1000; - Map> mockBrAPI = new HashMap<>(); - - @MockBean(BrAPIGermplasmDAO.class) - BrAPIGermplasmDAO germplasmDAO() { return mock(BrAPIGermplasmDAO.class);} - @Inject - BrAPIGermplasmDAO germplasmDAO; - - @AfterEach - @SneakyThrows - void setupNextTest() { - // There is some thread sleeping used in this testing, wait for all processes to clean out between tests - Thread.sleep(5000); - fetchCount.set(0); - mockBrAPI = new HashMap<>(); - } - - @SneakyThrows - public Map mockFetch(UUID programId, Integer sleepTime) { - fetchCount.incrementAndGet(); - System.out.println("Starting sleep at " + LocalDateTime.now()); - Thread.sleep(sleepTime); - System.out.println("Woken up at " + LocalDateTime.now()); - return mockBrAPI.containsKey(programId) ? new HashMap<>(mockBrAPI.get(programId).stream().collect(Collectors.toMap(germplasm -> UUID.randomUUID().toString(), germplasm -> germplasm))) : new HashMap<>(); - } - - @SneakyThrows - public Map mockPost(UUID programId, List germplasm) { - if (!mockBrAPI.containsKey(programId)) { - mockBrAPI.put(programId, germplasm); - } else { - List allGermplasm = mockBrAPI.get(programId); - allGermplasm.addAll(germplasm); - } - Map germMap = new HashMap<>(); - germplasm.forEach(brAPIGermplasm -> germMap.put(brAPIGermplasm.getGermplasmDbId(), brAPIGermplasm)); - return germMap; - } - - @Test - @SneakyThrows - public void populatedRefreshQueueSkipsRefresh() throws Exception { - // Make a lot of post calls and just how many times the fetch method is called - ProgramCache cache = new ProgramCache<>(super.getRedisConnection(), (UUID id) -> mockFetch(id, waitTime), BrAPIGermplasm.class); - UUID programId = UUID.randomUUID(); - int numPost = 10; - int currPost = 0; - while (currPost < numPost) { - List newList = new ArrayList<>(); - newList.add(new BrAPIGermplasm().germplasmDbId(UUID.randomUUID().toString())); - cache.post(programId, () -> mockPost(programId, new ArrayList<>(newList))); - currPost += 1; - } - assertTrue(fetchCount.get() < numPost, "A fetch call was made for every post. It shouldn't."); - assertEquals(1, mockBrAPI.size(), "More than one program existed in mocked brapi db."); - assertEquals(numPost, mockBrAPI.get(programId).size(), "Wrong number of germplasm in db"); - while(cache.isRefreshing(programId)) { - Thread.sleep(waitTime); - } - Map cachedGermplasm = cache.get(programId); - assertEquals(numPost, cachedGermplasm.size(), "Wrong number of germplasm in cache"); - } - - @Test - @SneakyThrows - public void programRefreshesSeparated() throws Exception { - // Make a lot of post calls on different programs to check that they don't wait for each other - ProgramCache cache = new ProgramCache<>(super.getRedisConnection(), (UUID id) -> mockFetch(id, waitTime), BrAPIGermplasm.class); - int numPost = 10; - int currPost = 0; - while (currPost < numPost) { - UUID id = UUID.randomUUID(); - List newList = new ArrayList<>(); - newList.add(new BrAPIGermplasm().germplasmDbId(UUID.randomUUID().toString())); - cache.post(id, () -> mockPost(id, new ArrayList<>(newList))); - currPost += 1; - } - Thread.sleep(waitTime); - assertEquals(numPost, fetchCount.get(), "A fetch call should have been made for every post"); - assertEquals(numPost, mockBrAPI.size(), "Less programs existed than existed in mock brapi db."); - for (UUID key: mockBrAPI.keySet()) { - assertEquals(1, mockBrAPI.get(key).size(), "Wrong number of germplasm in db"); - assertEquals(1, cache.get(key).size(), "Wrong number of germplasm in cache"); - } - } - - @Test - @SneakyThrows - public void onlyOneRefreshIsQueued() throws ApiException { - // Test that the get method waits for an ongoing refresh to finish when there isn't any day - UUID programId = UUID.randomUUID(); - List newList = new ArrayList<>(); - newList.add(new BrAPIGermplasm().germplasmDbId(UUID.randomUUID().toString())); - mockBrAPI.put(programId, new ArrayList<>(newList)); - - ProgramCache cache = new ProgramCache<>(super.getRedisConnection(), (UUID id) -> mockFetch(id, waitTime*3), BrAPIGermplasm.class); - cache.populate(programId); - cache.get(programId); - cache.get(programId); - // Our fetch method should have only been called once for the initial loading - assertEquals(2, fetchCount.get(), "Fetch method was called on every get"); - } - - @Test - @SneakyThrows - public void postTriggersRefresh() throws Exception { - // Test that the get method does not wait for a refresh when there is data present - UUID programId = UUID.randomUUID(); - List newList = new ArrayList<>(); - newList.add(new BrAPIGermplasm().germplasmDbId(UUID.randomUUID().toString())); - mockBrAPI.put(programId, new ArrayList<>(newList)); - ProgramCache cache = new ProgramCache<>(super.getRedisConnection(), (UUID id) -> mockFetch(id, waitTime*2), BrAPIGermplasm.class); - cache.populate(programId); - Callable> postFunction = () -> mockPost(programId, new ArrayList<>(newList)); - - // Get waits for initial fetch - Map cachedGermplasm = cache.get(programId); - assertEquals(1, cachedGermplasm.size(), "Initial germplasm not as expected"); - - // Now post another object and call get immediately to see that it returns the old data - cache = new ProgramCache<>(super.getRedisConnection(), (UUID id) -> mockFetch(id, waitTime*4), BrAPIGermplasm.class); - cache.post(programId, postFunction); - System.out.println("calling get at: "+ LocalDateTime.now()); - cachedGermplasm = cache.get(programId); - assertEquals(2, cachedGermplasm.size(), "Get post method didn't insert the new data"); - Thread.sleep(waitTime); - assertEquals(true, cache.isRefreshing(programId), "Cache is not refreshing"); - - // Now wait for the fetch after the post to finish - Thread.sleep(waitTime*5); - cachedGermplasm = cache.get(programId); - assertEquals(2, cachedGermplasm.size(), "Get method did not get updated germplasm"); - } - - @Test - @SneakyThrows - @Order(1) - public void refreshErrorInvalidatesCache() throws Exception { - // Tests that data is invalidated when a refresh method fails - // Tests that data is no longer retrievable when invalidated and needs to be refreshed - - // Set starter data - UUID programId = UUID.randomUUID(); - List newList = new ArrayList<>(); - newList.add(new BrAPIGermplasm().germplasmDbId(UUID.randomUUID().toString())); - mockBrAPI.put(programId, new ArrayList<>(newList)); - - // Start cache - ProgramCache cache = new ProgramCache<>(super.getRedisConnection(), (UUID id) -> mockFetch(programId, waitTime), BrAPIGermplasm.class); - cache.populate(programId); - - //wait for the initial fetch to complete - Thread.sleep(waitTime*2); - - Map cachedGermplasm = cache.get(programId); - assertEquals(1, cachedGermplasm.size(), "Initial germplasm not as expected"); - - // Change our fetch method to throw an error now - cache = new ProgramCache<>(super.getRedisConnection(), (UUID id) -> {throw new ApiException("UhOh");}, BrAPIGermplasm.class); - cache.post(programId, () -> mockPost(programId, new ArrayList<>(newList))); - // Give it a second so we can wait for the cache to be invalidated and refresh to finish - Thread.sleep(waitTime*2); - - // Check that the fetch function needs to be called again since the cache was invalidated - cache = new ProgramCache<>(super.getRedisConnection(), (UUID id) -> mockFetch(programId, waitTime), BrAPIGermplasm.class); - assertEquals(1, fetchCount.get()); - cachedGermplasm = cache.get(programId); - Thread.sleep(waitTime*2); - assertEquals(2, fetchCount.get()); - assertEquals(2, cachedGermplasm.size(), "Newly retrieved germplasm not as expected"); - } -} diff --git a/src/test/java/org/breedinginsight/services/BrAPIGermplasmServiceUnitTest.java b/src/test/java/org/breedinginsight/services/BrAPIGermplasmServiceUnitTest.java index 14c96769a..2dca2e4eb 100644 --- a/src/test/java/org/breedinginsight/services/BrAPIGermplasmServiceUnitTest.java +++ b/src/test/java/org/breedinginsight/services/BrAPIGermplasmServiceUnitTest.java @@ -19,7 +19,6 @@ import org.breedinginsight.brapps.importer.daos.ImportDAO; import org.breedinginsight.brapps.importer.model.exports.FileType; import org.breedinginsight.daos.ProgramDAO; -import org.breedinginsight.daos.cache.ProgramCacheProvider; import org.breedinginsight.model.DownloadFile; import org.breedinginsight.model.Program; import org.breedinginsight.services.brapi.BrAPIEndpointProvider; @@ -33,7 +32,6 @@ import java.io.InputStream; import java.lang.reflect.Field; -import java.lang.reflect.Method; import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; import java.util.*; From a2dc720c5006062d942f15863c9b4a0cb343f13e Mon Sep 17 00:00:00 2001 From: Jason Loux Date: Mon, 30 Nov 2026 12:59:58 -0500 Subject: [PATCH 2/3] Remove unused cache env var, rename other env var --- .env.template | 6 +- .../brapi/v2/dao/BrAPIObservationDAO.java | 2 +- .../brapi/v2/dao/BrAPIObservationUnitDAO.java | 2 +- .../brapi/v2/dao/BrAPIStudyDAO.java | 2 +- .../utilities/BrAPIDAOUtil.java | 2 +- src/main/resources/application.yml | 16 +- .../TraitControllerIntegrationTest.java | 3 - .../BrAPIServiceFilterIntegrationTest.java | 288 ------------------ 8 files changed, 12 insertions(+), 309 deletions(-) delete mode 100644 src/test/java/org/breedinginsight/api/v1/controller/brapi/BrAPIServiceFilterIntegrationTest.java diff --git a/.env.template b/.env.template index 73ff2d89e..b8fe3e800 100644 --- a/.env.template +++ b/.env.template @@ -35,9 +35,9 @@ BRAPI_READ_TIMEOUT=60m # Max number of records to POST to the BrAPI service per request POST_CHUNK_SIZE=1000 -# Request cache records paginating through available records per program by CACHE_BRAPI_FETCH_PAGE_SIZE -CACHE_PAGINATE_GERMPLASM=false -CACHE_BRAPI_FETCH_PAGE_SIZE=65000 +# Amount of records to page at a time through a BrAPI search request result. See BrAPIDAOUtil.searchInternalReturnResponse. +# Should not exceed 65k for now due to BrAPI limitations +BRAPI_PAGE_THRU_PAGE_SIZE=65000 # BrAPI Server Variables BRAPI_SERVER_PORT=8083 diff --git a/src/main/java/org/breedinginsight/brapi/v2/dao/BrAPIObservationDAO.java b/src/main/java/org/breedinginsight/brapi/v2/dao/BrAPIObservationDAO.java index 42c753d22..dfc041da8 100644 --- a/src/main/java/org/breedinginsight/brapi/v2/dao/BrAPIObservationDAO.java +++ b/src/main/java/org/breedinginsight/brapi/v2/dao/BrAPIObservationDAO.java @@ -62,7 +62,7 @@ public BrAPIObservationDAO(ProgramDAO programDAO, BrAPIObservationUnitDAO observationUnitDAO, BrAPIDAOUtil brAPIDAOUtil, BrAPIEndpointProvider brAPIEndpointProvider, - @Property(name = "brapi.cache.fetch-page-size") int brapiFetchPageSize, + @Property(name = "brapi.page-thru.page-size") int brapiFetchPageSize, TraitService traitService) { this.programDAO = programDAO; this.importDAO = importDAO; diff --git a/src/main/java/org/breedinginsight/brapi/v2/dao/BrAPIObservationUnitDAO.java b/src/main/java/org/breedinginsight/brapi/v2/dao/BrAPIObservationUnitDAO.java index fb6a33876..02c7e838e 100644 --- a/src/main/java/org/breedinginsight/brapi/v2/dao/BrAPIObservationUnitDAO.java +++ b/src/main/java/org/breedinginsight/brapi/v2/dao/BrAPIObservationUnitDAO.java @@ -74,7 +74,7 @@ public BrAPIObservationUnitDAO(ProgramDAO programDAO, BrAPIGermplasmService germplasmService, ProgramService programService, @Property(name = "brapi.server.reference-source") String referenceSource, - @Property(name = "brapi.cache.fetch-page-size") int brapiFetchPageSize) { + @Property(name = "brapi.page-thru.page-size") int brapiFetchPageSize) { this.programDAO = programDAO; this.importDAO = importDAO; this.brAPIDAOUtil = brAPIDAOUtil; diff --git a/src/main/java/org/breedinginsight/brapi/v2/dao/BrAPIStudyDAO.java b/src/main/java/org/breedinginsight/brapi/v2/dao/BrAPIStudyDAO.java index 3af82e91d..1ab5f1b2d 100644 --- a/src/main/java/org/breedinginsight/brapi/v2/dao/BrAPIStudyDAO.java +++ b/src/main/java/org/breedinginsight/brapi/v2/dao/BrAPIStudyDAO.java @@ -49,7 +49,7 @@ public class BrAPIStudyDAO { @Property(name = "brapi.server.reference-source") private String referenceSource; - @Property(name = "brapi.cache.fetch-page-size") + @Property(name = "brapi.page-thru.page-size") private int brapiMaxPageSize; private ProgramDAO programDAO; diff --git a/src/main/java/org/breedinginsight/utilities/BrAPIDAOUtil.java b/src/main/java/org/breedinginsight/utilities/BrAPIDAOUtil.java index 858e8462a..1614b4352 100644 --- a/src/main/java/org/breedinginsight/utilities/BrAPIDAOUtil.java +++ b/src/main/java/org/breedinginsight/utilities/BrAPIDAOUtil.java @@ -66,7 +66,7 @@ public BrAPIDAOUtil(@Property(name = "brapi.search.wait-time") int searchWaitTim @Property(name = "brapi.read-timeout") Duration searchTimeout, @Property(name = "brapi.page-size") int pageSize, @Property(name = "brapi.post-group-size") int postGroupSize, - @Property(name = "brapi.cache.fetch-page-size") int brapiFetchPageSize, + @Property(name = "brapi.page-thru.page-size") int brapiFetchPageSize, ProgramService programService) { this.searchWaitTime = searchWaitTime; this.searchTimeout = searchTimeout; diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 838c1b992..bd93596a9 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -184,18 +184,12 @@ brapi: search: wait-time: 1000 post-group-size: ${POST_CHUNK_SIZE:1000} - paginate: - # These props are used as flippers for specific cache entities to be fetched all at once or paginated. - # If the props are set to true, there's a possibility the BrAPI server could run out of memory grabbing all the - # data and assigning it to entities in memory given a program that has a large amount of those types of entities. - # At that point these flippers should be set to true. - germplasm: ${CACHE_PAGINATE_GERMPLASM:false} - cache: - # This prop sets how many program cache entity records can be fetched at a time from BrAPI. Today, if over 65000 is used, - # a SQL error can happen for programs that have more than this page size, because to fetch these certain entities + page-thru: + # This prop sets how many entity records can be fetched at a time from BrAPI as it pages through all entities found in a search request result. + # Today, if over 65000 is used, a SQL error can happen for programs that have more than this page size, because to fetch these certain entities # the same amount of IDs must be passed for any collections that need to be fetched in the entity, and SQL has a max of ~65355 params. - # The ProgramCache will iterate through all pages of an entity to retrieve all the data from BrAPI. - fetch-page-size: ${CACHE_BRAPI_FETCH_PAGE_SIZE:65000} + # Page-thru requests will iterate through all pages of a search request result to retrieve all the data from BrAPI. + page-size: ${BRAPI_PAGE_THRU_PAGE_SIZE:65000} email: diff --git a/src/test/java/org/breedinginsight/api/v1/controller/TraitControllerIntegrationTest.java b/src/test/java/org/breedinginsight/api/v1/controller/TraitControllerIntegrationTest.java index 43b87e00e..fc97ac05c 100644 --- a/src/test/java/org/breedinginsight/api/v1/controller/TraitControllerIntegrationTest.java +++ b/src/test/java/org/breedinginsight/api/v1/controller/TraitControllerIntegrationTest.java @@ -27,7 +27,6 @@ import io.micronaut.http.client.exceptions.HttpClientResponseException; import io.micronaut.http.netty.cookies.NettyCookie; import io.micronaut.http.server.exceptions.InternalServerException; -import io.micronaut.test.annotation.MockBean; import io.micronaut.test.extensions.junit5.annotation.MicronautTest; import io.reactivex.Flowable; import junit.framework.AssertionFailedError; @@ -62,7 +61,6 @@ import org.breedinginsight.utilities.Utilities; import org.jooq.DSLContext; import org.junit.jupiter.api.*; -import org.mockito.stubbing.Answer; import org.redisson.api.RedissonClient; import javax.inject.Inject; @@ -73,7 +71,6 @@ import static io.micronaut.http.HttpRequest.*; import static org.breedinginsight.TestUtils.insertAndFetchTestProgram; import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; @MicronautTest diff --git a/src/test/java/org/breedinginsight/api/v1/controller/brapi/BrAPIServiceFilterIntegrationTest.java b/src/test/java/org/breedinginsight/api/v1/controller/brapi/BrAPIServiceFilterIntegrationTest.java deleted file mode 100644 index 8b3264d71..000000000 --- a/src/test/java/org/breedinginsight/api/v1/controller/brapi/BrAPIServiceFilterIntegrationTest.java +++ /dev/null @@ -1,288 +0,0 @@ -/* - * See the NOTICE file distributed with this work for additional information - * regarding copyright ownership. - * - * 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.breedinginsight.api.v1.controller.brapi; - -import io.kowalski.fannypack.FannyPack; -import io.micronaut.context.annotation.Property; -import io.micronaut.http.HttpResponse; -import io.micronaut.http.HttpStatus; -import io.micronaut.http.MediaType; -import io.micronaut.http.client.RxHttpClient; -import io.micronaut.http.client.annotation.Client; -import io.micronaut.http.client.exceptions.HttpClientResponseException; -import io.micronaut.http.netty.cookies.NettyCookie; -import io.micronaut.http.server.exceptions.InternalServerException; -import io.micronaut.test.annotation.MockBean; -import io.micronaut.test.extensions.junit5.annotation.MicronautTest; -import io.reactivex.Flowable; -import lombok.SneakyThrows; -import okhttp3.Call; -import org.brapi.client.v2.BrAPIClient; -import org.breedinginsight.DatabaseTest; -import org.breedinginsight.api.v1.controller.TestTokenValidator; -import org.breedinginsight.dao.db.tables.daos.ProgramDao; -import org.breedinginsight.dao.db.tables.daos.TraitDao; -import org.breedinginsight.dao.db.tables.pojos.ProgramEntity; -import org.breedinginsight.dao.db.tables.pojos.TraitEntity; -import org.breedinginsight.daos.ProgramDAO; -import org.breedinginsight.daos.UserDAO; -import org.breedinginsight.daos.impl.ProgramDAOImpl; -import org.breedinginsight.model.ProgramBrAPIEndpoints; -import org.breedinginsight.model.User; -import org.breedinginsight.services.ProgramService; -import org.breedinginsight.services.brapi.BrAPIClientProvider; -import org.breedinginsight.services.brapi.BrAPIEndpointProvider; -import org.breedinginsight.services.brapi.BrAPIProvider; -import org.jooq.Configuration; -import org.jooq.DSLContext; -import org.junit.jupiter.api.*; -import org.redisson.api.RedissonClient; - -import javax.inject.Inject; -import java.lang.reflect.Type; -import java.time.Duration; -import java.time.temporal.ChronoUnit; -import java.util.Optional; -import java.util.UUID; -import java.util.concurrent.atomic.AtomicReference; - -import static io.micronaut.http.HttpRequest.GET; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; - -@MicronautTest -@TestInstance(TestInstance.Lifecycle.PER_CLASS) -@TestMethodOrder(MethodOrderer.OrderAnnotation.class) -@Property(name = "brapi.read-timeout", value = "10m") -public class BrAPIServiceFilterIntegrationTest extends DatabaseTest { - - private ProgramEntity validProgram; - private TraitEntity validVariable; - - @Inject - private RedissonClient redissonClient; - - @Inject - private ProgramService programService; - @MockBean(ProgramService.class) - ProgramService programService() { return mock(ProgramService.class);} - @Inject - private BrAPIClientProvider brAPIClientProvider; - @MockBean(BrAPIClientProvider.class) - BrAPIClientProvider brAPIClientProvider() { return mock(BrAPIClientProvider.class, CALLS_REAL_METHODS); } - - @Inject - private ProgramDAO programDAO; - - @Inject - private DSLContext dsl; - @Inject - private ProgramDao programDao; - @Inject - private TraitDao traitDao; - @Inject - private UserDAO userDAO; - @Inject - private Configuration config; - - @Inject - private BrAPIProvider brAPIProvider; - - @Inject - private BrAPIEndpointProvider brAPIEndpointProvider; - - @Property(name = "brapi.server.core-url") - private String defaultBrAPICoreUrl; - @Property(name = "brapi.server.pheno-url") - private String defaultBrAPIPhenoUrl; - @Property(name = "brapi.server.geno-url") - private String defaultBrAPIGenoUrl; - @Property(name = "brapi.server.reference-source") - private String referenceSource; - - @MockBean(ProgramDAO.class) - ProgramDAO programDAO() { - return spy(new ProgramDAOImpl(config, dsl, brAPIProvider, brAPIClientProvider, brAPIEndpointProvider, defaultBrAPICoreUrl, defaultBrAPIPhenoUrl, defaultBrAPIGenoUrl, referenceSource, Duration.of(10, ChronoUnit.MINUTES))); - } - - @Inject - @Client("/${micronaut.bi.api.version}") - private RxHttpClient client; - - @BeforeAll - public void setup() { - - insertTestData(); - retrieveTestData(); - } - - private AtomicReference> fetchException; - private AtomicReference> urlCheck; - private BrAPIClient brAPIClient; - @BeforeEach - @SneakyThrows - public void beforeEach() { - fetchException = new AtomicReference<>(Optional.empty()); - urlCheck = new AtomicReference<>(Optional.empty()); - brAPIClient = spy(new BrAPIClient()); - - doAnswer(invocation -> { - BrAPIClient executingBrAPIClient = (BrAPIClient) invocation.getMock(); - // fetch the url that's set in the client - urlCheck.set(Optional.of(executingBrAPIClient.getBasePath())); - return invocation.callRealMethod(); - }).when(brAPIClient) - .execute(any(Call.class), any(Type.class)); - } - - public void insertTestData() { - // Insert our traits into the db - var fp = FannyPack.fill("src/test/resources/sql/TraitControllerIntegrationTest.sql"); - var securityFp = FannyPack.fill("src/test/resources/sql/ProgramSecuredAnnotationRuleIntegrationTest.sql"); - - // Insert system roles - User testUser = userDAO.getUserByOAuthId(TestTokenValidator.TEST_USER_ORCID).get(); - dsl.execute(securityFp.get("InsertSystemRoleAdmin"), testUser.getId().toString()); - - // Insert program - dsl.execute(fp.get("InsertProgram")); - - // Insert program observation level - dsl.execute(fp.get("InsertProgramObservationLevel")); - - // Insert program ontology sql - dsl.execute(fp.get("InsertProgramOntology")); - - // Insert method - dsl.execute(fp.get("InsertMethod")); - - // Insert scale - dsl.execute(fp.get("InsertScale")); - - // Insert trait - dsl.execute(fp.get("InsertTrait")); - } - - public void retrieveTestData() { - // Retrieve our new data - validProgram = programDao.findAll().get(0); - validVariable = traitDao.findAll().get(0); - } - @Disabled("Temporarily disabled, see BI-2238") - @Test - @Order(1) - @SneakyThrows - public void urlChangesForDifferentRequestsCallOne() { - // Checks that two requests sent to the same micronaut instance will have different - // urls. Could use some improvements - - String coreUrl = "http://core-test" + UUID.randomUUID().toString() + "/brapi/v2"; - String phenoUrl = "http://pheno-test" + UUID.randomUUID().toString() + "/brapi/v2"; - String genoUrl = "http://geno-test" + UUID.randomUUID().toString() + "/brapi/v2"; - ProgramBrAPIEndpoints programBrAPIEndpoints = getBrAPIEndpoints(coreUrl, phenoUrl, genoUrl); - - when(programService.getBrapiEndpoints(any(UUID.class))).thenReturn(programBrAPIEndpoints); - when(programService.exists(any(UUID.class))).thenReturn(true); - - brAPIClient.setBasePath(coreUrl); - doReturn(brAPIClient).when(programDAO).getCoreClient(any(UUID.class)); - - client.exchange( - GET("/programs/" + validProgram.getId() + "/traits?full=true") - .contentType(MediaType.APPLICATION_JSON) - .cookie(new NettyCookie("phylo-token", "test-registered-user")), String.class - ).blockingFirst(); - - assertTrue(fetchException.get().isPresent(), "No exception was thrown"); - assertTrue(fetchException.get().get() instanceof InternalServerException, "Wrong exception type was thrown"); - assertEquals("Error making BrAPI call", fetchException.get().get().getMessage()); - - // Check that our error is not an assertion error - assertEquals(coreUrl, urlCheck.get().get(), "URL was not as expected"); - } - @Disabled("Temporarily disabled, see BI-2238") - @Test - @Order(2) - @SneakyThrows - public void urlChangesForDifferentRequestsCallTwo() { - - String coreUrl1 = "http://core-test" + UUID.randomUUID().toString() + "/brapi/v2"; - String phenoUrl1 = "http://pheno-test" + UUID.randomUUID().toString() + "/brapi/v2"; - String genoUrl1 = "http://geno-test" + UUID.randomUUID().toString() + "/brapi/v2"; - ProgramBrAPIEndpoints programBrAPIEndpoints = getBrAPIEndpoints(coreUrl1, phenoUrl1, genoUrl1); - - reset(programService); - when(programService.getBrapiEndpoints(any(UUID.class))).thenReturn(programBrAPIEndpoints); - when(programService.exists(any(UUID.class))).thenReturn(true); - - brAPIClient.setBasePath(coreUrl1); - doReturn(brAPIClient).when(programDAO).getCoreClient(any(UUID.class)); - - // Assert our brapi url was used - client.exchange( - GET("/programs/" + validProgram.getId() + "/traits?full=true") - .contentType(MediaType.APPLICATION_JSON) - .cookie(new NettyCookie("phylo-token", "test-registered-user")), String.class - ).blockingFirst(); - - assertTrue(fetchException.get().isPresent(), "No exception was thrown"); - assertTrue(fetchException.get().get() instanceof InternalServerException, "Wrong exception type was thrown"); - assertEquals("Error making BrAPI call", fetchException.get().get().getMessage()); - - assertEquals(coreUrl1, urlCheck.get().get(), "Url was not as expected"); - } - @Disabled("Temporarily disabled, see BI-2238") - @Test - @SneakyThrows - public void getTraitSingleEditableUsesFilter() { - - String phenoUrl = "http://getTraitSingle" + UUID.randomUUID().toString() + "/brapi/v2"; - ProgramBrAPIEndpoints programBrAPIEndpoints = getBrAPIEndpoints(phenoUrl, phenoUrl, phenoUrl); - - reset(programService); - when(programService.getBrapiEndpoints(any(UUID.class))).thenReturn(programBrAPIEndpoints); - when(programService.exists(any(UUID.class))).thenReturn(true); - - brAPIClient.setBasePath(phenoUrl); - doReturn(brAPIClient).when(programDAO).getCoreClient(any(UUID.class)); - - Flowable> call = client.exchange( - GET("/programs/" + validProgram.getId() + "/traits/" + validVariable.getId()+"/editable") - .contentType(MediaType.APPLICATION_JSON) - .cookie(new NettyCookie("phylo-token", "test-registered-user")), String.class - ); - - // Expect error because brapi results will not be returned - HttpClientResponseException e = Assertions.assertThrows(HttpClientResponseException.class, () -> { - HttpResponse response = call.blockingFirst(); - }); - - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, e.getStatus(), "Response status is incorrect"); - assertEquals(phenoUrl, urlCheck.get().get(), "Url was not as expected"); - } - - public ProgramBrAPIEndpoints getBrAPIEndpoints(String coreUrl, String phenoUrl, String genoUrl){ - return ProgramBrAPIEndpoints.builder() - .coreUrl(coreUrl == null ? Optional.empty() : Optional.of(coreUrl)) - .genoUrl(genoUrl == null ? Optional.empty() : Optional.of(genoUrl)) - .phenoUrl(phenoUrl == null ? Optional.empty() : Optional.of(phenoUrl)) - .build(); - } -} From a639c3f669fb106a66e4f094202bf0dd695d3130 Mon Sep 17 00:00:00 2001 From: Jason Loux Date: Mon, 30 Nov 2026 14:51:05 -0500 Subject: [PATCH 3/3] Remove rest of comments/references to program cache --- .../brapi/v2/BrAPIGermplasmController.java | 8 ++++---- .../brapi/v2/dao/BrAPIObservationUnitDAO.java | 2 +- .../brapi/v2/services/BrAPIListService.java | 2 +- .../steps/CommitPendingImportObjectsStep.java | 6 ++---- .../processors/experiment/service/StudyService.java | 11 +---------- .../experiment/services/ExperimentStudyService.java | 11 +---------- .../services/SampleSubmissionService.java | 1 - .../v1/controller/TraitControllerIntegrationTest.java | 3 --- 8 files changed, 10 insertions(+), 34 deletions(-) diff --git a/src/main/java/org/breedinginsight/brapi/v2/BrAPIGermplasmController.java b/src/main/java/org/breedinginsight/brapi/v2/BrAPIGermplasmController.java index 1fe1a91b1..16323867a 100644 --- a/src/main/java/org/breedinginsight/brapi/v2/BrAPIGermplasmController.java +++ b/src/main/java/org/breedinginsight/brapi/v2/BrAPIGermplasmController.java @@ -87,8 +87,8 @@ public BrAPIGermplasmController(@Property(name = "brapi.server.reference-source" this.programService = programService; } - // NOTE: bypasses cache and makes api request directly to brapi service - // Needs to convert DeltaBreed UUIDs to BrAPI Service DbIds and back + // NOTE: Makes api request directly to BrAPI service + // Needs to convert DeltaBreed program UUID to BrAPI programDbId and back @Post("/programs/{programId}" + BrapiVersion.BRAPI_V2 + "/search/germplasm") @Produces(MediaType.APPLICATION_JSON) @ProgramSecured(roleGroups = {ProgramSecuredRoleGroup.PROGRAM_SCOPED_ROLES}) @@ -115,8 +115,8 @@ public HttpResponse searchGermplasm( return getObjectHttpResponse(brapiGermplasm, program.get().getKey()); } - // NOTE: bypasses cache and makes api request directly to brapi service - // Needs to convert BrAPIService dbIds to DeltaBreed UUIDs + // NOTE: Makes api request directly to BrAPI service + // Needs to convert DeltaBreed program UUID to BrAPI programDbId and back @Get("/programs/{programId}" + BrapiVersion.BRAPI_V2 + "/search/germplasm/{searchResultId}{?queryParams*}") @Produces(MediaType.APPLICATION_JSON) @ProgramSecured(roleGroups = {ProgramSecuredRoleGroup.PROGRAM_SCOPED_ROLES}) diff --git a/src/main/java/org/breedinginsight/brapi/v2/dao/BrAPIObservationUnitDAO.java b/src/main/java/org/breedinginsight/brapi/v2/dao/BrAPIObservationUnitDAO.java index 02c7e838e..3119c076a 100644 --- a/src/main/java/org/breedinginsight/brapi/v2/dao/BrAPIObservationUnitDAO.java +++ b/src/main/java/org/breedinginsight/brapi/v2/dao/BrAPIObservationUnitDAO.java @@ -203,7 +203,7 @@ public List getObservationUnitsForDatasetAndEnvs(@NotNull }).collect(Collectors.toList()); } - // Note: does not use cache, impractical to implement all search parameters client-side. + // Note: impractical to implement all search parameters client-side. public List getObservationUnits(Program program, Optional observationUnitId, Optional observationUnitName, diff --git a/src/main/java/org/breedinginsight/brapi/v2/services/BrAPIListService.java b/src/main/java/org/breedinginsight/brapi/v2/services/BrAPIListService.java index 2bfeccb22..a0f366915 100644 --- a/src/main/java/org/breedinginsight/brapi/v2/services/BrAPIListService.java +++ b/src/main/java/org/breedinginsight/brapi/v2/services/BrAPIListService.java @@ -77,7 +77,7 @@ public List getListSummariesByTypeAndXref( itemsFromEachList.put(list.getListDbId(), listDetails.getResult().getData().get(0)); } if (type == BrAPIListTypes.GERMPLASM) { - // Fetch one germplasm for each list from cache. + // Fetch one germplasm for each list. List germplasmRepresentatives = germplasmDAO.getGermplasmByRawName((new ArrayList<>(itemsFromEachList.values())), program.getId()); // Build hashmap of germplasm by name. HashMap germplasmByName = new HashMap<>(); diff --git a/src/main/java/org/breedinginsight/brapps/importer/services/processors/experiment/create/workflow/steps/CommitPendingImportObjectsStep.java b/src/main/java/org/breedinginsight/brapps/importer/services/processors/experiment/create/workflow/steps/CommitPendingImportObjectsStep.java index d4f3e2198..45b5fcfb1 100644 --- a/src/main/java/org/breedinginsight/brapps/importer/services/processors/experiment/create/workflow/steps/CommitPendingImportObjectsStep.java +++ b/src/main/java/org/breedinginsight/brapps/importer/services/processors/experiment/create/workflow/steps/CommitPendingImportObjectsStep.java @@ -16,7 +16,6 @@ */ package org.breedinginsight.brapps.importer.services.processors.experiment.create.workflow.steps; -import io.micronaut.http.HttpResponse; import io.micronaut.http.server.exceptions.InternalServerException; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.map.CaseInsensitiveMap; @@ -186,8 +185,8 @@ public void process(ProcessContext processContext, ProcessedData processedData) // Do this check here, directly before creating new trials instead of in earlier step to minimize time window of race condition if (!newTrials.isEmpty()) { try { - List cachedTrials = brapiTrialDAO.getTrials(program.getId()); - List existingTrialNames = cachedTrials.stream().map(BrAPITrial::getTrialName).collect(Collectors.toList()); + List programTrials = brapiTrialDAO.getTrials(program.getId()); + List existingTrialNames = programTrials.stream().map(BrAPITrial::getTrialName).collect(Collectors.toList()); List newTrialNames = newTrials.stream().map(t -> Utilities.removeProgramKey(t.getTrialName(), program.getKey())).collect(Collectors.toList()); log.debug("** Trials Duplicate Check: {} -> {}", existingTrialNames, newTrialNames); if (newTrialNames.stream().anyMatch(existingTrialNames::contains)) { @@ -213,7 +212,6 @@ public void process(ProcessContext processContext, ProcessedData processedData) trialByNameNoScope.get(createdTrialName) .getBrAPIObject() .setTrialDbId(createdTrial.getTrialDbId()); - // TODO: May need to set the main ID for pending objects with the BrAPI ID for downstream usage once cache is removed. trialByNameNoScope.get(createdTrialName) .setId(UUID.fromString(createdTrial.getTrialDbId())); } diff --git a/src/main/java/org/breedinginsight/brapps/importer/services/processors/experiment/service/StudyService.java b/src/main/java/org/breedinginsight/brapps/importer/services/processors/experiment/service/StudyService.java index 06f6a3bbb..a706a5f79 100644 --- a/src/main/java/org/breedinginsight/brapps/importer/services/processors/experiment/service/StudyService.java +++ b/src/main/java/org/breedinginsight/brapps/importer/services/processors/experiment/service/StudyService.java @@ -120,16 +120,7 @@ public PendingImportObject constructPIOFromBrapiStudy(BrAPIStudy brA // TODO: used by both workflows public String seasonDbIdToYear(String seasonDbId, UUID programId) { - String year = null; - // TODO: add season objects to redis cache then just extract year from those - // removing this for now here - //if (this.seasonDbIdToYearCache.containsKey(seasonDbId)) { // get it from cache if possible - // year = this.seasonDbIdToYearCache.get(seasonDbId); - //} else { - year = seasonDbIdToYearFromDatabase(seasonDbId, programId); - // this.seasonDbIdToYearCache.put(seasonDbId, year); - //} - return year; + return seasonDbIdToYearFromDatabase(seasonDbId, programId); } // TODO: used by both workflows diff --git a/src/main/java/org/breedinginsight/brapps/importer/services/processors/experiment/services/ExperimentStudyService.java b/src/main/java/org/breedinginsight/brapps/importer/services/processors/experiment/services/ExperimentStudyService.java index c1bd4cd2c..5ba06ebf1 100644 --- a/src/main/java/org/breedinginsight/brapps/importer/services/processors/experiment/services/ExperimentStudyService.java +++ b/src/main/java/org/breedinginsight/brapps/importer/services/processors/experiment/services/ExperimentStudyService.java @@ -84,16 +84,7 @@ public PendingImportObject processAndCacheStudy( // TODO: used by both workflows private String seasonDbIdToYear(String seasonDbId, UUID programId) { - String year = null; - // TODO: add season objects to redis cache then just extract year from those - // removing this for now here - //if (this.seasonDbIdToYearCache.containsKey(seasonDbId)) { // get it from cache if possible - // year = this.seasonDbIdToYearCache.get(seasonDbId); - //} else { - year = seasonDbIdToYearFromDatabase(seasonDbId, programId); - // this.seasonDbIdToYearCache.put(seasonDbId, year); - //} - return year; + return seasonDbIdToYearFromDatabase(seasonDbId, programId); } // TODO: used by both workflows diff --git a/src/main/java/org/breedinginsight/services/SampleSubmissionService.java b/src/main/java/org/breedinginsight/services/SampleSubmissionService.java index fa57e197a..0a0e98a8a 100644 --- a/src/main/java/org/breedinginsight/services/SampleSubmissionService.java +++ b/src/main/java/org/breedinginsight/services/SampleSubmissionService.java @@ -490,7 +490,6 @@ public Optional updateSubmissionStatus(Program program, UUID s /** * Deletes BrAPI plates and submission objects as well as sample submission record in bidb - * We do not currently cache plates or samples so don't need to worry about that * @param submissionId sample submission UUID to delete * @return result describing whether the submission was deleted or why deletion was rejected * @exception ApiException if a BrAPI call fails diff --git a/src/test/java/org/breedinginsight/api/v1/controller/TraitControllerIntegrationTest.java b/src/test/java/org/breedinginsight/api/v1/controller/TraitControllerIntegrationTest.java index fc97ac05c..e728f345e 100644 --- a/src/test/java/org/breedinginsight/api/v1/controller/TraitControllerIntegrationTest.java +++ b/src/test/java/org/breedinginsight/api/v1/controller/TraitControllerIntegrationTest.java @@ -1257,9 +1257,6 @@ public void getTraitsQuery() { HttpResponse createResponse = createCall.blockingFirst(); assertEquals(HttpStatus.OK, createResponse.getStatus()); - //let the cache repopulate - Thread.sleep(3000); - List allTraits = traitDao.findAll(); Flowable> call = client.exchange(