-
Notifications
You must be signed in to change notification settings - Fork 90
dz4 #118
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
stashevgenij
wants to merge
7
commits into
hardcode-dev:master
Choose a base branch
from
stashevgenij:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
dz4 #118
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
086f271
2 - new relic
stashevgenij c4266e3
3 - skylight
stashevgenij 5cfd022
4 - prometeus + grafana
stashevgenij a293b01
5 - rmp
stashevgenij 66a578a
6 - rails pamel
stashevgenij 73766be
7 - local production
stashevgenij f1c9d45
8 - optimization
stashevgenij File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,4 @@ | ||
| web: bin/rails s -p 3000 | ||
| webpacker: ./bin/webpack-dev-server | ||
| job: bin/rake jobs:work | ||
| prometheus_exporter: bundle exec prometheus_exporter -a prometheus/custom-collector.rb |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| #!/usr/bin/env ruby | ||
| require "pathname" | ||
| require "fileutils" | ||
| include FileUtils | ||
|
|
||
| # path to your application root. | ||
| APP_ROOT = Pathname.new File.expand_path("..", __dir__) | ||
|
|
||
| def system!(*args) | ||
| system(*args) || abort("\n== Command #{args} failed ==") | ||
| end | ||
|
|
||
| chdir APP_ROOT do | ||
| puts "== ASSETS PRECOMPILE ==" | ||
| system! "bin/rails assets:precompile" | ||
|
|
||
| puts "== STARTING UP ==" | ||
| system! "RAILS_ENV=local_production bin/rails s" | ||
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| # Rails Optimization - HW4 | ||
|
|
||
| ### 1. Завести dev.to локально | ||
|
|
||
| Пробую запустить проект по инструкции из `README`. | ||
|
|
||
| Возникли ошибки при `yarn install`, помог запуск `yarn upgrade`. Старые миграции не проходили, пришлось указать версию в наследовании `ActiveRecord::Migration[4.2]`. | ||
|
|
||
| После этого проект успешно запустился, но база была пустая, запустил `db:seed`. Всё завелось) | ||
|
|
||
| ### 2. Настроить свой NewRelic для мониторинга локального dev.to | ||
|
|
||
| Зарегистрировался в New Relic, скачал конфиг, установил гем, данные начали появляться в New Relic. Файл конфига добавил в гит игнор. | ||
|
|
||
| ### 3. Настроить свой Skylight / Scout / Datadog для мониторинга локального dev.to | ||
|
|
||
| Зарегистрировался в Skylight, так как он уже настроен в проекте через ENV переменную, решил так и оставить, просто добавить эту переменную в `Envfile` и `config/application.yml`. | ||
|
|
||
| В Skylight появилось только окружение `production`, поэтому я добавил `development` в конфиге `application.rb`. | ||
|
|
||
| ### 4. Настроить свой Prometheus + Grafana для мониторинга локального dev.to | ||
|
|
||
| Добавил гем `prometheus_exporter`, ещё раз изучил и скопировал конфиги `docker-compose.yml`, `prometheus.yml`. Также решил добавить и `custom-collector.rb`, чтобы потренироваться с кастомными метриками. Добавил инишиалайзер, обновил `Procfile.dev`. | ||
|
|
||
| Запустил приложение, запустил докер с прометеусом и графаной, потыкал в прометеусе, зашел под админом в графану, добавил дата соурс, попробовал настроить дашборд. Всё получилось. | ||
|
|
||
| ### 5. Настроить rack-mini-profiler | ||
|
|
||
| Добавил гем, rmp поднялся. | ||
|
|
||
| ### 6. Настроить rails-panel | ||
|
|
||
| Добавил гем `meta_request`, Rails Panel поднялась. | ||
|
|
||
| ### 7. Сделать возможность запуска проекта в local_production | ||
|
|
||
| Скопировал конфиг `development.rb` и изменил настройки под `local_production`, дополнил все настройки новой средой `local_production`. Создал файл `tmp/caching-dev.txt`. Добавил скрипт запуска `bin/startup_lp` с компиляцией ассетов. | ||
|
|
||
| Возникла ошибка таймаута, поэтому увеличил время таймаута для среды `local_production`. | ||
|
|
||
| ### 8. Оптимизация | ||
|
|
||
| Сделал замеры до и после добавления кеширования, как итог скорость загрузки увеличилась примерно в 2 раза. | ||
|
|
||
| 100 запросов с помощью команды `ab` без кеширования выполнялись за 9-10 секунд, после добавления кеширования за 4-5. | ||
|
|
||
| ### Итог | ||
|
|
||
| Я попрактиковался в настройке и использовании разных систем мониторинга, попробовал как SaaS, так и DIY решения. Еще раз попробовал `rmp` и `rails-panel`, закрепил навыки. | ||
|
|
||
| Настроил среду `local_production`, в которой можно намного точнее замерять, профилировать и находить точки роста, которые возникают на проде. Также внедрю эту среду и в своих проектах, так как уже иногда возникала необходимость запускать продакшн локально и воспроизводить проблемы, как на проде, например с ассетами. | ||
|
|
||
| Попробовал инструмент `ab`, на мой взгляд, самый простой и быстрый для замера скорости загрузки страниц и понимания эффективности оптимизаций. Удобно использовать в фидбек-лупе, так как быстро даёт обратную связь по проделанным изменениям. | ||
|
|
||
| Добавил небольшую оптимизацию на главную страницу с помощью кеширования, оценил на конкретных цифрах какой эффект даёт кеширование фрагмента. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,107 @@ | ||
| # rubocop:disable Metrics/BlockLength | ||
| # | ||
| def yarn_integrity_enabled? | ||
| ENV.fetch("YARN_INTEGRITY_ENABLED", "true") == "true" | ||
| end | ||
|
|
||
| Rails.application.configure do | ||
| # Verifies that versions and hashed value of the package contents in the project's package.json | ||
| config.webpacker.check_yarn_integrity = yarn_integrity_enabled? | ||
|
|
||
| # 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.cache_classes = true | ||
|
|
||
| # Do not eager load code on boot. | ||
| config.eager_load = true | ||
|
|
||
| # Show full error reports and disable caching. | ||
| 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.action_controller.asset_host = 'http://localhost:3000' | ||
|
|
||
| # Don't care if the mailer can't send. | ||
| config.action_mailer.raise_delivery_errors = false | ||
|
|
||
| # Print deprecation notices to the Rails logger. | ||
| config.active_support.deprecation = :debug | ||
|
|
||
| # Raise an error on page load if there are pending migrations. | ||
| config.active_record.migration_error = :page_load | ||
|
|
||
| # Compress JavaScripts and CSS. | ||
| config.assets.js_compressor = Uglifier.new(harmony: true) | ||
|
|
||
| # 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 = false | ||
|
|
||
| # Do not fallback to assets pipeline if a precompiled asset is missed. | ||
| config.assets.compile = true | ||
|
|
||
| # Asset digests allow you to set far-future HTTP expiration dates on all assets, | ||
| # yet still be able to expire them through the digest params. | ||
| config.assets.digest = false | ||
|
|
||
| # Supress logger output for asset requests. | ||
| config.assets.quiet = true | ||
|
|
||
| # Adds additional error checking when serving assets at runtime. | ||
| # Checks for improperly declared sprockets dependencies. | ||
| # Raises helpful error messages. | ||
| config.assets.raise_runtime_errors = true | ||
|
|
||
| config.action_mailer.perform_caching = false | ||
|
|
||
| config.app_domain = "localhost:3000" | ||
|
|
||
| config.action_mailer.default_url_options = { host: "localhost:3000" } | ||
| config.action_mailer.delivery_method = :smtp | ||
| config.action_mailer.perform_deliveries = true | ||
| config.action_mailer.default_url_options = { host: config.app_domain } | ||
| config.action_mailer.smtp_settings = { | ||
| address: "smtp.gmail.com", | ||
| port: "587", | ||
| enable_starttls_auto: true, | ||
| user_name: '<%= ENV["DEVELOPMENT_EMAIL_USERNAME"] %>', | ||
| password: '<%= ENV["DEVELOPMENT_EMAIL_PASSWORD"] %>', | ||
| authentication: :plain, | ||
| domain: "localhost:3000" | ||
| } | ||
|
|
||
| config.action_mailer.preview_path = "#{Rails.root}/spec/mailers/previews" | ||
|
|
||
| # Raises error for missing translations | ||
| # config.action_view.raise_on_missing_translations = true | ||
|
|
||
| # config.public_file_server.enabled = true | ||
|
|
||
| config.file_watcher = ActiveSupport::EventedFileUpdateChecker | ||
|
|
||
| # Install the Timber.io logger | ||
| send_logs_to_timber = ENV["SEND_LOGS_TO_TIMBER"] || "false" # <---- set to false to stop sending dev logs to Timber.io | ||
| log_device = send_logs_to_timber == "true" ? Timber::LogDevices::HTTP.new(ENV["TIMBER"]) : STDOUT | ||
| logger = Timber::Logger.new(log_device) | ||
| logger.level = config.log_level | ||
| config.logger = ActiveSupport::TaggedLogging.new(logger) | ||
| end | ||
|
|
||
| # rubocop:enable Metrics/BlockLength |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| # config/initializers/prometheus.rb | ||
| if Rails.env != "test" | ||
| require 'prometheus_exporter/middleware' | ||
|
|
||
| # This reports stats per request like HTTP status and timings | ||
| Rails.application.middleware.unshift PrometheusExporter::Middleware | ||
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Отлично, всё то что надо! 👍