nitro_pg_cache 0.1.rc1 → 0.1.1.rc1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/README.md +29 -25
- data/lib/models/nitro_partial.rb +2 -0
- data/lib/nitro_pg_cache/version.rb +1 -1
- metadata +3 -3
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA1:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 01682be0423d2b4e7b061f19cd8faaa983b0a992
|
|
4
|
+
data.tar.gz: a1aa56e372e6daa72e62012a488781371cd942b6
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 62de0796c978a4f2c661f1068735f66ecb14d82355585ce19bf68aa88080689430ff1e66d3093f8e580c058dbc4a350cb2c1ea18fbe45dba4f5cff78681d6e1e
|
|
7
|
+
data.tar.gz: 8e09eed25db6f799b52949384303b7459a961cb5b96c8e02133ce60cfb95908cd7bfcc680b86c33a5eedc6a0be0018a709a7158bc6f8bf1b4bd35a5114cac4ea
|
data/README.md
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
|
|
1
|
+
## ATTENTION
|
|
2
2
|
To use this gem you need PostgreSQL 9.4 and higher!
|
|
3
3
|
|
|
4
|
-
|
|
4
|
+
## ATTENTION(РУС)
|
|
5
5
|
Для корректной работы библиотеки требуется версия PostgreSQL не ниже 9.4!
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
## NitroPgCache
|
|
8
8
|
This gem create DB-based solution for caching relation collections. It based on PostgreSQL version >= 9.4 .
|
|
9
9
|
It faster than memcache+dalli combination. In some cases three times faster, but with all DB facilities!
|
|
10
10
|
|
|
11
11
|
Right now nitro_pg_cache is in alpha-release state. It's working, but may need additional tuning and features, for example limits and expiring,
|
|
12
12
|
actually I don't know which will suit best.
|
|
13
13
|
|
|
14
|
-
|
|
14
|
+
## FEATURES
|
|
15
15
|
Already working*:
|
|
16
16
|
(* all benchmark numbers are given with pg_cache_key gem enabled, this mean that in rails < 5 or without pg_cache_key, you'll get +25% additional speed bonus for cached collection )
|
|
17
17
|
|
|
@@ -37,7 +37,7 @@ Can be done soon
|
|
|
37
37
|
( must check how mass update will suffer from json insert ).
|
|
38
38
|
9. Expiring and quantity limits, cache expiring can be done on different conditions including last time viewed.
|
|
39
39
|
|
|
40
|
-
|
|
40
|
+
## NitroPgCache (РУС)
|
|
41
41
|
Данная библиотека реализует кеширование relation-коллекций на основе движка PostgreSQL последних версий (>=9.4).
|
|
42
42
|
Получившийся результат по всем показателям скороси не уступает
|
|
43
43
|
классической схеме memcache+dalli, а во многих случаях и превосходит ее в разы, обладая при этом всеми достоинствами базы данных.
|
|
@@ -45,7 +45,7 @@ Can be done soon
|
|
|
45
45
|
В настоящий момент библиотека находится в состоянии alpha-release. Основной функционал ее работает, но ряд дополнительных возможностей требует реализации.
|
|
46
46
|
Например ограничения на количество кешей, устаревание кешей и пр. . Если есть какие-то пожелания какие конкретно должны быть возможности связанные с этим: велкам
|
|
47
47
|
|
|
48
|
-
|
|
48
|
+
## ВОЗМОЖНОСТИ БИБЛИОТЕКИ
|
|
49
49
|
|
|
50
50
|
Реализованные возможности*:
|
|
51
51
|
(* величины указаны при использовании гема pg_cache_key для реализации cache_key у коллекций,
|
|
@@ -67,7 +67,7 @@ Can be done soon
|
|
|
67
67
|
ключу еще и Json для локалс.
|
|
68
68
|
9. Устаревание И лимитирование кешей. Может быть реализовано многими способами.
|
|
69
69
|
|
|
70
|
-
|
|
70
|
+
### RESTRICTIONS:
|
|
71
71
|
|
|
72
72
|
Only clear collections rendering can be cached with this gem. i.e.:
|
|
73
73
|
Can convert:
|
|
@@ -82,7 +82,7 @@ Only clear collections rendering can be cached with this gem. i.e.:
|
|
|
82
82
|
=render partial: 'pagination_footer', records: @records
|
|
83
83
|
```
|
|
84
84
|
|
|
85
|
-
|
|
85
|
+
### ОГРАНИЧЕНИЯ:
|
|
86
86
|
|
|
87
87
|
Только чистый кеш на коллекцию может использоваться с данной библиотекой:
|
|
88
88
|
Может быть сконвертированно:
|
|
@@ -99,7 +99,7 @@ Only clear collections rendering can be cached with this gem. i.e.:
|
|
|
99
99
|
=render partial: 'pagination_footer', records: @records
|
|
100
100
|
```
|
|
101
101
|
|
|
102
|
-
|
|
102
|
+
### CACHING ALGORITHMS ( STRAIGHT/REVERSE/ARRAY CACHING )
|
|
103
103
|
|
|
104
104
|
Three types of caching collection mechanism are used: straight, 'reverse', array-elem
|
|
105
105
|
straight and reverse used for relation objects! array-elem - instantinated array or elem
|
|
@@ -117,7 +117,7 @@ array-elem (db_cache_array) - this is method used only with prerender: true for
|
|
|
117
117
|
DON'T USE IT ELSEWHERE!! If you have complex hierarchy of models and don't include them on update action of your controller
|
|
118
118
|
it may give you N+1 problem internally.
|
|
119
119
|
|
|
120
|
-
|
|
120
|
+
### ВАРИАНТЫ КЕШИРОВАНИЯ ( STRAIGHT/REVERSE/ARRAY CACHING )
|
|
121
121
|
|
|
122
122
|
Прямой и реверсивный ( straight and reverse ) используются только для relation объектов. array cache используется только если prerender: true
|
|
123
123
|
для измененного элемента.
|
|
@@ -134,7 +134,7 @@ array-elem (db_cache_array) - Этот метод используется то
|
|
|
134
134
|
НЕ ИСПОЛЬЗУЙТЕ ЕГО НИГДЕ В ДРУГИХ СЛУЧАЯХ!
|
|
135
135
|
|
|
136
136
|
|
|
137
|
-
|
|
137
|
+
### BENCHMARK VS MEMCACHE + DALLI
|
|
138
138
|
|
|
139
139
|
Comparisons were made manually with rack mini-profiler gem +
|
|
140
140
|
I used htop system-monitor to be sure that nothing going in the background and tempering with results
|
|
@@ -186,7 +186,7 @@ In rails >= 5 or with pg_cache_key gem it will bring nearly same result i.e. rat
|
|
|
186
186
|
|0.12K | 0.2-0.25 | 0.38s | ~1.7 times faster |
|
|
187
187
|
|
|
188
188
|
|
|
189
|
-
|
|
189
|
+
### СРАВНЕНИЕ С MEMCACHE + DALLI
|
|
190
190
|
|
|
191
191
|
Сравнения провел вручную на живых страницах с исопльзованием rack mini-profiler gem.
|
|
192
192
|
Используя htop, следил, чтобы ничего не загружало систему дополнительно и портило результаты.
|
|
@@ -236,26 +236,26 @@ mmch - (memcache) обычный матрешный кеш memcached + dalli
|
|
|
236
236
|
|0.38K | 0.35+s | 0.6 | ~1.7 times faster |
|
|
237
237
|
|0.12K | 0.2-0.25 | 0.38s | ~1.7 times faster |
|
|
238
238
|
|
|
239
|
-
|
|
239
|
+
### MEMORY USAGE
|
|
240
240
|
|
|
241
241
|
I didn't make a special comparision, but I assume that there is a insufficient difference between usual cache and pg_cache.
|
|
242
242
|
|
|
243
243
|
|
|
244
|
-
|
|
244
|
+
### ИСПОЛЬЗОВАНИЕ ПАМЯТИ
|
|
245
245
|
|
|
246
246
|
Объем используемой памяти примерно одинаковый и может зависеть от того какой конкретно пришел запрос, сколько в нем уже
|
|
247
247
|
закешированных элементов сколько новых и пр.
|
|
248
248
|
|
|
249
249
|
|
|
250
|
-
|
|
250
|
+
### GENERAL FALLBACK
|
|
251
251
|
With any variant of prerender true/false all not found caches get themselves cached usual way as in prerender-false case. i.e. as usual cache will do.
|
|
252
252
|
|
|
253
|
-
|
|
253
|
+
### ОСНОВНОЕ ПОВЕДЕНИЕ ПО УМОЛЧАНИЮ
|
|
254
254
|
Независимо от того стоит prerender-true или нет, если на момент запроса значение nitro_cache_value пустое,
|
|
255
255
|
то кеширование запускается обычным ходом, который совпадает, с вариантом когда prerender-false.
|
|
256
256
|
|
|
257
257
|
|
|
258
|
-
|
|
258
|
+
### HOW IT BEHAVE WHEN SOMETHING CHANGES ( KEYS, PARTIALS, ETC )
|
|
259
259
|
The main rule of thumb: no prerendering at server start, only mass cleaning old and creating new nitro_partial records!
|
|
260
260
|
If you are using prerender, then run rake task prerender in parallel manually or by any automation script
|
|
261
261
|
The rules of cache changes are depended on prerender state of partial true|false
|
|
@@ -290,7 +290,7 @@ The rules of cache changes are depended on prerender state of partial true|false
|
|
|
290
290
|
8. When expiration params changes При изменении параметров устаревания, проверяем в rake :expire_db_nitro_cache который можно в кронджобы вписать.
|
|
291
291
|
все кеши на соответствие новым правилам. Ненужное удаляем.
|
|
292
292
|
|
|
293
|
-
|
|
293
|
+
### ПРАВИЛА ИЗМНЕНИЯ КЕША, ЕСЛИ ЧТО_ТО ПОМЕНЯЛОСЬ (РУС)
|
|
294
294
|
Главное правило: никакого пререндеринга на старте сервера иначе у деплоя развяжется пупок.
|
|
295
295
|
На старте только: массовое удаление устаревшего, создание новых записей nitro_partial для новых паршиалов.
|
|
296
296
|
Правила поведения кеша при изменениях ( поведение зависит от значения prerender - true|false)
|
|
@@ -310,7 +310,7 @@ The rules of cache changes are depended on prerender state of partial true|false
|
|
|
310
310
|
3. При изменении параметров устаревания, проверяем в rake :expire_db_nitro_cache который можно в кронджобы вписать.
|
|
311
311
|
все кеши на соответствие новым правилам. Ненужное удаляем.
|
|
312
312
|
|
|
313
|
-
|
|
313
|
+
### PARTIAL PRERENDER
|
|
314
314
|
|
|
315
315
|
Since nitro_pg_cache works as usual cache* also we can prerender only for part of keys and part of records, only most wanted.
|
|
316
316
|
|
|
@@ -323,7 +323,7 @@ so we can set prerender scope with condition on :created_at column, and prerende
|
|
|
323
323
|
|
|
324
324
|
*see section LIMITATIONS for more details on the possibilities of replacing usual feed cache with nitro
|
|
325
325
|
|
|
326
|
-
|
|
326
|
+
### ЧАСТИЧНЫЙ ПРЕРЕНДЕРИНГ
|
|
327
327
|
В силу того что nitro_cache может работать практически как обычный матрешный кеш* мы можем включить пререндеринг только для части
|
|
328
328
|
ключей и части записей.
|
|
329
329
|
|
|
@@ -334,20 +334,20 @@ so we can set prerender scope with condition on :created_at column, and prerende
|
|
|
334
334
|
Второй пример: мы ведем длинную историю оплат пользователей, но для работы бухов нужен последний квартал или там год
|
|
335
335
|
мы можем выставить scope для пререндеринга по :created_at и пререрндерить только нужные записи.
|
|
336
336
|
|
|
337
|
-
|
|
337
|
+
### EXPIRING
|
|
338
338
|
Right now all cache get timestamp for the last access ( :viewed_at ) so it possible to control cache expiration on time basis
|
|
339
339
|
|
|
340
|
-
|
|
340
|
+
### УСТАРЕВАНИЕ
|
|
341
341
|
Сейчас все ключи хранят штамп времени последнего просмотра поэтому можно легко реализовать устаревающий кеш. например как рейк + крон-джоб
|
|
342
342
|
|
|
343
343
|
|
|
344
|
-
|
|
344
|
+
### STRAIGHT VS REVERSE VS CLASSIC POSSIBLE PROBLEMS
|
|
345
345
|
1. DB Sharding for reverse-cache. If we use db sharding reverse-cache may need additional tuning and testing since it's doing its job
|
|
346
346
|
in two steps. Straight-cache will work anyway.
|
|
347
347
|
2. Exotic cases for any variant of pg_cache. If we render same collection twice with different partial inside one controller action ( it's quite unusual behaviour ),
|
|
348
348
|
than we may instatinate collection twice.
|
|
349
349
|
|
|
350
|
-
|
|
350
|
+
### STRAIGHT VS REVERSE VS CLASSIC ВЕРОЯТНЫЕ ПРОБЛЕМЫ
|
|
351
351
|
1. БД-шардинг при обратном кешировании. Если мы используем БД шардинг, то вариант реверс кеширования требует доработки, потому что мы должны спрашивать
|
|
352
352
|
аггрегацию сразу же после того как сделали апдейт, поэтому по идее это должно идти на мастер-шард.
|
|
353
353
|
2. Экзотические варинты многоразового рендеринга с разными паршиалами одной коллекции в одном методе контроллера. Тогда может быть многоразовая инстантинация
|
|
@@ -364,7 +364,7 @@ Right now all cache get timestamp for the last access ( :viewed_at ) so it possi
|
|
|
364
364
|
( это случай когда он параллельно был создан в соседнем процессе ) и если такого нет создается новый.
|
|
365
365
|
|
|
366
366
|
|
|
367
|
-
|
|
367
|
+
### Usage
|
|
368
368
|
|
|
369
369
|
### As cache replacement
|
|
370
370
|
Replace:
|
|
@@ -410,6 +410,10 @@ class Request < ActiveRecord::Base
|
|
|
410
410
|
as: :request,
|
|
411
411
|
scope: Request.except_created.with_deleted.where(created_at: -6.month.from_now..Time.now ) )
|
|
412
412
|
end
|
|
413
|
+
|
|
414
|
+
# prerender all scopes
|
|
415
|
+
Partial.all.each(&:update_caches)
|
|
416
|
+
|
|
413
417
|
```
|
|
414
418
|
|
|
415
419
|
|
data/lib/models/nitro_partial.rb
CHANGED
|
@@ -164,6 +164,8 @@ class NitroPartial < ActiveRecord::Base
|
|
|
164
164
|
end
|
|
165
165
|
|
|
166
166
|
def update_cache_for_collection( collection, progress = nil )
|
|
167
|
+
|
|
168
|
+
nitro_caches.where( nitro_cacheable: collection ).delete_all
|
|
167
169
|
cache_keys.values.each do |locals|
|
|
168
170
|
progress.try(:inc)
|
|
169
171
|
ApplicationController.render( assigns: {
|
metadata
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: nitro_pg_cache
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.1.rc1
|
|
4
|
+
version: 0.1.1.rc1
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- alekseyl
|
|
8
8
|
autorequire:
|
|
9
9
|
bindir: bin
|
|
10
10
|
cert_chain: []
|
|
11
|
-
date: 2016-11-
|
|
11
|
+
date: 2016-11-17 00:00:00.000000000 Z
|
|
12
12
|
dependencies:
|
|
13
13
|
- !ruby/object:Gem::Dependency
|
|
14
14
|
name: rails
|
|
@@ -88,7 +88,7 @@ files:
|
|
|
88
88
|
- lib/nitro_pg_cache/model_ext.rb
|
|
89
89
|
- lib/nitro_pg_cache/version.rb
|
|
90
90
|
- lib/nitro_pg_cache/viewer_ext.rb
|
|
91
|
-
homepage:
|
|
91
|
+
homepage: https://github.com/alekseyl/nitro_pg_cache
|
|
92
92
|
licenses:
|
|
93
93
|
- MIT
|
|
94
94
|
metadata: {}
|