recapi 0.1.4 → 0.1.8
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 +36 -10
- data/lib/recapi.rb +142 -24
- metadata +1 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 45a27aa9c5eae2fa2088d58247ebd703b60df834bc22e508737d89f17e90a8a2
|
|
4
|
+
data.tar.gz: 7443f75901c5e2600ea181f3a61277bc9b2e5b2820aad2c999dba4b8353521b6
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 856de23aa6d4936301ac4d9a2dbd2de72c4ffea40e44ed41459f7b310ff36dc232103f9e8e6cd11d265790e6b95eda80cea2d6c40087d68df252d2861c5f2956
|
|
7
|
+
data.tar.gz: dfd97019465b529c84fb4d315876acac76a414432fe3d53a901ec037f3b03c5490c2ce76ed2f3000651ff904f37115c9da9d046c59c99286924abcfea1ded8fc
|
data/README.md
CHANGED
|
@@ -30,7 +30,7 @@ line with your address): save it as `lib/recapi.rb` and
|
|
|
30
30
|
`require Rails.root.join("lib/recapi").to_s` instead.
|
|
31
31
|
|
|
32
32
|
```sh
|
|
33
|
-
curl -fLo lib/recapi.rb https://api.<your-domain>/sdk/ruby/recapi-0.1.
|
|
33
|
+
curl -fLo lib/recapi.rb https://api.<your-domain>/sdk/ruby/recapi-0.1.8.rb
|
|
34
34
|
```
|
|
35
35
|
|
|
36
36
|
## Quick start
|
|
@@ -41,7 +41,7 @@ require "recapi"
|
|
|
41
41
|
|
|
42
42
|
# A secret key (rk_sec_…): it stays on your server.
|
|
43
43
|
RECAPI = Recapi::Client.new(ENV.fetch("RECAPI_KEY"), "https://api.example.com",
|
|
44
|
-
|
|
44
|
+
logger: Rails.logger)
|
|
45
45
|
```
|
|
46
46
|
|
|
47
47
|
```ruby
|
|
@@ -64,25 +64,28 @@ Ids may be strings or integers (an ActiveRecord id): they travel as strings.
|
|
|
64
64
|
|
|
65
65
|
A refused argument (an invalid id or level) raises `ArgumentError`, and an
|
|
66
66
|
API failure `Recapi::Error` (`code`, `status`, `retry_after`, `retryable?`,
|
|
67
|
-
`outage?`).
|
|
67
|
+
`outage?`). `recommend` and `popular` still raise on a bad request (400, 404,
|
|
68
|
+
413, other 3xx/4xx) or a reply that isn't the API's; an outage, a limit or a
|
|
69
|
+
refused key can start on a live site with no deploy, so they answer with a list
|
|
70
|
+
and a log line.
|
|
68
71
|
|
|
69
72
|
| Call | What it does |
|
|
70
73
|
|---|---|
|
|
71
74
|
| `track(item_id, level, user_id:, anon_id:, recommendation_id:)` | Records an interaction: `level` -10 to 10 or `:view` (3), `:cart` (5), `:purchase` (10), `:reject` (-10: never recommend the item to this user again until a positive event on it). The history changes at once; a background thread sends the event within 2 s (at once when a batch of 1,000 is full). |
|
|
72
75
|
| `flush` | Sends the queued events now, with retries (end of a job). A network error, 429 or 5xx is retried 3 times (0.5 s, 1 s, 2 s with jitter, or the `Retry-After`, at most 8 s), then the events stay queued and the sender backs off up to a minute; any other error drops them (logged). |
|
|
73
76
|
| `close` | Stops the sender and sends what is queued, one try per batch. It runs by itself at exit. |
|
|
74
|
-
| `recommend(user_id:, anon_id:, count:, placement:, tags_any:, tags_all:, exclude:, context_item_id:, discovery:)` | A `Recapi::Recommendations` (`recommendation_id`, `fallback?`, `items`). At most 1.5 s; on a network error, timeout or
|
|
77
|
+
| `recommend(user_id:, anon_id:, count:, placement:, tags_any:, tags_all:, exclude:, context_item_id:, discovery:)` | A `Recapi::Recommendations` (`recommendation_id`, `fallback?`, `items`). At most 1.5 s; on a network error, timeout, 5xx or 429 it returns popular items (`fallback?`, no id), or no item when those fail too: hide the slot; on a 401 or 403 no item at once. Any other failure (a bad request, a reply that isn't the API's) raises. |
|
|
75
78
|
| `identify(anon_id, user_id)` | At login: the visitor's history and shown items become the user's. The user's first restore from recapi then leaves that visitor's browsing out, so it doesn't count twice. |
|
|
76
|
-
| `popular(count:, tags_any:, tags_all:)` | Popular items, for pages without a user. |
|
|
79
|
+
| `popular(count:, tags_any:, tags_all:)` | Popular items, for pages without a user. On a network error, timeout, 5xx, 429, 401 or 403: an empty list and a log line. Other failures as in `recommend`. |
|
|
77
80
|
| `upsert_items(items)` | Creates or replaces items (hashes of `item_id`, `title`, `tags`, `metadata`…), 1,000 per request, retried like events. Returns how many were stored. |
|
|
78
81
|
| `delete_user(user_id)` | Erases a user's events in recapi and their state in the store, retried like events. |
|
|
79
82
|
|
|
80
83
|
`Recapi::Client.new(api_key, base_url, store:, timeout:, flush_interval:,
|
|
81
84
|
max_batch:, logger:)` sets the options. The default `Recapi::MemoryStore`
|
|
82
|
-
keeps the 10,000 most recent users in the process; pass
|
|
83
|
-
|
|
84
|
-
several processes serve the same users. It
|
|
85
|
-
Python library, so both can share one store. Written to `Rails.cache` or a
|
|
85
|
+
keeps the 10,000 most recent users in the process; pass a Redis client
|
|
86
|
+
(`get`/`set`/`del`) or a `Rails.cache` on Redis, Memcached or Solid Cache (it
|
|
87
|
+
has `read`/`write`/`delete`) when several processes serve the same users. It
|
|
88
|
+
stores the same JSON as the Python library, so both can share one store. Written to `Rails.cache` or a
|
|
86
89
|
redis-rb client, a user's state lasts 30 days from its last write, with no
|
|
87
90
|
setting to choose: well past the 24 hours a click earns credit, and recapi gives
|
|
88
91
|
a known `user_id` its history back afterwards. Any other store gets a plain
|
|
@@ -93,7 +96,30 @@ client; a forked worker (Puma cluster, Unicorn, Passenger) starts its own
|
|
|
93
96
|
queue and sender at its first call. Proxies come from `HTTPS_PROXY`,
|
|
94
97
|
`HTTP_PROXY` and `NO_PROXY`, as `Net::HTTP` reads them. Failures are logged
|
|
95
98
|
to `logger:`, anything with `warn` and `error` (`Rails.logger`, a
|
|
96
|
-
`Logger`); without one they go to `$stderr` as `recapi: …` lines
|
|
99
|
+
`Logger`); without one they go to `$stderr` as `recapi: …` lines, with lost
|
|
100
|
+
events (a refused batch, rejected events) at most one line a minute for each
|
|
101
|
+
error code and for rejected events, and `recommend`'s and `popular`'s failures
|
|
102
|
+
at most one line a minute for each error code, so a revoked key on a busy server
|
|
103
|
+
doesn't flood the log, and a full queue one line until a send works. A failed write to
|
|
104
|
+
`$stderr` (a full disk, a closed stream) is ignored. A logger you give gets
|
|
105
|
+
every line, and if it raises, that reaches your code.
|
|
106
|
+
|
|
107
|
+
### Which Rails caches work
|
|
108
|
+
|
|
109
|
+
Not every `Rails.cache` can hold this, and Rails' defaults often can't. The
|
|
110
|
+
library recognises ActiveSupport's own classes (a subclass of one is left alone)
|
|
111
|
+
and logs one line at start:
|
|
112
|
+
|
|
113
|
+
| `Rails.cache` | Where Rails sets it | What happens | Shared between |
|
|
114
|
+
|---|---|---|---|
|
|
115
|
+
| `RedisCacheStore`, `MemCacheStore`, Solid Cache | your choice; Solid Cache in new 8.x apps' production | used, no line | servers |
|
|
116
|
+
| `FileStore` | production on 7.2 and older | used, with a warning | one server's processes |
|
|
117
|
+
| `MemoryStore` | development on 8.x | the library's own store instead, with a warning | nothing |
|
|
118
|
+
| `NullStore` | development on 7.2 and older, without `rails dev:cache` | the library's own store instead, with a warning | nothing |
|
|
119
|
+
|
|
120
|
+
`FileStore` frees an expired entry only when it is read again or `cleanup` runs,
|
|
121
|
+
so a visitor who never returns stays on disk (about 8 KB each): run
|
|
122
|
+
`Rails.cache.cleanup` on a schedule, or leave `store:` out.
|
|
97
123
|
|
|
98
124
|
## Development
|
|
99
125
|
|
data/lib/recapi.rb
CHANGED
|
@@ -25,7 +25,7 @@ rescue LoadError
|
|
|
25
25
|
end
|
|
26
26
|
|
|
27
27
|
module Recapi
|
|
28
|
-
VERSION = "0.1.
|
|
28
|
+
VERSION = "0.1.8"
|
|
29
29
|
|
|
30
30
|
# Decayed user history, exactly as docs/history-spec.md (times in unix ms).
|
|
31
31
|
# A port of sdk/python's history.py, snapshot merging included.
|
|
@@ -297,8 +297,7 @@ module Recapi
|
|
|
297
297
|
@status >= 500
|
|
298
298
|
end
|
|
299
299
|
|
|
300
|
-
# Whether recapi couldn't answer in time or failed on its side.
|
|
301
|
-
# the tenant's own limit and a 4xx an integration bug: a fallback would hide both.
|
|
300
|
+
# Whether recapi couldn't answer in time or failed on its side.
|
|
302
301
|
def outage?
|
|
303
302
|
%w[network timeout].include?(@code) || @status >= 500
|
|
304
303
|
end
|
|
@@ -319,7 +318,8 @@ module Recapi
|
|
|
319
318
|
end
|
|
320
319
|
|
|
321
320
|
# In-process store keeping the most recently used max_users users. Pass a
|
|
322
|
-
# shared one (Redis, Rails.cache
|
|
321
|
+
# shared one (Redis, a Rails.cache on Redis, Memcached or Solid Cache) when
|
|
322
|
+
# several processes serve the same users.
|
|
323
323
|
class MemoryStore
|
|
324
324
|
def initialize(max_users: 10_000)
|
|
325
325
|
@max = [1, max_users].max
|
|
@@ -353,11 +353,21 @@ module Recapi
|
|
|
353
353
|
# Bundler app without it in its Gemfile can't require.
|
|
354
354
|
class StderrLogger
|
|
355
355
|
def warn(message)
|
|
356
|
-
|
|
356
|
+
write_line(message)
|
|
357
357
|
end
|
|
358
358
|
|
|
359
359
|
def error(message)
|
|
360
|
+
write_line(message)
|
|
361
|
+
end
|
|
362
|
+
|
|
363
|
+
private
|
|
364
|
+
|
|
365
|
+
# A full disk or a closed stderr must not reach the app's track or kill the
|
|
366
|
+
# sender thread: a line nobody can read is no reason to stop sending.
|
|
367
|
+
def write_line(message)
|
|
360
368
|
$stderr.write("#{message}\n")
|
|
369
|
+
rescue StandardError
|
|
370
|
+
nil
|
|
361
371
|
end
|
|
362
372
|
end
|
|
363
373
|
|
|
@@ -377,6 +387,7 @@ module Recapi
|
|
|
377
387
|
LEVEL_NAMES = { "view" => 3, "cart" => 5, "purchase" => 10, "reject" => -10 }.freeze
|
|
378
388
|
# Events waiting for a send: a minute-long outage at 150 events/s fits.
|
|
379
389
|
MAX_QUEUE = 10_000
|
|
390
|
+
LOST_LINE_MS = 60_000
|
|
380
391
|
MAX_FLUSH_BACKOFF = 60.0
|
|
381
392
|
RETRIES = 3
|
|
382
393
|
RETRY_BASE = 0.5
|
|
@@ -396,6 +407,16 @@ module Recapi
|
|
|
396
407
|
# starts afresh. It bounds a Redis at about one month's visitors instead of
|
|
397
408
|
# growing for ever.
|
|
398
409
|
STATE_LIFETIME_SECONDS = 30 * 24 * 60 * 60
|
|
410
|
+
# ActiveSupport's caches that lose visitors' state, by exact class: a subclass
|
|
411
|
+
# may have changed what makes them so. They keep nothing or only in this
|
|
412
|
+
# process, where our MemoryStore is as local, holds more and competes with
|
|
413
|
+
# nothing else in the app's cache.
|
|
414
|
+
USE_OURS = {
|
|
415
|
+
"ActiveSupport::Cache::NullStore" => "keeps nothing",
|
|
416
|
+
"ActiveSupport::Cache::MemoryStore" => "keeps its entries in this process only"
|
|
417
|
+
}.freeze
|
|
418
|
+
FILE_STORE = "ActiveSupport::Cache::FileStore"
|
|
419
|
+
private_constant :USE_OURS, :FILE_STORE
|
|
399
420
|
# Where redis-rb defines set: 4.x and 5 on, older versions, Redis::Distributed.
|
|
400
421
|
REDIS_RB_SET = %w[Redis::Commands::Strings Redis Redis::Distributed].freeze
|
|
401
422
|
# Open connections kept between calls: one per call in flight at the busiest moment.
|
|
@@ -426,7 +447,8 @@ module Recapi
|
|
|
426
447
|
# api_key: secret key (rk_sec_...): a server can then restore a user's
|
|
427
448
|
# history from recapi when the store lacks it. base_url: your recapi API
|
|
428
449
|
# origin. store: per-user state, anything with get/set/delete (a Redis
|
|
429
|
-
# client) or read/write/delete (Rails.cache); defaults to a MemoryStore
|
|
450
|
+
# client) or read/write/delete (Rails.cache); defaults to a MemoryStore,
|
|
451
|
+
# which also replaces ActiveSupport's NullStore and MemoryStore.
|
|
430
452
|
# timeout: per-request seconds (recommend() uses at most 1.5).
|
|
431
453
|
# flush_interval: seconds between background sends. max_batch: events per
|
|
432
454
|
# request, at most the API's 1,000. logger: where failures are logged,
|
|
@@ -443,12 +465,14 @@ module Recapi
|
|
|
443
465
|
raise ArgumentError, "base_url must be an http(s) URL"
|
|
444
466
|
end
|
|
445
467
|
|
|
446
|
-
@
|
|
468
|
+
@logger = logger || StderrLogger.new
|
|
469
|
+
@limit_lost_lines = logger.nil?
|
|
470
|
+
@lost_printed = {}
|
|
471
|
+
@store = store ? store_to_use(store) : MemoryStore.new
|
|
447
472
|
@store_lifetime = store_lifetime
|
|
448
473
|
@timeout = timeout.to_f
|
|
449
474
|
@interval = flush_interval.to_f
|
|
450
475
|
@max_batch = max_batch.to_i.clamp(1, MAX_EVENTS_PER_REQUEST)
|
|
451
|
-
@logger = logger || StderrLogger.new
|
|
452
476
|
# Two environments' keys may share one Redis: their users must not mix.
|
|
453
477
|
@prefix = "recapi:#{Digest::SHA256.hexdigest(api_key)[0, 12]}:"
|
|
454
478
|
# Indirections the tests replace (clock, backoff sleep, jitter).
|
|
@@ -526,10 +550,12 @@ module Recapi
|
|
|
526
550
|
# for user_id and returns it for the store. A history the store started
|
|
527
551
|
# without it (a track() or identify() came first) gets recapi's fetched
|
|
528
552
|
# once, within the same deadline, and merged in. No retry, at most 1.5 s:
|
|
529
|
-
# on a network error, timeout or
|
|
530
|
-
# no id) and logs the error. If those fail too (recapi is down
|
|
531
|
-
# is empty: hide the slot.
|
|
532
|
-
#
|
|
553
|
+
# on a network error, timeout, 5xx or 429 it returns popular items (fallback,
|
|
554
|
+
# no id) and logs the error. If those fail too (recapi is down, or the plan's
|
|
555
|
+
# limit covers them), the list is empty: hide the slot. On a 401 or 403 (a
|
|
556
|
+
# revoked key, a suspended shop) it is empty at once, as popular would be
|
|
557
|
+
# refused too. Any other failure raises: a bad request or a reply that isn't
|
|
558
|
+
# the API's can't start on a live site without a deploy.
|
|
533
559
|
def recommend(user_id: nil, anon_id: nil, count: 0, placement: nil, tags_any: nil, tags_all: nil,
|
|
534
560
|
exclude: nil, context_item_id: nil, discovery: nil)
|
|
535
561
|
deadline = monotonic + recommend_timeout
|
|
@@ -557,7 +583,7 @@ module Recapi
|
|
|
557
583
|
)
|
|
558
584
|
rec_id, items = parse_recommendations(response)
|
|
559
585
|
rescue Error => e
|
|
560
|
-
raise unless e
|
|
586
|
+
raise unless spare_the_page?(e)
|
|
561
587
|
|
|
562
588
|
return fallback(e, count, excluded, context_item_id, tags_any, tags_all)
|
|
563
589
|
end
|
|
@@ -621,9 +647,16 @@ module Recapi
|
|
|
621
647
|
nil
|
|
622
648
|
end
|
|
623
649
|
|
|
624
|
-
# Non-personalised popular items, for pages without a user (no retry).
|
|
650
|
+
# Non-personalised popular items, for pages without a user (no retry). On a
|
|
651
|
+
# network error, timeout, 5xx, 429, 401 or 403 it logs the error and returns
|
|
652
|
+
# an empty list: hide the slot. Any other failure raises, as in recommend.
|
|
625
653
|
def popular(count: DEFAULT_COUNT, tags_any: nil, tags_all: nil)
|
|
626
654
|
fetch_popular(count, tags_any, tags_all, nil)
|
|
655
|
+
rescue Error => e
|
|
656
|
+
raise unless spare_the_page?(e)
|
|
657
|
+
|
|
658
|
+
log_list(e, "recapi: popular items failed, served no items: #{e.code}: #{e.message}")
|
|
659
|
+
[]
|
|
627
660
|
end
|
|
628
661
|
|
|
629
662
|
# Creates or replaces items (hashes of the API's item fields: item_id,
|
|
@@ -718,6 +751,7 @@ module Recapi
|
|
|
718
751
|
@send_lock = Mutex.new
|
|
719
752
|
@thread = nil
|
|
720
753
|
@failures = 0
|
|
754
|
+
@overflow_printed = false
|
|
721
755
|
@closed = false
|
|
722
756
|
@idle = []
|
|
723
757
|
@idle_lock = Mutex.new
|
|
@@ -777,6 +811,13 @@ module Recapi
|
|
|
777
811
|
def drop_overflow
|
|
778
812
|
dropped = @queue.size - MAX_QUEUE
|
|
779
813
|
@queue.shift(dropped)
|
|
814
|
+
# A full queue drops on every track through an outage: on $stderr, which
|
|
815
|
+
# the operator can't filter, one line until a send works is enough, and
|
|
816
|
+
# the "sending failed" lines keep showing the outage. A logger given gets
|
|
817
|
+
# them all. Runs under @mutex.
|
|
818
|
+
return if @limit_lost_lines && @overflow_printed
|
|
819
|
+
|
|
820
|
+
@overflow_printed = true
|
|
780
821
|
@logger.warn("recapi: event queue full, dropped the #{dropped} oldest events")
|
|
781
822
|
end
|
|
782
823
|
|
|
@@ -809,7 +850,7 @@ module Recapi
|
|
|
809
850
|
send_events(batch, retry_errors)
|
|
810
851
|
rescue StandardError => e
|
|
811
852
|
if e.is_a?(Error) && !e.retryable?
|
|
812
|
-
|
|
853
|
+
log_lost(e.code, "recapi: dropped #{batch.size} events: #{e.message}")
|
|
813
854
|
next
|
|
814
855
|
end
|
|
815
856
|
# Anything else keeps the batch, a bug of ours included: event ids
|
|
@@ -823,7 +864,10 @@ module Recapi
|
|
|
823
864
|
@logger.warn("recapi: sending #{batch.size} events failed, kept: #{e.message}")
|
|
824
865
|
return
|
|
825
866
|
end
|
|
826
|
-
@mutex.synchronize
|
|
867
|
+
@mutex.synchronize do
|
|
868
|
+
@failures = 0
|
|
869
|
+
@overflow_printed = false
|
|
870
|
+
end
|
|
827
871
|
end
|
|
828
872
|
end
|
|
829
873
|
end
|
|
@@ -850,7 +894,38 @@ module Recapi
|
|
|
850
894
|
detail = rejected.first(5).map do |r|
|
|
851
895
|
r.is_a?(Hash) && r["index"].is_a?(Integer) ? r.merge("event" => events[r["index"]]) : r
|
|
852
896
|
end
|
|
853
|
-
|
|
897
|
+
log_lost(:rejected, "recapi: #{rejected.size} event(s) rejected: #{JSON.generate(detail)}")
|
|
898
|
+
end
|
|
899
|
+
|
|
900
|
+
# A revoked key refuses every batch and the sender runs on with no backoff,
|
|
901
|
+
# so $stderr gets one line a minute per kind (error code, or rejected
|
|
902
|
+
# events): one line per outage would have aged out of the log by the time
|
|
903
|
+
# someone looks. A logger given gets them all.
|
|
904
|
+
def log_lost(kind, message)
|
|
905
|
+
@logger.error(message) if line_due?(kind)
|
|
906
|
+
end
|
|
907
|
+
|
|
908
|
+
# A list call's failure, one per page view through a revoked key or an
|
|
909
|
+
# outage: limited like lost events on $stderr, one line a minute per code
|
|
910
|
+
# whichever call hit it. Its own kind, or a list line would mute the line
|
|
911
|
+
# saying events are being lost.
|
|
912
|
+
def log_list(error, message)
|
|
913
|
+
@logger.warn(message) if line_due?("list #{error.code}")
|
|
914
|
+
end
|
|
915
|
+
|
|
916
|
+
# Any app thread can get here, next to the sender: not while holding @mutex.
|
|
917
|
+
def line_due?(kind)
|
|
918
|
+
return true unless @limit_lost_lines
|
|
919
|
+
|
|
920
|
+
now = @clock.call
|
|
921
|
+
@mutex.synchronize do
|
|
922
|
+
last = @lost_printed[kind]
|
|
923
|
+
# abs: a clock set back must not mute the kind until it catches up.
|
|
924
|
+
next false if last && (now - last).abs < LOST_LINE_MS
|
|
925
|
+
|
|
926
|
+
@lost_printed[kind] = now
|
|
927
|
+
true
|
|
928
|
+
end
|
|
854
929
|
end
|
|
855
930
|
|
|
856
931
|
# Calls the block, retrying retryable errors with jittered exponential
|
|
@@ -873,7 +948,25 @@ module Recapi
|
|
|
873
948
|
|
|
874
949
|
# --- recommendations ------------------------------------------------------
|
|
875
950
|
|
|
951
|
+
# Whether recommend and popular answer this failure with a list instead of
|
|
952
|
+
# raising it. An outage, a limit or a revoked key can start on a live site
|
|
953
|
+
# with no deploy, and a page must not pay for it: the log and the dashboard
|
|
954
|
+
# show it. What's left (a bad request, a reply that isn't the API's) can't
|
|
955
|
+
# start without a deploy, and a developer sees it on the first run.
|
|
956
|
+
def spare_the_page?(error)
|
|
957
|
+
error.outage? || error.status == 429 || key_refused?(error)
|
|
958
|
+
end
|
|
959
|
+
|
|
960
|
+
# A key or shop recapi won't serve: any other call fails too.
|
|
961
|
+
def key_refused?(error)
|
|
962
|
+
[401, 403].include?(error.status)
|
|
963
|
+
end
|
|
964
|
+
|
|
876
965
|
def fallback(error, count, excluded, context_item_id, tags_any, tags_all)
|
|
966
|
+
if key_refused?(error)
|
|
967
|
+
log_list(error, "recapi: recommendations refused, served no items: #{error.code}: #{error.message}")
|
|
968
|
+
return Recommendations.new(recommendation_id: nil, fallback: true, items: [])
|
|
969
|
+
end
|
|
877
970
|
# The requested length without the excluded items, so a few more are
|
|
878
971
|
# asked for. 0 is the recommendations default; popular refuses it.
|
|
879
972
|
n = count.to_i.zero? ? DEFAULT_COUNT : count.to_i
|
|
@@ -882,12 +975,13 @@ module Recapi
|
|
|
882
975
|
begin
|
|
883
976
|
popular = fetch_popular([n + skip.size, MAX_COUNT].min, tags_any, tags_all, recommend_timeout)
|
|
884
977
|
rescue Error => e
|
|
885
|
-
# recapi is down
|
|
886
|
-
# exception that fails the whole page.
|
|
887
|
-
|
|
978
|
+
# recapi is down or the limit covers popular too: an empty list the page
|
|
979
|
+
# can hide beats an exception that fails the whole page.
|
|
980
|
+
log_list(error, "recapi: recommendations failed (#{error.code}: #{error.message}), popular too, " \
|
|
981
|
+
"served no items: #{e.code}: #{e.message}")
|
|
888
982
|
return Recommendations.new(recommendation_id: nil, fallback: true, items: [])
|
|
889
983
|
end
|
|
890
|
-
|
|
984
|
+
log_list(error, "recapi: recommendations failed, served popular items: #{error.code}: #{error.message}")
|
|
891
985
|
items = popular.reject { |item| skip.key?(item.item_id) }.first(n)
|
|
892
986
|
Recommendations.new(recommendation_id: nil, fallback: true, items: items)
|
|
893
987
|
end
|
|
@@ -904,7 +998,9 @@ module Recapi
|
|
|
904
998
|
snapshot = request("GET", path, query: query, timeout: (deadline - monotonic) / 2)
|
|
905
999
|
raise Error.new("invalid_response", "malformed history response") unless snapshot.is_a?(Hash)
|
|
906
1000
|
rescue Error => e
|
|
907
|
-
|
|
1001
|
+
# The same limit as the list's own line: a revoked key fails this first
|
|
1002
|
+
# on every recommend for a user with a local history.
|
|
1003
|
+
log_list(e, "recapi: could not restore the user's stored history: #{e.code}: #{e.message}")
|
|
908
1004
|
return state
|
|
909
1005
|
end
|
|
910
1006
|
with_locks(key) do
|
|
@@ -1020,10 +1116,30 @@ module Recapi
|
|
|
1020
1116
|
@logger.error("recapi: store write failed: #{e.class}: #{e.message}")
|
|
1021
1117
|
end
|
|
1022
1118
|
|
|
1119
|
+
# The store, or our own in its place if it is an ActiveSupport cache that
|
|
1120
|
+
# loses state. Says so in one line, at start only. Any doubt, or a store
|
|
1121
|
+
# that fails here, means the store as given.
|
|
1122
|
+
def store_to_use(store)
|
|
1123
|
+
name = store.class.name
|
|
1124
|
+
if USE_OURS.key?(name)
|
|
1125
|
+
@logger.warn("recapi: #{name} #{USE_OURS[name]}, so recapi uses its own in-process store (10,000 users). " \
|
|
1126
|
+
"For several processes or servers, use Redis, Memcached or Solid Cache.")
|
|
1127
|
+
return MemoryStore.new
|
|
1128
|
+
end
|
|
1129
|
+
if name == FILE_STORE
|
|
1130
|
+
@logger.warn("recapi: #{name} isn't shared between servers, and frees an expired entry only when it is " \
|
|
1131
|
+
"read again or cleanup runs. Run Rails.cache.cleanup on a schedule; for several servers, " \
|
|
1132
|
+
"use Redis, Memcached or Solid Cache.")
|
|
1133
|
+
end
|
|
1134
|
+
store
|
|
1135
|
+
rescue StandardError
|
|
1136
|
+
store
|
|
1137
|
+
end
|
|
1138
|
+
|
|
1023
1139
|
# What makes this store's write expire the entry. By class name, since the
|
|
1024
1140
|
# library requires neither gem. Any doubt (a subclass's own set, a wrapper
|
|
1025
|
-
# such as ConnectionPool::Wrapper) means no option,
|
|
1026
|
-
# customer's.
|
|
1141
|
+
# such as ConnectionPool::Wrapper, a store that fails here) means no option,
|
|
1142
|
+
# as for a store of the customer's.
|
|
1027
1143
|
def store_lifetime
|
|
1028
1144
|
klass = @store.class
|
|
1029
1145
|
if klass.public_method_defined?(:set)
|
|
@@ -1033,6 +1149,8 @@ module Recapi
|
|
|
1033
1149
|
else
|
|
1034
1150
|
{}
|
|
1035
1151
|
end
|
|
1152
|
+
rescue StandardError
|
|
1153
|
+
{}
|
|
1036
1154
|
end
|
|
1037
1155
|
|
|
1038
1156
|
# Redis clients have get/set/del, Rails.cache read/write/delete.
|