Skip to content

A professional grade hybrid monitoring solution for FXServer (FiveM/RedM) featuring modular architecture, automatic version checking, and intelligent Discord alerting.

License

Notifications You must be signed in to change notification settings

ByteBrushStudios/SpikeGuard

Repository files navigation

🛡️ SpikeGuard - Advanced FXServer Performance Monitor

Version Node.js FXServer Discord.js License Modular

A professional-grade hybrid monitoring solution for FXServer (FiveM/RedM) featuring modular architecture, automatic version checking, and intelligent Discord alerting.

📚 Documentation🚀 Quick Start⚙️ Configuration� Modular Architecture�🐛 Troubleshooting

Caution

This resource is not yet ready for production use and is only public at this stage for transparency. Please check back soon for the full release :D


🌟 Overview

SpikeGuard is a comprehensive monitoring system designed specifically for FXServer environments. Unlike simple webhook-based solutions, SpikeGuard provides:

  • 🔍 Real-time Performance Monitoring - Track memory usage, hitch warnings, and player counts with precision
  • 🤖 Intelligent Discord Integration - Advanced embed notifications with cooldown protection and smart alerting
  • 📊 Automatic Profiler Dumps - Capture detailed performance data when thresholds are exceeded
  • ⚡ Low-latency Communication - File-based JSON communication for reliable data exchange
  • 🛠️ Production-ready - Robust error handling, logging, and monitoring capabilities
  • 🔄 Automatic Version Checking - Stay updated with the latest releases from GitHub
  • 🧩 Modular Architecture - Clean, maintainable code with separated concerns

� What's Included

🧩 Modular Architecture

  • Separated Concerns: Each component (performance, profiler, file management, version checking) is now a separate module
  • Better Maintainability: Easier to update, debug, and extend individual components
  • Improved Testing: Each module can be tested independently
  • Cleaner Code: Reduced complexity in the main monitoring script

🔄 Automatic Version Checking

  • GitHub Integration: Automatically checks for new releases from GitHub repository
  • Update Notifications: Console alerts when newer versions are available
  • Manual Checks: spikeguard:version command for on-demand version checking
  • Version Info: Export function to get current and latest version information

📊 Enhanced Monitoring

  • Performance Analysis: Automatic analysis of performance data with severity levels
  • Trend Tracking: Historical performance data with trends analysis
  • Better Statistics: Enhanced console commands with detailed system information
  • Improved Profiler: More comprehensive profiler dumps with system information

�🎯 Key Features

🔧 FXServer Monitoring (Lua) - Now Modular!

  • Memory Tracking: Precise memory usage monitoring (0.01MB accuracy)
  • Hitch Detection: Real-time frame time spike detection with configurable thresholds
  • Player Monitoring: Track connected players and server capacity
  • Server Metrics: Uptime, resource count, and performance state tracking
  • Consecutive Spike Detection: Identify performance patterns and trends
  • Console Commands: Enhanced manual control with detailed statistics
  • Export Functions: Extended integration with version and performance state exports
  • Performance Analysis: Automatic analysis with recommendations and severity levels

🤖 Discord Bot (Node.js)

  • File Watcher: Real-time monitoring using chokidar for instant updates
  • Smart Alerting: Multi-level alerts (warning/critical) with spam protection
  • Rich Embeds: Professional Discord embeds with color coding and comprehensive data
  • Cooldown System: Prevents alert spam with configurable cooldown periods
  • Slash Commands: Ready-to-extend framework for Discord interactions
  • Error Recovery: Robust error handling with automatic reconnection

📊 Data & Analytics

  • JSON Status Files: Human-readable status tracking with timestamps
  • Profiler Integration: Automatic profiler dumps with detailed server metrics
  • Log Management: Comprehensive logging with configurable levels
  • Performance History: Track server performance over time
  • Threshold Monitoring: Configurable warning and critical thresholds

🧩 Modular Architecture

SpikeGuard introduces a completely modular architecture for better maintainability and extensibility:

📁 Module Structure

fx/modules/
├── 🔄 version.lua      # Version checking and update notifications  
├── 📊 performance.lua  # Performance data collection and analysis
├── 💾 profiler.lua     # Profiler dump generation and management
└── 📁 filemanager.lua  # File operations and status management

