Skip to content

Task-3 #96

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
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,14 @@ gem 'rails', '~> 5.2.3'
gem 'pg', '>= 0.18', '< 2.0'
gem 'puma', '~> 3.11'
gem 'bootsnap', '>= 1.1.0', require: false
gem 'rack-mini-profiler'
gem 'bullet'
gem 'ruby-prof'
gem 'stackprof'
gem 'memory_profiler'
gem 'oj'
gem "pghero"
gem "pg_query", ">= 2"

group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
Expand All @@ -17,6 +25,7 @@ group :development do
# Access an interactive console on exception pages or by calling 'console' anywhere in the code.
gem 'web-console', '>= 3.3.0'
gem 'listen', '>= 3.0.5', '< 3.2'
gem 'meta_request'
end

group :test do
Expand Down
207 changes: 125 additions & 82 deletions Gemfile.lock
Original file line number Diff line number Diff line change
@@ -1,145 +1,188 @@
GEM
remote: https://rubygems.org/
specs:
actioncable (5.2.3)
actionpack (= 5.2.3)
actioncable (5.2.8.1)
actionpack (= 5.2.8.1)
nio4r (~> 2.0)
websocket-driver (>= 0.6.1)
actionmailer (5.2.3)
actionpack (= 5.2.3)
actionview (= 5.2.3)
activejob (= 5.2.3)
actionmailer (5.2.8.1)
actionpack (= 5.2.8.1)
actionview (= 5.2.8.1)
activejob (= 5.2.8.1)
mail (~> 2.5, >= 2.5.4)
rails-dom-testing (~> 2.0)
actionpack (5.2.3)
actionview (= 5.2.3)
activesupport (= 5.2.3)
rack (~> 2.0)
actionpack (5.2.8.1)
actionview (= 5.2.8.1)
activesupport (= 5.2.8.1)
rack (~> 2.0, >= 2.0.8)
rack-test (>= 0.6.3)
rails-dom-testing (~> 2.0)
rails-html-sanitizer (~> 1.0, >= 1.0.2)
actionview (5.2.3)
activesupport (= 5.2.3)
actionview (5.2.8.1)
activesupport (= 5.2.8.1)
builder (~> 3.1)
erubi (~> 1.4)
rails-dom-testing (~> 2.0)
rails-html-sanitizer (~> 1.0, >= 1.0.3)
activejob (5.2.3)
activesupport (= 5.2.3)
activejob (5.2.8.1)
activesupport (= 5.2.8.1)
globalid (>= 0.3.6)
activemodel (5.2.3)
activesupport (= 5.2.3)
activerecord (5.2.3)
activemodel (= 5.2.3)
activesupport (= 5.2.3)
activemodel (5.2.8.1)
activesupport (= 5.2.8.1)
activerecord (5.2.8.1)
activemodel (= 5.2.8.1)
activesupport (= 5.2.8.1)
arel (>= 9.0)
activestorage (5.2.3)
actionpack (= 5.2.3)
activerecord (= 5.2.3)
marcel (~> 0.3.1)
activesupport (5.2.3)
activestorage (5.2.8.1)
actionpack (= 5.2.8.1)
activerecord (= 5.2.8.1)
marcel (~> 1.0.0)
activesupport (5.2.8.1)
concurrent-ruby (~> 1.0, >= 1.0.2)
i18n (>= 0.7, < 2)
minitest (~> 5.1)
tzinfo (~> 1.1)
arel (9.0.0)
bindex (0.6.0)
bootsnap (1.4.2)
msgpack (~> 1.0)
builder (3.2.3)
byebug (11.0.1)
concurrent-ruby (1.1.5)
crass (1.0.4)
erubi (1.8.0)
ffi (1.10.0)
globalid (0.4.2)
activesupport (>= 4.2.0)
i18n (1.6.0)
bindex (0.8.1)
bootsnap (1.16.0)
msgpack (~> 1.2)
builder (3.2.4)
bullet (7.0.7)
activesupport (>= 3.0.0)
uniform_notifier (~> 1.11)
byebug (11.1.3)
concurrent-ruby (1.2.2)
crass (1.0.6)
date (3.3.3)
erubi (1.12.0)
ffi (1.15.5)
globalid (1.1.0)
activesupport (>= 5.0)
google-protobuf (3.22.2)
i18n (1.12.0)
concurrent-ruby (~> 1.0)
listen (3.1.5)
rb-fsevent (~> 0.9, >= 0.9.4)
rb-inotify (~> 0.9, >= 0.9.7)
ruby_dep (~> 1.2)
loofah (2.2.3)
loofah (2.19.1)
crass (~> 1.0.2)
nokogiri (>= 1.5.9)
mail (2.7.1)
mail (2.8.1)
mini_mime (>= 0.1.1)
marcel (0.3.3)
mimemagic (~> 0.3.2)
method_source (0.9.2)
mimemagic (0.3.3)
mini_mime (1.0.1)
mini_portile2 (2.4.0)
minitest (5.11.3)
msgpack (1.2.9)
nio4r (2.3.1)
nokogiri (1.10.2)
mini_portile2 (~> 2.4.0)
pg (1.1.4)
puma (3.12.1)
rack (2.0.6)
rack-test (1.1.0)
rack (>= 1.0, < 3)
rails (5.2.3)
actioncable (= 5.2.3)
actionmailer (= 5.2.3)
actionpack (= 5.2.3)
actionview (= 5.2.3)
activejob (= 5.2.3)
activemodel (= 5.2.3)
activerecord (= 5.2.3)
activestorage (= 5.2.3)
activesupport (= 5.2.3)
net-imap
net-pop
net-smtp
marcel (1.0.2)
memory_profiler (1.0.1)
meta_request (0.7.4)
rack-contrib (>= 1.1, < 3)
railties (>= 3.0.0, < 7.1)
method_source (1.0.0)
mini_mime (1.1.2)
mini_portile2 (2.8.1)
minitest (5.18.0)
msgpack (1.6.1)
net-imap (0.3.4)
date
net-protocol
net-pop (0.1.2)
net-protocol
net-protocol (0.2.1)
timeout
net-smtp (0.3.3)
net-protocol
nio4r (2.5.8)
nokogiri (1.13.10)
mini_portile2 (~> 2.8.0)
racc (~> 1.4)
oj (3.14.2)
pg (1.4.6)
pg_query (4.2.0)
google-protobuf (>= 3.19.2)
pghero (2.8.3)
activerecord (>= 5)
puma (3.12.6)
racc (1.6.2)
rack (2.2.6.4)
rack-contrib (2.3.0)
rack (~> 2.0)
rack-mini-profiler (3.0.0)
rack (>= 1.2.0)
rack-test (2.1.0)
rack (>= 1.3)
rails (5.2.8.1)
actioncable (= 5.2.8.1)
actionmailer (= 5.2.8.1)
actionpack (= 5.2.8.1)
actionview (= 5.2.8.1)
activejob (= 5.2.8.1)
activemodel (= 5.2.8.1)
activerecord (= 5.2.8.1)
activestorage (= 5.2.8.1)
activesupport (= 5.2.8.1)
bundler (>= 1.3.0)
railties (= 5.2.3)
railties (= 5.2.8.1)
sprockets-rails (>= 2.0.0)
rails-dom-testing (2.0.3)
activesupport (>= 4.2.0)
nokogiri (>= 1.6)
rails-html-sanitizer (1.0.4)
loofah (~> 2.2, >= 2.2.2)
railties (5.2.3)
actionpack (= 5.2.3)
activesupport (= 5.2.3)
rails-html-sanitizer (1.5.0)
loofah (~> 2.19, >= 2.19.1)
railties (5.2.8.1)
actionpack (= 5.2.8.1)
activesupport (= 5.2.8.1)
method_source
rake (>= 0.8.7)
thor (>= 0.19.0, < 2.0)
rake (12.3.2)
rb-fsevent (0.10.3)
rb-inotify (0.10.0)
rake (13.0.6)
rb-fsevent (0.11.2)
rb-inotify (0.10.1)
ffi (~> 1.0)
ruby-prof (1.4.3)
ruby_dep (1.5.0)
sprockets (3.7.2)
sprockets (4.2.0)
concurrent-ruby (~> 1.0)
rack (> 1, < 3)
sprockets-rails (3.2.1)
actionpack (>= 4.0)
activesupport (>= 4.0)
rack (>= 2.2.4, < 4)
sprockets-rails (3.4.2)
actionpack (>= 5.2)
activesupport (>= 5.2)
sprockets (>= 3.0.0)
thor (0.20.3)
stackprof (0.2.24)
thor (1.2.1)
thread_safe (0.3.6)
tzinfo (1.2.5)
timeout (0.3.2)
tzinfo (1.2.11)
thread_safe (~> 0.1)
uniform_notifier (1.16.0)
web-console (3.7.0)
actionview (>= 5.0)
activemodel (>= 5.0)
bindex (>= 0.4.0)
railties (>= 5.0)
websocket-driver (0.7.0)
websocket-driver (0.7.5)
websocket-extensions (>= 0.1.0)
websocket-extensions (0.1.3)
websocket-extensions (0.1.5)

