diff --git a/.rubocop.yml b/.rubocop.yml index 3ffe2b0d8..aa916e963 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -1,2 +1,57 @@ inherit_from: .rubocop_todo.yml +AllCops: + Exclude: + - 'bin/**/*' + - 'example/**/*' + - 'spec/fixtures/**/*' + - 'features/fixtures/**/*' + +# We can't use ".freeze" on our constants in case users are monkey patching +# them — this would be a BC break +Style/MutableConstant: + Enabled: false + +Layout/EmptyLinesAroundAttributeAccessor: + Enabled: true + +Layout/SpaceAroundMethodCallOperator: + Enabled: true + +Lint/RaiseException: + Enabled: true + +Lint/StructNewOverride: + Enabled: true + +Lint/DeprecatedOpenSSLConstant: + Enabled: true + +Lint/MixedRegexpCaptureTypes: + Enabled: true + +Style/RedundantFetchBlock: + Enabled: true + +Style/ExponentialNotation: + Enabled: false + +Style/HashEachMethods: + Enabled: true + +Style/RedundantRegexpCharacterClass: + Enabled: true + +Style/RedundantRegexpEscape: + Enabled: true + +# These require newer version of Ruby than our minimum supported version, so +# have to be disabled +Style/HashTransformKeys: # Requires Ruby 2.5 + Enabled: false + +Style/HashTransformValues: # Requires Ruby 2.4 + Enabled: false + +Style/SlicingWithRange: # Requires Ruby 2.6 + Enabled: false diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index 4715394ab..fcb383927 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -1,11 +1,40 @@ # This configuration was generated by # `rubocop --auto-gen-config` -# on 2018-02-06 11:17:57 +0000 using RuboCop version 0.52.1. +# on 2020-05-15 11:35:58 +0100 using RuboCop version 0.83.0. # The point is for the user to remove these configuration records # one by one as the offenses are removed from the code base. # Note that changes in the inspected code, or installation of new # versions of RuboCop, may require this file to be generated again. +# Offense count: 3 +# Configuration parameters: Include. +# Include: **/*.gemfile, **/Gemfile, **/gems.rb +Bundler/DuplicatedGem: + Exclude: + - 'Gemfile' + +# Offense count: 5 +# Cop supports --auto-correct. +# Configuration parameters: TreatCommentsAsGroupSeparators, Include. +# Include: **/*.gemfile, **/Gemfile, **/gems.rb +Bundler/OrderedGems: + Exclude: + - 'Gemfile' + +# Offense count: 1 +# Configuration parameters: Include. +# Include: **/*.gemspec +Gemspec/RequiredRubyVersion: + Exclude: + - 'bugsnag.gemspec' + +# Offense count: 2 +# Cop supports --auto-correct. +Layout/BlockEndNewline: + Exclude: + - 'spec/integrations/mongo_spec.rb' + - 'spec/report_spec.rb' + # Offense count: 4 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, IndentOneStep, IndentationWidth. @@ -14,16 +43,45 @@ Layout/CaseIndentation: Exclude: - 'lib/bugsnag/cleaner.rb' -# Offense count: 3 +# Offense count: 15 +# Cop supports --auto-correct. +Layout/EmptyLineAfterGuardClause: + Exclude: + - 'lib/bugsnag.rb' + - 'lib/bugsnag/cleaner.rb' + - 'lib/bugsnag/delivery/thread_queue.rb' + - 'lib/bugsnag/helpers.rb' + - 'lib/bugsnag/session_tracker.rb' + +# Offense count: 10 +# Cop supports --auto-correct. +Layout/EmptyLineAfterMagicComment: + Exclude: + - 'spec/breadcrumbs/validator_spec.rb' + - 'spec/bugsnag_spec.rb' + - 'spec/configuration_spec.rb' + - 'spec/integrations/mongo_spec.rb' + - 'spec/integrations/que_spec.rb' + - 'spec/integrations/resque_spec.rb' + - 'spec/integrations/shoryuken_spec.rb' + - 'spec/middleware/exception_meta_data_spec.rb' + - 'spec/report_spec.rb' + - 'spec/session_tracker_spec.rb' + +# Offense count: 5 # Cop supports --auto-correct. Layout/EmptyLines: Exclude: + - 'features/steps/ruby_notifier_steps.rb' - 'lib/bugsnag/helpers.rb' - 'lib/bugsnag/integrations/mailman.rb' - 'lib/bugsnag/stacktrace.rb' + - 'spec/integrations/mailman_spec.rb' # Offense count: 4 # Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle. +# SupportedStyles: around, only_before Layout/EmptyLinesAroundAccessModifier: Exclude: - 'lib/bugsnag/delivery.rb' @@ -31,25 +89,38 @@ Layout/EmptyLinesAroundAccessModifier: - 'lib/bugsnag/middleware_stack.rb' - 'lib/bugsnag/session_tracker.rb' -# Offense count: 1 +# Offense count: 2 +# Cop supports --auto-correct. +Layout/EmptyLinesAroundAttributeAccessor: + Exclude: + - 'lib/bugsnag/configuration.rb' + - 'spec/report_spec.rb' + +# Offense count: 24 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle. # SupportedStyles: empty_lines, no_empty_lines Layout/EmptyLinesAroundBlockBody: Exclude: - 'lib/bugsnag/middleware/classify_error.rb' - -# Offense count: 11 + - 'spec/bugsnag_spec.rb' + - 'spec/helper_spec.rb' + - 'spec/integration_spec.rb' + - 'spec/integrations/logger_spec.rb' + - 'spec/integrations/rack_spec.rb' + - 'spec/integrations/rails3_request_spec.rb' + - 'spec/middleware_spec.rb' + - 'spec/report_spec.rb' + +# Offense count: 9 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle. -# SupportedStyles: empty_lines, empty_lines_except_namespace, empty_lines_special, no_empty_lines +# SupportedStyles: empty_lines, empty_lines_except_namespace, empty_lines_special, no_empty_lines, beginning_only, ending_only Layout/EmptyLinesAroundClassBody: Exclude: - - 'lib/bugsnag/integrations/delayed_job.rb' - 'lib/bugsnag/integrations/mailman.rb' - 'lib/bugsnag/integrations/rack.rb' - 'lib/bugsnag/integrations/railtie.rb' - - 'lib/bugsnag/integrations/rake.rb' - 'lib/bugsnag/integrations/resque.rb' - 'lib/bugsnag/integrations/shoryuken.rb' - 'lib/bugsnag/integrations/sidekiq.rb' @@ -57,12 +128,6 @@ Layout/EmptyLinesAroundClassBody: - 'lib/bugsnag/session_tracker.rb' - 'lib/bugsnag/stacktrace.rb' -# Offense count: 1 -# Cop supports --auto-correct. -Layout/EmptyLinesAroundExceptionHandlingKeywords: - Exclude: - - 'lib/bugsnag/integrations/rake.rb' - # Offense count: 1 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle. @@ -71,26 +136,54 @@ Layout/EmptyLinesAroundModuleBody: Exclude: - 'lib/bugsnag/integrations/rails/controller_methods.rb' +# Offense count: 2 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyleAlignWith, AutoCorrect, Severity. +# SupportedStylesAlignWith: keyword, variable, start_of_line +Layout/EndAlignment: + Exclude: + - 'lib/bugsnag/cleaner.rb' + # Offense count: 1 # Cop supports --auto-correct. +# Configuration parameters: AllowForAlignment, AllowBeforeTrailingComments, ForceEqualSignAlignment. +Layout/ExtraSpacing: + Exclude: + - 'Rakefile' + +# Offense count: 7 +# Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, IndentationWidth. # SupportedStyles: special_inside_parentheses, consistent, align_brackets -Layout/IndentArray: +Layout/FirstArrayElementIndentation: Exclude: - 'lib/bugsnag/middleware/classify_error.rb' + - 'spec/report_spec.rb' + - 'spec/stacktrace_spec.rb' -# Offense count: 12 +# Offense count: 164 # Cop supports --auto-correct. # Configuration parameters: IndentationWidth. # SupportedStyles: special_inside_parentheses, consistent, align_braces -Layout/IndentHash: +Layout/FirstHashElementIndentation: EnforcedStyle: consistent +# Offense count: 2 +# Cop supports --auto-correct. +# Configuration parameters: AllowMultipleStyles, EnforcedHashRocketStyle, EnforcedColonStyle, EnforcedLastArgumentHashStyle. +# SupportedHashRocketStyles: key, separator, table +# SupportedColonStyles: key, separator, table +# SupportedLastArgumentHashStyles: always_inspect, always_ignore, ignore_implicit, ignore_explicit +Layout/HashAlignment: + Exclude: + - 'lib/bugsnag/delivery/synchronous.rb' + - 'spec/integrations/rake_spec.rb' + # Offense count: 1 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle. -# SupportedStyles: auto_detection, squiggly, active_support, powerpack, unindent -Layout/IndentHeredoc: +# SupportedStyles: squiggly, active_support, powerpack, unindent +Layout/HeredocIndentation: Exclude: - 'lib/generators/bugsnag/bugsnag_generator.rb' @@ -101,11 +194,23 @@ Layout/IndentationWidth: Exclude: - 'lib/bugsnag/cleaner.rb' -# Offense count: 2 +# Offense count: 6 +# Cop supports --auto-correct. +# Configuration parameters: AllowDoxygenCommentStyle, AllowGemfileRubyComment. +Layout/LeadingCommentSpace: + Exclude: + - 'spec/integration_spec.rb' + - 'spec/integrations/mailman_spec.rb' + - 'spec/integrations/que_spec.rb' + - 'spec/integrations/resque_spec.rb' + +# Offense count: 4 # Cop supports --auto-correct. Layout/MultilineBlockLayout: Exclude: - 'lib/bugsnag/middleware/classify_error.rb' + - 'spec/integrations/mongo_spec.rb' + - 'spec/report_spec.rb' # Offense count: 3 # Cop supports --auto-correct. @@ -124,7 +229,13 @@ Layout/SpaceAfterComma: - 'lib/bugsnag/middleware_stack.rb' - 'lib/bugsnag/report.rb' -# Offense count: 5 +# Offense count: 1 +# Cop supports --auto-correct. +Layout/SpaceAfterNot: + Exclude: + - 'features/steps/ruby_notifier_steps.rb' + +# Offense count: 9 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle. # SupportedStyles: space, no_space @@ -136,7 +247,20 @@ Layout/SpaceAroundEqualsInParameterDefault: - 'lib/bugsnag/integrations/rake.rb' - 'lib/bugsnag/report.rb' -# Offense count: 2 +# Offense count: 16 +# Cop supports --auto-correct. +# Configuration parameters: AllowForAlignment, EnforcedStyleForExponentOperator. +# SupportedStylesForExponentOperator: space, no_space +Layout/SpaceAroundOperators: + Exclude: + - 'Gemfile' + - 'Rakefile' + - 'spec/bugsnag_spec.rb' + - 'spec/integrations/rake_spec.rb' + - 'spec/integrations/sidekiq_spec.rb' + - 'spec/report_spec.rb' + +# Offense count: 89 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBraces. # SupportedStyles: space, no_space @@ -145,120 +269,178 @@ Layout/SpaceBeforeBlockBraces: Exclude: - 'lib/bugsnag/middleware/suggestion_data.rb' - 'lib/bugsnag/middleware_stack.rb' - -# Offense count: 23 + - 'spec/bugsnag_spec.rb' + - 'spec/configuration_spec.rb' + - 'spec/helper_spec.rb' + - 'spec/integration_spec.rb' + - 'spec/integrations/mailman_spec.rb' + - 'spec/integrations/rack_spec.rb' + - 'spec/integrations/rake_spec.rb' + - 'spec/integrations/sidekiq_spec.rb' + - 'spec/middleware_spec.rb' + - 'spec/report_spec.rb' + - 'spec/session_tracker_spec.rb' + - 'spec/stacktrace_spec.rb' + +# Offense count: 48 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBraces, SpaceBeforeBlockParameters. # SupportedStyles: space, no_space # SupportedStylesForEmptyBraces: space, no_space Layout/SpaceInsideBlockBraces: - Exclude: - - 'lib/bugsnag.rb' - - 'lib/bugsnag/cleaner.rb' - - 'lib/bugsnag/helpers.rb' - - 'lib/bugsnag/integrations/shoryuken.rb' - - 'lib/bugsnag/middleware/callbacks.rb' - - 'lib/bugsnag/middleware/rack_request.rb' - - 'lib/bugsnag/middleware/warden_user.rb' - - 'lib/bugsnag/middleware_stack.rb' - - 'lib/bugsnag/report.rb' - - 'lib/bugsnag/stacktrace.rb' + Enabled: false -# Offense count: 22 +# Offense count: 162 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBraces. # SupportedStyles: space, no_space, compact # SupportedStylesForEmptyBraces: space, no_space Layout/SpaceInsideHashLiteralBraces: - Exclude: - - 'lib/bugsnag.rb' - - 'lib/bugsnag/cleaner.rb' - - 'lib/bugsnag/integrations/resque.rb' - - 'lib/bugsnag/middleware/exception_meta_data.rb' - - 'lib/bugsnag/middleware/mailman.rb' - - 'lib/bugsnag/middleware/suggestion_data.rb' - - 'lib/bugsnag/middleware/warden_user.rb' - - 'lib/bugsnag/report.rb' - - 'lib/bugsnag/session_tracker.rb' + Enabled: false -# Offense count: 2 +# Offense count: 3 # Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle. +# SupportedStyles: space, no_space Layout/SpaceInsideParens: Exclude: - 'lib/bugsnag/stacktrace.rb' + - 'spec/integrations/shoryuken_spec.rb' -# Offense count: 4 +# Offense count: 8 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle. # SupportedStyles: final_newline, final_blank_line -Layout/TrailingBlankLines: +Layout/TrailingEmptyLines: Exclude: - - 'lib/bugsnag/integrations/que.rb' - 'lib/bugsnag/session_tracker.rb' - 'lib/bugsnag/tasks.rb' - 'lib/bugsnag/version.rb' + - 'spec/breadcrumbs/breadcrumb_spec.rb' + - 'spec/breadcrumbs/validator_spec.rb' + - 'spec/middleware_stack_spec.rb' + - 'spec/spec_helper.rb' + - 'spec/utility/circular_buffer_spec.rb' -# Offense count: 2 +# Offense count: 5 +# Cop supports --auto-correct. +# Configuration parameters: AllowInHeredoc. +Layout/TrailingWhitespace: + Exclude: + - 'spec/integrations/clearance_user_spec.rb' + - 'spec/integrations/que_spec.rb' + - 'spec/integrations/rake_spec.rb' + - 'spec/integrations/shoryuken_spec.rb' + - 'spec/integrations/warden_user_spec.rb' + +# Offense count: 90 Lint/AmbiguousBlockAssociation: Exclude: - 'lib/bugsnag/delivery/thread_queue.rb' - 'lib/bugsnag/middleware/suggestion_data.rb' + - 'spec/integrations/rack_spec.rb' + - 'spec/integrations/rails3_request_spec.rb' + - 'spec/integrations/sidekiq_spec.rb' + - 'spec/middleware_spec.rb' + - 'spec/report_spec.rb' + - 'spec/session_tracker_spec.rb' + - 'spec/stacktrace_spec.rb' -# Offense count: 4 +# Offense count: 3 # Configuration parameters: AllowSafeAssignment. Lint/AssignmentInCondition: Exclude: - 'lib/bugsnag/delivery/thread_queue.rb' - 'lib/bugsnag/helpers.rb' - - 'lib/bugsnag/integrations/delayed_job.rb' # Offense count: 2 -Lint/DuplicateMethods: +# Cop supports --auto-correct. +Lint/BooleanSymbol: Exclude: - - 'lib/bugsnag/configuration.rb' + - 'spec/breadcrumbs/validator_spec.rb' -# Offense count: 2 +# Offense count: 15 +Lint/IneffectiveAccessModifier: + Exclude: + - 'lib/bugsnag/helpers.rb' + +# Offense count: 1 # Cop supports --auto-correct. -# Configuration parameters: EnforcedStyleAlignWith, AutoCorrect. -# SupportedStylesAlignWith: keyword, variable, start_of_line -Lint/EndAlignment: +# Configuration parameters: EnforcedStyle. +# SupportedStyles: runtime_error, standard_error +Lint/InheritException: Exclude: - - 'lib/bugsnag/cleaner.rb' + - 'spec/report_spec.rb' -# Offense count: 2 -Lint/HandleExceptions: +# Offense count: 1 +# Cop supports --auto-correct. +Lint/ParenthesesAsGroupedExpression: + Exclude: + - 'spec/report_spec.rb' + +# Offense count: 3 +# Cop supports --auto-correct. +Lint/RedundantRequireStatement: Exclude: - 'lib/bugsnag.rb' - - 'lib/bugsnag/tasks/bugsnag.rake' + - 'lib/bugsnag/delivery/thread_queue.rb' + - 'lib/bugsnag/session_tracker.rb' -# Offense count: 10 -Lint/IneffectiveAccessModifier: +# Offense count: 1 +# Cop supports --auto-correct. +Lint/RedundantStringCoercion: Exclude: - - 'lib/bugsnag/helpers.rb' + - 'features/support/env.rb' -# Offense count: 5 +# Offense count: 12 Lint/RescueException: Exclude: + - 'lib/bugsnag/integrations/delayed_job.rb' - 'lib/bugsnag/integrations/mailman.rb' - 'lib/bugsnag/integrations/rack.rb' - 'lib/bugsnag/integrations/rake.rb' - 'lib/bugsnag/integrations/shoryuken.rb' - 'lib/bugsnag/integrations/sidekiq.rb' - - 'lib/bugsnag/integrations/delayed_job.rb' + - 'spec/middleware_spec.rb' + - 'spec/report_spec.rb' + - 'spec/stacktrace_spec.rb' -# Offense count: 6 +# Offense count: 1 +# Cop supports --auto-correct. +Lint/SendWithMixinArgument: + Exclude: + - 'lib/bugsnag/integrations/rake.rb' + +# Offense count: 2 +# Configuration parameters: AllowComments. +Lint/SuppressedException: + Exclude: + - 'lib/bugsnag.rb' + - 'lib/bugsnag/tasks/bugsnag.rake' + +# Offense count: 103 # Cop supports --auto-correct. # Configuration parameters: IgnoreEmptyBlocks, AllowUnusedKeywordArguments. Lint/UnusedBlockArgument: Exclude: + - 'features/support/env.rb' - 'lib/bugsnag/configuration.rb' - 'lib/bugsnag/helpers.rb' - 'lib/bugsnag/middleware_stack.rb' - 'lib/bugsnag/report.rb' + - 'spec/bugsnag_spec.rb' + - 'spec/helper_spec.rb' + - 'spec/integrations/rack_spec.rb' + - 'spec/integrations/rails3_request_spec.rb' + - 'spec/integrations/sidekiq_spec.rb' + - 'spec/middleware_spec.rb' + - 'spec/report_spec.rb' + - 'spec/session_tracker_spec.rb' + - 'spec/stacktrace_spec.rb' # Offense count: 3 # Cop supports --auto-correct. -# Configuration parameters: AllowUnusedKeywordArguments, IgnoreEmptyMethods. +# Configuration parameters: AllowUnusedKeywordArguments, IgnoreEmptyMethods, IgnoreNotImplementedMethods. Lint/UnusedMethodArgument: Exclude: - 'lib/bugsnag.rb' @@ -266,53 +448,59 @@ Lint/UnusedMethodArgument: - 'lib/bugsnag/integrations/sidekiq.rb' # Offense count: 1 +# Cop supports --auto-correct. # Configuration parameters: ContextCreatingMethods, MethodCreatingMethods. Lint/UselessAccessModifier: Exclude: - 'lib/bugsnag/helpers.rb' -# Offense count: 25 +# Offense count: 4 +Lint/UselessAssignment: + Exclude: + - 'features/steps/ruby_notifier_steps.rb' + - 'spec/breadcrumbs/breadcrumb_spec.rb' + - 'spec/session_tracker_spec.rb' + +# Offense count: 33 +# Configuration parameters: IgnoredMethods. Metrics/AbcSize: - Max: 86 + Max: 68 -# Offense count: 1 +# Offense count: 74 # Configuration parameters: CountComments, ExcludedMethods. +# ExcludedMethods: refine Metrics/BlockLength: - Max: 30 + Max: 1026 -# Offense count: 2 +# Offense count: 1 # Configuration parameters: CountBlocks. Metrics/BlockNesting: Max: 4 -# Offense count: 3 +# Offense count: 4 # Configuration parameters: CountComments. Metrics/ClassLength: - Max: 149 - Exclude: - - 'lib/bugsnag/report.rb' - - 'lib/bugsnag/configuration.rb' + Max: 174 -# Offense count: 12 +# Offense count: 15 +# Configuration parameters: IgnoredMethods. Metrics/CyclomaticComplexity: - Max: 19 + Max: 18 -# Offense count: 34 -# Configuration parameters: CountComments. +# Offense count: 42 +# Configuration parameters: CountComments, ExcludedMethods. Metrics/MethodLength: - Max: 55 + Max: 54 -# Offense count: 1 +# Offense count: 3 # Configuration parameters: CountComments. Metrics/ModuleLength: - Max: 125 - Exclude: - - 'lib/bugsnag/helpers.rb' - - 'lib/bugsnag.rb' + Max: 152 -# Offense count: 11 +# Offense count: 15 +# Configuration parameters: IgnoredMethods. Metrics/PerceivedComplexity: - Max: 21 + Max: 20 # Offense count: 2 Naming/AccessorMethodName: @@ -320,24 +508,57 @@ Naming/AccessorMethodName: - 'lib/bugsnag/session_tracker.rb' # Offense count: 1 -# Configuration parameters: Blacklist. -# Blacklist: END, (?-mix:EO[A-Z]{1}) +Naming/ConstantName: + Exclude: + - 'spec/integrations/que_spec.rb' + +# Offense count: 1 +# Configuration parameters: ForbiddenDelimiters. +# ForbiddenDelimiters: (?-mix:(^|\s)(EO[A-Z]{1}|END)(\s|$)) Naming/HeredocDelimiterNaming: Exclude: - 'lib/generators/bugsnag/bugsnag_generator.rb' # Offense count: 1 -# Configuration parameters: NamePrefix, NamePrefixBlacklist, NameWhitelist, MethodDefinitionMacros. +# Configuration parameters: EnforcedStyleForLeadingUnderscores. +# SupportedStylesForLeadingUnderscores: disallowed, required, optional +Naming/MemoizedInstanceVariableName: + Exclude: + - 'lib/bugsnag.rb' + +# Offense count: 1 +# Configuration parameters: NamePrefix, ForbiddenPrefixes, AllowedMethods, MethodDefinitionMacros. # NamePrefix: is_, has_, have_ -# NamePrefixBlacklist: is_, has_, have_ -# NameWhitelist: is_a? +# ForbiddenPrefixes: is_, has_, have_ +# AllowedMethods: is_a? # MethodDefinitionMacros: define_method, define_singleton_method Naming/PredicateName: Exclude: - 'spec/**/*' - 'lib/bugsnag/helpers.rb' -# Offense count: 5 +# Offense count: 10 +# Cop supports --auto-correct. +# Configuration parameters: PreferredName. +Naming/RescuedExceptionsVariableName: + Exclude: + - 'lib/bugsnag/integrations/delayed_job.rb' + - 'lib/bugsnag/integrations/mailman.rb' + - 'lib/bugsnag/integrations/rack.rb' + - 'lib/bugsnag/integrations/rails/active_record_rescue.rb' + - 'lib/bugsnag/integrations/rake.rb' + - 'lib/bugsnag/integrations/shoryuken.rb' + - 'lib/bugsnag/integrations/sidekiq.rb' + - 'lib/bugsnag/middleware/rack_request.rb' + +# Offense count: 3 +# Configuration parameters: EnforcedStyle. +# SupportedStyles: snake_case, normalcase, non_integer +Naming/VariableNumber: + Exclude: + - 'spec/breadcrumbs/validator_spec.rb' + +# Offense count: 20 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle. # SupportedStyles: prefer_alias, prefer_alias_method @@ -346,8 +567,14 @@ Style/Alias: - 'lib/bugsnag/configuration.rb' - 'lib/bugsnag/integrations/rake.rb' - 'lib/bugsnag/session_tracker.rb' + - 'spec/bugsnag_spec.rb' + - 'spec/integrations/mailman_spec.rb' + - 'spec/integrations/mongo_spec.rb' + - 'spec/integrations/que_spec.rb' + - 'spec/integrations/resque_spec.rb' + - 'spec/integrations/shoryuken_spec.rb' -# Offense count: 2 +# Offense count: 4 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle. # SupportedStyles: always, conditionals @@ -355,35 +582,30 @@ Style/AndOr: Exclude: - 'lib/bugsnag.rb' - 'lib/bugsnag/helpers.rb' + - 'spec/spec_helper.rb' -# Offense count: 2 +# Offense count: 6 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle. +# SupportedStyles: percent_q, bare_percent +Style/BarePercentLiterals: + Exclude: + - 'features/steps/ruby_notifier_steps.rb' + +# Offense count: 5 # Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, ProceduralMethods, FunctionalMethods, IgnoredMethods. -# SupportedStyles: line_count_based, semantic, braces_for_chaining +# Configuration parameters: EnforcedStyle, ProceduralMethods, FunctionalMethods, IgnoredMethods, AllowBracesOnProceduralOneLiners, BracesRequiredMethods. +# SupportedStyles: line_count_based, semantic, braces_for_chaining, always_braces # ProceduralMethods: benchmark, bm, bmbm, create, each_with_object, measure, new, realtime, tap, with_object # FunctionalMethods: let, let!, subject, watch # IgnoredMethods: lambda, proc, it Style/BlockDelimiters: Exclude: - 'lib/bugsnag/middleware/classify_error.rb' + - 'spec/integrations/mongo_spec.rb' + - 'spec/report_spec.rb' -# Offense count: 12 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: braces, no_braces, context_dependent -Style/BracesAroundHashParameters: - Exclude: - - 'lib/bugsnag/integrations/resque.rb' - - 'lib/bugsnag/integrations/shoryuken.rb' - - 'lib/bugsnag/integrations/sidekiq.rb' - - 'lib/bugsnag/middleware/mailman.rb' - - 'lib/bugsnag/middleware/rack_request.rb' - - 'lib/bugsnag/middleware/rails3_request.rb' - - 'lib/bugsnag/middleware/rake.rb' - - 'lib/bugsnag/middleware/suggestion_data.rb' - - 'lib/bugsnag/middleware/warden_user.rb' - -# Offense count: 16 +# Offense count: 27 # Cop supports --auto-correct. # Configuration parameters: AutoCorrect, EnforcedStyle. # SupportedStyles: nested, compact @@ -398,19 +620,27 @@ Style/ClassCheck: Exclude: - 'lib/bugsnag/cleaner.rb' -# Offense count: 6 +# Offense count: 9 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, SingleLineConditionsOnly, IncludeTernaryExpressions. # SupportedStyles: assign_to_condition, assign_inside_condition Style/ConditionalAssignment: Exclude: + - 'features/steps/ruby_notifier_steps.rb' - 'lib/bugsnag.rb' - 'lib/bugsnag/cleaner.rb' - 'lib/bugsnag/delivery/synchronous.rb' - 'lib/bugsnag/middleware_stack.rb' - 'lib/bugsnag/report.rb' + - 'spec/report_spec.rb' + +# Offense count: 2 +# Cop supports --auto-correct. +Style/Dir: + Exclude: + - 'spec/report_spec.rb' -# Offense count: 38 +# Offense count: 22 Style/Documentation: Enabled: false @@ -422,15 +652,55 @@ Style/EmptyElse: Exclude: - 'lib/bugsnag/stacktrace.rb' +# Offense count: 15 +# Cop supports --auto-correct. +Style/Encoding: + Exclude: + - 'Rakefile' + - 'spec/breadcrumbs/breadcrumb_spec.rb' + - 'spec/breadcrumbs/validator_spec.rb' + - 'spec/bugsnag_spec.rb' + - 'spec/cleaner_spec.rb' + - 'spec/configuration_spec.rb' + - 'spec/helper_spec.rb' + - 'spec/integrations/mongo_spec.rb' + - 'spec/integrations/que_spec.rb' + - 'spec/integrations/resque_spec.rb' + - 'spec/integrations/shoryuken_spec.rb' + - 'spec/middleware/exception_meta_data_spec.rb' + - 'spec/report_spec.rb' + - 'spec/session_tracker_spec.rb' + - 'spec/utility/circular_buffer_spec.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +Style/ExpandPathArguments: + Exclude: + - 'lib/generators/bugsnag/bugsnag_generator.rb' + +# Offense count: 80 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle. +# SupportedStyles: always, always_true, never +Style/FrozenStringLiteralComment: + Enabled: false + # Offense count: 3 +# Configuration parameters: AllowedVariables. +Style/GlobalVars: + Exclude: + - 'features/steps/ruby_notifier_steps.rb' + - 'features/support/env.rb' + +# Offense count: 5 # Configuration parameters: MinBodyLength. Style/GuardClause: Exclude: - 'lib/bugsnag.rb' - - 'lib/bugsnag/integrations/delayed_job.rb' - 'lib/bugsnag/integrations/resque.rb' + - 'spec/spec_helper.rb' -# Offense count: 98 +# Offense count: 547 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, UseHashRocketsWithSymbolValues, PreferHashRocketsForNonAlnumEndingSymbols. # SupportedStyles: ruby19, hash_rockets, no_mixed_keys, ruby19_no_mixed_keys @@ -438,11 +708,12 @@ Style/HashSyntax: Enabled: false # Offense count: 1 +# Configuration parameters: AllowIfModifier. Style/IfInsideElse: Exclude: - 'lib/bugsnag/session_tracker.rb' -# Offense count: 15 +# Offense count: 14 # Cop supports --auto-correct. Style/IfUnlessModifier: Exclude: @@ -452,21 +723,38 @@ Style/IfUnlessModifier: - 'lib/bugsnag/integrations/rack.rb' - 'lib/bugsnag/integrations/resque.rb' - 'lib/bugsnag/middleware/callbacks.rb' - - 'lib/bugsnag/middleware/exception_meta_data.rb' - 'lib/bugsnag/middleware/rack_request.rb' - 'lib/bugsnag/session_tracker.rb' - 'lib/bugsnag/stacktrace.rb' + - 'spec/cleaner_spec.rb' -# Offense count: 6 +# Offense count: 5 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle. +# SupportedStyles: line_count_dependent, lambda, literal +Style/Lambda: + Exclude: + - 'spec/integrations/rack_spec.rb' + - 'spec/middleware/exception_meta_data_spec.rb' + +# Offense count: 8 # Cop supports --auto-correct. +# Configuration parameters: IgnoredMethods. Style/MethodCallWithoutArgsParentheses: Exclude: - 'lib/bugsnag/delivery/synchronous.rb' - 'lib/bugsnag/report.rb' - 'lib/bugsnag/session_tracker.rb' + - 'spec/integrations/rake_spec.rb' + - 'spec/integrations/shoryuken_spec.rb' + +# Offense count: 1 +Style/MethodMissingSuper: + Exclude: + - 'lib/bugsnag/middleware_stack.rb' # Offense count: 1 -Style/MethodMissing: +Style/MissingRespondToMissing: Exclude: - 'lib/bugsnag/middleware_stack.rb' @@ -481,19 +769,23 @@ Style/MultilineIfModifier: Exclude: - 'lib/bugsnag/integrations/rails/controller_methods.rb' -# Offense count: 29 -# Cop supports --auto-correct. -Style/MutableConstant: - Enabled: false - # Offense count: 4 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle. # SupportedStyles: both, prefix, postfix Style/NegatedIf: Exclude: - - 'lib/bugsnag.rb' - 'lib/bugsnag/session_tracker.rb' + - 'spec/middleware_spec.rb' + - 'spec/stacktrace_spec.rb' + +# Offense count: 5 +# Cop supports --auto-correct. +# Configuration parameters: AllowedMethods. +# AllowedMethods: be, be_a, be_an, be_between, be_falsey, be_kind_of, be_instance_of, be_truthy, be_within, eq, eql, end_with, include, match, raise_error, respond_to, start_with +Style/NestedParenthesizedCalls: + Exclude: + - 'spec/session_tracker_spec.rb' # Offense count: 2 # Cop supports --auto-correct. @@ -511,20 +803,23 @@ Style/NonNilCheck: Exclude: - 'lib/bugsnag/report.rb' -# Offense count: 1 +# Offense count: 13 # Cop supports --auto-correct. # Configuration parameters: Strict. Style/NumericLiterals: MinDigits: 7 -# Offense count: 1 +# Offense count: 6 # Cop supports --auto-correct. -# Configuration parameters: AutoCorrect, EnforcedStyle. +# Configuration parameters: AutoCorrect, EnforcedStyle, IgnoredMethods. # SupportedStyles: predicate, comparison Style/NumericPredicate: Exclude: - 'spec/**/*' + - 'Rakefile' + - 'lib/bugsnag.rb' - 'lib/bugsnag/session_tracker.rb' + - 'lib/bugsnag/utility/circular_buffer.rb' # Offense count: 2 # Cop supports --auto-correct. @@ -532,19 +827,36 @@ Style/ParallelAssignment: Exclude: - 'lib/bugsnag/stacktrace.rb' +# Offense count: 6 +# Cop supports --auto-correct. +# Configuration parameters: PreferredDelimiters. +Style/PercentLiteralDelimiters: + Exclude: + - 'features/steps/ruby_notifier_steps.rb' + # Offense count: 6 # Cop supports --auto-correct. Style/PerlBackrefs: Exclude: - 'lib/bugsnag/stacktrace.rb' -# Offense count: 1 +# Offense count: 8 +# Cop supports --auto-correct. +Style/Proc: + Exclude: + - 'spec/bugsnag_spec.rb' + - 'spec/report_spec.rb' + +# Offense count: 4 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle. # SupportedStyles: compact, exploded Style/RaiseArgs: Exclude: - 'lib/bugsnag/tasks/bugsnag.rake' + - 'spec/bugsnag_spec.rb' + - 'spec/integrations/rack_spec.rb' + - 'spec/integrations/rails3_request_spec.rb' # Offense count: 4 # Cop supports --auto-correct. @@ -553,7 +865,7 @@ Style/RedundantBegin: - 'lib/bugsnag/delivery/synchronous.rb' - 'lib/bugsnag/integrations/mailman.rb' - 'lib/bugsnag/integrations/shoryuken.rb' - - 'lib/bugsnag/integrations/sidekiq.rb' + - 'spec/bugsnag_spec.rb' # Offense count: 1 # Cop supports --auto-correct. @@ -561,32 +873,41 @@ Style/RedundantException: Exclude: - 'lib/bugsnag/tasks/bugsnag.rake' -# Offense count: 11 +# Offense count: 2 +# Cop supports --auto-correct. +Style/RedundantInterpolation: + Exclude: + - 'spec/helper_spec.rb' + +# Offense count: 13 # Cop supports --auto-correct. Style/RedundantSelf: Exclude: - 'lib/bugsnag/configuration.rb' - - 'lib/bugsnag/integrations/railtie.rb' -# Offense count: 2 +# Offense count: 5 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, AllowInnerSlashes. # SupportedStyles: slashes, percent_r, mixed Style/RegexpLiteral: Exclude: + - 'features/steps/ruby_notifier_steps.rb' - 'lib/bugsnag/stacktrace.rb' + - 'spec/report_spec.rb' + - 'spec/stacktrace_spec.rb' -# Offense count: 6 +# Offense count: 11 # Cop supports --auto-correct. Style/RescueModifier: Exclude: - - 'lib/bugsnag/cleaner.rb' - 'lib/bugsnag/middleware/rack_request.rb' - 'lib/bugsnag/middleware/rails3_request.rb' - 'lib/bugsnag/middleware/warden_user.rb' - 'lib/bugsnag/stacktrace.rb' + - 'spec/integrations/rack_spec.rb' + - 'spec/stacktrace_spec.rb' -# Offense count: 5 +# Offense count: 15 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle. # SupportedStyles: implicit, explicit @@ -596,36 +917,65 @@ Style/RescueStandardError: - 'lib/bugsnag/integrations/railtie.rb' - 'lib/bugsnag/stacktrace.rb' - 'lib/bugsnag/tasks/bugsnag.rake' + - 'spec/bugsnag_spec.rb' + - 'spec/report_spec.rb' -# Offense count: 1 +# Offense count: 2 +# Cop supports --auto-correct. +# Configuration parameters: ConvertCodeThatCanStartToReturnNil, AllowedMethods. +# AllowedMethods: present?, blank?, presence, try, try! +Style/SafeNavigation: + Exclude: + - 'lib/bugsnag/middleware/callbacks.rb' + - 'spec/spec_helper.rb' + +# Offense count: 4 # Cop supports --auto-correct. # Configuration parameters: AllowAsExpressionSeparator. Style/Semicolon: Exclude: - 'lib/bugsnag/configuration.rb' + - 'spec/cleaner_spec.rb' + - 'spec/configuration_spec.rb' -# Offense count: 3 +# Offense count: 2 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle. +# SupportedStyles: only_raise, only_fail, semantic +Style/SignalException: + Exclude: + - 'spec/bugsnag_spec.rb' + +# Offense count: 15 # Cop supports --auto-correct. # Configuration parameters: . # SupportedStyles: use_perl_names, use_english_names Style/SpecialGlobalVars: EnforcedStyle: use_perl_names -# Offense count: 176 +# Offense count: 1817 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, ConsistentQuotesInMultiline. # SupportedStyles: single_quotes, double_quotes Style/StringLiterals: Enabled: false -# Offense count: 5 +# Offense count: 1 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle. +# SupportedStyles: single_quotes, double_quotes +Style/StringLiteralsInInterpolation: + Exclude: + - 'features/support/env.rb' + +# Offense count: 14 # Cop supports --auto-correct. # Configuration parameters: MinSize. # SupportedStyles: percent, brackets Style/SymbolArray: EnforcedStyle: brackets -# Offense count: 3 +# Offense count: 4 # Cop supports --auto-correct. # Configuration parameters: IgnoredMethods. # IgnoredMethods: respond_to, define_method @@ -634,6 +984,7 @@ Style/SymbolProc: - 'lib/bugsnag/middleware/classify_error.rb' - 'lib/bugsnag/middleware/rack_request.rb' - 'lib/bugsnag/middleware/suggestion_data.rb' + - 'spec/report_spec.rb' # Offense count: 1 # Cop supports --auto-correct. @@ -643,37 +994,56 @@ Style/TernaryParentheses: Exclude: - 'lib/bugsnag/report.rb' -# Offense count: 5 +# Offense count: 1 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyleForMultiline. # SupportedStylesForMultiline: comma, consistent_comma, no_comma -Style/TrailingCommaInLiteral: +Style/TrailingCommaInArguments: Exclude: - - 'lib/bugsnag/integrations/delayed_job.rb' + - 'spec/report_spec.rb' # Offense count: 2 # Cop supports --auto-correct. -# Configuration parameters: ExactNameMatch, AllowPredicates, AllowDSLWriters, IgnoreClassMethods, Whitelist. -# Whitelist: to_ary, to_a, to_c, to_enum, to_h, to_hash, to_i, to_int, to_io, to_open, to_path, to_proc, to_r, to_regexp, to_str, to_s, to_sym +# Configuration parameters: EnforcedStyleForMultiline. +# SupportedStylesForMultiline: comma, consistent_comma, no_comma +Style/TrailingCommaInArrayLiteral: + Exclude: + - 'spec/stacktrace_spec.rb' + +# Offense count: 4 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyleForMultiline. +# SupportedStylesForMultiline: comma, consistent_comma, no_comma +Style/TrailingCommaInHashLiteral: + Exclude: + - 'spec/integrations/que_spec.rb' + - 'spec/integrations/rails3_request_spec.rb' + +# Offense count: 2 +# Cop supports --auto-correct. +# Configuration parameters: ExactNameMatch, AllowPredicates, AllowDSLWriters, IgnoreClassMethods, AllowedMethods. +# AllowedMethods: to_ary, to_a, to_c, to_enum, to_h, to_hash, to_i, to_int, to_io, to_open, to_path, to_proc, to_r, to_regexp, to_str, to_s, to_sym Style/TrivialAccessors: Exclude: - 'lib/bugsnag/configuration.rb' -# Offense count: 1 +# Offense count: 2 # Cop supports --auto-correct. # Configuration parameters: MinSize, WordRegex. # SupportedStyles: percent, brackets Style/WordArray: EnforcedStyle: brackets -# Offense count: 3 +# Offense count: 4 # Cop supports --auto-correct. Style/ZeroLengthPredicate: Exclude: + - 'Rakefile' - 'lib/bugsnag/session_tracker.rb' -# Offense count: 92 -# Configuration parameters: AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, IgnoredPatterns. +# Offense count: 371 +# Cop supports --auto-correct. +# Configuration parameters: AutoCorrect, AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, IgnoredPatterns. # URISchemes: http, https -Metrics/LineLength: - Max: 162 +Layout/LineLength: + Max: 175 diff --git a/CHANGELOG.md b/CHANGELOG.md index 256cb4f57..be53a6bef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,31 @@ Changelog ========= +## 6.14.0 (20 July 2020) + +### Enhancements + +* Add configurable `discard_classes` option to allow filtering errors using either a `String` or `Regexp` matched against the error's class name + | [#597](https://github.com/bugsnag/bugsnag-ruby/pull/597) + +* The Breadcrumb name limit of 30 characters has been removed + | [#600](https://github.com/bugsnag/bugsnag-ruby/pull/600) + +* Improve performance of payload cleaning + | [#601](https://github.com/bugsnag/bugsnag-ruby/pull/601) + +* Improve performance when processing stacktraces + | [#602](https://github.com/bugsnag/bugsnag-ruby/pull/602) + | [#603](https://github.com/bugsnag/bugsnag-ruby/pull/603) + +* If a custom object responds to `id` method, show the id and class in error reports + | [#531](https://github.com/bugsnag/bugsnag-ruby/pull/531) + | [manojmj92](https://github.com/manojmj92) + +### Deprecated + +* The `ignore_classes` configuration option has been deprecated in favour of `discard_classes`. `ignore_classes` will be removed in the next major release + ## 6.13.1 (11 May 2020) ### Fixes diff --git a/Gemfile b/Gemfile index 74a298c81..93e21543b 100644 --- a/Gemfile +++ b/Gemfile @@ -32,13 +32,15 @@ group :coverage, optional: true do end group :rubocop, optional: true do - gem 'rubocop', '~> 0.52.1' + gem 'rubocop', '~> 0.83' end group :sidekiq, optional: true do gem 'sidekiq', '~> 5.2.7' # redis 4.1.2 dropped support for Ruby 2.2 gem 'redis', ruby_version < Gem::Version.new('2.3.0') ? '4.1.1' : '>= 4.1.2' + # rack 2.2.0 dropped support for Ruby 2.2 + gem 'rack', ruby_version < Gem::Version.new('2.3.0') ? '< 2.2.0' : '~> 2.2' end group :doc, optional: true do diff --git a/TESTING.md b/TESTING.md index f5fe99e87..513d83588 100644 --- a/TESTING.md +++ b/TESTING.md @@ -42,7 +42,7 @@ aws configure --profile=opensource Subsequently you'll need to run the following commmand to authenticate with the registry: ``` -$(aws ecr get-login --profile=opensource --no-include-email) +aws ecr get-login-password --profile=opensource | docker login --username AWS --password-stdin 855461928731.dkr.ecr.us-west-1.amazonaws.com ``` __Your session will periodically expire__, so you'll need to run this command to re-authenticate when that happens. @@ -64,7 +64,7 @@ Configure the tests to be run in the following way: When running the end-to-end tests, you'll want to restrict the feature files run to the specific test features for the platform. This is done using the Cucumber CLI syntax at the end of the `docker-compose run ruby-maze-runner` command, i.e: ``` -RUBY_TEST_VERSION=2.6 RAILS_VERSION=6 docker-compose run ruby-maze-runner features/rails_features --tags "@rails6" +RUBY_TEST_VERSION=2.6 RAILS_VERSION=6 docker-compose run --use-aliases ruby-maze-runner features/rails_features --tags "@rails6" ``` - Plain ruby tests should target `features/plain_features` @@ -75,7 +75,7 @@ RUBY_TEST_VERSION=2.6 RAILS_VERSION=6 docker-compose run ruby-maze-runner featur In order to target specific features the exact `.feature` file can be specified, i.e: ``` -RUBY_TEST_VERSION=2.6 RAILS_VERSION=6 docker-compose run ruby-maze-runner features/rails_features/app_version.feature --tags "@rails6" +RUBY_TEST_VERSION=2.6 RAILS_VERSION=6 docker-compose run --use-aliases ruby-maze-runner features/rails_features/app_version.feature --tags "@rails6" ``` In order to avoid running flakey or unfinished tests, the tag `"not @wip"` can be added to the tags option. This is recommended for all CI runs. If a tag is already specified, this should be added using the `and` keyword, e.g. `--tags "@rails6 and not @wip"` diff --git a/VERSION b/VERSION index d7d9d3fbd..68390495f 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -6.13.1 +6.14.0 diff --git a/dockerfiles/Dockerfile.ruby-maze-runner b/dockerfiles/Dockerfile.ruby-maze-runner index 3b72c15b8..de09d813c 100644 --- a/dockerfiles/Dockerfile.ruby-maze-runner +++ b/dockerfiles/Dockerfile.ruby-maze-runner @@ -20,7 +20,7 @@ COPY spec ./spec RUN gem build bugsnag.gemspec # The maze-runner node tests -FROM 855461928731.dkr.ecr.us-west-1.amazonaws.com/maze-runner:v2-cli as ruby-maze-runner +FROM 855461928731.dkr.ecr.us-west-1.amazonaws.com/maze-runner:latest-cli as ruby-maze-runner WORKDIR /app/ COPY features ./features COPY --from=ruby-package-builder /app/bugsnag-*.gem bugsnag.gem diff --git a/example/rails-60/.browserslistrc b/example/rails-60/.browserslistrc new file mode 100644 index 000000000..e94f8140c --- /dev/null +++ b/example/rails-60/.browserslistrc @@ -0,0 +1 @@ +defaults diff --git a/example/rails-60/.gitignore b/example/rails-60/.gitignore new file mode 100644 index 000000000..f3c55eb4f --- /dev/null +++ b/example/rails-60/.gitignore @@ -0,0 +1,45 @@ +/.ruby-version +/Gemfile.lock +/yarn.lock + +# See https://help.github.com/articles/ignoring-files for more about ignoring files. +# +# If you find yourself ignoring temporary files generated by your text editor +# or operating system, you probably want to add a global ignore instead: +# git config --global core.excludesfile '~/.gitignore_global' + +# Ignore bundler config. +/.bundle + +# Ignore the default SQLite database. +/db/*.sqlite3 +/db/*.sqlite3-journal +/db/*.sqlite3-* + +# Ignore all logfiles and tempfiles. +/log/* +/tmp/* +!/log/.keep +!/tmp/.keep + +# Ignore pidfiles, but keep the directory. +/tmp/pids/* +!/tmp/pids/ +!/tmp/pids/.keep + +# Ignore uploaded files in development. +/storage/* +!/storage/.keep + +/public/assets +.byebug_history + +# Ignore master key for decrypting credentials and more. +/config/master.key + +/public/packs +/public/packs-test +/node_modules +/yarn-error.log +yarn-debug.log* +.yarn-integrity diff --git a/example/rails-60/Gemfile b/example/rails-60/Gemfile new file mode 100644 index 000000000..2a8f4d30e --- /dev/null +++ b/example/rails-60/Gemfile @@ -0,0 +1,56 @@ +source 'https://rubygems.org' +git_source(:github) { |repo| "https://github.com/#{repo}.git" } + +# Install Bugsnag +gem "bugsnag", path: "../../" + +# Example task queues +gem "que" +gem "resque" +gem "sidekiq" + +# Bundle edge Rails instead: gem 'rails', github: 'rails/rails' +gem 'rails', '~> 6.0.3', '>= 6.0.3.1' +# Use sqlite3 and pg as the database for Active Record +gem 'pg' +gem 'sqlite3' + +# Use Puma as the app server +gem 'puma', '~> 4.1' +# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder +gem 'jbuilder', '~> 2.7' +# Use Redis adapter to run Action Cable in production +# gem 'redis', '~> 4.0' +# Use Active Model has_secure_password +# gem 'bcrypt', '~> 3.1.7' + +# Use Active Storage variant +# gem 'image_processing', '~> 1.2' + +# Reduces boot times through caching; required in config/boot.rb +gem 'bootsnap', '>= 1.4.2', require: false + +group :development, :test do + # Call 'byebug' anywhere in the code to stop execution and get a debugger console + gem 'byebug', platforms: [:mri, :mingw, :x64_mingw] +end + +group :development do + # Access an interactive console on exception pages or by calling 'console' anywhere in the code. + gem 'web-console', '>= 3.3.0' + gem 'listen', '~> 3.2' + # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring + gem 'spring' + gem 'spring-watcher-listen', '~> 2.0.0' +end + +group :test do + # Adds support for Capybara system testing and selenium driver + gem 'capybara', '>= 2.15' + gem 'selenium-webdriver' + # Easy installation and use of web drivers to run system tests with browsers + gem 'webdrivers' +end + +# Windows does not include zoneinfo files, so bundle the tzinfo-data gem +gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] diff --git a/example/rails-60/README.md b/example/rails-60/README.md new file mode 100644 index 000000000..2eaa10f01 --- /dev/null +++ b/example/rails-60/README.md @@ -0,0 +1,137 @@ +# Bugsnag Rails v6.0 demo + +This Rails application demonstrates how to use Bugsnag with Rails v6.0, as well as integrating it into Sidekiq, Que, and Resque. +Further details about integrating Bugsnag with Rails applications can be found [here.](https://docs.bugsnag.com/platforms/ruby/rails/) + +Install dependencies + +```shell +bundle install +``` + +Install local binaries + +```shell +bundle exec rake app:update:bin +``` + +## Rails v6.0 + +### Configuration + +There are two methods of configuring Bugsnag within a Rails application: + +1. Your `API_KEY` can be exported as an environment variable `BUGSNAG_API_KEY`. + +2. Generate a bugsnag configuration file at `config/initializers/bugsnag.rb` which can be populated with the [available configuration options](https://docs.bugsnag.com/platforms/ruby/rails/configuration-options/) by running the rails command: + + ```shell + bundle exec bin/rails generate bugsnag YOUR_API_KEY_HERE + ``` + +This is sufficient to start reporting unhandled exceptions to Bugsnag. + +### Running the example + +Run the example using: + +```shell +bundle exec bin/rails server +``` + +Once the server is running, head to the default path for more information on Bugsnag logging examples. + +## Sidekiq in Rails + +Sidekiq requires a datastore to run, this example uses [redis](https://redis.io/), installation instructions for which can be found [here](https://redis.io/topics/quickstart) and an official docker image can be found [here](https://hub.docker.com/_/redis/). + +### Configuration + +Once the configuration has been added to the Rails environment there is no need to further configure Sidekiq. + +### Running the examples + +Start the Rails server as mentioned above. + +Navigate to the `/sidekiq` page and run any of the examples using the links provided. + +The worker code can be found in `app/workers/sidekiq_workers.rb`. + +To process the jobs, run Sidekiq using the following command: + +```shell +bundle exec sidekiq +``` + +## Que in Rails + +Que requires a database backend in order to queue jobs. By default this database will be PostgreSQL although this can be changed via options as detailed in [the que documentation](https://github.com/chanks/que). + +Once PostgreSQL is set up as detailed using [the PostgreSQL documentation](https://www.postgresql.org/docs/), ensure Que can connect correctly before running any of the following examples which reference a `quedb` that can be created with the following command: + +```shell +createdb quedb +``` + +You can configure your connection in the `config/database.yml` file. + +### Configuration + +All tasks run with Que should set the rails environment to `que`. This ensures that the correct database and connection settings are used. +Do this by prepending `RAILS_ENV=que` before each command, or run: + +```shell +export RAILS_ENV=que +``` + +Ensure that the initial Que setup is complete by running: + +```shell +bundle exec bin/rails generate que:install +``` + +and + +```shell +bundle exec bin/rake db:migrate +``` + +Further configuration will be taken from the Rails environment. + +### Running the examples + +Start the Rails server as mentioned above. + +Navigate to the `/que` page and queue jobs for any of the examples using links provided. + +To process the jobs, run Que using the cli command: + +```shell +bundle exec que ./config/environment.rb +``` + +## Resque in Rails + +Resque requires a datastore to run, this example uses [redis](https://redis.io/), installation instructions for which can be found [here](https://redis.io/topics/quickstart) and an official docker image can be found [here](https://hub.docker.com/_/redis/). + +### Configuration + +Resque can be configured by using the Rails environment by making sure it depends on the `environment` task. This can be achieved when running the worker: + +```shell +QUEUE=crash bundle exec rake environment resque:work +``` + +Or by creating a task, `resque:setup`, that depends on the `environment` task. An example of this can be found in `lib/tasks/resque:setup.rake`. + +### Running the examples + +Start the Rails server as mentioned above. + +Navigate to the `/resque` page and queue any of the examples using links provided. + +To process the queues, run the `resque:work` task as stated in the example webpage. In order to process any of the queues on a single thread start the resque worker using the command: + +```shell +QUEUE=crash,callback,metadata bundle exec rake resque:work +``` diff --git a/example/rails-60/Rakefile b/example/rails-60/Rakefile new file mode 100644 index 000000000..e85f91391 --- /dev/null +++ b/example/rails-60/Rakefile @@ -0,0 +1,6 @@ +# Add your own tasks in files placed in lib/tasks ending in .rake, +# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. + +require_relative 'config/application' + +Rails.application.load_tasks diff --git a/example/rails-60/app/assets/config/manifest.js b/example/rails-60/app/assets/config/manifest.js new file mode 100644 index 000000000..591819335 --- /dev/null +++ b/example/rails-60/app/assets/config/manifest.js @@ -0,0 +1,2 @@ +//= link_tree ../images +//= link_directory ../stylesheets .css diff --git a/example/rails-60/app/assets/images/.keep b/example/rails-60/app/assets/images/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/example/rails-60/app/channels/application_cable/channel.rb b/example/rails-60/app/channels/application_cable/channel.rb new file mode 100644 index 000000000..d67269728 --- /dev/null +++ b/example/rails-60/app/channels/application_cable/channel.rb @@ -0,0 +1,4 @@ +module ApplicationCable + class Channel < ActionCable::Channel::Base + end +end diff --git a/example/rails-60/app/channels/application_cable/connection.rb b/example/rails-60/app/channels/application_cable/connection.rb new file mode 100644 index 000000000..0ff5442f4 --- /dev/null +++ b/example/rails-60/app/channels/application_cable/connection.rb @@ -0,0 +1,4 @@ +module ApplicationCable + class Connection < ActionCable::Connection::Base + end +end diff --git a/example/rails-60/app/controllers/application_controller.rb b/example/rails-60/app/controllers/application_controller.rb new file mode 100644 index 000000000..4be69567f --- /dev/null +++ b/example/rails-60/app/controllers/application_controller.rb @@ -0,0 +1,50 @@ +class ApplicationController < ActionController::Base + def crash + raise 'Bugsnag Rails demo says: It crashed! ' \ + 'Go check bugsnag.com for a new notification' + end + + def callback + Bugsnag.before_notify_callbacks << proc { |report| + report.add_tab(:diagnostics, { + message: 'Rails v6.0 demo says: Everything is great', + code: 200 + }) + } + + raise 'Bugsnag Rails demo says: It crashed! But, due to the attached callback' \ + 'the exception has meta information. Go check ' \ + 'bugsnag.com for a new notification (see the Diagnostics tab)!' + end + + def notify + Bugsnag.notify(RuntimeError.new("Bugsnag Rails demo says: False alarm, your application didn't crash")) + end + + def data + error = RuntimeError.new("Bugsnag Rails demo says: False alarm, your application didn't crash") + + Bugsnag.notify(error) do |report| + report.add_tab(:user, { + username: 'bob-hoskins', + email: 'bugsnag@bugsnag.com', + registered_user: true + }) + + report.add_tab(:diagnostics, { + message: 'Rails demo says: Everything is great', + code: 200 + }) + end + end + + def severity + error = RuntimeError.new( + "Bugsnag Rails demo says: Look at the circle on the right side — it's different!" + ) + + Bugsnag.notify(error) do |report| + report.severity = 'info' + end + end +end diff --git a/example/rails-60/app/controllers/concerns/.keep b/example/rails-60/app/controllers/concerns/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/example/rails-60/app/controllers/que_controller.rb b/example/rails-60/app/controllers/que_controller.rb new file mode 100644 index 000000000..eb7529196 --- /dev/null +++ b/example/rails-60/app/controllers/que_controller.rb @@ -0,0 +1,14 @@ +require './app/jobs/que_crash' +require './app/jobs/que_callback' + +class QueController < ActionController::Base + layout "application" + + def crash + QueCrash.enqueue + end + + def callbacks + QueCallback.enqueue + end +end diff --git a/example/rails-60/app/controllers/resque_controller.rb b/example/rails-60/app/controllers/resque_controller.rb new file mode 100644 index 000000000..2bdea9196 --- /dev/null +++ b/example/rails-60/app/controllers/resque_controller.rb @@ -0,0 +1,15 @@ +class ResqueController < ActionController::Base + layout "application" + + def crash + Resque.enqueue(ResqueWorkers::Crash) + end + + def metadata + Resque.enqueue(ResqueWorkers::Metadata) + end + + def callbacks + Resque.enqueue(ResqueWorkers::Callback) + end +end diff --git a/example/rails-60/app/controllers/sidekiq_controller.rb b/example/rails-60/app/controllers/sidekiq_controller.rb new file mode 100644 index 000000000..b925be414 --- /dev/null +++ b/example/rails-60/app/controllers/sidekiq_controller.rb @@ -0,0 +1,17 @@ +require './app/workers/sidekiq_workers' + +class SidekiqController < ActionController::Base + layout "application" + + def crash + SidekiqWorkers::CrashWorker.perform_async + end + + def metadata + SidekiqWorkers::MetadataWorker.perform_async + end + + def callbacks + SidekiqWorkers::CallbackWorker.perform_async + end +end diff --git a/example/rails-60/app/helpers/application_helper.rb b/example/rails-60/app/helpers/application_helper.rb new file mode 100644 index 000000000..de6be7945 --- /dev/null +++ b/example/rails-60/app/helpers/application_helper.rb @@ -0,0 +1,2 @@ +module ApplicationHelper +end diff --git a/example/rails-60/app/javascript/channels/consumer.js b/example/rails-60/app/javascript/channels/consumer.js new file mode 100644 index 000000000..0eceb59b1 --- /dev/null +++ b/example/rails-60/app/javascript/channels/consumer.js @@ -0,0 +1,6 @@ +// Action Cable provides the framework to deal with WebSockets in Rails. +// You can generate new channels where WebSocket features live using the `rails generate channel` command. + +import { createConsumer } from "@rails/actioncable" + +export default createConsumer() diff --git a/example/rails-60/app/javascript/channels/index.js b/example/rails-60/app/javascript/channels/index.js new file mode 100644 index 000000000..0cfcf7491 --- /dev/null +++ b/example/rails-60/app/javascript/channels/index.js @@ -0,0 +1,5 @@ +// Load all the channels within this directory and all subdirectories. +// Channel files must be named *_channel.js. + +const channels = require.context('.', true, /_channel\.js$/) +channels.keys().forEach(channels) diff --git a/example/rails-60/app/javascript/packs/application.js b/example/rails-60/app/javascript/packs/application.js new file mode 100644 index 000000000..9cd55d4b9 --- /dev/null +++ b/example/rails-60/app/javascript/packs/application.js @@ -0,0 +1,17 @@ +// This file is automatically compiled by Webpack, along with any other files +// present in this directory. You're encouraged to place your actual application logic in +// a relevant structure within app/javascript and only use these pack files to reference +// that code so it'll be compiled. + +require("@rails/ujs").start() +require("turbolinks").start() +require("@rails/activestorage").start() +require("channels") + + +// Uncomment to copy all static images under ../images to the output folder and reference +// them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>) +// or the `imagePath` JavaScript helper below. +// +// const images = require.context('../images', true) +// const imagePath = (name) => images(name, true) diff --git a/example/rails-60/app/jobs/application_job.rb b/example/rails-60/app/jobs/application_job.rb new file mode 100644 index 000000000..d394c3d10 --- /dev/null +++ b/example/rails-60/app/jobs/application_job.rb @@ -0,0 +1,7 @@ +class ApplicationJob < ActiveJob::Base + # Automatically retry jobs that encountered a deadlock + # retry_on ActiveRecord::Deadlocked + + # Most jobs are safe to ignore if the underlying records are no longer available + # discard_on ActiveJob::DeserializationError +end diff --git a/example/rails-60/app/jobs/que_callback.rb b/example/rails-60/app/jobs/que_callback.rb new file mode 100644 index 000000000..34efe9a48 --- /dev/null +++ b/example/rails-60/app/jobs/que_callback.rb @@ -0,0 +1,14 @@ +class QueCallback < Que::Job + @run_at = proc { 5.seconds.from_now } + + def run(_options = {}) + Bugsnag.before_notify_callbacks << proc { |report| + report.add_tab(:diagnostics, { + message: 'Que demo says: Everything is great', + code: 200 + }) + } + + raise 'Oh no!' + end +end diff --git a/example/rails-60/app/jobs/que_crash.rb b/example/rails-60/app/jobs/que_crash.rb new file mode 100644 index 000000000..b6f2a3b04 --- /dev/null +++ b/example/rails-60/app/jobs/que_crash.rb @@ -0,0 +1,7 @@ +class QueCrash < Que::Job + @run_at = proc { 5.seconds.from_now } + + def run(_options = {}) + raise "Oh no" + end +end diff --git a/example/rails-60/app/mailers/application_mailer.rb b/example/rails-60/app/mailers/application_mailer.rb new file mode 100644 index 000000000..286b2239d --- /dev/null +++ b/example/rails-60/app/mailers/application_mailer.rb @@ -0,0 +1,4 @@ +class ApplicationMailer < ActionMailer::Base + default from: 'from@example.com' + layout 'mailer' +end diff --git a/example/rails-60/app/models/application_record.rb b/example/rails-60/app/models/application_record.rb new file mode 100644 index 000000000..10a4cba84 --- /dev/null +++ b/example/rails-60/app/models/application_record.rb @@ -0,0 +1,3 @@ +class ApplicationRecord < ActiveRecord::Base + self.abstract_class = true +end diff --git a/example/rails-60/app/models/concerns/.keep b/example/rails-60/app/models/concerns/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/example/rails-60/app/views/application/data.html.erb b/example/rails-60/app/views/application/data.html.erb new file mode 100644 index 000000000..3c050280e --- /dev/null +++ b/example/rails-60/app/views/application/data.html.erb @@ -0,0 +1,10 @@ +

