ApiRequestCountKpiProcessor.java

/*
 * Copyright 2026 Global Crop Diversity Trust
 * Licensed under the Apache License, Version 2.0
 * See LICENSE file in project root folder or http://www.apache.org/licenses/LICENSE-2.0
 */

package org.gringlobal.metrics;

import static org.gringlobal.model.kpi.QExecutionRun.executionRun;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicLong;

import org.gringlobal.model.kpi.DimensionKey;
import org.gringlobal.model.kpi.Execution;
import org.gringlobal.model.kpi.ExecutionRun;
import org.gringlobal.model.kpi.KPIParameter;
import org.gringlobal.model.kpi.Observation;
import org.gringlobal.model.kpi.QExecutionRun;
import org.gringlobal.persistence.kpi.DimensionKeyRepository;
import org.gringlobal.persistence.kpi.ExecutionRepository;
import org.gringlobal.persistence.kpi.ExecutionRunRepository;
import org.gringlobal.persistence.kpi.KPIParameterRepository;
import org.gringlobal.persistence.kpi.ObservationRepository;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.data.domain.Pageable;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.querydsl.jpa.impl.JPAQueryFactory;
import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;

@Slf4j
@Component
public class ApiRequestCountKpiProcessor implements InitializingBean {

	private static final String PARAM_NAME = "api.request";
	private static final String EXECUTION_NAME = "system.api.requests.monthly";
	private static final String DIMENSION_NAME = "sid";

	@Autowired
	private ApiRequestMetrics requestMetrics;

	@Autowired
	private KPIParameterRepository kpiParameterRepository;
	@Autowired
	private DimensionKeyRepository dimensionKeyRepository;
	@Autowired
	private ExecutionRepository executionRepository;
	@Autowired
	private ExecutionRunRepository executionRunRepository;
	@Autowired
	private ObservationRepository observationRepository;
	@Autowired
	private JPAQueryFactory jpaQueryFactory;

	@Override
	public void afterPropertiesSet() {
		try {
			KPIParameter param = kpiParameterRepository.findByName(PARAM_NAME);
			if (param == null) {
				KPIParameter p = new KPIParameter();
				p.setName(PARAM_NAME);
				p.setTitle("API Request");
				p.setEntity(KPIParameter.SYSTEM_PARAM_ENTITY);
				param = kpiParameterRepository.save(p);
			}
			Execution exec = executionRepository.findByName(EXECUTION_NAME);
			if (exec == null) {
				Execution e = new Execution();
				e.setType(Execution.ExecutionType.MANUAL);
				e.setName(EXECUTION_NAME);
				e.setIsActive("Y");
				e.setTitle("Monthly API requests per SID");
				e.setParameter(param);
				e.setProperty("id");
				exec = executionRepository.save(e);
			}
			log.debug("Initialized KPI entities for API requests counter: parameter={}, execution={}", param.getName(), exec.getName());
		} catch (Exception e) {
			log.error("Failed to initialize KPI entities for API requests", e);
		}
	}

	@Scheduled(initialDelayString = "PT1M", fixedDelayString = "PT6M") // Every 6 minutes
	@SchedulerLock(name = "org.gringlobal.metrics.ApiRequestCountKpiProcessor")
	@Transactional
	public void persistRequestCounts() {
		try {
			log.debug("Persisting API request counts to KPI");
			var snapshot = requestMetrics.getAndResetCounters();
			mergeSnapshotIntoDailyRun(snapshot, LocalDate.now());
		} catch (Throwable e) {
			log.error("Failed persisting API request counts: {}", e.getMessage(), e);
		}
	}

	// Try to persist on shutdown to avoid loss on restarts
	@EventListener(ContextClosedEvent.class)
	@SchedulerLock(name = "org.gringlobal.metrics.ApiRequestCountKpiProcessor")
	@Transactional
	public void onShutdownPersist() {
		try {
			var snapshot = requestMetrics.getAndResetCounters();
			mergeSnapshotIntoDailyRun(snapshot, LocalDate.now());
		} catch (Throwable e) {
			log.warn("Failed to persist API request counts on shutdown", e);
		}
	}

