fix: drop telemetry from app (#52)

This commit is contained in:
James Ward
2026-03-20 17:20:18 -05:00
committed by James Cox
parent 11a76bffe1
commit 4d82cb7188
32 changed files with 2 additions and 991 deletions
@@ -15,7 +15,6 @@ public class AppProperties {
private String version;
private RemoteAuth remoteAuth;
private Boolean forceDisableOidc = false;
private Telemetry telemetry = new Telemetry();
/**
* Type of disk storage where library files are stored.
@@ -41,10 +40,4 @@ public class AppProperties {
private String adminGroup;
private String groupsDelimiter = "\\s+"; // Default to whitespace for backward compatibility
}
@Getter
@Setter
public static class Telemetry {
private String baseUrl = "https://telemetry.booklore.org";
}
}
@@ -1,148 +0,0 @@
package org.booklore.crons;
import jakarta.annotation.PostConstruct;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.booklore.config.AppProperties;
import org.booklore.model.dto.BookloreTelemetry;
import org.booklore.model.dto.InstallationPing;
import org.booklore.model.dto.settings.AppSettings;
import org.booklore.service.TelemetryService;
import org.booklore.service.appsettings.AppSettingService;
import org.springframework.boot.sql.init.dependency.DependsOnDatabaseInitialization;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.TimeUnit;
@Service
@AllArgsConstructor
@DependsOnDatabaseInitialization
@Slf4j
public class CronService {
private static final String LAST_TELEMETRY_KEY = "last_telemetry_sent";
private static final String LAST_PING_KEY = "last_ping_sent";
private static final String LAST_PING_APP_VERSION_KEY = "last_ping_app_version";
private static final long INTERVAL_HOURS = 24;
private final AppProperties appProperties;
private final TelemetryService telemetryService;
private final RestClient restClient;
private final AppSettingService appSettingService;
@PostConstruct
public void initScheduledTasks() {
checkAndRunTelemetry();
checkAndRunPing();
}
@Scheduled(fixedDelay = 24, timeUnit = TimeUnit.HOURS, initialDelay = 24)
public void sendTelemetryData() {
if (isTelemetryEnabled()) {
String url = appProperties.getTelemetry().getBaseUrl() + "/api/v1/ingest";
BookloreTelemetry telemetry = telemetryService.collectTelemetry();
if (postData(url, telemetry)) {
appSettingService.saveSetting(LAST_TELEMETRY_KEY, Instant.now().toString());
}
}
}
@Scheduled(fixedDelay = 24, timeUnit = TimeUnit.HOURS, initialDelay = 12)
public void sendPing() {
if (isTelemetryEnabled()) {
String url = appProperties.getTelemetry().getBaseUrl() + "/api/v1/heartbeat";
InstallationPing ping = telemetryService.getInstallationPing();
if (ping != null && postData(url, ping)) {
appSettingService.saveSetting(LAST_PING_KEY, Instant.now().toString());
appSettingService.saveSetting(LAST_PING_APP_VERSION_KEY, ping.getAppVersion());
}
}
}
protected boolean postData(String url, Object body) {
try {
restClient.post()
.uri(url)
.body(body)
.retrieve()
.body(String.class);
return true;
} catch (Exception ex) {
log.debug("POST request to URL: {}, Message: {}", url, ex.getMessage());
return false;
}
}
private boolean isTelemetryEnabled() {
AppSettings settings = appSettingService.getAppSettings();
return settings != null && settings.isTelemetryEnabled();
}
private void checkAndRunTelemetry() {
AppSettings settings = appSettingService.getAppSettings();
if (settings == null || !settings.isTelemetryEnabled()) {
return;
}
String lastRunStr = appSettingService.getSettingValue(LAST_TELEMETRY_KEY);
if (shouldRunTask(lastRunStr)) {
log.info("Running stats on startup (last run: {})", lastRunStr);
sendTelemetryData();
}
}
private void checkAndRunPing() {
String lastRunStr = appSettingService.getSettingValue(LAST_PING_KEY);
if (hasAppVersionChanged()) {
log.info("App version changed, sending immediate ping");
sendPing();
return;
}
if (shouldRunTask(lastRunStr)) {
log.info("Running ping on startup (last run: {})", lastRunStr);
sendPing();
}
}
/**
* Determines if a task should run immediately on startup.
* Returns false for new installations (no last run recorded) to follow normal schedule.
* Returns true if more than INTERVAL_HOURS have passed since the last run,
* preventing data gaps when the server restarts close to scheduled execution time.
* <p>
* Example: Telemetry normally runs at 2:00 AM daily. If the server restarts at 1:55 AM,
* the scheduled task would reset and not run until 2:00 AM the next day (48 hours later).
* This method checks if 24+ hours have passed since the last run and executes immediately
* on startup if needed, ensuring data is sent at 1:55 AM instead of waiting another 24 hours.
*/
private boolean shouldRunTask(String lastRunStr) {
if (lastRunStr == null || lastRunStr.isEmpty()) {
return false;
}
try {
Instant lastRun = Instant.parse(lastRunStr);
Instant threshold = Instant.now().minus(INTERVAL_HOURS, ChronoUnit.HOURS);
return lastRun.isBefore(threshold);
} catch (Exception e) {
log.warn("Failed to parse last run timestamp: {}", e.getMessage());
return false;
}
}
/**
* Checks if the app version has changed since the last ping.
* Returns true if this is an established installation with a version change.
*/
private boolean hasAppVersionChanged() {
String lastPingVersion = appSettingService.getSettingValue(LAST_PING_APP_VERSION_KEY);
InstallationPing ping = telemetryService.getInstallationPing();
String currentVersion = ping != null ? ping.getAppVersion() : null;
if (lastPingVersion == null || lastPingVersion.isEmpty() || currentVersion == null) {
return false;
}
return !lastPingVersion.equals(currentVersion);
}
}
@@ -1,113 +0,0 @@
package org.booklore.model.dto;
import lombok.*;
import java.util.List;
import java.util.Map;
@Builder
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class BookloreTelemetry {
private int telemetryVersion;
private String installationId;
private String installationDate;
private String appVersion;
private int totalLibraries;
private long totalBooks;
private long totalAdditionalBookFiles;
private long totalAuthors;
private long totalBookNotes;
private long totalBookmarks;
private int totalShelves;
private int totalMagicShelves;
private int totalCategories;
private int totalTags;
private int totalMoods;
private int totalKoreaderUsers;
private UserStatistics userStatistics;
private MetadataStatistics metadataStatistics;
private OpdsStatistics opdsStatistics;
private KoboStatistics koboStatistics;
private EmailStatistics emailStatistics;
private BookStatistics bookStatistics;
private List<LibraryStatistics> libraryStatisticsList;
@Builder
@Getter
@NoArgsConstructor
@AllArgsConstructor
public static class UserStatistics {
private int totalUsers;
private int totalLocalUsers;
private int totalOidcUsers;
private boolean oidcEnabled;
}
@Builder
@Getter
@NoArgsConstructor
@AllArgsConstructor
public static class MetadataStatistics {
private String[] enabledMetadataProviders;
private String[] enabledReviewMetadataProviders;
private boolean saveMetadataToFile;
private boolean moveFileViaPattern;
private boolean autoBookSearchEnabled;
private boolean similarBookRecommendationsEnabled;
private boolean metadataDownloadOnBookdropEnabled;
}
@Builder
@Getter
@NoArgsConstructor
@AllArgsConstructor
public static class OpdsStatistics {
private boolean opdsEnabled;
private int totalOpdsUsers;
}
@Builder
@Getter
@NoArgsConstructor
@AllArgsConstructor
public static class KoboStatistics {
private int totalKoboUsers;
private int totalHardcoverSyncEnabled;
private int totalAutoAddToShelf;
private boolean convertToKepubEnabled;
}
@Builder
@Getter
@NoArgsConstructor
@AllArgsConstructor
public static class EmailStatistics {
private int totalEmailProviders;
private int totalEmailRecipients;
}
@Builder
@Getter
@NoArgsConstructor
@AllArgsConstructor
public static class BookStatistics {
private long totalBooks;
private Map<String, Long> bookCountByType;
}
@Builder
@Getter
@NoArgsConstructor
@AllArgsConstructor
public static class LibraryStatistics {
private long bookCount;
private int totalLibraryPaths;
private boolean watchEnabled;
private String iconType;
}
}
@@ -1,21 +0,0 @@
package org.booklore.model.dto;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.time.Instant;
@Builder
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class InstallationPing {
private int pingVersion;
private String appVersion;
private String installationId;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX", timezone = "UTC")
private Instant installationDate;
}
@@ -38,7 +38,6 @@ public enum AppSettingKey {
SIMILAR_BOOK_RECOMMENDATION ("similar_book_recommendation", false, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_GLOBAL_PREFERENCES)),
PDF_CACHE_SIZE_IN_MB ("pdf_cache_size_in_mb", false, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_GLOBAL_PREFERENCES)),
MAX_FILE_UPLOAD_SIZE_IN_MB ("max_file_upload_size_in_mb", false, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_GLOBAL_PREFERENCES)),
TELEMETRY_ENABLED ("telemetryEnabled", false, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_GLOBAL_PREFERENCES)),
// No specific permissions required
SIDEBAR_LIBRARY_SORTING ("sidebar_library_sorting", true, false, List.of()),
@@ -26,7 +26,6 @@ public class AppSettings {
private boolean remoteAuthEnabled;
private boolean metadataDownloadOnBookdrop;
private boolean oidcEnabled;
private boolean telemetryEnabled;
private OidcProviderDetails oidcProviderDetails;
private OidcAutoProvisionDetails oidcAutoProvisionDetails;
private MetadataProviderSettings metadataProviderSettings;
@@ -1,182 +0,0 @@
package org.booklore.service;
import org.booklore.model.dto.BookloreTelemetry;
import org.booklore.model.dto.Installation;
import org.booklore.model.dto.InstallationPing;
import org.booklore.model.dto.settings.AppSettings;
import org.booklore.model.dto.settings.MetadataProviderSettings;
import org.booklore.model.dto.settings.MetadataPublicReviewsSettings;
import org.booklore.model.dto.settings.UserSettingKey;
import org.booklore.model.entity.LibraryEntity;
import org.booklore.model.enums.BookFileType;
import org.booklore.model.enums.MetadataProvider;
import org.booklore.model.enums.ProvisioningMethod;
import org.booklore.repository.*;
import org.booklore.service.appsettings.AppSettingService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
@AllArgsConstructor
public class TelemetryService {
private final VersionService versionService;
private final LibraryRepository libraryRepository;
private final BookRepository bookRepository;
private final BookMarkRepository bookMarkRepository;
private final BookNoteRepository bookNoteRepository;
private final BookAdditionalFileRepository bookAdditionalFileRepository;
private final AuthorRepository authorRepository;
private final ShelfRepository shelfRepository;
private final MagicShelfRepository magicShelfRepository;
private final CategoryRepository categoryRepository;
private final TagRepository tagRepository;
private final MoodRepository moodRepository;
private final UserRepository userRepository;
private final EmailProviderV2Repository emailProviderV2Repository;
private final EmailRecipientV2Repository emailRecipientV2Repository;
private final AppSettingService appSettingService;
private final KoboUserSettingsRepository koboUserSettingsRepository;
private final UserSettingRepository userSettingRepository;
private final KoreaderUserRepository koreaderUserRepository;
private final OpdsUserV2Repository opdsUserV2Repository;
private final InstallationService installationService;
public InstallationPing getInstallationPing() {
Installation installation = installationService.getOrCreateInstallation();
return InstallationPing.builder()
.pingVersion(1)
.appVersion(versionService.appVersion)
.installationId(installation.getId())
.installationDate(installation.getDate())
.build();
}
public BookloreTelemetry collectTelemetry() {
long totalUsers = userRepository.count();
long localUsers = userRepository.countByProvisioningMethod(ProvisioningMethod.LOCAL);
long oidcUsers = userRepository.countByProvisioningMethod(ProvisioningMethod.OIDC);
AppSettings settings = appSettingService.getAppSettings();
BookloreTelemetry.BookStatistics bookStatistics = BookloreTelemetry.BookStatistics.builder()
.totalBooks(bookRepository.count())
.bookCountByType(getBookFileTypeCounts())
.build();
List<BookloreTelemetry.LibraryStatistics> libraryStatisticsList = libraryRepository.findAll().stream()
.map(this::mapLibraryStatistics)
.collect(Collectors.toList());
String[] enabledMetadataProviders = getEnabledMetadataProviders(settings.getMetadataProviderSettings());
String[] enabledReviewMetadataProviders = getEnabledReviewMetadataProviders(settings.getMetadataPublicReviewsSettings());
Installation installation = installationService.getOrCreateInstallation();
return BookloreTelemetry.builder()
.telemetryVersion(2)
.installationId(installation.getId())
.installationDate(installation.getDate() != null ? installation.getDate().toString() : null)
.appVersion(versionService.appVersion)
.totalLibraries((int) libraryRepository.count())
.totalBooks(bookRepository.count())
.totalAdditionalBookFiles(bookAdditionalFileRepository.count())
.totalAuthors(authorRepository.count())
.totalBookmarks(bookMarkRepository.count())
.totalBookNotes(bookNoteRepository.count())
.totalShelves((int) shelfRepository.count())
.totalMagicShelves((int) magicShelfRepository.count())
.totalCategories((int) categoryRepository.count())
.totalTags((int) tagRepository.count())
.totalMoods((int) moodRepository.count())
.totalKoreaderUsers((int) koreaderUserRepository.count())
.userStatistics(BookloreTelemetry.UserStatistics.builder()
.totalUsers((int) totalUsers)
.totalLocalUsers((int) localUsers)
.totalOidcUsers((int) oidcUsers)
.oidcEnabled(oidcUsers > 0)
.build())
.metadataStatistics(BookloreTelemetry.MetadataStatistics.builder()
.enabledMetadataProviders(enabledMetadataProviders)
.enabledReviewMetadataProviders(enabledReviewMetadataProviders)
.saveMetadataToFile(settings.getMetadataPersistenceSettings().getSaveToOriginalFile().isAnyFormatEnabled())
.moveFileViaPattern(settings.getMetadataPersistenceSettings().isMoveFilesToLibraryPattern())
.autoBookSearchEnabled(settings.isAutoBookSearch())
.similarBookRecommendationsEnabled(settings.isSimilarBookRecommendation())
.metadataDownloadOnBookdropEnabled(settings.isMetadataDownloadOnBookdrop())
.build())
.opdsStatistics(BookloreTelemetry.OpdsStatistics.builder()
.opdsEnabled(settings.isOpdsServerEnabled())
.totalOpdsUsers((int) opdsUserV2Repository.count())
.build())
.emailStatistics(BookloreTelemetry.EmailStatistics.builder()
.totalEmailProviders((int) emailProviderV2Repository.count())
.totalEmailRecipients((int) emailRecipientV2Repository.count())
.build())
.koboStatistics(BookloreTelemetry.KoboStatistics.builder()
.convertToKepubEnabled(settings.getKoboSettings().isConvertToKepub())
.totalKoboUsers((int) koboUserSettingsRepository.count())
.totalHardcoverSyncEnabled((int) userSettingRepository.countBySettingKeyAndSettingValue(
UserSettingKey.HARDCOVER_SYNC_ENABLED.getDbKey(), "true"))
.totalAutoAddToShelf((int) koboUserSettingsRepository.countByAutoAddToShelfTrue())
.build())
.bookStatistics(bookStatistics)
.libraryStatisticsList(libraryStatisticsList)
.build();
}
private Map<String, Long> getBookFileTypeCounts() {
Map<String, Long> countByType = new HashMap<>();
for (BookFileType type : BookFileType.values()) {
countByType.put(type.name(), bookRepository.countByBookType(type));
}
return countByType;
}
private BookloreTelemetry.LibraryStatistics mapLibraryStatistics(LibraryEntity lib) {
return BookloreTelemetry.LibraryStatistics.builder()
.totalLibraryPaths(lib.getLibraryPaths() != null ? lib.getLibraryPaths().size() : 0)
.bookCount(bookRepository.countByLibraryId(lib.getId()))
.watchEnabled(lib.isWatch())
.iconType(lib.getIconType() != null ? lib.getIconType().name() : null)
.build();
}
private String[] getEnabledMetadataProviders(MetadataProviderSettings providers) {
List<String> enabled = new ArrayList<>();
if (providers.getAmazon() != null && providers.getAmazon().isEnabled())
enabled.add(MetadataProvider.Amazon.name());
if (providers.getGoogle() != null && providers.getGoogle().isEnabled())
enabled.add(MetadataProvider.Google.name());
if (providers.getGoodReads() != null && providers.getGoodReads().isEnabled())
enabled.add(MetadataProvider.GoodReads.name());
if (providers.getHardcover() != null && providers.getHardcover().isEnabled())
enabled.add(MetadataProvider.Hardcover.name());
if (providers.getComicvine() != null && providers.getComicvine().isEnabled())
enabled.add(MetadataProvider.Comicvine.name());
if (providers.getRanobedb() != null && providers.getRanobedb().isEnabled())
enabled.add(MetadataProvider.Ranobedb.name());
if (providers.getDouban() != null && providers.getDouban().isEnabled())
enabled.add(MetadataProvider.Douban.name());
if (providers.getLubimyczytac() != null && providers.getLubimyczytac().isEnabled())
enabled.add(MetadataProvider.Lubimyczytac.name());
return enabled.toArray(new String[0]);
}
private String[] getEnabledReviewMetadataProviders(MetadataPublicReviewsSettings reviewSettings) {
List<String> enabled = new ArrayList<>();
if (reviewSettings.getProviders() != null) {
reviewSettings.getProviders().stream()
.filter(MetadataPublicReviewsSettings.ReviewProviderConfig::isEnabled)
.forEach(cfg -> enabled.add(cfg.getProvider().name()));
}
return enabled.toArray(new String[0]);
}
}
@@ -185,7 +185,6 @@ public class AppSettingService {
builder.opdsServerEnabled(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.OPDS_SERVER_ENABLED, "false")));
builder.komgaApiEnabled(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.KOMGA_API_ENABLED, "false")));
builder.komgaGroupUnknown(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.KOMGA_GROUP_UNKNOWN, "true")));
builder.telemetryEnabled(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.TELEMETRY_ENABLED, "true")));
builder.pdfCacheSizeInMb(Integer.parseInt(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.PDF_CACHE_SIZE_IN_MB, "5120")));
builder.maxFileUploadSizeInMb(Integer.parseInt(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.MAX_FILE_UPLOAD_SIZE_IN_MB, "100")));
builder.metadataDownloadOnBookdrop(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.METADATA_DOWNLOAD_ON_BOOKDROP, "true")));
@@ -19,8 +19,6 @@ app:
admin-group: ${REMOTE_AUTH_ADMIN_GROUP}
groups-delimiter: ${REMOTE_AUTH_GROUPS_DELIMITER:\\s+}
force-disable-oidc: ${FORCE_DISABLE_OIDC:false}
telemetry:
base-url: ${TELEMETRY_BASE_URL:https://telemetry.booklore.org}
disk-type: ${DISK_TYPE:LOCAL}
server:
@@ -1,389 +0,0 @@
package org.booklore.crons;
import org.booklore.config.AppProperties;
import org.booklore.model.dto.BookloreTelemetry;
import org.booklore.model.dto.InstallationPing;
import org.booklore.model.dto.settings.AppSettings;
import org.booklore.service.TelemetryService;
import org.booklore.service.appsettings.AppSettingService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.web.client.RestClient;
import java.time.Instant;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.*;
class CronServiceTest {
private AppProperties appProperties;
private TelemetryService telemetryService;
private RestClient restClient;
private AppSettingService appSettingService;
private CronService cronService;
@BeforeEach
void setUp() {
appProperties = mock(AppProperties.class, RETURNS_DEEP_STUBS);
telemetryService = mock(TelemetryService.class);
restClient = mock(RestClient.class, RETURNS_DEEP_STUBS);
appSettingService = mock(AppSettingService.class);
cronService = new CronService(appProperties, telemetryService, restClient, appSettingService);
AppSettings defaultSettings = mock(AppSettings.class);
when(appSettingService.getAppSettings()).thenReturn(defaultSettings);
when(defaultSettings.isTelemetryEnabled()).thenReturn(true);
InstallationPing defaultPing = InstallationPing.builder().appVersion("1.0.0").build();
when(telemetryService.getInstallationPing()).thenReturn(defaultPing);
}
@Test
void sendTelemetryData_telemetryDisabled_doesNotSend() {
AppSettings settings = mock(AppSettings.class);
when(appSettingService.getAppSettings()).thenReturn(settings);
when(settings.isTelemetryEnabled()).thenReturn(false);
cronService.sendTelemetryData();
verifyNoInteractions(telemetryService);
verify(appSettingService, never()).saveSetting(anyString(), anyString());
}
@Test
void sendTelemetryData_telemetryEnabled_postSuccess_savesSetting() {
AppSettings settings = mock(AppSettings.class);
when(appSettingService.getAppSettings()).thenReturn(settings);
when(settings.isTelemetryEnabled()).thenReturn(true);
when(appProperties.getTelemetry().getBaseUrl()).thenReturn("http://telemetry");
BookloreTelemetry telemetry = mock(BookloreTelemetry.class);
when(telemetryService.collectTelemetry()).thenReturn(telemetry);
RestClient.RequestBodyUriSpec post = mock(RestClient.RequestBodyUriSpec.class, RETURNS_DEEP_STUBS);
when(restClient.post()).thenReturn(post);
when(post.uri(anyString())).thenReturn(post);
when(post.body(any())).thenReturn(post);
when(post.retrieve().body(String.class)).thenReturn("ok");
cronService.sendTelemetryData();
verify(appSettingService).saveSetting(eq("last_telemetry_sent"), anyString());
}
@Test
void sendTelemetryData_telemetryEnabled_postFails_doesNotSaveSetting() {
AppSettings settings = mock(AppSettings.class);
when(appSettingService.getAppSettings()).thenReturn(settings);
when(settings.isTelemetryEnabled()).thenReturn(true);
when(appProperties.getTelemetry().getBaseUrl()).thenReturn("http://telemetry");
BookloreTelemetry telemetry = mock(BookloreTelemetry.class);
when(telemetryService.collectTelemetry()).thenReturn(telemetry);
CronService spy = spy(cronService);
doReturn(false).when(spy).postData(anyString(), any());
spy.sendTelemetryData();
verify(appSettingService, never()).saveSetting(eq("last_telemetry_sent"), anyString());
}
@Test
void sendPing_telemetryDisabled_doesNotSend() {
AppSettings settings = mock(AppSettings.class);
when(appSettingService.getAppSettings()).thenReturn(settings);
when(settings.isTelemetryEnabled()).thenReturn(false);
cronService.sendPing();
verifyNoInteractions(restClient);
}
@Test
void sendPing_telemetryEnabled_postSuccess_savesSettings() {
AppSettings settings = mock(AppSettings.class);
when(appSettingService.getAppSettings()).thenReturn(settings);
when(settings.isTelemetryEnabled()).thenReturn(true);
when(appProperties.getTelemetry().getBaseUrl()).thenReturn("http://telemetry");
InstallationPing ping = InstallationPing.builder().appVersion("1.0.0").build();
when(telemetryService.getInstallationPing()).thenReturn(ping);
RestClient.RequestBodyUriSpec post = mock(RestClient.RequestBodyUriSpec.class, RETURNS_DEEP_STUBS);
when(restClient.post()).thenReturn(post);
when(post.uri(anyString())).thenReturn(post);
when(post.body(any())).thenReturn(post);
when(post.retrieve().body(String.class)).thenReturn("ok");
cronService.sendPing();
verify(appSettingService).saveSetting(eq("last_ping_sent"), anyString());
verify(appSettingService).saveSetting(eq("last_ping_app_version"), eq("1.0.0"));
}
@Test
void sendPing_telemetryEnabled_postFails_doesNotSaveSettings() {
AppSettings settings = mock(AppSettings.class);
when(appSettingService.getAppSettings()).thenReturn(settings);
when(settings.isTelemetryEnabled()).thenReturn(true);
when(appProperties.getTelemetry().getBaseUrl()).thenReturn("http://telemetry");
InstallationPing ping = InstallationPing.builder().appVersion("1.0.0").build();
when(telemetryService.getInstallationPing()).thenReturn(ping);
CronService spy = spy(cronService);
doReturn(false).when(spy).postData(anyString(), any());
spy.sendPing();
verify(appSettingService, never()).saveSetting(eq("last_ping_sent"), anyString());
verify(appSettingService, never()).saveSetting(eq("last_ping_app_version"), anyString());
}
@Test
void shouldRunTask_nullOrEmpty_returnsFalse() {
assertFalse(cronServiceShouldRunTask(null));
assertFalse(cronServiceShouldRunTask(""));
}
@Test
void shouldRunTask_invalidTimestamp_returnsFalse() {
assertFalse(cronServiceShouldRunTask("not-a-timestamp"));
}
@Test
void shouldRunTask_recentTimestamp_returnsFalse() {
String now = Instant.now().toString();
assertFalse(cronServiceShouldRunTask(now));
}
@Test
void shouldRunTask_oldTimestamp_returnsTrue() {
String old = Instant.now().minusSeconds(60 * 60 * 25).toString();
assertTrue(cronServiceShouldRunTask(old));
}
boolean cronServiceShouldRunTask(String lastRunStr) {
return invokeShouldRunTask(cronService, lastRunStr);
}
boolean invokeShouldRunTask(CronService cronService, String lastRunStr) {
try {
var m = CronService.class.getDeclaredMethod("shouldRunTask", String.class);
m.setAccessible(true);
return (boolean) m.invoke(cronService, lastRunStr);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Test
void hasAppVersionChanged_noLastPing_returnsFalse() {
when(appSettingService.getSettingValue("last_ping_app_version")).thenReturn(null);
InstallationPing ping = InstallationPing.builder().appVersion("1.0.0").build();
when(telemetryService.getInstallationPing()).thenReturn(ping);
assertFalse(invokeHasAppVersionChanged(cronService));
}
@Test
void hasAppVersionChanged_lastPingEmpty_returnsFalse() {
when(appSettingService.getSettingValue("last_ping_app_version")).thenReturn("");
InstallationPing ping = InstallationPing.builder().appVersion("1.0.0").build();
when(telemetryService.getInstallationPing()).thenReturn(ping);
assertFalse(invokeHasAppVersionChanged(cronService));
}
@Test
void hasAppVersionChanged_sameVersion_returnsFalse() {
when(appSettingService.getSettingValue("last_ping_app_version")).thenReturn("1.0.0");
InstallationPing ping = InstallationPing.builder().appVersion("1.0.0").build();
when(telemetryService.getInstallationPing()).thenReturn(ping);
assertFalse(invokeHasAppVersionChanged(cronService));
}
@Test
void hasAppVersionChanged_differentVersion_returnsTrue() {
when(appSettingService.getSettingValue("last_ping_app_version")).thenReturn("1.0.0");
InstallationPing ping = InstallationPing.builder().appVersion("2.0.0").build();
when(telemetryService.getInstallationPing()).thenReturn(ping);
assertTrue(invokeHasAppVersionChanged(cronService));
}
@Test
void hasAppVersionChanged_nullPing_returnsFalse() {
when(appSettingService.getSettingValue("last_ping_app_version")).thenReturn("1.0.0");
when(telemetryService.getInstallationPing()).thenReturn(null);
assertFalse(invokeHasAppVersionChanged(cronService));
}
boolean invokeHasAppVersionChanged(CronService cronService) {
try {
var m = CronService.class.getDeclaredMethod("hasAppVersionChanged");
m.setAccessible(true);
return (boolean) m.invoke(cronService);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Test
void checkAndRunTelemetry_telemetryDisabled_doesNothing() {
AppSettings settings = mock(AppSettings.class);
when(appSettingService.getAppSettings()).thenReturn(settings);
when(settings.isTelemetryEnabled()).thenReturn(false);
cronService.initScheduledTasks();
verify(appSettingService, never()).getSettingValue("last_telemetry_sent");
}
@Test
void checkAndRunTelemetry_shouldRunTaskTrue_callsSendTelemetryData() {
AppSettings settings = mock(AppSettings.class);
when(appSettingService.getAppSettings()).thenReturn(settings);
when(settings.isTelemetryEnabled()).thenReturn(true);
when(appSettingService.getSettingValue("last_telemetry_sent")).thenReturn(Instant.now().minusSeconds(60 * 60 * 25).toString());
CronService spy = spy(cronService);
doNothing().when(spy).sendTelemetryData();
// Ensure getInstallationPing returns non-null for ping checks
InstallationPing ping = InstallationPing.builder().appVersion("1.0.0").build();
when(telemetryService.getInstallationPing()).thenReturn(ping);
spy.initScheduledTasks();
verify(spy).sendTelemetryData();
}
@Test
void checkAndRunPing_appVersionChanged_callsSendPing() {
when(appSettingService.getSettingValue("last_ping_app_version")).thenReturn("1.0.0");
InstallationPing ping = InstallationPing.builder().appVersion("2.0.0").build();
when(telemetryService.getInstallationPing()).thenReturn(ping);
CronService spy = spy(cronService);
doNothing().when(spy).sendPing();
spy.initScheduledTasks();
verify(spy).sendPing();
}
@Test
void checkAndRunPing_shouldRunTaskTrue_callsSendPing() {
when(appSettingService.getSettingValue("last_ping_app_version")).thenReturn("1.0.0");
InstallationPing ping = InstallationPing.builder().appVersion("1.0.0").build();
when(telemetryService.getInstallationPing()).thenReturn(ping);
when(appSettingService.getSettingValue("last_ping_sent")).thenReturn(Instant.now().minusSeconds(60 * 60 * 25).toString());
CronService spy = spy(cronService);
doNothing().when(spy).sendPing();
spy.initScheduledTasks();
verify(spy).sendPing();
}
@Test
void checkAndRunPing_shouldRunTaskFalse_doesNotCallSendPing() {
when(appSettingService.getSettingValue("last_ping_app_version")).thenReturn("1.0.0");
InstallationPing ping = InstallationPing.builder().appVersion("1.0.0").build();
when(telemetryService.getInstallationPing()).thenReturn(ping);
when(appSettingService.getSettingValue("last_ping_sent")).thenReturn(Instant.now().toString());
CronService spy = spy(cronService);
doNothing().when(spy).sendPing();
spy.initScheduledTasks();
verify(spy, never()).sendPing();
}
@Test
void sendTelemetryData_nullSettings_doesNotThrowOrSend() {
when(appSettingService.getAppSettings()).thenReturn(null);
cronService.sendTelemetryData();
verifyNoInteractions(telemetryService);
verify(appSettingService, never()).saveSetting(anyString(), anyString());
}
@Test
void sendTelemetryData_telemetryEnabled_collectTelemetryReturnsNull_doesNotThrow() {
AppSettings settings = mock(AppSettings.class);
when(appSettingService.getAppSettings()).thenReturn(settings);
when(settings.isTelemetryEnabled()).thenReturn(true);
when(appProperties.getTelemetry().getBaseUrl()).thenReturn("http://telemetry");
when(telemetryService.collectTelemetry()).thenReturn(null);
CronService spy = spy(cronService);
doReturn(false).when(spy).postData(anyString(), any());
spy.sendTelemetryData();
verify(appSettingService, never()).saveSetting(eq("last_telemetry_sent"), anyString());
}
@Test
void sendPing_nullPing_doesNotSave() {
when(telemetryService.getInstallationPing()).thenReturn(null);
cronService.sendPing();
verify(appSettingService, never()).saveSetting(anyString(), anyString());
}
@Test
void shouldRunTask_farFutureTimestamp_returnsFalse() {
String future = Instant.now().plusSeconds(60 * 60 * 25).toString();
assertFalse(cronServiceShouldRunTask(future));
}
@Test
void shouldRunTask_epoch_returnsTrue() {
String epoch = Instant.EPOCH.toString();
assertTrue(cronServiceShouldRunTask(epoch));
}
@Test
void hasAppVersionChanged_lastPingNullCurrentNull_returnsFalse() {
when(appSettingService.getSettingValue("last_ping_app_version")).thenReturn(null);
when(telemetryService.getInstallationPing()).thenReturn(null);
assertFalse(invokeHasAppVersionChanged(cronService));
}
@Test
void hasAppVersionChanged_lastPingEmptyCurrentNull_returnsFalse() {
when(appSettingService.getSettingValue("last_ping_app_version")).thenReturn("");
when(telemetryService.getInstallationPing()).thenReturn(null);
assertFalse(invokeHasAppVersionChanged(cronService));
}
@Test
void hasAppVersionChanged_lastPingNonEmptyCurrentNull_returnsFalse() {
when(appSettingService.getSettingValue("last_ping_app_version")).thenReturn("1.0.0");
when(telemetryService.getInstallationPing()).thenReturn(null);
assertFalse(invokeHasAppVersionChanged(cronService));
}
@Test
void checkAndRunTelemetry_nullSettings_doesNothing() {
when(appSettingService.getAppSettings()).thenReturn(null);
cronService.initScheduledTasks();
verify(appSettingService, never()).getSettingValue("last_telemetry_sent");
}
@Test
void checkAndRunTelemetry_shouldRunTaskFalse_doesNotCallSendTelemetryData() {
AppSettings settings = mock(AppSettings.class);
when(appSettingService.getAppSettings()).thenReturn(settings);
when(settings.isTelemetryEnabled()).thenReturn(true);
when(appSettingService.getSettingValue("last_telemetry_sent")).thenReturn(Instant.now().toString());
CronService spy = spy(cronService);
doNothing().when(spy).sendTelemetryData();
spy.initScheduledTasks();
verify(spy, never()).sendTelemetryData();
}
@Test
void checkAndRunPing_nullLastPingVersion_doesNotCallSendPing() {
when(appSettingService.getSettingValue("last_ping_app_version")).thenReturn(null);
InstallationPing ping = InstallationPing.builder().appVersion("1.0.0").build();
when(telemetryService.getInstallationPing()).thenReturn(ping);
CronService spy = spy(cronService);
doNothing().when(spy).sendPing();
spy.initScheduledTasks();
verify(spy, never()).sendPing();
}
@Test
void checkAndRunPing_nullPing_doesNotCallSendPing() {
when(appSettingService.getSettingValue("last_ping_app_version")).thenReturn("1.0.0");
when(telemetryService.getInstallationPing()).thenReturn(null);
CronService spy = spy(cronService);
doNothing().when(spy).sendPing();
spy.initScheduledTasks();
verify(spy, never()).sendPing();
}
@Test
void checkAndRunPing_shouldRunTaskFalseAndNoVersionChange_doesNotCallSendPing() {
when(appSettingService.getSettingValue("last_ping_app_version")).thenReturn("1.0.0");
InstallationPing ping = InstallationPing.builder().appVersion("1.0.0").build();
when(telemetryService.getInstallationPing()).thenReturn(ping);
when(appSettingService.getSettingValue("last_ping_sent")).thenReturn(Instant.now().toString());
CronService spy = spy(cronService);
doNothing().when(spy).sendPing();
spy.initScheduledTasks();
verify(spy, never()).sendPing();
}
}