🔧 Module Responsibilities

Version Manager (version.lua)

  • 🔍 GitHub API Integration: Checks for latest releases automatically
  • 📢 Update Notifications: Console alerts when updates are available
  • 🕐 Scheduled Checks: Hourly version checks with rate limiting
  • 📊 Version Info Export: Provides version data to other modules
-- Example: Get version information
local versionInfo = exports.spikeguard:GetVersionInfo()
print("Current: " .. versionInfo.current)
print("Latest: " .. versionInfo.latest) 
print("Update Available: " .. tostring(versionInfo.update_available))

Performance Monitor (performance.lua)

  • 📈 Data Collection: Memory, hitch, player count, and server metrics
  • 🔍 Performance Analysis: Automatic issue detection with severity levels
  • 📊 Trend Tracking: Historical data with 100-entry rolling window
  • 🎯 Smart Thresholds: Consecutive hitch detection and pattern analysis
-- Example: Get performance analysis
local perfState = exports.spikeguard:GetPerformanceState()
print("Consecutive Hitches: " .. perfState.consecutive_hitches)
print("History Entries: " .. perfState.history_size)

Profiler Manager (profiler.lua)

  • 💾 Automatic Dumps: Triggered by performance thresholds
  • 🛡️ Cooldown Protection: Prevents spam with 30-second intervals
  • 📋 Comprehensive Data: Server info, resource list, and system metrics
  • 🔧 FXServer Integration: Attempts to trigger built-in profiler commands

File Manager (filemanager.lua)

  • 📁 Safe File Operations: Error-resistant read/write operations
  • 🔍 Directory Management: Auto-creation and validation
  • Data Validation: JSON structure and type checking
  • 📊 File Statistics: Size, validity, and accessibility monitoring

🎯 Benefits of Modular Design

  • 🔧 Easy Maintenance: Update individual components without affecting others
  • 🧪 Better Testing: Each module can be tested independently
  • 📈 Scalability: Add new features without modifying core logic
  • 🐛 Isolation: Bugs in one module don't crash the entire system
  • 📚 Code Clarity: Clear separation of concerns and responsibilities

🔄 Module Communication

Modules communicate through:

  • 📞 Direct Function Calls: For data retrieval and processing
  • 📡 Event System: For notifications and state changes
  • 📊 Shared Data Structures: For consistent data formats
-- Example: Module interaction
TriggerEvent('spikeguard:updateAvailable', {
    current = "1.0.0",
    latest = "1.0.1",
    info = updateInfo
})

🚀 Quick Start Guide

Prerequisites

Before installing SpikeGuard, ensure you have:

  • FXServer: Running FiveM or RedM server with resource loading capabilities
  • Node.js: Version 16.9.0 or higher (Download here)
  • Discord Bot: Created via Discord Developer Portal
  • File Permissions: Write access to server directories
  • Network Access: Internet connection for Discord API

⚡ Express Setup (5 minutes)

  1. Download & Extract

    git clone https://github.com/your-repo/spikeguard.git
    cd spikeguard
  2. Install Dependencies

    cd bot
    npm install
  3. Configure Discord Bot

    • Copy bot/config.example.json to bot/config.json
    • Add your Discord bot token and channel ID
  4. Deploy FXServer Resource

    • Copy fx/ folder to your server's resources/spikeguard/
    • Add ensure spikeguard to your server.cfg
  5. Start Everything

    # Start your FXServer
    # Then run the bot
    npm start

📋 Detailed Installation

1️⃣ FXServer Resource Setup

Step 1: Copy Resource Files

# Copy the fx/ folder to your server resources
cp -r ./fx /path/to/your/fxserver/resources/spikeguard

# Windows users:
# Copy fx\ to C:\YourFXServer\resources\spikeguard\

Step 2: Configure server.cfg Add to your server.cfg:

# Essential resources first
ensure mapmanager
ensure chat
ensure spawnmanager

# Add SpikeGuard
ensure spikeguard

# Optional: Add after other monitoring tools

Step 3: Configure Thresholds Edit resources/spikeguard/config.lua:

