Почтовый штемпель на локальном хосте и проблема постановки - PullRequest
0 голосов
/ 13 февраля 2019

После того, как я настроил использование службы postmark для отправки электронных писем, у меня возникают проблемы с development и staging envs.

Краткое объяснение : портмарк работает хорошов приведенных ниже ситуациях с 'ok' и при DeserializationError кажется, что активное задание не выполняется, потому что он проверяет, существует ли идентификатор пользователя в производственной базе данных.

Разработка env:

devise mailing -> ActiveJob::DeserializationError
deliver_later -> ActiveJob::DeserializationError
delover_now  -> ok 

Постановка env

devise mailing -> ActiveJob::DeserializationError
deliver_later -> ActiveJob::DeserializationError
delover_now  -> ok 

env

devise mailing -> ok
deliver_later -> ok
deliver_now -> ok

Длинное объяснение :

Когда я нахожусь на этих двух envs и запрашиваю devise инструкции подтверждения, он отправляет ссылку на этоэлектронное письмо с URL-адресом production с прикрепленным к нему токеном, указывающим на неправильную страницу.

Самое интригующее, что после того, как я отправил письмо с консоли envs для разработки или подготовки, и открыл панель управления sidekiq иЯ обнаружил, что когда на производстве нет идентификатора пользователя, связанного с идентификатором, который было отправлено по электронной почте для этого письма (из других envs), это почтовое сообщение завершается неудачно с этим сообщением:

Консоль:

> Rails.env
"development"
> @user.id
22
> UserMailer.welcome(@user).deliver_later

Ошибка Sidekiq:

ActiveJob :: DeserializationError: Ошибка при попытке десериализации аргументов: не удалось найти пользователя с 'id' = 22 * ​​1043 *

Консоль:

> Rails.env
"staging"
> @user.id
15
> UserMailer.welcome(@user).deliver_later

Ошибка Sidekiq:

ActiveJob :: DeserializationError: Ошибка при попытке десериализации аргументов: не удалось найти пользователя с 'id' = 15


Некоторые конфиги:

Rails 5.0.1
postmark (1.14.0)
postmark-rails (0.18.0)

production.rb

...
  config.action_mailer.delivery_method = :postmark
  config.action_mailer.postmark_settings = { :api_token => ENV["POSTMARK_API_KEY"] }
  config.action_mailer.default_url_options = { host: "www.mywebsite.com" }
...

development.rb

...
  config.action_mailer.delivery_method = :postmark
  config.action_mailer.postmark_settings = { :api_token => ENV["POSTMARK_API_KEY"] }
  config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
...

staging.rb

...
  config.action_mailer.delivery_method = :postmark
  config.action_mailer.postmark_settings = { :api_token => ENV["POSTMARK_API_KEY"] }
  config.action_mailer.default_url_options = { host: "website.herokuapp.com" }
...

sidekiq.yml

:concurrency: 3
:timeout: 60
:verbose: true
:queues:  
  - default
  - mailers

Объекты: во всех трех средах используется разный ключ API штемпеля.

UPDATE 1

Здесьthe development:

development.rb

Rails.application.configure do

  config.action_mailer.delivery_method = :postmark
  config.action_mailer.postmark_settings = { :api_token => ENV["POSTMARK_API_KEY"] }
  config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }

  config.cache_classes = false

  config.eager_load = false

  # Show full error reports.
  config.consider_all_requests_local = true

  # Enable/disable caching. By default caching is disabled.
  if Rails.root.join('tmp/caching-dev.txt').exist?
    config.action_controller.perform_caching = true

    config.cache_store = :memory_store
    config.public_file_server.headers = {
      'Cache-Control' => 'public, max-age=172800'
    }
  else
    config.action_controller.perform_caching = false

    config.cache_store = :null_store
  end

  config.assets.precompile += %w( '.svg' ) 

  # Don't care if the mailer can't send.
  config.action_mailer.raise_delivery_errors = true

  config.action_mailer.perform_caching = false

  # Print deprecation notices to the Rails logger.
  config.active_support.deprecation = :log

  # Raise an error on page load if there are pending migrations.
  config.active_record.migration_error = :page_load

  # Debug mode disables concatenation and preprocessing of assets.
  # This option may cause significant delays in view rendering with a large
  # number of complex assets.
  config.assets.debug = true

  # Suppress logger output for asset requests.
  config.assets.quiet = true

  # Raises error for missing translations
  # config.action_view.raise_on_missing_translations = true

  # Use an evented file watcher to asynchronously detect changes in source code,
  # routes, locales, etc. This feature depends on the listen gem.
  config.file_watcher = ActiveSupport::EventedFileUpdateChecker

