posthog-rails 3.23.0 → 3.25.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: eb2bfa860e2d1ca788adc0bec17f3be4a81adc3a8f0fb372589dd0e4e7bbaf05
4
- data.tar.gz: 162adfdd32fe7a1f5ae1df7105a3bff5a6bb30163b4f63baffaa216679bb39c9
3
+ metadata.gz: 94abc2b8a286465010b2f0ab2581933e9d2fa68abcdb145e7076193a21cfe854
4
+ data.tar.gz: 8d220b357b4a739bd50b791bce91ccbe053978866875deb8ad69a9d247336d6d
5
5
  SHA512:
6
- metadata.gz: 5e8cbf5fff7bbf47b38f2d8aa8f1f9bc79ac96bcd45853b11ecd950a94b0cb9ca8ff921f15b143a63b04ff6ace705a3d7464856b68653e50d96cd9394b7c08ba
7
- data.tar.gz: 1d14eadae606d7bda8cbee71891f11f65af3fa9c9af48ad9e0559b5c98a4311c7ec5427b5b788fee6333950832eb36f050e83b30661a0f354932482fded38972
6
+ metadata.gz: 9a50c5a41a58e760e75458379d55f3054768b81c413929dfa3177bc33311d139fa61807f69678a6f9ad3ee6b20c5592fea0007f9b480c0a6607ecc6fc0887db6
7
+ data.tar.gz: f140b196bb5487e4e33fb4eda36f6581fb44acc62a7a27ee322da653585cdbe6dd9be4df86b53e03c9d8bc2b6deb5d1fbffc756f31999598b3cbc4fe63fbd561
@@ -10,7 +10,8 @@
10
10
  # These settings control how PostHog integrates with Rails features.
11
11
 
12
12
  PostHog::Rails.configure do |config|
13
- # Automatically capture exceptions (default: false)
13
+ # Automatically capture exceptions, including terminating rails runner failures (default: false)
14
+ # Successful runner exits are ignored; failures are captured before SDK shutdown
14
15
  # Includes Action Cable connect/disconnect, channel subscribe/unsubscribe, and channel actions.
15
16
  # config.auto_capture_exceptions = true
16
17
 
@@ -22,6 +23,10 @@ PostHog::Rails.configure do |config|
22
23
  # Set to true to enable automatic ActiveJob exception tracking
23
24
  # config.auto_instrument_active_job = true
24
25
 
26
+ # Report failures when Active Job schedules a retry (default: false)
27
+ # Requires auto_instrument_active_job; terminal unhandled failures are already reported.
28
+ # config.report_active_job_retries = true
29
+
25
30
  # Use PostHog tracing headers for request-scoped identity/session context (default: true)
26
31
  # Request metadata (current URL, method, path, user agent, and IP) is always captured during Rails requests
27
32
  # Set to false to ignore client-supplied X-PostHog-Distinct-Id and X-PostHog-Session-Id headers
@@ -185,6 +190,15 @@ PostHog.init do |config|
185
190
  # config.test_mode = true if Rails.env.test? || Rails.env.development?
186
191
  end
187
192
 
193
+ # ============================================================================
194
+ # OPTIONAL SIDEKIQ INTEGRATION (Rails 7.1+, Sidekiq 7.0.3+)
195
+ # ============================================================================
196
+ # Install explicitly to report only terminal job failures. Other policies: :all, :dead.
197
+ # require 'posthog/rails/sidekiq'
198
+ # Sidekiq.configure_server do |config|
199
+ # PostHog::Rails::Sidekiq.install(config, error_reporting: :exhausted)
200
+ # end
201
+
188
202
  # ============================================================================
189
203
  # DEFAULT EXCLUDED EXCEPTIONS
190
204
  # ============================================================================
@@ -6,8 +6,29 @@ require 'posthog/rails/request_metadata'
6
6
 
7
7
  module PostHog
8
8
  module Rails
9
+ # @api private
10
+ class ActionCableExceptionContext < ExceptionContext
11
+ def initialize(request, connection)
12
+ super(request)
13
+ @connection = connection
14
+ end
15
+
16
+ private
17
+
18
+ def extract_current_user(controller)
19
+ return super if controller
20
+
21
+ method_name = PostHog::Rails.config&.current_user_method || :current_user
22
+ @connection.send(method_name) if @connection.respond_to?(method_name, true)
23
+ rescue StandardError
24
+ nil
25
+ end
26
+ end
27
+
9
28
  # @api private
10
29
  class ActionCableCapture < CaptureExceptions
30
+ include ParameterFilter
31
+
11
32
  def initialize(connection, operation, channel: nil, data: nil)
12
33
  super(nil)
13
34
  @connection = connection
@@ -76,16 +97,7 @@ module PostHog
76
97
  end
77
98
 
78
99
  def extract_distinct_id(env)