-- Adjust for your server specifications
Config.Thresholds = {
    HitchWarning = 150,    -- ms (stricter for high-performance servers)
    MemoryWarning = 800,   -- MB (adjust based on your server RAM)
    CriticalHitch = 300,   -- ms
    CriticalMemory = 1200  -- MB
}

-- Enable debug mode for initial testing
Config.Debug = true

2️⃣ Discord Bot Setup

Step 1: Create Discord Application

  1. Visit Discord Developer Portal
  2. Click "New Application" → Name it "SpikeGuard"
  3. Go to "Bot" section → Click "Add Bot"
  4. Copy the Bot Token (keep this secure!)
  5. Enable "Message Content Intent" under Privileged Gateway Intents

Step 2: Invite Bot to Server

Generate invite URL with required permissions:

https://discord.com/api/oauth2/authorize?client_id=YOUR_CLIENT_ID&permissions=277025458176&scope=bot%20applications.commands

Required permissions:

  • ✅ Send Messages
  • ✅ Use Slash Commands
  • ✅ Embed Links
  • ✅ Read Message History
  • ✅ Use External Emojis

Step 3: Configure Bot Settings

Copy the example configuration:

cd bot
cp config.example.json config.json

Edit config.json:

{
  "discord": {
    "token": "YOUR_BOT_TOKEN_HERE",
    "clientId": "YOUR_CLIENT_ID",
    "guildId": "YOUR_SERVER_ID", 
    "channelId": "YOUR_MONITORING_CHANNEL_ID"
  },
  "thresholds": {
    "memory": {
      "warning": 800,     // MB - Adjust to match FXServer config
      "critical": 1200    // MB
    },
    "hitch": {
      "warning": 150,     // ms - Adjust to match FXServer config  
      "critical": 300     // ms
    }
  }
}

Step 4: Install Dependencies & Test

# Install Node.js dependencies
npm install

# Run test suite to validate configuration
npm test

# If tests pass, start the bot
npm start

⚙️ Configuration

🔧 FXServer Configuration (fx/config.lua)

-- Monitoring frequency (milliseconds)
Config.MonitorInterval = 5000  -- 5 seconds (recommended)

-- Performance thresholds
Config.Thresholds = {
    HitchWarning = 200,     -- Frame time spike warning (ms)
    MemoryWarning = 600,    -- Memory usage warning (MB)
    CriticalHitch = 500,    -- Critical frame time spike (ms)
    CriticalMemory = 1000   -- Critical memory usage (MB)
}

-- Profiler settings
Config.Profiler = {
    AutoDump = true,        -- Automatically dump profiler data
    DumpOnHitch = true,     -- Dump when hitch threshold exceeded
    DumpThreshold = 200     -- Hitch threshold for profiler dump (ms)
}

-- Advanced settings
Config.Advanced = {
    ConsecutiveHitchThreshold = 3,  -- Consecutive hitches before escalation
    MemoryCheckInterval = 10,       -- Garbage collection frequency
    EnableDetailedMetrics = true    -- Collect additional server metrics
}

-- Debug mode (disable in production)
Config.Debug = false

🤖 Discord Bot Configuration (bot/config.json)

{
  "discord": {
    "token": "YOUR_BOT_TOKEN",
    "clientId": "YOUR_CLIENT_ID", 
    "guildId": "YOUR_SERVER_ID",
    "channelId": "YOUR_CHANNEL_ID"
  },
  "monitoring": {
    "statusFile": "../shared/status.json",
    "checkInterval": 2000,    // File check frequency (ms)
    "cooldownTime": 60000     // Alert cooldown (ms)
  },
  "thresholds": {
    "memory": {
      "warning": 600,         // Must match FXServer config
      "critical": 1000
    },
    "hitch": {
      "warning": 200,         // Must match FXServer config
      "critical": 500
    }
  },
  "alerts": {
    "enabled": true,
    "mentionRole": "@ServerAdmins",  // Optional role to mention
    "embedColors": {
      "warning": "#FFA500",   // Orange for warnings
      "critical": "#FF0000",  // Red for critical alerts
      "info": "#00FF00"       // Green for status
    }
  },
  "logging": {
    "enabled": true,
    "level": "info",          // debug, info, warn, error
    "logDir": "../logs/"
  }
}

