apmlens 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 1d80552cd71dc91bdca452f949b714ea91ff20171d2e2914cf74aa0bf1f66009
4
+ data.tar.gz: e3b2920157f387daf32f3e1892f8896020380f47ca3b9fb0a314e8c86bce2c33
5
+ SHA512:
6
+ metadata.gz: 69afa3bdfbca8277b28324eb8f4ced78ab453d382d3c41d875e3398d449f6a76d77eaaaf4eaa8c68ab5269f6ce8b145e1f69841843947d0417291bdbc31ebc5a
7
+ data.tar.gz: 1b21f0ce85d6b320d8b8fd3e86c657881c3527feefff27786e9429348a51b2c9e6be40636df2e664cffdfd8ce6b08f416ea0b3a97ddb7e472e5d772a4292a46c
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 APMLens Team
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,51 @@
1
+ # APMLens Ruby Gem
2
+
3
+ The official Ruby agent for [APMLens](https://apmlens.com).
4
+
5
+ This gem is designed with the **Power Law** in mind: It delivers 95% of the monitoring value (Error Tracking + P95 Latency) with < 200 lines of code and zero external dependencies.
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'apmlens', '~> 1.0'
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ ### Rails
18
+ It works automatically. Just configure it in `config/initializers/apmlens.rb`:
19
+
20
+ ```ruby
21
+ Apmlens.configure do |c|
22
+ c.ingestion_key = ENV['APMLENS_KEY']
23
+ c.service = 'my-rails-app'
24
+ end
25
+ ```
26
+
27
+ ### Manual Usage (Ruby Scripts)
28
+
29
+ ```ruby
30
+ require 'apmlens'
31
+
32
+ # 1. Config
33
+ Apmlens.configure do |c|
34
+ c.ingestion_key = 'ik_...'
35
+ end
36
+
37
+ # 2. Track Errors
38
+ begin
39
+ risk_method
40
+ rescue => e
41
+ Apmlens.capture_error(e, user_id: current_user.id)
42
+ end
43
+
44
+ # 3. Track Metrics (Aggregated automatically)
45
+ Apmlens.capture_trace('job.duration', 500)
46
+ ```
47
+
48
+ ## Architecture
49
+
50
+ * **In-Memory Buffer**: Metrics are aggregated locally (P95, Avg, Max) and flushed once per minute. This solves the "N+1 Query" scalability problem.
51
+ * **Non-Blocking**: All network calls happen in a background thread. Your app never waits for APMLens.
@@ -0,0 +1,149 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "json"
5
+ require "thread"
6
+ require "singleton"
7
+
8
+ module Apmlens
9
+ # The Heavy Lifter.
10
+ # Handles buffering, threading, and network transmission.
11
+ class Client
12
+ include Singleton
13
+
14
+ def initialize
15
+ @queue = Queue.new
16
+ @metric_buffer = Hash.new { |h, k| h[k] = [] }
17
+ @metric_lock = Mutex.new
18
+ @metric_count = 0
19
+ end
20
+
21
+ def start!
22
+ start_worker_thread!
23
+ end
24
+
25
+ def capture_error(exception, context = {})
26
+ param_hash = {
27
+ type: "errors",
28
+ body: {
29
+ service: Apmlens.configuration.service,
30
+ error: {
31
+ class: exception.class.name,
32
+ message: exception.message,
33
+ stack_trace: exception.backtrace&.first(20),
34
+ occurred_at: Time.now.utc.iso8601,
35
+ metadata: context
36
+ }
37
+ }
38
+ }
39
+ enqueue(param_hash)
40
+ end
41
+
42
+ def capture_trace(name, value, tags = {})
43
+ key = { name: name, tags: tags }
44
+ config = Apmlens.configuration
45
+
46
+ @metric_lock.synchronize do
47
+ # 1. Series Limit: Check if this is a new series and if we've reached the limit
48
+ if !@metric_buffer.key?(key) && @metric_buffer.size >= config.max_series_limit
49
+ return
50
+ end
51
+
52
+ # 2. Samples Limit: Check if we've reached the total samples limit
53
+ if @metric_count >= config.max_samples_limit
54
+ return
55
+ end
56
+
57
+ @metric_buffer[key] << value
58
+ @metric_count += 1
59
+ end
60
+ end
61
+
62
+ private
63
+
64
+ def enqueue(payload)
65
+ # Circuit Breaker: Drop if queue is full to avoid memory leaks
66
+ return if @queue.size >= Apmlens.configuration.max_queue_limit
67
+ @queue.push(payload)
68
+ end
69
+
70
+ def start_worker_thread!
71
+ return if @worker_thread&.alive?
72
+
73
+ @worker_thread = Thread.new do
74
+ last_flush = Time.now
75
+ loop do
76
+ # 1. Process Queue (Non-blocking wait for up to 10s)
77
+ # We wait less than 60s so we can check if we need to flush metrics
78
+ begin
79
+ # Wait up to 10 seconds for an error event
80
+ item = @queue.pop(timeout: 10)
81
+ if item
82
+ send_http(item[:type], item[:body])
83
+ end
84
+ rescue ThreadError
85
+ # Queue empty (legacy behavior if non_block=true used)
86
+ # Timeout, check metrics flush
87
+ rescue => e
88
+ warn "[Apmlens] Worker Error: #{e.message}"
89
+ end
90
+
91
+ # 2. Flush Metrics (Every 60s)
92
+ if Time.now - last_flush > 60
93
+ flush_metrics!
94
+ last_flush = Time.now
95
+ end
96
+ end
97
+ end
98
+ end
99
+
100
+ def flush_metrics!
101
+ snapshot = {}
102
+ @metric_lock.synchronize do
103
+ snapshot = @metric_buffer
104
+ @metric_buffer = Hash.new { |h, k| h[k] = [] }
105
+ @metric_count = 0
106
+ end
107
+
108
+ return if snapshot.empty?
109
+
110
+ # Client Service Aggregation (P95, Avg, Max)
111
+ payload = snapshot.map do |key, values|
112
+ values.compact!
113
+ next if values.empty?
114
+
115
+ sorted = values.sort
116
+ count = values.size
117
+ sum = values.sum
118
+
119
+ {
120
+ name: key[:name],
121
+ tags: key[:tags],
122
+ stats: {
123
+ count: count,
124
+ min: sorted.first,
125
+ max: sorted.last,
126
+ avg: sum / count.to_f,
127
+ p95: sorted[(count * 0.95).to_i]
128
+ }
129
+ }
130
+ end.compact
131
+
132
+ send_http("metrics", { service: Apmlens.configuration.service, metrics: payload })
133
+ end
134
+
135
+ def send_http(type, data)
136
+ uri = URI("#{Apmlens.configuration.endpoint}/api/v1/ingest/#{type}")
137
+ req = Net::HTTP::Post.new(uri)
138
+ req["Authorization"] = "Bearer #{Apmlens.configuration.ingestion_key}"
139
+ req["Content-Type"] = "application/json"
140
+ req.body = data.to_json
141
+
142
+ Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https", open_timeout: 2, read_timeout: 5) do |http|
143
+ http.request(req)
144
+ end
145
+ rescue => e
146
+ warn "[Apmlens] HTTP Error: #{e.message}"
147
+ end
148
+ end
149
+ end
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Apmlens
4
+ class Configuration
5
+ attr_accessor :ingestion_key, :service, :endpoint, :environment,
6
+ :max_series_limit, :max_samples_limit, :max_queue_limit,
7
+ :slow_query_threshold, :large_result_threshold
8
+
9
+ def initialize
10
+ @ingestion_key = ENV["APMLENS_KEY"]
11
+ @service = "ruby-app"
12
+ @endpoint = ENV.fetch("APMLENS_ENDPOINT", "https://app.apmlens.com")
13
+ @environment = ENV.fetch("RAILS_ENV", "development")
14
+ @enabled = false
15
+ @max_series_limit = 2_000
16
+ @max_samples_limit = 100_000
17
+ @max_queue_limit = 1_000
18
+ @slow_query_threshold = 500 # ms
19
+ @large_result_threshold = 2000 # records
20
+ end
21
+
22
+ def enabled?
23
+ @enabled && !@ingestion_key.nil?
24
+ end
25
+
26
+ def enable!
27
+ @enabled = true
28
+ end
29
+
30
+ def disable!
31
+ @enabled = false
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Apmlens
4
+ class QueryTrackingMiddleware
5
+ def initialize(app)
6
+ @app = app
7
+ end
8
+
9
+ def call(env)
10
+ Thread.current[:apmlens_query_tracker] = {}
11
+ @app.call(env)
12
+ ensure
13
+ Thread.current[:apmlens_query_tracker] = nil
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,97 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Apmlens
4
+ class Railtie < Rails::Railtie
5
+ initializer "apmlens.configure_rails_initialization" do |app|
6
+ # 1. Subscribe to Unhandled Exceptions (Rails 7+)
7
+ if app.respond_to?(:error)
8
+ app.error.subscribe do |error, handled:, severity:, context:, source:|
9
+ next if handled
10
+ Apmlens.capture_error(error, context)
11
+ end
12
+ end
13
+
14
+ # 2. Subscribe to SQL Queries (N+1 Detection Support + Full Table Scan)
15
+ ActiveSupport::Notifications.subscribe("sql.active_record") do |_, start, finish, _, payload|
16
+ duration = (finish - start) * 1000
17
+ Apmlens.capture_trace("db.query", duration, { name: payload[:name] })
18
+
19
+ # Track query fingerprints for N+1 detection
20
+ query_tracker = Thread.current[:apmlens_query_tracker]
21
+ if query_tracker
22
+ fingerprint = fingerprint_sql(payload[:sql])
23
+ query_tracker[fingerprint] ||= 0
24
+ query_tracker[fingerprint] += 1
25
+ end
26
+
27
+ # Slow Query Detection
28
+ if duration > Apmlens.configuration.slow_query_threshold
29
+ Apmlens.capture_trace("slow_query.detected", duration, {
30
+ sql: payload[:sql],
31
+ sql_fingerprint: fingerprint_sql(payload[:sql])
32
+ })
33
+ end
34
+ end
35
+
36
+ # 3. Request Duration + N+1 Detection
37
+ ActiveSupport::Notifications.subscribe("process_action.action_controller") do |_, start, finish, _, payload|
38
+ duration = (finish - start) * 1000
39
+ Apmlens.capture_trace("http.request", duration, {
40
+ controller: payload[:controller],
41
+ action: payload[:action],
42
+ status: payload[:status]
43
+ })
44
+
45
+ # Check for N+1 patterns
46
+ query_tracker = Thread.current[:apmlens_query_tracker]
47
+ if query_tracker
48
+ query_tracker.each do |fingerprint, count|
49
+ if count > 5 # Threshold for N+1 detection
50
+ Apmlens.capture_trace("n_plus_one.detected", count, {
51
+ sql_fingerprint: fingerprint,
52
+ controller: payload[:controller],
53
+ action: payload[:action]
54
+ })
55
+ end
56
+ end
57
+ end
58
+ end
59
+
60
+ # 4. Large Result Set Detection (Memory Bloat)
61
+ ActiveSupport::Notifications.subscribe("instantiation.active_record") do |_, start, finish, _, payload|
62
+ record_count = payload[:record_count]
63
+
64
+ if record_count && record_count > Apmlens.configuration.large_result_threshold
65
+ duration = (finish - start) * 1000
66
+ Apmlens.capture_trace("large_result_set.detected", duration, {
67
+ record_count: record_count,
68
+ class_name: payload[:class_name]
69
+ })
70
+ end
71
+ end
72
+
73
+ # 5. Initialize query tracker at the start of each request
74
+ app.middleware.use Apmlens::QueryTrackingMiddleware
75
+ end
76
+
77
+ private
78
+
79
+ def self.fingerprint_sql(sql)
80
+ return "unknown" if sql.nil?
81
+
82
+ # Remove literals and normalize whitespace
83
+ normalized = sql.gsub(/\b\d+\b/, '?') # Numbers
84
+ .gsub(/'[^']*'/, '?') # Strings
85
+ .gsub(/\s+/, ' ') # Whitespace
86
+ .strip
87
+
88
+ # Extract table name if possible
89
+ if normalized =~ /FROM\s+["']?(\w+)["']?/i
90
+ table = $1
91
+ "#{table}:#{normalized[0..50]}"
92
+ else
93
+ normalized[0..50]
94
+ end
95
+ end
96
+ end
97
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Apmlens
4
+ VERSION = "1.0.0"
5
+ end
data/lib/apmlens.rb ADDED
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "apmlens/version"
4
+ require_relative "apmlens/configuration"
5
+ require_relative "apmlens/client"
6
+ require_relative "apmlens/query_tracking_middleware"
7
+ require_relative "apmlens/railtie" if defined?(Rails)
8
+
9
+ # The Main Entry Point
10
+ # This file is loaded when user does `require 'apmlens'`
11
+ module Apmlens
12
+ class << self
13
+ # @return [Apmlens::Configuration]
14
+ def configuration
15
+ @configuration ||= Configuration.new
16
+ end
17
+
18
+ # Configure the gem in an initializer
19
+ def configure
20
+ yield(configuration)
21
+ configuration.enable!
22
+ start!
23
+ end
24
+
25
+ # Initialize the background worker
26
+ def start!
27
+ return unless configuration.enabled?
28
+ Client.instance.start!
29
+ end
30
+
31
+ # Public API: Notify an error
32
+ def capture_error(exception, context = {})
33
+ return unless configuration.enabled?
34
+ Client.instance.capture_error(exception, context)
35
+ end
36
+
37
+ # Public API: Record a metric
38
+ def capture_trace(name, value, tags = {})
39
+ return unless configuration.enabled?
40
+ Client.instance.capture_trace(name, value, tags)
41
+ end
42
+ end
43
+ end
metadata ADDED
@@ -0,0 +1,79 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: apmlens
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - APMLens Team
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: rspec
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: '3.12'
19
+ type: :development
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: '3.12'
26
+ - !ruby/object:Gem::Dependency
27
+ name: webmock
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - "~>"
31
+ - !ruby/object:Gem::Version
32
+ version: '3.18'
33
+ type: :development
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - "~>"
38
+ - !ruby/object:Gem::Version
39
+ version: '3.18'
40
+ description: A lightweight, non-blocking APM agent that monitors errors and performance
41
+ metrics with client-side aggregation.
42
+ email:
43
+ - help@apmlens.com
44
+ executables: []
45
+ extensions: []
46
+ extra_rdoc_files: []
47
+ files:
48
+ - LICENSE.txt
49
+ - README.md
50
+ - lib/apmlens.rb
51
+ - lib/apmlens/client.rb
52
+ - lib/apmlens/configuration.rb
53
+ - lib/apmlens/query_tracking_middleware.rb
54
+ - lib/apmlens/railtie.rb
55
+ - lib/apmlens/version.rb
56
+ homepage: https://apmlens.com
57
+ licenses:
58
+ - MIT
59
+ metadata:
60
+ homepage_uri: https://apmlens.com
61
+ source_code_uri: https://github.com/apmlens/apmlens
62
+ rdoc_options: []
63
+ require_paths:
64
+ - lib
65
+ required_ruby_version: !ruby/object:Gem::Requirement
66
+ requirements:
67
+ - - ">="
68
+ - !ruby/object:Gem::Version
69
+ version: 3.0.0
70
+ required_rubygems_version: !ruby/object:Gem::Requirement
71
+ requirements:
72
+ - - ">="
73
+ - !ruby/object:Gem::Version
74
+ version: '0'
75
+ requirements: []
76
+ rubygems_version: 3.6.7
77
+ specification_version: 4
78
+ summary: Official APMLens APM Agent for Ruby
79
+ test_files: []