PLATFORMS
ruby

DEPENDENCIES
bootsnap (>= 1.1.0)
bullet
byebug
listen (>= 3.0.5, < 3.2)
memory_profiler
meta_request
oj
pg (>= 0.18, < 2.0)
pg_query (>= 2)
pghero
puma (~> 3.11)
rack-mini-profiler
rails (~> 5.2.3)
ruby-prof
stackprof
tzinfo-data
web-console (>= 3.3.0)

Expand Down
2 changes: 1 addition & 1 deletion app/controllers/trips_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@ class TripsController < ApplicationController
def index
@from = City.find_by_name!(params[:from])
@to = City.find_by_name!(params[:to])
@trips = Trip.where(from: @from, to: @to).order(:start_time)
@trips = Trip.includes(bus: :services).where(from: @from, to: @to).order(:start_time)
end
end
1 change: 0 additions & 1 deletion app/views/trips/_delimiter.html.erb

This file was deleted.

1 change: 0 additions & 1 deletion app/views/trips/_service.html.erb

This file was deleted.

6 changes: 0 additions & 6 deletions app/views/trips/_services.html.erb

This file was deleted.

5 changes: 0 additions & 5 deletions app/views/trips/_trip.html.erb

This file was deleted.

41 changes: 26 additions & 15 deletions app/views/trips/index.html.erb
Original file line number Diff line number Diff line change
@@ -1,16 +1,27 @@
<h1>
<%= "Автобусы #{@from.name} – #{@to.name}" %>
</h1>
<h2>
<%= "В расписании #{@trips.count} рейсов" %>
</h2>
<%= cache([@from.name, @to.name]) do %>
<h1>
<%= "Автобусы #{@from.name} – #{@to.name}" %>
</h1>
<h2>
<%= "В расписании #{@trips.count} рейсов" %>
</h2>