Bugsnag Rails demo says: It didn't crash!

+ +

+ But still go check your Bugsnag dashboard + for a new notification. +

+ +

Check out the user tab to see the metadata.

+ +

← return to examples

diff --git a/example/rails-60/app/views/application/index.html.erb b/example/rails-60/app/views/application/index.html.erb new file mode 100644 index 000000000..098615448 --- /dev/null +++ b/example/rails-60/app/views/application/index.html.erb @@ -0,0 +1,70 @@ +

This application demonstrates the use of Bugsnag with the Rails web framework.

+ +

For other examples within this application see the following pages:

+ + + +

+ While testing the examples open + your Bugsnag dashboard + in order to see the example errors and exceptions being received. +

+ +
    +
  1. +

    Crash

    +

    + Raises an error within the framework, generating a report in the + Bugsnag dashboard. +

    +
  2. + +
  3. +

    Crash and use callbacks

    +

    + Raises an exception within the framework, but with additional data + attached to the report. By registering a callback before the error + occurs useful data can be attached as a tab in the Bugsnag dashboard. +

    +
  4. + +
  5. +

    Notify

    +

    + Sends Bugsnag a report on demand using bugsnag.notify. + Allows details of handled errors or information to be sent to the + Bugsnag dashboard without crashing your code. +

    +
  6. + +
  7. +

    Notify with data

    +

    + Same as notify but allows you to attach additional data + within a block, similar to the + before_notify_callbacks example above. +

    +

    + In this case we're adding information about the user to go into the + user tab, and additional diagnostics as a + diagnostics tab. +

    +
  8. + +
  9. +

    Set the severity

    +

    + This uses the same mechanism as adding meta-data, but allows you to + set the severity when notifying Bugsnag of the error. +

    +

    + Valid severities are error, warning, and + info. Have a look on the dashboard to see the + difference in these severities. +

  10. + +
