2024-10-14 22:34:41 +01:00
|
|
|
package stirling.software.SPDF.service;
|
|
|
|
|
|
|
|
import java.util.HashMap;
|
|
|
|
import java.util.Map;
|
|
|
|
import java.util.concurrent.ConcurrentHashMap;
|
|
|
|
|
|
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
|
|
import org.springframework.scheduling.annotation.Scheduled;
|
|
|
|
import org.springframework.stereotype.Service;
|
|
|
|
|
|
|
|
import io.micrometer.core.instrument.MeterRegistry;
|
|
|
|
import io.micrometer.core.instrument.search.Search;
|
|
|
|
|
|
|
|
@Service
|
|
|
|
public class MetricsAggregatorService {
|
|
|
|
|
|
|
|
private final MeterRegistry meterRegistry;
|
|
|
|
private final PostHogService postHogService;
|
|
|
|
private final Map<String, Double> lastSentMetrics = new ConcurrentHashMap<>();
|
|
|
|
|
|
|
|
@Autowired
|
|
|
|
public MetricsAggregatorService(MeterRegistry meterRegistry, PostHogService postHogService) {
|
|
|
|
this.meterRegistry = meterRegistry;
|
|
|
|
this.postHogService = postHogService;
|
|
|
|
}
|
|
|
|
|
2024-11-25 14:02:17 +00:00
|
|
|
@Scheduled(fixedRate = 1800000) // Run every 30 minutes
|
2024-10-14 22:34:41 +01:00
|
|
|
public void aggregateAndSendMetrics() {
|
|
|
|
Map<String, Object> metrics = new HashMap<>();
|
|
|
|
Search.in(meterRegistry)
|
|
|
|
.name("http.requests")
|
|
|
|
.counters()
|
|
|
|
.forEach(
|
|
|
|
counter -> {
|
2024-11-20 08:20:01 +00:00
|
|
|
String method = counter.getId().getTag("method");
|
|
|
|
String uri = counter.getId().getTag("uri");
|
2024-11-26 20:50:35 +00:00
|
|
|
|
2024-11-20 08:20:01 +00:00
|
|
|
// Skip if either method or uri is null
|
|
|
|
if (method == null || uri == null) {
|
|
|
|
return;
|
|
|
|
}
|
2024-11-26 21:30:47 +00:00
|
|
|
if (!method.equals("GET") && !method.equals("POST")) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
// Skip URIs that are 2 characters or shorter
|
|
|
|
if (uri.length() <= 2) {
|
|
|
|
return;
|
|
|
|
}
|
2024-11-26 20:50:35 +00:00
|
|
|
|
|
|
|
String key =
|
|
|
|
String.format(
|
|
|
|
"http_requests_%s_%s", method, uri.replace("/", "_"));
|
2024-10-14 22:34:41 +01:00
|
|
|
|
|
|
|
double currentCount = counter.count();
|
|
|
|
double lastCount = lastSentMetrics.getOrDefault(key, 0.0);
|
|
|
|
double difference = currentCount - lastCount;
|
|
|
|
|
|
|
|
if (difference > 0) {
|
|
|
|
metrics.put(key, difference);
|
|
|
|
lastSentMetrics.put(key, currentCount);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
// Send aggregated metrics to PostHog
|
|
|
|
if (!metrics.isEmpty()) {
|
|
|
|
postHogService.captureEvent("aggregated_metrics", metrics);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|