A platform for community discussion. Free, open, simple.
FEATURE: Track automation errors and improve logging (#36938)
Régis Hanol6a79b59ac880
diff --git a/plugins/automation/admin/assets/javascripts/admin/components/automation-list.gjs b/plugins/automation/admin/assets/javascripts/admin/components/automation-list.gjsindex f06d8b0977e..d39341536a0 100644--- a/plugins/automation/admin/assets/javascripts/admin/components/automation-list.gjs+++ b/plugins/automation/admin/assets/javascripts/admin/components/automation-list.gjs@@ -11,6 +11,7 @@ import avatar from "discourse/helpers/avatar";import formatDate from "discourse/helpers/format-date";import { popupAjaxError } from "discourse/lib/ajax-error";import { removeValueFromArray } from "discourse/lib/array-tools";+import getURL from "discourse/lib/get-url";import { escapeExpression } from "discourse/lib/utilities";import { or } from "discourse/truth-helpers";import { i18n } from "discourse-i18n";@@ -78,6 +79,10 @@ export default class AutomationList extends Component {});}+ get logsUrl() {+ return getURL("/logs?search=discourse-automation");+ }+<template><section class="discourse-automations-table"><DPageSubheader @titleLabel={{i18n "discourse_automation.table_title"}}>@@ -181,6 +186,18 @@ export default class AutomationList extends Component {<span class="automations__stats">{{this.statsText automation.stats}}</span>+ {{#if automation.stats.last_day.total_errors}}+ <a+ href={{this.logsUrl}}+ class="automations__errors"+ data-auto-route="true"+ >+ {{i18n+ "discourse_automation.models.automation.recent_errors"+ count=automation.stats.last_day.total_errors+ }}+ </a>+ {{/if}}</td><td class="d-admin-row__detail automations__last-run"><div class="d-admin-row__mobile-label">diff --git a/plugins/automation/app/jobs/regular/discourse_automation/call_zapier_webhook.rb b/plugins/automation/app/jobs/regular/discourse_automation/call_zapier_webhook.rbindex 27d5629960a..2efc048a93f 100644--- a/plugins/automation/app/jobs/regular/discourse_automation/call_zapier_webhook.rb+++ b/plugins/automation/app/jobs/regular/discourse_automation/call_zapier_webhook.rb@@ -17,7 +17,7 @@ module Jobs)if result.status != 200- Rails.logger.warn(+ ::DiscourseAutomation::Logger.warn("Failed to call Zapier webhook at #{args["webhook_url"]} Status: #{result.status}: #{result.status_line}",)enddiff --git a/plugins/automation/app/jobs/scheduled/discourse_automation/tracker.rb b/plugins/automation/app/jobs/scheduled/discourse_automation/tracker.rbindex 031d6c7c06d..902e60adc70 100644--- a/plugins/automation/app/jobs/scheduled/discourse_automation/tracker.rb+++ b/plugins/automation/app/jobs/scheduled/discourse_automation/tracker.rb@@ -17,8 +17,8 @@ module Jobs.find_each do |pending_automation|run_pending_automation(pending_automation)rescue => e- Rails.logger.error(- "Error running automation #{pending_automation.automation.name}: #{e}",+ ::DiscourseAutomation::Logger.error(+ "Error running automation '#{pending_automation.automation.name}': #{e.message}",)end@@ -26,11 +26,7 @@ module Jobs.includes(:automation).limit(BATCH_LIMIT).where("execute_at < ?", Time.now)- .find_each do |pending_pm|- send_pending_pm(pending_pm)- rescue => e- Rails.logger.error("Error sending PM for #{pending_pm.automation.name}: #{e}")- end+ .find_each { |pending_pm| send_pending_pm(pending_pm) }enddef send_pending_pm(pending_pm)@@ -47,6 +43,15 @@ module Jobspending_pm.destroy!end+ rescue ActiveRecord::RecordNotSaved => e+ ::DiscourseAutomation::Logger.error(+ "Failed to send pending PM '#{pending_pm.title}': #{e.message}",+ )+ pending_pm.destroy!+ rescue => e+ ::DiscourseAutomation::Logger.error(+ "Error sending pending PM '#{pending_pm.title}': #{e.message}",+ )enddef run_pending_automation(pending_automation)diff --git a/plugins/automation/app/models/discourse_automation/stat.rb b/plugins/automation/app/models/discourse_automation/stat.rbindex 8f81bc8dea3..d513d5118ea 100644--- a/plugins/automation/app/models/discourse_automation/stat.rb+++ b/plugins/automation/app/models/discourse_automation/stat.rb@@ -5,6 +5,7 @@ module DiscourseAutomationself.table_name = "discourse_automation_stats"def self.log(automation_id, run_time = nil)+ errored = falseif block_given? && run_time.nil?start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)begin@@ -13,11 +14,12 @@ module DiscourseAutomationresultrescue => erun_time = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time+ errored = trueraise eendendensure- update_stats(automation_id, run_time || 0)+ update_stats(automation_id, run_time || 0, errored:)enddef self.fetch_period_summaries@@ -47,6 +49,7 @@ module DiscourseAutomationautomation_id,SUM(total_runs) AS total_runs,SUM(total_time) AS total_time,+ SUM(total_errors) AS total_errors,CASE WHEN SUM(total_runs) > 0THEN SUM(total_time) / SUM(total_runs)ELSE 0@@ -76,6 +79,7 @@ module DiscourseAutomationresult[automation_id][period_name] = {total_runs: stat.total_runs,total_time: stat.total_time,+ total_errors: stat.total_errors,average_run_time: stat.average_run_time,min_run_time: stat.min_run_time,max_run_time: stat.max_run_time,@@ -86,29 +90,26 @@ module DiscourseAutomationresultend- def self.update_stats(automation_id, run_time)+ def self.update_stats(automation_id, run_time, errored: false)today = Date.currentcurrent_time = Time.now+ error_increment = errored ? 1 : 0builder = DB.build <<~SQLINSERT INTO discourse_automation_stats- (automation_id, date, last_run_at, total_time, average_run_time, min_run_time, max_run_time, total_runs)- VALUES (:automation_id, :date, :current_time, :run_time, :run_time, :run_time, :run_time, 1)+ (automation_id, date, last_run_at, total_time, average_run_time, min_run_time, max_run_time, total_runs, total_errors)+ VALUES (:automation_id, :date, :current_time, :run_time, :run_time, :run_time, :run_time, 1, :error_increment)ON CONFLICT (automation_id, date) DO UPDATE SETlast_run_at = :current_time,total_time = discourse_automation_stats.total_time + :run_time,total_runs = discourse_automation_stats.total_runs + 1,+ total_errors = discourse_automation_stats.total_errors + :error_increment,average_run_time = (discourse_automation_stats.total_time + :run_time) / (discourse_automation_stats.total_runs + 1),min_run_time = LEAST(discourse_automation_stats.min_run_time, :run_time),max_run_time = GREATEST(discourse_automation_stats.max_run_time, :run_time)SQL- builder.exec(- automation_id: automation_id,- date: today,- current_time: current_time,- run_time: run_time,- )+ builder.exec(automation_id:, date: today, current_time:, run_time:, error_increment:)endendend@@ -118,14 +119,15 @@ end# Table name: discourse_automation_stats## id :bigint not null, primary key-# automation_id :bigint not null+# average_run_time :float not null# date :date not null# last_run_at :datetime not null-# total_time :float not null-# average_run_time :float not null-# min_run_time :float not null# max_run_time :float not null+# min_run_time :float not null+# total_errors :integer default(0), not null# total_runs :integer not null+# total_time :float not null+# automation_id :bigint not null## Indexes#diff --git a/plugins/automation/app/serializers/discourse_automation/automation_serializer.rb b/plugins/automation/app/serializers/discourse_automation/automation_serializer.rbindex 1953b66ffee..16597d7ecd9 100644--- a/plugins/automation/app/serializers/discourse_automation/automation_serializer.rb+++ b/plugins/automation/app/serializers/discourse_automation/automation_serializer.rb@@ -89,6 +89,7 @@ module DiscourseAutomationEMPTY_STATS = {total_runs: 0,total_time: 0,+ total_errors: 0,average_run_time: 0,min_run_time: 0,max_run_time: 0,diff --git a/plugins/automation/assets/stylesheets/common/discourse-automation.scss b/plugins/automation/assets/stylesheets/common/discourse-automation.scssindex 3493176f88d..bee9b7d1138 100644--- a/plugins/automation/assets/stylesheets/common/discourse-automation.scss+++ b/plugins/automation/assets/stylesheets/common/discourse-automation.scss@@ -10,6 +10,12 @@font-size: var(--font-down-1);}+ &__errors {+ display: block;+ font-size: var(--font-down-1);+ color: var(--danger);+ }+td[role="button"] {cursor: pointer;}diff --git a/plugins/automation/config/locales/client.en.yml b/plugins/automation/config/locales/client.en.ymlindex 42c283829ee..f9b9cf95b47 100644--- a/plugins/automation/config/locales/client.en.yml+++ b/plugins/automation/config/locales/client.en.yml@@ -452,6 +452,9 @@ en:runs_today: "%{count} today"runs_this_week: "%{count} this week"runs_this_month: "%{count} this month"+ recent_errors:+ one: "%{count} error recently"+ other: "%{count} errors recently"runs:label: Runsname:diff --git a/plugins/automation/db/migrate/20260119164737_add_total_errors_to_automation_stats.rb b/plugins/automation/db/migrate/20260119164737_add_total_errors_to_automation_stats.rbnew file mode 100644index 00000000000..4a1e5de915d--- /dev/null+++ b/plugins/automation/db/migrate/20260119164737_add_total_errors_to_automation_stats.rb@@ -0,0 +1,7 @@+# frozen_string_literal: true++class AddTotalErrorsToAutomationStats < ActiveRecord::Migration[8.0]+ def change+ add_column :discourse_automation_stats, :total_errors, :integer, default: 0, null: false+ end+enddiff --git a/plugins/automation/lib/discourse_automation/logger.rb b/plugins/automation/lib/discourse_automation/logger.rbnew file mode 100644index 00000000000..1f4404d208f--- /dev/null+++ b/plugins/automation/lib/discourse_automation/logger.rb@@ -0,0 +1,19 @@+# frozen_string_literal: true++module DiscourseAutomation+ module Logger+ PREFIX = "[discourse-automation]"++ def self.warn(message)+ Rails.logger.warn("#{PREFIX} #{message}")+ end++ def self.error(message)+ Rails.logger.error("#{PREFIX} #{message}")+ end++ def self.info(message)+ Rails.logger.info("#{PREFIX} #{message}")+ end+ end+enddiff --git a/plugins/automation/lib/discourse_automation/scriptable.rb b/plugins/automation/lib/discourse_automation/scriptable.rbindex 4eaff6c9865..281ee6c7136 100644--- a/plugins/automation/lib/discourse_automation/scriptable.rb+++ b/plugins/automation/lib/discourse_automation/scriptable.rb@@ -261,7 +261,9 @@ module DiscourseAutomationelsesender = User.find_by(username: sender)if !sender- Rails.logger.warn "[discourse-automation] Did not send PM #{pm[:title]} - sender does not exist: `#{sender}`"+ DiscourseAutomation::Logger.warn(+ "Did not send PM #{pm[:title]} - sender does not exist: `#{sender}`",+ )returnend@@ -300,7 +302,6 @@ module DiscourseAutomationendend- post_created = falsepm = pm.merge(archetype: Archetype.private_message)pm[:target_usernames] = pm[:target_usernames].join(",")pm[:target_group_names] = pm[:target_group_names].join(",")@@ -308,14 +309,26 @@ module DiscourseAutomationif pm[:target_usernames].blank? && pm[:target_group_names].blank? &&pm[:target_emails].blank?- Rails.logger.warn "[discourse-automation] Did not send PM #{pm[:title]} - no valid targets exist"+ DiscourseAutomation::Logger.warn(+ "Did not send PM #{pm[:title]} - no valid targets exist",+ )returnelsif non_existing_targets.any?- Rails.logger.warn "[discourse-automation] Did not send PM #{pm[:title]} to all users - some do not exist: `#{non_existing_targets.join(",")}`"+ DiscourseAutomation::Logger.warn(+ "Did not send PM #{pm[:title]} to all users - some do not exist: `#{non_existing_targets.join(",")}`",+ )endpm[:acting_user] = Discourse.system_user- PostCreator.new(sender, pm).create!+ creator = PostCreator.new(sender, pm)+ post = creator.create+ if post.blank? || creator.errors.present?+ error_message = creator.errors.full_messages.join(", ")+ DiscourseAutomation::Logger.error(+ "Failed to send PM '#{pm[:title]}' - #{error_message}",+ )+ raise ActiveRecord::RecordNotSaved.new(error_message)+ endendendenddiff --git a/plugins/automation/lib/discourse_automation/scripts/auto_responder.rb b/plugins/automation/lib/discourse_automation/scripts/auto_responder.rbindex 538f682cffa..2217c9586ab 100644--- a/plugins/automation/lib/discourse_automation/scripts/auto_responder.rb+++ b/plugins/automation/lib/discourse_automation/scripts/auto_responder.rb@@ -72,12 +72,19 @@ DiscourseAutomation::Scriptable.add(DiscourseAutomation::Scripts::AUTO_RESPONDERautomation.add_id_to_custom_field(post.topic, key)- PostCreator.create!(- answering_user,- topic_id: post.topic.id,- reply_to_post_number: post.post_number,- raw: answers,- skip_validations: true,- )+ creator =+ PostCreator.new(+ answering_user,+ topic_id: post.topic.id,+ reply_to_post_number: post.post_number,+ raw: answers,+ skip_validations: true,+ )+ result = creator.create+ if result.blank? || creator.errors.present?+ DiscourseAutomation::Logger.error(+ "Failed to create auto-response in topic #{post.topic.id}: #{creator.errors.full_messages.join(", ")}",+ )+ endendenddiff --git a/plugins/automation/lib/discourse_automation/scripts/gift_exchange.rb b/plugins/automation/lib/discourse_automation/scripts/gift_exchange.rbindex 32c86c3fb57..46c34dc42e0 100644--- a/plugins/automation/lib/discourse_automation/scripts/gift_exchange.rb+++ b/plugins/automation/lib/discourse_automation/scripts/gift_exchange.rb@@ -17,20 +17,22 @@ DiscourseAutomation::Scriptable.add(DiscourseAutomation::Scripts::GIFT_EXCHANGE)group_id = fields.dig("gift_exchangers_group", "value")unless group = Group.find_by(id: group_id)- Rails.logger.warn "[discourse-automation] Couldn’t find group with id #{group_id}"+ DiscourseAutomation::Logger.warn("Couldn't find group with id #{group_id}")nextendcf_name = "#{group.name}-gifts-were-exchanged-#{automation.id}-#{version}-#{now.year}"if group.custom_fields[cf_name].present?- Rails.logger.warn "[discourse-automation] Gift exchange script has already been run on #{cf_name} this year #{now.year} for this script version #{version}"+ DiscourseAutomation::Logger.warn(+ "Gift exchange script has already been run on #{cf_name} this year #{now.year} for this script version #{version}",+ )nextendusernames = group.users.pluck(:username)if usernames.size < 3- Rails.logger.warn "[discourse-automation] Gift exchange needs at least 3 users in a group"+ DiscourseAutomation::Logger.warn("Gift exchange needs at least 3 users in a group")nextend@@ -45,12 +47,12 @@ DiscourseAutomation::Scriptable.add(DiscourseAutomation::Scripts::GIFT_EXCHANGE)Array(fields.dig("giftee_assignment_messages", "value")).each do |giftee_assignment_message|if giftee_assignment_message["title"].blank?- Rails.logger.warn "[discourse-automation] Gift exchange requires a title for the PM"+ DiscourseAutomation::Logger.warn("Gift exchange requires a title for the PM")nextendif giftee_assignment_message["raw"].blank?- Rails.logger.warn "[discourse-automation] Gift exchange requires a raw for the PM"+ DiscourseAutomation::Logger.warn("Gift exchange requires a raw for the PM")nextenddiff --git a/plugins/automation/lib/discourse_automation/scripts/group_category_notification_default.rb b/plugins/automation/lib/discourse_automation/scripts/group_category_notification_default.rbindex 1424b2e2fc2..cae81397b2e 100644--- a/plugins/automation/lib/discourse_automation/scripts/group_category_notification_default.rb+++ b/plugins/automation/lib/discourse_automation/scripts/group_category_notification_default.rb@@ -17,7 +17,7 @@ DiscourseAutomation::Scriptable.add(notification_level = fields.dig("notification_level", "value")unless group = Group.find_by(id: group_id)- Rails.logger.warn "[discourse-automation] Couldn’t find group with id #{group_id}"+ DiscourseAutomation::Logger.warn("Couldn't find group with id #{group_id}")nextenddiff --git a/plugins/automation/lib/discourse_automation/scripts/post.rb b/plugins/automation/lib/discourse_automation/scripts/post.rbindex cd25e47ef96..5bab6e7ccd6 100644--- a/plugins/automation/lib/discourse_automation/scripts/post.rb+++ b/plugins/automation/lib/discourse_automation/scripts/post.rb@@ -29,8 +29,13 @@ DiscourseAutomation::Scriptable.add(DiscourseAutomation::Scripts::POST) docreator = User.find_by(username: creator_username)topic = Topic.find_by(id: topic_id)- if !topic || topic.closed? || topic.archived?- Rails.logger.warn "[discourse-automation] topic with id: `#{topic_id}` was not found"+ if !topic+ DiscourseAutomation::Logger.warn("topic with id: `#{topic_id}` was not found")+ next+ end++ if topic.closed? || topic.archived?+ DiscourseAutomation::Logger.warn("topic with id: `#{topic_id}` is closed or archived")nextend@@ -53,11 +58,18 @@ DiscourseAutomation::Scriptable.add(DiscourseAutomation::Scripts::POST) dopost_raw = utils.apply_placeholders(post_raw, placeholders)if !creator- Rails.logger.warn "[discourse-automation] creator with username: `#{creator_username}` was not found"+ DiscourseAutomation::Logger.warn("creator with username: `#{creator_username}` was not found")nextend- new_post = PostCreator.new(creator, topic_id: topic_id, raw: post_raw).create!+ post_creator = PostCreator.new(creator, topic_id:, raw: post_raw)+ new_post = post_creator.create+ if new_post.blank? || post_creator.errors.present?+ DiscourseAutomation::Logger.error(+ "Failed to create post in topic #{topic_id}: #{post_creator.errors.full_messages.join(", ")}",+ )+ next+ endif context["kind"] == DiscourseAutomation::Triggers::USER_UPDATED && new_post.persisted?user.user_custom_fields.create(name: automation.name, value: "true")diff --git a/plugins/automation/lib/discourse_automation/scripts/topic.rb b/plugins/automation/lib/discourse_automation/scripts/topic.rbindex 9737768020a..6ff94990d56 100644--- a/plugins/automation/lib/discourse_automation/scripts/topic.rb+++ b/plugins/automation/lib/discourse_automation/scripts/topic.rb@@ -48,29 +48,24 @@ DiscourseAutomation::Scriptable.add(DiscourseAutomation::Scripts::TOPIC) docreator = User.find_by(username: creator_username)if !creator- Rails.logger.warn "[discourse-automation] creator with username: `#{creator_username}` was not found"+ DiscourseAutomation::Logger.warn("creator with username: `#{creator_username}` was not found")nextendcategory_id = fields.dig("category", "value")category = Category.find_by(id: category_id)if !category- Rails.logger.warn "[discourse-automation] category of id: `#{category_id}` was not found"+ DiscourseAutomation::Logger.warn("category of id: `#{category_id}` was not found")nextendtags = fields.dig("tags", "value") || []- begin- new_post =- PostCreator.new(- creator,- raw: topic_raw,- title: title,- category: category.id,- tags: tags,- ).create!- rescue StandardError => e- Rails.logger.warn "[discourse-automation] couldn't create post: #{e.message}"+ post_creator = PostCreator.new(creator, raw: topic_raw, title:, category: category.id, tags:)+ new_post = post_creator.create+ if new_post.blank? || post_creator.errors.present?+ DiscourseAutomation::Logger.error(+ "Failed to create topic '#{title}': #{post_creator.errors.full_messages.join(", ")}",+ )nextenddiff --git a/plugins/automation/lib/discourse_automation/scripts/user_group_membership_through_badge.rb b/plugins/automation/lib/discourse_automation/scripts/user_group_membership_through_badge.rbindex 5b1e05d9b68..637aa83ceef 100644--- a/plugins/automation/lib/discourse_automation/scripts/user_group_membership_through_badge.rb+++ b/plugins/automation/lib/discourse_automation/scripts/user_group_membership_through_badge.rb@@ -29,13 +29,13 @@ DiscourseAutomation::Scriptable.add(badge = Badge.find_by(id: badge_id)unless badge- Rails.logger.warn("[discourse-automation] Couldn’t find badge with id #{badge_id}")+ DiscourseAutomation::Logger.warn("Couldn't find badge with id #{badge_id}")nextendgroup = Group.find_by(id: group_id)unless group- Rails.logger.warn("[discourse-automation] Couldn’t find group with id #{group_id}")+ DiscourseAutomation::Logger.warn("Couldn't find group with id #{group_id}")nextenddiff --git a/plugins/automation/lib/discourse_automation/scripts/zapier_webhook.rb b/plugins/automation/lib/discourse_automation/scripts/zapier_webhook.rbindex 85d71a6e0ab..c9d3dbb9f7a 100644--- a/plugins/automation/lib/discourse_automation/scripts/zapier_webhook.rb+++ b/plugins/automation/lib/discourse_automation/scripts/zapier_webhook.rb@@ -11,7 +11,9 @@ DiscourseAutomation::Scriptable.add(DiscourseAutomation::Scripts::ZAPIER_WEBHOOKwebhook_url = fields.dig("webhook_url", "value")unless webhook_url&.start_with?("https://hooks.zapier.com/hooks/catch/")- Rails.logger.warn "[discourse-automation] #{webhook_url} is not a valid Zapier webhook URL, expecting an URL starting with https://hooks.zapier.com/hooks/catch/"+ DiscourseAutomation::Logger.warn(+ "#{webhook_url} is not a valid Zapier webhook URL, expecting an URL starting with https://hooks.zapier.com/hooks/catch/",+ )nextenddiff --git a/plugins/automation/lib/discourse_automation/triggers/recurring.rb b/plugins/automation/lib/discourse_automation/triggers/recurring.rbindex f373420ad14..38a7a4509d5 100644--- a/plugins/automation/lib/discourse_automation/triggers/recurring.rb+++ b/plugins/automation/lib/discourse_automation/triggers/recurring.rb@@ -117,9 +117,9 @@ module DiscourseAutomationdef self.log_debugging_info(context)return if !SiteSetting.discourse_automation_enable_recurring_debug- str = "[automation] scheduling recurring automation debug: "+ str = "scheduling recurring automation debug: "str += context.map { |k, v| "#{k}=#{v.inspect}" }.join(", ")- Rails.logger.warn(str)+ DiscourseAutomation::Logger.warn(str)endendenddiff --git a/plugins/automation/spec/models/stat_spec.rb b/plugins/automation/spec/models/stat_spec.rbindex e92705f7df7..428ce155e82 100644--- a/plugins/automation/spec/models/stat_spec.rb+++ b/plugins/automation/spec/models/stat_spec.rb@@ -11,7 +11,7 @@ RSpec.describe DiscourseAutomation::Stat dobefore dofreeze_time today- # Last day: 2 runs+ # Last day: 2 runs, 1 errorDiscourseAutomation::Stat.create!(automation_id: automation_id,date: today - 1.day,@@ -21,6 +21,7 @@ RSpec.describe DiscourseAutomation::Stat domin_run_time: 1.0,max_run_time: 2.0,total_runs: 2,+ total_errors: 1,)# Same day, different automation@@ -33,9 +34,10 @@ RSpec.describe DiscourseAutomation::Stat domin_run_time: 1.0,max_run_time: 1.0,total_runs: 1,+ total_errors: 0,)- # Last week: 3 runs (including the day above)+ # Last week: 2 runs, 1 error (not including the day above which has its own stats)DiscourseAutomation::Stat.create!(automation_id: automation_id,date: today - 5.days,@@ -45,9 +47,10 @@ RSpec.describe DiscourseAutomation::Stat domin_run_time: 0.5,max_run_time: 2.0,total_runs: 2,+ total_errors: 1,)- # Last month: 5 runs (including the week above)+ # Last month: 2 runs, 0 errors (not including the week above)DiscourseAutomation::Stat.create!(automation_id: automation_id,date: today - 20.days,@@ -57,6 +60,7 @@ RSpec.describe DiscourseAutomation::Stat domin_run_time: 1.5,max_run_time: 2.5,total_runs: 2,+ total_errors: 0,)end@@ -75,6 +79,7 @@ RSpec.describe DiscourseAutomation::Stat do:average_run_time,:min_run_time,:max_run_time,+ :total_errors,)endend@@ -88,6 +93,7 @@ RSpec.describe DiscourseAutomation::Stat domin_run_time: 1.0,max_run_time: 2.0,average_run_time: 1.5,+ total_errors: 1,)expect(auto_summary[:last_week]).to include(@@ -95,6 +101,7 @@ RSpec.describe DiscourseAutomation::Stat dototal_time: 5.5,min_run_time: 0.5,max_run_time: 2.0,+ total_errors: 2,)expect(auto_summary[:last_month]).to include(@@ -102,6 +109,7 @@ RSpec.describe DiscourseAutomation::Stat dototal_time: 9.5,min_run_time: 0.5,max_run_time: 2.5,+ total_errors: 2,)end@@ -112,6 +120,7 @@ RSpec.describe DiscourseAutomation::Stat doother_summary = summaries[another_automation_id]expect(other_summary[:last_day][:total_runs]).to eq(1)expect(other_summary[:last_day][:total_time]).to eq(1.0)+ expect(other_summary[:last_day][:total_errors]).to eq(0)expect(other_summary[:last_run_at].to_date).to eq((today - 1.day).to_date)end@@ -132,6 +141,7 @@ RSpec.describe DiscourseAutomation::Stat domin_run_time: 1.0,max_run_time: 1.0,total_runs: 1,+ total_errors: 0,)summaries = DiscourseAutomation::Stat.fetch_period_summaries@@ -156,23 +166,63 @@ RSpec.describe DiscourseAutomation::Stat doexpect(stat.min_run_time).to eq(0.75)expect(stat.max_run_time).to eq(0.75)expect(stat.total_runs).to eq(1)+ expect(stat.total_errors).to eq(0)endcontext "when an error occurs" do- it "yields the correct error and records it" do+ it "re-raises the error and records the run time" doallow(Process).to receive(:clock_gettime).from_described_class.and_return(10.0, 10.75)expect { DiscourseAutomation::Stat.log(automation_id) { raise } }.to raise_error(RuntimeError,)- stat = DiscourseAutomation::Stat.find_by(automation_id: automation_id)+ stat = DiscourseAutomation::Stat.find_by(automation_id:)expect(stat.total_time).to eq(0.75)expect(stat.average_run_time).to eq(0.75)expect(stat.min_run_time).to eq(0.75)expect(stat.max_run_time).to eq(0.75)expect(stat.total_runs).to eq(1)end++ it "increments the error count" do+ allow(Process).to receive(:clock_gettime).from_described_class.and_return(10.0, 10.75)++ expect { DiscourseAutomation::Stat.log(automation_id) { raise } }.to raise_error(+ RuntimeError,+ )++ stat = DiscourseAutomation::Stat.find_by(automation_id:)+ expect(stat.total_errors).to eq(1)+ end++ it "accumulates errors across multiple runs" do+ allow(Process).to receive(:clock_gettime).from_described_class.and_return(+ 10.0,+ 10.5,+ 11.0,+ 11.5,+ 12.0,+ 12.5,+ )++ # First run: success+ DiscourseAutomation::Stat.log(automation_id) { "ok" }++ # Second run: error+ expect {+ DiscourseAutomation::Stat.log(automation_id) { raise "error 1" }+ }.to raise_error(RuntimeError)++ # Third run: error+ expect {+ DiscourseAutomation::Stat.log(automation_id) { raise "error 2" }+ }.to raise_error(RuntimeError)++ stat = DiscourseAutomation::Stat.find_by(automation_id: automation_id)+ expect(stat.total_runs).to eq(3)+ expect(stat.total_errors).to eq(2)+ endendend@@ -186,6 +236,7 @@ RSpec.describe DiscourseAutomation::Stat doexpect(stat.min_run_time).to eq(run_time)expect(stat.max_run_time).to eq(run_time)expect(stat.total_runs).to eq(1)+ expect(stat.total_errors).to eq(0)endenddiff --git a/plugins/automation/spec/requests/admin_discourse_automation_automations_spec.rb b/plugins/automation/spec/requests/admin_discourse_automation_automations_spec.rbindex 3452fa5a5a5..85a69360c36 100644--- a/plugins/automation/spec/requests/admin_discourse_automation_automations_spec.rb+++ b/plugins/automation/spec/requests/admin_discourse_automation_automations_spec.rb@@ -459,12 +459,42 @@ describe DiscourseAutomation::AdminAutomationsController doexpect(automation1_response["stats"]["last_day"]["average_run_time"]).to eq(1.0)expect(automation1_response["stats"]["last_day"]["min_run_time"]).to eq(0.5)expect(automation1_response["stats"]["last_day"]["max_run_time"]).to eq(1.5)+ expect(automation1_response["stats"]["last_day"]["total_errors"]).to eq(0)expect(automation1_response["stats"]["last_week"]["total_runs"]).to eq(3)# Verify specific values for automation2expect(automation2_response["stats"]["last_month"]["total_runs"]).to eq(1)expect(automation2_response["stats"]["last_month"]["total_time"]).to eq(3.0)+ expect(automation2_response["stats"]["last_month"]["total_errors"]).to eq(0)+ end++ context "when automation has errors" do+ before do+ freeze_time DateTime.parse("2023-01-01")++ # Simulate 3 runs with 2 errors for automation1+ DiscourseAutomation::Stat.log(automation1.id) { "success" }+ expect {+ DiscourseAutomation::Stat.log(automation1.id) { raise "error 1" }+ }.to raise_error(RuntimeError)+ expect {+ DiscourseAutomation::Stat.log(automation1.id) { raise "error 2" }+ }.to raise_error(RuntimeError)+ end++ it "includes error counts in the response" do+ get "/admin/plugins/automation/automations.json"++ expect(response.status).to eq(200)++ parsed_response = response.parsed_body+ automation1_response =+ parsed_response["automations"].find { |a| a["id"] == automation1.id }++ expect(automation1_response["stats"]["last_day"]["total_runs"]).to eq(5) # 2 from before + 3 new+ expect(automation1_response["stats"]["last_day"]["total_errors"]).to eq(2)+ endendendenddiff --git a/plugins/automation/spec/scripts/topic_spec.rb b/plugins/automation/spec/scripts/topic_spec.rbindex d0671672a6a..136df680aed 100644--- a/plugins/automation/spec/scripts/topic_spec.rb+++ b/plugins/automation/spec/scripts/topic_spec.rb@@ -173,7 +173,7 @@ describe "Topic" doafter { Rails.logger.stop_broadcasting_to(fake_logger) }- it "logs a warning" do+ it "logs an error" doexpect { UserUpdater.new(user, user).update(location: "Japan") }.to change {Topic.count}.by(1)@@ -181,7 +181,7 @@ describe "Topic" doTopic.count}- expect(Rails.logger.warnings.first).to match(/Title has already been used/)+ expect(Rails.logger.errors.first).to match(/Title has already been used/)endendenddiff --git a/plugins/automation/spec/scripts/user_group_membership_through_badge_spec.rb b/plugins/automation/spec/scripts/user_group_membership_through_badge_spec.rbindex baa6c791ce6..a330508079b 100644--- a/plugins/automation/spec/scripts/user_group_membership_through_badge_spec.rb+++ b/plugins/automation/spec/scripts/user_group_membership_through_badge_spec.rb@@ -47,7 +47,7 @@ describe "UserGroupMembershipThroughBadge" doit "logs warning message and does nothing" doexpect(fake_logger.warnings).to include(- "[discourse-automation] Couldn’t find badge with id #{unknown_badge_id}",+ "[discourse-automation] Couldn't find badge with id #{unknown_badge_id}",)expect(user.reload.groups).to be_emptyend@@ -68,7 +68,7 @@ describe "UserGroupMembershipThroughBadge" do)expect(fake_logger.warnings).to include(- "[discourse-automation] Couldn’t find group with id #{target_group.id}",+ "[discourse-automation] Couldn't find group with id #{target_group.id}",)expect(user.reload.groups).to be_emptyend