🖥️ Hosting & Deployment

🔄 Development Environment

Testing Locally:

# Run FXServer with SpikeGuard resource
# In separate terminal:
cd bot
npm run dev  # Uses nodemon for auto-restart

Validate Setup:

npm test           # Run test suite
npm run validate   # Test + validation

🌐 Production Deployment

Option 1: PM2 Process Manager (Recommended)

# Install PM2 globally
npm install -g pm2

# Start bot with PM2
cd bot
pm2 start index.js --name "spikeguard-bot"

# Configure auto-restart on server reboot
pm2 startup
pm2 save

# Monitor the process
pm2 status
pm2 logs spikeguard-bot

PM2 Ecosystem File (ecosystem.config.js):

module.exports = {
  apps: [{
    name: 'spikeguard-bot',
    script: 'index.js',
    cwd: './bot',
    instances: 1,
    autorestart: true,
    watch: false,
    max_memory_restart: '200M',
    env: {
      NODE_ENV: 'production'
    },
    error_file: '../logs/bot-error.log',
    out_file: '../logs/bot-out.log',
    log_file: '../logs/bot-combined.log'
  }]
};

Option 2: Docker Deployment

Dockerfile:

FROM node:18-alpine

WORKDIR /app
COPY bot/package*.json ./
RUN npm ci --only=production

COPY bot/ .
COPY shared/ ../shared/
COPY logs/ ../logs/

USER node
CMD ["node", "index.js"]

docker-compose.yml:

version: '3.8'
services:
  spikeguard-bot:
    build: .
    restart: unless-stopped
    volumes:
      - ./shared:/app/shared
      - ./logs:/app/logs
      - ./profiler:/app/profiler
    environment:
      - NODE_ENV=production

Option 3: Systemd Service (Linux)

Create /etc/systemd/system/spikeguard.service:

[Unit]
Description=SpikeGuard Discord Bot
After=network.target

[Service]
Type=simple
User=your-user
WorkingDirectory=/path/to/spikeguard/bot
ExecStart=/usr/bin/node index.js
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target

Enable and start:

sudo systemctl enable spikeguard
sudo systemctl start spikeguard
sudo systemctl status spikeguard

🏠 VPS/Cloud Hosting Recommendations

Minimum Requirements:

  • CPU: 1 vCore
  • RAM: 512MB (1GB recommended)
  • Storage: 5GB SSD
  • Network: Stable internet connection

Recommended Providers:

  • DigitalOcean: $5/month droplet
  • AWS EC2: t3.micro free tier eligible
  • Google Cloud: e2-micro free tier
  • Linode: $5/month nanode
  • Vultr: $2.50/month VPS

📊 Usage & Monitoring

🎮 FXServer Console Commands

# 📊 Detailed status report with performance analysis
spikeguard:status
# Shows: Memory, hitch time, players, uptime, consecutive hitches,
#        profiler stats, version info, and performance issues

# 💾 Force profiler dump (bypasses cooldown)
spikeguard:dump
# Immediately creates a profiler dump with current performance data

# 🔄 Reload configuration and reset state
spikeguard:reload
# Resets performance monitor state and reloads configuration

# 🔍 Check for updates manually
spikeguard:version
# Manually triggers version check against GitHub releases

# 📈 System statistics and trends
spikeguard:stats
# Shows: File system status, performance history, trends,
#        profiler statistics, and monitoring health

Example Output:

[SpikeGuard Status Report]
Version: v1.0.0 (Up to date)
Memory Usage: 487.3 MB
Hitch Time: 23 ms
Players Online: 45
Server Uptime: 7245 seconds
Consecutive Hitches: 0
Profiler Dumps: 3 total
Monitoring Cycles: 1449

Recent Trends (15 minutes):
  Average Memory: 456.7 MB
  Average Hitch: 31.2 ms
  Max Hitch: 156 ms

🤖 Discord Commands

# Check server status (coming soon)
/spikeguard status

# View recent alerts
/spikeguard history

# Configure thresholds
/spikeguard config

