posthog-rails 3.21.0 → 3.23.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: 80e2400e119100e9916f8ecc8092d96b0d9552596c8c865895cf36e4389f78cb
4
- data.tar.gz: 80c09b13dbafaf6f9a5efe3359e9a02dc4d92175a493f214d885c82f6194c9d8
3
+ metadata.gz: eb2bfa860e2d1ca788adc0bec17f3be4a81adc3a8f0fb372589dd0e4e7bbaf05
4
+ data.tar.gz: 162adfdd32fe7a1f5ae1df7105a3bff5a6bb30163b4f63baffaa216679bb39c9
5
5
  SHA512:
6
- metadata.gz: 89ebcf81d463b9b3990500f95b0a73dc5c7ba6e3b06d7573a96c7c9299a31ef007ec116649733f6629809be4809b8aea5e774d1ff8ed271f486fcb658f42135f
7
- data.tar.gz: b150e2c4c23ac510bd0b6b50fb64a3c8290bf01503bae5d2795a8c5f214104c7c1ec72a5e47f51442cc35627a71630e4195610cf2532dfb340609cb48df1748b
6
+ metadata.gz: 5e8cbf5fff7bbf47b38f2d8aa8f1f9bc79ac96bcd45853b11ecd950a94b0cb9ca8ff921f15b143a63b04ff6ace705a3d7464856b68653e50d96cd9394b7c08ba
7
+ data.tar.gz: 1d14eadae606d7bda8cbee71891f11f65af3fa9c9af48ad9e0559b5c98a4311c7ec5427b5b788fee6333950832eb36f050e83b30661a0f354932482fded38972
@@ -11,7 +11,7 @@
11
11
 
12
12
  PostHog::Rails.configure do |config|
13
13
  # Automatically capture exceptions (default: false)
14
- # Set to true to enable automatic exception tracking
14
+ # Includes Action Cable connect/disconnect, channel subscribe/unsubscribe, and channel actions.
15
15
  # config.auto_capture_exceptions = true
16
16
 
17
17
  # Report exceptions that Rails rescues (e.g., with rescue_from) (default: false)
@@ -70,6 +70,18 @@ PostHog::Rails.configure do |config|
70
70
  # Broadcast Rails.logger into PostHog Logs (default: true when logs enabled)
71
71
  # config.logs_forward_rails_logger = true
72
72
 
73
+ # Structured notification logs (default: []; requires logs_enabled).
74
+ # Select only installed components; this does not load optional Rails components.
75
+ # Set logs_forward_rails_logger = false to avoid also forwarding generic log lines.
76
+ # config.logs_notifications = [:action_controller, :active_record, :active_job, :action_mailer]
77
+ # SQL records are debug; other successful lifecycle events are info, failures error.
78
+ # Controller params and keyed job arguments respect Rails filter_parameters and
79
+ # are JSON strings in rails.params / rails.job.arguments (bounded to 10 KB).
80
+ # Custom filters see original key/value types; unsafe or oversized parameter
81
+ # trees are redacted as a whole, not truncated before filtering.
82
+ # Unkeyed job arguments are redacted. SQL text/binds, headers/cookies, mail
83
+ # recipients, subject and content are not collected by notification logging.
84
+
73
85
  # Minimum severity to forward; nil inherits Rails.logger's level (default: nil)
74
86
  # config.logs_level = :info
75
87
 