79
- super
80
- rescue StandardError
81
- nil
82
- end
83
-
84
- def extract_current_user(controller)
85
- return super if controller
86
-
87
- method_name = PostHog::Rails.config&.current_user_method || :current_user
88
- @connection.send(method_name) if @connection.respond_to?(method_name, true)
100
+ ActionCableExceptionContext.new(ActionDispatch::Request.new(env), @connection).distinct_id
89
101
  rescue StandardError
90
102
  nil
91
103
  end
@@ -213,7 +225,7 @@ module PostHog
213
225
  end
214
226
  end
215
227
 
216
- private_constant :ActionCableCapture, :ActionCableContext,
228
+ private_constant :ActionCableExceptionContext, :ActionCableCapture, :ActionCableContext,
217
229
  :ActionCableConnectionExtensions, :ActionCableChannelExtensions,
218
230
  :ActionCableDispatch, :ActionCableSubscriptionsExtensions
219
231
  end
@@ -13,8 +13,34 @@ module PostHog
13
13
  def self.prepended(base)
14
14
  base.extend(ClassMethods)
15
15
  base.around_perform :with_posthog_job_context, prepend: true if base.respond_to?(:around_perform)
16
+ base.prepend(LegacyRetryReporting) if ::ActiveJob::VERSION::MAJOR < 6
17
+ return if @retry_subscription
18
+
19
+ @retry_subscription = ActiveSupport::Notifications.subscribe('enqueue_retry.active_job') do |*args|
20
+ payload = args.last
21
+ job = payload[:job]
22
+ job.send(:capture_posthog_retry, payload[:error]) if job.is_a?(ActiveJobExtensions)
23
+ end
16
24
  end
17
25
 
26
+ # Active Job 5.2 neither emits enqueue_retry nor passes the error to retry_job.
27
+ module LegacyRetryReporting
28
+ # @api private
29
+ def rescue_with_handler(exception, ...)
30
+ previous_exception = @posthog_retry_exception
31
+ @posthog_retry_exception = exception
32
+ super
33
+ ensure
34
+ @posthog_retry_exception = previous_exception
35
+ end
36
+
37
+ # @api private
38
+ def retry_job(...)
39
+ super.tap { capture_posthog_retry(@posthog_retry_exception) }
40
+ end
41
+ end
42
+ private_constant :LegacyRetryReporting
43
+
18
44
  module ClassMethods
19
45
  # DSL for defining how to extract distinct_id from job arguments.
20
46
  #
@@ -148,7 +174,34 @@ module PostHog
148
174
  nil
149
175
  end
150
176
 
151
- def capture_job_exception(exception)
177
+ def capture_posthog_retry(exception)
178
+ config = PostHog::Rails.config
179
+ return unless config&.auto_instrument_active_job && config.report_active_job_retries && exception
180
+ return unless PostHog.initialized? && PostHog.client.enabled?
181
+ return if excluded_posthog_retry?(exception, config)
182
+
183
+ Internal::Context.with_context(
184
+ @posthog_execution_context || posthog_job_context, fresh: true, enrich_current_span: false
185
+ ) do
186
+ capture_job_exception(exception, retry_failure: true)
187
+ end
188
+ rescue StandardError => e
189
+ PostHog::Logging.logger.error("Failed to capture job retry: #{e.class}")
190
+ end
191
+
192
+ def excluded_posthog_retry?(exception, config)
193
+ seen = {}.compare_by_identity
194
+ current = exception
195
+ while current && seen.size < PostHog::ExceptionCapture::MAX_CHAINED_EXCEPTIONS && !seen.key?(current)
196
+ return true unless config.should_capture_exception?(current)
197
+
198
+ seen[current] = true
199
+ current = current.respond_to?(:cause) ? current.cause : nil
200
+ end
201
+ false
202
+ end
203
+
204
+ def capture_job_exception(exception, retry_failure: false)
152
205
  return unless PostHog::Rails.config&.auto_instrument_active_job
153
206
 
154
207
  # Build distinct_id from job arguments if possible
@@ -159,7 +212,7 @@ module PostHog
159
212
  end
160
213
 
161
214
  properties = {
162
- '$exception_source' => 'active_job',
215
+ '$exception_source' => retry_failure ? 'rails.active_job' : 'active_job',
163
216
  '$job_class' => self.class.name,
164
217
  '$job_id' => job_id,
165
218
  '$queue_name' => queue_name,
@@ -167,14 +220,18 @@ module PostHog
167
220
  '$job_executions' => executions
168
221
  }
169
222
 
223
+ properties['$exception_level'] = 'error' if retry_failure
224
+
170
225
  # Add serialized job arguments (be careful with sensitive data)
171
226
  properties['$job_arguments'] = sanitize_job_arguments(arguments) if arguments.present?
172
227
 
