### SparkProvider Singleton Source: https://github.com/lucko/spark/blob/master/_autodocs/BUILD-SUMMARY.txt Documentation for the SparkProvider singleton, including its get() method and initialization details. ```APIDOC ## SparkProvider Singleton ### Description Provides access to the Spark API functionality through a singleton instance. ### Method - **get**(): SparkProvider - Returns the singleton instance of SparkProvider. ### Initialization Details on how to initialize the SparkProvider. ### Request Example ```java SparkProvider provider = SparkProvider.get(); ``` ### Response #### Success Response (200) - **SparkProvider** (SparkProvider) - The singleton instance. #### Response Example ```java // provider instance obtained ``` ``` -------------------------------- ### Example: Display MSPT Distribution Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/double-average-info.md Demonstrates how to poll 10-second window data for MillisPerTick (MSPT) and print various statistical measures including min, max, mean, and several percentiles. ```java Spark spark = SparkProvider.get(); GenericStatistic mspt = spark.mspt(); if (mspt != null) { DoubleAverageInfo info = mspt.poll(MillisPerTick.SECONDS_10); System.out.println("MSPT Distribution (10-second window):"); System.out.println(" Min (0%): " + info.min()); System.out.println(" 25th%ile: " + info.percentile(0.25)); System.out.println(" 50th%ile (median): " + info.percentile(0.50)); System.out.println(" 75th%ile: " + info.percentile(0.75)); System.out.println(" 95th%ile: " + info.percentile95th()); System.out.println(" 99th%ile: " + info.percentile(0.99)); System.out.println(" Max (100%): " + info.max()); } ``` -------------------------------- ### min() Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/double-average-info.md Gets the minimum (best case) value in the recorded dataset. ```APIDOC ## min() ### Description Gets the minimum (best case) value in the recorded dataset. ### Method Java Method ### Parameters (none) ### Response #### Success Response - **return value** (`double`) - The minimum value ### Example ```java Spark spark = SparkProvider.get(); GenericStatistic mspt = spark.mspt(); if (mspt != null) { DoubleAverageInfo info = mspt.poll(MillisPerTick.SECONDS_10); double minMspt = info.min(); System.out.println("Best tick: " + minMspt + " ms"); } ``` ``` -------------------------------- ### Spark API Reference - spark.md Source: https://github.com/lucko/spark/blob/master/_autodocs/BUILD-SUMMARY.txt Documentation for the main Spark interface, including method signatures, parameters, return values, and examples. ```APIDOC ## Spark Interface ### Description This section documents the main Spark interface, detailing its available methods for performance profiling. ### Methods - **method1**(param1: type1, param2: type2): returnType - Description of method1 - **method2**(param1: type1): returnType - Description of method2 - **method3**(): returnType - Description of method3 - **method4**(param1: type1): returnType - Description of method4 - **method5**(param1: type1, param2: type2): returnType - Description of method5 - **method6**(param1: type1): returnType - Description of method6 ### Request Example ```json { "example": "request body for spark methods" } ``` ### Response #### Success Response (200) - **field1** (type) - Description of field1 - **field2** (type) - Description of field2 #### Response Example ```json { "example": "response body for spark methods" } ``` ``` -------------------------------- ### DoubleStatistic Example Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/statistic.md Demonstrates polling a value from a DoubleStatistic for a specific time window. Suitable for metrics like CPU usage. ```java DoubleStatistic cpuUsage = spark.cpuProcess(); double value = cpuUsage.poll(CpuUsage.SECONDS_10); ``` -------------------------------- ### name() Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/garbage-collector.md Gets the name of the garbage collector. ```APIDOC ## name() ### Description Gets the name of the garbage collector. ### Method ```java @NonNull String name() ``` ### Parameters (none) ### Return Type `String` - Non-null name of the garbage collector (e.g., "G1 Young Generation", "G1 Old Generation") ### Example ```java Spark spark = SparkProvider.get(); Map gcStats = spark.gc(); for (GarbageCollector gc : gcStats.values()) { System.out.println("Garbage Collector: " + gc.name()); } ``` ``` -------------------------------- ### totalTime() Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/garbage-collector.md Gets the total cumulative time spent performing garbage collection since the JVM started. Time is measured in milliseconds. ```APIDOC ## totalTime() ### Description Gets the total cumulative time spent performing garbage collection since the JVM started. Time is measured in milliseconds. ### Method ```java long totalTime() ``` ### Parameters (none) ### Return Type `long` - Total milliseconds spent in garbage collection ### Example ```java Spark spark = SparkProvider.get(); Map gcStats = spark.gc(); long totalGCTimeMs = 0; for (GarbageCollector gc : gcStats.values()) { totalGCTimeMs += gc.totalTime(); System.out.println(gc.name() + ": " + gc.totalTime() + " ms"); } System.out.println("Total GC time across all collectors: " + totalGCTimeMs + " ms"); ``` ``` -------------------------------- ### GenericStatistic Example Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/statistic.md Demonstrates polling complex information from a GenericStatistic for a specific time window. Suitable for metrics like MSPT which include average, min, max, and percentiles. ```java GenericStatistic mspt = spark.mspt(); DoubleAverageInfo info = mspt.poll(MillisPerTick.SECONDS_10); ``` -------------------------------- ### Build JSON Components for Formatted Messages Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/placeholder-resolver.md This example shows how to resolve placeholders into JSON components, which can be used for advanced formatting in modern Minecraft clients. The actual sending mechanism depends on the server software. ```java public void sendFormattedMessage(Player player) { Spark spark = SparkProvider.get(); PlaceholderResolver resolver = spark.placeholders(); String tpsComponent = resolver.resolveComponentJson("%spark_tps%"); String cpuComponent = resolver.resolveComponentJson("%spark_cpu_process%"); if (tpsComponent != null && cpuComponent != null) { // Components can be sent to modern Minecraft clients for advanced formatting // (Implementation depends on your server software) player.sendMessage("Server metrics - TPS: " + tpsComponent + " CPU: " + cpuComponent); } } ``` -------------------------------- ### Get Spark Instance (Singleton Pattern) Source: https://github.com/lucko/spark/blob/master/_autodocs/module-structure.md Access the global Spark instance. Throws an exception if Spark has not loaded yet. Ensure Spark is initialized before calling this method. ```java public static Spark get() { if (instance == null) { throw new IllegalStateException("spark has not loaded yet!"); } return instance; } ``` -------------------------------- ### Accessing the Spark Instance Source: https://github.com/lucko/spark/blob/master/_autodocs/usage-guide.md Get the Spark API instance using SparkProvider.get(). This is the primary entry point for interacting with the API. ```java import me.lucko.spark.api.SparkProvider; import me.lucko.spark.api.Spark; Spark spark = SparkProvider.get(); ``` -------------------------------- ### avgTime() Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/garbage-collector.md Gets the average duration of each garbage collection cycle. Time is measured in milliseconds. ```APIDOC ## avgTime() ### Description Gets the average duration of each garbage collection cycle. Time is measured in milliseconds. ### Calculation `totalTime() / totalCollections()` ### Method ```java double avgTime() ``` ### Parameters (none) ### Return Type `double` - Average milliseconds per collection (0.0 if no collections have occurred) ### Example ```java Spark spark = SparkProvider.get(); Map gcStats = spark.gc(); for (GarbageCollector gc : gcStats.values()) { if (gc.totalCollections() > 0) { System.out.println(gc.name() + " average duration: " + gc.avgTime() + " ms"); if (gc.avgTime() > 100.0) { System.out.println(" ⚠️ Long GC pauses detected!"); } } } ``` ``` -------------------------------- ### Complete Server Health Check Example Source: https://github.com/lucko/spark/blob/master/_autodocs/configuration.md This Java class demonstrates how to retrieve and print various server metrics like CPU usage, TPS, MSPT, and garbage collection statistics using the Spark API. ```java public class ServerHealthCheck { private final Spark spark; public ServerHealthCheck() { try { this.spark = SparkProvider.get(); } catch (IllegalStateException e) { throw new RuntimeException("spark not available", e); } } public void printHealthReport() { System.out.println("=== Server Health Report ==="); // CPU metrics (always available) DoubleStatistic cpu = spark.cpuProcess(); System.out.println("Process CPU (1m avg): " + cpu.poll(CpuUsage.MINUTES_1) + "%"); // TPS metrics (server only) DoubleStatistic tps = spark.tps(); if (tps != null) { System.out.println("Server TPS (1m avg): " + tps.poll(TicksPerSecond.MINUTES_1)); } // MSPT metrics (server only) GenericStatistic mspt = spark.mspt(); if (mspt != null) { DoubleAverageInfo info = mspt.poll(MillisPerTick.MINUTES_1); System.out.println("MSPT (1m avg): " + info.mean() + " ms (95th: " + info.percentile95th() + "ms)"); } // GC metrics Map gcStats = spark.gc(); for (GarbageCollector gc : gcStats.values()) { if (gc.totalCollections() > 0) { System.out.println(gc.name() + ": " + gc.avgTime() + "ms avg per collection"); } } } } ``` -------------------------------- ### Handle Platform Differences in Metrics Source: https://github.com/lucko/spark/blob/master/_autodocs/configuration.md This example demonstrates how to conditionally display metrics like TPS, which are not available on all platforms. It first retrieves the CPU usage (always available) and then checks for TPS availability before appending it to the output string. ```java public String getServerHealth() { Spark spark = SparkProvider.get(); StringBuilder sb = new StringBuilder(); // CPU always available double cpu = spark.cpuProcess().poll(CpuUsage.SECONDS_10); sb.append("CPU: ").append(cpu).append("%"); // TPS only on servers DoubleStatistic tps = spark.tps(); if (tps != null) { sb.append(" | TPS: ").append(tps.poll(TicksPerSecond.MINUTES_1)); } return sb.toString(); } ``` -------------------------------- ### getWindows() Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/statistic.md Gets the array of all time windows for which rolling averages are tracked. The array elements correspond to the window enum constants. ```APIDOC ## getWindows() ### Description Gets the array of all time windows for which rolling averages are tracked. The array elements correspond to the window enum constants. ### Method ```java @NonNull W[] getWindows() ``` ### Return Type `W[]` - Non-null array of window enum constants ### Example ```java Spark spark = SparkProvider.get(); DoubleStatistic cpuStat = spark.cpuProcess(); CpuUsage[] windows = cpuStat.getWindows(); for (CpuUsage window : windows) { System.out.println("Window: " + window); System.out.println(" Duration: " + window.length()); double value = cpuStat.poll(window); System.out.println(" Value: " + value); } ``` ``` -------------------------------- ### Get Server Millis Per Tick (MSPT) Source: https://github.com/lucko/spark/blob/master/_autodocs/quick-reference.md Retrieve the server's Millis Per Tick (MSPT) statistics, which indicates server performance. This is only available on servers. Check for null before polling. ```java GenericStatistic mspt = spark.mspt(); if (mspt != null) { DoubleAverageInfo info = mspt.poll(MillisPerTick.SECONDS_10); double mean = info.mean(); double min = info.min(); double max = info.max(); double p50 = info.median(); double p95 = info.percentile95th(); double p99 = info.percentile(0.99); } ``` -------------------------------- ### Accessing DoubleAverageInfo Statistics Source: https://github.com/lucko/spark/blob/master/_autodocs/types.md Example of how to retrieve and print statistical information (mean and 95th percentile) for MSPT using a specific time window. ```java DoubleAverageInfo info = mspt.poll(MillisPerTick.SECONDS_10); System.out.println("Mean: " + info.mean()); System.out.println("95th%ile: " + info.percentile95th()); ``` -------------------------------- ### Get Server Ticks Per Second (TPS) Source: https://github.com/lucko/spark/blob/master/_autodocs/quick-reference.md Retrieve the server's Ticks Per Second (TPS) statistics. This is only available on servers. Check for null before polling different time windows. ```java DoubleStatistic tps = spark.tps(); if (tps != null) { double tps5s = tps.poll(TicksPerSecond.SECONDS_5); double tps10s = tps.poll(TicksPerSecond.SECONDS_10); double tps1m = tps.poll(TicksPerSecond.MINUTES_1); double tps5m = tps.poll(TicksPerSecond.MINUTES_5); double tps15m = tps.poll(TicksPerSecond.MINUTES_15); } ``` -------------------------------- ### Get MSPT Metrics (Server Only) Source: https://github.com/lucko/spark/blob/master/_autodocs/usage-guide.md Access Milliseconds Per Tick (MSPT) statistics for detailed performance analysis on server platforms. Supports 10s, 1m, and 5m rolling averages. Provides mean, min, max, median, and custom percentiles. ```java GenericStatistic mspt = spark.mspt(); if (mspt != null) { // Get statistics for a specific window DoubleAverageInfo info10s = mspt.poll(MillisPerTick.SECONDS_10); // Access individual statistics System.out.println("Mean MSPT: " + info10s.mean() + " ms"); System.out.println("Min MSPT: " + info10s.min() + " ms"); System.out.println("Max MSPT: " + info10s.max() + " ms"); System.out.println("Median MSPT: " + info10s.median() + " ms"); System.out.println("95th percentile: " + info10s.percentile95th() + " ms"); System.out.println("Custom percentile (p99): " + info10s.percentile(0.99) + " ms"); // Analyze performance if (info10s.mean() > 50.0) { System.out.println("Server is lagging (average > 50ms)"); } if (info10s.percentile95th() > 100.0) { System.out.println("Severe lag spikes detected"); } } else { System.out.println("MSPT metrics not available on this platform"); } ``` -------------------------------- ### Get TPS Metrics Source: https://github.com/lucko/spark/blob/master/_autodocs/configuration.md Retrieve Ticks Per Second (TPS) statistics. This may be null on platforms that do not support tick tracking. Available windows include SECONDS_5, SECONDS_10, MINUTES_1, MINUTES_5, and MINUTES_15. ```java Spark spark = SparkProvider.get(); DoubleStatistic tps = spark.tps(); if (tps != null) { double tps5s = tps.poll(TicksPerSecond.SECONDS_5); double tps10s = tps.poll(TicksPerSecond.SECONDS_10); double tps1m = tps.poll(TicksPerSecond.MINUTES_1); double tps5m = tps.poll(TicksPerSecond.MINUTES_5); double tps15m = tps.poll(TicksPerSecond.MINUTES_15); } else { System.out.println("TPS metrics not available on this platform"); } ``` -------------------------------- ### totalCollections() Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/garbage-collector.md Gets the total cumulative number of garbage collection runs performed since the JVM started. ```APIDOC ## totalCollections() ### Description Gets the total cumulative number of garbage collection runs performed since the JVM started. ### Method ```java long totalCollections() ``` ### Parameters (none) ### Return Type `long` - Total count of collection invocations ### Example ```java Spark spark = SparkProvider.get(); Map gcStats = spark.gc(); GarbageCollector youngGen = gcStats.get("G1 Young Generation"); if (youngGen != null) { System.out.println("Young GC runs: " + youngGen.totalCollections()); } ``` ``` -------------------------------- ### Basic Spark Initialization Source: https://github.com/lucko/spark/blob/master/_autodocs/quick-reference.md Initialize the Spark API using SparkProvider.get(). Ensure Spark is available before calling this. ```java Spark spark = SparkProvider.get(); ``` -------------------------------- ### Log Server Metrics with Legacy Colors Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/placeholder-resolver.md This snippet demonstrates how to log various server metrics, including TPS, MSPT, and memory usage, using legacy color formatting. Null checks are essential before logging. ```java public void logMetrics() { Spark spark = SparkProvider.get(); PlaceholderResolver resolver = spark.placeholders(); String tps = resolver.resolveLegacyFormatting("%spark_tps%"); String mspt = resolver.resolveLegacyFormatting("%spark_mspt%"); String memory = resolver.resolveLegacyFormatting("%spark_memory%"); if (tps != null && mspt != null && memory != null) { System.out.println("[Spark] TPS: " + tps + " | MSPT: " + mspt + " | Memory: " + memory); } } ``` -------------------------------- ### mean() Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/double-average-info.md Gets the arithmetic mean (average) of all recorded values. ```APIDOC ## mean() ### Description Gets the arithmetic mean (average) of all recorded values. ### Method Java Method ### Parameters (none) ### Response #### Success Response - **return value** (`double`) - The mean value ### Example ```java Spark spark = SparkProvider.get(); GenericStatistic mspt = spark.mspt(); if (mspt != null) { DoubleAverageInfo info = mspt.poll(MillisPerTick.SECONDS_10); System.out.println("Average MSPT: " + info.mean() + " ms"); } ``` ``` -------------------------------- ### StatisticWindow.length() Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/statistic-window.md Gets the duration of this time window as a `Duration` object. ```APIDOC ## length() ### Description Gets the duration of this time window as a `Duration` object. ### Method ```java @NonNull Duration length() ``` ### Parameters (none) ### Response #### Success Response - **return** (`Duration`) - Non-null java.time.Duration representing the window length ### Request Example ```java CpuUsage window = CpuUsage.MINUTES_1; Duration length = window.length(); System.out.println("Window duration: " + length); System.out.println("In seconds: " + length.getSeconds()); System.out.println("In minutes: " + length.toMinutes()); ``` ``` -------------------------------- ### Select Appropriate Window Duration Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/statistic-window.md Query specific statistic windows based on predefined durations like 10 seconds, 1 minute, or 15 minutes. This allows for tailored performance monitoring. ```java public void selectWindow(Spark spark) { DoubleStatistic tps = spark.tps(); if (tps == null) return; // Short-term view: Check 5-10 second average double recentTps = tps.poll(TicksPerSecond.SECONDS_10); if (recentTps < 15.0) { System.out.println("Immediate lag detected!"); } // Medium-term view: Check 1-minute average double mediumTps = tps.poll(TicksPerSecond.MINUTES_1); if (mediumTps < 15.0 && recentTps >= 15.0) { System.out.println("Recent lag spike resolved"); } // Long-term view: Check 15-minute average double longTermTps = tps.poll(TicksPerSecond.MINUTES_15); if (longTermTps < 19.0) { System.out.println("Chronic performance issues detected"); } } ``` -------------------------------- ### max() Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/double-average-info.md Gets the maximum (worst case) value in the recorded dataset. ```APIDOC ## max() ### Description Gets the maximum (worst case) value in the recorded dataset. ### Method Java Method ### Parameters (none) ### Response #### Success Response - **return value** (`double`) - The maximum value ### Example ```java Spark spark = SparkProvider.get(); GenericStatistic mspt = spark.mspt(); if (mspt != null) { DoubleAverageInfo info = mspt.poll(MillisPerTick.SECONDS_10); double maxMspt = info.max(); if (maxMspt > 100.0) { System.out.println("Worst tick: " + maxMspt + " ms"); System.out.println("This is a severe lag spike!"); } } ``` ``` -------------------------------- ### Safe Spark Initialization with Error Handling Source: https://github.com/lucko/spark/blob/master/_autodocs/quick-reference.md Safely initialize Spark by wrapping the SparkProvider.get() call in a try-catch block to handle cases where Spark might not be available. ```java Spark spark = null; try { spark = SparkProvider.get(); } catch (IllegalStateException e) { // spark not available } ``` -------------------------------- ### Query All Windows Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/statistic-window.md Retrieve all available statistic windows and their corresponding values at once. This is useful for a comprehensive overview of current statistics. ```java public void queryAllWindows(Spark spark) { DoubleStatistic cpu = spark.cpuProcess(); // Get all windows and values at once double[] allValues = cpu.poll(); CpuUsage[] windows = cpu.getWindows(); for (int i = 0; i < windows.length; i++) { CpuUsage window = windows[i]; double value = allValues[i]; System.out.println(window + " (" + window.length() + "): " + value + "%"); } } ``` -------------------------------- ### avgFrequency() Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/garbage-collector.md Gets the average frequency (interval) between garbage collection runs. Time is measured in milliseconds. ```APIDOC ## avgFrequency() ### Description Gets the average frequency (interval) between garbage collection runs. Time is measured in milliseconds. ### Calculation `totalUptime / totalCollections` ### Method ```java long avgFrequency() ``` ### Parameters (none) ### Return Type `long` - Average milliseconds between collections ### Example ```java Spark spark = SparkProvider.get(); Map gcStats = spark.gc(); for (GarbageCollector gc : gcStats.values()) { System.out.println(gc.name() + ":"); System.out.println(" Frequency (ms between GC): " + gc.avgFrequency()); System.out.println(" Duration (avg per GC): " + gc.avgTime() + " ms"); long frequencySec = gc.avgFrequency() / 1000; System.out.println(" Roughly every " + frequencySec + " seconds"); } ``` ``` -------------------------------- ### name() Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/statistic.md Gets the human-readable name of this statistic. This method returns a non-null descriptive name for the statistic. ```APIDOC ## name() ### Description Gets the human-readable name of this statistic. ### Method ```java @NonNull String name() ``` ### Return Type `String` - Non-null descriptive name for the statistic ### Example ```java Spark spark = SparkProvider.get(); DoubleStatistic cpuStat = spark.cpuProcess(); System.out.println("Statistic name: " + cpuStat.name()); // Output: "CPU Usage (Process)" ``` ``` -------------------------------- ### Get Statistic Name Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/statistic.md Retrieves the human-readable name of a statistic. Useful for logging or display purposes. ```java Spark spark = SparkProvider.get(); DoubleStatistic cpuStat = spark.cpuProcess(); System.out.println("Statistic name: " + cpuStat.name()); // Output: "CPU Usage (Process)" ``` -------------------------------- ### DoubleAverageInfo Source: https://github.com/lucko/spark/blob/master/_autodocs/BUILD-SUMMARY.txt Documentation for the DoubleAverageInfo interface, detailing statistical data methods and use case examples. ```APIDOC ## DoubleAverageInfo ### Description Interface providing detailed statistical data for numerical metrics. ### Methods - **mean**(): double - Calculates the mean. - **min**(): double - Returns the minimum value. - **max**(): double - Returns the maximum value. - **median**(): double - Calculates the median. - **percentile95th**(): double - Calculates the 95th percentile. - **percentile**(double percentile): double - Calculates a specified percentile. ### Use Case Examples Three examples demonstrating the practical application of DoubleAverageInfo. ``` -------------------------------- ### Typical Usage Pattern Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/statistic.md Demonstrates a typical pattern for analyzing statistics, including retrieving the statistic's name and iterating through its available windows. ```APIDOC ## Typical Usage Pattern ```java public void analyzeStatistic(Statistic stat) { System.out.println("Analyzing: " + stat.name()); // This would be a DoubleStatistic or GenericStatistic in practice // with a specific window type, but for this example: // Get the available windows Enum[] windows = stat.getWindows(); System.out.println("Available windows: " + windows.length); for (Enum window : windows) { System.out.println(" - " + window); } } ``` ``` -------------------------------- ### Get StatisticWindow Duration Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/statistic-window.md Demonstrates how to retrieve the duration of a StatisticWindow enum as a Java Duration object and its components. ```java CpuUsage window = CpuUsage.MINUTES_1; Duration length = window.length(); System.out.println("Window duration: " + length); System.out.println("In seconds: " + length.getSeconds()); System.out.println("In minutes: " + length.toMinutes()); ``` -------------------------------- ### Compare Performance Between Recent and Historical Data Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/double-average-info.md Compares the mean MSPT between a recent 10-second window and a 15-minute historical window to calculate performance change percentage and flag significant degradation. ```java public void comparePerformance() { Spark spark = SparkProvider.get(); GenericStatistic mspt = spark.mspt(); if (mspt == null) return; DoubleAverageInfo recent = mspt.poll(MillisPerTick.SECONDS_10); DoubleAverageInfo historical = mspt.poll(MillisPerTick.MINUTES_15); double recentMean = recent.mean(); double historicalMean = historical.mean(); double change = ((recentMean - historicalMean) / historicalMean) * 100; System.out.println("Performance change: " + change + "%"); if (change > 10) { System.out.println("Performance has degraded significantly!"); } } ``` -------------------------------- ### percentile(double percentile) Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/double-average-info.md Gets the value at a specific percentile of the recorded data. Useful for understanding the distribution of values. ```APIDOC ## percentile(double percentile) ### Description Gets the value at a specific percentile of the recorded data. Useful for understanding the distribution of values. ### Method Signature ```java double percentile(double percentile) ``` ### Parameters #### Path Parameters - **percentile** (double) - Required - Percentile as a value between 0.0 and 1.0 (e.g., 0.5 for 50th percentile, 0.99 for 99th) ### Return Type - **double** - The value at the specified percentile ### Example ```java Spark spark = SparkProvider.get(); GenericStatistic mspt = spark.mspt(); if (mspt != null) { DoubleAverageInfo info = mspt.poll(MillisPerTick.SECONDS_10); System.out.println("MSPT Distribution (10-second window):"); System.out.println(" Min (0%): " + info.min()); System.out.println(" 25th%ile: " + info.percentile(0.25)); System.out.println(" 50th%ile (median): " + info.percentile(0.50)); System.out.println(" 75th%ile: " + info.percentile(0.75)); System.out.println(" 95th%ile: " + info.percentile95th()); System.out.println(" 99th%ile: " + info.percentile(0.99)); System.out.println(" Max (100%): " + info.max()); } ``` ``` -------------------------------- ### median() Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/double-average-info.md Gets the median value (50th percentile) of the recorded values. This is a convenience method that calls `percentile(0.50)`. ```APIDOC ## median() ### Description Gets the median value (50th percentile) of the recorded values. This is a convenience method that calls `percentile(0.50)`. ### Method Java Method ### Parameters (none) ### Response #### Success Response - **return value** (`double`) - The median value ### Example ```java Spark spark = SparkProvider.get(); GenericStatistic mspt = spark.mspt(); if (mspt != null) { DoubleAverageInfo info = mspt.poll(MillisPerTick.MINUTES_1); double mean = info.mean(); double median = info.median(); if (median > mean) { System.out.println("Half of ticks are above average (right-skewed distribution)"); } else if (median < mean) { System.out.println("Half of ticks are below average (left-skewed distribution)"); } else { System.out.println("Distribution is symmetrical"); } } ``` ``` -------------------------------- ### Core API Interfaces Source: https://github.com/lucko/spark/blob/master/_autodocs/module-structure.md The main entry point for all metrics and statistics, and the singleton provider for the Spark instance. ```APIDOC ## me.lucko.spark.api ### Description Provides the core API interfaces for interacting with Spark. ### Classes - `Spark`: Interface - Main entry point for all metrics and statistics. - `SparkProvider`: Class - Singleton provider for the Spark instance. ``` -------------------------------- ### Get Garbage Collector Names Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/garbage-collector.md Iterate through all garbage collectors and print their names. Requires Spark API initialization. ```java Spark spark = SparkProvider.get(); Map gcStats = spark.gc(); for (GarbageCollector gc : gcStats.values()) { System.out.println("Garbage Collector: " + gc.name()); } ``` -------------------------------- ### Handle IllegalStateException from SparkProvider Source: https://github.com/lucko/spark/blob/master/_autodocs/usage-guide.md Use a try-catch block to gracefully handle cases where Spark may not be loaded or installed. ```java try { Spark spark = SparkProvider.get(); } catch (IllegalStateException e) { // Handle gracefully - spark may not be installed System.out.println("spark not available: " + e.getMessage()); } ``` -------------------------------- ### Query All Time Window Metrics Source: https://github.com/lucko/spark/blob/master/_autodocs/README.md Retrieve all available metrics for a given statistic at once. Useful for a comprehensive overview. ```java double[] all = spark.cpuProcess().poll(); ``` -------------------------------- ### Null Checking for Performance Statistics Source: https://github.com/lucko/spark/blob/master/_autodocs/quick-reference.md Demonstrates how to safely check for null values when accessing TPS, MSPT, and placeholder statistics, as these may not be available on all platforms or configurations. ```java Spark spark = SparkProvider.get(); // TPS and MSPT may be null on non-server platforms DoubleStatistic tps = spark.tps(); if (tps != null) { // Use TPS } GenericStatistic mspt = spark.mspt(); if (mspt != null) { // Use MSPT } // Placeholders may resolve to null String placeholder = spark.placeholders().resolveLegacyFormatting("%spark_tps%"); if (placeholder != null) { // Use placeholder } ``` -------------------------------- ### SparkProvider Class Source: https://github.com/lucko/spark/blob/master/_autodocs/module-structure.md Provides access to the Spark instance. ```APIDOC ## SparkProvider (final class) ### Method - **get(): Spark** Returns the singleton instance of the Spark API. ### Returns - **Spark** ``` -------------------------------- ### Accessing Statistic Name and Windows Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/double-statistic.md Demonstrates how to access the statistic's name and iterate through its available windows using inherited methods. Useful for dynamic inspection of statistics. ```java Spark spark = SparkProvider.get(); DoubleStatistic stat = spark.cpuProcess(); System.out.println("Statistic: " + stat.name()); CpuUsage[] windows = stat.getWindows(); for (CpuUsage window : windows) { System.out.println(" Window: " + window + " (" + window.length() + ")"); System.out.println(" Value: " + stat.poll(window)); } ``` -------------------------------- ### Get Average MSPT Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/double-average-info.md Retrieves the average milliseconds per tick (MSPT) over a specified duration. This is useful for general performance monitoring. ```java Spark spark = SparkProvider.get(); GenericStatistic mspt = spark.mspt(); if (mspt != null) { DoubleAverageInfo info = mspt.poll(MillisPerTick.SECONDS_10); System.out.println("Average MSPT: " + info.mean() + " ms"); } ``` -------------------------------- ### Safely Resolve Placeholder with Null Check Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/placeholder-resolver.md Demonstrates how to resolve a placeholder and safely use the result by checking for null. This is crucial as the resolver returns null if the placeholder is unrecognized, unavailable, or the plugin is not initialized. ```java String result = resolver.resolveLegacyFormatting("%spark_tps%"); if (result != null) { // Use result } else { // Fallback or error handling } ``` -------------------------------- ### StatisticWindow Interface Source: https://github.com/lucko/spark/blob/master/_autodocs/BUILD-SUMMARY.txt Documentation for the StatisticWindow interface and its associated enums, detailing window definitions and querying patterns. ```APIDOC ## StatisticWindow ### Description Interface representing a time window for collecting statistics. ### Enums - **CpuUsage**: Enum for CPU usage windows. - **TicksPerSecond**: Enum for ticks per second windows. - **MillisPerTick**: Enum for milliseconds per tick windows. ### Window Definitions Complete definitions for all supported statistic windows. ### Querying Patterns Examples and explanations of how to query statistics across multiple windows. ``` -------------------------------- ### Access Statistic Name and Windows Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/generic-statistic.md Demonstrates how to retrieve the name of a statistic and iterate through its available time windows using inherited methods from the Statistic interface. ```java Spark spark = SparkProvider.get(); GenericStatistic stat = spark.mspt(); if (stat != null) { System.out.println("Statistic: " + stat.name()); MillisPerTick[] windows = stat.getWindows(); for (MillisPerTick window : windows) { System.out.println(" Window: " + window + " (" + window.length() + ")"); DoubleAverageInfo info = stat.poll(window); System.out.println(" Mean: " + info.mean()); } } ``` -------------------------------- ### percentile95th() Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/double-average-info.md Gets the 95th percentile value. This is a convenience method that calls `percentile(0.95)`. Useful for understanding worst-case performance while ignoring extreme outliers. ```APIDOC ## percentile95th() ### Description Gets the 95th percentile value. This is a convenience method that calls `percentile(0.95)`. Useful for understanding worst-case performance while ignoring extreme outliers. ### Method Java Method ### Parameters (none) ### Response #### Success Response - **return value** (`double`) - The 95th percentile value ### Example ```java Spark spark = SparkProvider.get(); GenericStatistic mspt = spark.mspt(); if (mspt != null) { DoubleAverageInfo info = mspt.poll(MillisPerTick.MINUTES_5); double p95 = info.percentile95th(); // Minecraft ticks should be roughly 50ms (20 TPS) double tickBudget = 50.0; if (p95 > tickBudget) { System.out.println("95% of ticks exceed the 50ms budget"); System.out.println("Only the fastest 5% of ticks are within budget"); } } ``` ``` -------------------------------- ### Display Server Health in Actionbar Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/placeholder-resolver.md Use this to display server metrics like TPS and CPU usage in the player's action bar. Ensure to check for null values as placeholders may not always be available. ```java public void updateActionbar(Player player) { Spark spark = SparkProvider.get(); PlaceholderResolver resolver = spark.placeholders(); String tpsString = resolver.resolveLegacyFormatting("%spark_tps%"); String cpuString = resolver.resolveLegacyFormatting("%spark_cpu_process%"); if (tpsString != null && cpuString != null) { String message = "TPS: " + tpsString + " | CPU: " + cpuString; player.sendActionBar(message); } } ``` -------------------------------- ### Get Minimum MSPT Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/double-average-info.md Retrieves the minimum milliseconds per tick (MSPT) recorded, representing the best-case performance. Useful for understanding optimal tick times. ```java Spark spark = SparkProvider.get(); GenericStatistic mspt = spark.mspt(); if (mspt != null) { DoubleAverageInfo info = mspt.poll(MillisPerTick.SECONDS_10); double minMspt = info.min(); System.out.println("Best tick: " + minMspt + " ms"); } ``` -------------------------------- ### Spark Performance Metrics API Source: https://github.com/lucko/spark/blob/master/_autodocs/README.md Illustrates how to access various performance metrics from the Spark interface. Note that TPS and MSPT may be null on certain platforms. ```java // May be null on non-server platforms DoubleStatistic tps = spark.tps(); GenericStatistic mspt = spark.mspt(); // May return null for unknown placeholders String value = spark.placeholders().resolveLegacyFormatting("%unknown%"); // Always safe DoubleStatistic cpu = spark.cpuProcess(); Map gc = spark.gc(); ``` -------------------------------- ### Get Available Time Windows Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/statistic.md Retrieves all time windows for which rolling averages are tracked for a statistic. This allows iteration over different averaging periods and polling their values. ```java Spark spark = SparkProvider.get(); DoubleStatistic cpuStat = spark.cpuProcess(); CpuUsage[] windows = cpuStat.getWindows(); for (CpuUsage window : windows) { System.out.println("Window: " + window); System.out.println(" Duration: " + window.length()); double value = cpuStat.poll(window); System.out.println(" Value: " + value); } ``` -------------------------------- ### resolveLegacyFormatting Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/placeholder-resolver.md Resolves a placeholder to a string with legacy color formatting. Returns null if the placeholder cannot be resolved. ```APIDOC ## resolveLegacyFormatting(String placeholder) ### Description Resolves a placeholder to a string with legacy color formatting. Returns null if the placeholder cannot be resolved. ### Method ```java @Nullable String resolveLegacyFormatting(@NonNull String placeholder) ``` ### Parameters #### Path Parameters - **placeholder** (String) - Required - The placeholder to resolve (e.g., "%spark_tps%", "%spark_cpu_process%") ### Response #### Success Response - **return value** (String or null) - Formatted string with legacy color codes (e.g., `&c`, `&a`), or null if not found ### Request Example ```java Spark spark = SparkProvider.get(); PlaceholderResolver resolver = spark.placeholders(); String tpsFormatted = resolver.resolveLegacyFormatting("%spark_tps%"); if (tpsFormatted != null) { System.out.println("TPS: " + tpsFormatted); } else { System.out.println("Could not resolve TPS placeholder"); } ``` ``` -------------------------------- ### Get Placeholder Resolver Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/spark.md Retrieves a placeholder resolver for formatting spark metrics as text. Use this to format metrics like CPU usage or TPS into human-readable strings. ```java Spark spark = SparkProvider.get(); PlaceholderResolver placeholders = spark.placeholders(); String legacyFormatted = placeholders.resolveLegacyFormatting("%spark_cpu_process%"); String jsonFormatted = placeholders.resolveComponentJson("%spark_tps%"); ``` -------------------------------- ### Display Server Health Report Source: https://github.com/lucko/spark/blob/master/_autodocs/usage-guide.md Generates a comprehensive server health report including CPU usage, TPS, MSPT, and GC times. Requires SparkProvider to be initialized. ```java public class ServerHealthDisplay { private final Spark spark; public ServerHealthDisplay() { this.spark = SparkProvider.get(); } public String getHealthReport() { StringBuilder sb = new StringBuilder(); sb.append("═══ Server Health ═══\n"); // CPU metrics double processCpu = spark.cpuProcess().poll(CpuUsage.MINUTES_1); double systemCpu = spark.cpuSystem().poll(CpuUsage.MINUTES_1); sb.append("Process CPU: ").append(String.format("%.1f%%", processCpu)).append("\n"); sb.append("System CPU: ").append(String.format("%.1f%%", systemCpu)).append("\n"); // TPS metrics (if available) DoubleStatistic tps = spark.tps(); if (tps != null) { double tpsValue = tps.poll(TicksPerSecond.MINUTES_1); sb.append("TPS (1m): ").append(String.format("%.1f", tpsValue)).append("\n"); } // MSPT metrics (if available) GenericStatistic mspt = spark.mspt(); if (mspt != null) { DoubleAverageInfo info = mspt.poll(MillisPerTick.MINUTES_1); sb.append("MSPT (mean): ").append(String.format("%.1f", info.mean())).append("ms\n"); sb.append("MSPT (max): ").append(String.format("%.1f", info.max())).append("ms\n"); } // GC metrics Map gcStats = spark.gc(); long totalGCTime = 0; for (GarbageCollector gc : gcStats.values()) { totalGCTime += gc.totalTime(); } sb.append("Total GC time: ").append(totalGCTime).append("ms\n"); return sb.toString(); } } ``` -------------------------------- ### Get System CPU Usage Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/spark.md Retrieves the CPU usage statistic for the overall system. This is useful for understanding the total CPU load on the machine, not just the application's share. ```java Spark spark = SparkProvider.get(); DoubleStatistic systemCpu = spark.cpuSystem(); double[] allWindows = systemCpu.poll(); System.out.println("10s average: " + allWindows[0]); System.out.println("1m average: " + allWindows[1]); System.out.println("15m average: " + allWindows[2]); ``` -------------------------------- ### PlaceholderResolver Source: https://github.com/lucko/spark/blob/master/_autodocs/BUILD-SUMMARY.txt Documentation for the PlaceholderResolver interface, detailing methods for placeholder formatting and available placeholders. ```APIDOC ## PlaceholderResolver ### Description Interface for formatting and resolving placeholders. ### Methods - **resolveLegacy**(String key): String - Resolves a placeholder using legacy formatting. - **resolveJson**(String key): String - Resolves a placeholder using JSON formatting. ### Available Placeholders A list of 12 available placeholders that can be resolved. ### Usage Patterns Examples and explanations of how to use the PlaceholderResolver. ``` -------------------------------- ### Get Process CPU Usage Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/spark.md Retrieves the CPU usage statistic for the current process. Use this to monitor the application's own CPU consumption over various time windows. ```java Spark spark = SparkProvider.get(); DoubleStatistic processCpu = spark.cpuProcess(); double cpu10s = processCpu.poll(CpuUsage.SECONDS_10); double cpu1m = processCpu.poll(CpuUsage.MINUTES_1); double cpu15m = processCpu.poll(CpuUsage.MINUTES_15); ``` -------------------------------- ### Spark Interface Source: https://github.com/lucko/spark/blob/master/_autodocs/types.md The main entry point for the Spark API, providing access to all performance metrics and statistics. ```APIDOC ## Spark (Interface) ### Description The main entry point for the spark API. Provides access to all performance metrics and statistics. ### Methods - `cpuProcess()`: Returns a `DoubleStatistic` for process CPU usage. - `cpuSystem()`: Returns a `DoubleStatistic` for system CPU usage. - `tps()`: Returns a nullable `DoubleStatistic` for ticks per second. - `mspt()`: Returns a nullable `GenericStatistic` for milliseconds per tick. - `gc()`: Returns a map of garbage collector statistics. - `placeholders()`: Returns a `PlaceholderResolver`. ``` -------------------------------- ### Get CPU Usage Statistics Source: https://github.com/lucko/spark/blob/master/_autodocs/usage-guide.md Access process and system CPU usage statistics. Poll for specific rolling averages (10s, 1m, 15m) or retrieve all available values. ```java DoubleStatistic processCpu = spark.cpuProcess(); DoubleStatistic systemCpu = spark.cpuSystem(); // Poll a specific window double processCpu10s = processCpu.poll(CpuUsage.SECONDS_10); double processCpu1m = processCpu.poll(CpuUsage.MINUTES_1); double processCpu15m = processCpu.poll(CpuUsage.MINUTES_15); // Poll all windows at once double[] allValues = processCpu.poll(); CpuUsage[] windows = processCpu.getWindows(); for (int i = 0; i < windows.length; i++) { System.out.println(windows[i] + ": " + allValues[i] + "% "); } ``` -------------------------------- ### Inherited Methods Source: https://github.com/lucko/spark/blob/master/_autodocs/api-reference/double-statistic.md The DoubleStatistic interface inherits methods from the Statistic interface, including name() to get the statistic's name and getWindows() to retrieve the available time windows. ```APIDOC ## Inherited Methods ### name() Gets the statistic name. ### getWindows() Gets the windows used for rolling averages. ### Request Example ```java Spark spark = SparkProvider.get(); DoubleStatistic stat = spark.cpuProcess(); System.out.println("Statistic: " + stat.name()); CpuUsage[] windows = stat.getWindows(); for (CpuUsage window : windows) { System.out.println(" Window: " + window + " (" + window.length() + ")"); System.out.println(" Value: " + stat.poll(window)); } ``` ```