@@ -0,0 +1,220 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'posthog/rails/capture_exceptions'
4
+ require 'posthog/internal/context'
5
+ require 'posthog/rails/request_metadata'
6
+
7
+ module PostHog
8
+ module Rails
9
+ # @api private
10
+ class ActionCableCapture < CaptureExceptions
11
+ def initialize(connection, operation, channel: nil, data: nil)
12
+ super(nil)
13
+ @connection = connection
14
+ @operation = operation
15
+ @channel = channel
16
+ @data = data
17
+ end
18
+
19
+ def call
20
+ with_context do
21
+ yield
22
+ rescue StandardError => e
23
+ dispatch = ActionCableDispatch.current(@connection) if @channel
24
+ if dispatch
25
+ dispatch.defer(self, e)
26
+ else
27
+ capture_exception(e, connection_env)
28
+ end
29
+ raise
30
+ end
31
+ end
32
+
33
+ def with_context(&block)
34
+ Internal::Context.with_context(context_data(connection_env), fresh: true, owner: PostHog.client,
35
+ enrich_current_span: false, &block)
36
+ end
37
+
38
+ def report(exception)
39
+ with_context { capture_exception(exception, connection_env) }
40
+ end
41
+
42
+ private
43
+
44
+ def connection_env
45
+ env = @connection.env if @connection.respond_to?(:env)
46
+ env.is_a?(Hash) ? env : {}
47
+ rescue StandardError
48
+ {}
49
+ end
50
+
51
+ def context_data(env)
52
+ request = ActionDispatch::Request.new(env)
53
+ data = { properties: RequestMetadata.extract(request) }
54
+ return data if PostHog::Rails.config&.use_tracing_headers == false
55
+
56
+ data.merge(
57
+ distinct_id: TracingHeaders.extract_header(request, 'X-POSTHOG-DISTINCT-ID'),
58
+ session_id: TracingHeaders.extract_header(request, 'X-POSTHOG-SESSION-ID')
59
+ )
60
+ rescue StandardError
61
+ {}
62
+ end
63
+
64
+ def capture_exception(exception, env)
65
+ return unless PostHog.initialized? && PostHog.client.enabled?
66
+ return unless should_capture?(exception)
67
+
68
+ PostHog.capture_exception(
69
+ exception,
70
+ extract_distinct_id(env),
71
+ build_cable_properties,
72
+ mechanism: { 'type' => 'middleware', 'handled' => false }
73
+ )
74
+ rescue StandardError => e
75
+ PostHog::Logging.logger.error("Failed to capture Action Cable exception: #{e.class}")
76
+ end
77
+
78
+ 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)
89
+ rescue StandardError
90
+ nil
91
+ end
92
+
93
+ def filter_sensitive_params(params)
94
+ return ParameterFilter::EMPTY_HASH unless params.is_a?(Hash)
95
+
96
+ filters = Array(::Rails.application&.config&.filter_parameters)
97
+ config = @connection.config if @connection.respond_to?(:config)
98
+ filters += Array(config.filter_parameters) if config.respond_to?(:filter_parameters)
99
+ ParameterFilter.backend.new(filters.uniq).filter(params)
100
+ end
101
+
102
+ def build_cable_properties
103
+ properties = {
104
+ '$exception_source' => 'rails.action_cable',
105
+ '$exception_level' => 'error',
106
+ '$action_cable_operation' => @operation,
107
+ '$connection_class' => @connection.class.name
108
+ }
109
+ return properties unless @channel
110
+
111
+ properties['$channel_class'] = @channel.class.name
112
+ properties['$channel_params'] = safe_serialize(filter_sensitive_params(@channel.params))
113
+ if @data
114
+ filtered_data = safe_serialize(filter_sensitive_params(@data))
115
+ properties['$action_data'] = filtered_data
116
+ properties['$action'] = filtered_data['action'].presence || 'receive'
117
+ end
118
+ properties
119
+ end
120
+ end
121
+
122
+ # A channel error reaches connection rescue handlers outside the channel boundary.
123
+ # Keep its capture pending only for the current command, not on the shared socket.
124
+ # @api private
125
+ class ActionCableDispatch
126
+ def self.current(connection)
127
+ dispatch = Thread.current[:posthog_cable_dispatch]
128
+ dispatch if dispatch&.connection.equal?(connection)
129
+ end
130
+
131
+ attr_reader :connection, :exception
132
+ attr_accessor :handled
133
+
134
+ def initialize(connection)
135
+ @connection = connection
136
+ end
137
+
138
+ def defer(capture, exception)
139
+ return if @capture
140
+
141
+ @capture = capture
142
+ @exception = exception
143
+ end
144
+
145
+ def call
146
+ previous = Thread.current[:posthog_cable_dispatch]
147
+ Thread.current[:posthog_cable_dispatch] = self
148
+ result = yield
149
+ @capture&.report(@exception) unless handled
150
+ result
151
+ rescue StandardError => e
152
+ @capture&.report(e)
153
+ raise
154
+ ensure
155
+ Thread.current[:posthog_cable_dispatch] = previous
156
+ end
157
+ end
158
+
159
+ # @api private
160
+ module ActionCableSubscriptionsExtensions
161
+ def execute_command(data)
162
+ ActionCableCapture.new(@connection, 'command').with_context do
163
+ ActionCableDispatch.new(@connection).call { super }
164
+ end
165
+ end
166
+ end
167
+
168
+ # @api private
169
+ module ActionCableContext
170
+ private
171
+
172
+ def with_posthog_cable_context(operation, connection: self, channel: nil, data: nil, &block)
173
+ ActionCableCapture.new(connection, operation, channel: channel, data: data).call(&block)
174
+ end
175
+ end
176
+
177
+ # @api private
178
+ module ActionCableConnectionExtensions
179
+ include ActionCableContext
180
+
181
+ def rescue_with_handler(exception)
182
+ result = super
183
+ dispatch = ActionCableDispatch.current(self)
184
+ dispatch.handled = true if result && dispatch&.exception.equal?(exception)
185
+ result
186
+ end
187
+
188
+ private
189
+
190
+ def handle_open
191
+ with_posthog_cable_context('connect') { super }
192
+ end
193
+
194
+ def handle_close
195
+ with_posthog_cable_context('disconnect') { super }
196
+ end
197
+ end
198
+
199
+ # @api private
200
+ module ActionCableChannelExtensions
201
+ include ActionCableContext
202
+
203
+ def subscribe_to_channel
204
+ with_posthog_cable_context('subscribe', connection: connection, channel: self) { super }
205
+ end
206
+
207
+ def unsubscribe_from_channel
208
+ with_posthog_cable_context('unsubscribe', connection: connection, channel: self) { super }
209
+ end
210
+
211
+ def perform_action(data)
212
+ with_posthog_cable_context('action', connection: connection, channel: self, data: data) { super }
213
+ end
214
+ end
215
+
216
+ private_constant :ActionCableCapture, :ActionCableContext,
217
+ :ActionCableConnectionExtensions, :ActionCableChannelExtensions,
218
+ :ActionCableDispatch, :ActionCableSubscriptionsExtensions
219
+ end
220
+ end
@@ -91,6 +91,11 @@ module PostHog
91
91
 