228
+ return if defined?(PostHog::Rails::Sidekiq) && Sidekiq.defer_capture?(exception, distinct_id, properties)
229
+
173
230
  PostHog.capture_exception(
174
231
  exception,
175
232
  distinct_id,
176
233
  properties,
177
- mechanism: { 'type' => 'active_job', 'handled' => false }
234
+ mechanism: { 'type' => retry_failure ? 'task' : 'active_job', 'handled' => retry_failure }
178
235
  )
179
236
  rescue StandardError => e
180
237
  # Don't let PostHog errors break job processing
@@ -1,6 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'posthog/rails/parameter_filter'
3
+ require 'posthog/rails/exception_context'
4
4
 
5
5
  module PostHog
6
6
  module Rails
@@ -8,8 +8,6 @@ module PostHog
8
8
  #
9
9
  # @api private
10
10
  class CaptureExceptions
11
- include ParameterFilter
12
-
13
11
  # @param app [#call] Rack application.
14
12
  def initialize(app)
15
13
  @app = app
@@ -51,8 +49,9 @@ module PostHog
51
49
 
52
50
  def capture_exception(exception, env)
53
51
  request = ActionDispatch::Request.new(env)
54
- distinct_id = extract_distinct_id(env)
55
- additional_properties = build_properties(request, env)
52
+ context = ExceptionContext.new(request)
53
+ distinct_id = context.distinct_id
54
+ additional_properties = { '$exception_source' => 'rails' }.merge(context.properties)
56
55
 