📈 Understanding Alerts

Warning Level (🟡):

  • Memory usage: 600-999 MB
  • Hitch time: 200-499 ms
  • Action: Monitor closely

Critical Level (🔴):

  • Memory usage: 1000+ MB
  • Hitch time: 500+ ms
  • Action: Immediate investigation required

Profiler Dumps (🔥):

  • Automatically generated on performance spikes
  • Contains detailed server metrics
  • Saved to profiler/ directory with timestamps

📁 File Structure Overview

SpikeGuard/
├── 📁 fx/                          # FXServer Lua Resource
│   ├── 📄 fxmanifest.lua           # Resource manifest
│   ├── 📄 config.lua               # Server configuration
│   └── 📄 performance_monitor.lua  # Main monitoring script
├── 📁 bot/                         # Discord Bot (Node.js)
│   ├── 📄 index.js                 # Main bot application
│   ├── 📄 package.json             # Dependencies & scripts
│   ├── 📄 config.json              # Bot configuration
│   ├── 📄 test.js                  # Test suite
│   └── 📁 utils/
│       └── 📄 embedBuilder.js      # Discord embed utilities
├── 📁 shared/                      # Communication Layer
│   └── 📄 status.json              # Real-time server status
├── 📁 logs/                        # Log Files
│   └── 📄 spikeguard-YYYY-MM-DD.log
├── 📁 profiler/                    # Performance Dumps
│   └── 📄 profiler-YYYY-MM-DDTHH-MM-SS.json
├── 📄 start-bot.bat               # Windows startup script
├── 📄 start-bot.sh                # Linux startup script
├── 📄 DEPLOYMENT.md               # Detailed deployment guide
└── 📄 README.md                   # This file

🔧 Advanced Configuration

🎛️ Performance Tuning

High-Performance Servers:

-- Stricter monitoring for better performance
Config.MonitorInterval = 3000  -- Check every 3 seconds
Config.Thresholds = {
    HitchWarning = 100,        -- Very strict hitch detection
    MemoryWarning = 400,       -- Lower memory threshold
    CriticalHitch = 200,
    CriticalMemory = 800
}

Resource-Constrained Servers:

-- Relaxed monitoring to reduce overhead
Config.MonitorInterval = 10000  -- Check every 10 seconds
Config.Thresholds = {
    HitchWarning = 300,         -- More lenient thresholds
    MemoryWarning = 1000,
    CriticalHitch = 600,
    CriticalMemory = 1500
}

🔧 Custom Resource Integration

🔧 Custom Resource Integration

Enhanced Export Functions:

-- Basic performance data
local memoryUsage = exports.spikeguard:GetMemoryUsage()
local hitchTime = exports.spikeguard:GetHitchWarning()
local playerCount = exports.spikeguard:GetPlayersCount()
local serverUptime = exports.spikeguard:GetServerUptime()

-- Advanced monitoring data
local serverMetrics = exports.spikeguard:GetServerMetrics()
local performanceState = exports.spikeguard:GetPerformanceState()

-- Version information
local versionInfo = exports.spikeguard:GetVersionInfo()
print("SpikeGuard version: " .. versionInfo.current)
if versionInfo.update_available then
    print("Update available: " .. versionInfo.latest)
end

-- Force profiler dump
local dumpSuccess = exports.spikeguard:ForceProfilerDump()

Performance State Data:

local perfState = exports.spikeguard:GetPerformanceState()
-- Contains:
-- - consecutive_hitches: Number of consecutive performance issues
-- - last_hitch_time: Previous hitch measurement
-- - history_size: Number of stored performance entries
-- - trends: Performance trends over time (if available)
-- - uptime_seconds: Server uptime

Event Integration (New Events):

-- Listen for version updates
AddEventHandler('spikeguard:updateAvailable', function(updateInfo)
    print('SpikeGuard update available:')
    print('Current: ' .. updateInfo.current)
    print('Latest: ' .. updateInfo.latest)
    print('Download: ' .. updateInfo.info.url)
end)

-- Listen for profiler dumps
AddEventHandler('spikeguard:profilerDumped', function(dumpInfo)
    print('Profiler dump created: ' .. dumpInfo.filename)
    print('Trigger: ' .. dumpInfo.trigger)
    print('Total dumps: ' .. dumpInfo.dump_count)
end)

