### Setup Dummy App Dependencies Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/README.md Install gems and set up the database for the dummy application used for testing. ```bash cd test/dummy && bundle install && rails db:create && rails db:migrate ``` -------------------------------- ### Install Optional System Monitoring Gems Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/CONFIGURATION-GUIDE.md To enable system monitoring features, install the required optional gems and run `bundle install`. ```bash gem 'sys-filesystem' gem 'sys-cpu' gem 'get_process_mem' bundle install ``` -------------------------------- ### Install Dependencies Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/README.md Run bundle install to install the necessary Ruby gems for the project. ```bash bundle install ``` -------------------------------- ### Start Rails Server Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/README.md Run the Rails server to start the application. ```bash rails s ``` -------------------------------- ### Minimal Rails Performance Setup Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/CONFIGURATION-GUIDE.md Configure the minimal setup for Rails Performance, including Redis connection and enabling the gem. ```ruby # config/initializers/rails_performance.rb if defined?(RailsPerformance) RailsPerformance.setup do |config| config.redis = Redis.new(url: ENV["REDIS_URL"] || "redis://localhost:6379/0") config.enabled = true end end ``` -------------------------------- ### RailsPerformance Setup Block Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-configuration.md The `setup` block yields the `RailsPerformance` module for configuration. It must be guarded with `if defined?(RailsPerformance)`. ```ruby RailsPerformance.setup do |config| config.redis = Redis.new(url: ENV["REDIS_URL"]) config.duration = 4.hours config.enabled = true # ... more configuration end ``` -------------------------------- ### start_monitoring Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-extensions.md Starts a background thread to periodically measure system resource usage every 60 seconds. ```APIDOC ## start_monitoring ### Description Starts a background thread to periodically measure system resource usage every 60 seconds. ### Method ```ruby monitor.start_monitoring ``` ### Return nil ``` -------------------------------- ### Card Widget Usage Example Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-widgets.md Example of creating a collection and instantiating a P50Card widget. ```ruby collection = RailsPerformance::DataSource.new(type: :requests).db card = RailsPerformance::Widgets::P50Card.new(collection) ``` -------------------------------- ### Redis Key Format Example Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/README.md Illustrates the pipe-delimited identifier format used for keys in Redis. ```text performance|controller|HomeController|action|index|...|datetimei|1718900600|request_id|{id}|END|1.0.2 ``` -------------------------------- ### Example: Iterate and Display Slow Requests Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-reports.md Demonstrates how to initialize a SlowRequestsReport and iterate through its data to display details of slow requests. ```ruby db = RailsPerformance::DataSource.new(type: :requests).db report = SlowRequestsReport.new(db) report.data.each do |req| puts "SLOW: #{req[:controller]}##{req[:action]} took #{req[:duration].round(1)}ms" end ``` -------------------------------- ### RailsPerformance Setup Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/00-START-HERE.txt Configure the Rails Performance gem with essential settings like Redis connection and enabling/disabling the service. ```APIDOC ## RailsPerformance.setup ### Description Configures the Rails Performance gem with necessary options. ### Method `setup` block ### Parameters - `config.redis` (Redis instance) - Required - The Redis client instance for data storage. - `config.enabled` (boolean) - Required - Enables or disables the performance tracking. ### Request Example ```ruby RailsPerformance.setup do |config| config.redis = Redis.new(url: ENV["REDIS_URL"]) config.enabled = true end ``` ``` -------------------------------- ### Example: Process RequestsReport Data Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-reports.md Demonstrates how to iterate through the aggregated request statistics and print key metrics for each controller action. ```ruby db = RailsPerformance::DataSource.new(type: :requests).db report = RailsPerformance::Reports::RequestsReport.new(db) report.data.each do |stat| puts "#{stat[:group]}: #{stat[:count]} requests, #{stat[:duration_average].round(1)}ms avg" end ``` -------------------------------- ### Redis Value Format Example Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/README.md Shows the JSON structure for performance metrics stored as values in Redis. ```json { "duration": 45.2, "view_runtime": 12.5, "db_runtime": 8.3, "exception": null, "custom_data": null } ``` -------------------------------- ### Get Controller, Action, and Format Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-models.md Returns a formatted string including the controller, action, and format. Useful for detailed logging. ```ruby record.controller_action_format ``` -------------------------------- ### Query Pattern for Resource Records Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/overview.md Example Redis KEYS command pattern to query resource metrics by server and context. ```redis resource|*server|app-1|*context|rails|* ``` -------------------------------- ### Redis Key Format for Event Annotations Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/types.md Example of a Redis key format used for event annotations. ```text rails_performance:records:events:{datetimei}|1.0.0 ``` -------------------------------- ### Redis Key Format for Custom Events Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/types.md Example of a Redis key format used for tracking custom events. ```text custom|tag_name|email_send|namespace_name|communications|datetime|20200124T0523|datetimei|1579861423|status|success|END|1.0.2 ``` -------------------------------- ### Install Rails Performance Gem Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/00-START-HERE.txt Add the gem to your application's Gemfile to include it in your project. ```ruby gem 'rails_performance' ``` -------------------------------- ### Initialize Resource Monitor with Environment Variables Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-extensions.md Sets up the global resource monitor using environment variables for context and role, falling back to default values if not set. This pattern is used for application-wide monitoring setup. ```ruby RailsPerformance._resource_monitor = ResourcesMonitor.new( ENV["RAILS_PERFORMANCE_SERVER_CONTEXT"] || "rails", ENV["RAILS_PERFORMANCE_SERVER_ROLE"] || "web" ) ``` -------------------------------- ### Redis Key Format for Resource Records Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/types.md Example of a Redis key format used for tracking resource records. ```text resource|server|app-1|context|rails|role|web|datetime|20200124T0523|datetimei|1579861423|END|1.0.2 ``` -------------------------------- ### Redis Key Format for Trace Records Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/types.md Example of a Redis key format used for trace records. ```text trace|{request_id}|END|1.0.2 ``` -------------------------------- ### Install System Monitoring Gems Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/README.md Add these gems to your Gemfile to enable system resource monitoring (CPU, memory, disk) on the dashboard. ```ruby gem "sys-filesystem" gem "sys-cpu" gem "get_process_mem" ``` -------------------------------- ### ApexCharts Example Data Structure Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-widgets.md Example data structure for ApexCharts, showing timestamps in milliseconds since epoch and corresponding numeric values or nil for gaps. ```ruby [ [1718900460000, 45.2], # timestamp, value [1718900520000, nil], # gap (no data for this minute) [1718900580000, 48.1], ... ] ``` -------------------------------- ### Get Controller and Action Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-models.md Returns a formatted string representing the controller and action name. Useful for logging or display. ```ruby record.controller_action ``` -------------------------------- ### Example of value method usage Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-models.md Demonstrates how to use the `value` method after deserializing a record from the database. It shows the expected output format of the parsed JSON. ```ruby record = RequestRecord.from_db(key, '{"duration":42.5,"db_runtime":5}') record.value ``` -------------------------------- ### Redis Key Format for Sidekiq Records Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/types.md Example of a Redis key format used for tracking Sidekiq records. ```text sidekiq|queue|default|worker|EmailWorker|jid|{jid}|datetime|20200124T0523|datetimei|1579861423|enqueued_ati|1579861612|start_timei|1579861614|status|success|END|1.0.2 ``` -------------------------------- ### Basic Rails Performance Setup Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/00-START-HERE.txt Configure the Rails Performance gem with Redis connection and enable/disable functionality. Ensure Redis is accessible via the REDIS_URL environment variable. ```ruby RailsPerformance.setup do |config| config.redis = Redis.new(url: ENV["REDIS_URL"]) config.enabled = true end ``` -------------------------------- ### Example: ResponseTimeReport Data Format Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-reports.md Illustrates the expected format of the data returned by ResponseTimeReport, showing timestamps and average durations. ```ruby report = ResponseTimeReport.new(collection) # Returns [[1718900460000, 45.2], [1718900520000, nil], [1718900580000, 48.1], ...] ``` -------------------------------- ### Record Custom Maintenance Window Events Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-events.md Log the start and end of a maintenance window with distinct visual styles. ```ruby # Before maintenance RailsPerformance.create_event( name: "Maintenance", options: { borderColor: "#FF6B6B", label: { borderColor: "#FF6B6B", text: "Maintenance Start" } } ) # ... perform maintenance ... # After maintenance RailsPerformance.create_event( name: "Maintenance Complete", options: { borderColor: "#51CF66", label: { borderColor: "#51CF66", text: "Maintenance Complete" } } ) ``` -------------------------------- ### Redis Key Format for Request Records Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/types.md Example of a Redis key format used for tracking request records. ```text performance|controller|HomeController|action|index|format|html|status|200|datetime|20200124T0523|datetimei|1579861423|method|GET|path|/|request_id|{id}|END|1.0.2 ``` -------------------------------- ### Start System Resource Monitoring Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-extensions.md Initiates a background thread to periodically measure system resources like CPU, memory, and disk usage. The monitoring runs at a default interval of 60 seconds. ```ruby monitor.start_monitoring ``` -------------------------------- ### Rails Performance Gem Setup Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/README.md This snippet shows how to set up the Rails Performance gem by adding it to the Gemfile and configuring its various options in an initializer file. It covers settings for Redis, duration, debugging, and endpoint monitoring. ```ruby RailsPerformance.setup do |config| config.redis = Redis.new(url: ENV["REDIS_URL"].presence || "redis://127.0.0.1:6379/0") # or Redis::Namespace.new("rails-performance", redis: Redis.new), see below in README config.duration = 4.hours config.debug = false config.enabled = true # configure Recent tab (time window and limit of requests) # config.recent_requests_time_window = 60.minutes # config.recent_requests_limit = nil # or 1000 # configure Slow Requests tab (time window, limit of requests and threshold) # config.slow_requests_time_window = 4.hours # time window for slow requests # config.slow_requests_limit = 500 # number of max rows # config.slow_requests_threshold = 500 # number of ms # default path where to mount gem, # alternatively you can mount the RailsPerformance::Engine in your routes.rb config.mount_at = '/rails/performance' # protect your Performance Dashboard with HTTP BASIC password config.http_basic_authentication_enabled = false config.http_basic_authentication_user_name = 'rails_performance' config.http_basic_authentication_password = 'password12' # if you need an additional rules to check user permissions config.verify_access_proc = proc { |controller| true } # for example when you have `current_user` # config.verify_access_proc = proc { |controller| controller.current_user && controller.current_user.admin? } # You can ignore endpoints with Rails standard notation controller#action # config.ignored_endpoints = ['HomeController#contact'] # You can ignore request paths by specifying the beginning of the path. # For example, all routes starting with '/admin' can be ignored: config.ignored_paths = ['/rails/performance', '/admin'] # store custom data for the request # config.custom_data_proc = proc do |env| # request = Rack::Request.new(env) # { # email: request.env['warden'].user&.email, # if you are using Devise for example # user_agent: request.env['HTTP_USER_AGENT'] # } # end # config home button link config.home_link = '/' # To skip some Rake tasks from monitoring config.skipable_rake_tasks = ['webpacker:compile'] # To monitor rake tasks performance, you need to include rake tasks # config.include_rake_tasks = false # To monitor custom events with `RailsPerformance.measure` block # config.include_custom_events = true # To monitor system resources (CPU, memory, disk) # to enabled add required gems (see README) # config.system_monitor_duration = 24.hours end if defined?(RailsPerformance) ``` -------------------------------- ### Install and Configure Rails Performance Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/overview.md Add the gem to your Gemfile and configure its settings in an initializer. You can customize Redis connection, data duration, enablement, mount path, and ignored paths. ```ruby # Gemfile gem 'rails_performance' # config/initializers/rails_performance.rb RailsPerformance.setup do |config| config.redis = Redis.new(url: ENV["REDIS_URL"]) config.duration = 4.hours config.enabled = true config.mount_at = '/rails/performance' config.ignored_paths = ['/health', '/metrics'] end ``` -------------------------------- ### Measure CPU Load Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-widgets.md Instantiate and measure the CPULoad monitor to get the CPU load percentage. The key for this monitor is 'CPULoad'. ```ruby monitor = RailsPerformance::Widgets::CPULoad.new(nil) monitor.measure # => Float (0-100) monitor.key # => "CPULoad" ``` -------------------------------- ### Multi-Server Setup Configuration Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/CONFIGURATION-GUIDE.md Configure Rails Performance for a multi-server environment using a shared Redis instance and identifying servers for dashboard analysis. Sets longer data retention and enables system monitoring. ```ruby RailsPerformance.setup do |config| # Shared Redis (usually separate Redis server or cluster) config.redis = Redis::Namespace.new( "app-" + Rails.env + "-performance", redis: Redis.new(url: ENV["REDIS_CLUSTER_URL"]) ) # Server identification for dashboard ENV["RAILS_PERFORMANCE_SERVER_ID"] ||= `hostname`.strip # Longer retention for multi-server analysis config.duration = 7.days # Enable system monitoring config.system_monitor_duration = 24.hours config.enabled = true end ``` -------------------------------- ### Redis Key Format for Grape Records Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/types.md Example of a Redis key format used for tracking Grape API records. ```text grape|datetime|20210409T1115|datetimei|1617992134|format|json|path|/api/users|status|200|method|GET|request_id|{id}|END|1.0.2 ``` -------------------------------- ### Production Rails Performance Setup Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/CONFIGURATION-GUIDE.md Configure Rails Performance for a production environment, including Redis, data retention, authentication, request filtering, and custom data capture. ```ruby # config/initializers/rails_performance.rb if defined?(RailsPerformance) RailsPerformance.setup do |config| # Redis config.redis = Redis.new(url: ENV["REDIS_URL"]) # Data retention config.duration = 7.days # Store 7 days of data # Enable/disable config.enabled = !Rails.env.test? config.debug = false # Dashboard mounting config.mount_at = "/admin/performance" # HTTP Basic Authentication config.http_basic_authentication_enabled = true config.http_basic_authentication_user_name = "admin" config.http_basic_authentication_password = ENV["PERF_DASHBOARD_PASSWORD"] # Access control config.verify_access_proc = proc { |controller| controller.current_user&.admin? } # Request filtering config.ignored_paths = [ "/health", "/metrics", "/admin/performance" # Don't track dashboard itself ] config.ignored_endpoints = [ "HealthController#check" ] # Performance windows config.slow_requests_threshold = 500 # ms config.slow_requests_time_window = 4.hours config.recent_requests_time_window = 1.hour # Custom data capture config.custom_data_proc = proc do |env| request = Rack::Request.new(env) { user_id: request.env["warden"]&.user&.id, user_agent: request.user_agent } end # Features config.include_custom_events = true config.include_rake_tasks = true config.skipable_rake_tasks = ["assets:precompile", "webpacker:compile"] # System monitoring (if gems present) config.system_monitor_duration = 24.hours config.system_monitors = ["CPULoad", "MemoryUsage", "DiskUsage"] end end ``` -------------------------------- ### Redis Key Format for Rake Records Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/types.md Example of a Redis key format used for tracking Rake task records. ```text rake|task|["db:migrate"]|datetime|20210416T1254|datetimei|1618602843|status|success|END|1.0.2 ``` -------------------------------- ### Query Pattern for Request Records Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/overview.md Example Redis KEYS command pattern to query request records based on controller and datetime. ```redis performance|*controller|PostsController|*datetime|20260620*|* ``` -------------------------------- ### Create and Convert Event to Annotation Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-events.md Example demonstrating the creation of a new event record and its subsequent conversion into an annotation format for chart display. This shows a practical use case for the `to_annotation` method. ```ruby event = RailsPerformance::Events::Record.create(name: "Deploy") annotation = event.to_annotation # => {x: 1718900600000, borderColor: "#FF00FF", label: {...}} ``` -------------------------------- ### Query Pattern for Sidekiq Records Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/overview.md Example Redis KEYS command pattern to query Sidekiq job records by queue and status. ```redis sidekiq|*queue|default|*status|success|* ``` -------------------------------- ### Enable Rake Task Performance Tracking Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-configuration.md Enables tracking of Rake task performance. Requires additional setup in the engine. ```ruby RailsPerformance.include_rake_tasks = false ``` -------------------------------- ### Measure Disk Usage Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-widgets.md Instantiate and measure the DiskUsage monitor to get the disk usage percentage. The key for this monitor is 'DiskUsage'. ```ruby monitor = RailsPerformance::Widgets::DiskUsage.new(nil) monitor.measure # => Float (0-100) monitor.key # => "DiskUsage" ``` -------------------------------- ### Configure Redis Connection Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-configuration.md Set the Redis connection instance for storing performance data. Supports Redis::Namespace for multi-application setups. ```ruby RailsPerformance.redis = Redis.new ``` ```ruby RailsPerformance.setup do |config| config.redis = Redis.new(url: ENV["REDIS_URL"]) # or with namespace config.redis = Redis::Namespace.new("rails-performance", redis: Redis.new) end ``` -------------------------------- ### Multi-Source Aggregation for Requests Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-data-source.md Combines data from multiple DataSource instances into a single collection. This example aggregates successful requests and redirect responses into one collection for further analysis. ```ruby # Combine multiple request statuses into one collection success_source = RailsPerformance::DataSource.new( type: :requests, q: {status: 200} ) redirect_source = RailsPerformance::DataSource.new( type: :requests, q: {status: [301, 302, 303, 307]} ) combined = RailsPerformance::Models::Collection.new success_source.add_to(combined) redirect_source.add_to(combined) # Now combined has both successful and redirect responses report = RailsPerformance::Reports::RequestsReport.new(combined) ``` -------------------------------- ### Record Simple Deployment Event Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-events.md Use this to record a basic deployment event. You can use the direct class method or the convenience method. ```ruby # In a Rake task or hook after deployment RailsPerformance::Events::Record.create(name: "Deploy") # or via the convenience method RailsPerformance.create_event(name: "Deploy") ``` -------------------------------- ### Instantiate MetricsCollector Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-extensions.md Creates a new instance of the MetricsCollector. This is the basic setup for the collector. ```ruby MetricsCollector.new ``` -------------------------------- ### Annotation Hash Structure Example Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-events.md Illustrates the expected hash structure for chart annotations, including timestamp, border color, and label configuration. This format is used for displaying events on charts. ```ruby { x: 1718900600000, # Timestamp in milliseconds borderColor: "#FF00FF", # Border color (default or from options) label: { borderColor: "#FF00FF", # Label border color orientation: "horizontal", # horizontal or vertical text: "Deploy" # Label text } } ``` -------------------------------- ### Initialize a New SidekiqRecord Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-models.md Instantiate a SidekiqRecord with essential job details. Optional parameters like status and duration can be provided. ```ruby SidekiqRecord.new( queue:, worker:, jid:, datetime:, datetimei:, enqueued_ati:, start_timei:, status: nil, duration: nil, json: "{}" ) ``` -------------------------------- ### Get Current System Resource Metrics Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-extensions.md Retrieves a hash containing the current system resource metrics, including CPU Load, Memory Usage, and Disk Usage. These metrics are obtained from associated widget classes. ```ruby monitor.payload ``` -------------------------------- ### Initialize DataSource Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-data-source.md Create a data source for querying specific types of performance data. You can specify the data type, query filters, and the number of days to look back. ```ruby DataSource.new(type:, q: {}, days: RailsPerformance::Utils.days(RailsPerformance.duration)) ``` -------------------------------- ### Instantiate ResourceRecord Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-models.md Initializes a new ResourceRecord with server, context, role, datetime, and JSON metrics. ```ruby ResourceRecord.new( server:, context:, role:, datetime:, datetimei:, json: ) ``` -------------------------------- ### Insert Request Middleware Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-extensions.md Example of how to insert the Rails Performance middleware into the Rails application's middleware stack. ```ruby app.middleware.insert_after ActionDispatch::Executor, RailsPerformance::Rails::Middleware app.middleware.insert_before RailsPerformance::Rails::Middleware, RailsPerformance::Rails::MiddlewareTraceStorerAndCleanup ``` -------------------------------- ### Kamal Configuration for Server ID Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/README.md Example of setting the RAILS_PERFORMANCE_SERVER_ID environment variable within a Kamal deployment configuration. ```yaml env: clear: RAILS_PERFORMANCE_SERVER_ID: "server" ``` -------------------------------- ### ResourcesMonitor.new Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-extensions.md Initializes a new ResourcesMonitor instance to track system resource usage. It requires the server context and role to be specified. ```APIDOC ## ResourcesMonitor.new ### Description Initializes a new ResourcesMonitor instance to track system resource usage. It requires the server context and role to be specified. ### Constructor ```ruby ResourcesMonitor.new(context, role) ``` ### Parameters #### Path Parameters - **context** (String) - Required - Server context (e.g., "rails", "sidekiq") - **role** (String) - Required - Server role (e.g., "web", "background") ``` -------------------------------- ### Initialize Rails Performance Data Source Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/README.md Create a data source to query performance records. Specify the record type and optional query parameters. ```ruby source = RailsPerformance::DataSource.new(type: :requests, q: {controller: "Home"}) collection = source.db ``` -------------------------------- ### Instantiate ResourcesMonitor Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-extensions.md Create a new instance of ResourcesMonitor to track system resources. Specify the server context and role for monitoring. ```ruby ResourcesMonitor.new(context, role) ``` -------------------------------- ### Get Request Duration Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-models.md Provides a shortcut to retrieve the duration of a request from its value hash. Returns the duration in milliseconds. ```ruby request.duration ``` -------------------------------- ### Run Tests Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/README.md Execute the test suite to ensure the application is functioning correctly. ```bash rails test ``` -------------------------------- ### Get RequestsReport Data Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-reports.md Retrieves aggregated HTTP request metrics. The data is sorted by the metric specified during instantiation. ```ruby report.data ``` -------------------------------- ### Get Recent Requests Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/README.md Retrieve a collection of recent requests using a data source and generate a report to display them. ```ruby source = RailsPerformance::DataSource.new(type: :requests) collection = source.db report = RailsPerformance::Reports::RecentRequestsReport.new(collection) requests = report.data # Array of recent request hashes ``` -------------------------------- ### Gem Version Constant Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-core.md Represents the current version of the Rails Performance gem. This is useful for tracking the installed version and compatibility. ```ruby RailsPerformance::VERSION = "1.6.0" ``` -------------------------------- ### RailsPerformance.setup Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-core.md Configure performance tracking by yielding the RailsPerformance module to a block. This allows setting various configuration options like Redis connection, duration, and enablement. ```APIDOC ## RailsPerformance.setup ### Description Configure performance tracking. The block parameter receives the `RailsPerformance` module itself. ### Method ```ruby RailsPerformance.setup { |config| ... } ``` ### Parameters - **config** (Block) - Yields the `RailsPerformance` module for configuration. ### Return nil ### Example ```ruby RailsPerformance.setup do |config| config.redis = Redis.new(url: ENV["REDIS_URL"]) config.duration = 4.hours config.enabled = true end ``` ``` -------------------------------- ### Ignore Request Paths Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-configuration.md Specify an array of request path prefixes to exclude from tracking. Any path starting with these prefixes will be ignored. ```ruby RailsPerformance.ignored_paths = [] ``` ```ruby config.ignored_paths = ['/rails/performance', '/admin', '/health'] ``` -------------------------------- ### GrapeRecord.new Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-models.md Constructor for the GrapeRecord class. Initializes a new GrapeRecord with provided request details and timing information. ```APIDOC ## GrapeRecord.new ### Description Constructor for the GrapeRecord class. Initializes a new GrapeRecord with provided request details and timing information. ### Method Constructor ### Parameters #### Path Parameters - **request_id** (String) - Required - **datetime** (String) - Optional - Formatted datetime - **datetimei** (Integer) - Optional - Unix timestamp - **format** (String) - Optional - Response format (e.g., "json") - **path** (String) - Optional - API endpoint path (e.g., "/api/users") - **status** (Integer) - Optional - HTTP status code - **method** (String) - Optional - HTTP method - **endpoint_render_grape** (Float) - Optional - Time spent rendering response (ms) - **endpoint_run_grape** (Float) - Optional - Time spent in endpoint logic (ms) - **format_response_grape** (Float) - Optional - Time spent formatting response (ms) - **json** (String) - Optional - JSON string, defaults to "{}" ``` -------------------------------- ### Configure Server Context and Role Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/README.md Set environment variables to define the context and role for system monitoring, distinguishing between web and sidekiq servers. ```ruby RailsPerformance::SystemMonitor::ResourcesMonitor.new( ENV["RAILS_PERFORMANCE_SERVER_CONTEXT"].presence || "rails", ENV["RAILS_PERFORMANCE_SERVER_ROLE"].presence || "web" ) ``` -------------------------------- ### Initialize GrapeRecord Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-models.md Creates a new GrapeRecord instance. Datetime and datetimei can be provided or will be inferred. JSON defaults to an empty string if not provided. ```ruby GrapeRecord.new( request_id:, datetime: nil, datetimei: nil, format: nil, path: nil, status: nil, method: nil, endpoint_render_grape: nil, endpoint_run_grape: nil, format_response_grape: nil, json: "{}" ) ``` -------------------------------- ### Create Deployment Events Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/overview.md Create specific deployment events to track deployment-related activities. Options can be passed to customize the event. ```ruby RailsPerformance.create_event(name: "Deploy", options: {...}) ``` -------------------------------- ### Create DataSource for Requests Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-data-source.md Instantiate a DataSource to fetch all requests from the last 4 hours. This is a common use case for monitoring general request activity. ```ruby # All requests from last 4 hours data_source = RailsPerformance::DataSource.new(type: :requests) ``` -------------------------------- ### Temporarily Disable RailsPerformance Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/CONFIGURATION-GUIDE.md You can disable RailsPerformance at runtime by setting `enabled` to false, or permanently by configuring it within the `setup` block. ```ruby RailsPerformance.enabled = false # At runtime (won't persist) # Permanently in code RailsPerformance.setup { |config| config.enabled = false } ``` -------------------------------- ### Initialize an Event Record Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-events.md Use this constructor to create a new event record. Typically, you would use the `.create` class method instead for persistence. ```ruby RailsPerformance::Events::Record.new( name: "Deploy v2.0.0", datetimei: Time.now.to_i, options: { borderColor: "#00E396", label: { borderColor: "#00E396", orientation: "vertical", text: "Release" } } ) ``` -------------------------------- ### Get or Create CurrentRequest Context Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-extensions.md Retrieves the current thread-local request context or creates a new one if it doesn't exist. ```ruby CurrentRequest.current ``` -------------------------------- ### Get Percentile Report Data Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-reports.md Fetches the calculated percentile values (P50, P95, P99) for request durations in milliseconds. ```ruby report = PercentileReport.new(collection) data = report.data # => {p50: 42.5, p95: 189.3, p99: 245.1} ``` -------------------------------- ### Create DataSource with Query Filters Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-data-source.md Create a DataSource to query requests for a specific controller. This allows for targeted performance analysis by applying filters. ```ruby # Requests for specific controller data_source = RailsPerformance::DataSource.new( type: :requests, q: {controller: "PostsController"} ) ``` -------------------------------- ### Configure Rails Performance Settings Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/README.md Set up essential configurations for the gem, including Redis connection, enablement, duration, mount path, and access verification. ```ruby RailsPerformance.setup do |config| config.redis = Redis.new(url: ENV["REDIS_URL"]) config.enabled = true config.duration = 4.hours config.mount_at = "/rails/performance" config.verify_access_proc = proc { |controller| controller.current_user&.admin? } end ``` -------------------------------- ### Initialize ResourceChart Widget Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-widgets.md Instantiate the ResourceChart widget for a specific resource type. The widget returns time-series data suitable for charting. ```ruby chart = RailsPerformance::Widgets::ResourceChart.new( resource_collection, "CPULoad" ) # Returns time-series: [[timestamp_ms, cpu_percentage], ...] # Shows data per server if multiple servers # Groups by server_id for multi-server setups ``` -------------------------------- ### Create DataSource for Sidekiq Jobs Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-data-source.md Instantiate a DataSource to fetch Sidekiq jobs from the last 24 hours. This is useful for monitoring background job performance. ```ruby # Sidekiq jobs from last 24 hours data_source = RailsPerformance::DataSource.new( type: :sidekiq, days: 1 ) ``` -------------------------------- ### Measure Memory Usage Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-widgets.md Instantiate and measure the MemoryUsage monitor to get the process memory usage in MB. The key for this monitor is 'MemoryUsage'. ```ruby monitor = RailsPerformance::Widgets::MemoryUsage.new(nil) monitor.measure # => Float (MB) monitor.key # => "MemoryUsage" ``` -------------------------------- ### Get Current UTC Time Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-core.md Retrieves the current time in UTC. This method ensures time zone independence for tracking purposes. ```ruby now = RailsPerformance::Utils.time ``` -------------------------------- ### Create Response Time Chart Widget Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/README.md Instantiate a widget to visualize report data, such as response times, typically for a dashboard. ```ruby widget = RailsPerformance::Widgets::ResponseTimeChart.new(collection) # Returns [[timestamp_ms, value], ...] ``` -------------------------------- ### Redis Key for Request Records Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/overview.md Example of the key format used to store request records in Redis, including metadata and schema version. ```text Key: "performance|controller|...|action|...|...|datetimei|{ts}|request_id|{id}|END|1.0.2" Value: JSON {view_runtime, db_runtime, duration, exception, ...} Expiration: RailsPerformance.duration (default 4 hours) ``` -------------------------------- ### Get Record Hash for Display Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-models.md Generates a hash representation of the record suitable for UI display. Includes optional custom data if configured. ```ruby record.record_hash ``` -------------------------------- ### SystemMonitor Resources Integration Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-widgets.md Initialize a ResourcesMonitor for system metrics with specified context and role. The payload contains periodically measured metrics. ```ruby monitor = RailsPerformance::SystemMonitor::ResourcesMonitor.new( context: "rails", role: "web" ) # Monitors periodically measure and store metrics payload = monitor.payload # => { # "CPULoad" => 25.5, # "MemoryUsage" => 512.3, # "DiskUsage" => 65.2 # } ``` -------------------------------- ### Get Throughput Report Data Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-reports.md Retrieves the throughput data, which includes request counts per minute, with gaps filled by nil values. ```ruby report = ThroughputReport.new(collection) # Returns [[1718900460000, 12], [1718900520000, nil], [1718900580000, 8], ...] ``` -------------------------------- ### Instantiate ResourcesReport Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-reports.md Creates a new ResourcesReport object to track system resource metrics. Optional parameters can be provided for grouping, sorting, and titling the report. ```ruby ResourcesReport.new(db, group: nil, sort: nil, title: nil) ``` -------------------------------- ### RailsPerformance::Utils.kind_of_now Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-core.md Gets the current time with a one-minute offset. This is useful for defining time ranges to ensure complete data coverage for recent periods. ```APIDOC ## Class Methods ### kind_of_now ```ruby RailsPerformance::Utils.kind_of_now ``` #### Description Current time plus 1 minute offset. Used for time range calculations to ensure full coverage of recent data. #### Return `Time` (UTC) #### Example ```ruby range_end = RailsPerformance::Utils.kind_of_now ``` ``` -------------------------------- ### SidekiqJobsTable Widget Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-widgets.md Instantiate the SidekiqJobsTable widget to display Sidekiq background job metrics. It requires a collection of Sidekiq data. ```ruby sidekiq_collection = RailsPerformance::DataSource.new(type: :sidekiq).db RailsPerformance::Widgets::SidekiqJobsTable.new(sidekiq_collection) ``` -------------------------------- ### RakeRecord Instance Methods Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-models.md Provides methods to get a hash representation of the record or save it. `record_hash` returns a hash of task details, and `save` persists the record. ```ruby record.record_hash ``` ```ruby record.save ``` -------------------------------- ### Initialize RequestRecord Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-models.md Constructs a new RequestRecord object with various performance-related attributes. Some attributes can be optional. ```ruby RequestRecord.new( controller:, action:, format:, status:, datetime:, datetimei:, method:, path:, request_id:, view_runtime: nil, db_runtime: nil, duration: nil, http_referer: nil, custom_data: nil, exception: nil, exception_object: nil, json: "{}" ) ``` -------------------------------- ### Enable HTTP Basic Authentication Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/CONFIGURATION-GUIDE.md Configure HTTP Basic Authentication for access control. Set username and password, and allow all requests. ```ruby config.http_basic_authentication_enabled = true config.http_basic_authentication_user_name = "admin" config.http_basic_authentication_password = ENV["PERF_PASSWORD"] config.verify_access_proc = proc { |controller| true } ``` -------------------------------- ### Typical Rails Performance Report Usage Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-reports.md Demonstrates the standard workflow for using reports in Rails Performance. This includes creating a DataSource, initializing a report, fetching aggregated data, and processing the results. ```ruby # 1. Create a DataSource to fetch data data_source = RailsPerformance::DataSource.new(type: :requests) collection = data_source.db # 2. Create report with collection report = RailsPerformance::Reports::RequestsReport.new(collection) # 3. Get aggregated data results = report.data # 4. Render results results.each do |row| # Process row data end ``` -------------------------------- ### RailsPerformance::Events::Record.new Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-events.md Initializes a new event record. This is typically not called directly; use `.create` instead. ```APIDOC ## RailsPerformance::Events::Record.new ### Description Initializes an event record. This method is typically not called directly; use `.create` instead. ### Method `RailsPerformance::Events::Record.new(name:, datetimei: Time.now.to_i, options: {})` ### Parameters #### Arguments - **name** (String) - Required - Event name for display - **datetimei** (Integer) - Optional - Unix timestamp in seconds. Defaults to current Unix time. - **options** (Hash) - Optional - Visual styling options (e.g., `borderColor`, `label`). Defaults to an empty hash. ### Example ```ruby record = RailsPerformance::Events::Record.new( name: "Deploy v2.0.0", datetimei: Time.now.to_i, options: { borderColor: "#00E396", label: { borderColor: "#00E396", orientation: "vertical", text: "Release" } } ) ``` ``` -------------------------------- ### ApexCharts Data Format for Response Time Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-widgets.md Instantiate a ResponseTimeChart widget with a collection to get data formatted for ApexCharts. The data is returned as an array of [timestamp_ms, value] pairs. ```ruby chart = RailsPerformance::Widgets::ResponseTimeChart.new(collection) # Returns: [[timestamp_ms, value], ...] ``` -------------------------------- ### ThroughputChart Widget Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-widgets.md Instantiate the ThroughputChart widget to visualize requests per minute over time. It takes a collection of data as input. ```ruby RailsPerformance::Widgets::ThroughputChart.new(collection) # Returns [[timestamp_ms, request_count], ...] ``` -------------------------------- ### Get Recent Requests Report Data Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-reports.md Retrieves an array of recent request details, sorted newest first. The data includes various request attributes and is limited by configuration. ```ruby db = RailsPerformance::DataSource.new(type: :requests).db report = RecentRequestsReport.new(db) report.data.first(10).each do |req| puts "#{req[:datetime]} #{req[:method]} #{req[:path]} #{req[:status]}" end ``` -------------------------------- ### ResourceChart Widget Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-widgets.md Instantiate the ResourceChart widget for system resource metrics like CPU, memory, or disk usage. Specify the resource type during instantiation. ```ruby RailsPerformance::Widgets::ResourceChart.new(collection, resource_type) # resource_type: "CPULoad", "MemoryUsage", or "DiskUsage" ``` -------------------------------- ### Required Environment Variables for Redis and Server Identification Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/CONFIGURATION-GUIDE.md Set essential environment variables for Redis connection and server identification, especially in multi-server setups. These are crucial for the gem's operation. ```bash # Redis connection (primary) REDIS_URL=redis://localhost:6379/0 REDIS_URL=redis://:password@redis.example.com:6379/0 # Server identification (multi-server) RAILS_PERFORMANCE_SERVER_ID=web-1 RAILS_PERFORMANCE_SERVER_CONTEXT=rails RAILS_PERFORMANCE_SERVER_ROLE=web # For Sidekiq instances RAILS_PERFORMANCE_SERVER_CONTEXT=sidekiq RAILS_PERFORMANCE_SERVER_ROLE=background # Authentication PERF_DASHBOARD_PASSWORD=secure_password_here ``` -------------------------------- ### Create Custom Event with Options Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/README.md Log custom events with specific styling options for the event label and border color on the charts. ```ruby RailsPerformance.create_event(name: "Deploy", options: { borderColor: "#00E396", label: { borderColor: "#00E396", orientation: "horizontal", text: "Deploy" } }) ``` -------------------------------- ### Get Current UTC Time + 1 Minute Offset Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-core.md Retrieves the current time with a one-minute offset. Used for time range calculations to ensure complete coverage of recent data. ```ruby range_end = RailsPerformance::Utils.kind_of_now ``` -------------------------------- ### Generate Request Metrics Report Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/REFERENCE-INDEX.md Create a `RequestsReport` to get aggregated metrics per action. Use `ResponseTimeChart` for average response time over time, and `RecentRequestsReport` for a list of recent requests. ```ruby # Aggregated metrics report = RailsPerformance::Reports::RequestsReport.new(collection) metrics = report.data ``` ```ruby # Time-series report = RailsPerformance::Reports::ResponseTimeChart.new(collection) chart_data = report.data # [[timestamp_ms, value], ...] ``` ```ruby # Recent requests report = RailsPerformance::Reports::RecentRequestsReport.new(collection) requests = report.data ``` -------------------------------- ### TraceRecord Constructor Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-models.md Initializes a new TraceRecord instance with a request ID and trace value. ```APIDOC ## TraceRecord.new ### Description Initializes a new TraceRecord instance, which stores trace/span data for detailed request debugging. ### Method Constructor ### Parameters - **request_id** (String) - Required - The ID associated with the request. - **value** (Array) - Required - An array of trace event hashes. ``` -------------------------------- ### Initialize Widgets in Controller Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-widgets.md Initialize various widgets within the engine controller by creating instances of widget classes and calling their `data` method with a collection from the data source. ```ruby # In engine controller (app/controllers/rails_performance/dashboard_controller.rb) collection = RailsPerformance::DataSource.new(type: :requests).db @response_time_chart = RailsPerformance::Widgets::ResponseTimeChart.new(collection).data @requests_table = RailsPerformance::Widgets::RequestsTable.new(collection).data @percentiles = RailsPerformance::Widgets::PercentileCard.new(collection).data ``` -------------------------------- ### Create GrapeRecord from Database Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-models.md Instantiates a GrapeRecord from a Redis key and JSON value. Use this when loading existing records. ```ruby GrapeRecord.from_db(key, value) ``` -------------------------------- ### Configure System Monitor Widgets Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-configuration.md Specifies the names of system monitor widgets to use for monitoring CPU, memory, and disk usage. ```ruby RailsPerformance.system_monitors = ["CPULoad", "MemoryUsage", "DiskUsage"] ``` -------------------------------- ### Instantiate TraceRecord Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-models.md Creates a new TraceRecord instance, requiring a request ID and an array of trace event hashes. ```ruby TraceRecord.new(request_id:, value:) ``` -------------------------------- ### ResponseTimeChart Widget Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-widgets.md Instantiate the ResponseTimeChart widget to display average response time over time. It requires a collection of data. ```ruby RailsPerformance::Widgets::ResponseTimeChart.new(collection) # Returns [[timestamp_ms, avg_duration], ...] ``` -------------------------------- ### Combine HTTP Basic Auth and App-Level Auth Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/CONFIGURATION-GUIDE.md Implement defense in depth by enabling both HTTP Basic Authentication and application-level authorization. ```ruby config.http_basic_authentication_enabled = true config.http_basic_authentication_user_name = ENV["PERF_USER"] config.http_basic_authentication_password = ENV["PERF_PASSWORD"] config.verify_access_proc = proc do |controller| controller.current_user&.admin? end ``` -------------------------------- ### Instantiate Collection Source: https://github.com/igorkasyanchuk/rails_performance/blob/master/_autodocs/api-reference-models.md Creates an empty in-memory container for organizing record objects. ```ruby Collection.new ```