92
92
  private
93
93
 
94
+ # Completion notifications run after around_perform has restored the parent scope.
95
+ def posthog_logs_context
96
+ @posthog_execution_context || posthog_job_context
97
+ end
98
+
94
99
  def copy_posthog_ids(data)
95
100
  data = {} unless data.is_a?(Hash)
96
101
  %w[distinct_id session_id].each_with_object({}) do |key, result|
@@ -47,6 +47,11 @@ module PostHog
47
47
  # (only takes effect when {#logs_enabled} is true).
48
48
  attr_accessor :logs_forward_rails_logger
49
49
 
50
+ # @return [Array<Symbol>] Components whose notifications produce structured logs. Defaults to [].
51
+ # Supports :action_controller, :active_record, :active_job, and :action_mailer.
52
+ # Only takes effect when logs_enabled is true; components are not loaded automatically.
53
+ attr_accessor :logs_notifications
54
+
50
55
  # @return [Integer, Symbol, nil] Minimum severity to forward to PostHog Logs. When nil, inherits the
51
56
  # current Rails.logger level. Accepts a Logger severity constant (e.g. Logger::INFO) or symbol (:info).
52
57
  attr_accessor :logs_level
@@ -76,6 +81,7 @@ module PostHog
76
81
  @user_id_method = nil
