Перейти к содержимому
Mineforgian

PerformanceAnalyzer

Monitor your server in real-time, find the source of lag spikes in seconds, and keep your players happy — all from a single, lightweight plugin.

Загрузки
487
Подписчики
0
Обновлён
17 июня 2026 г.
Лицензия
MIT

Опубликован 21 ноября 2025 г.

Why PerformanceAnalyzer?

Most monitoring plugins tell you that your server is lagging. PerformanceAnalyzer tells you why.

When a TPS drop or MSPT spike occurs, the plugin automatically captures a full snapshot of your server state — loaded chunks, entity counts, player activity, suspect plugins — so you can diagnose the problem instantly instead of guessing.

⚡ New in v3.0.0

  • AntiCheat is now its own plugin. PerformanceAnalyzer is now a focused, pure performance monitor. The XRay/Movement detection lives on in the standalone BSAntiCheat plugin — install it alongside PerformanceAnalyzer and the GUI will link the two together automatically.
  • Per-second drop detection — performance drops are now sampled every second (decoupled from the database logging interval), so short-lived spikes are no longer missed.
  • REST API is live — JSON endpoints for Grafana/Prometheus dashboards.
  • Developer API — other plugins can read live TPS/MSPT/heap/entity data.

Key Features

Real-Time Performance Monitoring

  • TPS, MSPT & Heap tracking with historical data and ASCII sparklines
  • Spark Integration for highly accurate TPS (10s/1m/5m), MSPT (avg/p95/max), and CPU data
  • ProtocolLib Integration for packet analysis and flood detection
  • Database Logging (SQLite or MySQL) with async batch writes via HikariCP
  • Fallback File Logging — if the database goes down, metrics are written to a file instead of being lost

Automatic Lag Diagnosis

  • Performance Drop Detection — triggers automatically when TPS drops or MSPT spikes, sampled every second
  • Full Server Snapshots — captures chunks, entities, memory, and player locations at the moment of the drop
  • Accurate Low/High Tracking — reports the actual worst TPS/MSPT seen during the drop window
  • Lag Source Analysis — identifies the players and plugins most likely responsible
  • Problematic Chunk Detection — finds chunks overloaded with tile entities or redstone
  • Chunk Thrashing Detection — spots chunks that load/unload too frequently
  • Throttled & quiet — the expensive deep analysis is rate-limited and stays out of the console unless debug mode is on, so the diagnostics never make the lag worse

Interactive GUI System

  • Performance Dashboard — live TPS, MSPT, heap with auto-refresh
  • Lag Analysis Page — top 5 active players and suspect plugins with risk scores
  • Performance Drops Page — browse up to 21 recent drops, click for detailed reports
  • Config GUI — toggle settings without touching files
  • Companion detection — shows BSAntiCheat status when the AntiCheat plugin is installed
  • Multi-page navigation, color-coded items, intuitive design

Silent Mode / Streamer Mode

  • /perfsilent — mute all alert notifications in chat
  • /perfsilent performance — mute just the performance alert category
  • /perfsilent list — view your current preferences
  • /perfsilent reset — receive all alerts again
  • Persistent across server restarts
  • Perfect for streamers, builders, or admins who don't need constant notifications

Discord Webhook Integration

  • Automatic notifications for TPS drops, high MSPT, heap warnings, and packet floods
  • Color-coded embeds per alert type
  • Configurable: choose exactly which events get reported
  • Async, rate-limited HTTP requests — zero performance impact
  • SSRF-protected: only valid Discord webhook URLs are accepted

Auto Entity Cleaner

  • Priority-based removal: items > projectiles > monsters > animals
  • Protects named entities, tamed animals, villagers, and boss mobs
  • Per-world and per-chunk limits
  • Dry-run mode for safe testing before enabling

Additional Tools

  • World Statistics (/worldstats) — entities, chunks, density, trend analysis per world
  • Entity Analysis (/entitystats) — breakdown by category, hotspot detection
  • Chunk Statistics (/chunkstats) — load tracking, problematic chunks, thrashing
  • REST API — JSON endpoints for Grafana/Prometheus dashboards with API key auth
  • Developer APIPerformanceAPI for other plugins to read live metrics
  • Auto Database Cleanup — configurable retention (default: 30 days)
  • Multi-Language — English & German, easily extensible

Commands

