FirehoseReindexListener.java
/*
* Copyright 2021 Global Crop Diversity Trust
*
* 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.genesys.server.component.elastic;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.BlockingQueue;
import javax.annotation.Resource;
import org.genesys.blocks.model.EmptyModel;
import org.genesys.server.component.firehose.FirehoseDeleteAllEvent;
import org.genesys.server.component.firehose.FirehoseEvent;
import org.genesys.server.model.genesys.Accession;
import org.genesys.server.model.genesys.AccessionId;
import org.genesys.server.model.genesys.AccessionRef;
import org.genesys.server.service.ElasticsearchService;
import org.genesys.server.exception.SearchException;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.proxy.LazyInitializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalApplicationListener;
import org.springframework.transaction.event.TransactionalEventListener;
/**
* The FirehoseReindexListener is a {@link TransactionalApplicationListener} that
* is attached to the {@link TransactionPhase} {@code TransactionPhase.AFTER_COMMIT}
* This event listener updates the Elasticsearch update queues immediately.
*
* @author Matija Obreza
*/
// Instantiated in ElasticsearchConfig! @Component
public class FirehoseReindexListener implements InitializingBean {
private final static Logger LOG = LoggerFactory.getLogger(FirehoseReindexListener.class);
private List<Class<?>> includedClasses;
@Resource
private BlockingQueue<ElasticReindex> elasticReindexQueue;
@Autowired
private ElasticsearchService elasticsearchService;
@Override
public void afterPropertiesSet() throws Exception {
includedClasses = elasticsearchService.getIndexedEntities();
}
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void handleEvent(FirehoseEvent firehoseEvent) {
Class<?> clazz = firehoseEvent.getClazz();
Object entity = firehoseEvent.getEntity();
if (entity == null) return;
if (entity instanceof AccessionId) {
AccessionId accessionId = (AccessionId) entity;
LOG.trace("Scheduling reindexing of {} {}", Accession.class.getName(), accessionId.getId());
addNotNull(elasticReindexQueue, new ElasticReindex(Accession.class, accessionId.getId()));
} else if (entity instanceof AccessionRef){
AccessionRef<?> accessionRef = (AccessionRef<?>) entity;
if (accessionRef.getAccession() != null) {
LOG.trace("Scheduling reindexing of {} {}", Accession.class.getName(), accessionRef.getAccession().getId());
addNotNull(elasticReindexQueue, new ElasticReindex(Accession.class, accessionRef.getAccession().getId()));
}
} else if (isIndexed(clazz) && entity instanceof EmptyModel) {
scheduleReindexing(entity);
} else if (ElasticTrigger.class.isAssignableFrom(clazz)) {
try {
Object[] reindexedEntities = ((ElasticTrigger) entity).reindexedEntities();
if (reindexedEntities != null) {
for (var m : reindexedEntities) {
if (m instanceof EmptyModel) {
var toReindex = new ElasticReindex((EmptyModel) m);
var newlyAdded = elasticReindexQueue.add(toReindex);
LOG.info("Firehose dependency {} was (newly={}) queued.", toReindex, newlyAdded);
}
}
}
} catch (Throwable e) {
LOG.error("Error inspecting reindexed entities of {} id={}: {}", clazz, firehoseEvent.getId(), e.getMessage()); // , e);
}
}
}
@EventListener(classes = { FirehoseDeleteAllEvent.class })
// @TransactionalEventListener doesn't work in unit tests
// @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void handleDeleteAllEvent(FirehoseDeleteAllEvent firehoseDeleteAllEvent) {
if (!isIndexed(firehoseDeleteAllEvent.getClazz())) {
return;
}
// Remove from created and updated only
var clazz = firehoseDeleteAllEvent.getClazz();
LOG.debug("Removing all queued items of {}", clazz);
elasticReindexQueue.removeIf(reference -> Objects.equals(reference.getClazz(), clazz));
try {
elasticsearchService.removeAll(clazz);
} catch (SearchException e) {
LOG.warn("Error reindexing {}: {}", clazz, e.getMessage()); //, e);
}
}
public void scheduleReindexing(Object toReindex) {
if (toReindex == null) {
return;
}
HashSet<Object> visited = new HashSet<Object>();
maybeReindex(toReindex, visited);
}
private void maybeReindex(Object toReindex, HashSet<Object> visited) {
if (toReindex == null || visited.contains(toReindex)) {
return;
}
visited.add(toReindex);
ElasticReindex fri = forReindexing(toReindex);
if (fri != null) {
LOG.trace("Scheduling {}#{}", fri.getClazz(), fri.getId());
addNotNull(elasticReindexQueue, fri);
}
if (toReindex instanceof ElasticTrigger) {
Object[] rels = ((ElasticTrigger) toReindex).reindexedEntities();
if (rels != null) {
for (Object related : rels) {
maybeReindex(related, visited);
}
}
}
}
private <T> void addNotNull(Collection<T> destination, T element) {
if (element != null && !destination.contains(element)) {
destination.add(element);
}
}
private ElasticReindex forReindexing(Object toReindex) {
Class<?> clazz = toReindex.getClass();
if (toReindex instanceof HibernateProxy) {
LazyInitializer lazyInitializer = ((HibernateProxy) toReindex).getHibernateLazyInitializer();
clazz = lazyInitializer.getPersistentClass();
if (isIndexed(clazz)) {
LOG.trace("Scheduling reindexing of {} {}", clazz, toReindex);
return new ElasticReindex(clazz, (Long) lazyInitializer.getIdentifier());
} else {
return null;
}
} else if (isIndexed(clazz)) {
if (toReindex instanceof EmptyModel) {
LOG.trace("Scheduling reindexing of {} {}", clazz, toReindex);
return new ElasticReindex(clazz, ((EmptyModel) toReindex).getId());
} else {
LOG.warn("Don't know how to index {}. Not an EmptyModel.", clazz.getName());
return null;
}
}
return null;
}
private boolean isIndexed(Class<?> clazz) {
if (includedClasses.contains(clazz)) {
return true;
}
return false;
}
}