A platform for community discussion. Free, open, simple.
DEV: Have `contract` take a block in services
Loïc Guitautfc1c5f6a8d54
diff --git a/app/services/flags/create_flag.rb b/app/services/flags/create_flag.rbindex 09addd884ec..d0089b02469 100644--- a/app/services/flags/create_flag.rb+++ b/app/services/flags/create_flag.rb@@ -3,28 +3,26 @@class Flags::CreateFlaginclude Service::Base- contract- policy :invalid_access- policy :unique_name- model :flag, :instantiate_flag-- transaction do- step :create- step :log- end-- class Contract+ contract doattribute :name, :stringattribute :description, :stringattribute :require_message, :booleanattribute :enabled, :booleanattribute :applies_to+validates :name, presence: truevalidates :description, presence: truevalidates :name, length: { maximum: Flag::MAX_NAME_LENGTH }validates :description, length: { maximum: Flag::MAX_DESCRIPTION_LENGTH }validates :applies_to, inclusion: { in: -> { Flag.valid_applies_to_types } }, allow_nil: falseend+ policy :invalid_access+ policy :unique_name+ model :flag, :instantiate_flag+ transaction do+ step :create+ step :log+ endprivatediff --git a/app/services/flags/reorder_flag.rb b/app/services/flags/reorder_flag.rbindex a306a7cd32f..bd3ae1125e4 100644--- a/app/services/flags/reorder_flag.rb+++ b/app/services/flags/reorder_flag.rb@@ -5,23 +5,21 @@ VALID_DIRECTIONS = %w[up down]class Flags::ReorderFlaginclude Service::Base- contract+ contract do+ attribute :flag_id, :integer+ attribute :direction, :string++ validates :flag_id, presence: true+ validates :direction, inclusion: { in: VALID_DIRECTIONS }+ endmodel :flagpolicy :invalid_accesspolicy :invalid_move-transaction dostep :movestep :logend- class Contract- attribute :flag_id, :integer- attribute :direction, :string- validates :flag_id, presence: true- validates :direction, inclusion: { in: VALID_DIRECTIONS }- end-privatedef fetch_flag(flag_id:)diff --git a/app/services/flags/toggle_flag.rb b/app/services/flags/toggle_flag.rbindex d7c65258fd7..06afe4f4424 100644--- a/app/services/flags/toggle_flag.rb+++ b/app/services/flags/toggle_flag.rb@@ -3,20 +3,18 @@class Flags::ToggleFlaginclude Service::Base- contract+ contract do+ attribute :flag_id, :integer++ validates :flag_id, presence: true+ endmodel :flagpolicy :invalid_access-transaction dostep :togglestep :logend- class Contract- attribute :flag_id, :integer- validates :flag_id, presence: true- end-privatedef fetch_flag(flag_id:)diff --git a/app/services/flags/update_flag.rb b/app/services/flags/update_flag.rbindex eaaee969d15..766d2bb701c 100644--- a/app/services/flags/update_flag.rb+++ b/app/services/flags/update_flag.rb@@ -3,30 +3,28 @@class Flags::UpdateFlaginclude Service::Base- contract- model :flag- policy :not_system- policy :not_used- policy :invalid_access- policy :unique_name-- transaction do- step :update- step :log- end-- class Contract+ contract doattribute :name, :stringattribute :description, :stringattribute :require_message, :booleanattribute :enabled, :booleanattribute :applies_to+validates :name, presence: truevalidates :description, presence: truevalidates :name, length: { maximum: Flag::MAX_NAME_LENGTH }validates :description, length: { maximum: Flag::MAX_DESCRIPTION_LENGTH }validates :applies_to, inclusion: { in: -> { Flag.valid_applies_to_types } }, allow_nil: falseend+ model :flag+ policy :not_system+ policy :not_used+ policy :invalid_access+ policy :unique_name+ transaction do+ step :update+ step :log+ endprivatediff --git a/app/services/update_site_setting.rb b/app/services/update_site_setting.rbindex 0b4f28ff1f3..70f2d1d6325 100644--- a/app/services/update_site_setting.rb+++ b/app/services/update_site_setting.rb@@ -4,20 +4,18 @@ class UpdateSiteSettinginclude Service::Basepolicy :current_user_is_admin- contract- step :convert_name_to_sym- policy :setting_is_visible- policy :setting_is_configurable- step :cleanup_value- step :save-- class Contract+ contract doattribute :setting_nameattribute :new_valueattribute :allow_changing_hidden, :boolean, default: falsevalidates :setting_name, presence: trueend+ step :convert_name_to_sym+ policy :setting_is_visible+ policy :setting_is_configurable+ step :cleanup_value+ step :saveprivatediff --git a/app/services/user/silence.rb b/app/services/user/silence.rbindex 778afd4cceb..afc87131942 100644--- a/app/services/user/silence.rb+++ b/app/services/user/silence.rb@@ -3,16 +3,7 @@class User::Silenceinclude Service::Base- contract- model :user- policy :not_silenced_already, class_name: User::Policy::NotAlreadySilenced- model :users- policy :can_silence_all_users- step :silence- model :post, optional: true- step :perform_post_action-- class Contract+ contract doattribute :user_id, :integerattribute :reason, :stringattribute :message, :string@@ -28,6 +19,13 @@ class User::Silencevalidates :other_user_ids, length: { maximum: User::MAX_SIMILAR_USERS }validates :post_action, inclusion: { in: %w[delete delete_replies edit] }, allow_blank: trueend+ model :user+ policy :not_silenced_already, class_name: User::Policy::NotAlreadySilenced+ model :users+ policy :can_silence_all_users+ step :silence+ model :post, optional: true+ step :perform_post_actionprivatediff --git a/app/services/user/suspend.rb b/app/services/user/suspend.rbindex 806f730db7b..bd08a6dc2e9 100644--- a/app/services/user/suspend.rb+++ b/app/services/user/suspend.rb@@ -3,16 +3,7 @@class User::Suspendinclude Service::Base- contract- model :user- policy :not_suspended_already, class_name: User::Policy::NotAlreadySuspended- model :users- policy :can_suspend_all_users- step :suspend- model :post, optional: true- step :perform_post_action-- class Contract+ contract doattribute :user_id, :integerattribute :reason, :stringattribute :message, :string@@ -28,6 +19,13 @@ class User::Suspendvalidates :other_user_ids, length: { maximum: User::MAX_SIMILAR_USERS }validates :post_action, inclusion: { in: %w[delete delete_replies edit] }, allow_blank: trueend+ model :user+ policy :not_suspended_already, class_name: User::Policy::NotAlreadySuspended+ model :users+ policy :can_suspend_all_users+ step :suspend+ model :post, optional: true+ step :perform_post_actionprivatediff --git a/lib/service.rb b/lib/service.rbindex 8f1ef6c6973..07d39252657 100644--- a/lib/service.rb+++ b/lib/service.rb@@ -11,12 +11,12 @@ module Service# Currently, there are 5 types of steps:## * +contract(name = :default)+: used to validate the input parameters,- # typically provided by a user calling an endpoint. A special embedded- # +Contract+ class has to be defined to holds the validations. If the- # validations fail, the step will fail. Otherwise, the resulting contract- # will be available in +context[:contract]+. When calling +step(name)+ or- # +model(name = :model)+ methods after validating a contract, the contract- # should be used as an argument instead of context attributes.+ # typically provided by a user calling an endpoint. A block has to be+ # defined to hold the validations. If the validations fail, the step will+ # fail. Otherwise, the resulting contract will be available in+ # +context[:contract]+. When calling +step(name)+ or +model(name = :model)++ # methods after validating a contract, the contract should be used as an+ # argument instead of context attributes.# * +model(name = :model)+: used to instantiate a model (either by building# it or fetching it from the DB). If a falsy value is returned, then the# step will fail. Otherwise the resulting object will be assigned indiff --git a/lib/service/base.rb b/lib/service/base.rbindex cb7f38d5498..46559ddb858 100644--- a/lib/service/base.rb+++ b/lib/service/base.rb@@ -78,10 +78,12 @@ module Servicesteps << ModelStep.new(name, step_name, optional: optional)end- def contract(name = :default, class_name: self::Contract, default_values_from: nil)+ def contract(name = :default, default_values_from: nil, &block)+ contract_class = Class.new(Service::ContractBase).tap { _1.class_eval(&block) }+ const_set("#{name.to_s.classify.sub("Default", "")}Contract", contract_class)steps << ContractStep.new(name,- class_name: class_name,+ class_name: contract_class,default_values_from: default_values_from,)end@@ -214,20 +216,6 @@ module Serviceincluded do# The global context which is available from any step.attr_reader :context-- # @!visibility private- # Internal class used to setup the base contract of the service.- self::Contract =- Class.new do- include ActiveModel::API- include ActiveModel::Attributes- include ActiveModel::AttributeMethods- include ActiveModel::Validations::Callbacks-- def raw_attributes- @attributes.values_before_type_cast- end- endendclass_methods do@@ -306,10 +294,10 @@ module Service# end# @!scope class- # @!method contract(name = :default, class_name: self::Contract, default_values_from: nil)+ # @!method contract(name = :default, default_values_from: nil, &block)# @param name [Symbol] name for this contract- # @param class_name [Class] a class defining the contract# @param default_values_from [Symbol] name of the model to get default values from+ # @param block [Proc] a block containing validations# Checks the validity of the input parameters.# Implements ActiveModel::Validations and ActiveModel::Attributes.#@@ -317,9 +305,7 @@ module Service# (can be customized by providing the +name+ argument).## @example- # contract- #- # class Contract+ # contract do# attribute :name# validates :name, presence: true# enddiff --git a/lib/service/contract_base.rb b/lib/service/contract_base.rbnew file mode 100644index 00000000000..79a0413df2b--- /dev/null+++ b/lib/service/contract_base.rb@@ -0,0 +1,12 @@+# frozen_string_literal: true++class Service::ContractBase+ include ActiveModel::API+ include ActiveModel::Attributes+ include ActiveModel::AttributeMethods+ include ActiveModel::Validations::Callbacks++ def raw_attributes+ @attributes.values_before_type_cast+ end+enddiff --git a/plugins/chat/app/services/chat/add_users_to_channel.rb b/plugins/chat/app/services/chat/add_users_to_channel.rbindex 318459615fe..291c0d761e6 100644--- a/plugins/chat/app/services/chat/add_users_to_channel.rb+++ b/plugins/chat/app/services/chat/add_users_to_channel.rb@@ -22,33 +22,28 @@ module Chat# @option params_to_create [Array<String>] usernames# @option params_to_create [Array<String>] groups# @return [Service::Base::Context]- contract- model :channel- policy :can_add_users_to_channel- model :target_users, optional: true- policy :satisfies_dms_max_users_limit,- class_name: Chat::DirectMessageChannel::Policy::MaxUsersExcess-- transaction do- step :upsert_memberships- step :recompute_users_count- step :notice_channel- end-- # @!visibility private- class Contract+ contract doattribute :usernames, :arrayattribute :groups, :array-attribute :channel_id, :integer- validates :channel_id, presence: true+ validates :channel_id, presence: truevalidate :target_presencedef target_presenceusernames.present? || groups.present?endend+ model :channel+ policy :can_add_users_to_channel+ model :target_users, optional: true+ policy :satisfies_dms_max_users_limit,+ class_name: Chat::DirectMessageChannel::Policy::MaxUsersExcess+ transaction do+ step :upsert_memberships+ step :recompute_users_count+ step :notice_channel+ endprivate@@ -128,20 +123,17 @@ module Chatreturn if added_users.blank?- result =- ::Chat::CreateMessage.call(- guardian: Discourse.system_user.guardian,- chat_channel_id: channel.id,- message:- I18n.t(- "chat.channel.users_invited_to_channel",- invited_users: added_users.map { |u| "@#{u.username}" }.join(", "),- inviting_user: "@#{guardian.user.username}",- count: added_users.count,- ),- )-- fail!(failure: "Failed to notice the channel") if result.failure?+ ::Chat::CreateMessage.call(+ guardian: Discourse.system_user.guardian,+ chat_channel_id: channel.id,+ message:+ I18n.t(+ "chat.channel.users_invited_to_channel",+ invited_users: added_users.map { |u| "@#{u.username}" }.join(", "),+ inviting_user: "@#{guardian.user.username}",+ count: added_users.count,+ ),+ ) { on_failure { fail!(failure: "Failed to notice the channel") } }endendenddiff --git a/plugins/chat/app/services/chat/auto_join_channel_batch.rb b/plugins/chat/app/services/chat/auto_join_channel_batch.rbindex 6a95cc4d314..6518e6f2e53 100644--- a/plugins/chat/app/services/chat/auto_join_channel_batch.rb+++ b/plugins/chat/app/services/chat/auto_join_channel_batch.rb@@ -14,13 +14,7 @@ module Chatclass AutoJoinChannelBatchinclude Service::Base- contract- model :channel- step :create_memberships- step :recalculate_user_count- step :publish_new_channel-- class Contract+ contract do# Backward-compatible attributesattribute :chat_channel_id, :integerattribute :starts_at, :integer@@ -41,6 +35,10 @@ module Chatself.end_user_id ||= ends_atendend+ model :channel+ step :create_memberships+ step :recalculate_user_count+ step :publish_new_channelprivatediff --git a/plugins/chat/app/services/chat/auto_remove/handle_category_updated.rb b/plugins/chat/app/services/chat/auto_remove/handle_category_updated.rbindex fff835bc986..6da61967c1d 100644--- a/plugins/chat/app/services/chat/auto_remove/handle_category_updated.rb+++ b/plugins/chat/app/services/chat/auto_remove/handle_category_updated.rb@@ -14,7 +14,11 @@ module Chatclass HandleCategoryUpdatedinclude Service::Base- contract+ contract do+ attribute :category_id, :integer++ validates :category_id, presence: true+ endstep :assign_defaultspolicy :chat_enabledmodel :category@@ -23,12 +27,6 @@ module Chatstep :remove_users_without_channel_permissionstep :publish- class Contract- attribute :category_id, :integer-- validates :category_id, presence: true- end-privatedef assign_defaultsdiff --git a/plugins/chat/app/services/chat/auto_remove/handle_destroyed_group.rb b/plugins/chat/app/services/chat/auto_remove/handle_destroyed_group.rbindex 9d8e42b6c33..fc29b1152d0 100644--- a/plugins/chat/app/services/chat/auto_remove/handle_destroyed_group.rb+++ b/plugins/chat/app/services/chat/auto_remove/handle_destroyed_group.rb@@ -21,7 +21,11 @@ module Chatclass HandleDestroyedGroupinclude Service::Base- contract+ contract do+ attribute :destroyed_group_user_ids++ validates :destroyed_group_user_ids, presence: true+ endstep :assign_defaultspolicy :chat_enabledpolicy :not_everyone_allowed@@ -30,12 +34,6 @@ module Chatstep :remove_users_without_channel_permissionstep :publish- class Contract- attribute :destroyed_group_user_ids-- validates :destroyed_group_user_ids, presence: true- end-privatedef assign_defaultsdiff --git a/plugins/chat/app/services/chat/auto_remove/handle_user_removed_from_group.rb b/plugins/chat/app/services/chat/auto_remove/handle_user_removed_from_group.rbindex c6bdec7171e..5862ba696f8 100644--- a/plugins/chat/app/services/chat/auto_remove/handle_user_removed_from_group.rb+++ b/plugins/chat/app/services/chat/auto_remove/handle_user_removed_from_group.rb@@ -20,7 +20,11 @@ module Chatclass HandleUserRemovedFromGroupinclude Service::Base- contract+ contract do+ attribute :user_id, :integer++ validates :user_id, presence: true+ endstep :assign_defaultspolicy :chat_enabledpolicy :not_everyone_allowed@@ -30,12 +34,6 @@ module Chatstep :remove_from_private_channelsstep :publish- class Contract- attribute :user_id, :integer-- validates :user_id, presence: true- end-privatedef assign_defaultsdiff --git a/plugins/chat/app/services/chat/create_category_channel.rb b/plugins/chat/app/services/chat/create_category_channel.rbindex 5f98b74ac9f..179bcf7947b 100644--- a/plugins/chat/app/services/chat/create_category_channel.rb+++ b/plugins/chat/app/services/chat/create_category_channel.rb@@ -29,17 +29,7 @@ module Chatpolicy :public_channels_enabledpolicy :can_create_channel- contract- model :category, :fetch_category- policy :category_channel_does_not_exist- transaction do- model :channel, :create_channel- model :membership, :create_membership- end- step :enforce_automatic_channel_memberships-- # @!visibility private- class Contract+ contract doattribute :name, :stringattribute :description, :stringattribute :slug, :string@@ -55,6 +45,13 @@ module Chatvalidates :category_id, presence: truevalidates :name, length: { maximum: SiteSetting.max_topic_title_length }end+ model :category+ policy :category_channel_does_not_exist+ transaction do+ model :channel, :create_channel+ model :membership, :create_membership+ end+ step :enforce_automatic_channel_membershipsprivatediff --git a/plugins/chat/app/services/chat/create_direct_message_channel.rb b/plugins/chat/app/services/chat/create_direct_message_channel.rbindex fd19a811a49..3af0d6df2c5 100644--- a/plugins/chat/app/services/chat/create_direct_message_channel.rb+++ b/plugins/chat/app/services/chat/create_direct_message_channel.rb@@ -23,7 +23,18 @@ module Chat# @option params_to_create [Boolean] upsert# @return [Service::Base::Context]- contract+ contract do+ attribute :name, :string+ attribute :target_usernames, :array+ attribute :target_groups, :array+ attribute :upsert, :boolean, default: false++ validate :target_presence++ def target_presence+ target_usernames.present? || target_groups.present?+ end+ endmodel :target_userspolicy :can_create_direct_messagepolicy :satisfies_dms_max_users_limit,@@ -38,20 +49,6 @@ module Chatstep :update_membershipsstep :recompute_users_count- # @!visibility private- class Contract- attribute :name, :string- attribute :target_usernames, :array- attribute :target_groups, :array- attribute :upsert, :boolean, default: false-- validate :target_presence-- def target_presence- target_usernames.present? || target_groups.present?- end- end-privatedef can_create_direct_message(guardian:, target_users:)diff --git a/plugins/chat/app/services/chat/create_message.rb b/plugins/chat/app/services/chat/create_message.rbindex 4b6170eb195..4aebe1471ed 100644--- a/plugins/chat/app/services/chat/create_message.rb+++ b/plugins/chat/app/services/chat/create_message.rb@@ -22,7 +22,26 @@ module Chat# @param incoming_chat_webhook [Chat::IncomingWebhook]policy :no_silenced_user- contract+ contract do+ attribute :chat_channel_id, :string+ attribute :in_reply_to_id, :string+ attribute :context_topic_id, :integer+ attribute :context_post_ids, :array+ attribute :message, :string+ attribute :staged_id, :string+ attribute :upload_ids, :array+ attribute :thread_id, :string+ attribute :streaming, :boolean, default: false+ attribute :enforce_membership, :boolean, default: false+ attribute :incoming_chat_webhook+ attribute :process_inline, :boolean, default: Rails.env.test?+ attribute :force_thread, :boolean, default: false+ attribute :strip_whitespaces, :boolean, default: true+ attribute :created_by_sdk, :boolean, default: false++ validates :chat_channel_id, presence: true+ validates :message, presence: true, if: -> { upload_ids.blank? }+ endmodel :channelstep :enforce_membershipmodel :membership@@ -35,7 +54,6 @@ module Chatmodel :uploads, optional: truestep :clean_messagemodel :message_instance, :instantiate_message-transaction dostep :create_excerptstep :update_created_by_sdk@@ -51,27 +69,6 @@ module Chatstep :processstep :publish_user_tracking_state- class Contract- attribute :chat_channel_id, :string- attribute :in_reply_to_id, :string- attribute :context_topic_id, :integer- attribute :context_post_ids, :array- attribute :message, :string- attribute :staged_id, :string- attribute :upload_ids, :array- attribute :thread_id, :string- attribute :streaming, :boolean, default: false- attribute :enforce_membership, :boolean, default: false- attribute :incoming_chat_webhook- attribute :process_inline, :boolean, default: Rails.env.test?- attribute :force_thread, :boolean, default: false- attribute :strip_whitespaces, :boolean, default: true- attribute :created_by_sdk, :boolean, default: false-- validates :chat_channel_id, presence: true- validates :message, presence: true, if: -> { upload_ids.blank? }- end-privatedef no_silenced_user(guardian:)diff --git a/plugins/chat/app/services/chat/create_thread.rb b/plugins/chat/app/services/chat/create_thread.rbindex 0e1316de21e..e7b6f042b60 100644--- a/plugins/chat/app/services/chat/create_thread.rb+++ b/plugins/chat/app/services/chat/create_thread.rb@@ -16,7 +16,14 @@ module Chat# @option params_to_create [String,nil] title# @return [Service::Base::Context]- contract+ contract do+ attribute :original_message_id, :integer+ attribute :channel_id, :integer+ attribute :title, :string++ validates :original_message_id, :channel_id, presence: true+ validates :title, length: { maximum: Chat::Thread::MAX_TITLE_LENGTH }+ endmodel :channelpolicy :can_view_channelpolicy :threading_enabled_for_channel@@ -29,16 +36,6 @@ module Chatstep :trigger_chat_thread_created_eventend- # @!visibility private- class Contract- attribute :original_message_id, :integer- attribute :channel_id, :integer- attribute :title, :string-- validates :original_message_id, :channel_id, presence: true- validates :title, length: { maximum: Chat::Thread::MAX_TITLE_LENGTH }- end-privatedef fetch_channel(contract:)diff --git a/plugins/chat/app/services/chat/flag_message.rb b/plugins/chat/app/services/chat/flag_message.rbindex 0bdea682e13..ad610dddebe 100644--- a/plugins/chat/app/services/chat/flag_message.rb+++ b/plugins/chat/app/services/chat/flag_message.rb@@ -26,27 +26,22 @@ module Chat# the force_review option.# @return [Service::Base::Context]- contract- model :message- policy :can_flag_message_in_channel- step :flag_message-- # @!visibility private- class Contract+ contract doattribute :message_id, :integer- validates :message_id, presence: true-attribute :channel_id, :integer- validates :channel_id, presence: true-attribute :flag_type_id, :integer- validates :flag_type_id, inclusion: { in: ->(_flag_type) { ::ReviewableScore.types.values } }-attribute :message, :stringattribute :is_warning, :booleanattribute :take_action, :booleanattribute :queue_for_review, :boolean++ validates :message_id, presence: true+ validates :channel_id, presence: true+ validates :flag_type_id, inclusion: { in: ->(_flag_type) { ::ReviewableScore.types.values } }end+ model :message+ policy :can_flag_message_in_channel+ step :flag_messageprivatediff --git a/plugins/chat/app/services/chat/invite_users_to_channel.rb b/plugins/chat/app/services/chat/invite_users_to_channel.rbindex e2346f42f7a..1a492af4584 100644--- a/plugins/chat/app/services/chat/invite_users_to_channel.rb+++ b/plugins/chat/app/services/chat/invite_users_to_channel.rb@@ -16,22 +16,18 @@ module Chat# @option optional_params [Integer, nil] message_id# @return [Service::Base::Context]- contract- model :channel- policy :can_view_channel- model :users, optional: true- step :send_invite_notifications-- # @!visibility private- class Contract+ contract doattribute :user_ids, :array- validates :user_ids, presence: true-attribute :channel_id, :integer- validates :channel_id, presence: true-attribute :message_id, :integer++ validates :user_ids, presence: true+ validates :channel_id, presence: trueend+ model :channel+ policy :can_view_channel+ model :users, optional: true+ step :send_invite_notificationsprivatediff --git a/plugins/chat/app/services/chat/leave_channel.rb b/plugins/chat/app/services/chat/leave_channel.rbindex f905eb04ff6..63afd9ab3df 100644--- a/plugins/chat/app/services/chat/leave_channel.rb+++ b/plugins/chat/app/services/chat/leave_channel.rb@@ -17,16 +17,14 @@ module Chat# @param [Integer] channel_id of the channel# @return [Service::Base::Context]- contract- model :channel- step :leave- step :recompute_users_count-- # @!visibility private- class Contract+ contract doattribute :channel_id, :integer+validates :channel_id, presence: trueend+ model :channel+ step :leave+ step :recompute_users_countprivatediff --git a/plugins/chat/app/services/chat/list_channel_messages.rb b/plugins/chat/app/services/chat/list_channel_messages.rbindex 62b3770ccad..1ec134f8e98 100644--- a/plugins/chat/app/services/chat/list_channel_messages.rb+++ b/plugins/chat/app/services/chat/list_channel_messages.rb@@ -15,33 +15,9 @@ module Chat# @param [Guardian] guardian# @return [Service::Base::Context]- contract-- model :channel- policy :can_view_channel- step :fetch_optional_membership- step :enabled_threads?- step :determine_target_message_id- policy :target_message_exists- step :fetch_messages- step :fetch_thread_ids- step :fetch_tracking- step :fetch_thread_participants- step :fetch_thread_memberships- step :update_membership_last_viewed_at- step :update_user_last_channel-- class Contract+ contract doattribute :channel_id, :integer- validates :channel_id, presence: true-attribute :page_size, :integer- validates :page_size,- numericality: {- less_than_or_equal_to: ::Chat::MessagesQuery::MAX_PAGE_SIZE,- only_integer: true,- },- allow_nil: true# If this is not present, then we just fetch messages with page_size# and direction.@@ -50,6 +26,13 @@ module Chatattribute :fetch_from_last_read, :boolean # (optional)attribute :target_date, :string # (optional)+ validates :channel_id, presence: true+ validates :page_size,+ numericality: {+ less_than_or_equal_to: ::Chat::MessagesQuery::MAX_PAGE_SIZE,+ only_integer: true,+ },+ allow_nil: truevalidates :direction,inclusion: {in: Chat::MessagesQuery::VALID_DIRECTIONS,@@ -57,14 +40,28 @@ module Chatallow_nil: trueend+ model :channel+ policy :can_view_channel+ model :membership, optional: true+ step :enabled_threads?+ step :determine_target_message_id+ policy :target_message_exists+ step :fetch_messages+ step :fetch_thread_ids+ step :fetch_tracking+ step :fetch_thread_participants+ step :fetch_thread_memberships+ step :update_membership_last_viewed_at+ step :update_user_last_channel+privatedef fetch_channel(contract:)::Chat::Channel.includes(:chatable).find_by(id: contract.channel_id)end- def fetch_optional_membership(channel:, guardian:)- context.membership = channel.membership_for(guardian.user)+ def fetch_membership(channel:, guardian:)+ channel.membership_for(guardian.user)enddef enabled_threads?(channel:)diff --git a/plugins/chat/app/services/chat/list_channel_thread_messages.rb b/plugins/chat/app/services/chat/list_channel_thread_messages.rbindex 152e4268678..63fc584ff57 100644--- a/plugins/chat/app/services/chat/list_channel_thread_messages.rb+++ b/plugins/chat/app/services/chat/list_channel_thread_messages.rb@@ -15,19 +15,8 @@ module Chat# @option optional_params [Integer] thread_id# @return [Service::Base::Context]- contract-- model :thread- policy :can_view_thread- step :fetch_optional_membership- step :determine_target_message_id- policy :target_message_exists- step :fetch_messages-- class Contract+ contract doattribute :thread_id, :integer- validates :thread_id, presence: true-# If this is not present, then we just fetch messages with page_size# and direction.attribute :target_message_id, :integer # (optional)@@ -38,6 +27,7 @@ module Chatattribute :fetch_from_first_message, :boolean # (optional)attribute :target_date, :string # (optional)+ validates :thread_id, presence: truevalidates :direction,inclusion: {in: Chat::MessagesQuery::VALID_DIRECTIONS,@@ -50,13 +40,15 @@ module Chat},allow_nil: trueend+ model :thread+ policy :can_view_thread+ model :membership, optional: true+ step :determine_target_message_id+ policy :target_message_exists+ model :messages, optional: trueprivate- def fetch_optional_membership(thread:, guardian:)- context.membership = thread.membership_for(guardian.user)- end-def fetch_thread(contract:)::Chat::Thread.strict_loading.includes(channel: :chatable).find_by(id: contract.thread_id)end@@ -65,6 +57,10 @@ module Chatguardian.user == Discourse.system_user || guardian.can_preview_chat_channel?(thread.channel)end+ def fetch_membership(thread:, guardian:)+ thread.membership_for(guardian.user)+ end+def determine_target_message_id(contract:, membership:, guardian:, thread:)if contract.fetch_from_last_messagecontext.target_message_id = thread.last_message_id@@ -106,7 +102,7 @@ module Chatcontext.can_load_more_past = messages_data[:can_load_more_past]context.can_load_more_future = messages_data[:can_load_more_future]- context.messages = [+ [messages_data[:messages],messages_data[:past_messages]&.reverse,messages_data[:target_message],diff --git a/plugins/chat/app/services/chat/lookup_channel_threads.rb b/plugins/chat/app/services/chat/lookup_channel_threads.rbindex 261f35bb916..2c57dc76444 100644--- a/plugins/chat/app/services/chat/lookup_channel_threads.rb+++ b/plugins/chat/app/services/chat/lookup_channel_threads.rb@@ -24,7 +24,19 @@ module Chat# @param [Integer] offset# @return [Service::Base::Context]- contract+ contract do+ attribute :channel_id, :integer+ attribute :limit, :integer+ attribute :offset, :integer++ validates :channel_id, presence: true+ validates :limit,+ numericality: {+ less_than_or_equal_to: THREADS_LIMIT,+ only_integer: true,+ },+ allow_nil: true+ endstep :set_limitstep :set_offsetmodel :channel@@ -36,22 +48,6 @@ module Chatstep :fetch_participantsstep :build_load_more_url- # @!visibility private- class Contract- attribute :channel_id, :integer- validates :channel_id, presence: true-- attribute :limit, :integer- validates :limit,- numericality: {- less_than_or_equal_to: THREADS_LIMIT,- only_integer: true,- },- allow_nil: true-- attribute :offset, :integer- end-privatedef set_limit(contract:)diff --git a/plugins/chat/app/services/chat/lookup_thread.rb b/plugins/chat/app/services/chat/lookup_thread.rbindex 937993bfcd5..f8aa427d3b5 100644--- a/plugins/chat/app/services/chat/lookup_thread.rb+++ b/plugins/chat/app/services/chat/lookup_thread.rb@@ -16,20 +16,17 @@ module Chat# @param [Guardian] guardian# @return [Service::Base::Context]- contract- model :thread, :fetch_thread- policy :invalid_access- policy :threading_enabled_for_channel- step :fetch_membership- step :fetch_participants-- # @!visibility private- class Contract+ contract doattribute :thread_id, :integerattribute :channel_id, :integervalidates :thread_id, :channel_id, presence: trueend+ model :thread+ policy :invalid_access+ policy :threading_enabled_for_channel+ model :membership, optional: true+ model :participants, optional: trueprivate@@ -50,11 +47,11 @@ module Chatenddef fetch_membership(thread:, guardian:)- context.membership = thread.membership_for(guardian.user)+ thread.membership_for(guardian.user)enddef fetch_participants(thread:)- context.participants = ::Chat::ThreadParticipantQuery.call(thread_ids: [thread.id])[thread.id]+ ::Chat::ThreadParticipantQuery.call(thread_ids: [thread.id])[thread.id]endendenddiff --git a/plugins/chat/app/services/chat/lookup_user_threads.rb b/plugins/chat/app/services/chat/lookup_user_threads.rbindex 75d311e1553..571c9f7c7d1 100644--- a/plugins/chat/app/services/chat/lookup_user_threads.rb+++ b/plugins/chat/app/services/chat/lookup_user_threads.rb@@ -20,7 +20,10 @@ module Chat# @param [Integer] offset# @return [Service::Base::Context]- contract+ contract do+ attribute :limit, :integer+ attribute :offset, :integer+ endstep :set_limitstep :set_offsetmodel :threads@@ -29,12 +32,6 @@ module Chatstep :fetch_participantsstep :build_load_more_url- # @!visibility private- class Contract- attribute :limit, :integer- attribute :offset, :integer- end-privatedef set_limit(contract:)diff --git a/plugins/chat/app/services/chat/mark_thread_title_prompt_seen.rb b/plugins/chat/app/services/chat/mark_thread_title_prompt_seen.rbindex bd102747818..4a03d07febf 100644--- a/plugins/chat/app/services/chat/mark_thread_title_prompt_seen.rb+++ b/plugins/chat/app/services/chat/mark_thread_title_prompt_seen.rb@@ -21,19 +21,16 @@ module Chat# @param [Guardian] guardian# @return [Service::Base::Context]- contract- model :thread- policy :threading_enabled_for_channel- policy :can_view_channel- transaction { step :create_or_update_membership }-- # @!visibility private- class Contract+ contract doattribute :thread_id, :integerattribute :channel_id, :integervalidates :thread_id, :channel_id, presence: trueend+ model :thread+ policy :threading_enabled_for_channel+ policy :can_view_channel+ transaction { step :create_or_update_membership }privatediff --git a/plugins/chat/app/services/chat/restore_message.rb b/plugins/chat/app/services/chat/restore_message.rbindex d5bf0d835fe..757d672ba4c 100644--- a/plugins/chat/app/services/chat/restore_message.rb+++ b/plugins/chat/app/services/chat/restore_message.rb@@ -17,7 +17,13 @@ module Chat# @param [Guardian] guardian# @return [Service::Base::Context]- contract+ contract do+ attribute :message_id, :integer+ attribute :channel_id, :integer++ validates :message_id, presence: true+ validates :channel_id, presence: true+ endmodel :messagepolicy :invalid_accesstransaction do@@ -27,14 +33,6 @@ module Chatendstep :publish_events- # @!visibility private- class Contract- attribute :message_id, :integer- attribute :channel_id, :integer- validates :message_id, presence: true- validates :channel_id, presence: true- end-privatedef fetch_message(contract:)diff --git a/plugins/chat/app/services/chat/search_chatable.rb b/plugins/chat/app/services/chat/search_chatable.rbindex 37566821905..47c29aeb168 100644--- a/plugins/chat/app/services/chat/search_chatable.rb+++ b/plugins/chat/app/services/chat/search_chatable.rb@@ -16,16 +16,7 @@ module Chat# @param [Guardian] guardian# @return [Service::Base::Context]- contract- step :clean_term- model :memberships, optional: true- model :users, optional: true- model :groups, optional: true- model :category_channels, optional: true- model :direct_message_channels, optional: true-- # @!visibility private- class Contract+ contract doattribute :term, :string, default: ""attribute :include_users, :boolean, default: trueattribute :include_groups, :boolean, default: true@@ -33,6 +24,12 @@ module Chatattribute :include_direct_message_channels, :boolean, default: trueattribute :excluded_memberships_channel_id, :integerend+ step :clean_term+ model :memberships, optional: true+ model :users, optional: true+ model :groups, optional: true+ model :category_channels, optional: true+ model :direct_message_channels, optional: trueprivatediff --git a/plugins/chat/app/services/chat/stop_message_streaming.rb b/plugins/chat/app/services/chat/stop_message_streaming.rbindex 730c93b749d..ce35b04b70d 100644--- a/plugins/chat/app/services/chat/stop_message_streaming.rb+++ b/plugins/chat/app/services/chat/stop_message_streaming.rb@@ -13,7 +13,11 @@ module Chat# @param [Integer] message_id# @param [Guardian] guardian# @return [Service::Base::Context]- contract+ contract do+ attribute :message_id, :integer++ validates :message_id, presence: true+ endmodel :messagestep :enforce_membershipmodel :membership@@ -21,13 +25,6 @@ module Chatstep :stop_message_streamingstep :publish_message_streaming_state- # @!visibility private- class Contract- attribute :message_id, :integer-- validates :message_id, presence: true- end-privatedef fetch_message(contract:)diff --git a/plugins/chat/app/services/chat/tracking_state.rb b/plugins/chat/app/services/chat/tracking_state.rbindex 5bfd53ffe2a..7704b29821f 100644--- a/plugins/chat/app/services/chat/tracking_state.rb+++ b/plugins/chat/app/services/chat/tracking_state.rb@@ -33,26 +33,17 @@ module Chat# @param [Guardian] guardian# @return [Service::Base::Context]- contract- step :cast_thread_and_channel_ids_to_integer- model :report-- # @!visibility private- class Contract- attribute :channel_ids, default: []- attribute :thread_ids, default: []+ contract do+ attribute :channel_ids, :array, default: []+ attribute :thread_ids, :array, default: []attribute :include_missing_memberships, default: falseattribute :include_threads, default: falseattribute :include_read, default: trueend+ model :reportprivate- def cast_thread_and_channel_ids_to_integer(contract:)- contract.thread_ids = contract.thread_ids.map(&:to_i)- contract.channel_ids = contract.channel_ids.map(&:to_i)- end-def fetch_report(contract:, guardian:)::Chat::TrackingStateReportQuery.call(guardian: guardian,diff --git a/plugins/chat/app/services/chat/trash_message.rb b/plugins/chat/app/services/chat/trash_message.rbindex 6bb8100bc1e..51be333c270 100644--- a/plugins/chat/app/services/chat/trash_message.rb+++ b/plugins/chat/app/services/chat/trash_message.rb@@ -17,7 +17,13 @@ module Chat# @param [Guardian] guardian# @return [Service::Base::Context]- contract+ contract do+ attribute :message_id, :integer+ attribute :channel_id, :integer++ validates :message_id, presence: true+ validates :channel_id, presence: true+ endmodel :messagepolicy :invalid_accesstransaction do@@ -29,14 +35,6 @@ module Chatendstep :publish_events- # @!visibility private- class Contract- attribute :message_id, :integer- attribute :channel_id, :integer- validates :message_id, presence: true- validates :channel_id, presence: true- end-privatedef fetch_message(contract:)diff --git a/plugins/chat/app/services/chat/trash_messages.rb b/plugins/chat/app/services/chat/trash_messages.rbindex 1593752e793..eb278cde763 100644--- a/plugins/chat/app/services/chat/trash_messages.rb+++ b/plugins/chat/app/services/chat/trash_messages.rb@@ -17,7 +17,13 @@ module Chat# @param [Guardian] guardian# @return [Service::Base::Context]- contract+ contract do+ attribute :channel_id, :integer+ attribute :message_ids, :array++ validates :channel_id, presence: true+ validates :message_ids, length: { minimum: 1, maximum: 50 }+ endmodel :messagespolicy :can_delete_all_chat_messagestransaction do@@ -29,14 +35,6 @@ module Chatendstep :publish_events- # @!visibility private- class Contract- attribute :channel_id, :integer- attribute :message_ids, :array- validates :channel_id, presence: true- validates :message_ids, length: { minimum: 1, maximum: 50 }- end-privatedef fetch_messages(contract:)diff --git a/plugins/chat/app/services/chat/unfollow_channel.rb b/plugins/chat/app/services/chat/unfollow_channel.rbindex 5f58c3ebb96..851ef0260d0 100644--- a/plugins/chat/app/services/chat/unfollow_channel.rb+++ b/plugins/chat/app/services/chat/unfollow_channel.rb@@ -17,15 +17,13 @@ module Chat# @param [Integer] channel_id of the channel# @return [Service::Base::Context]- contract- model :channel- step :unfollow-- # @!visibility private- class Contract+ contract doattribute :channel_id, :integer+validates :channel_id, presence: trueend+ model :channel+ step :unfollowprivatediff --git a/plugins/chat/app/services/chat/update_channel.rb b/plugins/chat/app/services/chat/update_channel.rbindex fbf920fbd89..38a3faad535 100644--- a/plugins/chat/app/services/chat/update_channel.rb+++ b/plugins/chat/app/services/chat/update_channel.rb@@ -32,17 +32,9 @@ module Chat# @option params_to_edit [Boolean] allow_channel_wide_mentions Allow the use of @here and @all in the channel.# @return [Service::Base::Context]- model :channel, :fetch_channel+ model :channelpolicy :check_channel_permission- contract default_values_from: :channel- step :update_channel- step :mark_all_threads_as_read_if_needed- step :update_site_settings_if_needed- step :publish_channel_update- step :auto_join_users_if_needed-- # @!visibility private- class Contract+ contract(default_values_from: :channel) doattribute :name, :stringattribute :description, :stringattribute :slug, :string@@ -56,6 +48,11 @@ module Chat)endend+ step :update_channel+ step :mark_all_threads_as_read_if_needed+ step :update_site_settings_if_needed+ step :publish_channel_update+ step :auto_join_users_if_neededprivatediff --git a/plugins/chat/app/services/chat/update_channel_status.rb b/plugins/chat/app/services/chat/update_channel_status.rbindex 8719406d07c..1816599846c 100644--- a/plugins/chat/app/services/chat/update_channel_status.rb+++ b/plugins/chat/app/services/chat/update_channel_status.rb@@ -16,15 +16,13 @@ module Chat# @return [Service::Base::Context]model :channel, :fetch_channel- contract- policy :check_channel_permission- step :change_status-- # @!visibility private- class Contract+ contract doattribute :status+validates :status, inclusion: { in: Chat::Channel.editable_statuses.keys }end+ policy :check_channel_permission+ step :change_statusprivatediff --git a/plugins/chat/app/services/chat/update_message.rb b/plugins/chat/app/services/chat/update_message.rbindex 2bf2ecbb746..8bbc5fc36b2 100644--- a/plugins/chat/app/services/chat/update_message.rb+++ b/plugins/chat/app/services/chat/update_message.rb@@ -15,7 +15,17 @@ module Chat# @param message [String]# @param upload_ids [Array<Integer>] IDs of uploaded documents- contract+ contract do+ attribute :message_id, :string+ attribute :message, :string+ attribute :upload_ids, :array+ attribute :streaming, :boolean, default: false+ attribute :strip_whitespaces, :boolean, default: true+ attribute :process_inline, :boolean, default: Rails.env.test?++ validates :message_id, presence: true+ validates :message, presence: true, if: -> { upload_ids.blank? }+ endmodel :messagemodel :uploads, optional: truestep :enforce_membership@@ -23,7 +33,6 @@ module Chatpolicy :can_modify_channel_messagepolicy :can_modify_messagestep :clean_message-transaction dostep :modify_messagestep :update_excerpt@@ -32,22 +41,6 @@ module Chatstep :publishend- class Contract- attribute :message_id, :string- validates :message_id, presence: true-- attribute :message, :string- validates :message, presence: true, if: -> { upload_ids.blank? }-- attribute :upload_ids, :array-- attribute :streaming, :boolean, default: false-- attribute :strip_whitespaces, :boolean, default: true-- attribute :process_inline, :boolean, default: Rails.env.test?- end-privatedef enforce_membership(guardian:, message:)diff --git a/plugins/chat/app/services/chat/update_thread.rb b/plugins/chat/app/services/chat/update_thread.rbindex dccd3160986..3d0db4a1059 100644--- a/plugins/chat/app/services/chat/update_thread.rb+++ b/plugins/chat/app/services/chat/update_thread.rb@@ -19,22 +19,19 @@ module Chat# @option params_to_edit [String,nil] title# @return [Service::Base::Context]- contract- model :thread, :fetch_thread- policy :can_view_channel- policy :can_edit_thread- policy :threading_enabled_for_channel- step :update- step :publish_metadata-- # @!visibility private- class Contract+ contract doattribute :thread_id, :integerattribute :title, :stringvalidates :thread_id, presence: truevalidates :title, length: { maximum: Chat::Thread::MAX_TITLE_LENGTH }end+ model :thread+ policy :can_view_channel+ policy :can_edit_thread+ policy :threading_enabled_for_channel+ step :update+ step :publish_metadataprivatediff --git a/plugins/chat/app/services/chat/update_thread_notification_settings.rb b/plugins/chat/app/services/chat/update_thread_notification_settings.rbindex 6d7b1266f13..4cdeae35a68 100644--- a/plugins/chat/app/services/chat/update_thread_notification_settings.rb+++ b/plugins/chat/app/services/chat/update_thread_notification_settings.rb@@ -23,25 +23,21 @@ module Chat# @param [Guardian] guardian# @return [Service::Base::Context]- contract- model :thread, :fetch_thread- policy :can_view_channel- policy :threading_enabled_for_channel- transaction { step :create_or_update_membership }-- # @!visibility private- class Contract+ contract doattribute :thread_id, :integerattribute :channel_id, :integerattribute :notification_level, :integervalidates :thread_id, :channel_id, :notification_level, presence: true-validates :notification_level,inclusion: {in: Chat::UserChatThreadMembership.notification_levels.values,}end+ model :thread, :fetch_thread+ policy :can_view_channel+ policy :threading_enabled_for_channel+ transaction { step :create_or_update_membership }privatediff --git a/plugins/chat/app/services/chat/update_user_channel_last_read.rb b/plugins/chat/app/services/chat/update_user_channel_last_read.rbindex 94600d55ab8..45629daa820 100644--- a/plugins/chat/app/services/chat/update_user_channel_last_read.rb+++ b/plugins/chat/app/services/chat/update_user_channel_last_read.rb@@ -15,7 +15,12 @@ module Chat# @param [Guardian] guardian# @return [Service::Base::Context]- contract+ contract do+ attribute :message_id, :integer+ attribute :channel_id, :integer++ validates :message_id, :channel_id, presence: true+ endmodel :channelmodel :membershippolicy :invalid_access@@ -27,14 +32,6 @@ module Chatendstep :publish_new_last_read_to_clients- # @!visibility private- class Contract- attribute :message_id, :integer- attribute :channel_id, :integer-- validates :message_id, :channel_id, presence: true- end-privatedef fetch_channel(contract:)diff --git a/plugins/chat/app/services/chat/update_user_thread_last_read.rb b/plugins/chat/app/services/chat/update_user_thread_last_read.rbindex 5004416503a..6fcb9d0e73d 100644--- a/plugins/chat/app/services/chat/update_user_thread_last_read.rb+++ b/plugins/chat/app/services/chat/update_user_thread_last_read.rb@@ -17,7 +17,13 @@ module Chat# @param [Guardian] guardian# @return [Service::Base::Context]- contract+ contract do+ attribute :channel_id, :integer+ attribute :thread_id, :integer+ attribute :message_id, :integer++ validates :thread_id, :channel_id, presence: true+ endmodel :threadpolicy :invalid_accessmodel :membership@@ -27,15 +33,6 @@ module Chatstep :mark_thread_readstep :publish_new_last_read_to_clients- # @!visibility private- class Contract- attribute :channel_id, :integer- attribute :thread_id, :integer- attribute :message_id, :integer-- validates :thread_id, :channel_id, presence: true- end-privatedef fetch_thread(contract:)diff --git a/plugins/chat/app/services/chat/upsert_draft.rb b/plugins/chat/app/services/chat/upsert_draft.rbindex 392ef5621b3..d6b4a5db889 100644--- a/plugins/chat/app/services/chat/upsert_draft.rb+++ b/plugins/chat/app/services/chat/upsert_draft.rb@@ -20,20 +20,17 @@ module Chat# @param [String] json object as string containing the data of the draft (message, uploads, replyToMsg and editing keys)# @option [Integer] thread_id of the channel# @return [Service::Base::Context]- contract- model :channel- policy :can_upsert_draft- step :check_thread_exists- step :upsert_draft-- # @!visibility private- class Contract+ contract doattribute :channel_id, :integervalidates :channel_id, presence: trueattribute :thread_id, :integerattribute :data, :stringend+ model :channel+ policy :can_upsert_draft+ step :check_thread_exists+ step :upsert_draftprivatediff --git a/spec/lib/service/runner_spec.rb b/spec/lib/service/runner_spec.rbindex 1d8cd6680bb..b9d98c66b03 100644--- a/spec/lib/service/runner_spec.rb+++ b/spec/lib/service/runner_spec.rb@@ -38,18 +38,17 @@ RSpec.describe Service::Runner doclass FailedContractServiceinclude Service::Base- class Contract+ contract doattribute :test+validates :test, presence: trueend-- contractendclass SuccessContractServiceinclude Service::Base- contract+ contract {}endclass FailureWithModelServicediff --git a/spec/lib/steps_inspector_spec.rb b/spec/lib/steps_inspector_spec.rbindex 38227239a7d..dcc0917460b 100644--- a/spec/lib/steps_inspector_spec.rb+++ b/spec/lib/steps_inspector_spec.rb@@ -6,18 +6,16 @@ RSpec.describe StepsInspector domodel :modelpolicy :policy- contract+ contract do+ attribute :parameter++ validates :parameter, presence: true+ endtransaction dostep :in_transaction_step_1step :in_transaction_step_2endstep :final_step-- class Contract- attribute :parameter-- validates :parameter, presence: true- endendsubject(:inspector) { described_class.new(result) }