-- Listen for status file updates
AddEventHandler('spikeguard:statusFileUpdated', function(fileInfo)
    print('Status file updated: ' .. fileInfo.timestamp)
    print('Data size: ' .. fileInfo.data_size .. ' bytes')
end)

-- Request current status (enhanced response)
TriggerEvent('spikeguard:requestStatus')
AddEventHandler('spikeguard:statusResponse', function(statusData)
    -- Now includes version_info and performance_state
    print('Performance State:', json.encode(statusData.performance_state))
    print('Version Info:', json.encode(statusData.version_info))
end)

Real-world Integration Example:

-- Example: Performance-based server announcements
CreateThread(function()
    while true do
        local perfState = exports.spikeguard:GetPerformanceState()
        
        if perfState.consecutive_hitches >= 3 then
            TriggerClientEvent('chat:addMessage', -1, {
                args = {'Server', 'Experiencing performance issues, please be patient...'}
            })
        end
        
        Wait(30000) -- Check every 30 seconds
    end
end)

-- Example: Auto-restart protection
AddEventHandler('spikeguard:profilerDumped', function(dumpInfo)
    if dumpInfo.trigger == 'hitch_threshold_exceeded' then
        -- Log critical performance issue
        local timestamp = os.date('%Y-%m-%d %H:%M:%S')
        local logEntry = string.format('[%s] Critical performance issue detected - Dump: %s', 
            timestamp, dumpInfo.filename)
        
        -- You could implement auto-restart logic here
        print('^1[AUTO-RESTART]^7 ' .. logEntry)
    end
end)

🐛 Troubleshooting

❌ Common Issues & Solutions

FXServer Resource Issues

Problem: Resource not starting

# Check server console for errors
# Ensure folder name matches: resources/spikeguard/

# Verify server.cfg entry
ensure spikeguard

# Check file permissions (Linux)
chmod -R 755 resources/spikeguard/

Problem: No status.json file created

-- Enable debug mode in config.lua
Config.Debug = true

-- Check shared directory permissions
-- Ensure relative path is correct

Problem: Profiler dumps not generating

# Test manual dump in server console
spikeguard:dump

# Check profiler directory permissions
# Verify threshold settings in config.lua

Discord Bot Issues

Problem: Bot not connecting

# Verify bot token in config.json
# Check internet connectivity
# Ensure bot has required permissions

# Test with minimal config
npm test

Problem: No alerts received

# Check file watcher status
# Verify channel permissions
# Test threshold settings
# Check console for errors

# Manual threshold test
node -e "
const config = require('./config.json');
console.log('Thresholds:', config.thresholds);
"

Problem: Alert spam

// Increase cooldown time in config.json
{
  "monitoring": {
    "cooldownTime": 300000  // 5 minutes
  }
}

🔍 Debug Mode

Enable verbose logging:

FXServer (config.lua):

Config.Debug = true

Discord Bot (config.json):

{
  "logging": {
    "enabled": true,
    "level": "debug"
  }
}

Log File Locations:

  • FXServer: Server console output
  • Discord Bot: logs/spikeguard-YYYY-MM-DD.log
  • Status Data: shared/status.json
  • Profiler Data: profiler/profiler-*.json

📞 Getting Help

  1. Check Logs: Always start with log files
  2. Run Tests: Use npm test to validate configuration
  3. Console Commands: Use spikeguard:status for diagnostics
  4. Debug Mode: Enable verbose logging
  5. Community: Join our Discord server for support

🛡️ Security Considerations

🔐 Bot Token Security

DO NOT:

  • ❌ Commit bot tokens to git repositories
  • ❌ Share tokens in screenshots or logs
  • ❌ Use tokens in publicly accessible files

DO:

  • ✅ Use environment variables for tokens
  • ✅ Restrict bot permissions to minimum required
  • ✅ Regularly rotate bot tokens
  • ✅ Use .gitignore to exclude config files

Environment Variable Setup:

