Skip to content

OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub

Introduce base service and adds logging to CopyProjectFolder

Marcello Rocha5b980d10811a
diff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/copy_template_folder_command.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/copy_template_folder_command.rb
index f16d41e5997..c4cb0511b48 100644
--- a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/copy_template_folder_command.rb
+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/copy_template_folder_command.rb
@@ -31,6 +31,8 @@ module Storages
module StorageInteraction
module Nextcloud
class CopyTemplateFolderCommand
+ include TaggedLogging
+
using ServiceResultRefinements
def self.call(auth_strategy:, storage:, source_path:, destination_path:)
@@ -43,24 +45,25 @@ module Storages
end
def call(auth_strategy:, source_path:, destination_path:)
- valid_input_result = validate_inputs(source_path, destination_path).on_failure { |failure| return failure }
+ with_tagged_logger do
+ valid_input_result = validate_inputs(source_path, destination_path).on_failure { return _1 }
- remote_urls = build_origin_urls(**valid_input_result.result)
+ remote_urls = build_origin_urls(**valid_input_result.result)
- ensure_remote_folder_does_not_exist(auth_strategy, remote_urls[:destination_url]).on_failure do |failure|
- return failure
- end
+ ensure_remote_folder_does_not_exist(auth_strategy, remote_urls[:destination_url]).on_failure { return _1 }
- copy_folder(auth_strategy, **remote_urls).on_failure { |failure| return failure }
+ copy_folder(auth_strategy, **remote_urls).on_failure { return _1 }
- get_folder_id(valid_input_result.result[:destination_path])
+ get_folder_id(valid_input_result.result[:destination_path])
+ end
end
private
def validate_inputs(source_path, destination_path)
+ info "Validating #{source_path} and #{destination_path}"
if source_path.blank? || destination_path.blank?
- return Util.error(:error, "Source and destination paths must be present.")
+ return Util.error(:missing_paths, "Source and destination paths must be present.")
end
ServiceResult.success(result: { source_path:, destination_path: })
@@ -74,27 +77,29 @@ module Storages
end
def ensure_remote_folder_does_not_exist(auth_strategy, destination_url)
+ info "Checking if #{destination_url} does not already exists."
response = Authentication[auth_strategy].call(storage: @storage) { |http| http.head(destination_url) }
case response
in { status: 200..299 }
ServiceResult.failure(result: :conflict,
errors: Util.storage_error(
- response:, code: :conflict, source: self.class,
+ response:, code: :conflict, source:,
log_message: "The copy would overwrite an already existing folder"
))
in { status: 401 }
ServiceResult.failure(result: :unauthorized,
- errors: Util.storage_error(response:, code: :unauthorized, source: self.class))
+ errors: Util.storage_error(response:, code: :unauthorized, source:))
in { status: 404 }
ServiceResult.success
else
ServiceResult.failure(result: :error,
- errors: Util.storage_error(response:, code: :error, source: self.class))
+ errors: Util.storage_error(response:, code: :error, source:))
end
end
def copy_folder(auth_strategy, source_url:, destination_url:)
+ info "Copying #{source_url} to #{destination_url}"
response = Authentication[auth_strategy].call(storage: @storage) do |http|
http.request("COPY", source_url, headers: { "Destination" => destination_url, "Depth" => "infinity" })
end
@@ -102,9 +107,8 @@ module Storages
handle_response(response)
end
+ # rubocop:disable Metrics/AbcSize
def handle_response(response)
- source = self.class
-
case response
in { status: 200..299 }
ServiceResult.success(message: "Folder was successfully copied")
@@ -129,6 +133,7 @@ module Storages
errors: Util.storage_error(response:, code: :error, source:))
end
end
+ # rubocop:enable Metrics/AbcSize
def get_folder_id(destination_path)
call = Registry
@@ -137,6 +142,8 @@ module Storages
call.map { |result| @data.with(id: result[destination_path]["fileid"]) }
end
+
+ def source = self.class
end
end
end
diff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/one_drive/copy_template_folder_command.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/one_drive/copy_template_folder_command.rb
index 04408181ceb..abcb240a1f4 100644
--- a/modules/storages/app/common/storages/peripherals/storage_interaction/one_drive/copy_template_folder_command.rb
+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/one_drive/copy_template_folder_command.rb
@@ -33,6 +33,8 @@ module Storages
module StorageInteraction
module OneDrive
class CopyTemplateFolderCommand
+ include TaggedLogging
+
def self.call(auth_strategy:, storage:, source_path:, destination_path:)
if source_path.blank? || destination_path.blank?
return ServiceResult.failure(
@@ -51,10 +53,13 @@ module Storages
end
def call(auth_strategy:, source_location:, destination_name:)
- Authentication[auth_strategy].call(storage: @storage) do |httpx|
- handle_response(
- httpx.post(url_for(source_location) + query, json: { name: destination_name })
- )
+ with_tagged_logger do
+ info "Requesting Copy of folder #{source_location} to #{destination_name}"
+ Authentication[auth_strategy].call(storage: @storage) do |httpx|
+ handle_response(
+ httpx.post(url_for(source_location) + query, json: { name: destination_name })
+ )
+ end
end
end
diff --git a/modules/storages/app/common/storages/tagged_logging.rb b/modules/storages/app/common/storages/tagged_logging.rb
index 33f05ae5298..e64939d27f8 100644
--- a/modules/storages/app/common/storages/tagged_logging.rb
+++ b/modules/storages/app/common/storages/tagged_logging.rb
@@ -32,7 +32,7 @@ module Storages
module TaggedLogging
delegate :info, :error, to: :logger
- # @param tag [String, Array<String>] the tag or list of tags to annotate the logs with
+ # @param tag [Class, String, Array<Class, String>] the tag or list of tags to annotate the logs with
# @yield [Logger]
def with_tagged_logger(tag = self.class, &)
logger.tagged(*tag, &)
diff --git a/modules/storages/app/services/storages/base_service.rb b/modules/storages/app/services/storages/base_service.rb
new file mode 100644
index 00000000000..df3e08f70ff
--- /dev/null
+++ b/modules/storages/app/services/storages/base_service.rb
@@ -0,0 +1,73 @@
+# frozen_string_literal: true
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2023 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See COPYRIGHT and LICENSE files for more details.
+#++
+
+module Storages
+ class BaseService
+ extend ActiveModel::Naming
+ extend ActiveModel::Translation
+
+ include TaggedLogging
+
+ class << self
+ def i18n_key=(value)
+ @yaml_key = value
+ end
+
+ def i18n_key = @yaml_key || class_name
+
+ def i18n_scope = "services"
+
+ def model_name = ActiveModel::Name.new(self, Storages, i18n_key)
+ end
+
+ def initialize
+ @result = ServiceResult.success(errors: ActiveModel::Errors.new(self))
+ end
+
+ def read_attribute_for_validation(attr) = attr
+
+ private
+
+ # @param attribute [Symbol] attribute to which the error will be tied to
+ # @param storage_error [Storages::StorageError] an StorageError instance
+ # @param options [Hash{Symbol => Object}] optional extra parameters for the message generation
+ # @return ServiceResult
+ def add_error(attribute, storage_error, options: {})
+ case storage_error.code
+ when :error, :unauthorized
+ @result.errors.add(:base, storage_error.code, **options)
+ else
+ @result.errors.add(attribute, storage_error.code, **options)
+ end
+
+ @result
+ end
+ end
+end
diff --git a/modules/storages/app/services/storages/nextcloud_group_folder_properties_sync_service.rb b/modules/storages/app/services/storages/nextcloud_group_folder_properties_sync_service.rb
index 447bdc8f50f..16b7384a40c 100644
--- a/modules/storages/app/services/storages/nextcloud_group_folder_properties_sync_service.rb
+++ b/modules/storages/app/services/storages/nextcloud_group_folder_properties_sync_service.rb
@@ -29,11 +29,7 @@
#++
module Storages
- class NextcloudGroupFolderPropertiesSyncService
- extend ActiveModel::Naming
- extend ActiveModel::Translation
- include TaggedLogging
-
+ class NextcloudGroupFolderPropertiesSyncService < BaseService
using Peripherals::ServiceResultRefinements
PERMISSIONS_MAP = { read_files: 1, write_files: 2, create_files: 4, delete_files: 8, share_files: 16 }.freeze
@@ -45,19 +41,15 @@ module Storages
"nextcloud.queries.group_users", "nextcloud.queries.file_ids", "nextcloud.authentication.userless",
"nextcloud.commands.add_user_to_group", "nextcloud.commands.remove_user_from_group"]
- def self.i18n_scope = "services"
- def self.model_name = ActiveModel::Name.new(self, Storages, "NextcloudSyncService")
+ def self.i18n_key = "NextcloudSyncService"
def self.call(storage)
new(storage).call
end
- def read_attribute_for_validation(attr) = attr
-
def initialize(storage, **)
super(**)
@storage = storage
- @result = ServiceResult.success(errors: ActiveModel::Errors.new(self))
end
def call
@@ -76,21 +68,6 @@ module Storages
@result
end
- # @param attribute [Symbol] attribute to which the error will be tied to
- # @param storage_error [Storages::StorageError] an StorageError instance
- # @param options [Hash{Symbol => Object}] optional extra parameters for the message generation
- # @return ServiceResult
- def add_error(attribute, storage_error, options: {})
- case storage_error.code
- when :error, :unauthorized
- @result.errors.add(:base, storage_error.code, **options)
- else
- @result.errors.add(attribute, storage_error.code, **options)
- end
-
- @result
- end
-
# @return [ServiceResult]
def prepare_remote_folders
info "Preparing the remote group folder #{@storage.group_folder}"
diff --git a/modules/storages/app/services/storages/one_drive_managed_folder_sync_service.rb b/modules/storages/app/services/storages/one_drive_managed_folder_sync_service.rb
index 166df565b89..7aee8b51bc1 100644
--- a/modules/storages/app/services/storages/one_drive_managed_folder_sync_service.rb
+++ b/modules/storages/app/services/storages/one_drive_managed_folder_sync_service.rb
@@ -29,10 +29,7 @@
#++
module Storages
- class OneDriveManagedFolderSyncService
- extend ActiveModel::Naming
- extend ActiveModel::Translation
- include TaggedLogging
+ class OneDriveManagedFolderSyncService < BaseService
include Injector["one_drive.commands.create_folder", "one_drive.commands.rename_file",
"one_drive.commands.set_permissions", "one_drive.queries.files", "one_drive.authentication.userless"]
@@ -40,8 +37,7 @@ module Storages
OP_PERMISSIONS = %i[read_files write_files create_files delete_files share_files].freeze
- def self.i18n_scope = "services"
- def self.model_name = ActiveModel::Name.new(self, Storages, "OneDriveSyncService")
+ def self.i18n_key = "OneDriveSyncService"
def self.call(storage)
new(storage).call
@@ -53,8 +49,6 @@ module Storages
@result = ServiceResult.success(errors: ActiveModel::Errors.new(self))
end
- def read_attribute_for_validation(attr) = attr
-
def call
with_tagged_logger([self.class.name, "storage-#{@storage.id}"]) do
return unless @storage.automatic_management_enabled?
diff --git a/modules/storages/app/services/storages/project_storages/copy_project_folders_service.rb b/modules/storages/app/services/storages/project_storages/copy_project_folders_service.rb
index 68f4b41e820..879e9f3215e 100644
--- a/modules/storages/app/services/storages/project_storages/copy_project_folders_service.rb
+++ b/modules/storages/app/services/storages/project_storages/copy_project_folders_service.rb
@@ -30,28 +30,62 @@
module Storages
module ProjectStorages
- class CopyProjectFoldersService
+ class CopyProjectFoldersService < BaseService
+ using Peripherals::ServiceResultRefinements
+
def self.call(source:, target:)
new.call(source, target)
end
def initialize
+ super
@data = Peripherals::StorageInteraction::ResultData::CopyTemplateFolder
- .new(id: nil, polling_url: nil, requires_polling: false)
+ .new(id: nil, polling_url: nil, requires_polling: false)
end
+ # rubocop:disable Metrics/AbcSize
def call(source, target)
- return ServiceResult.success(result: @data) if source.project_folder_inactive?
- return ServiceResult.success(result: @data.with(id: source.project_folder_id)) if source.project_folder_manual?
+ with_tagged_logger([self.class, source&.id, target&.id]) do
+ return @result.map { @data } if non_managed_project_folder?(source)
+ return @result.map { @data.with(id: source.project_folder_id) } if manually_managed_source?(source)
+
+ info "Initiating copy of project folder #{source.managed_project_folder_path} to #{target.managed_project_folder_path}"
+ copy_result = initiate_copy(source.storage, source.project_folder_location, target.managed_project_folder_path)
+ @result.map { copy_result.result }
+ end
+ end
+ # rubocop:enable Metrics/AbcSize
- auth_strategy = Peripherals::Registry.resolve("#{source.storage.short_provider_type}.authentication.userless").call
+ private
+
+ def non_managed_project_folder?(source)
+ if source.project_folder_inactive?
+ info "#{source.storage.name} on #{source.project.name} is inactive. Skipping copy."
+ true
+ end
+ end
+ def manually_managed_source?(source)
+ if source.project_folder_manual?
+ info "#{source.storage.name} on #{source.project.name} is set to manual. Skipping copy."
+ true
+ end
+ end
+
+ def initiate_copy(storage, source_path, destination_path)
Peripherals::Registry
- .resolve("#{source.storage.short_provider_type}.commands.copy_template_folder")
- .call(auth_strategy:,
- storage: source.storage,
- source_path: source.project_folder_location,
- destination_path: target.managed_project_folder_path)
+ .resolve("#{storage.short_provider_type}.commands.copy_template_folder")
+ .call(auth_strategy: auth_strategy(storage.short_provider_type),
+ storage:,
+ source_path:,
+ destination_path:).on_failure do |failed|
+ log_storage_error(failed.errors)
+ add_error(:base, failed.errors, options: { destination_path:, source_path: }).fail!
+ end
+ end
+
+ def auth_strategy(short_provider_type)
+ Peripherals::Registry.resolve("#{short_provider_type}.authentication.userless").call
end
end
end
diff --git a/modules/storages/config/locales/en.yml b/modules/storages/config/locales/en.yml
index 60422aa37c5..6f3db0eeef6 100644
--- a/modules/storages/config/locales/en.yml
+++ b/modules/storages/config/locales/en.yml
@@ -87,6 +87,12 @@ en:
rename_project_folder: 'Rename managed project Folder:'
errors:
models:
+ copy_project_folders_service:
+ conflict: "The folder %{destination_path} already exists. Interrupting process to avoid overwrites."
+ not_found: "The source template location %{source_path} wasn't found."
+ unauthorized: "OpenProject could not authenticate with the Storage Provider. Please check your storage configuration"
+ forbidden: "OpenProject could not access the source folder. Please check your permissions configuration on the Storage Provider"
+ error: "An unexpected error occurred. Please check OpenProject logs for more information or contact an administrator"
nextcloud_sync_service:
attributes:
add_user_to_group:
diff --git a/modules/storages/spec/services/storages/project_storages/copy_project_folders_service_spec.rb b/modules/storages/spec/services/storages/project_storages/copy_project_folders_service_spec.rb
index 6e4feef1bf3..05f2619d4ef 100644
--- a/modules/storages/spec/services/storages/project_storages/copy_project_folders_service_spec.rb
+++ b/modules/storages/spec/services/storages/project_storages/copy_project_folders_service_spec.rb
@@ -32,6 +32,8 @@ require "spec_helper"
require_module_spec_helper
RSpec.describe Storages::ProjectStorages::CopyProjectFoldersService, :webmock do
+ using Storages::Peripherals::ServiceResultRefinements
+
let(:storage) { create(:nextcloud_storage, :as_automatically_managed) }
let(:target) { create(:project_storage, storage:) }
let(:system_user) { create(:system) }
@@ -84,6 +86,13 @@ RSpec.describe Storages::ProjectStorages::CopyProjectFoldersService, :webmock do
context "with non-managed project folders" do
let(:source) { create(:project_storage, project_folder_id: nil, project_folder_mode: "inactive") }
+ it "logs the occurrence" do
+ allow(Rails.logger).to receive(:info)
+ service.call(source:, target:)
+ expect(Rails.logger)
+ .to have_received(:info).with("#{source.storage.name} on #{source.project.name} is inactive. Skipping copy.")
+ end
+
it "succeeds" do
expect(service.call(source:, target:)).to be_success
end
@@ -94,4 +103,68 @@ RSpec.describe Storages::ProjectStorages::CopyProjectFoldersService, :webmock do
expect(result.result.id).to eq(source.project_folder_id)
end
end
+
+ describe "error messages" do
+ let(:source) { create(:project_storage, :as_automatically_managed, storage:) }
+
+ it "the target folder already exists" do
+ Storages::Peripherals::Registry
+ .stub("#{source.storage.short_provider_type}.commands.copy_template_folder",
+ ->(_) { build_failure(:conflict) })
+
+ result = service.call(source:, target:)
+
+ expect(result).to be_failure
+ expect(result.errors[:base])
+ .to contain_exactly(I18n.t("services.errors.models.copy_project_folders_service.conflict",
+ destination_path: target.managed_project_folder_path))
+ end
+
+ it "source folder was not found" do
+ Storages::Peripherals::Registry
+ .stub("#{source.storage.short_provider_type}.commands.copy_template_folder",
+ ->(_) { build_failure(:not_found) })
+
+ result = service.call(source:, target:)
+
+ expect(result).to be_failure
+ expect(result.errors[:base])
+ .to contain_exactly(I18n.t("services.errors.models.copy_project_folders_service.not_found",
+ source_path: source.project_folder_location))
+ end
+
+ it "token is unauthorized to do the copy" do
+ Storages::Peripherals::Registry
+ .stub("#{source.storage.short_provider_type}.commands.copy_template_folder",
+ ->(_) { build_failure(:unauthorized) })
+
+ result = service.call(source:, target:)
+
+ expect(result).to be_failure
+ expect(result.errors[:base])
+ .to contain_exactly(I18n.t("services.errors.models.copy_project_folders_service.unauthorized"))
+ end
+
+ it "token has no access to the source folder" do
+ Storages::Peripherals::Registry
+ .stub("#{source.storage.short_provider_type}.commands.copy_template_folder",
+ ->(_) { build_failure(:forbidden) })
+
+ result = service.call(source:, target:)
+
+ expect(result).to be_failure
+ expect(result.errors[:base])
+ .to contain_exactly(I18n.t("services.errors.models.copy_project_folders_service.forbidden",
+ source_path: source.project_folder_location))
+ end
+ end
+
+ private
+
+ def build_failure(code)
+ response = "Response info"
+ storage_error = Storages::Peripherals::StorageInteraction::OneDrive::Util
+ .storage_error(response:, code:, source: described_class, log_message: "Log message for #{code}")
+ ServiceResult.failure(result: code, errors: storage_error)
+ end
end