Command Description Permission
/perfstatus Live TPS, MSPT, heap data performance.status
/perfhistory [min] Historical MSPT sparkline & stats performance.history
/perfgui Open the interactive GUI performance.gui
/perfreload Reload plugin configuration performance.admin
/perfsilent [type] Toggle alert notifications (streamer mode) performance.admin
/perfdrops [#] View/analyze performance drops performance.admin
/worldstats [world] Per-world statistics (alias /ws) performance.admin
/entitystats [world] Entity analysis & hotspots (alias /es) performance.admin
/chunkstats [sub] Chunk load tracking & problems (alias /cs) performance.admin

Permissions

Permission Description Default
performance.status Use /perfstatus Everyone
performance.history Use /perfhistory Everyone
performance.gui Use /perfgui Everyone
performance.admin Admin commands & alert notifications OP
performance.silent Use silent mode to mute alerts OP

Configuration Highlights

Database (SQLite or MySQL)
database:
  type: sqlite                    # or 'mysql'
  sqlite_file: "plugins/PerformanceAnalyzer/perf.db"
  retention_days: 30              # Auto-cleanup (0 = disabled)
  fallback_file_logging: true     # Log to file if the DB is unavailable
  fallback_log_file: "plugins/PerformanceAnalyzer/fallback.log"
  pool:
    max_pool_size: 10
    minimum_idle: 2
Performance Thresholds
thresholds:
  mspt: 50.0                      # MSPT warning (ms)
  heap_usage_percent: 80.0         # Heap warning (%)
  tps_drop: 19.0                   # TPS drop warning
  packet_flood_per_tick: 1000.0    # Packet flood detection
Lag Analysis Thresholds

All thresholds are adjustable for your hardware:

lag_analysis:
  player_tracking: true
  plugin_analysis: true
  chunk_analysis_timeout_ms: 5000

  # Chunk thresholds (Standard | Powerful | Weak)
  chunk_tile_entities_threshold: 10    # 10 | 20-30 | 5-8
  chunk_redstone_threshold: 30         # 30 | 50-100 | 15-20
  chunk_entity_warning: 50             # 50 | 80-100 | 30-40
  chunk_entity_critical: 100           # 100 | 150-200 | 60-80

  # World thresholds
  world_entity_warning: 5000
  world_entity_critical: 10000
Discord Webhook
discord:
  enabled: false
  webhook_url: ""
  alert_types:
    high_mspt: true
    tps_drop: true
    high_heap: true
    packet_flood: true
REST API
api:
  enabled: false
  port: 8080
  key: "changeme"    # IMPORTANT: Set a secure key! The server won't start otherwise.

Endpoints: /api/health, /api/metrics, /api/worlds, /api/trends Authentication: Authorization: Bearer <key>

Auto Entity Cleaner
entity_cleaner:
  enabled: false
  interval_seconds: 300
  world_limit: 5000
  chunk_limit: 100
  dry_run: true                  # Test mode (logs only, no removal)
  protect_villagers: true
  protect_item_frames: true
  blacklist: ["ENDER_DRAGON", "WITHER", "WARDEN"]
  world_whitelist: []            # Worlds that are never cleaned

Developer API

Other plugins can read live performance data directly:

PerformanceAPI api = (PerformanceAPI) Bukkit.getPluginManager().getPlugin("PerformanceAnalyzer");
double tps = api.getCurrentTPS();
double mspt = api.getCurrentMSPT();
double heap = api.getHeapUsagePercent();
int entities = api.getTotalEntityCount();

Language Support

English and German are included. Language files live in plugins/PerformanceAnalyzer/lang/ and are fully customizable.

Adding a new language:

  1. Copy en.yml to your language code (e.g. fr.yml)
  2. Translate all messages
  3. Set language: fr in config.yml
  4. Run /perfreload

Looking for AntiCheat?

As of v3.0.0, the XRay and Movement detection has moved into its own dedicated plugin: BSAntiCheat. Install both side by side — PerformanceAnalyzer handles performance and lag diagnosis, BSAntiCheat handles cheat detection, and the GUI links them together.


Optional Dependencies

Plugin Benefit
spark Accurate TPS (10s/1m/5m), MSPT (avg/p95/max), CPU monitoring
ProtocolLib Packet analysis & flood detection
BSAntiCheat Companion AntiCheat plugin (XRay & movement detection)

All integrations are optional — the plugin works fully standalone.


Requirements

  • Java 21
  • Paper 1.21.4 – 1.21.x
  • Thread-safe, async operations, minimal performance overhead

Config Auto-Migration

When updating, your existing config is never overwritten. New settings are automatically added with sensible defaults. Just replace the JAR and restart.


Special Thanks

To ELITEK3V for testing.

Ченджлог

3.0.0Релиз1.21.9, 1.21.10, 1.21.11 · 17 июня 2026 г.

[3.0.0] - 2026-06-17

Changed

  • BREAKING: AntiCheat split into a separate plugin (BSAntiCheat). PerformanceAnalyzer is now a focused performance-monitoring & lag-diagnosis plugin. All XRay and Movement detection — including the related commands, GUI, config, permissions and language strings — has been removed from this plugin and lives on in the standalone BSAntiCheat plugin. The performance GUI detects BSAntiCheat and links to it when installed.
  • Performance drop detection now runs every second on its own scheduled task, decoupled from the database logging interval. Previously checkForDrop() was only called once per log_interval_seconds (60s by default), so short-lived TPS/MSPT spikes were missed.

Added

  • REST API is now active. The MetricsAPI server is started on enable (was previously implemented but never wired up). Endpoints: /api/health, /api/metrics, /api/worlds, /api/trends, with API key authentication. Disabled by default.
  • Auto Entity Cleaner is now active. AutoEntityCleaner is hooked into plugin enable/disable. Disabled by default with dry_run: true.
  • Developer API: PerformanceAnalyzer now implements the public PerformanceAPI interface — getCurrentTPS(), getCurrentMSPT(), getHeapUsagePercent(), getTotalEntityCount(), getEntityCount(World), getVersion().
  • Accurate low/high drop tracking: recorded performance drops now report the actual worst TPS / highest MSPT observed during the drop window instead of the value at the moment of recording.
  • Documented config keys that were previously only added silently via migration: database.fallback_file_logging, database.fallback_log_file, gui.auto_refresh, and the full api.* and entity_cleaner.* sections.

Fixed

  • Duplicate logging task / task leak on /perfreload: TickSampler.setDatabase() now cancels the previously scheduled logging task before scheduling a new one. Previously every reload added another logging task, causing duplicate database writes and duplicate alert/drop checks.
  • Verbose console output during lag events: the per-world / per-chunk diagnostic logging in the performance drop analyzer is now gated behind debug mode, so it no longer floods the console (and adds load) while the server is already struggling.
  • Throttled deep analysis: the expensive server-state/chunk-snapshot analysis now runs at most once per 30 seconds during sustained drops, preventing it from piling up chunk snapshots on the main thread.

Removed

  • AntiCheat classes: XRayDetector, MovementChecker, ViolationTracker, XRayAlertManager, MovementAlertManager, AntiCheatGUI, LuckPermsHook
  • AntiCheat commands: /xrayalerts, /movealerts, /xrayores, /acwhitelist
  • AntiCheat permissions: performance.anticheat.manage, performance.anticheat.bypass
  • All anticheat.* config keys, performance.anticheat_enabled, discord.alert_types.anticheat, and all AntiCheat/XRay/Movement language strings (EN & DE)
  • XRAY and MOVEMENT silent-mode categories — only ALL and PERFORMANCE remain; /perfsilent now accepts all, performance, list, reset
  • Dead code: unused ConfigMigrator class (a duplicate migration system with a phantom "prometheus" feature), legacy synchronous analyzeChunk(), DatabaseManager.deleteAntiCheatLogs(), isPlayerSuspicious() from the public API, and empty Javadoc stubs in Constants

Config

  • config_version bumped to 6 — auto-migration adds the new fallback-logging keys to existing configs (existing settings are never overwritten)
2.3.4Релиз1.21.9, 1.21.10, 1.21.11 · 7 мая 2026 г.

[2.3.4] - 2026-05-07

Fixed

  • Redstone False Positives in Performance Drop Analyzer: Removed 26 non-performance-impacting blocks (buttons, pressure plates, lecterns, daylight detectors, tripwire, levers, targets) from isRedstoneComponent(). These blocks appear in naturally generated structures (villages, temples) and caused massive false positives through sampling extrapolation
  • Redstone Sampling Extrapolation: Added minimum threshold (≥3 components found) before extrapolating redstone counts. Previously, a single naturally-generated button was multiplied by ×64, producing false "problematic redstone" reports
  • Wrong Coordinates in Problematic Chunk Reports: Chunk coordinates are now displayed alongside block coordinates ([Chunk X,Z | Blocks ~X,Z]) for easier in-game navigation
  • NullPointerException in PerformanceDropAnalyzer: worldInfo.get("name").equals(...) replaced with Objects.equals() to prevent NPE when world name is null
  • Swallowed Exceptions in Chunk Analysis: ChunkSnapshot and synchronous chunk analysis errors are now logged at FINE level instead of being silently ignored
  • Unbounded Database Queue (OOM Risk): DatabaseManager.logAsync() now enforces a maximum queue size of 10,000 entries. Prevents OutOfMemoryError when the database is unavailable for extended periods
  • Excessive Block Checks in MovementChecker: isNearLiquid() reduced from 27 block checks (3×3×3 cube) to 7 checks (current block + 6 adjacent faces), reducing CPU load per PlayerMoveEvent by ~74%
  • Duplicated Alert Cooldown Constants: AlertManager and MovementAlertManager now use the centralized Constants.ALERT_COOLDOWN_MS instead of defining their own identical values
  • Silent Config Parsing Failures: Invalid alert categories in AlertPreferenceManager now log a warning instead of being silently skipped
  • Thread-Safety in WorldStatsManager: Trend history lists now use Collections.synchronizedList() to prevent concurrent modification issues

Added

  • Constants.DB_MAX_QUEUE_SIZE — centralized maximum queue size for database log entries
2.3.3Релиз1.21.9, 1.21.10, 1.21.11 · 12 апреля 2026 г.

[2.3.3] - 2026-04-12

Fixed

  • Sneaking/Swimming/Climbing False Positives: These movement types are now skipped entirely by the speed checker.
  • Silk Touch Ores Not Recognized as Self-Placed: The player-placed block check now applies to ALL worlds, not just restricted worlds. Previously, silk-touching an ore block, placing it in your base, and breaking it would count toward XRay detection
  • Y-Level Pattern Analysis Removed: Completely removed the Y-Level analysis feature. Mining at optimal Y-levels is normal gameplay (anyone can Google "best Y level for diamonds") and produced false positives

Removed

  • analyzeYLevelPattern(), trackYLevel(), getOptimalYRange() methods from XRayDetector
  • playerOreYLevels tracking map from XRayDetector
  • xray_ylevel_high/medium/low config entries and validation
  • XRAY_YLEVEL violation type
2.3.2Релиз1.21.9, 1.21.10, 1.21.11 · 11 апреля 2026 г.

[2.3.2] - 2026-04-11

Fixed

  • Race Condition in AlertManager: Cooldown check now uses atomic compareAndSet() instead of separate get()/set(), preventing duplicate alerts under concurrent access
  • Race Condition in TickSampler: Tick sampling now uses idx.getAndUpdate() for atomic index read-modify-write, preventing data corruption in the nanos array
  • Connection Pool Leak in DatabaseManager: shutdown() now uses try-finally to ensure HikariDataSource.close() is always called, even if flushBatchSafe() throws an exception
  • NullPointerException in GUIs: Added null-checks for getItemMeta() in all GUI classes (PerformanceGUI, AntiCheatGUI, LagAnalysisGUI, PerformanceDropsGUI) — follows the safe pattern already used in ConfigGUI
  • Thread-Safety in ViolationTracker: resetViolations(UUID, ViolationType) now uses computeIfPresent() to prevent race condition where the PlayerViolations object could be removed between get() and counts.remove()
  • MovementChecker Violation Reset Too Aggressive: Consecutive violation counters now only reset when speed is significantly below threshold (70%), preventing a single valid move from immediately washing out violations
  • XRay Y-Level Thresholds Too Aggressive: Default thresholds raised from 75%/65%/55% to 85%/75%/65% to reduce false positives from legitimate caving
  • UpdateChecker Missing Field Validation: Now checks for version_number field existence in Modrinth API response before accessing it
  • Inconsistent Activity Weights: PlayerActivityTracker.getTotalActivity() now uses centralized Constants.ACTIVITY_WEIGHT_* values instead of hardcoded numbers

Added

  • Configurable XRay Y-Level Thresholds (config.yml)
    • anticheat.xray_ylevel_high (default: 0.85) — percentage for maximum suspicion
    • anticheat.xray_ylevel_medium (default: 0.75) — percentage for moderate suspicion
    • anticheat.xray_ylevel_low (default: 0.65) — percentage for low suspicion
    • Config validation ensures values are 0.0-1.0 and properly ordered (low < medium < high)
    • Auto-migration adds defaults for existing configs

Changed

  • XRayDetector.analyzeYLevelPattern() reads thresholds from config instead of using hardcoded values
2.3.1Релиз1.21.9, 1.21.10, 1.21.11 · 10 апреля 2026 г.

[2.3.1] - 2026-04-10

Added

  • Silent Mode / Streamer Mode (/perfsilent)
    • Toggle all alerts on/off: /perfsilent
    • Toggle per category: /perfsilent xray, /perfsilent movement, /perfsilent performance
    • Reset all preferences at once: /perfsilent reset
    • View current status: /perfsilent list
    • Persistent across server restarts (saved in config.yml under alerts.silent_players)
    • Aliases: /ps, /silent
    • Full tab-completion support
    • Bilingual: German & English language strings
  • AntiCheat DB Cleanup Commands
    • /movealerts clear <player> --db — deletes movement violation entries from the database
    • /xrayalerts clear <player> --db — deletes XRay detection entries from the database
    • Without --db: only clears in-memory alerts (as before), now shows a hint about the --db option
    • Tab-completion for --db flag
  • Teleport Immunity for Movement Checks
    • New PlayerTeleportEvent listener prevents false positives from legitimate teleports (/tp, /home, ender pearls, etc.)
    • 1-second grace period after any teleport where movement checks are skipped
    • lastLocations reset to teleport destination to prevent follow-up false positives
    • Consecutive violation counters reset on teleport

Fixed

  • Version Inconsistency: pom.xml, plugin.yml, and main class now use the same version dynamically via getDescription().getVersion() instead of hardcoded strings
  • Race Condition in AsyncConfigSaver: pendingSave changed from volatile boolean to AtomicBoolean with proper atomic check-and-set operations, preventing lost config saves under concurrent requests
  • NullPointerException in PerformanceDropAnalyzer: Added null-checks for Player.getWorld() and Player.getLocation() during world unload scenarios
  • Memory Leak in AlertManager: Added periodic cleanup task (every 5 minutes) for stale lastAlertTimes entries that were never removed
  • AntiCheat False Positives: Improved lag compensation from linear to square-root scaling (200ms ping = +10%, 500ms = +20%, 1000ms = +30%), reducing false positives for high-ping players without allowing extreme speeds

Changed

  • All three alert systems (AlertManager, XRayAlertManager, MovementAlertManager) now respect per-player alert preferences before sending chat notifications
  • Config auto-migration adds alerts.silent_players for new installations
2.3.0Релиз1.21.9, 1.21.10, 1.21.11 · 22 февраля 2026 г.

[2.3.0] - 2026-02-22

Added

  • Lag Compensation for Movement Checks
    • Player ping considered in speed calculations (+10% per 100ms above 100ms)
    • Reduces false-positives for high-ping players
  • Knockback/Damage Immunity Detection
    • 2-second immunity window after explosions and entity attacks
    • Prevents false-positives from legitimate knockback
  • Y-Level Analysis for XRay Detection
    • Tracks mining height for all ores
    • Optimal Y-level ranges based on Minecraft 1.21
    • New detection method: XRAY_YLEVEL
    • Detects suspicious pattern: 75%+ mining at optimal height
  • Async Chunk Analysis
    • Uses ChunkSnapshot for thread-safe analysis
    • Parallel processing with CompletableFuture
    • 90% less main-thread load during performance drop analysis
    • Timeout protection maintained
  • Auto-Cleanup for Database
    • Automatic retention policy (default: 30 days)
    • Runs daily (1h after startup, then every 24h)
    • Configurable: database.retention_days (set to 0 to disable)
  • GUI Auto-Refresh System
    • Performance data updates every 3 seconds
    • Only active for open GUIs (no overhead)
    • Automatic cleanup on GUI close
    • Configurable: gui.auto_refresh
  • Trend Analysis for World Stats
    • Historical tracking (up to 288 snapshots = 24h @ 5min intervals)
    • Trend direction: INCREASING, DECREASING, STABLE
    • Change rate calculation (entities/hour)
    • Methods: recordSnapshot(), analyzeTrend(), analyzeTrendsForAllWorlds()
  • REST API for External Monitoring
    • 4 JSON endpoints: /api/health, /api/metrics, /api/worlds, /api/trends
    • API key authentication (Authorization: Bearer)
    • Perfect for Grafana/Prometheus dashboards
    • Config: api.enabled, api.port, api.key
  • Automatic Entity Cleaner
    • Smart entity management to prevent lag
    • Priority-based removal (items → projectiles → monsters → animals)
    • Protection for named entities, tamed animals, villagers
    • Boss mob blacklist (Ender Dragon, Wither, Warden)
    • Per-world and per-chunk limits
    • Dry-run mode for safe testing
    • Config: entity_cleaner.*

Changed

  • Movement Checker (MovementChecker.java)
    • Added environmental checks (slime blocks, bubble columns)
    • 2x vertical speed allowance near slime blocks/bubble columns
    • Enhanced cleanup method to include new tracking maps
  • XRay Detector (XRayDetector.java)
    • Added Y-level tracking for pattern analysis
    • New method: analyzeYLevelPattern()
    • New method: getOptimalYRange() with Minecraft 1.21 spawn data
    • Enhanced checkSuspiciousPattern() with Y-level analysis
  • Performance Drop Analyzer (PerformanceDropAnalyzer.java)
    • Replaced synchronous chunk analysis with async processing
    • Added analyzeChunkAsync() method using ChunkSnapshot
    • Legacy analyzeChunk() kept as fallback
    • Improved error handling for async operations
  • Database Manager (DatabaseManager.java)
    • Added auto-cleanup task for retention management
    • Enhanced shutdown procedure to cancel cleanup task
  • World Stats Manager (WorldStatsManager.java)
    • Added trend tracking infrastructure
    • New records: WorldStatsSnapshot, TrendAnalysis
    • Multiple helper methods for trend calculation
  • Performance GUI (PerformanceGUI.java)
    • Added auto-refresh system with task management
    • New InventoryCloseEvent handler for cleanup
    • New method: shutdown() for proper cleanup
  • Plugin Config (PluginConfig.java)
    • Added 10 new config methods for features
    • Auto-migration for all new config entries

Fixed

  • Memory leaks from incomplete cleanup (movement checker, XRay detector)
  • False-positives in movement detection from knockback
  • False-positives in movement detection from environmental effects
  • Main-thread bottleneck in chunk analysis

Performance

  • 90% reduction in main-thread load during performance drop analysis
  • Reduced false-positive alerts (less CPU overhead)
  • More efficient memory usage with automatic cleanup

Security

  • REST API authentication with API keys
  • SSRF protection in Discord webhook validation (from v2.2.0)
  • SQL injection prevention (from v2.2.0)
2.2.0Релиз1.21.9, 1.21.10, 1.21.11 · 6 января 2026 г.

[2.2.0] - 2026-01-05

🏗️ Major Release - Stability & Performance Update

This release focuses on security hardening, graceful degradation, performance optimizations, and critical bug fixes to ensure stable operation on production servers.

🔐 Security Hardening

SQL Injection Prevention

  • Type-Safe Database Queries
    • New TimeUnit enum for SQL time unit operations
    • Replaces dangerous string concatenation in DatabaseManager
    • Prevents SQL injection attacks via time-based queries
    • Enum values: SECOND, MINUTE, HOUR, DAY
    • Each value provides safe SQL name via getSqlNameUpper()

SSRF Protection

  • Discord Webhook URL Validation
    • Protocol validation: HTTPS-only (HTTP rejected)
    • Domain whitelist: Only discord.com and discordapp.com allowed
    • Path validation: Must start with /api/webhooks/
    • Prevents Server-Side Request Forgery attacks
    • Logs validation failures for security monitoring

Memory Leak Prevention

  • Size Limits on All Maps
    • XRayDetector.playerPlacedBlocks - Max size: 10,000 entries
    • XRayDetector.playerOreMines - NEW: Max size: 5,000 players
    • XRayDetector.playerStoneMines - NEW: Max size: 5,000 players
    • MovementChecker.moveCounter - Periodic reset at threshold
    • Automatic cleanup routines prevent unbounded growth
    • Warning logs when size limits are hit
    • Debug logging shows cleanup statistics and map sizes

💾 Graceful Degradation

FallbackLogger System

  • Automatic Database Failover
    • Queue-based async file writing (ConcurrentLinkedQueue)
    • CSV format: timestamp | type | value | description
    • Detects 3 consecutive database failures
    • Switches to file logging automatically
    • Configurable flush threshold (default: 100 entries)
    • File rotation and management
    • Fallback file path: plugins/PerformanceAnalyzer/fallback.log

Database Availability Monitoring

  • Failure Detection
    • isDatabaseAvailable() method for health checks
    • Consecutive failure counter
    • Automatic recovery detection (resets to DB logging)
    • Logs critical warnings when switching modes

Configuration

fallback_logging:
  enabled: true
  file: "plugins/PerformanceAnalyzer/fallback.log"

⚡ Performance & Reliability

AsyncConfigSaver (CRITICAL FIX)

  • Thread-Safe Config Operations
    • FIXED: Now uses Bukkit Scheduler instead of ForkJoinPool
    • CRITICAL: saveConfig() runs on main thread (Bukkit requirement)
    • Previously used CompletableFuture.runAsync() which caused ConcurrentModificationException
    • Uses CompletableFuture for async pattern
    • Atomic boolean flags prevent concurrent saves
    • saveAsync() schedules on main thread via runTask()
    • saveSyncOnShutdown() ensures data persistence on server stop
    • Error handling with exception logging and stack traces
    • Prevents thread-safety violations and data corruption

Performance Optimizations

  • Event Sampling - Movement checks reduced by ~90%

    • Only every 10th PlayerMoveEvent processed
    • OR significant distance (>2 blocks) always checked
    • Counter reset at 1000 to prevent overflow
    • Minimal detection accuracy loss
  • Database Indexing

    • Indexes on timestamp column for time-range queries
    • Indexes on type column for metric filtering
    • Significantly faster query performance
    • Auto-created during database initialization

Constants Class

  • Centralized Configuration
    • 255 lines of well-organized constants
    • Categories: Database, Discord, Movement, XRay, Performance, Vehicle Speeds
    • No more magic numbers scattered throughout codebase
    • Easy to tune and maintain
    • All values documented with comments

🏗️ Architecture Improvements

CommandRegistry System

  • Modular Command Registration
    • Replaces 112-line monster method in PerformanceAnalyzer
    • Separate methods for each category:
      • registerPerformanceCommands() - /perfstatus, /perfhistory, /perfreload
      • registerAnalysisCommands() - /worldstats, /entitystats, /chunkstats, /perfdrops
      • registerGUICommands() - /perfgui
      • registerAntiCheatCommands() - /acwhitelist, /xrayalerts, /movealerts, /xrayores
    • Easy to extend with new commands
    • Clean separation of concerns
    • AntiCheat commands dynamically registered when module enabled

ConfigMigrator Class

  • Extracted Migration Logic
    • Separate class for config version upgrades
    • Version-by-version migration (v0 → v1 → v2 → ... → v5)
    • Only runs when config_version < Constants.CONFIG_VERSION
    • Returns boolean if changes were made
    • Cleaner PluginConfig class (separation of concerns)
    • Easy to add new migrations

Public API

  • PerformanceAPI Interface
    • double getCurrentTPS() - Get current server TPS
    • double getCurrentMSPT() - Get current MSPT
    • boolean isPlayerSuspicious(UUID playerUUID) - Check if player flagged
    • Enables third-party plugin integration
    • Future: Additional methods for detailed performance data

🐛 Critical Bug Fixes

DatabaseManager Exception Handling

  • FIXED: Added missing stack traces to SQL exceptions
  • IMPROVED: Now logs failed SQL statements for debugging
  • ADDED: JavaDoc documentation for run() method
  • Better error messages for database initialization failures
  • Prevents silent failures during schema creation

XRayDetector Map Size Enforcement

  • FIXED: Unbounded memory growth in playerOreMines and playerStoneMines
  • ADDED: Hard limit of 5,000 player entries per map
  • IMPROVED: Cleanup task now removes empty playerStoneMines entries
  • Warning logs when size limit is exceeded
  • Debug output shows current map sizes

Config.yml Language Consistency

  • FIXED: All comments now in English (was mixed German/English)
  • Consistent with multi-language support design
  • User-facing messages still use language files (en.yml/de.yml)
  • Better for international plugin distribution

🔧 Code Quality Improvements

  • Consistent Error Handling - All exceptions logged with stack traces
  • English Logging - All console logs in English (user-facing messages use i18n)
  • Null Safety - Extensive null checks before operations
  • Improved Documentation - JavaDoc added to critical methods
  • Code Comments - All config comments translated to English

📦 New Files Created

  • util/Constants.java - Centralized constants
  • commands/CommandRegistry.java - Modular command registration
  • config/ConfigMigrator.java - Config migration logic
  • config/AsyncConfigSaver.java - Async config saves
  • db/FallbackLogger.java - Fallback file logging
  • db/TimeUnit.java - SQL-safe time units
  • api/PerformanceAPI.java - Public API interface

🔧 Modified Files

  • PerformanceAnalyzer.java - CommandRegistry integration, version update to 2.2.0
  • DatabaseManager.java - CRITICAL FIX: Stack traces, SQL logging, FallbackLogger, TimeUnit enum, failure detection
  • AsyncConfigSaver.java - CRITICAL FIX: Thread-safety with Bukkit Scheduler
  • PluginConfig.java - AsyncConfigSaver, ConfigMigrator, fallback config methods
  • DiscordWebhook.java - URL validation, SSRF protection
  • MovementChecker.java - Constants usage, event sampling
  • XRayDetector.java - CRITICAL FIX: Size limits (5000 players), improved cleanup, memory leak prevention
  • Constants.java - NEW: XRAY_MAX_PLAYER_ENTRIES constant
  • config.yml - FIXED: All comments translated to English
  • pom.xml - Version 2.2.0

⚠️ Breaking Changes

None - This release is fully backward compatible with v2.1.0.

  • All new features have sensible defaults
  • Existing configs auto-migrate
  • No database schema changes
  • No API changes to existing methods

📊 Configuration Changes

New Config Sections:

# Graceful Degradation 
fallback_logging:
  enabled: true
  file: "plugins/PerformanceAnalyzer/fallback.log"

Auto-Migration:

  • Config auto-migrates from v5 to v5 (no version bump needed)
  • New fallback_logging section added automatically
  • Existing settings preserved

🔄 Migration Guide (from v2.1.0)

  1. Backup - Backup your plugins/PerformanceAnalyzer/ folder
  2. Stop Server - Stop your server
  3. Replace JAR - Replace old JAR with PerformanceAnalyzer-2.2.0.jar
  4. Start Server - Start your server
  5. Auto-Migration - Config auto-updates (check console for "Config migrated")
  6. Verify - Run /perfstatus to ensure plugin loaded correctly

Optional Post-Migration:

  • Review fallback logging settings in config.yml
  • Check fallback.log file (created only on database failure)

📈 Performance Impact

  • CPU Usage: Reduced ~90% for movement checks (event sampling)
  • Memory Usage: Lower (cleanup routines, size limits)
  • Disk I/O: Reduced (async config saves, fallback only on failure)
  • Database Load: Reduced (batching, indexing)
  • Startup Time: Unchanged

🐛 Known Issues

None - All known issues from v2.1.0 have been resolved, including:

  • ✅ AsyncConfigSaver thread-safety violation (ConcurrentModificationException)
  • ✅ DatabaseManager silent failures (missing stack traces)
  • ✅ XRayDetector unbounded memory growth (5000+ players)
  • ✅ Config.yml mixed language comments (now all English)

2.0.0Релиз1.21.9, 1.21.10, 1.21.11 · 18 декабря 2025 г.

v2.0.0 (18.02.2025) - Major Release

Why Version 2.0? This release fundamentally transforms PerformanceAnalyzer from a simple monitoring tool into an intelligent lag diagnosis system. With 4 new classes, a completely redesigned GUI, and groundbreaking lag source detection, this is more than just new features—it's a new generation of the plugin.

Major New Features:

  • 🎯 Lag Source Detection - Automatically identifies what's causing lag

    • Player Activity Tracking - Monitors player actions (blocks, movements, commands, interactions)
    • Plugin Performance Analysis - Identifies suspect plugins by event listeners and task count
    • Integrated with Performance Drops - Lag sources are shown in /perfdrops reports
    • Shows top 5 most active players during performance drops
    • Shows top 5 suspect plugins with risk scores
    • Weighted activity scoring (breaking blocks = higher weight than walking)
    • Detects "heavy" plugins (WorldEdit, FAWE, CoreProtect, etc.)
  • 🚨 Restricted World Zones - Instant alerts for specific worlds

    • Configure worlds as "restricted zones" for mining monitoring
    • Option to monitor specific ores or all ores in restricted worlds
    • Instant alerts when players mine ores in restricted zones (no threshold needed)
    • Perfect for protecting areas or catching suspicious behavior
    • New config: anticheat.restricted_worlds and anticheat.restricted_world_ores
    • Logs to database with type anticheat_restricted_zone

Critical Bugfixes:

  • ✅ Fixed missing imports in PerformanceAnalyzer.java (Player, UUID)
  • ✅ Fixed MySQL incompatibility - AUTOINCREMENT vs AUTO_INCREMENT
  • ✅ Fixed MySQL datetime syntax - All time-based queries now work with MySQL
    • getRecentMspt() - Fixed
    • getAverageByType() - Fixed
    • countPerformanceSpikes() - Fixed
    • cleanOldData() - Fixed
  • ✅ Plugin now fully compatible with both SQLite AND MySQL

Improvements:

  • 🔧 Configurable Performance Thresholds - All lag detection thresholds are now customizable
    • Chunk thresholds: tile entities, redstone, entities (warning/critical)
    • World health thresholds: entity warning/critical levels
    • Plugin risk score interpretation: low/medium/high boundaries
    • Prevents false positives on servers with different hardware
    • Config includes recommendations for standard/powerful/weak servers
    • Allows fine-tuning based on your specific server needs
  • Movement detection now properly distinguishes between walking and sprinting
  • XRay detector properly handles ore blocks (not items)
  • Better null-safety in configuration migration
  • Improved performance drop reports with lag source attribution
  • Version compatibility updated: Paper 1.21.x (all 1.21 versions)

🔥 Performance Optimizations:

  • Movement Sampling - PlayerMove events only processed every 10th occurrence or >2 blocks distance (~90% reduction)
  • Chunk Analysis Timeout - Configurable timeout (default 5s) prevents long-running chunk scans
  • Self-Monitoring - Plugin measures and warns about its own performance impact
  • Config Options - All lag analysis features can be disabled independently
  • Memory Cleanup - Automatic cleanup on player quit prevents memory leaks
  • New Config Section: lag_analysis with player_tracking, plugin_analysis, chunk_analysis_timeout_ms

🎨 GUI Improvements:

  • 🆕 Lag-Analyse GUI Page - Interactive page showing active players and suspect plugins
    • Top 5 most active players with detailed breakdown
    • Top 5 suspect plugins with risk scores
    • Refresh and clear data buttons
    • Config-aware (shows warnings if features disabled)
  • 🆕 Performance Drops GUI Page - Browse and click drops for detailed reports
    • Visual list of 21 recent drops
    • Color-coded by severity (Red/Orange/Yellow)
    • Click any drop for full report in chat
    • Shows lag source previews
  • Expanded Main GUI - Now 2 rows of features instead of 1
    • Database Info button
    • World Stats quick-link
    • Better organization
  • Multi-page Navigation - Consistent back buttons between pages

New Classes:

  • PlayerActivityTracker - Monitors player actions in real-time (with sampling)
  • PluginTimingsAnalyzer - Analyzes plugin performance impact
  • LagAnalysisGUI - GUI page for lag source inspection
  • PerformanceDropsGUI - GUI page for drop history browsing

Комментарии

Загружаем…