# Linux/macOS
export DISCORD_BOT_TOKEN="your_token_here"
export DISCORD_CHANNEL_ID="your_channel_id"

# Windows
set DISCORD_BOT_TOKEN=your_token_here
set DISCORD_CHANNEL_ID=your_channel_id

Modified config.json:

{
  "discord": {
    "token": "${DISCORD_BOT_TOKEN}",
    "channelId": "${DISCORD_CHANNEL_ID}"
  }
}

🛡️ Server Security

  • File Permissions: Restrict write access to SpikeGuard directories
  • Network Security: Use firewalls to protect Discord bot traffic
  • Resource Isolation: Run bot as non-privileged user
  • Regular Updates: Keep Node.js and dependencies updated

🔄 Maintenance & Updates

📅 Regular Maintenance Tasks

Weekly:

  • Review generated profiler dumps
  • Check log file sizes and rotate if needed
  • Monitor alert frequency and adjust thresholds

Monthly:

  • Update Node.js dependencies: npm update
  • Review server performance trends
  • Clean old profiler dumps: find profiler/ -mtime +30 -delete

Quarterly:

  • Update Discord.js library
  • Review and optimize threshold settings
  • Backup configuration files

🔄 Update Procedure

  1. Backup Configuration

    cp bot/config.json bot/config.json.backup
    cp fx/config.lua fx/config.lua.backup
  2. Update Dependencies

    cd bot
    npm update
    npm audit fix
  3. Test Updates

    npm test
    npm run validate
  4. Deploy Updates

    # Restart FXServer resource
    # Restart Discord bot
    pm2 restart spikeguard-bot

📈 Performance Metrics

📊 Expected Performance

FXServer Resource:

  • Memory Usage: <5MB additional overhead
  • CPU Impact: <1% during monitoring cycles
  • Disk I/O: Minimal (status file updates every 5s)

Discord Bot:

  • Memory Usage: 50-100MB typical
  • CPU Usage: <1% during normal operation
  • Network: ~1KB per alert, minimal during idle

File Sizes:

  • Status file: ~1KB (updated every 5s)
  • Profiler dumps: 5-50KB each (created on spikes)
  • Log files: 1-10MB per day (depending on activity)

🎯 Performance Baselines

Healthy Server (Typical Values):

  • Memory Usage: 200-600MB
  • Hitch Time: 15-100ms
  • Players Online: Variable
  • Consecutive Hitches: 0-2

Warning Indicators:

  • Memory consistently >600MB
  • Hitch times frequently >200ms
  • Multiple consecutive hitches
  • Profiler dumps every few minutes

Critical Indicators:

  • Memory >1000MB sustained
  • Hitch times >500ms regularly
  • Continuous performance degradation
  • Server instability or crashes

🤝 Contributing

🔧 Development Setup

# Clone repository
git clone https://github.com/ByteBrushStudios/SpikeGuard.git
cd spikeguard

# Install dependencies
cd bot && npm install

# Set up development environment
cp config.example.json config.json
# Edit config.json with test bot credentials

# Run tests
npm test

# Start development server
npm run dev

📝 Code Style

  • JavaScript: Use ESLint with standard configuration
  • Lua: Follow FXServer scripting conventions
  • Documentation: Update README for any configuration changes
  • Testing: Add tests for new features

🐛 Bug Reports

When reporting bugs, include:

  • SpikeGuard version
  • FXServer version and OS
  • Node.js version
  • Complete error logs
  • Steps to reproduce
  • Configuration files (remove sensitive data)

💡 Feature Requests

We welcome feature requests! Consider:

  • Performance impact on FXServer
  • Discord API limitations
  • Cross-platform compatibility
  • Backward compatibility

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments

  • CFX Team - For the excellent server platform
  • Discord.js - For the robust Discord API library
  • Node.js Community - For the ecosystem and tools
  • FiveM/RedM Community - For feedback and testing

📞 Support & Community


Made with ❤️ for the FiveM and RedM communities

Star this repository if SpikeGuard helps your server!

🔝 Back to top

About

A professional grade hybrid monitoring solution for FXServer (FiveM/RedM) featuring modular architecture, automatic version checking, and intelligent Discord alerting.

Resources

License

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Sponsor this project