	/**
	 * Merges the given per-SID request-count snapshot into the execution run for the
	 * provided date. If a run already exists for that date, existing observations are
	 * updated with the snapshot counts. Otherwise a new run is created and, unless
	 * yesterday was the first of the month, yesterday's observations are carried over.
	 */
	private void mergeSnapshotIntoDailyRun(Map<String, Long> snapshot, LocalDate date) {
		Execution execution = executionRepository.findByName(EXECUTION_NAME);
		if (execution == null) {
			log.debug("KPI execution not initialized; skipping persistence for {}", date);
			return;
		}
		if (! Objects.equals("Y", execution.getIsActive())) {
			log.debug("KPI execution {} not active; skipping persistence for {}", execution.getName(), date);
			return;
		}

		// Start with today's snapshot
		Map<String, Long> merged = new HashMap<>();
		if (snapshot == null || snapshot.isEmpty()) {
			log.debug("No new API requests to persist for {}", date);
		} else {
			merged.putAll(snapshot);
		}

		// Target run for new observations
		ExecutionRun targetRun = null;
		// Observations to persist
		var updatedObservations = new LinkedList<Observation>();
		// Running total of all observation values that will exist for this run.
		final AtomicLong totalValue = new AtomicLong(0L);

		// Find existing run for today
		ExecutionRun todayRun = jpaQueryFactory.selectFrom(QExecutionRun.executionRun)
			.where(executionRun.execution().eq(execution).and(executionRun.timestamp.eq(date)))
			.limit(1)
			.fetchFirst();

		if (todayRun != null) {
			log.info("Merging snapshot for {} into existing run id={} timestamp={}", date, todayRun.getId(), todayRun.getTimestamp());

			targetRun = todayRun;

			// Update existing observations for the same day
			observationRepository.findByExecutionRun(todayRun, Pageable.unpaged())
				.forEach(obs -> {
					String sid = obs.getDimensions().stream()
						.filter(dk -> DIMENSION_NAME.equals(dk.getName()))
						.map(DimensionKey::getValue)
						.findFirst().orElse(ApiRequestMetrics.UNKNOWN_SID);

					if (merged.containsKey(sid)) {
						log.debug("Adding {} to {} for sid {}", merged.get(sid), obs.getValue(), sid);
						// Update existing observation and remove so it does not get inserted again
						long newValue = (long) obs.getValue() + merged.get(sid);
						obs.setValue(newValue);
						updatedObservations.add(obs);
						merged.remove(sid);
						totalValue.addAndGet(newValue);
					} else {
						totalValue.addAndGet((long) obs.getValue());
					}
				});

		} else {
			// No run yet for today: create one and carry over yesterday's totals,
			// except when yesterday was the first of the month (preserving a clean month boundary).

			ExecutionRun run = new ExecutionRun();
			run.setExecution(execution);
			run.setTimestamp(date);

			targetRun = run;

			LocalDate yesterday = date.minusDays(1);
			if (yesterday.getDayOfMonth() != 1) {
				// Find the latest run for this month, excluding the 1st
				// The 1st of the month contains the final result of the previous month.
				var firstOfMonth = yesterday.withDayOfMonth(1);
				ExecutionRun yRun = jpaQueryFactory.selectFrom(QExecutionRun.executionRun)
					.where(executionRun.execution().eq(execution).and(executionRun.timestamp.loe(yesterday)).and(executionRun.timestamp.gt(firstOfMonth)))
					.orderBy(QExecutionRun.executionRun.timestamp.desc())
					.limit(1)
					.fetchFirst();

				if (yRun != null) {
					log.info("Carrying over yesterday's counts into {} from run id={} timestamp={}", date, yRun.getId(), yRun.getTimestamp());
					observationRepository.findByExecutionRun(yRun, Pageable.unpaged())
						.forEach(obs -> {
							String sid = obs.getDimensions().stream()
								.filter(dk -> DIMENSION_NAME.equals(dk.getName()))
								.map(DimensionKey::getValue)
								.findFirst().orElse(ApiRequestMetrics.UNKNOWN_SID);

							// Seed today's totals with yesterday's values so that counters accumulate
							merged.merge(sid, (long) obs.getValue(), Long::sum);
						});
				}
			}
		}

		log.info("Inserting {} new observations into run id={} date={}", merged.size(), targetRun.getId(), targetRun.getTimestamp());
		for (Map.Entry<String, Long> e : merged.entrySet()) {
			DimensionKey dk = dimensionKeyRepository.findByNameAndValue(DIMENSION_NAME, e.getKey());
			if (dk == null) {
				dk = DimensionKey.createFor(DIMENSION_NAME, e.getKey());
				dk = dimensionKeyRepository.save(dk);
			}
			Observation obs = new Observation();
			obs.setExecutionRun(targetRun);
			obs.setValue(e.getValue());
			obs.getDimensions().add(dk);
			updatedObservations.add(obs);
			totalValue.addAndGet(e.getValue());
		}

		// Update total value of the run
		targetRun.setTotalValue(totalValue.doubleValue());
		targetRun = executionRunRepository.save(targetRun);

		if (!updatedObservations.isEmpty()) {
			observationRepository.saveAll(updatedObservations);
		}
		log.debug("Saved {} KPI observations for {}", updatedObservations.size(), date);
	}

}