diff --git a/example/rails-60/app/views/application/notify.html.erb b/example/rails-60/app/views/application/notify.html.erb new file mode 100644 index 000000000..40b7904fe --- /dev/null +++ b/example/rails-60/app/views/application/notify.html.erb @@ -0,0 +1,8 @@ +

Bugsnag Rails demo says: It didn't crash!

+ +

+ But still go check your Bugsnag dashboard + for a new notification. +

+ +

← return to examples

diff --git a/example/rails-60/app/views/application/severity.html.erb b/example/rails-60/app/views/application/severity.html.erb new file mode 100644 index 000000000..5954e03ee --- /dev/null +++ b/example/rails-60/app/views/application/severity.html.erb @@ -0,0 +1,5 @@ +

+ Bugsnag Rails demo says: Look at the circle on the right side — it's different! +

+ +

← return to examples

diff --git a/example/rails-60/app/views/layouts/application.html.erb b/example/rails-60/app/views/layouts/application.html.erb new file mode 100644 index 000000000..6a2702144 --- /dev/null +++ b/example/rails-60/app/views/layouts/application.html.erb @@ -0,0 +1,16 @@ + + + + Bugsnag Rails v6.0 demo + <%= csrf_meta_tags %> + <%= csp_meta_tag %> + + + + + +

