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.gringlobal.component.elastic;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.BlockingQueue;

import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;
import org.genesys.blocks.model.EmptyModel;
import org.gringlobal.component.firehose.FirehoseDeleteAllEvent;
import org.gringlobal.component.firehose.FirehoseEvent;
import org.gringlobal.custom.elasticsearch.SearchException;
import org.gringlobal.service.ElasticsearchService;
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.stereotype.Component;
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
 */
@Component
@Slf4j
public class FirehoseReindexListener implements InitializingBean {
	private static final Logger LOGtest = LoggerFactory.getLogger("org.gringlobal.test.Elasticsearch");

	private Set<Class<?>> includedClasses;

	@Resource
	private BlockingQueue<ElasticReindex> elasticReindexQueue; // JVM-bound queue

	@Autowired
	private ElasticsearchService elasticsearchService;
	
	@Override
	public void afterPropertiesSet() throws Exception {
		includedClasses = new HashSet<>(elasticsearchService.getIndexedEntities());
	}

	@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
	public void handleEvent(FirehoseEvent firehoseEvent) {
		Class<?> clazz = firehoseEvent.getClazz();
		Object entity = firehoseEvent.getEntity();

		if (isIndexed(clazz) && entity instanceof EmptyModel) {
			var reindex = new ElasticReindex((EmptyModel) entity);
			log.debug("Scheduling {}", reindex);

			var newlyAdded = elasticReindexQueue.add(reindex);
			LOGtest.info("Firehose scheduling {} was (newly={}) queued.", reindex, newlyAdded);

		} else if (entity != null && ElasticTrigger.class.isAssignableFrom(clazz)) {
			// Interesting!
			if (LOGtest.isInfoEnabled()) LOGtest.info("Firehose sent an ElasticTrigger {}", entity);
			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);
							LOGtest.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();
		var size = elasticReindexQueue.size();
		log.debug("Removing all queued items of {}", clazz);
		if (LOGtest.isInfoEnabled()) LOGtest.info("Firehose removing queued items of {} from set of {}", clazz, size);
		elasticReindexQueue.removeIf(reference -> Objects.equals(reference.getClazz(), clazz));
		if (LOGtest.isInfoEnabled()) LOGtest.info("Firehose set of {} remains", size);
		try {
			elasticsearchService.removeAll(clazz);
		} catch (SearchException e) {
			log.warn("Error reindexing {}: {}", clazz, e.getMessage()); //, e);
		}
	}

	private boolean isIndexed(Class<?> clazz) {
		if (includedClasses.contains(clazz)) {
			return true;
		}
		return false;
	}
}