FirehoseMessageProcessor.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.firehose;

import java.time.Duration;
import java.time.Instant;
import java.util.LinkedList;
import java.util.List;
import java.util.NavigableSet;

import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.collections4.CollectionUtils;
import org.gringlobal.component.firehose.FirehoseEvent.EventType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * Inspects the insert/update/delete queues and issues delayed notifications using {@link FirehoseDelayedEvent}.
 */
@Component("firehoseMessageProcessor")
@Slf4j
public class FirehoseMessageProcessor {

	@Autowired
	private ApplicationEventPublisher applicationEventPublisher;

	@Value("${firehose.delay:10}")
	private int firehoseDelay;

	@Resource(name = "updatedEventSet")
	private NavigableSet<FirehoseEvent> updatedEvents;

	@Resource(name = "removedEventSet")
	private NavigableSet<FirehoseEvent> removedEvents;

	@Resource(name = "createdEventSet")
	private NavigableSet<FirehoseEvent> createdEvents;

	@Scheduled(fixedDelay = 1000)
	public void processQueues() {
		var maximumTimestamp = Instant.now().minus(Duration.ofSeconds(firehoseDelay));
		if (log.isTraceEnabled()) {
			log.trace("Scanning for changed objects before {} in created:{} updated:{} deleted:{}", maximumTimestamp, createdEvents.size(), updatedEvents.size(), removedEvents.size());
		}

		List<FirehoseEvent> removedEventsForSending = getEventsTimestampedBefore(removedEvents, maximumTimestamp);
		List<FirehoseEvent> createdEventsForSending = getEventsTimestampedBefore(createdEvents, maximumTimestamp);
		List<FirehoseEvent> updatedEventsForSending = getEventsTimestampedBefore(updatedEvents, maximumTimestamp);

		processEvents(FirehoseEvent.EventType.DELETE, removedEventsForSending);
		processEvents(FirehoseEvent.EventType.CREATE, createdEventsForSending);
		processEvents(FirehoseEvent.EventType.UPDATE, updatedEventsForSending);
	}

	private void processEvents(EventType eventType, List<FirehoseEvent> events) {
		if (CollectionUtils.isEmpty(events)) {
			// log.trace("Nothing to process");
			return;
		}

		events.forEach(firehoseEvent -> {
			if (eventType == FirehoseEvent.EventType.CREATE) {
				log.debug("Sending CREATE notification for {} id={} @ {}", firehoseEvent.getClazz(), firehoseEvent.getId(), firehoseEvent.getTimestamp());
			} else if (eventType == FirehoseEvent.EventType.UPDATE) {
				log.debug("Sending UPDATE notification for {} id={} @ {}", firehoseEvent.getClazz(), firehoseEvent.getId(), firehoseEvent.getTimestamp());
			} else if (eventType == FirehoseEvent.EventType.DELETE) {
				log.debug("Sending DELETE notification for {} id={} @ {}", firehoseEvent.getClazz(), firehoseEvent.getId(), firehoseEvent.getTimestamp());
			}
			log.info("Publishing {} notification for {} id={} @ {}", eventType, firehoseEvent.getClazz(), firehoseEvent.getId(), firehoseEvent.getTimestamp());
			applicationEventPublisher.publishEvent(new FirehoseDelayedEvent(eventType, firehoseEvent));
		});
	}

	private List<FirehoseEvent> getEventsTimestampedBefore(NavigableSet<FirehoseEvent> events, Instant maximumTimestamp) {
		if (events.isEmpty()) {
			return null;
		}

		var eventsBeforeStopDate = events.headSet(new FirehoseEvent(null, null, maximumTimestamp, null));
		if (eventsBeforeStopDate.size() == 0) {
			return null;
		}
		log.debug("Matched {} of {} events", eventsBeforeStopDate.size(), events.size());
		var eventsForSending =  new LinkedList<>(eventsBeforeStopDate);
		eventsBeforeStopDate.clear();
		log.debug("Keeping {} events, remaining {} of {} events", eventsForSending.size(), eventsBeforeStopDate.size(), events.size());

		return eventsForSending;
	}
}