Bugsnag Rails v6.0 demo

+ + <%= yield %> + + diff --git a/example/rails-60/app/views/layouts/mailer.html.erb b/example/rails-60/app/views/layouts/mailer.html.erb new file mode 100644 index 000000000..cbd34d2e9 --- /dev/null +++ b/example/rails-60/app/views/layouts/mailer.html.erb @@ -0,0 +1,13 @@ + + + + + + + + + <%= yield %> + + diff --git a/example/rails-60/app/views/layouts/mailer.text.erb b/example/rails-60/app/views/layouts/mailer.text.erb new file mode 100644 index 000000000..37f0bddbd --- /dev/null +++ b/example/rails-60/app/views/layouts/mailer.text.erb @@ -0,0 +1 @@ +<%= yield %> diff --git a/example/rails-60/app/views/que/callbacks.html.erb b/example/rails-60/app/views/que/callbacks.html.erb new file mode 100644 index 000000000..d7e5095f1 --- /dev/null +++ b/example/rails-60/app/views/que/callbacks.html.erb @@ -0,0 +1,8 @@ +

Que

+ +

+ Que has queued the callbacks task, check + your Bugsnag dashboard for the result! +

+ +

← return to Que examples

diff --git a/example/rails-60/app/views/que/crash.html.erb b/example/rails-60/app/views/que/crash.html.erb new file mode 100644 index 000000000..d3d004644 --- /dev/null +++ b/example/rails-60/app/views/que/crash.html.erb @@ -0,0 +1,8 @@ +

Que

+ +

+ Que has queued the crash task, check + your Bugsnag dashboard for the result! +

+ +

← return to Que examples

diff --git a/example/rails-60/app/views/que/index.html.erb b/example/rails-60/app/views/que/index.html.erb new file mode 100644 index 000000000..2568880cc --- /dev/null +++ b/example/rails-60/app/views/que/index.html.erb @@ -0,0 +1,41 @@ +

Bugsnag Que demo

+ +

This route demonstrates how to use Bugsnag with Que.

+ +

+ While testing the examples open + your Bugsnag dashboard + in order to see the example errors and exceptions being received. +

+ +

+ Make sure you have a PostgreSQL instance running that your test application + can connect to before running these examples. +

+ +
    +
  1. +

    Crash

    + +

    + Raises an error within the framework, generating a report in the + Bugsnag dashboard. +

    +
  2. + +
  3. +

    Crash and use callbacks

    + +

    + Raises an exception within the framework, but with additional data + attached to the report. +

    + +

    + By registering a callback before the error occurs useful data can + be attached as a tab in the Bugsnag dashboard. +

    +
  4. +
+ +

← return home

diff --git a/example/rails-60/app/views/resque/callbacks.html.erb b/example/rails-60/app/views/resque/callbacks.html.erb new file mode 100644 index 000000000..d730810d8 --- /dev/null +++ b/example/rails-60/app/views/resque/callbacks.html.erb @@ -0,0 +1,17 @@ +

Resque

+ +

+ The callback task has been queued. +

+ +

+ This can be executed by running: +

+ +
QUEUE=callback bundle exec rake resque:work
+ +

+ Check your Bugsnag dashboard for the result! +

+ +

← return to Resque examples

diff --git a/example/rails-60/app/views/resque/crash.html.erb b/example/rails-60/app/views/resque/crash.html.erb new file mode 100644 index 000000000..2d28f986e --- /dev/null +++ b/example/rails-60/app/views/resque/crash.html.erb @@ -0,0 +1,17 @@ +

Resque

+ +

+ The crash task has been queued. +

+ +

+ This can be executed by running: +

+ +
QUEUE=crash bundle exec rake resque:work
+ +

+ Check your Bugsnag dashboard for the result! +

+ +

← return to Resque examples

diff --git a/example/rails-60/app/views/resque/index.html.erb b/example/rails-60/app/views/resque/index.html.erb new file mode 100644 index 000000000..7f5e4d763 --- /dev/null +++ b/example/rails-60/app/views/resque/index.html.erb @@ -0,0 +1,64 @@ +

Rescue

+ +

This route demonstrates how to use Bugsnag with Rescue.

+ +

+ While testing the examples open + your Bugsnag dashboard + in order to see the example errors and exceptions being received. +

+ +

+ Make sure you have a Redis instance running that your test application can + connect to before running these examples. +

+ +

+ While each queue can be run individually, to run Resque so that it + automatically executes each task, use: +

+ +
QUEUE=crash,callback,metadata bundle exec rake resque:work
+ +
    +
  1. +

    Crash

    + +

    + Raises an error within the framework, generating a report in the + Bugsnag dashboard. +

    +
  2. + +
  3. +

    Crash and use callbacks

    + +

    + Raises an exception within the framework, but with additional data + attached to the report. +

    + +

    + By registering a callback before the error occurs useful data can + be attached as a tab in the Bugsnag dashboard. +

    +
  4. + +
  5. +

    Notify with data

    + +

    + Same as notify but allows you to attach additional data + within a block, similar to the + "crash and use callbacks" example above. +

    + +

    + In this case we're adding information about the queue to go into the + queue tab, and additional diagnostics as a + diagnostics tab. +

    +
  6. +
+ +

← return home

diff --git a/example/rails-60/app/views/resque/metadata.html.erb b/example/rails-60/app/views/resque/metadata.html.erb new file mode 100644 index 000000000..c35532cad --- /dev/null +++ b/example/rails-60/app/views/resque/metadata.html.erb @@ -0,0 +1,17 @@ +

Resque

+ +

+ The metadata task has been queued. +

+ +

+ This can be executed by running: +

+ +
QUEUE=metadata bundle exec rake resque:work
+ +

+ Check your Bugsnag dashboard for the result! +

+ +

← return to Resque examples

diff --git a/example/rails-60/app/views/sidekiq/callbacks.html.erb b/example/rails-60/app/views/sidekiq/callbacks.html.erb new file mode 100644 index 000000000..14bb48406 --- /dev/null +++ b/example/rails-60/app/views/sidekiq/callbacks.html.erb @@ -0,0 +1,12 @@ +

Sidekiq

+ +

+ Sidekiq is performing a task that will crash, but registers a callback + before this to attach additional metadata. +

+ +

+ Check your Bugsnag dashboard for the result! +

+ +

← return to Sidekiq examples

diff --git a/example/rails-60/app/views/sidekiq/crash.html.erb b/example/rails-60/app/views/sidekiq/crash.html.erb new file mode 100644 index 000000000..010630a2a --- /dev/null +++ b/example/rails-60/app/views/sidekiq/crash.html.erb @@ -0,0 +1,8 @@ +

Sidekiq

+ +

+ Sidekiq is performing a task that will crash, so check + your Bugsnag dashboard for the result! +

+ +

← return to Sidekiq examples

diff --git a/example/rails-60/app/views/sidekiq/index.html.erb b/example/rails-60/app/views/sidekiq/index.html.erb new file mode 100644 index 000000000..110b6746c --- /dev/null +++ b/example/rails-60/app/views/sidekiq/index.html.erb @@ -0,0 +1,47 @@ +

Sidekiq

+ +

This route demonstrates how to use Bugsnag with Sidekiq.

+ +

+ While testing the examples open + your Bugsnag dashboard + in order to see the example errors and exceptions being received. +

+ +

+ Make sure you have a Redis instance running that your test application can + connect to before running these examples. +

+ +
    +
  1. +

    Crash

    + +

    Raises an error within the framework, generating a report in the Bugsnag dashboard.

    +
  2. + +
  3. +

    Crash and use callbacks

    + +

    + Raises an exception within the framework, but with additional data + attached to the report. By registering a callback before the error + occurs useful data can be attached as a tab in the Bugsnag dashboard. +

    +
  4. + +
  5. +

    Notify with data

    + +

    + Sends Bugsnag a report on demand using bugsnag.notify + and attaches additional data within a block, similar to + the "Crash and use callbacks" example above. In this case we're + adding information about the function being called to go into the + function tab, and additional diagnostics + as a diagnostics tab. +

    +
  6. +
+ +

← return home

diff --git a/example/rails-60/app/views/sidekiq/metadata.html.erb b/example/rails-60/app/views/sidekiq/metadata.html.erb new file mode 100644 index 000000000..78f0c218f --- /dev/null +++ b/example/rails-60/app/views/sidekiq/metadata.html.erb @@ -0,0 +1,12 @@ +

Sidekiq

+ +

+ Sidekiq is performing a task that will notify an error with some metadata + without crashing. +

+ +

+ Check your Bugsnag dashboard for the result! +

+ +

← return to Sidekiq examples