77
82
  @logs_enabled = false
78
83
  @logs_forward_rails_logger = true
84
+ @logs_notifications = []
79
85
  @logs_level = nil
80
86
  @logs_max_records_per_minute = DEFAULT_LOGS_MAX_RECORDS_PER_MINUTE
81
87
  @logs_before_send = nil
@@ -21,6 +21,11 @@ module PostHog
21
21
  return unless PostHog::Rails.config&.auto_capture_exceptions
22
22
  return unless PostHog::Rails.config&.should_capture_exception?(error)
23
23
 
24
+ if defined?(::Sidekiq::JobRetry::Handled) && error.is_a?(::Sidekiq::JobRetry::Handled)
25
+ error = error.cause || error
26
+ return unless PostHog::Rails.config&.should_capture_exception?(error)
27
+ end
28
+
24
29
  distinct_id = context[:user_id] || context[:distinct_id]
25
30
 
26
31
  properties = {
@@ -74,18 +74,22 @@ module PostHog
74
74
  # which, as an Exception, escapes the rescue below and breaks the app.
75
75
  REENTRANCY_KEY = :posthog_rails_logs_emitting
76
76
 
77
+ def accepts_severity?(severity)
78
+ severity >= @threshold
79
+ end
80
+
77
81
  # Mirrors `Logger#add` message/progname resolution, then emits to OTel
78
82
  # instead of writing to a log device.
79
83
  #
80
84
  # @return [Boolean] Always true so it composes with broadcast loggers.
81
- def add(severity, message = nil, progname = nil)
85
+ def add(severity, message = nil, progname = nil, attributes: {})
82
86
  return true if Thread.current[REENTRANCY_KEY]
83
87
 
84
88
  begin
85
89
  Thread.current[REENTRANCY_KEY] = true
86
90
 
87
91
  severity ||= ::Logger::UNKNOWN
88
- return true if severity < @threshold
92
+ return true unless accepts_severity?(severity)
89
93
 
90
94
  if message.nil?
91
95
  if block_given?
@@ -99,7 +103,9 @@ module PostHog
99
103
  return true if message.nil?
100
104
  return true if self_log?(message, progname)
101
105
 
102
- record = apply_before_send(build_record(severity, message, progname))
106
+ record = build_record(severity, message, progname)
107
+ record[:attributes].merge!(attributes)
108
+ record = apply_before_send(record)
103
109
  return true if record.nil?
104
110
 
105
111
  case @rate_limiter&.record
@@ -0,0 +1,293 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+ require 'active_support/lazy_load_hooks'
5
+ require 'active_support/notifications'
6
+ require 'posthog/rails/parameter_filter'
7
+ require 'posthog/internal/context'
8
+
9
+ module PostHog
10
+ module Rails
11
+ module Logs
12
+ # Optional completion records, sharing the ordinary logger's sink and controls.
13
+ # @api private
14
+ module Notifications
15
+ class UnsafeParameters < StandardError; end
16
+ private_constant :UnsafeParameters
17
+
18
+ EVENTS = {
19
+ action_controller: %w[process_action.action_controller],
20
+ active_record: %w[sql.active_record],
21
+ active_job: %w[enqueue.active_job enqueue_at.active_job perform.active_job
22
+ enqueue_retry.active_job retry_stopped.active_job discard.active_job],
23
+ action_mailer: %w[process.action_mailer deliver.action_mailer]
24
+ }.freeze
25
+ SQL_OPERATION = /\A\s*(
26
+ SELECT|INSERT|UPDATE|DELETE|BEGIN|COMMIT|ROLLBACK|SAVEPOINT|RELEASE|WITH|CREATE|ALTER|DROP|PRAGMA|EXPLAIN
27
+ )\b/ix
28
+ BODIES = {
29
+ action_controller: 'Rails controller request completed',
30
+ active_record: 'Rails SQL query completed',
31
+ active_job: 'Rails job lifecycle event',
32
+ action_mailer: 'Rails mailer lifecycle event'
33
+ }.freeze
34
+
35
+ class << self
36
+ def install(appender)
37
+ @appender = appender
38
+ selections = PostHog::Rails.config.logs_notifications
39
+ @components = selections.is_a?(Array) ? selections & EVENTS.keys : []
40
+ if !selections.is_a?(Array) || (selections - EVENTS.keys).any?
41
+ PostHog::Logging.logger.warn('Invalid logs_notifications selection; ignoring unknown components')
42
+ end
43
+ @hooked ||= {}
44
+ @loaded ||= {}
45
+ @subscriptions ||= {}
46
+ @components.each do |component|
47
+ unless @hooked[component]
48
+ @hooked[component] = true
49
+ ActiveSupport.on_load(component) { Notifications.component_loaded(component) }
50
+ end
51
+ subscribe(component) if @loaded[component]
52
+ end
53
+ end
54
+
55
+ def component_loaded(component)
56
+ @loaded[component] = true
57
+ subscribe(component) if @appender && @components.include?(component)
58
+ end
59
+
60
+ def reset
61
+ (@subscriptions || {}).each_value do |subscriptions|
62
+ subscriptions.each { |subscription| ActiveSupport::Notifications.unsubscribe(subscription) }
63
+ end
64
+ @subscriptions = {}
65
+ @components = []
66
+ @appender = nil
67
+ end
68
+
69
+ private
70
+
71
+ def subscribe(component)
72
+ return if @subscriptions.key?(component)
73
+
74
+ @subscriptions[component] = EVENTS.fetch(component).map do |name|
75
+ ActiveSupport::Notifications.subscribe(name) do |*args|
76
+ capture(component, ActiveSupport::Notifications::Event.new(*args))
77
+ end
78
+ end
79
+ end
80
+
81
+ def capture(component, event)
82
+ return unless @appender && PostHog::Rails.config.logs_enabled
83
+ return unless PostHog.initialized? && PostHog.client.enabled?
84
+ return if Thread.current[Appender::REENTRANCY_KEY]
85
+
86
+ payload = event.payload
87
+ error = payload[:exception_object] || payload[:error]
88
+ if component == :active_job && %w[enqueue.active_job enqueue_at.active_job].include?(event.name) &&
89
+ payload[:job].respond_to?(:enqueue_error)
90
+ error ||= payload[:job].enqueue_error
91
+ end
92
+ error_type = error ? error.class.name : Array(payload[:exception]).first
93
+ severity = severity_for(component, payload, error_type)
94
+ return unless @appender.accepts_severity?(severity)
95
+
96
+ attributes = build_attributes(component, event)
97
+ attributes['error.type'] = error_type if error_type.is_a?(String)
98
+ emit_in_context(component, payload) do
99
+ @appender.add(severity, BODIES.fetch(component), attributes: attributes)
100
+ end
101
+ rescue StandardError => e
102
+ return if @warned
103
+
104
+ @warned = true
105
+ PostHog::Logging.logger.warn("PostHog notification log failed (#{e.class}); dropping the record")
106
+ end
107
+
108
+ # Parameter filters are application callbacks and can themselves log or query.
109
+ def build_attributes(component, event)
110
+ Thread.current[Appender::REENTRANCY_KEY] = true
111
+ { 'event.name' => event.name }.merge(attributes_for(component, event.payload))
112
+ ensure
113
+ Thread.current[Appender::REENTRANCY_KEY] = nil
114
+ end
115
+
116
+ def emit_in_context(component, payload, &block)
117
+ job = payload[:job]
118
+ if component == :active_job && PostHog::Rails.config.auto_instrument_active_job &&
119
+ job.respond_to?(:posthog_logs_context, true)
120
+ Internal::Context.with_context(
121
+ job.send(:posthog_logs_context), fresh: true, owner: PostHog.client, enrich_current_span: false, &block
122
+ )
123
+ else
124
+ yield
125
+ end
126
+ end
127
+
128
+ def attributes_for(component, payload)
129
+ case component
130
+ when :action_controller
131
+ attributes = pick(payload, controller: 'rails.controller', action: 'rails.action',
132
+ method: 'http.request.method', status: 'http.response.status_code')
133
+ if payload[:params].is_a?(Hash)
134
+ attributes['rails.params'] =
135
+ bounded_json(controller_params(payload[:params]))
136
+ end
137
+ attributes
138
+ when :active_record
139
+ attributes = pick(payload, name: 'rails.sql.name', cached: 'rails.sql.cached')
140
+ # Never export statements: even SQL without binds may contain literal secrets.
141
+ operation = payload[:sql].to_s[SQL_OPERATION, 1]
142
+ attributes['db.operation.name'] = operation.upcase if operation
143
+ attributes
144
+ when :active_job
145
+ job_attributes(payload)
146
+ when :action_mailer
147
+ pick(payload, mailer: 'rails.mailer', action: 'rails.action')
148
+ end
149
+ end
150
+
151
+ def job_attributes(payload)
152
+ job = payload[:job]
153
+ return {} unless job
154
+
155
+ wait = payload[:wait]
156
+ wait = wait.to_f if wait.is_a?(ActiveSupport::Duration)
157
+ attributes = pick(
158
+ { job_class: job.class.name, id: job.job_id, queue: job.queue_name,
159
+ executions: job.executions, priority: job.priority, wait: wait },
160
+ job_class: 'rails.job.class', id: 'rails.job.id', queue: 'rails.job.queue',
161
+ executions: 'rails.job.executions', priority: 'rails.job.priority', wait: 'rails.job.retry_wait'
162
+ )
163
+ return attributes if job.class.respond_to?(:log_arguments?) && !job.class.log_arguments?
164
+ return attributes if defined?(::ActionMailer::MailDeliveryJob) && job.is_a?(::ActionMailer::MailDeliveryJob)
165
+ return attributes if defined?(::ActionMailer::DeliveryJob) && job.is_a?(::ActionMailer::DeliveryJob)
166
+
167
+ # Unkeyed arguments have no filterable name. Do not guess which are safe.
168
+ budget = [1000, 10_000]
169
+ arguments = job.arguments
170
+ arguments = if arguments.size > 100
171
+ '[FILTERED]'
172
+ else
173
+ arguments.map do |argument|
174
+ argument.is_a?(Hash) ? filtered_params(argument, budget) : '[FILTERED]'
175
+ end
176
+ end
177
+ attributes['rails.job.arguments'] = bounded_json(arguments)
178
+ attributes
179
+ end
180
+
181
+ def pick(payload, mapping)
182
+ mapping.each_with_object({}) do |(key, name), attributes|
183
+ value = payload[key]
184
+ attributes[name] = safe_value(value) unless value.nil?
185
+ end
186
+ end
187
+
188
+ # Rails controller notifications already contain request.filtered_parameters.
189
+ def controller_params(params)
190
+ copy_filter_value(params, 0, [1000, 10_000])
191
+ rescue UnsafeParameters
192
+ '[FILTERED]'
193
+ end
194
+
195
+ def filtered_params(params, budget = [1000, 10_000])
196
+ return {} unless ::Rails.application
197
+
198
+ filters = ::Rails.application.config.filter_parameters
199
+ return '[FILTERED]' if filters.empty?
200
+
201
+ if ::Rails.version.to_f >= 6.0
202
+ require 'active_support/parameter_filter'
203
+ else
204
+ require 'action_dispatch/http/parameter_filter'
205
+ end
206
+ # Rails Proc filters can depend on key/value types and the complete original root.
207
+ # Never pass a normalized or partially truncated parameter tree to those callbacks.
208
+ filtered = ParameterFilter.backend.new(filters).filter(copy_filter_value(params, 0, budget))
209
+ copy_filter_value(filtered, 0, [1000, 10_000])
210
+ rescue UnsafeParameters
211
+ '[FILTERED]'
212
+ end
213
+
214
+ def copy_filter_value(value, depth, budget, copies = {}.compare_by_identity)
215
+ raise UnsafeParameters if depth > 10 || budget[0] <= 0
216
+
217
+ budget[0] -= 1
218
+ case value
219
+ when String, Symbol
220
+ budget[1] -= value.bytesize if value.is_a?(String)
221
+ budget[1] -= value.to_s.bytesize if value.is_a?(Symbol)
222
+ raise UnsafeParameters if budget[1].negative?
223
+
224
+ copies[value] ||= value.clone
225
+ when Integer, Float, true, false, nil
226
+ value
227
+ when Array, Hash
228
+ raise UnsafeParameters if value.size > 100
229
+
230
+ copy = value.clone(freeze: false).clear
231
+ if value.is_a?(Hash)
232
+ raise UnsafeParameters if value.default_proc
233
+
234
+ copy.default = copy_filter_value(value.default, depth + 1, budget, copies) unless value.default.nil?
235
+ value.each do |key, item|
236
+ raise UnsafeParameters unless key.is_a?(String) || key.is_a?(Symbol)
237
+
238
+ copied_key = copy_filter_value(key, depth + 1, budget, copies)
239
+ copy[copied_key] = copy_filter_value(item, depth + 1, budget, copies)
240
+ end
241
+ else
242
+ value.each { |item| copy << copy_filter_value(item, depth + 1, budget, copies) }
243
+ end
244
+ copy.freeze if value.frozen?
245
+ copies[value] ||= copy
246
+ else
247
+ raise UnsafeParameters
248
+ end
249
+ end
250
+
251
+ def bounded_json(value)
252
+ json = JSON.generate(value)
253
+ json.bytesize <= 10_000 ? json : JSON.generate('[FILTERED: payload too large]')
254
+ rescue JSON::GeneratorError
255
+ JSON.generate('[FILTERED]')
256
+ end
257
+
258
+ # Bound traversal and omit arbitrary object inspection from notification payloads.
259
+ def safe_value(value, depth = 0, budget = [1000])
260
+ return '[FILTERED]' if depth > 10 || budget[0] <= 0
261
+
262
+ budget[0] -= 1
263
+
264
+ case value
265
+ when String then value[0, 10_000].dup
266
+ when Symbol then value.to_s
267
+ when Integer, Float, true, false, nil then value
268
+ when Array then value.first(100).map { |item| safe_value(item, depth + 1, budget) }
269
+ when Hash
270
+ value.first(100).each_with_object({}) do |(key, item), result|
271
+ next unless key.is_a?(String) || key.is_a?(Symbol)
272
+
273
+ result[key.to_s] = safe_value(item, depth + 1, budget)
274
+ end
275
+ else '[FILTERED]'
276
+ end
277
+ end
278
+
279
+ def severity_for(component, payload, error_type)
280
+ return ::Logger::ERROR if error_type
281
+ return ::Logger::DEBUG if component == :active_record
282
+
283
+ status = payload[:status]
284
+ return ::Logger::ERROR if status.is_a?(Integer) && status >= 500
285
+ return ::Logger::WARN if status.is_a?(Integer) && status >= 400
286
+
287
+ ::Logger::INFO
288
+ end
289
+ end
290
+ end
291
+ end
292
+ end
293
+ end
@@ -5,6 +5,7 @@ require 'posthog/logging'
5
5
  require 'posthog/rails/configuration'
6
6
  require 'posthog/rails/logs/appender'
7
7
  require 'posthog/rails/logs/rate_limiter'
8
+ require 'posthog/rails/logs/notifications'
8
9
 
9
10
  module PostHog
10
11
  module Rails
@@ -68,6 +69,8 @@ module PostHog
68
69
  rate_limiter: build_rate_limiter(config),
69
70
  before_send: config.logs_before_send
70
71
  )