57
56
  PostHog.capture_exception(
58
57
  exception,
@@ -65,99 +64,10 @@ module PostHog
65
64
  PostHog::Logging.logger.error("Backtrace: #{e.backtrace&.first(5)&.join("\n")}")
66
65
  end
67
66
 
68
- def extract_distinct_id(env)
69
- # Prefer authenticated Rails user context. Request/tracing context is
70
- # applied later by the core capture path if this returns nil.
71
- return nil unless PostHog::Rails.config&.capture_user_context
72
-
73
- user = extract_current_user(env['action_controller.instance'])
74
- user_id = extract_user_id(user) if user
75
- return user_id if present?(user_id)
76
-
77
- nil
78
- end
79
-
80
- def extract_current_user(controller)
81
- resolver = PostHog::Rails.config&.current_user_resolver
82
- return resolve_current_user(resolver, controller) if resolver
83
-
84
- method_name = PostHog::Rails.config&.current_user_method || :current_user
85
- return unless controller.respond_to?(method_name, true)
86
-
87
- controller.send(method_name)
88
- end
89
-
90
- def resolve_current_user(resolver, controller)
91
- call_current_user_resolver(resolver, controller)
92
- rescue StandardError => e
93
- PostHog::Logging.logger.warn("current_user_resolver failed: #{e.message}")
94
- nil
95
- end
96
-
97
- def call_current_user_resolver(resolver, controller)
98
- if resolver.arity.zero?
99
- controller ? controller.instance_exec(&resolver) : resolver.call
100
- elsif controller
101
- resolver.call(controller)
102
- end
103
- end
104
-
105
- def extract_user_id(user)
106
- # Use configured method if specified
107
- method_name = PostHog::Rails.config&.user_id_method
108
- return user.send(method_name) if method_name && user.respond_to?(method_name)
109
-
110
- # Try explicit PostHog method (allows users to customize without config)
111
- return user.posthog_distinct_id if user.respond_to?(:posthog_distinct_id)
112
- return user.distinct_id if user.respond_to?(:distinct_id)
113
-
114
- # Try common ID methods
115
- return user.id if user.respond_to?(:id)
116
- return user['id'] if user.respond_to?(:[]) && user['id']
117
- return user.pk if user.respond_to?(:pk)
118
- return user['pk'] if user.respond_to?(:[]) && user['pk']
119
- return user.uuid if user.respond_to?(:uuid)
120
- return user['uuid'] if user.respond_to?(:[]) && user['uuid']
121
-
122
- user.to_s
123
- end
124
-
125
- def build_properties(request, env)
126
- properties = {
127
- '$exception_source' => 'rails'
128
- }
129
-
130
- # Add controller and action if available
131
- if env['action_controller.instance']
132
- controller = env['action_controller.instance']
133
- properties['$controller'] = safe_serialize(controller.controller_name)
134
- properties['$action'] = safe_serialize(controller.action_name)
135
- end
136
-
137
- # Add request parameters (be careful with sensitive data)
138
- if request.params.present?
139
- filtered_params = filter_sensitive_params(request.params)
140
- # Safe serialize to handle any complex objects in params
141
- properties['$request_params'] = safe_serialize(filtered_params) unless filtered_params.empty?
142
- end
143
-
144
- response_status_code = env['posthog.response_status_code']
145
- properties['$response_status_code'] = response_status_code if response_status_code
146
-
147
- # Add referrer
148
- properties['$referrer'] = safe_serialize(request.referrer) if request.referrer
149
-
150
- properties
151
- end
152
-
153
67
  def response_status(response)
154
68
  status = response.respond_to?(:[]) ? response[0] : nil
155
69
  status if status.is_a?(Integer)
156
70
  end
157
-
158
- def present?(value)
159
- !(value.nil? || (value.respond_to?(:empty?) && value.empty?))
160
- end
161
71
  end
162
72
  end
163
73
  end
@@ -19,6 +19,10 @@ module PostHog
19
19
  # @return [Boolean] Whether to automatically instrument ActiveJob. Defaults to false.
20
20
  attr_accessor :auto_instrument_active_job
21
21
 
22
+ # @return [Boolean] Whether to report each Active Job retry failure. Requires auto_instrument_active_job.
23
+ # Defaults to false.
24
+ attr_accessor :report_active_job_retries
25
+
22
26
  # @return [Array<String>] Exception class names to ignore in addition to the defaults.
23
27
  attr_accessor :excluded_exceptions
24
28
 
@@ -73,6 +77,7 @@ module PostHog
73
77
  @auto_capture_exceptions = false
74
78
  @report_rescued_exceptions = false
75
79
  @auto_instrument_active_job = false
80
+ @report_active_job_retries = false
76
81
  @excluded_exceptions = []
77
82
  @use_tracing_headers = true
78
83
  @capture_user_context = true
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'posthog/rails/exception_context'
4
+
5
+ module PostHog
6
+ module Rails
7
+ module ControllerHelpers
8
+ private
9
+
10
+ # Report a handled exception with filtered Rails request context.
11
+ # Manual reporting is independent of automatic capture and its exclusions.
12
+ #
13
+ # @param exception [Exception, String, Object] Input accepted by {PostHog::Client#capture_exception}.
14
+ # @param distinct_id [String, nil] Explicit identity, before configured user and request identity.
15
+ # @param additional_properties [Hash, nil] Explicit properties override inferred request properties.
16
+ # @param flags [PostHog::FeatureFlagEvaluations, nil] Flag evaluation snapshot.
17
+ # @param mechanism [Hash, nil] Explicit exception mechanism; defaults to core manual capture semantics.
18
+ # @return [Boolean, nil] The result of {PostHog.capture_exception}, or false when unavailable or capture fails.
19
+ def capture_exception(exception, distinct_id = nil, additional_properties = {}, flags: nil, mechanism: nil)
20
+ return false unless PostHog.initialized? && PostHog.client.enabled?
21
+
22
+ context = ExceptionContext.new(request, self, manual: true)
23
+ distinct_id = context.distinct_id if distinct_id.nil?
24
+ properties = context.properties.merge(additional_properties || {})
25
+
26
+ PostHog.capture_exception(exception, distinct_id, properties, flags: flags, mechanism: mechanism)
27
+ rescue StandardError
28
+ PostHog::Logging.logger.error('Failed to capture controller exception')
29
+ false
30
+ end
31
+ end
32
+ end
33
+ end
@@ -19,7 +19,10 @@ module PostHog
19
19
  # @return [void]
20
20
  def report(error, handled:, severity:, context:, source: nil)
21
21
  return unless PostHog::Rails.config&.auto_capture_exceptions
22
- return unless PostHog::Rails.config&.should_capture_exception?(error)
22
+
23
+ runner_report = !handled && source == 'application.runner.railties'
24
+ return unless runner_report || PostHog::Rails.config&.should_capture_exception?(error)
25
+ return if defined?(PostHog::Rails::Sidekiq) && Sidekiq.suppress_rails_report?(error, source)
23
26
 
24
27
  if defined?(::Sidekiq::JobRetry::Handled) && error.is_a?(::Sidekiq::JobRetry::Handled)
25
28
  error = error.cause || error
@@ -43,6 +46,12 @@ module PostHog
43
46
  end
44
47
  end
45
48
 
49
+ # Keep the reporter's object and serialized context until terminal capture.
50
+ if runner_report
51
+ Thread.current[:posthog_rails_runner_report] = [error, distinct_id, properties]
52
+ return
53
+ end
54
+
46
55
  PostHog.capture_exception(
47
56
  error,
48
57
  distinct_id,
@@ -53,6 +62,27 @@ module PostHog
53
62
  PostHog::Logging.logger.error("Failed to report error via subscriber: #{e.message}")
54
63
  PostHog::Logging.logger.error("Backtrace: #{e.backtrace&.first(5)&.join("\n")}")
55
64
  end
65
+
66
+ def self.take_runner_report(exception)
67
+ report = Thread.current[:posthog_rails_runner_report]
68
+ Thread.current[:posthog_rails_runner_report] = nil
69
+ return report if report && report.first.equal?(exception)
70
+
71
+ # Rails also converts inline errors when --skip-executor prevents a report.
72
+ # Only its command conversion may replace the terminal exception.
73
+ return unless exception.is_a?(SystemExit) && exception.status == 1
74
+
75
+ original = exception.cause
76
+ return unless original.is_a?(NameError) || original.is_a?(SyntaxError)
77
+ return unless defined?(::Rails::Command::RunnerCommand)
78
+
79
+ # Inline eval shares Rails' filename, so also check the caller beyond exit.
80
+ location = exception.backtrace_locations&.find { |frame| frame.base_label != 'exit' }
81
+ return unless location&.base_label == 'perform'
82
+ return unless location.path == ::Rails::Command::RunnerCommand.instance_method(:perform).source_location.first
83
+
84
+ report && report.first.equal?(original) ? report : [original, nil, {}]
85
+ end
56
86
  end
57
87
  end
58
88
  end
@@ -0,0 +1,155 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'posthog/rails/parameter_filter'
4
+ require 'posthog/rails/request_metadata'
5
+
6
+ module PostHog
7
+ module Rails
8
+ # Shared request enrichment for automatic and manual exception capture.
9
+ #
10
+ # @api private
11
+ class ExceptionContext
12
+ include ParameterFilter
13
+
14
+ def initialize(request, controller = request.env['action_controller.instance'], manual: false)
15
+ @request = request
16
+ @controller = controller
17
+ @manual = manual
18
+ end
19
+
20
+ def distinct_id
21
+ # Prefer authenticated Rails user context. Request/tracing context is
22
+ # applied later by the core capture path if this returns nil.
23
+ return nil unless PostHog::Rails.config&.capture_user_context
24
+
25
+ user = extract_current_user(@controller)
26
+ user_id = extract_user_id(user) if user
27
+ return user_id if present?(user_id)
28
+
29
+ nil
30
+ rescue StandardError
31
+ raise unless @manual
32
+
33
+ nil
34
+ end
35
+
36
+ def properties
37
+ request = @request
38
+ env = request.env
39
+ properties = @manual ? RequestMetadata.extract(request) : {}
40
+
41
+ # Add controller and action if available
42
+ if @controller
43
+ controller = @controller
44
+ properties['$controller'] = safe_serialize(controller.controller_name)
45
+ properties['$action'] = safe_serialize(controller.action_name)
46
+ end
47
+
48
+ # Add request parameters (be careful with sensitive data)
49
+ params = request_parameters
50
+ if params.present?
51
+ filtered_params = filter_request_parameters(params)
52
+ # Safe serialize to handle any complex objects in params
53
+ properties['$request_params'] = safe_serialize(filtered_params) unless filtered_params.empty?
54
+ end
55
+
56
+ status = env['posthog.response_status_code']
57
+ status ||= @controller.response.status if @manual && @controller&.performed?
58
+ properties['$response_status_code'] = status if status
59
+
60
+ # Add referrer
61
+ properties['$referrer'] = safe_serialize(request.referrer) if request.referrer
62
+
63
+ if @manual
64
+ %w[$current_url $referrer].each do |key|
65
+ properties[key] = properties[key].split(/[?#]/, 2).first if properties[key]
66
+ end
67
+ end
68
+
69
+ properties
70
+ rescue StandardError
71
+ raise unless @manual
72
+
73
+ {}
74
+ end
75
+
76
+ private
77
+
78
+ def request_parameters
79
+ return @request.params unless @manual
80
+
81
+ # Only Rails-owned parsed caches are safe to read without invoking body-parser diagnostics.
82
+ cached = @request.get_header('action_dispatch.request.parameters')
83
+ return cached if cached.is_a?(Hash)
84
+
85
+ body = @request.get_header('action_dispatch.request.request_parameters')
86
+ body = {} unless body.is_a?(Hash)
87
+ body.merge(@request.query_parameters).merge(@request.path_parameters)
88
+ rescue StandardError
89
+ raise unless @manual
90
+
91
+ {}
92
+ end
93
+
94
+ def filter_request_parameters(params)
95
+ if @manual && @request.has_header?('action_dispatch.parameter_filter')
96
+ ParameterFilter.backend.new(@request.get_header('action_dispatch.parameter_filter')).filter(params)
97
+ else
98
+ filter_sensitive_params(params)
99
+ end
100
+ end
101
+
102
+ def extract_current_user(controller)
103
+ resolver = PostHog::Rails.config&.current_user_resolver
104
+ return resolve_current_user(resolver, controller) if resolver
105
+
106
+ method_name = PostHog::Rails.config&.current_user_method || :current_user
107
+ return unless controller.respond_to?(method_name, true)
108
+
109
+ controller.send(method_name)
110
+ end
111
+
112
+ def resolve_current_user(resolver, controller)
113
+ call_current_user_resolver(resolver, controller)
114
+ rescue StandardError => e
115
+ message = @manual ? 'current_user_resolver failed' : "current_user_resolver failed: #{e.message}"
116
+ PostHog::Logging.logger.warn(message)
117
+ nil
118
+ end
119
+
120
+ def call_current_user_resolver(resolver, controller)
121
+ if resolver.arity.zero?
122
+ controller ? controller.instance_exec(&resolver) : resolver.call
123
+ elsif controller
124
+ resolver.call(controller)
125
+ end
126
+ end
127
+
128
+ def extract_user_id(user)
129
+ # Use configured method if specified
130
+ method_name = PostHog::Rails.config&.user_id_method
131
+ return user.send(method_name) if method_name && user.respond_to?(method_name)
132
+
133
+ # Try explicit PostHog method (allows users to customize without config)
134
+ return user.posthog_distinct_id if user.respond_to?(:posthog_distinct_id)
135
+ return user.distinct_id if user.respond_to?(:distinct_id)
136
+
137
+ # Try common ID methods
138
+ return user.id if user.respond_to?(:id)
139
+ return user['id'] if user.respond_to?(:[]) && user['id']
140
+ return user.pk if user.respond_to?(:pk)
141
+ return user['pk'] if user.respond_to?(:[]) && user['pk']
142
+ return user.uuid if user.respond_to?(:uuid)
143
+ return user['uuid'] if user.respond_to?(:[]) && user['uuid']
144
+
145
+ user.to_s
146
+ end
147
+
148
+ def present?(value)
149
+ !(value.nil? || (value.respond_to?(:empty?) && value.empty?))
150
+ end
151
+ end
152
+
153
+ private_constant :ExceptionContext
154
+ end
155
+ end
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require 'English'
3
4
  require 'posthog/rails/facade'
4
5
 
5
6
  module PostHog
@@ -11,6 +12,13 @@ module PostHog
11
12
  PostHog::Rails.install_posthog_facade!
12
13
  end
13
14
 
15
+ initializer 'posthog.controller_helpers' do
16
+ ActiveSupport.on_load(:action_controller) do
17
+ include PostHog::Rails::ControllerHelpers unless method_defined?(:capture_exception) ||
18
+ private_method_defined?(:capture_exception)
19
+ end
20
+ end
21
+
14
22
  # Insert middleware for request context and exception capturing
15
23
  initializer 'posthog.insert_middlewares' do |app|
16
24
  # Wrap the Rails exception middleware so request context is active for
@@ -81,17 +89,45 @@ module PostHog
81
89
  install_posthog_logs if PostHog::Rails.config&.logs_enabled
82
90
  end
83
91
 
92
+ runner_started = false
93
+ runner { runner_started = true }
94
+
84
95
  # Ensure PostHog shuts down gracefully (register only once)
85
96
  config.after_initialize do
86
97
  next if @posthog_at_exit_registered
87
98
 
88
99
  @posthog_at_exit_registered = true
89
100
  at_exit do
101
+ capture_runner_exception($ERROR_INFO) if runner_started
90
102
  PostHog::Rails::Logs::Setup.shutdown
91
103
  PostHog.client&.shutdown if PostHog.initialized?
92
104
  end
93
105
  end
94
106
 
107
+ # Use the same exit hook so the terminating event is queued before shutdown
108
+ # drains the client, including on Rails versions without runner error reports.
109
+ def self.capture_runner_exception(exception)
110
+ report = ErrorSubscriber.take_runner_report(exception)
111
+ return unless exception
112
+ return if exception.is_a?(SystemExit) && exception.success?
113
+ return if exception.is_a?(SignalException)
114
+
115
+ exception, distinct_id, properties = report if report
116
+ return unless PostHog.initialized? && PostHog.client.enabled?
117
+ return unless PostHog::Rails.config&.auto_capture_exceptions
118
+ return unless PostHog::Rails.config.should_capture_exception?(exception)
119
+
120
+ PostHog.capture_exception(
121
+ exception,
122
+ distinct_id,
123
+ (properties || {}).merge('$exception_source' => 'rails.runner', '$exception_level' => 'fatal'),
124
+ mechanism: { 'type' => 'at_exit', 'handled' => false, 'synthetic' => false }
125
+ )
126
+ rescue Exception => e # rubocop:disable Lint/RescueException -- Reporting must not replace the terminating exception.
127
+ PostHog::Logging.logger.warn("Failed to capture Rails runner exception: #{e.class}: #{e.message}")
128
+ end
129
+ private_class_method :capture_runner_exception
130
+
95
131
  MISSING_MIDDLEWARE_MESSAGE = 'No such middleware to insert'
96
132
  MIDDLEWARE_FALLBACK_OPERATION = :posthog_insert_middleware_with_fallback
97
133
 
@@ -0,0 +1,160 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'posthog-rails'
4
+ require 'sidekiq'
5
+ require 'posthog/internal/context'
6
+
7
+ module PostHog
8
+ module Rails
9
+ module Sidekiq
10
+ JOB_SCOPE_KEY = :posthog_sidekiq_job
11
+ INSTALLATION_IVAR = :@posthog_sidekiq_integration
12
+ DEFERRED_REPORT_IVAR = :@posthog_sidekiq_report
13
+ Scope = Struct.new(:installation, :previous)
14
+
15
+ # Install job error reporting on a Sidekiq server configuration.
16
+ # @param config [::Sidekiq::Config]
17
+ # @param error_reporting [Symbol] :all, :exhausted, or :dead.
18
+ # @return [void]
19
+ def self.install(config, error_reporting:)
20
+ unless %i[all exhausted dead].include?(error_reporting)
21
+ raise ArgumentError, 'error_reporting must be :all, :exhausted, or :dead'
22
+ end
23
+
24
+ if Gem::Version.new(::Rails.version) < Gem::Version.new('7.1') ||
25
+ Gem::Version.new(::Sidekiq::VERSION) < Gem::Version.new('7.0.3')
26
+ PostHog::Logging.logger.warn(
27
+ 'Sidekiq retry reporting requires Rails 7.1+ and Sidekiq 7.0.3+; leaving existing reporting unchanged.'
28
+ )
29
+ return
30
+ end
31
+
32
+ if (installation = config.instance_variable_get(INSTALLATION_IVAR))
33
+ installation.error_reporting = error_reporting
34
+ return
35
+ end
36
+
37
+ installation = Installation.new(error_reporting)
38
+ config.server_middleware { |chain| chain.prepend(ServerMiddleware, installation) }
39
+ config.capsules.each_value do |capsule|
40
+ # Leave uncached chains lazy so they inherit later global middleware additions.
41
+ capsule.instance_variable_get(:@server_chain)&.prepend(ServerMiddleware, installation)
42
+ end
43
+ config[:error_handlers] = config.error_handlers + [installation.method(:report_error)]
44
+ config[:death_handlers] = config.death_handlers + [installation.method(:report_death)]
45
+ config.instance_variable_set(INSTALLATION_IVAR, installation)
46
+ nil
47
+ end
48
+
49
+ # @api private
50
+ def self.in_job?
51
+ scope = Thread.current[JOB_SCOPE_KEY]
52
+ scope&.installation&.enabled?
53
+ end
54
+
55
+ # @api private
56
+ def self.defer_capture?(error, distinct_id, properties)
57
+ return false unless in_job?
58
+ return true if error.instance_variable_defined?(DEFERRED_REPORT_IVAR)
59
+
60
+ context = Internal::Context.current
61
+ # Sidekiq invokes its handlers after the job's tracing middleware unwinds.
62
+ properties = PostHog.client.send(:active_trace_properties).merge(properties)
63
+ context_data = { distinct_id: context&.distinct_id, session_id: context&.session_id,
64
+ properties: context&.properties }
65
+ error.instance_variable_set(DEFERRED_REPORT_IVAR, [distinct_id, properties, context_data]) unless error.frozen?
66
+ true
67
+ end
68
+
69
+ # @api private
70
+ def self.suppress_rails_report?(error, source)
71
+ scope = Thread.current[JOB_SCOPE_KEY]
72
+ installation = scope&.installation
73
+ # Sidekiq sets its capsule before dispatch, including failures before middleware runs.
74
+ installation ||= Thread.current[:sidekiq_capsule]&.config&.instance_variable_get(INSTALLATION_IVAR)
75
+ return false unless installation&.enabled?
76
+
77
+ source == 'job.sidekiq' || (source == 'application.active_job' && scope) ||
78
+ (defined?(::Sidekiq::JobRetry::Handled) && error.is_a?(::Sidekiq::JobRetry::Handled))
79
+ end
80
+
81
+ class Installation
82
+ attr_accessor :error_reporting
83
+
84
+ def initialize(error_reporting)
85
+ @error_reporting = error_reporting
86
+ end
87
+
88
+ def enabled?
89
+ PostHog.initialized? && PostHog.client.enabled?
90
+ end
91
+
92
+ def with_job
93
+ scope = Scope.new(self, Thread.current[JOB_SCOPE_KEY])
94
+ Thread.current[JOB_SCOPE_KEY] = scope
95
+ yield
96
+ ensure
97
+ Thread.current[JOB_SCOPE_KEY] = scope.previous
98
+ end
99
+
100
+ def report_error(error, context, _config = nil)
101
+ return unless enabled? && error_reporting == :all
102
+ return unless context[:job].is_a?(Hash)
103
+
104
+ capture(error, 'sidekiq.error_handler')
105
+ end
106
+
107
+ def report_death(job, error)
108
+ return unless enabled? && job.is_a?(Hash)
109
+ return unless error_reporting == :exhausted ||
110
+ (error_reporting == :dead && job['retry'] && job['dead'] != false && !job['discarded_at'])
111
+
112
+ capture(error, 'sidekiq.death_handler')
113
+ end
114
+
115
+ private
116
+
117
+ def capture(error, source)
118
+ return if excluded?(error)
119
+
120
+ distinct_id, properties, context = error.instance_variable_get(DEFERRED_REPORT_IVAR)
121
+ properties = (properties || {}).merge('$exception_source' => source, '$exception_level' => 'error')
122
+ Internal::Context.with_context(context, fresh: true, owner: PostHog.client, enrich_current_span: false) do
123
+ PostHog.capture_exception(
124
+ error, distinct_id, properties, mechanism: { 'type' => 'task', 'handled' => false }
125
+ )
126
+ end
127
+ rescue StandardError => e
128
+ PostHog::Logging.logger.error("Failed to capture Sidekiq job error: #{e.class}")
129
+ end
130
+
131
+ def excluded?(error)
132
+ seen = {}.compare_by_identity
133
+ current = error
134
+ while current && seen.size < PostHog::ExceptionCapture::MAX_CHAINED_EXCEPTIONS && !seen.key?(current)
135
+ return true unless PostHog::Rails.config.should_capture_exception?(current)
136
+
137
+ seen[current] = true
138
+ current = current.cause
139
+ end
140
+ false
141
+ end
142
+ end
143
+
144
+ class ServerMiddleware
145
+ def initialize(installation)
146
+ @installation = installation
147
+ end
148
+
149
+ def call(_worker, _job, _queue, &block)
150
+ return yield unless @installation.enabled?
151
+
152
+ @installation.with_job(&block)
153
+ end
154
+ end
155
+
156
+ private_constant :JOB_SCOPE_KEY, :INSTALLATION_IVAR, :DEFERRED_REPORT_IVAR,
157
+ :Scope, :Installation, :ServerMiddleware
158
+ end
159
+ end
160
+ end
@@ -79,12 +79,13 @@ module PostHog
79
79
  private
80
80
 
81
81
  def capture_streaming_exception(exception, source, env = nil)
82
- properties = env ? build_properties(ActionDispatch::Request.new(env), env) : {}
82
+ context = ExceptionContext.new(ActionDispatch::Request.new(env)) if env
83
+ properties = context ? context.properties : {}
83
84
  properties['$exception_source'] = source
84
85
  properties['$exception_level'] = 'error'
85
86
  PostHog.capture_exception(
86
87
  exception,
87
- env ? extract_distinct_id(env) : nil,
88
+ context&.distinct_id,
88
89
  properties,
89
90
  mechanism: { 'type' => 'middleware', 'handled' => false }
90
91
  )
@@ -2,6 +2,6 @@
2
2
 
3
3
  module PostHog
4
4
  module Rails
5
- VERSION = '3.23.0'
5
+ VERSION = '3.25.0'
6
6
  end
7
7
  end
data/lib/posthog/rails.rb CHANGED
@@ -6,6 +6,7 @@ require 'posthog/rails/tracing_headers'
6
6
  require 'posthog/rails/request_metadata'
7
7
  require 'posthog/rails/request_context'
8
8
  require 'posthog/rails/capture_exceptions'
9
+ require 'posthog/rails/controller_helpers'
9
10
  require 'posthog/rails/streaming_exceptions'
10
11
  require 'posthog/rails/rescued_exception_interceptor'
11
12
  require 'posthog/rails/active_job'
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: posthog-rails
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.23.0
4
+ version: 3.25.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - PostHog
@@ -52,7 +52,9 @@ files:
52
52
  - lib/posthog/rails/active_job.rb
53
53
  - lib/posthog/rails/capture_exceptions.rb
54
54
  - lib/posthog/rails/configuration.rb
55
+ - lib/posthog/rails/controller_helpers.rb
55
56
  - lib/posthog/rails/error_subscriber.rb
57
+ - lib/posthog/rails/exception_context.rb
56
58
  - lib/posthog/rails/facade.rb
57
59
  - lib/posthog/rails/logs/appender.rb
58
60
  - lib/posthog/rails/logs/notifications.rb
@@ -64,6 +66,7 @@ files:
64
66
  - lib/posthog/rails/request_context.rb
65
67
  - lib/posthog/rails/request_metadata.rb
66
68
  - lib/posthog/rails/rescued_exception_interceptor.rb
69
+ - lib/posthog/rails/sidekiq.rb
67
70
  - lib/posthog/rails/streaming_exceptions.rb
68
71
  - lib/posthog/rails/tracing_headers.rb
69
72
  - lib/posthog/rails/version.rb