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.genesys.server.component.firehose;

import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.NavigableSet;
import java.util.TreeSet;

import javax.annotation.Resource;

import org.apache.commons.collections4.CollectionUtils;
import org.genesys.server.component.firehose.FirehoseEvent.EventType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;

/**
 *
 * Inspects the insert/update/delete queues and issues notifications.
 *
 * @author Artem Hrybeniuk
 */
// Instantiated in FirehoseConfig! @Component("firehoseMessageProcessor")
public class FirehoseMessageProcessor {

	public static final Logger LOG = LoggerFactory.getLogger(FirehoseMessageProcessor.class);

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

	@Resource(name = "updatedEventSet")
	private Map<String, FirehoseEvent> updatedEvents;

	@Resource(name = "removedEventSet")
	private Map<String, FirehoseEvent> removedEvents;

	@Resource(name = "createdEventSet")
	private Map<String, FirehoseEvent> createdEvents;

	@Scheduled(fixedDelay = 1000)
	public void processQueues() {
//		Date stopDate = new Date(System.currentTimeMillis() - (firehoseDelay * 1000 * 60)); // delay in minutes
		Instant stopDate = Instant.ofEpochMilli(System.currentTimeMillis() - (firehoseDelay * 1000)); // delay in seconds
		LOG.trace("Scanning for Firehose events before: {}", stopDate);

		List<FirehoseEvent> removedEventsForSending = getEventsBeforeStopDate(removedEvents, stopDate);
		List<FirehoseEvent> createdEventsForSending = getEventsBeforeStopDate(createdEvents, stopDate);
		List<FirehoseEvent> updatedEventsForSending = getEventsBeforeStopDate(updatedEvents, stopDate);

		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)) {
			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());
			}
		});
	}

	private List<FirehoseEvent> getEventsBeforeStopDate(Map<String, FirehoseEvent> events, Instant stopDate) {
		if (events.isEmpty()) {
			return null;
		}

		NavigableSet<FirehoseEvent> eventNavigableSet = Collections.synchronizedNavigableSet(new TreeSet<>(events.values()));
		var eventsBeforeStopDate = eventNavigableSet.headSet(new FirehoseEvent(null, null, stopDate, null));
		if (eventsBeforeStopDate.size() == 0) {
			return null;
		}
		var eventsForSending =  new ArrayList<>(eventsBeforeStopDate);
		eventsForSending.forEach(event -> events.remove(event.getKey()));
		if (LOG.isDebugEnabled()) {
			LOG.debug("Matched {} of {} events, keeping {} events", eventsBeforeStopDate.size(), eventNavigableSet.size(), events.size());
		}

		return eventsForSending;
	}
}