diff --git a/example/rails-60/app/workers/resque_workers.rb b/example/rails-60/app/workers/resque_workers.rb new file mode 100644 index 000000000..1b0feee35 --- /dev/null +++ b/example/rails-60/app/workers/resque_workers.rb @@ -0,0 +1,47 @@ +module ResqueWorkers + class Crash + @queue = :crash + + def self.perform + raise 'Crashed - Check your Bugsnag dashboard' + end + end + + # Unhandled with callback Exception example + class Callback + @queue = :callback + + def self.perform + Bugsnag.before_notify_callbacks << proc { |report| + report.add_tab(:diagnostics, { + message: 'Resque demo says: Everything is great', + code: 200 + }) + } + + raise 'Crashed - Check the Bugsnag dashboard for diagnostic data' + end + end + + # Handled example with additional data + class Metadata + @queue = :metadata + + def self.perform + error = Exception.new "Didn't crash, but sent a notification anyway" + + Bugsnag.notify(error) do |report| + report.add_tab(:queue, { + :name => "metadata", + :fatal => false + }) + + report.add_tab(:diagnostics, { + :message => 'Resque demo says: Everything is great' + }) + end + + puts "The Resque worker hasn't crashed, but it has sent a notification, with additional data to the dashboard" + end + end +end diff --git a/example/rails-60/app/workers/sidekiq_workers.rb b/example/rails-60/app/workers/sidekiq_workers.rb new file mode 100644 index 000000000..59bfddef1 --- /dev/null +++ b/example/rails-60/app/workers/sidekiq_workers.rb @@ -0,0 +1,47 @@ +module SidekiqWorkers + class CallbackWorker + include Sidekiq::Worker + + sidekiq_options :retry => false + + def perform + Bugsnag.before_notify_callbacks << proc { |report| + report.add_tab(:diagnostics, { + message: 'Sidekiq demo says: Everything is great', + code: 200 + }) + } + + raise 'Sidekiq crashed, but the callback added metadata - Check your Bugsnag dashboard' + end + end + + class CrashWorker + include Sidekiq::Worker + sidekiq_options :retry => false + + def perform + raise 'Sidekiq crashed - Check your Bugsnag dashboard' + end + end + + class MetadataWorker + include Sidekiq::Worker + sidekiq_options :retry => false + + def perform + error = Exception.new('Sidekiq notified with metadata - Check your Bugsnag dashboard') + + Bugsnag.notify(error) do |report| + report.add_tab(:function, { + name: 'Metadata', + fatal: false + }) + + report.add_tab(:diagnostics, { + message: 'Sidekiq demo says: Everything is great', + }) + end + end + end +end diff --git a/example/rails-60/babel.config.js b/example/rails-60/babel.config.js new file mode 100644 index 000000000..12f98da5a --- /dev/null +++ b/example/rails-60/babel.config.js @@ -0,0 +1,72 @@ +module.exports = function(api) { + var validEnv = ['development', 'test', 'production'] + var currentEnv = api.env() + var isDevelopmentEnv = api.env('development') + var isProductionEnv = api.env('production') + var isTestEnv = api.env('test') + + if (!validEnv.includes(currentEnv)) { + throw new Error( + 'Please specify a valid `NODE_ENV` or ' + + '`BABEL_ENV` environment variables. Valid values are "development", ' + + '"test", and "production". Instead, received: ' + + JSON.stringify(currentEnv) + + '.' + ) + } + + return { + presets: [ + isTestEnv && [ + '@babel/preset-env', + { + targets: { + node: 'current' + } + } + ], + (isProductionEnv || isDevelopmentEnv) && [ + '@babel/preset-env', + { + forceAllTransforms: true, + useBuiltIns: 'entry', + corejs: 3, + modules: false, + exclude: ['transform-typeof-symbol'] + } + ] + ].filter(Boolean), + plugins: [ + 'babel-plugin-macros', + '@babel/plugin-syntax-dynamic-import', + isTestEnv && 'babel-plugin-dynamic-import-node', + '@babel/plugin-transform-destructuring', + [ + '@babel/plugin-proposal-class-properties', + { + loose: true + } + ], + [ + '@babel/plugin-proposal-object-rest-spread', + { + useBuiltIns: true + } + ], + [ + '@babel/plugin-transform-runtime', + { + helpers: false, + regenerator: true, + corejs: false + } + ], + [ + '@babel/plugin-transform-regenerator', + { + async: false + } + ] + ].filter(Boolean) + } +} diff --git a/example/rails-60/config.ru b/example/rails-60/config.ru new file mode 100644 index 000000000..f7ba0b527 --- /dev/null +++ b/example/rails-60/config.ru @@ -0,0 +1,5 @@ +# This file is used by Rack-based servers to start the application. + +require_relative 'config/environment' + +run Rails.application diff --git a/example/rails-60/config/application.rb b/example/rails-60/config/application.rb new file mode 100644 index 000000000..7606973a3 --- /dev/null +++ b/example/rails-60/config/application.rb @@ -0,0 +1,19 @@ +require_relative 'boot' + +require 'rails/all' + +# Require the gems listed in Gemfile, including any gems +# you've limited to :test, :development, or :production. +Bundler.require(*Rails.groups) + +module Rails60 + class Application < Rails::Application + # Initialize configuration defaults for originally generated Rails version. + config.load_defaults 6.0 + + # Settings in config/environments/* take precedence over those specified here. + # Application configuration can go into files in config/initializers + # -- all .rb files in that directory are automatically loaded after loading + # the framework and any gems in your application. + end +end diff --git a/example/rails-60/config/boot.rb b/example/rails-60/config/boot.rb new file mode 100644 index 000000000..b9e460cef --- /dev/null +++ b/example/rails-60/config/boot.rb @@ -0,0 +1,4 @@ +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) + +require 'bundler/setup' # Set up gems listed in the Gemfile. +require 'bootsnap/setup' # Speed up boot time by caching expensive operations. diff --git a/example/rails-60/config/cable.yml b/example/rails-60/config/cable.yml new file mode 100644 index 000000000..e168aa54b --- /dev/null +++ b/example/rails-60/config/cable.yml @@ -0,0 +1,10 @@ +development: + adapter: async + +test: + adapter: test + +production: + adapter: redis + url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %> + channel_prefix: rails_60_production diff --git a/example/rails-60/config/credentials.yml.enc b/example/rails-60/config/credentials.yml.enc new file mode 100644 index 000000000..e015aa824 --- /dev/null +++ b/example/rails-60/config/credentials.yml.enc @@ -0,0 +1 @@ +KQhHHa39d1cmOiryTxmJvb3odw1lJYakJGSiQ8FJQGokXbkGPDUpG8UPuuvdKdwvh2O03jgdRlZ5ZeGtDgUeEVgSeWdGsvAXH9mwKfLxqm5lQuq5DfEnOOEpzAoReLpu4Hp7kmdJEwz/APbiEZ74NEFz94nDyWFkZwKsH1NSATVicP3gvGO0fgY0/ADOGcezOLcMrHCckCIap1oe4Fr68R0YbQxUhaNfZzsQN2RPHCw4fvQARYZcEPiTpoPRMwZsxkFdWQCpUUuQASdMFuu3+Cq//+Q57V+k3F353s52pQ1qCX/Oq0pBe8XXTzzQVK+x35xD7puFsz3N7wa2RtkmdUR0SsS/b92MRHMB94KjnQWLn7FS8/rYtDaiv6WnrXSGzwhOOtW8M3vOi35F1yoiUuM6bfIW68sCR3LR--hk5vbvf0FXhi6gl0--1WNlajBXqT6SQsGjKFHIlQ== \ No newline at end of file diff --git a/example/rails-60/config/database.yml b/example/rails-60/config/database.yml new file mode 100644 index 000000000..832c7883a --- /dev/null +++ b/example/rails-60/config/database.yml @@ -0,0 +1,32 @@ +# SQLite. Versions 3.8.0 and up are supported. +# gem install sqlite3 +# +# Ensure the SQLite 3 gem is defined in your Gemfile +# gem 'sqlite3' +# +default: &default + adapter: sqlite3 + pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> + timeout: 5000 + +que: + adapter: postgresql + pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> + host: localhost + timeout: 5000 + database: quedb + +development: + <<: *default + database: db/development.sqlite3 + +# Warning: The database defined as "test" will be erased and +# re-generated from your development database when you run "rake". +# Do not set this db to the same as development or production. +test: + <<: *default + database: db/test.sqlite3 + +production: + <<: *default + database: db/production.sqlite3 diff --git a/example/rails-60/config/environment.rb b/example/rails-60/config/environment.rb new file mode 100644 index 000000000..426333bb4 --- /dev/null +++ b/example/rails-60/config/environment.rb @@ -0,0 +1,5 @@ +# Load the Rails application. +require_relative 'application' + +# Initialize the Rails application. +Rails.application.initialize! diff --git a/example/rails-60/config/environments/development.rb b/example/rails-60/config/environments/development.rb new file mode 100644 index 000000000..66df51f6f --- /dev/null +++ b/example/rails-60/config/environments/development.rb @@ -0,0 +1,62 @@ +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # In the development environment your application's code is reloaded on + # every request. This slows down response time but is perfect for development + # since you don't have to restart the web server when you make code changes. + config.cache_classes = false + + # Do not eager load code on boot. + config.eager_load = false + + # Show full error reports. + config.consider_all_requests_local = true + + # Enable/disable caching. By default caching is disabled. + # Run rails dev:cache to toggle caching. + if Rails.root.join('tmp', 'caching-dev.txt').exist? + config.action_controller.perform_caching = true + config.action_controller.enable_fragment_cache_logging = true + + config.cache_store = :memory_store + config.public_file_server.headers = { + 'Cache-Control' => "public, max-age=#{2.days.to_i}" + } + else + config.action_controller.perform_caching = false + + config.cache_store = :null_store + end + + # Store uploaded files on the local file system (see config/storage.yml for options). + config.active_storage.service = :local + + # Don't care if the mailer can't send. + config.action_mailer.raise_delivery_errors = false + + config.action_mailer.perform_caching = false + + # Print deprecation notices to the Rails logger. + config.active_support.deprecation = :log + + # Raise an error on page load if there are pending migrations. + config.active_record.migration_error = :page_load + + # Highlight code that triggered database queries in logs. + config.active_record.verbose_query_logs = true + + # Debug mode disables concatenation and preprocessing of assets. + # This option may cause significant delays in view rendering with a large + # number of complex assets. + config.assets.debug = true + + # Suppress logger output for asset requests. + config.assets.quiet = true + + # Raises error for missing translations. + # config.action_view.raise_on_missing_translations = true + + # Use an evented file watcher to asynchronously detect changes in source code, + # routes, locales, etc. This feature depends on the listen gem. + config.file_watcher = ActiveSupport::EventedFileUpdateChecker +end diff --git a/example/rails-60/config/environments/production.rb b/example/rails-60/config/environments/production.rb new file mode 100644 index 000000000..244c22e00 --- /dev/null +++ b/example/rails-60/config/environments/production.rb @@ -0,0 +1,112 @@ +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Code is not reloaded between requests. + config.cache_classes = true + + # Eager load code on boot. This eager loads most of Rails and + # your application in memory, allowing both threaded web servers + # and those relying on copy on write to perform better. + # Rake tasks automatically ignore this option for performance. + config.eager_load = true + + # Full error reports are disabled and caching is turned on. + config.consider_all_requests_local = false + config.action_controller.perform_caching = true + + # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] + # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). + # config.require_master_key = true + + # Disable serving static files from the `/public` folder by default since + # Apache or NGINX already handles this. + config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? + + # Compress CSS using a preprocessor. + # config.assets.css_compressor = :sass + + # Do not fallback to assets pipeline if a precompiled asset is missed. + config.assets.compile = false + + # Enable serving of images, stylesheets, and JavaScripts from an asset server. + # config.action_controller.asset_host = 'http://assets.example.com' + + # Specifies the header that your server uses for sending files. + # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache + # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX + + # Store uploaded files on the local file system (see config/storage.yml for options). + config.active_storage.service = :local + + # Mount Action Cable outside main process or domain. + # config.action_cable.mount_path = nil + # config.action_cable.url = 'wss://example.com/cable' + # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] + + # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. + # config.force_ssl = true + + # Use the lowest log level to ensure availability of diagnostic information + # when problems arise. + config.log_level = :debug + + # Prepend all log lines with the following tags. + config.log_tags = [ :request_id ] + + # Use a different cache store in production. + # config.cache_store = :mem_cache_store + + # Use a real queuing backend for Active Job (and separate queues per environment). + # config.active_job.queue_adapter = :resque + # config.active_job.queue_name_prefix = "rails_60_production" + + config.action_mailer.perform_caching = false + + # Ignore bad email addresses and do not raise email delivery errors. + # Set this to true and configure the email server for immediate delivery to raise delivery errors. + # config.action_mailer.raise_delivery_errors = false + + # Enable locale fallbacks for I18n (makes lookups for any locale fall back to + # the I18n.default_locale when a translation cannot be found). + config.i18n.fallbacks = true + + # Send deprecation notices to registered listeners. + config.active_support.deprecation = :notify + + # Use default logging formatter so that PID and timestamp are not suppressed. + config.log_formatter = ::Logger::Formatter.new + + # Use a different logger for distributed setups. + # require 'syslog/logger' + # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') + + if ENV["RAILS_LOG_TO_STDOUT"].present? + logger = ActiveSupport::Logger.new(STDOUT) + logger.formatter = config.log_formatter + config.logger = ActiveSupport::TaggedLogging.new(logger) + end + + # Do not dump schema after migrations. + config.active_record.dump_schema_after_migration = false + + # Inserts middleware to perform automatic connection switching. + # The `database_selector` hash is used to pass options to the DatabaseSelector + # middleware. The `delay` is used to determine how long to wait after a write + # to send a subsequent read to the primary. + # + # The `database_resolver` class is used by the middleware to determine which + # database is appropriate to use based on the time delay. + # + # The `database_resolver_context` class is used by the middleware to set + # timestamps for the last write to the primary. The resolver uses the context + # class timestamps to determine how long to wait before reading from the + # replica. + # + # By default Rails will store a last write timestamp in the session. The + # DatabaseSelector middleware is designed as such you can define your own + # strategy for connection switching and pass that into the middleware through + # these configuration options. + # config.active_record.database_selector = { delay: 2.seconds } + # config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver + # config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session +end diff --git a/example/rails-60/config/environments/que.rb b/example/rails-60/config/environments/que.rb new file mode 100644 index 000000000..66df51f6f --- /dev/null +++ b/example/rails-60/config/environments/que.rb @@ -0,0 +1,62 @@ +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # In the development environment your application's code is reloaded on + # every request. This slows down response time but is perfect for development + # since you don't have to restart the web server when you make code changes. + config.cache_classes = false + + # Do not eager load code on boot. + config.eager_load = false + + # Show full error reports. + config.consider_all_requests_local = true + + # Enable/disable caching. By default caching is disabled. + # Run rails dev:cache to toggle caching. + if Rails.root.join('tmp', 'caching-dev.txt').exist? + config.action_controller.perform_caching = true + config.action_controller.enable_fragment_cache_logging = true + + config.cache_store = :memory_store + config.public_file_server.headers = { + 'Cache-Control' => "public, max-age=#{2.days.to_i}" + } + else + config.action_controller.perform_caching = false + + config.cache_store = :null_store + end + + # Store uploaded files on the local file system (see config/storage.yml for options). + config.active_storage.service = :local + + # Don't care if the mailer can't send. + config.action_mailer.raise_delivery_errors = false + + config.action_mailer.perform_caching = false + + # Print deprecation notices to the Rails logger. + config.active_support.deprecation = :log + + # Raise an error on page load if there are pending migrations. + config.active_record.migration_error = :page_load + + # Highlight code that triggered database queries in logs. + config.active_record.verbose_query_logs = true + + # Debug mode disables concatenation and preprocessing of assets. + # This option may cause significant delays in view rendering with a large + # number of complex assets. + config.assets.debug = true + + # Suppress logger output for asset requests. + config.assets.quiet = true + + # Raises error for missing translations. + # config.action_view.raise_on_missing_translations = true + + # Use an evented file watcher to asynchronously detect changes in source code, + # routes, locales, etc. This feature depends on the listen gem. + config.file_watcher = ActiveSupport::EventedFileUpdateChecker +end diff --git a/example/rails-60/config/environments/test.rb b/example/rails-60/config/environments/test.rb new file mode 100644 index 000000000..0cb24249b --- /dev/null +++ b/example/rails-60/config/environments/test.rb @@ -0,0 +1,49 @@ +# The test environment is used exclusively to run your application's +# test suite. You never need to work with it otherwise. Remember that +# your test database is "scratch space" for the test suite and is wiped +# and recreated between test runs. Don't rely on the data there! + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + config.cache_classes = false + config.action_view.cache_template_loading = true + + # Do not eager load code on boot. This avoids loading your whole application + # just for the purpose of running a single test. If you are using a tool that + # preloads Rails for running tests, you may have to set it to true. + config.eager_load = false + + # Configure public file server for tests with Cache-Control for performance. + config.public_file_server.enabled = true + config.public_file_server.headers = { + 'Cache-Control' => "public, max-age=#{1.hour.to_i}" + } + + # Show full error reports and disable caching. + config.consider_all_requests_local = true + config.action_controller.perform_caching = false + config.cache_store = :null_store + + # Raise exceptions instead of rendering exception templates. + config.action_dispatch.show_exceptions = false + + # Disable request forgery protection in test environment. + config.action_controller.allow_forgery_protection = false + + # Store uploaded files on the local file system in a temporary directory. + config.active_storage.service = :test + + config.action_mailer.perform_caching = false + + # Tell Action Mailer not to deliver emails to the real world. + # The :test delivery method accumulates sent emails in the + # ActionMailer::Base.deliveries array. + config.action_mailer.delivery_method = :test + + # Print deprecation notices to the stderr. + config.active_support.deprecation = :stderr + + # Raises error for missing translations. + # config.action_view.raise_on_missing_translations = true +end diff --git a/example/rails-60/config/initializers/application_controller_renderer.rb b/example/rails-60/config/initializers/application_controller_renderer.rb new file mode 100644 index 000000000..89d2efab2 --- /dev/null +++ b/example/rails-60/config/initializers/application_controller_renderer.rb @@ -0,0 +1,8 @@ +# Be sure to restart your server when you modify this file. + +# ActiveSupport::Reloader.to_prepare do +# ApplicationController.renderer.defaults.merge!( +# http_host: 'example.org', +# https: false +# ) +# end diff --git a/example/rails-60/config/initializers/assets.rb b/example/rails-60/config/initializers/assets.rb new file mode 100644 index 000000000..4b828e80c --- /dev/null +++ b/example/rails-60/config/initializers/assets.rb @@ -0,0 +1,14 @@ +# Be sure to restart your server when you modify this file. + +# Version of your assets, change this if you want to expire all your assets. +Rails.application.config.assets.version = '1.0' + +# Add additional assets to the asset load path. +# Rails.application.config.assets.paths << Emoji.images_path +# Add Yarn node_modules folder to the asset load path. +Rails.application.config.assets.paths << Rails.root.join('node_modules') + +# Precompile additional assets. +# application.js, application.css, and all non-JS/CSS in the app/assets +# folder are already added. +# Rails.application.config.assets.precompile += %w( admin.js admin.css ) diff --git a/example/rails-60/config/initializers/backtrace_silencers.rb b/example/rails-60/config/initializers/backtrace_silencers.rb new file mode 100644 index 000000000..59385cdf3 --- /dev/null +++ b/example/rails-60/config/initializers/backtrace_silencers.rb @@ -0,0 +1,7 @@ +# Be sure to restart your server when you modify this file. + +# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. +# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } + +# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. +# Rails.backtrace_cleaner.remove_silencers! diff --git a/example/rails-60/config/initializers/bugsnag.rb b/example/rails-60/config/initializers/bugsnag.rb new file mode 100644 index 000000000..58c57fbf6 --- /dev/null +++ b/example/rails-60/config/initializers/bugsnag.rb @@ -0,0 +1,3 @@ +Bugsnag.configure do |config| + config.api_key = "YOUR_API_KEY_HERE" +end diff --git a/example/rails-60/config/initializers/content_security_policy.rb b/example/rails-60/config/initializers/content_security_policy.rb new file mode 100644 index 000000000..35d0f26fc --- /dev/null +++ b/example/rails-60/config/initializers/content_security_policy.rb @@ -0,0 +1,30 @@ +# Be sure to restart your server when you modify this file. + +# Define an application-wide content security policy +# For further information see the following documentation +# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy + +# Rails.application.config.content_security_policy do |policy| +# policy.default_src :self, :https +# policy.font_src :self, :https, :data +# policy.img_src :self, :https, :data +# policy.object_src :none +# policy.script_src :self, :https +# policy.style_src :self, :https +# # If you are using webpack-dev-server then specify webpack-dev-server host +# policy.connect_src :self, :https, "http://localhost:3035", "ws://localhost:3035" if Rails.env.development? + +# # Specify URI for violation reports +# # policy.report_uri "/csp-violation-report-endpoint" +# end + +# If you are using UJS then enable automatic nonce generation +# Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) } + +# Set the nonce only to specific directives +# Rails.application.config.content_security_policy_nonce_directives = %w(script-src) + +# Report CSP violations to a specified URI +# For further information see the following documentation: +# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only +# Rails.application.config.content_security_policy_report_only = true diff --git a/example/rails-60/config/initializers/cookies_serializer.rb b/example/rails-60/config/initializers/cookies_serializer.rb new file mode 100644 index 000000000..5a6a32d37 --- /dev/null +++ b/example/rails-60/config/initializers/cookies_serializer.rb @@ -0,0 +1,5 @@ +# Be sure to restart your server when you modify this file. + +# Specify a serializer for the signed and encrypted cookie jars. +# Valid options are :json, :marshal, and :hybrid. +Rails.application.config.action_dispatch.cookies_serializer = :json diff --git a/example/rails-60/config/initializers/filter_parameter_logging.rb b/example/rails-60/config/initializers/filter_parameter_logging.rb new file mode 100644 index 000000000..4a994e1e7 --- /dev/null +++ b/example/rails-60/config/initializers/filter_parameter_logging.rb @@ -0,0 +1,4 @@ +# Be sure to restart your server when you modify this file. + +# Configure sensitive parameters which will be filtered from the log file. +Rails.application.config.filter_parameters += [:password] diff --git a/example/rails-60/config/initializers/inflections.rb b/example/rails-60/config/initializers/inflections.rb new file mode 100644 index 000000000..ac033bf9d --- /dev/null +++ b/example/rails-60/config/initializers/inflections.rb @@ -0,0 +1,16 @@ +# Be sure to restart your server when you modify this file. + +# Add new inflection rules using the following format. Inflections +# are locale specific, and you may define rules for as many different +# locales as you wish. All of these examples are active by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.plural /^(ox)$/i, '\1en' +# inflect.singular /^(ox)en/i, '\1' +# inflect.irregular 'person', 'people' +# inflect.uncountable %w( fish sheep ) +# end + +# These inflection rules are supported but not enabled by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.acronym 'RESTful' +# end diff --git a/example/rails-60/config/initializers/mime_types.rb b/example/rails-60/config/initializers/mime_types.rb new file mode 100644 index 000000000..dc1899682 --- /dev/null +++ b/example/rails-60/config/initializers/mime_types.rb @@ -0,0 +1,4 @@ +# Be sure to restart your server when you modify this file. + +# Add new mime types for use in respond_to blocks: +# Mime::Type.register "text/richtext", :rtf diff --git a/example/rails-60/config/initializers/wrap_parameters.rb b/example/rails-60/config/initializers/wrap_parameters.rb new file mode 100644 index 000000000..bbfc3961b --- /dev/null +++ b/example/rails-60/config/initializers/wrap_parameters.rb @@ -0,0 +1,14 @@ +# Be sure to restart your server when you modify this file. + +# This file contains settings for ActionController::ParamsWrapper which +# is enabled by default. + +# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. +ActiveSupport.on_load(:action_controller) do + wrap_parameters format: [:json] +end + +# To enable root element in JSON for ActiveRecord objects. +# ActiveSupport.on_load(:active_record) do +# self.include_root_in_json = true +# end diff --git a/example/rails-60/config/locales/en.yml b/example/rails-60/config/locales/en.yml new file mode 100644 index 000000000..cf9b342d0 --- /dev/null +++ b/example/rails-60/config/locales/en.yml @@ -0,0 +1,33 @@ +# Files in the config/locales directory are used for internationalization +# and are automatically loaded by Rails. If you want to use locales other +# than English, add the necessary files in this directory. +# +# To use the locales, use `I18n.t`: +# +# I18n.t 'hello' +# +# In views, this is aliased to just `t`: +# +# <%= t('hello') %> +# +# To use a different locale, set it with `I18n.locale`: +# +# I18n.locale = :es +# +# This would use the information in config/locales/es.yml. +# +# The following keys must be escaped otherwise they will not be retrieved by +# the default I18n backend: +# +# true, false, on, off, yes, no +# +# Instead, surround them with single quotes. +# +# en: +# 'true': 'foo' +# +# To learn more, please read the Rails Internationalization guide +# available at https://guides.rubyonrails.org/i18n.html. + +en: + hello: "Hello world" diff --git a/example/rails-60/config/puma.rb b/example/rails-60/config/puma.rb new file mode 100644 index 000000000..5ed443774 --- /dev/null +++ b/example/rails-60/config/puma.rb @@ -0,0 +1,38 @@ +# Puma can serve each request in a thread from an internal thread pool. +# The `threads` method setting takes two numbers: a minimum and maximum. +# Any libraries that use thread pools should be configured to match +# the maximum value specified for Puma. Default is set to 5 threads for minimum +# and maximum; this matches the default thread size of Active Record. +# +max_threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 } +min_threads_count = ENV.fetch("RAILS_MIN_THREADS") { max_threads_count } +threads min_threads_count, max_threads_count + +# Specifies the `port` that Puma will listen on to receive requests; default is 3000. +# +port ENV.fetch("PORT") { 3000 } + +# Specifies the `environment` that Puma will run in. +# +environment ENV.fetch("RAILS_ENV") { "development" } + +# Specifies the `pidfile` that Puma will use. +pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" } + +# Specifies the number of `workers` to boot in clustered mode. +# Workers are forked web server processes. If using threads and workers together +# the concurrency of the application would be max `threads` * `workers`. +# Workers do not work on JRuby or Windows (both of which do not support +# processes). +# +# workers ENV.fetch("WEB_CONCURRENCY") { 2 } + +# Use the `preload_app!` method when specifying a `workers` number. +# This directive tells Puma to first boot the application and load code +# before forking the application. This takes advantage of Copy On Write +# process behavior so workers use less memory. +# +# preload_app! + +# Allow puma to be restarted by `rails restart` command. +plugin :tmp_restart diff --git a/example/rails-60/config/routes.rb b/example/rails-60/config/routes.rb new file mode 100644 index 000000000..b5f1747c3 --- /dev/null +++ b/example/rails-60/config/routes.rb @@ -0,0 +1,27 @@ +Rails.application.routes.draw do + # Vanilla rails routing + get '/', to: 'application#index' + get '/crash', to: 'application#crash' + get '/crash_with_callback', to: 'application#callback' + get '/notify', to: 'application#notify' + get '/notify_data', to: 'application#data' + get '/notify_severity', to: 'application#severity' + + # Sidekiq routing + get '/sidekiq', to: 'sidekiq#index' + get '/sidekiq/crash', to: 'sidekiq#crash' + get '/sidekiq/notify_data', to: 'sidekiq#metadata' + get '/sidekiq/crash_with_callback', to: 'sidekiq#callbacks' + + # Que routing + get '/que', to: 'que#index' + get '/que/crash', to: 'que#crash' + get '/que/notify_data', to: 'que#metadata' + get '/que/crash_with_callback', to: 'que#callbacks' + + # Resque routing + get '/resque', to: 'resque#index' + get '/resque/crash', to: 'resque#crash' + get '/resque/crash_with_callback', to: 'resque#callbacks' + get '/resque/notify_data', to: 'resque#metadata' +end diff --git a/example/rails-60/config/spring.rb b/example/rails-60/config/spring.rb new file mode 100644 index 000000000..db5bf1307 --- /dev/null +++ b/example/rails-60/config/spring.rb @@ -0,0 +1,6 @@ +Spring.watch( + ".ruby-version", + ".rbenv-vars", + "tmp/restart.txt", + "tmp/caching-dev.txt" +) diff --git a/example/rails-60/config/storage.yml b/example/rails-60/config/storage.yml new file mode 100644 index 000000000..d32f76e8f --- /dev/null +++ b/example/rails-60/config/storage.yml @@ -0,0 +1,34 @@ +test: + service: Disk + root: <%= Rails.root.join("tmp/storage") %> + +local: + service: Disk + root: <%= Rails.root.join("storage") %> + +# Use rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key) +# amazon: +# service: S3 +# access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %> +# secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %> +# region: us-east-1 +# bucket: your_own_bucket + +# Remember not to checkin your GCS keyfile to a repository +# google: +# service: GCS +# project: your_project +# credentials: <%= Rails.root.join("path/to/gcs.keyfile") %> +# bucket: your_own_bucket + +# Use rails credentials:edit to set the Azure Storage secret (as azure_storage:storage_access_key) +# microsoft: +# service: AzureStorage +# storage_account_name: your_account_name +# storage_access_key: <%= Rails.application.credentials.dig(:azure_storage, :storage_access_key) %> +# container: your_container_name + +# mirror: +# service: Mirror +# primary: local +# mirrors: [ amazon, google, microsoft ] diff --git a/example/rails-60/db/seeds.rb b/example/rails-60/db/seeds.rb new file mode 100644 index 000000000..1beea2acc --- /dev/null +++ b/example/rails-60/db/seeds.rb @@ -0,0 +1,7 @@ +# This file should contain all the record creation needed to seed the database with its default values. +# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). +# +# Examples: +# +# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) +# Character.create(name: 'Luke', movie: movies.first) diff --git a/example/rails-60/lib/assets/.keep b/example/rails-60/lib/assets/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/example/rails-60/lib/tasks/resque:setup.rake b/example/rails-60/lib/tasks/resque:setup.rake new file mode 100644 index 000000000..1c97b45ea --- /dev/null +++ b/example/rails-60/lib/tasks/resque:setup.rake @@ -0,0 +1,5 @@ +require 'resque/tasks' + +task 'resque:setup' => :environment do + require './app/workers/resque_workers' +end diff --git a/example/rails-60/log/.keep b/example/rails-60/log/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/example/rails-60/public/404.html b/example/rails-60/public/404.html new file mode 100644 index 000000000..2be3af26f --- /dev/null +++ b/example/rails-60/public/404.html @@ -0,0 +1,67 @@ + + + + The page you were looking for doesn't exist (404) + + + + + + +
+
+

The page you were looking for doesn't exist.

+

You may have mistyped the address or the page may have moved.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/example/rails-60/public/422.html b/example/rails-60/public/422.html new file mode 100644 index 000000000..c08eac0d1 --- /dev/null +++ b/example/rails-60/public/422.html @@ -0,0 +1,67 @@ + + + + The change you wanted was rejected (422) + + + + + + +
+
+

The change you wanted was rejected.

+

Maybe you tried to change something you didn't have access to.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/example/rails-60/public/500.html b/example/rails-60/public/500.html new file mode 100644 index 000000000..78a030af2 --- /dev/null +++ b/example/rails-60/public/500.html @@ -0,0 +1,66 @@ + + + + We're sorry, but something went wrong (500) + + + + + + +
+
+

