#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
perf(analytics): start the PostHog client lazily and cut its queue thread wakeups (#8562)
brios032d27bf2d67
diff --git a/app/common/src/main/java/stirling/software/common/configuration/PostHogClientFactory.java b/app/common/src/main/java/stirling/software/common/configuration/PostHogClientFactory.javanew file mode 100644index 0000000000..d0f4c927d8--- /dev/null+++ b/app/common/src/main/java/stirling/software/common/configuration/PostHogClientFactory.java@@ -0,0 +1,14 @@+package stirling.software.common.configuration;++import com.posthog.java.PostHog;++/**+ * Creates PostHog clients on demand. Every created client starts and owns a "PostHog QueueManager+ * thread", so callers must {@link PostHog#shutdown() shutdown} the client they create when it is no+ * longer needed.+ */+@FunctionalInterface+public interface PostHogClientFactory {++ PostHog create();+}diff --git a/app/common/src/main/java/stirling/software/common/configuration/PostHogConfig.java b/app/common/src/main/java/stirling/software/common/configuration/PostHogConfig.javaindex 589b5cac9f..6bff16def0 100644--- a/app/common/src/main/java/stirling/software/common/configuration/PostHogConfig.java+++ b/app/common/src/main/java/stirling/software/common/configuration/PostHogConfig.java@@ -4,38 +4,35 @@ import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;+import com.posthog.java.HttpSender;import com.posthog.java.PostHog;--import jakarta.annotation.PreDestroy;--import lombok.extern.slf4j.Slf4j;+import com.posthog.java.QueueManager;+import com.posthog.java.Sender;@Configuration-@Slf4jpublic class PostHogConfig {- @Value("${posthog.api.key}")- private String posthogApiKey;-- @Value("${posthog.host}")- private String posthogHost;-- private PostHog postHogClient;-+ /**+ * The SDK's queue manager polls its queue every 100 ms by default. Telemetry tolerates seconds+ * of latency, so poll ten times less often and cut the thread's wakeups accordingly.+ */+ private static final int QUEUE_POLL_INTERVAL_MS = 1_000;++ /**+ * Building the sender and queue manager directly (instead of the plain {@code PostHog.Builder})+ * is what allows the poll interval override; the sender keeps the same configuration the plain+ * builder would produce.+ */@Bean- public PostHog postHogClient() {- postHogClient =- new PostHog.Builder(posthogApiKey)- .host(posthogHost)- .logger(new PostHogLoggerImpl())- .build();- return postHogClient;- }-- @PreDestroy- public void shutdownPostHog() {- if (postHogClient != null) {- postHogClient.shutdown();- }+ public PostHogClientFactory postHogClientFactory(+ @Value("${posthog.api.key}") String apiKey,+ @Value("${posthog.host}") String host,+ PostHogLoggerImpl postHogLogger) {+ return () -> {+ Sender sender = new HttpSender.Builder(apiKey).host(host).logger(postHogLogger).build();+ QueueManager queueManager =+ new QueueManager.Builder(sender).sleepMs(QUEUE_POLL_INTERVAL_MS).build();+ return new PostHog.BuilderWithCustomQueueManager(queueManager, sender).build();+ };}}diff --git a/app/common/src/main/java/stirling/software/common/service/PostHogService.java b/app/common/src/main/java/stirling/software/common/service/PostHogService.javaindex f6a339ab9a..fc80ae370a 100644--- a/app/common/src/main/java/stirling/software/common/service/PostHogService.java+++ b/app/common/src/main/java/stirling/software/common/service/PostHogService.java@@ -22,27 +22,38 @@ import org.springframework.stereotype.Service;import com.posthog.java.PostHog;+import jakarta.annotation.PreDestroy;++import lombok.extern.slf4j.Slf4j;++import stirling.software.common.configuration.PostHogClientFactory;import stirling.software.common.model.ApplicationProperties;@Service+@Slf4jpublic class PostHogService {- private final PostHog postHog;+ private final PostHogClientFactory postHogClientFactory;+ private final Object postHogClientLock = new Object();private final String uniqueId;private final String appVersion;private final ApplicationProperties applicationProperties;private final UserServiceInterface userService;private final Environment env;private boolean configDirMounted;+ // Under postHogClientLock. shutdown() is final: a late capture must not resurrect the queue+ // thread, while a runtime telemetry disable stays recoverable by design.+ private boolean closed;+ private volatile PostHog postHog;public PostHogService(- PostHog postHog,+ PostHogClientFactory postHogClientFactory,@Qualifier("UUID") String uuid,@Qualifier("configDirMounted") boolean configDirMounted,@Qualifier("appVersion") String appVersion,ApplicationProperties applicationProperties,@Autowired(required = false) UserServiceInterface userService,Environment env) {- this.postHog = postHog;+ this.postHogClientFactory = postHogClientFactory;this.uniqueId = uuid;this.appVersion = appVersion;this.applicationProperties = applicationProperties;@@ -52,24 +63,82 @@ public class PostHogService {captureSystemInfo();}- private void captureSystemInfo() {- if (!applicationProperties.getSystem().isPosthogEnabled()) {- return;+ /**+ * Creates the client on first use so that its QueueManager thread only exists while telemetry+ * is enabled. The constructor's system-info capture creates it during startup when telemetry is+ * on, so an enabled install still reports its startup snapshot as the first event.+ */+ private PostHog client() {+ PostHog client = postHog;+ if (client == null) {+ synchronized (postHogClientLock) {+ client = postHog;+ if (client == null) {+ if (closed) {+ throw new IllegalStateException("PostHogService is shut down");+ }+ client = postHogClientFactory.create();+ postHog = client;+ }+ }}+ return client;+ }++ private boolean telemetryEnabled() {+ return applicationProperties.getSystem().isPosthogEnabled();+ }++ /** Telemetry is best-effort: failures must never reach PDF-processing callers. */+ private void captureQuietly(String eventName, Map<String, Object> properties) {try {- postHog.capture(uniqueId, "system_info_captured", captureServerMetrics());+ client().capture(uniqueId, eventName, properties);} catch (Exception e) {- // Handle exceptions+ log.debug("PostHog capture of {} failed", eventName, e);+ }+ }++ private void shutdownClientIfDisabled() {+ PostHog client;+ synchronized (postHogClientLock) {+ if (postHog == null || telemetryEnabled()) {+ return;+ }+ client = postHog;+ postHog = null;+ }+ // shutdown() joins the queue thread, so run it outside the lock.+ client.shutdown();+ }++ @PreDestroy+ public void shutdown() {+ PostHog client;+ synchronized (postHogClientLock) {+ closed = true;+ client = postHog;+ postHog = null;+ }+ if (client != null) {+ client.shutdown();+ }+ }++ private void captureSystemInfo() {+ if (!telemetryEnabled()) {+ return;}+ captureQuietly("system_info_captured", captureServerMetrics());}public void captureEvent(String eventName, Map<String, Object> properties) {- if (!applicationProperties.getSystem().isPosthogEnabled()) {+ if (!telemetryEnabled()) {+ shutdownClientIfDisabled();return;}properties.put("app_version", appVersion);- postHog.capture(uniqueId, eventName, properties);+ captureQuietly(eventName, properties);}public Map<String, Object> captureServerMetrics() {diff --git a/app/common/src/test/java/stirling/software/common/service/PostHogServiceTest.java b/app/common/src/test/java/stirling/software/common/service/PostHogServiceTest.javaindex 025ef71a6e..0257798e42 100644--- a/app/common/src/test/java/stirling/software/common/service/PostHogServiceTest.java+++ b/app/common/src/test/java/stirling/software/common/service/PostHogServiceTest.java@@ -20,6 +20,7 @@ import org.springframework.mock.env.MockEnvironment;import com.posthog.java.PostHog;+import stirling.software.common.configuration.PostHogClientFactory;import stirling.software.common.model.ApplicationProperties;@ExtendWith(MockitoExtension.class)@@ -30,6 +31,7 @@ class PostHogServiceTest {private static final String APP_VERSION = "9.9.9";@Mock PostHog postHog;+ @Mock PostHogClientFactory postHogClientFactory;@Mock UserServiceInterface userService;/** Build an ApplicationProperties with analytics/posthog toggled. */@@ -39,14 +41,24 @@ class PostHogServiceTest {return appProps;}- /** Construct the service under test. */+ /** Construct the service under test with the factory wired to the shared client mock. */private PostHogService newService(ApplicationProperties appProps,UserServiceInterface user,boolean configDirMounted,MockEnvironment env) {+ when(postHogClientFactory.create()).thenReturn(postHog);+ return newDirectService(appProps, user, configDirMounted, env);+ }++ /** Construct without stubbing the factory so tests control what each create() returns. */+ private PostHogService newDirectService(+ ApplicationProperties appProps,+ UserServiceInterface user,+ boolean configDirMounted,+ MockEnvironment env) {return new PostHogService(- postHog, UUID, configDirMounted, APP_VERSION, appProps, user, env);+ postHogClientFactory, UUID, configDirMounted, APP_VERSION, appProps, user, env);}private MockEnvironment env() {@@ -438,4 +450,116 @@ class PostHogServiceTest {assertTrue(p.containsKey("security_csrfDisabled"));}}++ @Nested+ @DisplayName("Lazy client lifecycle")+ class LazyClientLifecycle {++ @Test+ @DisplayName("client is not created when telemetry is disabled")+ void noClientWhenDisabled() {+ PostHogService service = newService(props(false), userService, false, env());++ verify(postHogClientFactory, never()).create();++ service.captureEvent("evt", new HashMap<>());++ verify(postHogClientFactory, never()).create();+ verify(postHog, never()).capture(anyString(), anyString(), anyMap());+ }++ @Test+ @DisplayName("client is created once and reused when telemetry is enabled")+ void clientReusedWhenEnabled() {+ PostHogService service = newService(props(true), userService, false, env());+ clearInvocations(postHog);++ service.captureEvent("one", new HashMap<>());+ service.captureEvent("two", new HashMap<>());++ verify(postHogClientFactory, times(1)).create();+ verify(postHog).capture(eq(UUID), eq("one"), anyMap());+ verify(postHog).capture(eq(UUID), eq("two"), anyMap());+ }++ @Test+ @DisplayName("client is created lazily when telemetry is enabled after construction")+ void clientCreatedAfterRuntimeEnable() {+ ApplicationProperties appProps = props(false);+ PostHogService service = newService(appProps, userService, false, env());+ verify(postHogClientFactory, never()).create();++ appProps.getSystem().setEnableAnalytics(true);+ service.captureEvent("evt", new HashMap<>());++ verify(postHogClientFactory).create();+ verify(postHog).capture(eq(UUID), eq("evt"), anyMap());+ }++ @Test+ @DisplayName("client is shut down when telemetry is disabled at runtime")+ void clientShutdownWhenDisabled() {+ ApplicationProperties appProps = props(true);+ PostHogService service = newService(appProps, userService, false, env());+ clearInvocations(postHog);++ appProps.getSystem().setEnablePosthog(false);+ service.captureEvent("evt", new HashMap<>());++ verify(postHog).shutdown();+ verify(postHog, never()).capture(anyString(), anyString(), anyMap());+ }++ @Test+ @DisplayName("a fresh client is created if telemetry is re-enabled after a shutdown")+ void clientRecreatedAfterReenable() {+ PostHog secondClient = mock(PostHog.class);+ when(postHogClientFactory.create()).thenReturn(postHog, secondClient);+ ApplicationProperties appProps = props(true);+ PostHogService service = newDirectService(appProps, userService, false, env());++ appProps.getSystem().setEnablePosthog(false);+ service.captureEvent("off", new HashMap<>());+ appProps.getSystem().setEnablePosthog(true);+ service.captureEvent("on", new HashMap<>());++ verify(postHogClientFactory, times(2)).create();+ verify(postHog).shutdown();+ verify(secondClient).capture(eq(UUID), eq("on"), anyMap());+ }++ @Test+ @DisplayName("shutdown() closes a created client and tolerates never creating one")+ void shutdownLifecycle() {+ PostHogService enabled = newService(props(true), userService, false, env());+ enabled.shutdown();+ verify(postHog).shutdown();++ PostHogService disabled = newService(props(false), userService, false, env());+ assertDoesNotThrow(disabled::shutdown);+ }++ @Test+ @DisplayName("client creation failures are swallowed")+ void creationFailureSwallowed() {+ when(postHogClientFactory.create()).thenThrow(new IllegalStateException("no client"));+ PostHogService service = newDirectService(props(true), userService, false, env());++ assertDoesNotThrow(() -> service.captureEvent("evt", new HashMap<>()));+ verify(postHog, never()).capture(anyString(), anyString(), anyMap());+ }++ @Test+ @DisplayName("shutdown() is final: a later capture does not recreate the client")+ void noClientAfterShutdown() {+ PostHogService service = newService(props(true), userService, false, env());+ service.shutdown();+ clearInvocations(postHogClientFactory, postHog);++ assertDoesNotThrow(() -> service.captureEvent("late", new HashMap<>()));++ verify(postHogClientFactory, never()).create();+ verify(postHog, never()).capture(anyString(), anyString(), anyMap());+ }+ }}