Skip to content

Commit

Permalink
MSEARCH-794: refactor and fix tests
Browse files Browse the repository at this point in the history
  • Loading branch information
mukhiddin-yusuf committed Aug 19, 2024
1 parent 295a055 commit 5531c83
Show file tree
Hide file tree
Showing 28 changed files with 146 additions and 169 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
import org.folio.search.service.consortium.ConsortiumInstitutionService;
import org.folio.search.service.consortium.ConsortiumLibraryService;
import org.folio.search.service.consortium.ConsortiumLocationService;
import org.folio.search.service.consortium.UserTenantsService;
import org.folio.search.service.consortium.ConsortiumTenantService;
import org.folio.spring.integration.XOkapiHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
Expand All @@ -46,7 +46,7 @@ public class SearchConsortiumController implements SearchConsortiumApi {
static final String REQUEST_NOT_ALLOWED_MSG =
"The request allowed only for central tenant of consortium environment";

private final UserTenantsService userTenantsService;
private final ConsortiumTenantService consortiumTenantService;
private final ConsortiumInstanceService instanceService;
private final ConsortiumLocationService locationService;
private final ConsortiumInstanceSearchService searchService;
Expand Down Expand Up @@ -201,7 +201,7 @@ public ResponseEntity<ConsortiumItemCollection> fetchConsortiumBatchItems(String
}

private String verifyAndGetTenant(String tenantHeader) {
var centralTenant = userTenantsService.getCentralTenant(tenantHeader);
var centralTenant = consortiumTenantService.getCentralTenant(tenantHeader);
if (centralTenant.isEmpty() || !centralTenant.get().equals(tenantHeader)) {
throw new RequestValidationException(REQUEST_NOT_ALLOWED_MSG, XOkapiHeaders.TENANT, tenantHeader);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public List<UUID> fetchInventoryRecordIds(InventoryRecordType recordType, CqlQue
}
}

public int fetchInventoryRecordCount(InventoryRecordType recordType) {
public int fetchInventoryRecordsCount(InventoryRecordType recordType) {
if (recordType == null) {
log.warn("No Inventory Record Type was provided to fetch Inventory Count");
return 0;
Expand All @@ -67,7 +67,7 @@ public int fetchInventoryRecordCount(InventoryRecordType recordType) {
};

if (result == null) {
log.warn("Failed to retrieve Inventory Instances count");
log.warn("Failed to retrieve Inventory Records count");
return 0;
}

Expand All @@ -82,7 +82,7 @@ public int fetchInventoryRecordCount(InventoryRecordType recordType) {
public void publishReindexRecordsRange(MergeRangeEntity rangeEntity) {
if (rangeEntity == null
|| ObjectUtils.anyNull(rangeEntity.getId(), rangeEntity.getLowerId(), rangeEntity.getUpperId())) {
log.warn("invalid Range Entity: [rangeEntity: {}]", rangeEntity);
log.warn("Invalid Range Entity: [rangeEntity: {}]", rangeEntity);
return;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
import org.folio.search.domain.dto.ResourceEventType;
import org.folio.search.model.event.ContributorResourceEvent;
import org.folio.search.model.event.SubjectResourceEvent;
import org.folio.search.service.consortium.UserTenantsService;
import org.folio.search.service.consortium.ConsortiumTenantService;
import org.folio.search.utils.CollectionUtils;
import org.folio.search.utils.JsonConverter;
import org.springframework.kafka.core.KafkaTemplate;
Expand All @@ -54,7 +54,7 @@ public class KafkaMessageProducer {
private static final TypeReference<List<SubjectResourceEvent>> TYPE_REFERENCE_SUBJECT = new TypeReference<>() { };
private final JsonConverter jsonConverter;
private final KafkaTemplate<String, ResourceEvent> kafkaTemplate;
private final UserTenantsService userTenantsService;
private final ConsortiumTenantService consortiumTenantService;

public void prepareAndSendContributorEvents(List<ResourceEvent> resourceEvents) {
prepareAndSendEvents(resourceEvents, this::getContributorEvents);
Expand Down Expand Up @@ -113,7 +113,7 @@ private List<SubjectResourceEvent> extractSubjects(Map<String, Object> objectMap
}

private boolean isSharedResource(String tenantId) {
var centralTenant = userTenantsService.getCentralTenant(tenantId);
var centralTenant = consortiumTenantService.getCentralTenant(tenantId);
return centralTenant.isPresent() && centralTenant.get().equals(tenantId);
}

Expand Down
8 changes: 4 additions & 4 deletions src/main/java/org/folio/search/service/ResourceService.java
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
import org.folio.search.repository.ResourceRepository;
import org.folio.search.service.consortium.ConsortiumInstanceService;
import org.folio.search.service.consortium.ConsortiumTenantExecutor;
import org.folio.search.service.consortium.UserTenantsService;
import org.folio.search.service.consortium.ConsortiumTenantService;
import org.folio.search.service.converter.MultiTenantSearchDocumentConverter;
import org.folio.search.service.converter.preprocessor.InstanceEventPreProcessor;
import org.folio.search.service.metadata.ResourceDescriptionService;
Expand All @@ -64,7 +64,7 @@ public class ResourceService {
private final ResourceDescriptionService resourceDescriptionService;
private final MultiTenantSearchDocumentConverter multiTenantSearchDocumentConverter;
private final Map<String, ResourceRepository> resourceRepositoryBeans;
private final UserTenantsService userTenantsService;
private final ConsortiumTenantService consortiumTenantService;
private final ConsortiumTenantExecutor consortiumTenantExecutor;
private final ConsortiumInstanceService consortiumInstanceService;
private final IndexNameProvider indexNameProvider;
Expand Down Expand Up @@ -124,7 +124,7 @@ public FolioIndexOperationResponse indexConsortiumInstances(List<ConsortiumInsta
}

var validConsortiumInstances = consortiumInstances.stream()
.filter(event -> userTenantsService.getCentralTenant(event.getTenant()).isPresent())
.filter(event -> consortiumTenantService.getCentralTenant(event.getTenant()).isPresent())
.distinct()
.toList();

Expand All @@ -133,7 +133,7 @@ public FolioIndexOperationResponse indexConsortiumInstances(List<ConsortiumInsta
log.debug("Skip indexing consortium instances [{}]", invalidInstances);
}

var centralTenant = userTenantsService.getCentralTenant(validConsortiumInstances.get(0).getTenant())
var centralTenant = consortiumTenantService.getCentralTenant(validConsortiumInstances.get(0).getTenant())
.orElseThrow(() -> new IllegalStateException("Central tenant must exist"));

var instanceIds = validConsortiumInstances.stream().map(ConsortiumInstanceEvent::getInstanceId).collect(toSet());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public class ConsortiumInstanceService {
private final JsonConverter jsonConverter;
private final ConsortiumInstanceRepository repository;
private final ConsortiumTenantExecutor consortiumTenantExecutor;
private final UserTenantsService userTenantsService;
private final ConsortiumTenantService consortiumTenantService;
private final FolioMessageProducer<ConsortiumInstanceEvent> producer;
private final FolioExecutionContext context;

Expand Down Expand Up @@ -141,7 +141,7 @@ public List<ResourceEvent> fetchInstances(Iterable<String> instanceIds) {
// if more than one instance returned then holdings/items merging required
for (var instance : entry.getValue()) {
var instanceMap = jsonConverter.fromJsonToMap(instance.instance());
if (isCentralTenant(instance.id().tenantId())) {
if (consortiumTenantService.isCentralTenant(instance.id().tenantId())) {
mergedInstance = instanceMap;
}
addListItems(mergedHoldings, instanceMap, HOLDINGS_KEY);
Expand Down Expand Up @@ -198,7 +198,7 @@ private Map<String, Object> prepareInstance(ResourceEvent resourceEvent) {
SearchConverterUtils.setMapValueByPath(TENANT_ID_KEY, tenant, instance);
SearchConverterUtils.setMapValueByPath(HOLDINGS_TENANT_ID_KEY, tenant, instance);
SearchConverterUtils.setMapValueByPath(ITEMS_TENANT_ID_KEY, tenant, instance);
if (isCentralTenant(tenant)) {
if (consortiumTenantService.isCentralTenant(tenant)) {
SearchConverterUtils.setMapValueByPath(SHARED_KEY, true, instance);
}
return instance;
Expand All @@ -211,12 +211,7 @@ private Map<Boolean, List<ResourceEvent>> groupEventsByConsortiumTenant(List<Res
}

private boolean isConsortiumTenant(String tenantId) {
return userTenantsService.getCentralTenant(tenantId).isPresent();
}

private boolean isCentralTenant(String tenantId) {
var centralTenant = userTenantsService.getCentralTenant(tenantId);
return centralTenant.isPresent() && centralTenant.get().equals(tenantId);
return consortiumTenantService.getCentralTenant(tenantId).isPresent();
}

private <T> void prepareAndSendConsortiumInstanceEvents(Collection<T> values,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public class ConsortiumSearchHelper {
private static final String BROWSE_TENANT_FILTER_KEY = "instances.tenantId";

private final FolioExecutionContext folioExecutionContext;
private final UserTenantsService userTenantsService;
private final ConsortiumTenantService consortiumTenantService;

public QueryBuilder filterQueryForActiveAffiliation(QueryBuilder query, String resource) {
var contextTenantId = folioExecutionContext.getTenantId();
Expand All @@ -51,7 +51,7 @@ public QueryBuilder filterQueryForActiveAffiliation(QueryBuilder query, String r
* modified query will have member 'tenantId' filter with shared=true).
*/
public QueryBuilder filterQueryForActiveAffiliation(QueryBuilder query, String resource, String contextTenantId) {
var centralTenantId = userTenantsService.getCentralTenant(contextTenantId);
var centralTenantId = consortiumTenantService.getCentralTenant(contextTenantId);
if (centralTenantId.isEmpty()) {
return query;
}
Expand All @@ -76,7 +76,7 @@ public QueryBuilder filterBrowseQueryForActiveAffiliation(BrowseContext browseCo
String resource) {
logger.debug("Filtering browse query for {}", resource);
var contextTenantId = folioExecutionContext.getTenantId();
var centralTenantId = userTenantsService.getCentralTenant(contextTenantId);
var centralTenantId = consortiumTenantService.getCentralTenant(contextTenantId);
var sharedFilter = getBrowseSharedFilter(browseContext);
if (centralTenantId.isEmpty()) {
sharedFilter.ifPresent(filter -> browseContext.getFilters().remove(filter));
Expand Down Expand Up @@ -110,7 +110,7 @@ public <T> Set<InstanceSubResource> filterSubResourcesForConsortium(

var subResources = subResourceExtractor.apply(resource);
var contextTenantId = folioExecutionContext.getTenantId();
var centralTenantId = userTenantsService.getCentralTenant(contextTenantId);
var centralTenantId = consortiumTenantService.getCentralTenant(contextTenantId);
if (centralTenantId.isEmpty()) {
return subResources;
} else if (contextTenantId.equals(centralTenantId.get())) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@
@RequiredArgsConstructor
public class ConsortiumTenantProvider implements TenantProvider {

private final UserTenantsService userTenantsService;
private final ConsortiumTenantService consortiumTenantService;

@Override
public String getTenant(String tenantId) {
return userTenantsService.getCentralTenant(tenantId)
return consortiumTenantService.getCentralTenant(tenantId)
.orElse(tenantId);
}
}
Original file line number Diff line number Diff line change
@@ -1,23 +1,30 @@
package org.folio.search.service.consortium;

import static org.folio.search.configuration.SearchCacheNames.CONSORTIUM_TENANTS_CACHE;
import static org.folio.search.configuration.SearchCacheNames.USER_TENANTS_CACHE;

import java.util.Collections;
import java.util.List;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.folio.search.client.ConsortiumTenantsClient;
import org.folio.search.client.UserTenantsClient;
import org.folio.search.exception.FolioIntegrationException;
import org.folio.spring.FolioExecutionContext;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Log4j2
@Service
@RequiredArgsConstructor
public class UserTenantsService {
public class ConsortiumTenantService {

private final UserTenantsClient userTenantsClient;
private static final int DEFAULT_REQUEST_LIMIT = 10000;

private final UserTenantsClient userTenantsClient;
private final ConsortiumTenantsClient consortiumTenantsClient;
private final FolioExecutionContext context;

@Cacheable(cacheNames = USER_TENANTS_CACHE, key = "@folioExecutionContext.tenantId + ':' + #tenantId")
Expand Down Expand Up @@ -56,4 +63,41 @@ public Optional<String> getConsortiumId(String tenantId) {
return Optional.empty();
}

/**
* Get consortium tenants for tenantId.
*
* @return only consortium member tenants
* */
@Cacheable(cacheNames = CONSORTIUM_TENANTS_CACHE, key = "@folioExecutionContext.tenantId + ':' + #tenantId")
public List<String> getConsortiumTenants(String tenantId) {
try {
return getConsortiumId(tenantId)
.map(consortiumId -> consortiumTenantsClient.getConsortiumTenants(consortiumId, DEFAULT_REQUEST_LIMIT))
.map(ConsortiumTenantsClient.ConsortiumTenants::tenants)
.map(this::getTenantsList)
.orElse(Collections.emptyList());
} catch (Exception e) {
log.debug("Unexpected exception occurred while trying to get consortium tenants", e);
throw new FolioIntegrationException("Failed to retrieve consortium tenants", e);
}
}

public boolean isMemberTenantInConsortium(String tenantId) {
return getCentralTenant(tenantId)
.map(centralTenantId -> !centralTenantId.equals(tenantId))
.orElse(false);
}

public boolean isCentralTenant(String tenantId) {
return getCentralTenant(tenantId)
.map(centralTenantId -> centralTenantId.equals(tenantId))
.orElse(false);
}

private List<String> getTenantsList(List<ConsortiumTenantsClient.ConsortiumTenant> consortiumTenants) {
return consortiumTenants.stream()
.filter(consortiumTenant -> !consortiumTenant.isCentral())
.map(ConsortiumTenantsClient.ConsortiumTenant::id)
.toList();
}
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
import org.folio.search.domain.dto.ResourceEvent;
import org.folio.search.domain.dto.ResourceEventType;
import org.folio.search.model.metadata.AuthorityFieldDescription;
import org.folio.search.service.consortium.UserTenantsService;
import org.folio.search.service.consortium.ConsortiumTenantService;
import org.folio.search.service.metadata.ResourceDescriptionService;
import org.springframework.stereotype.Component;

Expand All @@ -32,7 +32,7 @@
public class AuthorityEventPreProcessor implements EventPreProcessor {

private final ResourceDescriptionService resourceDescriptionService;
private final UserTenantsService userTenantsService;
private final ConsortiumTenantService consortiumTenantService;
private Map<String, List<String>> fieldTypes;
private List<String> commonFields;

Expand Down Expand Up @@ -73,8 +73,7 @@ public List<ResourceEvent> preProcess(ResourceEvent event) {
var eventNewPart = getNewAsMap(event);
eventNewPart.put("tenantId", event.getTenant());

var centralTenant = userTenantsService.getCentralTenant(event.getTenant());
if (centralTenant.isPresent() && centralTenant.get().equals(event.getTenant())) {
if (consortiumTenantService.isCentralTenant(event.getTenant())) {
eventNewPart.put("shared", true);
}
}
Expand Down
Loading

0 comments on commit 5531c83

Please sign in to comment.