We're sorry, but something went wrong.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/example/rails-60/public/apple-touch-icon-precomposed.png b/example/rails-60/public/apple-touch-icon-precomposed.png new file mode 100644 index 000000000..e69de29bb diff --git a/example/rails-60/public/apple-touch-icon.png b/example/rails-60/public/apple-touch-icon.png new file mode 100644 index 000000000..e69de29bb diff --git a/example/rails-60/public/favicon.ico b/example/rails-60/public/favicon.ico new file mode 100644 index 000000000..e69de29bb diff --git a/example/rails-60/public/robots.txt b/example/rails-60/public/robots.txt new file mode 100644 index 000000000..c19f78ab6 --- /dev/null +++ b/example/rails-60/public/robots.txt @@ -0,0 +1 @@ +# See https://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file diff --git a/example/rails-60/public/style.css b/example/rails-60/public/style.css new file mode 100644 index 000000000..253bee2aa --- /dev/null +++ b/example/rails-60/public/style.css @@ -0,0 +1,34 @@ +body { + font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Helvetica, Arial, sans-serif, Apple Color Emoji, Segoe UI Emoji; + max-width: 80ch; + margin: 0 auto; +} + +pre, +code { + font-family: SFMono-Regular, Consolas, Liberation Mono, Menlo, monospace; +} + +pre { + background: rgba(0, 0, 0, .05); + border: 1px solid rgba(0, 0, 0, .1); + padding: 1rem; +} + +pre.shell::before { + content: '$ '; + pointer-events: none; +} + +a:link, +a:visited { + color: #536eec; +} + +a:hover { + opacity: .7; +} + +.upper { + text-transform: uppercase; +} diff --git a/example/rails-60/storage/.keep b/example/rails-60/storage/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/example/rails-60/tmp/.keep b/example/rails-60/tmp/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/example/rails-60/tmp/pids/.keep b/example/rails-60/tmp/pids/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/features/fixtures/rails3/app/config/initializers/bugsnag.rb b/features/fixtures/rails3/app/config/initializers/bugsnag.rb index fea970a97..b849c0995 100644 --- a/features/fixtures/rails3/app/config/initializers/bugsnag.rb +++ b/features/fixtures/rails3/app/config/initializers/bugsnag.rb @@ -11,10 +11,11 @@ config.release_stage = ENV["BUGSNAG_RELEASE_STAGE"] if ENV.include? "BUGSNAG_RELEASE_STAGE" config.send_code = ENV["BUGSNAG_SEND_CODE"] != "false" config.send_environment = ENV["BUGSNAG_SEND_ENVIRONMENT"] == "true" + config.meta_data_filters << 'filtered_parameter' if ENV["SQL_ONLY_BREADCRUMBS"] == "true" config.before_breadcrumb_callbacks << Proc.new do |breadcrumb| breadcrumb.ignore! unless breadcrumb.meta_data[:event_name] == "sql.active_record" && breadcrumb.meta_data[:name] == "User Load" end end -end \ No newline at end of file +end diff --git a/features/fixtures/rails4/app/config/initializers/bugsnag.rb b/features/fixtures/rails4/app/config/initializers/bugsnag.rb index d7ce3b9b3..b849c0995 100644 --- a/features/fixtures/rails4/app/config/initializers/bugsnag.rb +++ b/features/fixtures/rails4/app/config/initializers/bugsnag.rb @@ -11,6 +11,7 @@ config.release_stage = ENV["BUGSNAG_RELEASE_STAGE"] if ENV.include? "BUGSNAG_RELEASE_STAGE" config.send_code = ENV["BUGSNAG_SEND_CODE"] != "false" config.send_environment = ENV["BUGSNAG_SEND_ENVIRONMENT"] == "true" + config.meta_data_filters << 'filtered_parameter' if ENV["SQL_ONLY_BREADCRUMBS"] == "true" config.before_breadcrumb_callbacks << Proc.new do |breadcrumb| diff --git a/features/fixtures/rails5/app/config/initializers/bugsnag.rb b/features/fixtures/rails5/app/config/initializers/bugsnag.rb index d7ce3b9b3..b849c0995 100644 --- a/features/fixtures/rails5/app/config/initializers/bugsnag.rb +++ b/features/fixtures/rails5/app/config/initializers/bugsnag.rb @@ -11,6 +11,7 @@ config.release_stage = ENV["BUGSNAG_RELEASE_STAGE"] if ENV.include? "BUGSNAG_RELEASE_STAGE" config.send_code = ENV["BUGSNAG_SEND_CODE"] != "false" config.send_environment = ENV["BUGSNAG_SEND_ENVIRONMENT"] == "true" + config.meta_data_filters << 'filtered_parameter' if ENV["SQL_ONLY_BREADCRUMBS"] == "true" config.before_breadcrumb_callbacks << Proc.new do |breadcrumb| diff --git a/features/fixtures/rails6/app/config/initializers/bugsnag.rb b/features/fixtures/rails6/app/config/initializers/bugsnag.rb index d7ce3b9b3..b849c0995 100644 --- a/features/fixtures/rails6/app/config/initializers/bugsnag.rb +++ b/features/fixtures/rails6/app/config/initializers/bugsnag.rb @@ -11,6 +11,7 @@ config.release_stage = ENV["BUGSNAG_RELEASE_STAGE"] if ENV.include? "BUGSNAG_RELEASE_STAGE" config.send_code = ENV["BUGSNAG_SEND_CODE"] != "false" config.send_environment = ENV["BUGSNAG_SEND_ENVIRONMENT"] == "true" + config.meta_data_filters << 'filtered_parameter' if ENV["SQL_ONLY_BREADCRUMBS"] == "true" config.before_breadcrumb_callbacks << Proc.new do |breadcrumb| diff --git a/features/rails_features/meta_data_filters.feature b/features/rails_features/meta_data_filters.feature index fc6b4a8f6..b867e63e7 100644 --- a/features/rails_features/meta_data_filters.feature +++ b/features/rails_features/meta_data_filters.feature @@ -3,12 +3,14 @@ Feature: Metadata filters @rails3 @rails4 @rails5 @rails6 Scenario: Meta_data_filters should include Rails.configuration.filter_parameters Given I start the rails service - When I navigate to the route "/metadata_filters/filter" on the rails app + When I navigate to the route "/metadata_filters/filter?filtered_parameter=foo&other_parameter=bar" on the rails app And I wait to receive a request Then the request is valid for the error reporting API version "4.0" for the "Ruby Bugsnag Notifier" And the event "unhandled" is false And the exception "errorClass" equals "RuntimeError" And the exception "message" starts with "handled string" And the event "app.type" equals "rails" - And the event "metaData.request.url" ends with "/metadata_filters/filter" + And the event "metaData.request.url" ends with "/metadata_filters/filter?filtered_parameter=[FILTERED]&other_parameter=bar" And the event "metaData.my_specific_filter" equals "[FILTERED]" + And the event "metaData.request.params.filtered_parameter" equals "[FILTERED]" + And the event "metaData.request.params.other_parameter" equals "bar" diff --git a/lib/bugsnag.rb b/lib/bugsnag.rb index b20f3c5e0..1be5d084a 100644 --- a/lib/bugsnag.rb +++ b/lib/bugsnag.rb @@ -33,6 +33,7 @@ require "bugsnag/breadcrumbs/breadcrumb" require "bugsnag/breadcrumbs/breadcrumbs" +# rubocop:todo Metrics/ModuleLength module Bugsnag LOCK = Mutex.new INTEGRATIONS = [:resque, :sidekiq, :mailman, :delayed_job, :shoryuken, :que, :mongo] @@ -63,7 +64,7 @@ def notify(exception, auto_notify=false, &block) auto_notify = false end - return unless deliver_notification?(exception, auto_notify) + return unless should_deliver_notification?(exception, auto_notify) exception = NIL_EXCEPTION_DESCRIPTION if exception.nil? @@ -71,6 +72,7 @@ def notify(exception, auto_notify=false, &block) # If this is an auto_notify we yield the block before the any middleware is run yield(report) if block_given? && auto_notify + if report.ignore? configuration.debug("Not notifying #{report.exceptions.last[:errorClass]} due to ignore being signified in auto_notify block") return @@ -97,6 +99,7 @@ def notify(exception, auto_notify=false, &block) # If this is not an auto_notify then the block was provided by the user. This should be the last # block that is run as it is the users "most specific" block. yield(report) if block_given? && !auto_notify + if report.ignore? configuration.debug("Not notifying #{report.exceptions.last[:errorClass]} due to ignore being signified in user provided block") return @@ -111,13 +114,7 @@ def notify(exception, auto_notify=false, &block) report.severity_reason = initial_reason end - # Deliver - configuration.info("Notifying #{configuration.notify_endpoint} of #{report.exceptions.last[:errorClass]}") - options = {:headers => report.headers} - payload = ::JSON.dump(Bugsnag::Helpers.trim_if_needed(report.as_json)) - Bugsnag::Delivery[configuration.delivery_method].deliver(configuration.notify_endpoint, payload, configuration, options) - report_summary = report.summary - leave_breadcrumb(report_summary[:error_class], report_summary, Bugsnag::Breadcrumbs::ERROR_BREADCRUMB_TYPE, :auto) + deliver_notification(report) end end @@ -147,6 +144,7 @@ def at_exit_handler_installed? # Configuration getters ## # Returns the client's Configuration object, or creates one if not yet created. + # @return [Configuration] def configuration @configuration = nil unless defined?(@configuration) @configuration || LOCK.synchronize { @configuration ||= Bugsnag::Configuration.new } @@ -211,27 +209,40 @@ def leave_breadcrumb(name, meta_data={}, type=Bugsnag::Breadcrumbs::MANUAL_BREAD validator.validate(breadcrumb) # Skip if it's already invalid - unless breadcrumb.ignore? - # Run callbacks - configuration.before_breadcrumb_callbacks.each do |c| - c.arity > 0 ? c.call(breadcrumb) : c.call - break if breadcrumb.ignore? - end + return if breadcrumb.ignore? - # Return early if ignored - return if breadcrumb.ignore? + # Run callbacks + configuration.before_breadcrumb_callbacks.each do |c| + c.arity > 0 ? c.call(breadcrumb) : c.call + break if breadcrumb.ignore? + end + + # Return early if ignored + return if breadcrumb.ignore? - # Validate again in case of callback alteration - validator.validate(breadcrumb) + # Validate again in case of callback alteration + validator.validate(breadcrumb) - # Add to breadcrumbs buffer if still valid - configuration.breadcrumbs << breadcrumb unless breadcrumb.ignore? + # Add to breadcrumbs buffer if still valid + configuration.breadcrumbs << breadcrumb unless breadcrumb.ignore? + end + + ## + # Returns the client's Cleaner object, or creates one if not yet created. + # + # @api private + # + # @return [Cleaner] + def cleaner + @cleaner = nil unless defined?(@cleaner) + @cleaner || LOCK.synchronize do + @cleaner ||= Bugsnag::Cleaner.new(configuration) end end private - def deliver_notification?(exception, auto_notify) + def should_deliver_notification?(exception, auto_notify) reason = abort_reason(exception, auto_notify) configuration.debug(reason) unless reason.nil? reason.nil? @@ -249,6 +260,32 @@ def abort_reason(exception, auto_notify) end end + ## + # Deliver the notification to Bugsnag + # + # @param report [Report] + # @return void + def deliver_notification(report) + configuration.info("Notifying #{configuration.notify_endpoint} of #{report.exceptions.last[:errorClass]}") + + payload = report_to_json(report) + options = {:headers => report.headers} + + Bugsnag::Delivery[configuration.delivery_method].deliver( + configuration.notify_endpoint, + payload, + configuration, + options + ) + + leave_breadcrumb( + report.summary[:error_class], + report.summary, + Bugsnag::Breadcrumbs::ERROR_BREADCRUMB_TYPE, + :auto + ) + end + # Check if the API key is valid and warn (once) if it is not def check_key_valid @key_warning = false unless defined?(@key_warning) @@ -273,7 +310,23 @@ def check_endpoint_setup raise ArgumentError, "The session endpoint cannot be modified without the notify endpoint" end end + + ## + # Convert the Report object to JSON + # + # We ensure the report is safe to send by removing recursion, fixing + # encoding errors and redacting metadata according to "meta_data_filters" + # + # @param report [Report] + # @return string + def report_to_json(report) + cleaned = cleaner.clean_object(report.as_json) + trimmed = Bugsnag::Helpers.trim_if_needed(cleaned) + + ::JSON.dump(trimmed) + end end end +# rubocop:enable Metrics/ModuleLength Bugsnag.load_integrations unless ENV["BUGSNAG_DISABLE_AUTOCONFIGURE"] diff --git a/lib/bugsnag/breadcrumbs/breadcrumbs.rb b/lib/bugsnag/breadcrumbs/breadcrumbs.rb index 24f140e1d..69506d29d 100644 --- a/lib/bugsnag/breadcrumbs/breadcrumbs.rb +++ b/lib/bugsnag/breadcrumbs/breadcrumbs.rb @@ -1,6 +1,4 @@ module Bugsnag::Breadcrumbs - MAX_NAME_LENGTH = 30 - VALID_BREADCRUMB_TYPES = [ ERROR_BREADCRUMB_TYPE = "error", MANUAL_BREADCRUMB_TYPE = "manual", diff --git a/lib/bugsnag/breadcrumbs/validator.rb b/lib/bugsnag/breadcrumbs/validator.rb index c6893b50a..d1f559492 100644 --- a/lib/bugsnag/breadcrumbs/validator.rb +++ b/lib/bugsnag/breadcrumbs/validator.rb @@ -15,12 +15,6 @@ def initialize(configuration) # # @param breadcrumb [Bugsnag::Breadcrumbs::Breadcrumb] the breadcrumb to be validated def validate(breadcrumb) - # Check name length - if breadcrumb.name.size > Bugsnag::Breadcrumbs::MAX_NAME_LENGTH - @configuration.debug("Breadcrumb name trimmed to length #{Bugsnag::Breadcrumbs::MAX_NAME_LENGTH}. Original name: #{breadcrumb.name}") - breadcrumb.name = breadcrumb.name.slice(0...Bugsnag::Breadcrumbs::MAX_NAME_LENGTH) - end - # Check meta_data hash doesn't contain complex values breadcrumb.meta_data = breadcrumb.meta_data.select do |k, v| if valid_meta_data_type?(v) diff --git a/lib/bugsnag/cleaner.rb b/lib/bugsnag/cleaner.rb index ea7539d86..b33d06600 100644 --- a/lib/bugsnag/cleaner.rb +++ b/lib/bugsnag/cleaner.rb @@ -1,19 +1,76 @@ require 'uri' module Bugsnag + # @api private class Cleaner FILTERED = '[FILTERED]'.freeze RECURSION = '[RECURSION]'.freeze OBJECT = '[OBJECT]'.freeze RAISED = '[RAISED]'.freeze + OBJECT_WITH_ID_AND_CLASS = '[OBJECT]: [Class]: %s [ID]: %d'.freeze - def initialize(filters) - @filters = Array(filters) - @deep_filters = @filters.any? {|f| f.kind_of?(Regexp) && f.to_s.include?("\\.".freeze) } + ## + # @param configuration [Configuration] + def initialize(configuration) + @configuration = configuration end - def clean_object(obj) - traverse_object(obj, {}, nil) + def clean_object(object) + @deep_filters = deep_filters? + + traverse_object(object, {}, nil) + end + + ## + # @param url [String] + # @return [String] + def clean_url(url) + return url if @configuration.meta_data_filters.empty? + + uri = URI(url) + return url unless uri.query + + query_params = uri.query.split('&').map { |pair| pair.split('=') } + query_params.map! do |key, val| + if filters_match?(key) + "#{key}=#{FILTERED}" + else + "#{key}=#{val}" + end + end + + uri.query = query_params.join('&') + uri.to_s + end + + private + + ## + # This method calculates whether we need to filter deeply or not; i.e. whether + # we should match both with and without 'request.params' + # + # This is cached on the instance variable '@deep_filters' for performance + # reasons + # + # @return [Boolean] + def deep_filters? + @configuration.meta_data_filters.any? do |filter| + filter.is_a?(Regexp) && filter.to_s.include?("\\.".freeze) + end + end + + def clean_string(str) + if defined?(str.encoding) && defined?(Encoding::UTF_8) + if str.encoding == Encoding::UTF_8 + str.valid_encoding? ? str : str.encode('utf-16', invalid: :replace, undef: :replace).encode('utf-8') + else + str.encode('utf-8', invalid: :replace, undef: :replace) + end + elsif defined?(Iconv) + Iconv.conv('UTF-8//IGNORE', 'UTF-8', str) || str + else + str + end end def traverse_object(obj, seen, scope) @@ -28,12 +85,14 @@ def traverse_object(obj, seen, scope) value = case obj when Hash clean_hash = {} - obj.each do |k,v| + obj.each do |k, v| begin - if filters_match_deeply?(k, scope) + current_scope = [scope, k].compact.join('.') + + if filters_match_deeply?(k, current_scope) clean_hash[k] = FILTERED else - clean_hash[k] = traverse_object(v, seen, [scope, k].compact.join('.')) + clean_hash[k] = traverse_object(v, seen, current_scope) end # If we get an error here, we assume the key needs to be filtered # to avoid leaking things we shouldn't. We also remove the key itself @@ -63,7 +122,12 @@ def traverse_object(obj, seen, scope) # avoid leaking potentially sensitive data from objects' #inspect output if str =~ /#<.*>/ - OBJECT + # Use id of the object if available + if obj.respond_to?(:id) + format(OBJECT_WITH_ID_AND_CLASS, class_name: obj.class, id: obj.id) + else + OBJECT + end else clean_string(str) end @@ -73,67 +137,56 @@ def traverse_object(obj, seen, scope) value end - def clean_string(str) - if defined?(str.encoding) && defined?(Encoding::UTF_8) - if str.encoding == Encoding::UTF_8 - str.valid_encoding? ? str : str.encode('utf-16', invalid: :replace, undef: :replace).encode('utf-8') + ## + # @param key [String, #to_s] + # @return [Boolean] + def filters_match?(key) + str = key.to_s + + @configuration.meta_data_filters.any? do |filter| + case filter + when Regexp + str.match(filter) else - str.encode('utf-8', invalid: :replace, undef: :replace) + str.include?(filter.to_s) end - elsif defined?(Iconv) - Iconv.conv('UTF-8//IGNORE', 'UTF-8', str) || str - else - str end end - def self.clean_object_encoding(obj) - new(nil).clean_object(obj) - end + ## + # If someone has a Rails filter like /^stuff\.secret/, it won't match + # "request.params.stuff.secret", so we try it both with and without the + # "request.params." bit. + # + # @param key [String, #to_s] + # @param scope [String] + # @return [Boolean] + def filters_match_deeply?(key, scope) + return false unless scope_should_be_filtered?(scope) - def clean_url(url) - return url if @filters.empty? + return true if filters_match?(key) + return false unless @deep_filters - uri = URI(url) - return url unless uri.query + return true if filters_match?(scope) - query_params = uri.query.split('&').map { |pair| pair.split('=') } - query_params.map! do |key, val| - if filters_match?(key) - "#{key}=#{FILTERED}" + @configuration.scopes_to_filter.any? do |scope_to_filter| + if scope.start_with?("#{scope_to_filter}.request.params.") + filters_match?(scope.sub("#{scope_to_filter}.request.params.", '')) else - "#{key}=#{val}" + filters_match?(scope.sub("#{scope_to_filter}.", '')) end end - - uri.query = query_params.join('&') - uri.to_s end - private - - def filters_match?(key) - str = key.to_s - - @filters.any? do |f| - case f - when Regexp - str.match(f) - else - str.include?(f.to_s) - end + ## + # Should the given scope be filtered? + # + # @param scope [String] + # @return [Boolean] + def scope_should_be_filtered?(scope) + @configuration.scopes_to_filter.any? do |scope_to_filter| + scope.start_with?("#{scope_to_filter}.") end end - - # If someone has a Rails filter like /^stuff\.secret/, it won't match "request.params.stuff.secret", - # so we try it both with and without the "request.params." bit. - def filters_match_deeply?(key, scope) - return true if filters_match?(key) - return false unless @deep_filters - - long = [scope, key].compact.join('.') - short = long.sub(/^request\.params\./, '') - filters_match?(long) || filters_match?(short) - end end end diff --git a/lib/bugsnag/configuration.rb b/lib/bugsnag/configuration.rb index 90a3fa2fb..d017c111e 100644 --- a/lib/bugsnag/configuration.rb +++ b/lib/bugsnag/configuration.rb @@ -3,6 +3,7 @@ require "logger" require "bugsnag/middleware_stack" require "bugsnag/middleware/callbacks" +require "bugsnag/middleware/discard_error_class" require "bugsnag/middleware/exception_meta_data" require "bugsnag/middleware/ignore_error_class" require "bugsnag/middleware/suggestion_data" @@ -35,9 +36,13 @@ class Configuration attr_accessor :timeout attr_accessor :hostname attr_accessor :runtime_versions - attr_accessor :ignore_classes + attr_accessor :discard_classes attr_accessor :auto_capture_sessions + ## + # @deprecated Use {#discard_classes} instead + attr_accessor :ignore_classes + ## # @return [String] URL error notifications will be delivered to attr_reader :notify_endpoint @@ -67,6 +72,10 @@ class Configuration # @return [Regexp] matching file paths out of project attr_accessor :vendor_path + ## + # @return [Array] + attr_reader :scopes_to_filter + API_KEY_REGEX = /[0-9a-f]{32}/i THREAD_LOCAL_NAME = "bugsnag_req_data" @@ -86,7 +95,9 @@ class Configuration DEFAULT_MAX_BREADCRUMBS = 25 # Path to vendored code. Used to mark file paths as out of project. - DEFAULT_VENDOR_PATH = %r{^(vendor\/|\.bundle\/)} + DEFAULT_VENDOR_PATH = %r{^(vendor/|\.bundle/)} + + DEFAULT_SCOPES_TO_FILTER = ['events.metaData', 'events.breadcrumbs.metaData'].freeze alias :track_sessions :auto_capture_sessions alias :track_sessions= :auto_capture_sessions= @@ -99,6 +110,7 @@ def initialize self.send_environment = false self.send_code = true self.meta_data_filters = Set.new(DEFAULT_META_DATA_FILTERS) + self.scopes_to_filter = DEFAULT_SCOPES_TO_FILTER self.hostname = default_hostname self.runtime_versions = {} self.runtime_versions["ruby"] = RUBY_VERSION @@ -122,7 +134,10 @@ def initialize # SystemExit and SignalException are common Exception types seen with # successful exits and are not automatically reported to Bugsnag + # TODO move these defaults into `discard_classes` when `ignore_classes` + # is removed self.ignore_classes = Set.new([SystemExit, SignalException]) + self.discard_classes = Set.new([]) # Read the API key from the environment self.api_key = ENV["BUGSNAG_API_KEY"] @@ -147,6 +162,7 @@ def initialize # Configure the bugsnag middleware stack self.internal_middleware = Bugsnag::MiddlewareStack.new self.internal_middleware.use Bugsnag::Middleware::ExceptionMetaData + self.internal_middleware.use Bugsnag::Middleware::DiscardErrorClass self.internal_middleware.use Bugsnag::Middleware::IgnoreErrorClass self.internal_middleware.use Bugsnag::Middleware::SuggestionData self.internal_middleware.use Bugsnag::Middleware::ClassifyError @@ -304,6 +320,8 @@ def disable_sessions private + attr_writer :scopes_to_filter + PROG_NAME = "[Bugsnag]" def default_hostname diff --git a/lib/bugsnag/helpers.rb b/lib/bugsnag/helpers.rb index 99a3c2f21..21223f74a 100644 --- a/lib/bugsnag/helpers.rb +++ b/lib/bugsnag/helpers.rb @@ -17,12 +17,10 @@ module Helpers def self.trim_if_needed(value) value = "" if value.nil? - # Sanitize object - sanitized_value = Bugsnag::Cleaner.clean_object_encoding(value) - return sanitized_value unless payload_too_long?(sanitized_value) + return value unless payload_too_long?(value) # Trim metadata - reduced_value = trim_metadata(sanitized_value) + reduced_value = trim_metadata(value) return reduced_value unless payload_too_long?(reduced_value) # Trim code from stacktrace diff --git a/lib/bugsnag/middleware/discard_error_class.rb b/lib/bugsnag/middleware/discard_error_class.rb new file mode 100644 index 000000000..1dff08ed6 --- /dev/null +++ b/lib/bugsnag/middleware/discard_error_class.rb @@ -0,0 +1,30 @@ +module Bugsnag::Middleware + ## + # Determines if the exception should be ignored based on the configured + # `discard_classes` + class DiscardErrorClass + ## + # @param middleware [#call] The next middleware to call + def initialize(middleware) + @middleware = middleware + end + + ## + # @param report [Report] + def call(report) + should_discard = report.raw_exceptions.any? do |ex| + report.configuration.discard_classes.any? do |to_ignore| + case to_ignore + when String then to_ignore == ex.class.name + when Regexp then to_ignore =~ ex.class.name + else false + end + end + end + + report.ignore! if should_discard + + @middleware.call(report) + end + end +end diff --git a/lib/bugsnag/middleware/ignore_error_class.rb b/lib/bugsnag/middleware/ignore_error_class.rb index 5d21a7d08..3ef5c996a 100644 --- a/lib/bugsnag/middleware/ignore_error_class.rb +++ b/lib/bugsnag/middleware/ignore_error_class.rb @@ -2,6 +2,8 @@ module Bugsnag::Middleware ## # Determines if the exception should be ignored based on the configured # `ignore_classes` + # + # @deprecated Use {DiscardErrorClass} instead class IgnoreErrorClass def initialize(bugsnag) @bugsnag = bugsnag diff --git a/lib/bugsnag/middleware/rack_request.rb b/lib/bugsnag/middleware/rack_request.rb index 3a2a39719..6825ccf21 100644 --- a/lib/bugsnag/middleware/rack_request.rb +++ b/lib/bugsnag/middleware/rack_request.rb @@ -28,18 +28,16 @@ def call(report) url = "#{request.scheme}://#{request.host}" url << ":#{request.port}" unless [80, 443].include?(request.port) - cleaner = Bugsnag::Cleaner.new(report.configuration.meta_data_filters) - # If app is passed a bad URL, this code will crash attempting to clean it begin - url << cleaner.clean_url(request.fullpath) + url << Bugsnag.cleaner.clean_url(request.fullpath) rescue StandardError => stde Bugsnag.configuration.warn "RackRequest - Rescued error while cleaning request.fullpath: #{stde}" end referer = nil begin - referer = cleaner.clean_url(request.referer) if request.referer + referer = Bugsnag.cleaner.clean_url(request.referer) if request.referer rescue StandardError => stde Bugsnag.configuration.warn "RackRequest - Rescued error while cleaning request.referer: #{stde}" end diff --git a/lib/bugsnag/report.rb b/lib/bugsnag/report.rb index c3b1e54aa..66b3ed7fd 100644 --- a/lib/bugsnag/report.rb +++ b/lib/bugsnag/report.rb @@ -97,6 +97,7 @@ def as_json releaseStage: release_stage, type: app_type }, + breadcrumbs: breadcrumbs.map(&:to_h), context: context, device: { hostname: hostname, @@ -104,6 +105,7 @@ def as_json }, exceptions: exceptions, groupingHash: grouping_hash, + metaData: meta_data, session: session, severity: severity, severityReason: severity_reason, @@ -111,19 +113,7 @@ def as_json user: user } - # cleanup character encodings - payload_event = Bugsnag::Cleaner.clean_object_encoding(payload_event) - - # filter out sensitive values in (and cleanup encodings) metaData - filter_cleaner = Bugsnag::Cleaner.new(configuration.meta_data_filters) - payload_event[:metaData] = filter_cleaner.clean_object(meta_data) - payload_event[:breadcrumbs] = breadcrumbs.map do |breadcrumb| - breadcrumb_hash = breadcrumb.to_h - breadcrumb_hash[:metaData] = filter_cleaner.clean_object(breadcrumb_hash[:metaData]) - breadcrumb_hash - end - - payload_event.reject! {|k,v| v.nil? } + payload_event.reject! {|k, v| v.nil? } # return the payload hash { diff --git a/lib/bugsnag/stacktrace.rb b/lib/bugsnag/stacktrace.rb index 1eb0259e0..ac31bb535 100644 --- a/lib/bugsnag/stacktrace.rb +++ b/lib/bugsnag/stacktrace.rb @@ -9,27 +9,25 @@ class Stacktrace ## # Process a backtrace and the configuration into a parsed stacktrace. + # + # rubocop:todo Metrics/CyclomaticComplexity def initialize(backtrace, configuration) @configuration = configuration backtrace = caller if !backtrace || backtrace.empty? @processed_backtrace = backtrace.map do |trace| + # Parse the stacktrace line if trace.match(BACKTRACE_LINE_REGEX) file, line_str, method = [$1, $2, $3] elsif trace.match(JAVA_BACKTRACE_REGEX) method, file, line_str = [$1, $2, $3] end - # Parse the stacktrace line - next(nil) if file.nil? # Expand relative paths - p = Pathname.new(file) - if p.relative? - file = p.realpath.to_s rescue file - end + file = File.realpath(file) rescue file # Generate the stacktrace line hash trace_hash = {} @@ -64,6 +62,7 @@ def initialize(backtrace, configuration) end end.compact end + # rubocop:enable Metrics/CyclomaticComplexity ## # Returns the processed backtrace diff --git a/spec/breadcrumbs/breadcrumb_spec.rb b/spec/breadcrumbs/breadcrumb_spec.rb index 3f315b327..acd3f72c2 100644 --- a/spec/breadcrumbs/breadcrumb_spec.rb +++ b/spec/breadcrumbs/breadcrumb_spec.rb @@ -90,4 +90,4 @@ ) end end -end \ No newline at end of file +end diff --git a/spec/breadcrumbs/validator_spec.rb b/spec/breadcrumbs/validator_spec.rb index 07e7b2c5b..581b243c3 100644 --- a/spec/breadcrumbs/validator_spec.rb +++ b/spec/breadcrumbs/validator_spec.rb @@ -31,31 +31,6 @@ validator.validate(breadcrumb) end - it "trims long messages to length and warns" do - config = instance_double(Bugsnag::Configuration) - allow(config).to receive(:enabled_automatic_breadcrumb_types).and_return(enabled_automatic_breadcrumb_types) - validator = Bugsnag::Breadcrumbs::Validator.new(config) - - name = "1234567890123456789012345678901234567890" - - breadcrumb = instance_double(Bugsnag::Breadcrumbs::Breadcrumb, { - :auto => auto, - :name => name, - :type => type, - :meta_data => meta_data, - :meta_data= => nil - }) - - expect(breadcrumb).to_not receive(:ignore!) - expect(breadcrumb).to receive(:name=).with("123456789012345678901234567890") - expected_string = "Breadcrumb name trimmed to length 30. Original name: #{name}" - expect(config).to receive(:debug).with(expected_string) - - validator.validate(breadcrumb) - # Check the original message has not been modified - expect(name).to eq("1234567890123456789012345678901234567890") - end - describe "tests meta_data types" do it "accepts Strings, Numerics, Booleans, & nil" do config = instance_double(Bugsnag::Configuration) @@ -198,4 +173,4 @@ class TestClass end end end -end \ No newline at end of file +end diff --git a/spec/bugsnag_spec.rb b/spec/bugsnag_spec.rb index 73e4b1237..07cc6121d 100644 --- a/spec/bugsnag_spec.rb +++ b/spec/bugsnag_spec.rb @@ -268,7 +268,7 @@ module Kernel ) expect(breadcrumbs.to_a.size).to eq(1) expect(breadcrumbs.first.to_h).to match({ - :name => "123123123123123123123123123123", + :name => "123123123123123123123123123123456456456456456456456456456456", :type => Bugsnag::Breadcrumbs::MANUAL_BREADCRUMB_TYPE, :metaData => { :a => 1 @@ -311,7 +311,7 @@ module Kernel Bugsnag.leave_breadcrumb("TestName") expect(breadcrumbs.to_a.size).to eq(1) expect(breadcrumbs.first.to_h).to match({ - :name => "123123123123123123123123123123", + :name => "123123123123123123123123123123456456456456456", :type => Bugsnag::Breadcrumbs::MANUAL_BREADCRUMB_TYPE, :metaData => { :int => 1 diff --git a/spec/cleaner_spec.rb b/spec/cleaner_spec.rb index b40c657f2..96bb9dfec 100644 --- a/spec/cleaner_spec.rb +++ b/spec/cleaner_spec.rb @@ -3,7 +3,7 @@ require 'spec_helper' describe Bugsnag::Cleaner do - subject { described_class.new(nil) } + subject { Bugsnag::Cleaner.new(Bugsnag::Configuration.new) } describe "#clean_object" do is_jruby = defined?(RUBY_ENGINE) && RUBY_ENGINE == 'jruby' @@ -134,6 +134,17 @@ def to_s expect(subject.clean_object(object)).to eq("[RECURSION]") end + it "cleans custom objects to show the id of the object if object responds to id method" do + class MacaronWithId + def id + 10 + end + end + + a = MacaronWithId.new + expect(subject.clean_object(a)).to eq("[OBJECT]: [Class]: #{a.class.name} [ID]: #{a.id}") + end + it "cleans up binary strings properly" do if RUBY_VERSION > "1.9" obj = "Andr\xc7\xff" @@ -156,23 +167,113 @@ def to_s end it "filters by string inclusion" do - expect(described_class.new(['f']).clean_object({ :foo => 'bar' })).to eq({ :foo => '[FILTERED]' }) - expect(described_class.new(['b']).clean_object({ :foo => 'bar' })).to eq({ :foo => 'bar' }) + object = { events: { metaData: { foo: 'bar' } } } + + configuration = Bugsnag::Configuration.new + configuration.meta_data_filters = ['f'] + + cleaner = Bugsnag::Cleaner.new(configuration) + expect(cleaner.clean_object(object)).to eq({ events: { metaData: { foo: '[FILTERED]' } } }) + + configuration = Bugsnag::Configuration.new + configuration.meta_data_filters = ['b'] + + cleaner = Bugsnag::Cleaner.new(configuration) + expect(cleaner.clean_object(object)).to eq({ events: { metaData: { foo: 'bar' } } }) end it "filters by regular expression" do - expect(described_class.new([/fb?/]).clean_object({ :foo => 'bar' })).to eq({ :foo => '[FILTERED]' }) - expect(described_class.new([/fb+/]).clean_object({ :foo => 'bar' })).to eq({ :foo => 'bar' }) + object = { events: { metaData: { foo: 'bar' } } } + + configuration = Bugsnag::Configuration.new + configuration.meta_data_filters = [/fb?/] + + cleaner = Bugsnag::Cleaner.new(configuration) + expect(cleaner.clean_object(object)).to eq({ events: { metaData: { foo: '[FILTERED]' } } }) + + configuration = Bugsnag::Configuration.new + configuration.meta_data_filters = [/fb+/] + + cleaner = Bugsnag::Cleaner.new(configuration) + expect(cleaner.clean_object(object)).to eq({ events: { metaData: { foo: 'bar' } } }) end it "filters deeply nested keys" do - params = {:foo => {:bar => "baz"}} - expect(described_class.new([/^foo\.bar/]).clean_object(params)).to eq({:foo => {:bar => '[FILTERED]'}}) + configuration = Bugsnag::Configuration.new + configuration.meta_data_filters = [/^foo\.bar/] + + cleaner = Bugsnag::Cleaner.new(configuration) + + params = { events: { metaData: { foo: { bar: 'baz' } } } } + expect(cleaner.clean_object(params)).to eq({ events: { metaData: { foo: { bar: '[FILTERED]' } } } }) end it "filters deeply nested request parameters" do - params = {:request => {:params => {:foo => {:bar => "baz"}}}} - expect(described_class.new([/^foo\.bar/]).clean_object(params)).to eq({:request => {:params => {:foo => {:bar => '[FILTERED]'}}}}) + configuration = Bugsnag::Configuration.new + configuration.meta_data_filters = [/^foo\.bar/] + + cleaner = Bugsnag::Cleaner.new(configuration) + + params = { events: { metaData: { request: { params: { foo: { bar: 'baz' } } } } } } + expect(cleaner.clean_object(params)).to eq({ events: { metaData: { request: { params: { foo: { bar: '[FILTERED]' } } } } } }) + end + + it "doesn't filter by string inclusion when the scope is not in 'scopes_to_filter'" do + object = { foo: 'bar' } + + configuration = Bugsnag::Configuration.new + configuration.meta_data_filters = ['f'] + + cleaner = Bugsnag::Cleaner.new(configuration) + + expect(cleaner.clean_object(object)).to eq({ foo: 'bar' }) + + configuration = Bugsnag::Configuration.new + configuration.meta_data_filters = ['b'] + + cleaner = Bugsnag::Cleaner.new(configuration) + + expect(cleaner.clean_object(object)).to eq({ foo: 'bar' }) + end + + it "doesn't filter by regular expression when the scope is not in 'scopes_to_filter'" do + object = { foo: 'bar' } + + configuration = Bugsnag::Configuration.new + configuration.meta_data_filters = [/fb?/] + + cleaner = Bugsnag::Cleaner.new(configuration) + + expect(cleaner.clean_object(object)).to eq({ foo: 'bar' }) + + configuration = Bugsnag::Configuration.new + configuration.meta_data_filters = [/fb+/] + + cleaner = Bugsnag::Cleaner.new(configuration) + + expect(cleaner.clean_object(object)).to eq({ foo: 'bar' }) + end + + it "doesn't filter deeply nested keys when the scope is not in 'scopes_to_filter'" do + params = { foo: { bar: 'baz' } } + + configuration = Bugsnag::Configuration.new + configuration.meta_data_filters = [/^foo\.bar/] + + cleaner = Bugsnag::Cleaner.new(configuration) + + expect(cleaner.clean_object(params)).to eq({ foo: { bar: 'baz' } }) + end + + it "doesn't filter deeply nested request parameters when the scope is not in 'scopes_to_filter'" do + params = { request: { params: { foo: { bar: 'baz' } } } } + + configuration = Bugsnag::Configuration.new + configuration.meta_data_filters = [/^foo\.bar/] + + cleaner = Bugsnag::Cleaner.new(configuration) + + expect(cleaner.clean_object(params)).to eq({ request: { params: { foo: { bar: 'baz' } } } }) end it "filters objects which can't be stringified" do @@ -187,7 +288,12 @@ def to_s describe "#clean_url" do let(:filters) { [] } - subject { described_class.new(filters).clean_url(url) } + + subject do + configuration = Bugsnag::Configuration.new + configuration.meta_data_filters = filters + described_class.new(configuration).clean_url(url) + end context "with no filters configured" do let(:url) { "/dir/page?param1=value1¶m2=value2" } diff --git a/spec/configuration_spec.rb b/spec/configuration_spec.rb index 5db5e5f23..9bc1d5345 100644 --- a/spec/configuration_spec.rb +++ b/spec/configuration_spec.rb @@ -332,10 +332,14 @@ def debug(name, &block) end end - it "should have exit exception classes ignored by default" do + it "should have exit exception classes in ignore_classes by default" do expect(subject.ignore_classes).to eq(Set.new([SystemExit, SignalException])) end + it "should have nothing in discard_classes by default" do + expect(subject.discard_classes).to eq(Set.new([])) + end + describe "#breadcrumbs" do it "first returns a new circular buffer" do buffer = subject.breadcrumbs diff --git a/spec/helper_spec.rb b/spec/helper_spec.rb index 57089afbe..11323c932 100644 --- a/spec/helper_spec.rb +++ b/spec/helper_spec.rb @@ -4,23 +4,7 @@ require 'set' describe Bugsnag::Helpers do - describe "trim_if_needed" do - - it "breaks recursion" do - a = [1, 2, 3] - b = [2, a] - a << b - value = Bugsnag::Helpers.trim_if_needed(a) - expect(value).to eq([1, 2, 3, [2, "[RECURSION]"]]) - end - - it "does not break equal objects without recursion" do - data = [1, [1, 2], [1, 2], "a"] - value = Bugsnag::Helpers.trim_if_needed(data) - expect(value).to eq data - end - it "preserves bool types" do value = Bugsnag::Helpers.trim_if_needed([1, 3, true, "NO", "2", false]) expect(value[2]).to be_a(TrueClass) @@ -39,76 +23,7 @@ expect(value[4]).to be_a(String) end - context "an object will throw if `to_s` is called" do - class StringRaiser - def to_s - raise 'Oh no you do not!' - end - end - - it "uses the string '[RAISED]' instead" do - value = Bugsnag::Helpers.trim_if_needed([1, 3, StringRaiser.new]) - expect(value[2]).to eq "[RAISED]" - end - - it "replaces hash key with '[RAISED]'" do - a = {} - a[StringRaiser.new] = 1 - - value = Bugsnag::Helpers.trim_if_needed(a) - expect(value).to eq({ "[RAISED]" => "[FILTERED]" }) - end - - it "uses a single '[RAISED]'key when multiple keys raise" do - a = {} - a[StringRaiser.new] = 1 - a[StringRaiser.new] = 2 - - value = Bugsnag::Helpers.trim_if_needed(a) - expect(value).to eq({ "[RAISED]" => "[FILTERED]" }) - end - end - - context "an object will infinitely recurse if `to_s` is called" do - is_jruby = defined?(RUBY_ENGINE) && RUBY_ENGINE == 'jruby' - - class StringRecurser - def to_s - to_s - end - end - - it "uses the string '[RECURSION]' instead" do - skip "JRuby doesn't allow recovery from SystemStackErrors" if is_jruby - - value = Bugsnag::Helpers.trim_if_needed([1, 3, StringRecurser.new]) - expect(value[2]).to eq "[RECURSION]" - end - - it "replaces hash key with '[RECURSION]'" do - skip "JRuby doesn't allow recovery from SystemStackErrors" if is_jruby - - a = {} - a[StringRecurser.new] = 1 - - value = Bugsnag::Helpers.trim_if_needed(a) - expect(value).to eq({ "[RECURSION]" => "[FILTERED]" }) - end - - it "uses a single '[RECURSION]'key when multiple keys recurse" do - skip "JRuby doesn't allow recovery from SystemStackErrors" if is_jruby - - a = {} - a[StringRecurser.new] = 1 - a[StringRecurser.new] = 2 - - value = Bugsnag::Helpers.trim_if_needed(a) - expect(value).to eq({ "[RECURSION]" => "[FILTERED]" }) - end - end - context "payload length is less than allowed" do - it "does not change strings" do value = SecureRandom.hex(4096) expect(Bugsnag::Helpers.trim_if_needed(value)).to eq value @@ -126,7 +41,6 @@ def to_s end context "payload length is greater than allowed" do - it "trims metadata strings" do payload = { :events => [{ diff --git a/spec/integrations/rack_spec.rb b/spec/integrations/rack_spec.rb index 95cc9f013..57847efa4 100644 --- a/spec/integrations/rack_spec.rb +++ b/spec/integrations/rack_spec.rb @@ -127,9 +127,10 @@ class Request expect(report).to receive(:context=).with("TEST /TEST_PATH") expect(report).to receive(:user).and_return({}) - config = double - allow(config).to receive(:send_environment).and_return(true) - allow(config).to receive(:meta_data_filters).and_return(['email']) + config = Bugsnag.configuration + config.send_environment = true + config.meta_data_filters = ['email'] + allow(report).to receive(:configuration).and_return(config) expect(report).to receive(:add_tab).once.with(:request, { :url => "http://test_host/TEST_PATH?email=[FILTERED]&another_param=thing", @@ -187,9 +188,10 @@ class Request expect(report).to receive(:context=).with("TEST /TEST_PATH") expect(report).to receive(:user).and_return({}) - config = double - allow(config).to receive(:send_environment).and_return(true) - allow(config).to receive(:meta_data_filters).and_return(nil) + config = Bugsnag.configuration + config.send_environment = true + config.meta_data_filters = [] + allow(report).to receive(:configuration).and_return(config) expect(report).to receive(:add_tab).once.with(:environment, rack_env) expect(report).to receive(:add_tab).once.with(:request, { diff --git a/spec/report_spec.rb b/spec/report_spec.rb index 3d4b8530f..91126274d 100644 --- a/spec/report_spec.rb +++ b/spec/report_spec.rb @@ -1,5 +1,5 @@ # encoding: utf-8 -require 'spec_helper' +require_relative './spec_helper' require 'securerandom' require 'ostruct' @@ -27,6 +27,7 @@ def gloops end end +# rubocop:disable Metrics/BlockLength describe Bugsnag::Report do it "should contain an api_key if one is set" do Bugsnag.notify(BugsnagTestException.new("It crashed")) @@ -149,10 +150,12 @@ def gloops original_ignore_classes = Bugsnag.configuration.ignore_classes begin - # The default ignore_classes includes SignalException, so we need to + # The default ignore classes includes SignalException, so we need to # temporarily set it to something else. Bugsnag.configuration.ignore_classes = Set[SystemExit] + Bugsnag.notify(SignalException.new("TERM")) + expect(Bugsnag).to have_sent_notification{ |payload, headers| event = get_event_from_payload(payload) expect(event["unhandled"]).to be false @@ -589,7 +592,6 @@ def gloops end it "filters params from all payload hashes if they are set in default meta_data_filters" do - Bugsnag.notify(BugsnagTestException.new("It crashed")) do |report| report.meta_data.merge!({ :request => { @@ -635,7 +637,6 @@ def gloops end it "filters params from all payload hashes if they are added to meta_data_filters" do - Bugsnag.configuration.meta_data_filters << "other_data" Bugsnag.notify(BugsnagTestException.new("It crashed")) do |report| report.meta_data.merge!({:request => {:params => {:password => "1234", :other_password => "123456", :other_data => "123456"}}}) @@ -653,7 +654,6 @@ def gloops end it "filters params from all payload hashes if they are added to meta_data_filters as regex" do - Bugsnag.configuration.meta_data_filters << /other_data/ Bugsnag.notify(BugsnagTestException.new("It crashed")) do |report| report.meta_data.merge!({:request => {:params => {:password => "1234", :other_password => "123456", :other_data => "123456"}}}) @@ -671,7 +671,6 @@ def gloops end it "filters params from all payload hashes if they are added to meta_data_filters as partial regex" do - Bugsnag.configuration.meta_data_filters << /r_data/ Bugsnag.notify(BugsnagTestException.new("It crashed")) do |report| report.meta_data.merge!({:request => {:params => {:password => "1234", :other_password => "123456", :other_data => "123456"}}}) @@ -702,6 +701,33 @@ def gloops } end + it "does not apply filters outside of report.meta_data" do + Bugsnag.configuration.meta_data_filters << "data" + + Bugsnag.notify(BugsnagTestException.new("It crashed")) do |report| + report.meta_data = { + xyz: "abc", + data: "123456" + } + + report.user = { + id: 123, + data: "hello" + } + end + + expect(Bugsnag).to have_sent_notification{ |payload, headers| + event = get_event_from_payload(payload) + + expect(event["metaData"]).not_to be_nil + expect(event["metaData"]["xyz"]).to eq("abc") + expect(event["metaData"]["data"]).to eq("[FILTERED]") + + expect(event["user"]).not_to be_nil + expect(event["user"]["data"]).to eq("hello") + } + end + it "does not notify if report ignored" do Bugsnag.notify(BugsnagTestException.new("It crashed")) do |report| report.ignore! @@ -710,38 +736,154 @@ def gloops expect(Bugsnag).not_to have_sent_notification end - it "does not notify if the exception class is in the default ignore_classes list" do - Bugsnag.configuration.ignore_classes << ActiveRecord::RecordNotFound - Bugsnag.notify(ActiveRecord::RecordNotFound.new("It crashed")) + context "ignore_classes" do + context "as a constant" do + it "ignores exception when its class is ignored" do + Bugsnag.configuration.ignore_classes << BugsnagTestException - expect(Bugsnag).not_to have_sent_notification - end + Bugsnag.notify(BugsnagTestException.new("It crashed")) - it "does not notify if the non-default exception class is added to the ignore_classes" do - Bugsnag.configuration.ignore_classes << BugsnagTestException + expect(Bugsnag).not_to have_sent_notification + end - Bugsnag.notify(BugsnagTestException.new("It crashed")) + it "ignores exception when its ancestor is ignored" do + Bugsnag.configuration.ignore_classes << BugsnagTestException - expect(Bugsnag).not_to have_sent_notification - end + Bugsnag.notify(BugsnagSubclassTestException.new("It crashed")) - it "does not notify if exception's ancestor is an ignored class" do - Bugsnag.configuration.ignore_classes << BugsnagTestException + expect(Bugsnag).not_to have_sent_notification + end - Bugsnag.notify(BugsnagSubclassTestException.new("It crashed")) + it "ignores exception when the original exception is ignored" do + Bugsnag.configuration.ignore_classes << BugsnagTestException - expect(Bugsnag).not_to have_sent_notification + ex = NestedException.new("Self-referential exception") + ex.original_exception = BugsnagTestException.new("It crashed") + + Bugsnag.notify(ex) + + expect(Bugsnag).not_to have_sent_notification + end + end + + context "as a proc" do + it "ignores exception when the proc returns true" do + Bugsnag.configuration.ignore_classes << ->(exception) { true } + + Bugsnag.notify(BugsnagTestException.new("It crashed")) + + expect(Bugsnag).not_to have_sent_notification + end + + it "does not ignore exception when proc returns false" do + Bugsnag.configuration.ignore_classes << ->(exception) { false } + + Bugsnag.notify(BugsnagTestException.new("It crashed")) + + expect(Bugsnag).to have_sent_notification { |payload, headers| + exception = get_exception_from_payload(payload) + + expect(exception["errorClass"]).to eq("BugsnagTestException") + expect(exception["message"]).to eq("It crashed") + } + end + end end - it "does not notify if any caused exception is an ignored class" do - Bugsnag.configuration.ignore_classes << NestedException + context "discard_classes" do + context "as a string" do + it "discards exception when its class should be discarded" do + Bugsnag.configuration.discard_classes << "BugsnagTestException" - ex = NestedException.new("Self-referential exception") - ex.original_exception = BugsnagTestException.new("It crashed") + Bugsnag.notify(BugsnagTestException.new("It crashed")) - Bugsnag.notify(ex) + expect(Bugsnag).not_to have_sent_notification + end - expect(Bugsnag).not_to have_sent_notification + it "discards exception when the original exception should be discarded" do + Bugsnag.configuration.discard_classes << "BugsnagTestException" + + ex = NestedException.new("Self-referential exception") + ex.original_exception = BugsnagTestException.new("It crashed") + + Bugsnag.notify(ex) + + expect(Bugsnag).not_to have_sent_notification + end + + it "does not discard exception with a typo" do + Bugsnag.configuration.discard_classes << "BugsnagToastException" + + Bugsnag.notify(BugsnagTestException.new("It crashed")) + + expect(Bugsnag).to have_sent_notification { |payload, headers| + exception = get_exception_from_payload(payload) + + expect(exception["errorClass"]).to eq("BugsnagTestException") + expect(exception["message"]).to eq("It crashed") + } + end + + it "does not discard exception when its ancestor is discarded" do + Bugsnag.configuration.discard_classes << "BugsnagTestException" + + Bugsnag.notify(BugsnagSubclassTestException.new("It crashed")) + + expect(Bugsnag).to have_sent_notification { |payload, headers| + exception = get_exception_from_payload(payload) + + expect(exception["errorClass"]).to eq("BugsnagSubclassTestException") + expect(exception["message"]).to eq("It crashed") + } + end + end + + context "as a regexp" do + it "discards exception when its class should be discarded" do + Bugsnag.configuration.discard_classes << /^BugsnagTest.*/ + + Bugsnag.notify(BugsnagTestException.new("It crashed")) + + expect(Bugsnag).not_to have_sent_notification + end + + it "discards exception when the original exception should be discarded" do + Bugsnag.configuration.discard_classes << /^BugsnagTest.*/ + + ex = NestedException.new("Self-referential exception") + ex.original_exception = BugsnagTestException.new("It crashed") + + Bugsnag.notify(ex) + + expect(Bugsnag).not_to have_sent_notification + end + + it "does not discard exception when regexp does not match" do + Bugsnag.configuration.discard_classes << /^NotBugsnag.*/ + + Bugsnag.notify(BugsnagTestException.new("It crashed")) + + expect(Bugsnag).to have_sent_notification { |payload, headers| + exception = get_exception_from_payload(payload) + + expect(exception["errorClass"]).to eq("BugsnagTestException") + expect(exception["message"]).to eq("It crashed") + } + end + + it "does not discard exception when its ancestor is discarded" do + Bugsnag.configuration.discard_classes << /^BugsnagTest.*/ + + Bugsnag.notify(BugsnagSubclassTestException.new("It crashed")) + + expect(Bugsnag).to have_sent_notification { |payload, headers| + exception = get_exception_from_payload(payload) + + expect(exception["errorClass"]).to eq("BugsnagSubclassTestException") + expect(exception["message"]).to eq("It crashed") + } + end + end end it "sends the cause of the exception" do @@ -989,6 +1131,161 @@ def gloops } end + it "should handle recursive metadata" do + a = [1, 2, 3] + b = [2, a] + a << b + c = [1, 2, 3] + + Bugsnag.notify(BugsnagTestException.new("It crashed")) do |report| + report.add_tab(:some_tab, { + a: a, + b: b, + c: c + }) + end + + expect(Bugsnag).to have_sent_notification{ |payload, headers| + event = get_event_from_payload(payload) + expect(event["metaData"]["some_tab"]).to eq({ + "a" => [1, 2, 3, [2, "[RECURSION]"]], + "b" => [2, "[RECURSION]"], + "c" => [1, 2, 3] + }) + } + end + + it "does not detect two equal objects as recursion" do + Bugsnag.notify(BugsnagTestException.new("It crashed")) do |report| + report.add_tab(:some_tab, { + data: [1, [1, 2], [1, 2], "a"] + }) + end + + expect(Bugsnag).to have_sent_notification{ |payload, headers| + event = get_event_from_payload(payload) + expect(event["metaData"]["some_tab"]).to eq({ + "data" => [1, [1, 2], [1, 2], "a"] + }) + } + end + + context "an object that throws if `to_s` is called" do + class StringRaiser + def to_s + raise 'Oh no you do not!' + end + end + + it "uses the string '[RAISED]' instead" do + Bugsnag.notify(BugsnagTestException.new("It crashed")) do |report| + report.add_tab(:some_tab, { + data: [1, 2, StringRaiser.new] + }) + end + + expect(Bugsnag).to have_sent_notification{ |payload, headers| + event = get_event_from_payload(payload) + expect(event["metaData"]["some_tab"]).to eq({ + "data" => [1, 2, "[RAISED]"] + }) + } + end + + it "replaces hash key with '[RAISED]'" do + Bugsnag.notify(BugsnagTestException.new("It crashed")) do |report| + report.add_tab(:some_tab, { + StringRaiser.new => 1 + }) + end + + expect(Bugsnag).to have_sent_notification{ |payload, headers| + event = get_event_from_payload(payload) + expect(event["metaData"]["some_tab"]).to eq({ + "[RAISED]" => "[FILTERED]" + }) + } + end + + it "uses a single '[RAISED]'key when multiple keys raise" do + Bugsnag.notify(BugsnagTestException.new("It crashed")) do |report| + report.add_tab(:some_tab, { + StringRaiser.new => 1, + StringRaiser.new => 2 + }) + end + + expect(Bugsnag).to have_sent_notification{ |payload, headers| + event = get_event_from_payload(payload) + expect(event["metaData"]["some_tab"]).to eq({ + "[RAISED]" => "[FILTERED]" + }) + } + end + end + + context "an object that infinitely recurse if `to_s` is called" do + is_jruby = defined?(RUBY_ENGINE) && RUBY_ENGINE == 'jruby' + + class StringRecurser + def to_s + to_s + end + end + + it "uses the string '[RECURSION]' instead" do + skip "JRuby doesn't allow recovery from SystemStackErrors" if is_jruby + + Bugsnag.notify(BugsnagTestException.new("It crashed")) do |report| + report.add_tab(:some_tab, { + data: [1, 2, StringRecurser.new] + }) + end + + expect(Bugsnag).to have_sent_notification{ |payload, headers| + event = get_event_from_payload(payload) + expect(event["metaData"]["some_tab"]).to eq({ + "data" => [1, 2, "[RECURSION]"] + }) + } + end + + it "replaces hash key with '[RECURSION]'" do + skip "JRuby doesn't allow recovery from SystemStackErrors" if is_jruby + + Bugsnag.notify(BugsnagTestException.new("It crashed")) do |report| + report.add_tab(:some_tab, { + StringRecurser.new => 1 + }) + end + + expect(Bugsnag).to have_sent_notification{ |payload, headers| + event = get_event_from_payload(payload) + expect(event["metaData"]["some_tab"]).to eq({ + "[RECURSION]" => "[FILTERED]" + }) + } + end + + it "uses a single '[RECURSION]'key when multiple keys recurse" do + skip "JRuby doesn't allow recovery from SystemStackErrors" if is_jruby + + Bugsnag.notify(BugsnagTestException.new("It crashed")) do |report| + report.add_tab(:some_tab, { + StringRecurser.new => 1, + StringRecurser.new => 2 + }) + end + + expect(Bugsnag).to have_sent_notification{ |payload, headers| + event = get_event_from_payload(payload) + expect(event["metaData"]["some_tab"]).to eq({ + "[RECURSION]" => "[FILTERED]" + }) + } + end + end + it 'should handle exceptions with empty backtrace' do begin err = RuntimeError.new @@ -1280,3 +1577,4 @@ def gloops } end end +# rubocop:enable Metrics/BlockLength diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 6584fd1ea..b172d183b 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -10,6 +10,7 @@ require 'bugsnag' +require 'tmpdir' require 'webmock/rspec' require 'rspec/expectations' require 'rspec/mocks' @@ -43,12 +44,16 @@ def ruby_version_greater_equal?(version) RSpec.configure do |config| config.order = "random" + config.example_status_persistence_file_path = "#{Dir.tmpdir}/rspec_status" config.before(:each) do WebMock.stub_request(:post, "https://notify.bugsnag.com/") WebMock.stub_request(:post, "https://sessions.bugsnag.com/") Bugsnag.instance_variable_set(:@configuration, Bugsnag::Configuration.new) + Bugsnag.instance_variable_set(:@session_tracker, Bugsnag::SessionTracker.new) + Bugsnag.instance_variable_set(:@cleaner, Bugsnag::Cleaner.new(Bugsnag.configuration)) + Bugsnag.configure do |bugsnag| bugsnag.api_key = "c9d60ae4c7e70c4b6c4ebd3e8056d2b8" bugsnag.release_stage = "production" @@ -83,4 +88,4 @@ def have_sent_notification(&matcher) raise "no matcher provided to have_sent_notification (did you use { })" end end -end \ No newline at end of file +end diff --git a/spec/stacktrace_spec.rb b/spec/stacktrace_spec.rb index f17b2dff3..909d4e025 100644 --- a/spec/stacktrace_spec.rb +++ b/spec/stacktrace_spec.rb @@ -1,91 +1,159 @@ require 'spec_helper' describe Bugsnag::Stacktrace do - it "includes code in the stack trace" do - begin - _a = 1 - _b = 2 - _c = 3 - "Test".prepnd "T" - _d = 4 - _e = 5 - _f = 6 - rescue Exception => e - Bugsnag.notify(e) + context "sending code" do + it "includes code in the stack trace" do + begin + _a = 1 + _b = 2 + _c = 3 + "Test".prepnd "T" + _d = 4 + _e = 5 + _f = 6 + rescue Exception => e + Bugsnag.notify(e) + end + + expect(Bugsnag).to have_sent_notification{ |payload, headers| + exception = get_exception_from_payload(payload) + starting_line = __LINE__ - 13 + expect(exception["stacktrace"][0]["code"]).to eq({ + (starting_line + 0).to_s => ' _a = 1', + (starting_line + 1).to_s => ' _b = 2', + (starting_line + 2).to_s => ' _c = 3', + (starting_line + 3).to_s => ' "Test".prepnd "T"', + (starting_line + 4).to_s => ' _d = 4', + (starting_line + 5).to_s => ' _e = 5', + (starting_line + 6).to_s => ' _f = 6' + }) + } end - expect(Bugsnag).to have_sent_notification{ |payload, headers| - exception = get_exception_from_payload(payload) - starting_line = __LINE__ - 13 - expect(exception["stacktrace"][0]["code"]).to eq({ - (starting_line + 0).to_s => ' _a = 1', - (starting_line + 1).to_s => ' _b = 2', - (starting_line + 2).to_s => ' _c = 3', - (starting_line + 3).to_s => ' "Test".prepnd "T"', - (starting_line + 4).to_s => ' _d = 4', - (starting_line + 5).to_s => ' _e = 5', - (starting_line + 6).to_s => ' _f = 6' + it "allows you to disable sending code" do + Bugsnag.configuration.send_code = false + + notify_test_exception + + expect(Bugsnag).to have_sent_notification{ |payload, headers| + exception = get_exception_from_payload(payload) + expect(exception["stacktrace"][1]["code"]).to eq(nil) + } + end + + it 'should send the first 7 lines of the file for exceptions near the top' do + load 'spec/fixtures/crashes/start_of_file.rb' rescue Bugsnag.notify $! + + expect(Bugsnag).to have_sent_notification{ |payload, headers| + exception = get_exception_from_payload(payload) + + expect(exception["stacktrace"][0]["code"]).to eq({ + "1" => "#", + "2" => "raise 'hell'", + "3" => "#", + "4" => "#", + "5" => "#", + "6" => "#", + "7" => "#" }) - } - end + } + end - it "allows you to disable sending code" do - Bugsnag.configuration.send_code = false + it 'should send the last 7 lines of the file for exceptions near the bottom' do + load 'spec/fixtures/crashes/end_of_file.rb' rescue Bugsnag.notify $! - notify_test_exception + expect(Bugsnag).to have_sent_notification{ |payload, headers| + exception = get_exception_from_payload(payload) - expect(Bugsnag).to have_sent_notification{ |payload, headers| - exception = get_exception_from_payload(payload) - expect(exception["stacktrace"][1]["code"]).to eq(nil) - } - end + expect(exception["stacktrace"][0]["code"]).to eq({ + "3" => "#", + "4" => "#", + "5" => "#", + "6" => "#", + "7" => "#", + "8" => "raise 'hell'", + "9" => "#" + }) + } + end - it 'should send the first 7 lines of the file for exceptions near the top' do - load 'spec/fixtures/crashes/start_of_file.rb' rescue Bugsnag.notify $! - - expect(Bugsnag).to have_sent_notification{ |payload, headers| - exception = get_exception_from_payload(payload) - - expect(exception["stacktrace"][0]["code"]).to eq({ - "1" => "#", - "2" => "raise 'hell'", - "3" => "#", - "4" => "#", - "5" => "#", - "6" => "#", - "7" => "#" - }) - } - end + it 'should send the last 7 lines of the file for exceptions near the bottom' do + load 'spec/fixtures/crashes/short_file.rb' rescue Bugsnag.notify $! + + expect(Bugsnag).to have_sent_notification{ |payload, headers| + exception = get_exception_from_payload(payload) - it 'should send the last 7 lines of the file for exceptions near the bottom' do - load 'spec/fixtures/crashes/end_of_file.rb' rescue Bugsnag.notify $! - - expect(Bugsnag).to have_sent_notification{ |payload, headers| - exception = get_exception_from_payload(payload) - - expect(exception["stacktrace"][0]["code"]).to eq({ - "3" => "#", - "4" => "#", - "5" => "#", - "6" => "#", - "7" => "#", - "8" => "raise 'hell'", - "9" => "#" - }) - } + expect(exception["stacktrace"][0]["code"]).to eq({ + "1" => "raise 'hell'" + }) + } + end end - it 'should send the last 7 lines of the file for exceptions near the bottom' do - load 'spec/fixtures/crashes/short_file.rb' rescue Bugsnag.notify $! + context "file paths" do + it "leaves absolute paths alone" do + configuration = Bugsnag::Configuration.new + configuration.send_code = false + + backtrace = [ + "/foo/bar/app/models/user.rb:1:in `something'", + "/foo/bar/other_vendor/lib/dont.rb:2:in `to_s'", + "/foo/bar/vendor/lib/ignore_me.rb:3:in `to_s'", + "/foo/bar/.bundle/lib/ignore_me.rb:4:in `to_s'", + ] + + stacktrace = Bugsnag::Stacktrace.new(backtrace, configuration).to_a + + expect(stacktrace).to eq([ + { file: "/foo/bar/app/models/user.rb", lineNumber: 1, method: "something" }, + { file: "/foo/bar/other_vendor/lib/dont.rb", lineNumber: 2, method: "to_s" }, + { file: "/foo/bar/vendor/lib/ignore_me.rb", lineNumber: 3, method: "to_s" }, + { file: "/foo/bar/.bundle/lib/ignore_me.rb", lineNumber: 4, method: "to_s" }, + ]) + end + + it "does not modify relative paths if they can't be resolved" do + configuration = Bugsnag::Configuration.new + + backtrace = [ + "./foo/bar/baz.rb:1:in `something'", + "../foo.rb:1:in `to_s'", + "../xyz.rb:1:in `to_s'", + "abc.rb:1:in `defg'", + ] - expect(Bugsnag).to have_sent_notification{ |payload, headers| - exception = get_exception_from_payload(payload) + stacktrace = Bugsnag::Stacktrace.new(backtrace, configuration).to_a - expect(exception["stacktrace"][0]["code"]).to eq({ - "1" => "raise 'hell'" - }) - } + expect(stacktrace).to eq([ + { code: nil, file: "./foo/bar/baz.rb", lineNumber: 1, method: "something" }, + { code: nil, file: "../foo.rb", lineNumber: 1, method: "to_s" }, + { code: nil, file: "../xyz.rb", lineNumber: 1, method: "to_s" }, + { code: nil, file: "abc.rb", lineNumber: 1, method: "defg" }, + ]) + end + + it "resolves relative paths when the files exist" do + configuration = Bugsnag::Configuration.new + configuration.send_code = false + + dir = File.dirname(__FILE__) + + backtrace = [ + "./spec/spec_helper.rb:1:in `something'", + "./lib/bugsnag/breadcrumbs/../configuration.rb:100:in `to_s'", + "lib/bugsnag.rb:20:in `notify'", + "#{dir}/../spec/stacktrace_spec.rb:5:in `something_else'", + ] + + stacktrace = Bugsnag::Stacktrace.new(backtrace, configuration).to_a + + expect(stacktrace).to eq([ + { file: "#{dir}/spec_helper.rb", lineNumber: 1, method: "something" }, + { file: "#{File.dirname(dir)}/lib/bugsnag/configuration.rb", lineNumber: 100, method: "to_s" }, + { file: "#{File.dirname(dir)}/lib/bugsnag.rb", lineNumber: 20, method: "notify" }, + { file: "#{dir}/stacktrace_spec.rb", lineNumber: 5, method: "something_else" }, + ]) + end end context "with configurable vendor_path" do