A platform for community discussion. Free, open, simple.
FEATURE: React to publication schedules without polling
Régis Hanolcd771af1ea1d
diff --git a/app/jobs/regular/bump_topic.rb b/app/jobs/regular/bump_topic.rbindex 4bce5dd11c7..17835c68bea 100644--- a/app/jobs/regular/bump_topic.rb+++ b/app/jobs/regular/bump_topic.rb@@ -3,13 +3,15 @@module Jobsclass BumpTopic < ::Jobs::TopicTimerBasedef execute_timer_action(topic_timer, topic)- guardian = Guardian.new(topic_timer.user)+ guardian = topic_timer.user&.guardian- if guardian.can_create_post_on_topic?(topic) || guardian.can_set_topic_timer?(topic)- topic.add_small_action(Discourse.system_user, "autobumped", nil, bump: true)+ unless guardian&.can_create_post_on_topic?(topic) || guardian&.can_set_topic_timer?(topic)+ topic_timer.trash!(Discourse.system_user)+ returnend- topic_timer.trash!(Discourse.system_user)+ post = topic.add_small_action(Discourse.system_user, "autobumped", nil, bump: true)+ topic_timer.finish!(post ? :completed : :cancelled)endendenddiff --git a/app/jobs/regular/clear_slow_mode.rb b/app/jobs/regular/clear_slow_mode.rbindex 361cce87461..2d9a576f682 100644--- a/app/jobs/regular/clear_slow_mode.rb+++ b/app/jobs/regular/clear_slow_mode.rb@@ -4,7 +4,7 @@ module Jobsclass ClearSlowMode < ::Jobs::TopicTimerBasedef execute_timer_action(topic_timer, topic)topic.update!(slow_mode_seconds: 0)- topic_timer.trash!(Discourse.system_user)+ topic_timer.finish!(:completed)endendenddiff --git a/app/jobs/regular/delete_topic.rb b/app/jobs/regular/delete_topic.rbindex d3a35d5d980..66812a94287 100644--- a/app/jobs/regular/delete_topic.rb+++ b/app/jobs/regular/delete_topic.rb@@ -12,7 +12,7 @@ module Jobscontext: I18n.t("topic_statuses.auto_deleted_by_timer"),).destroy- topic_timer.trash!(Discourse.system_user)+ topic_timer.finish!(:completed)endendenddiff --git a/app/jobs/regular/topic_timer_base.rb b/app/jobs/regular/topic_timer_base.rbindex 35b582a97b4..dcfec85d57d 100644--- a/app/jobs/regular/topic_timer_base.rb+++ b/app/jobs/regular/topic_timer_base.rb@@ -14,7 +14,7 @@ module Jobsreturnend- execute_timer_action(topic_timer, topic)+ TopicTimer.transaction(requires_new: true) { execute_timer_action(topic_timer, topic) }endendenddiff --git a/app/models/topic.rb b/app/models/topic.rbindex 33779f63aad..3981a73ce8d 100644--- a/app/models/topic.rb+++ b/app/models/topic.rb@@ -1699,10 +1699,10 @@ class Topic < ActiveRecord::Base@slow_mode_topic_timer ||= topic_timers.find_by(status_type: TopicTimer.types[:clear_slow_mode])end- def delete_topic_timer(status_type, by_user: Discourse.system_user)+ def delete_topic_timer(status_type, by_user: Discourse.system_user, reason: :cancelled)options = { status_type: status_type }options.merge!(user: by_user) unless TopicTimer.public_types[status_type]- topic_timers.find_by(options)&.trash!(by_user)+ topic_timers.find_by(options)&.finish!(reason, by_user: by_user)@public_topic_timer = nilnilenddiff --git a/app/models/topic_timer.rb b/app/models/topic_timer.rbindex 0133defb33b..8b20f7c320c 100644--- a/app/models/topic_timer.rb+++ b/app/models/topic_timer.rb@@ -1,6 +1,16 @@# frozen_string_literal: trueclass TopicTimer < BaseTimer+ EVENT_ATTRIBUTES = %w[+ status_type+ execute_at+ category_id+ user_id+ based_on_last_post+ duration_minutes+ ].freeze+ REMOVAL_REASONS = %i[cancelled completed].freeze+belongs_to :userbelongs_to :topic, foreign_key: :timerable_idbelongs_to :category@@ -48,6 +58,29 @@ class TopicTimer < BaseTimerendend+ after_save :publish_timer_change+ after_destroy do+ DiscourseEvent.trigger(:topic_timer_changed, self, :cancelled, nil) unless trashed?+ end++ def trash!(trashed_by = nil)+ finish!(:cancelled, by_user: trashed_by)+ end++ def finish!(reason, by_user: Discourse.system_user)+ if REMOVAL_REASONS.exclude?(reason)+ raise ArgumentError, "Unknown timer removal reason: #{reason}"+ end++ with_lock do+ next false if trashed?++ trash_update(Time.current, by_user&.id)+ DiscourseEvent.trigger(:topic_timer_changed, self, reason, nil)+ true+ end+ end+def runnable?return false if deleted_at.present?return false if execute_at > Time.zone.now@@ -56,6 +89,19 @@ class TopicTimer < BaseTimerprivate+ def publish_timer_change+ if previously_new_record?+ DiscourseEvent.trigger(:topic_timer_changed, self, :created, nil)+ return+ end++ changes = saved_changes.slice(*EVENT_ATTRIBUTES)+ return if changes.empty?++ previous = attributes.slice(*EVENT_ATTRIBUTES).merge(changes.transform_values(&:first))+ DiscourseEvent.trigger(:topic_timer_changed, self, :updated, previous)+ end+def executed_at_in_future?return if created_at.blank? || (execute_at > created_at)diff --git a/app/services/topic_status_updater.rb b/app/services/topic_status_updater.rbindex cb2a2ba1068..086ae6f632b 100644--- a/app/services/topic_status_updater.rb+++ b/app/services/topic_status_updater.rb@@ -81,11 +81,12 @@ TopicStatusUpdater =endif @topic_timer- if status.manually_closing_topic? || status.closing_topic?- topic.delete_topic_timer(TopicTimer.types[:close])- topic.delete_topic_timer(TopicTimer.types[:silent_close])- elsif status.manually_opening_topic? || status.opening_topic?- topic.delete_topic_timer(TopicTimer.types[:open])+ reason = status.autoclosed? ? :completed : :cancelled+ if status.closing_topic?+ topic.delete_topic_timer(TopicTimer.types[:close], by_user: user, reason: reason)+ topic.delete_topic_timer(TopicTimer.types[:silent_close], by_user: user, reason: reason)+ elsif status.opening_topic?+ topic.delete_topic_timer(TopicTimer.types[:open], by_user: user, reason: reason)topic.inherit_auto_close_from_categoryendend@@ -189,9 +190,5 @@ TopicStatusUpdater =def manually_closing_topic?closed? && enabled?end-- def manually_opening_topic?- closed? && disabled?- endendenddiff --git a/lib/topic_publisher.rb b/lib/topic_publisher.rbindex 3b4d6ae4963..c18285457b7 100644--- a/lib/topic_publisher.rb+++ b/lib/topic_publisher.rb@@ -29,10 +29,12 @@ class TopicPublisher# Clean up any publishing artifactsSharedDraft.where(topic: @topic).delete_all- TopicTimer.where(topic: @topic).update_all(- deleted_at: DateTime.now,- deleted_by_id: @published_by.id,- )+ TopicTimer+ .where(topic: @topic)+ .find_each do |timer|+ reason = timer.publishing_to_category? ? :completed : :cancelled+ timer.finish!(reason, by_user: @published_by)+ endop = @topic.first_postdiff --git a/plugins/discourse-workflows/USE_CASES.md b/plugins/discourse-workflows/USE_CASES.mdindex 00cd5ff67c6..20a0b1a728d 100644--- a/plugins/discourse-workflows/USE_CASES.md+++ b/plugins/discourse-workflows/USE_CASES.md@@ -59,6 +59,8 @@ For each run, record:## Known edge cases to keep testing- `action:topic_tags` version `2.0` defaults to `mode: modify`: `add_tag_names` and `remove_tag_names` apply together, preserving unrelated tags and allowing implicit parent tags. `mode: replace` sets the complete tag set from `replace_tag_names`; an empty value clears all tags. Replacement uses the current topic state under a lock and rejects category or parent-tag rules that change the requested final set. Only the selected mode's fields are evaluated; invalid names and expression errors stop the action before any tag changes. Both modes enforce the actor’s permission to edit the topic’s tags and return the final `tag_names`; rejected changes neither persist nor emit tag-change events. Existing tag names remain usable after the maximum tag length is reduced. Version `1.0` retains `operation` and `tag_names`.+- `trigger:topic_timer_changed` exposes `change` (`created`, `updated`, `cancelled`, `completed`), `timer`, and `previous_timer`. Its timer-type filter matches either the previous or current type; inspect `timer.status_type` when handling replacement of a publication timer with another timer type.+- `trigger:topic_published` and completed publication timers expose the topic in its destination category. Use `trigger:topic_timer_changed` for scheduling and cancellation, and `trigger:topic_published` for publication cleanup.- Topic status triggers are separate nodes: `topic_closed`, `topic_reopened`, `topic_archived`, `topic_unarchived`, `topic_listed`, `topic_unlisted`, `topic_pinned`, `topic_unpinned`, `topic_pinned_globally`, and `topic_unpinned_globally` (all prefixed with `trigger:`). They share category and tag filters. Closing includes automatic closes; unpin events use the previous pin scope. Workflow and AI actions use the same status updater.- Topic-only triggers that need author/post fields should use `action:topic` get before filtering or messaging.- Generic prompts like "when someone posts" should use `trigger:post_created` for all regular posts; do not ask whether to include replies unless the prompt explicitly narrows the scope.diff --git a/plugins/discourse-workflows/config/locales/client.en.yml b/plugins/discourse-workflows/config/locales/client.en.ymlindex 6f0ebb118be..f7881e93cbd 100644--- a/plugins/discourse-workflows/config/locales/client.en.yml+++ b/plugins/discourse-workflows/config/locales/client.en.yml@@ -214,6 +214,8 @@ en:one: "%{count} item"other: "%{count} items"nodes:+ "trigger:topic_published": "Topic published"+ "trigger:topic_timer_changed": "Topic timer changed""trigger:topic_status_changed": "Topic status changed""trigger:topic_closed": "Topic closed""trigger:topic_reopened": "Topic reopened"@@ -287,6 +289,8 @@ en:"action:topic_moderation": "Topic moderation""action:flag_user": "Flag user"node_descriptions:+ "trigger:topic_published": "Fires when a topic is published"+ "trigger:topic_timer_changed": "Fires when a topic timer is created, updated, cancelled, or completed""trigger:topic_status_changed": "Fires when a topic is closed, reopened, archived, listed, or pinned, or those changes are reversed""trigger:topic_closed": "Fires when a topic is closed by a user or auto-close timer""trigger:topic_reopened": "Fires when a topic is reopened"@@ -873,6 +877,33 @@ en:category_ids_description: "Only consider topics in these categories. Leave empty to match all categories."tag_names: "Tags"tag_names_description: "Only consider topics that have at least one of these tags"+ topic_published:+ category_ids: "Published categories"+ category_ids_description: "Only trigger for topics published in these categories. Leave empty to match all categories."+ tag_names: "Tags"+ tag_names_description: "Only trigger for topics that have at least one of these tags"+ topic_timer_changed:+ changes: "Changes"+ changes_description: "Leave empty to match any change."+ changes_placeholder: "Any change"+ changes_created: "Created"+ changes_updated: "Updated"+ changes_cancelled: "Cancelled"+ changes_completed: "Completed"+ timer_types: "Timer types"+ timer_types_description: "Match the previous or current timer type. Leave empty to match all types."+ timer_types_placeholder: "All timer types"+ timer_types_close: "Close topic"+ timer_types_open: "Open topic"+ timer_types_publish_to_category: "Publish to category"+ timer_types_delete: "Delete topic"+ timer_types_reminder: "Reminder"+ timer_types_bump: "Bump topic"+ timer_types_delete_replies: "Delete replies"+ timer_types_silent_close: "Close topic silently"+ timer_types_clear_slow_mode: "Clear slow mode"+ tag_names: "Tags"+ tag_names_description: "Only trigger for topics that have at least one of these tags"topic_status_changed:statuses: "Status changes"statuses_description: "Leave empty to match any status change."diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic_published/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic_published/v1.rbnew file mode 100644index 00000000000..a184bd87fec--- /dev/null+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic_published/v1.rb@@ -0,0 +1,56 @@+# frozen_string_literal: true++module DiscourseWorkflows+ module Nodes+ module TopicPublished+ class V1 < NodeType+ description(+ name: "trigger:topic_published",+ version: "1.0",+ defaults: {+ icon: "calendar-days",+ color: "green",+ },+ group: "discourse_triggers",+ event: :topic_published,+ output_contracts: [+ {+ schema:+ Schema.merge(+ Schema::TOPIC_LIST_ITEM_SCHEMA,+ Schema.document(+ "published_at" => {+ "type" => "string",+ "format" => "date-time",+ },+ ),+ ),+ },+ ],+ properties: {+ **CATEGORY_FILTER_PROPERTIES,+ **TAG_FILTER_PROPERTIES,+ },+ )++ def initialize(topic, published_at)+ super(parameters: {})+ @topic = topic+ @published_at = published_at+ end++ def valid?+ @topic.present? && @published_at.present?+ end++ def output+ { topic: topic_data(@topic), published_at: @published_at.iso8601 }+ end++ def matches?(trigger_ctx)+ matches_topic_filters?(@topic, trigger_ctx)+ end+ end+ end+ end+enddiff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic_timer_changed/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic_timer_changed/v1.rbnew file mode 100644index 00000000000..cce0e7c484e--- /dev/null+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic_timer_changed/v1.rb@@ -0,0 +1,128 @@+# frozen_string_literal: true++module DiscourseWorkflows+ module Nodes+ module TopicTimerChanged+ class V1 < NodeType+ CHANGES = %w[created updated cancelled completed].freeze+ TIMER_PROPERTIES = {+ "id" => {+ "type" => "integer",+ },+ "status_type" => {+ "type" => "string",+ },+ "execute_at" => {+ "type" => "string",+ "format" => "date-time",+ },+ "category_id" => {+ "type" => %w[integer null],+ },+ "user_id" => {+ "type" => "integer",+ },+ "based_on_last_post" => {+ "type" => "boolean",+ },+ "duration_minutes" => {+ "type" => %w[integer null],+ },+ }.freeze++ description(+ name: "trigger:topic_timer_changed",+ version: "1.0",+ defaults: {+ icon: "clock",+ color: "orange",+ },+ group: "discourse_triggers",+ event: :topic_timer_changed,+ output_contracts: [+ {+ schema:+ Schema.merge(+ Schema::TOPIC_LIST_ITEM_SCHEMA,+ Schema.document(+ "change" => {+ "type" => "string",+ "enum" => CHANGES,+ },+ "timer" => {+ "type" => "object",+ "properties" => TIMER_PROPERTIES,+ },+ "previous_timer" => {+ "type" => %w[object null],+ "properties" => TIMER_PROPERTIES,+ },+ ),+ ),+ },+ ],+ properties: {+ changes: {+ type: :multi_options,+ required: false,+ default: [],+ options: CHANGES,+ },+ timer_types: {+ type: :multi_options,+ required: false,+ default: [],+ options: ::TopicTimer.types.keys.map(&:to_s),+ },+ **CATEGORY_FILTER_PROPERTIES,+ **TAG_FILTER_PROPERTIES,+ },+ )++ def initialize(timer, change, previous_attributes = nil)+ super(parameters: {})+ @timer = timer+ @topic = ::Topic.with_deleted.find_by(id: timer.timerable_id) if timer+ @change = change.to_s+ @previous_attributes = previous_attributes+ end++ def valid?+ @topic.present? && CHANGES.include?(@change)+ end++ def output+ {+ topic: topic_data(@topic),+ change: @change,+ timer: timer_data(@timer.attributes),+ previous_timer: @previous_attributes && timer_data(@previous_attributes),+ }+ end++ def matches?(trigger_ctx)+ changes = Array.wrap(trigger_ctx.get_node_parameter("changes", []))+ return false if changes.present? && !changes.include?(@change)++ types = Array.wrap(trigger_ctx.get_node_parameter("timer_types", []))+ timer_types =+ [@timer.status_type, @previous_attributes&.fetch("status_type", nil)].compact+ .map { |type| ::TopicTimer.types[type].to_s }+ return false if types.present? && !types.intersect?(timer_types)++ matches_topic_filters?(@topic, trigger_ctx)+ end++ private++ def timer_data(attributes)+ attributes.slice(*::TopicTimer::EVENT_ATTRIBUTES).merge(+ "id" => @timer.id,+ "status_type" => ::TopicTimer.types[attributes["status_type"]].to_s,+ "execute_at" => attributes["execute_at"].iso8601,+ )+ end+ end+ end+ end+enddiff --git a/plugins/discourse-workflows/spec/integration/topic_timer_triggers_spec.rb b/plugins/discourse-workflows/spec/integration/topic_timer_triggers_spec.rbnew file mode 100644index 00000000000..132e983bf14--- /dev/null+++ b/plugins/discourse-workflows/spec/integration/topic_timer_triggers_spec.rb@@ -0,0 +1,144 @@+# frozen_string_literal: true++RSpec.describe "Workflow topic timer triggers" do+ fab!(:admin)+ fab!(:category)+ fab!(:destination, :category)+ fab!(:topic) { Fabricate(:topic_with_op, category: category) }++ before { freeze_time }++ it "passes schedule changes only for the selected timer types and categories" do+ workflow =+ create_workflow(+ "trigger:topic_timer_changed",+ "timer_types" => ["publish_to_category"],+ "category_ids" => [category.id],+ )++ timer =+ topic.set_or_create_timer(+ TopicTimer.types[:publish_to_category],+ 1.hour.from_now.iso8601,+ by_user: admin,+ category_id: destination.id,+ )+ first_schedule = timer.execute_at+ timer.update!(execute_at: 2.hours.from_now)+ topic.delete_topic_timer(timer.status_type, by_user: admin)+ Fabricate(:topic_timer, topic: topic, user: admin, status_type: TopicTimer.types[:close])+ Fabricate(+ :topic_timer,+ topic: Fabricate(:topic, category: destination),+ user: admin,+ status_type: TopicTimer.types[:publish_to_category],+ category: category,+ )++ payloads = workflow_payloads(workflow)+ expect(payloads.map { |payload| payload["change"] }).to eq(%w[created updated cancelled])+ expect(payloads.first["timer"]).to include(+ "status_type" => "publish_to_category",+ "category_id" => destination.id,+ "user_id" => admin.id,+ )+ expect(payloads.second["previous_timer"]["execute_at"]).to eq(first_schedule.iso8601)+ expect(payloads.map { |payload| payload.dig("topic", "id") }.uniq).to eq([topic.id])+ expect(payloads).to all(+ match_node_output_schema(DiscourseWorkflows::Nodes::TopicTimerChanged::V1),+ )+ end++ it "matches the previous timer type when a publication schedule is replaced" do+ workflow =+ create_workflow(+ "trigger:topic_timer_changed",+ "changes" => ["updated"],+ "timer_types" => ["publish_to_category"],+ )+ timer =+ Fabricate(+ :topic_timer,+ topic: topic,+ user: admin,+ status_type: TopicTimer.types[:publish_to_category],+ category: destination,+ )++ timer.update!(status_type: TopicTimer.types[:close])++ payload = workflow_payloads(workflow).sole+ expect(payload["timer"]["status_type"]).to eq("close")+ expect(payload["previous_timer"]["status_type"]).to eq("publish_to_category")+ end++ it "runs the publication workflow only when the topic is published" do+ workflow = create_workflow("trigger:topic_published", "category_ids" => [destination.id])+ timer =+ Fabricate(+ :topic_timer,+ topic: topic,+ user: admin,+ status_type: TopicTimer.types[:publish_to_category],+ category: destination,+ )+ expect(workflow_payloads(workflow)).to be_empty+ freeze_time(2.hours.from_now)++ Jobs::PublishTopicToCategory.new.execute(topic_timer_id: timer.id)++ payload = workflow_payloads(workflow).sole+ expect(payload["topic"]).to include("id" => topic.id, "category_id" => destination.id)+ expect(payload["published_at"]).to eq(Time.current.iso8601)+ expect(payload).to match_node_output_schema(DiscourseWorkflows::Nodes::TopicPublished::V1)++ job = Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last["args"].first+ Jobs::DiscourseWorkflows::ExecuteWorkflow.new.execute(job.symbolize_keys)++ expect(workflow.executions.last.status).to eq("success")+ end++ it "captures the topic after the timer's immediate status change" do+ workflow = create_workflow("trigger:topic_timer_changed", "changes" => ["created"])++ Fabricate(:topic_timer, topic: topic, user: admin, status_type: TopicTimer.types[:open])++ expect(workflow_payloads(workflow).sole.dig("topic", "closed")).to eq(true)+ end++ it "triggers completion for a timer that deletes its topic" do+ workflow =+ create_workflow(+ "trigger:topic_timer_changed",+ "changes" => ["completed"],+ "timer_types" => ["delete"],+ )+ timer =+ Fabricate(:topic_timer, topic: topic, user: admin, status_type: TopicTimer.types[:delete])+ freeze_time(2.hours.from_now)++ Jobs::DeleteTopic.new.execute(topic_timer_id: timer.id)++ payload = workflow_payloads(workflow).sole+ expect(payload.dig("topic", "id")).to eq(topic.id)+ expect(payload).to match_node_output_schema(DiscourseWorkflows::Nodes::TopicTimerChanged::V1)+ end++ def create_workflow(trigger, parameters)+ graph =+ build_workflow_graph do |builder|+ builder.node "trigger", trigger, configuration: parameters+ builder.node "log", "action:log"+ builder.chain "trigger", "log"+ end++ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)+ end++ def workflow_payloads(workflow)+ Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.filter_map do |job|+ args = job["args"].first+ args["trigger_data"] if args["workflow_id"] == workflow.id+ end+ end+enddiff --git a/spec/jobs/bump_topic_spec.rb b/spec/jobs/bump_topic_spec.rbindex 753f6b54bb4..0ad010a67ff 100644--- a/spec/jobs/bump_topic_spec.rb+++ b/spec/jobs/bump_topic_spec.rb@@ -4,31 +4,75 @@ RSpec.describe Jobs::BumpTopic dofab!(:admin)fab!(:user)- it "can bump a topic" do- topic = Fabricate(:topic_timer, user: admin).topic+ it "respects the guardian" do+ topic = Fabricate(:topic_timer, user: user).topiccreate_post(topic: topic)+ topic.category = Fabricate(:private_category, group: Fabricate(:group))+ topic.save!freeze_time(2.hours.from_now)expect dodescribed_class.new.execute(topic_timer_id: topic.public_topic_timer.id)- end.to change { topic.posts.count }.by(1)+ end.not_to change { topic.posts.count }expect(topic.reload.public_topic_timer).to eq(nil)end- it "respects the guardian" do- topic = Fabricate(:topic_timer, user: user).topic- create_post(topic: topic)- topic.category = Fabricate(:private_category, group: Fabricate(:group))- topic.save!+ it "cancels the timer when the system user cannot create the bump post" do+ SiteSetting.suppress_secured_categories_from_admin = true+ group = Fabricate(:group, users: [admin])+ category = Fabricate(:private_category, group: group)+ topic = Fabricate(:topic_with_op, category: category)+ timer = Fabricate(:topic_timer, topic: topic, user: admin, status_type: TopicTimer.types[:bump])+ freeze_time(2.hours.from_now)++ events =+ DiscourseEvent.track_events(:topic_timer_changed) do+ expect do described_class.new.execute(topic_timer_id: timer.id) end.not_to change {+ topic.posts.count+ }+ end+ expect(timer.reload).to be_trashed+ expect(events.map { |event| event[:params][1] }).to eq([:cancelled])+ end++ it "rolls back a failed bump and completes its timer on retry" do+ topic = Fabricate(:topic_with_op)+ timer = Fabricate(:topic_timer, topic: topic, user: admin, status_type: TopicTimer.types[:bump])+ post_count = topic.posts.countfreeze_time(2.hours.from_now)+ handler = proc { raise "Listener unavailable" }+ DiscourseEvent.on(:topic_timer_changed, &handler)- expect do- described_class.new.execute(topic_timer_id: topic.public_topic_timer.id)- end.not_to change { topic.posts.count }+ expect do described_class.new.execute(topic_timer_id: timer.id) end.to raise_error(+ "Listener unavailable",+ )+ expect(topic.posts.count).to eq(post_count)++ DiscourseEvent.off(:topic_timer_changed, &handler)+ events =+ DiscourseEvent.track_events(:topic_timer_changed) do+ described_class.new.execute(topic_timer_id: timer.id)+ end+ expect(topic.posts.count).to eq(post_count + 1)expect(topic.reload.public_topic_timer).to eq(nil)+ expect(events.map { |event| event[:params][1] }).to eq([:completed])+ ensure+ DiscourseEvent.off(:topic_timer_changed, &handler) if handler+ end++ it "cancels the timer when its owner has been deleted" do+ timer = Fabricate(:topic_timer, user: user, status_type: TopicTimer.types[:bump])+ user.destroy!+ freeze_time(2.hours.from_now)++ expect do described_class.new.execute(topic_timer_id: timer.id) end.not_to change {+ timer.topic.posts.count+ }++ expect(timer.reload).to be_trashedendenddiff --git a/spec/jobs/delete_topic_spec.rb b/spec/jobs/delete_topic_spec.rbindex 86e0ab3b84c..a0f06baf6c9 100644--- a/spec/jobs/delete_topic_spec.rb+++ b/spec/jobs/delete_topic_spec.rb@@ -7,25 +7,41 @@ RSpec.describe Jobs::DeleteTopic dolet(:first_post) { create_post(topic: topic) }- it "can delete a topic" do+ it "does nothing when the topic is already deleted" dofirst_post+ topic.trash!- freeze_time(2.hours.from_now)+ freeze_time 2.hours.from_now+ Topic.any_instance.expects(:trash!).neverdescribed_class.new.execute(topic_timer_id: topic.public_topic_timer.id)- expect(topic.reload).to be_trashed- expect(first_post.reload).to be_trashed- expect(topic.reload.public_topic_timer).to eq(nil)end- it "does nothing when the topic is already deleted" do+ it "rolls back a failed deletion and completes its timer on retry" dofirst_post- topic.trash!+ timer = topic.public_topic_timer+ timer.update!(status_type: TopicTimer.types[:delete])+ freeze_time(2.hours.from_now)+ handler = proc { raise "Listener unavailable" }+ DiscourseEvent.on(:topic_timer_changed, &handler)- freeze_time 2.hours.from_now+ expect do described_class.new.execute(topic_timer_id: timer.id) end.to raise_error(+ "Listener unavailable",+ )+ expect(topic.reload).not_to be_trashed- Topic.any_instance.expects(:trash!).never- described_class.new.execute(topic_timer_id: topic.public_topic_timer.id)+ DiscourseEvent.off(:topic_timer_changed, &handler)+ events =+ DiscourseEvent.track_events(:topic_timer_changed) do+ described_class.new.execute(topic_timer_id: timer.id)+ end++ expect(topic.reload).to be_trashed+ expect(first_post.reload).to be_trashed+ expect(topic.reload.public_topic_timer).to eq(nil)+ expect(events.map { |event| event[:params][1] }).to eq([:completed])+ ensure+ DiscourseEvent.off(:topic_timer_changed, &handler) if handlerendit "does nothing when run too early" dodiff --git a/spec/models/topic_timer_lifecycle_spec.rb b/spec/models/topic_timer_lifecycle_spec.rbnew file mode 100644index 00000000000..384bb29c0ea--- /dev/null+++ b/spec/models/topic_timer_lifecycle_spec.rb@@ -0,0 +1,76 @@+# frozen_string_literal: true++RSpec.describe TopicTimer do+ fab!(:admin)+ fab!(:topic, :topic_with_op)+ fab!(:destination, :category)++ before { freeze_time }++ it "emits each publication schedule change once with its previous values" do+ scheduled_at = 1.hour.from_now.change(usec: 0)+ events =+ DiscourseEvent.track_events(:topic_timer_changed) do+ timer =+ topic.set_or_create_timer(+ TopicTimer.types[:publish_to_category],+ scheduled_at.iso8601,+ by_user: admin,+ category_id: destination.id,+ )++ timer.update!(execute_at: 2.hours.from_now)+ timer.save!+ topic.delete_topic_timer(timer.status_type, by_user: admin)+ timer.reload.trash!(admin)+ end++ expect(events.map { |event| event[:params][1] }).to eq(%i[created updated cancelled])+ expect(events.second[:params][2]).to include(+ "execute_at" => scheduled_at,+ "status_type" => TopicTimer.types[:publish_to_category],+ "category_id" => destination.id,+ )+ end++ it "emits completion when the publication timer publishes its topic" do+ timer =+ Fabricate(+ :topic_timer,+ topic: topic,+ user: admin,+ category: destination,+ status_type: TopicTimer.types[:publish_to_category],+ )+ freeze_time(2.hours.from_now)++ events =+ DiscourseEvent.track_events(:topic_timer_changed) do+ Jobs::PublishTopicToCategory.new.execute(topic_timer_id: timer.id)+ end++ expect(topic.reload.category_id).to eq(destination.id)+ expect(events.map { |event| event[:params][1] }).to eq([:completed])+ end++ it "emits completion when a timer closes a topic" do+ timer = Fabricate(:topic_timer, topic: topic, user: admin)+ freeze_time(2.hours.from_now)++ events =+ DiscourseEvent.track_events(:topic_timer_changed) do+ Jobs::CloseTopic.new.execute(topic_timer_id: timer.id)+ end++ expect(topic.reload).to be_closed+ expect(events.map { |event| event[:params][1] }).to eq([:completed])+ end++ it "emits cancellation when an active timer is destroyed" do+ timer = Fabricate(:topic_timer, topic: topic, user: admin)++ events = DiscourseEvent.track_events(:topic_timer_changed) { timer.destroy! }++ expect(events.map { |event| event[:params][1] }).to eq([:cancelled])+ end+end