<% @trips.each do |trip| %>
<ul>
<%= render "trip", trip: trip %>
<% if trip.bus.services.present? %>
<%= render "services", services: trip.bus.services %>
<% end %>
</ul>
<%= render "delimiter" %>
<% end %>
<% @trips.each do |trip| %>
<ul>
<li><%= "Отправление: #{trip.start_time}" %></li>
<li><%= "Прибытие: #{(Time.parse(trip.start_time) + trip.duration_minutes.minutes).strftime('%H:%M')}" %></li>
<li><%= "В пути: #{trip.duration_minutes / 60}ч. #{trip.duration_minutes % 60}мин." %></li>
<li><%= "Цена: #{trip.price_cents / 100}р. #{trip.price_cents % 100}коп." %></li>
<li><%= "Автобус: #{trip.bus.model} №#{trip.bus.number}" %></li>
<% if trip.bus.services.present? %>
<li>Сервисы в автобусе:</li>
<ul>
<% trip.bus.services.each do |service| %>
<li><%= "#{service.name}" %></li>
<% end %>
</ul>
<% end %>
</ul>
====================================================
<% end %>
<% end %>
4 changes: 2 additions & 2 deletions bin/setup
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ chdir APP_ROOT do
puts "\n== Preparing database =="
system! 'bin/rails db:setup'

puts "\n== Loading data from fixtures/small.json =="
system! 'bin/rake reload_json[fixtures/small.json]'
puts "\n== Loading data from fixtures/large.json =="
system! 'bin/rake reload_json[fixtures/large.json]'

puts "\n== Removing old logs and tempfiles =="
system! 'bin/rails log:clear tmp:clear'
Expand Down
24 changes: 24 additions & 0 deletions case-study.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Case-study оптимизации

## Оптимизация импорта
Изначально время импорта файла large.json занимало ~450s
Я переписал импорт сразу с потоковой записью в `Postgres`. После рефакторинга время обарботки файла large.json стало ~13s

## Оптимизация рендеринга страницы
Изначальное время рендеринга страницы с данными из файла large.json было ~34000ms.

### Правка №1
bullet и rack mini profiler указывали на проблему n+1
Добавил includes к формированию списка поездок:
@trips = Trip.includes(bus: :services).where(from: @from, to: @to).order(:start_time)
После рефакторинга время рендера страницы изменилось с ~34000ms до ~24000ms

### Правка №2
Rails panel указвыл, что практически все время тратиться на рендеринг шаблонов. Решил убрать все шаблоны и формировать html сразу на одной странице, тк он достаточно простой.
После рефакторинга время рендера страницы изменилось с ~24000ms до ~6000ms

### Правка №3
Решил установить pg_hero и проанализировать запросы. pg_hero не предлавагал добавлять никакие индексы и все было в норме. Но я добавил индыксы на имя города, и составной индекс для трипов по from_id, to_id. Какой-то прибавки к скорости рендера это не дало, все осталось в пределах погрешности.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В данном случае да, так как почти всё время уходит на рендеринг паршлов

Но если смотреть с точки зрения оптимизации БД - очень полезно

В принципе можно оставлять паршлы, но юзать рендеринг коллекций, и там можно даже задать шаблон разделителя. Всё в одном файле быстрее работает, но всё-таки не так удобно для разработки (в реальном мире)

https://guides.rubyonrails.org/layouts_and_rendering.html#spacer-templates


### Правка №4
Принял решение добавить кэширование. Закэшировал сразу всю страницу index. Время рендера закешированной версии страницы изменилось с ~6000ms до ~250ms
Loading