72
+ Notifications.install(@appender) if config.logs_enabled
73
+ @appender
71
74
  rescue StandardError => e
72
75
  warn_once("Failed to initialize PostHog Logs: #{e.message}")
73
76
  nil
@@ -78,6 +81,7 @@ module PostHog
78
81
  # @param timeout [Numeric] Max seconds to spend; see {SHUTDOWN_TIMEOUT_SECONDS}.
79
82
  # @return [void]
80
83
  def shutdown(timeout: SHUTDOWN_TIMEOUT_SECONDS)
84
+ Notifications.reset
81
85
  @provider&.shutdown(timeout: timeout)
82
86
  rescue StandardError => e
83
87
  logger.warn("Error shutting down PostHog Logs: #{e.message}")
@@ -102,6 +106,7 @@ module PostHog
102
106
  #
103
107
  # @return [void]
104
108
  def reset
109
+ Notifications.reset
105
110
  @installed = false
106
111
  @provider = nil
107
112
  @appender = nil
@@ -33,6 +33,30 @@ module PostHog
33
33
  )
34
34
  end
35
35
 
36
+ initializer 'posthog.action_cable' do
37
+ require 'posthog/rails/action_cable'
38
+
39
+ ActiveSupport.on_load(:action_cable_connection) do
40
+ prepend ActionCableConnectionExtensions unless self < ActionCableConnectionExtensions
41
+ subscriptions = ::ActionCable::Connection::Subscriptions
42
+ unless subscriptions < ActionCableSubscriptionsExtensions
43
+ subscriptions.prepend(ActionCableSubscriptionsExtensions)
44
+ end
45
+ end
46
+ ActiveSupport.on_load(:action_cable_channel) do
47
+ prepend ActionCableChannelExtensions unless self < ActionCableChannelExtensions
48
+ end
49
+
50
+ # Rails 5.2 has only the server configuration hook.
51
+ if ::Rails.version.to_f < 6.0
52
+ ActiveSupport.on_load(:action_cable) do
53
+ ::ActionCable::Connection::Base.prepend(ActionCableConnectionExtensions)
54
+ ::ActionCable::Channel::Base.prepend(ActionCableChannelExtensions)
55
+ ::ActionCable::Connection::Subscriptions.prepend(ActionCableSubscriptionsExtensions)
56
+ end
57
+ end
58
+ end
59
+
36
60
  initializer 'posthog.streaming_errors' do
37
61
  StreamingExceptions.install
38
62
  end
@@ -2,6 +2,6 @@
2
2
 
3
3
  module PostHog
4
4
  module Rails
5
- VERSION = '3.21.0'
5
+ VERSION = '3.23.0'
6
6
  end
7
7
  end
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.21.0
4
+ version: 3.23.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - PostHog
@@ -48,12 +48,14 @@ files:
48
48
  - lib/generators/posthog/templates/posthog.rb
49
49
  - lib/posthog-rails.rb
50
50
  - lib/posthog/rails.rb
51
+ - lib/posthog/rails/action_cable.rb
51
52
  - lib/posthog/rails/active_job.rb
52
53
  - lib/posthog/rails/capture_exceptions.rb
53
54
  - lib/posthog/rails/configuration.rb
54
55
  - lib/posthog/rails/error_subscriber.rb
55
56
  - lib/posthog/rails/facade.rb
56
57
  - lib/posthog/rails/logs/appender.rb
58
+ - lib/posthog/rails/logs/notifications.rb
57
59
  - lib/posthog/rails/logs/rate_limiter.rb
58
60
  - lib/posthog/rails/logs/setup.rb
59
61
  - lib/posthog/rails/logs/severity.rb