end

Я изменил старую конфигурацию с gmail, и проблема сохраняется ...

development.rb

Rails.application.configure do
  # Settings specified here will take precedence over those in config/application.rb.

  # In the development environment your application's code is reloaded on
  # every request. This slows down response time but is perfect for development
  # since you don't have to restart the web server when you make code changes.

  config.action_mailer.delivery_method = :letter_opener
  config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }

  config.cache_classes = false

  # Do not eager load code on boot.
  config.eager_load = false

  # Show full error reports.
  config.consider_all_requests_local = true

  # Enable/disable caching. By default caching is disabled.
  if Rails.root.join('tmp/caching-dev.txt').exist?
    config.action_controller.perform_caching = true

    config.cache_store = :memory_store
    config.public_file_server.headers = {
      'Cache-Control' => 'public, max-age=172800'
    }
  else
    config.action_controller.perform_caching = false

    config.cache_store = :null_store
  end

  config.assets.precompile += %w( '.svg' ) 

  # Don't care if the mailer can't send.
  config.action_mailer.raise_delivery_errors = true

  config.action_mailer.perform_caching = false

  # Print deprecation notices to the Rails logger.
  config.active_support.deprecation = :log

  # Raise an error on page load if there are pending migrations.
  config.active_record.migration_error = :page_load

  # Debug mode disables concatenation and preprocessing of assets.
  # This option may cause significant delays in view rendering with a large
  # number of complex assets.
  config.assets.debug = true

  # Suppress logger output for asset requests.
  config.assets.quiet = true

  # Raises error for missing translations
  # config.action_view.raise_on_missing_translations = true

  # Use an evented file watcher to asynchronously detect changes in source code,
  # routes, locales, etc. This feature depends on the listen gem.
  config.file_watcher = ActiveSupport::EventedFileUpdateChecker


  config.action_mailer.delivery_method = :smtp

  config.action_mailer.smtp_settings = {
    address: "smtp.gmail.com",
    port: 587,
    domain: 'gmail.com',
    user_name: ENV['GMAIL_ADDRESS'],
    password: ENV['GMAIL_APP_PASSWORD'],
    authentication: "plain",
    enable_starttls_auto: true
  }

  config.action_mailer.default_url_options = {host: "localhost:3000"}

end

ОБНОВЛЕНИЕ 2:

Я также пытался перейти к тем веткам, где работала рассылка, и ничего (я перезапустилсервер) ...

1 Ответ

0 голосов
/ 14 февраля 2019

Это частичное решение, позволяющее использовать рассылку в тестовых окружениях в моем случае.

На этом рельсовая документация рассылки по теме 10.2 Десериализация говорит:

Если переданная запись удаляется после постановки в очередь, но перед вызовом метода #perform Active Job вызовет исключение ActiveJob :: DeserializationError.

Итак, я понял, что каким-то образом запись имеетудаляется из кэша до того, как метод отправки (delivery_later) предпримет действие.Если это происходит только в средах development и staging, то я добавил:

production.rb

config.active_job.queue_adapter = :sidekiq

development.rb/ staging.rb

  config.active_job.queue_adapter = :inline
...