recapi 0.1.7 → 0.1.9

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.
Files changed (4) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +15 -10
  3. data/lib/recapi.rb +85 -23
  4. metadata +2 -2
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: f8edb463693be71a5cac3a101441d5fe6c045e5e58f4003025291995ec5c9e44
4
- data.tar.gz: 818ea20b257819a76f15c832af44b83694681fc36995f08b91987ac2b9e8afdf
3
+ metadata.gz: 28f52d6426fd83d0b14d106535a06fca9e6d29ac56b4a3b366ae31f8ca7e22df
4
+ data.tar.gz: 93361e6a7d6dcbbc86be19b92ccc7fb4bc3b3695f99fa701ad08cfea17ccb57f
5
5
  SHA512:
6
- metadata.gz: cb54199fc5b2ff480e94be20d594598a2cbda5fb2b1b8ffb854b3dd4ac0dd3d9d2858b05e67cc79b264d93f41f4e5132b57c50812aa5c626582583d369763df7
7
- data.tar.gz: 33fbcbfc1cca21caf75849d106e9500236d6adf2ac897c74b49e9731eb79b6680cb1054e637677babbd0ebc52fc853aa7a999ff10a1e11911da5ff01bb538c41
6
+ metadata.gz: 54a7bf72a2b956ed847fe57af69c3241af18c638a199a86aa3220b2f0726d495402a3faa4698e011f815f57881e5969090bf9047b28b60bc0b6d11767f88eacf
7
+ data.tar.gz: a7825355e8be66451b687bc342a8c9961f8b7f8bc4c04fb7c57a38442ab59ed12daf67be7b04a39cba4b7a76843c5faec071e35dbcc15a5b3a1aba6f5154ae4b
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.7.rb
33
+ curl -fLo lib/recapi.rb https://api.<your-domain>/sdk/ruby/recapi-0.1.9.rb
34
34
  ```
35
35
 
36
36
  ## Quick start
@@ -62,18 +62,22 @@ Ids may be strings or integers (an ActiveRecord id): they travel as strings.
62
62
 
63
63
  ## Calls
64
64
 
65
- A refused argument (an invalid id or level) raises `ArgumentError`, and an
66
- API failure `Recapi::Error` (`code`, `status`, `retry_after`, `retryable?`,
67
- `outage?`).
65
+ A refused argument (an invalid id or level) raises `ArgumentError`, except an
66
+ `item_id` or `context_item_id` the API would refuse, as a page often takes those
67
+ from a visitor's URL (see the table). An API failure is a `Recapi::Error` (`code`, `status`, `retry_after`, `retryable?`,
68
+ `outage?`). `recommend` and `popular` still raise on a bad request (400, 404,
69
+ 413, other 3xx/4xx) or a reply that isn't the API's; an outage, a limit or a
70
+ refused key can start on a live site with no deploy, so they answer with a list
71
+ and a log line.
68
72
 
69
73
  | Call | What it does |
70
74
  |---|---|
71
- | `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). |
75
+ | `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). An `item_id` the API would refuse (1-256 bytes of UTF-8, no control character; also `nil`, an Array or a Hash) drops the event with a log line: nothing raises, and the other events are sent as usual. A bad `level`, `user_id`, `anon_id` or `recommendation_id` still raises `ArgumentError`. |
72
76
  | `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
77
  | `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 5xx it returns popular items (`fallback?`, no id), or no item when recapi is down: hide the slot. A 4xx or 429 raises. |
78
+ | `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. A `context_item_id` the API would refuse (also an Array or a Hash, as `params[:id]` gives for `?id[]=a`) isn't sent: you get the same popular list and a log line, with no recommendation request. Any other failure (a bad request, a reply that isn't the API's) raises. |
75
79
  | `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. |
80
+ | `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
81
  | `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
82
  | `delete_user(user_id)` | Erases a user's events in recapi and their state in the store, retried like events. |
79
83
 
@@ -94,9 +98,10 @@ queue and sender at its first call. Proxies come from `HTTPS_PROXY`,
94
98
  `HTTP_PROXY` and `NO_PROXY`, as `Net::HTTP` reads them. Failures are logged
95
99
  to `logger:`, anything with `warn` and `error` (`Rails.logger`, a
96
100
  `Logger`); without one they go to `$stderr` as `recapi: …` lines, with lost
97
- events (a refused batch, rejected events) at most one line a minute for each
98
- error code and for rejected events, so a revoked key on a busy server doesn't
99
- flood the log, and a full queue one line until a send works. A failed write to
101
+ events (a refused batch, rejected events, a dropped `item_id`) at most one line a
102
+ minute for each error code, for rejected events and for dropped ids, and `recommend`'s and `popular`'s failures
103
+ at most one line a minute for each error code, so a revoked key on a busy server
104
+ doesn't flood the log, and a full queue one line until a send works. A failed write to
100
105
  `$stderr` (a full disk, a closed stream) is ignored. A logger you give gets
101
106
  every line, and if it raises, that reaches your code.
102
107
 
data/lib/recapi.rb CHANGED
@@ -25,7 +25,7 @@ rescue LoadError
25
25
  end
26
26
 
27
27
  module Recapi
28
- VERSION = "0.1.7"
28
+ VERSION = "0.1.9"
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. A 429 is
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
@@ -488,14 +487,22 @@ module Recapi
488
487
  # is queued. level is an integer -10 to 10 or :view (3), :cart (5),
489
488
  # :purchase (10), :reject (-10: never recommend the item to this user
490
489
  # again until a positive event on it). recommendation_id overrides the
491
- # automatic attribution. Ids may be strings or integers.
490
+ # automatic attribution. Ids may be strings or integers. An item_id the API
491
+ # would refuse raises nothing: a page often takes it from a visitor's URL, so
492
+ # the event is dropped and logged instead.
492
493
  def track(item_id, level, user_id: nil, anon_id: nil, recommendation_id: nil)
493
494
  level = level_value(level)
494
- item_id = id_string(item_id)
495
- raise ArgumentError, "item_id #{ID_RULE}" unless History.id?(item_id)
496
-
497
495
  user_id, anon_id, recommendation_id = check_ids(user_id: user_id, anon_id: anon_id,
498
496
  recommendation_id: recommendation_id)
497
+ item_id = id_string(item_id)
498
+ # A crafted link must not fail the page. Nothing is kept: in the history it
499
+ # would make the API refuse every later list. The line never quotes the
500
+ # visitor's id.
501
+ unless History.id?(item_id)
502
+ log_lost(:item_id, "recapi: event dropped: item_id #{ID_RULE}")
503
+ return nil
504
+ end
505
+
499
506
  t = now_ms
500
507
  attributed = recommendation_id
501
508
  key = key_for(user_id, anon_id)
@@ -551,10 +558,15 @@ module Recapi
551
558
  # for user_id and returns it for the store. A history the store started
552
559
  # without it (a track() or identify() came first) gets recapi's fetched
553
560
  # once, within the same deadline, and merged in. No retry, at most 1.5 s:
554
- # on a network error, timeout or 5xx it returns popular items (fallback,
555
- # no id) and logs the error. If those fail too (recapi is down), the list
556
- # is empty: hide the slot. A 4xx or 429 raises: a fallback would hide an
557
- # integration bug or a plan limit.
561
+ # on a network error, timeout, 5xx or 429 it returns popular items (fallback,
562
+ # no id) and logs the error. If those fail too (recapi is down, or the plan's
563
+ # limit covers them), the list is empty: hide the slot. On a 401 or 403 (a
564
+ # revoked key, a suspended shop) it is empty at once, as popular would be
565
+ # refused too. A context_item_id the API would refuse (a page often takes it
566
+ # from a visitor's URL: Rails' params[:id] can be an Array or a Hash) is never
567
+ # sent: the answer is the same popular list. Any other failure raises: a bad
568
+ # request or a reply that isn't the API's can't start on a live site without
569
+ # a deploy.
558
570
  def recommend(user_id: nil, anon_id: nil, count: 0, placement: nil, tags_any: nil, tags_all: nil,
559
571
  exclude: nil, context_item_id: nil, discovery: nil)
560
572
  deadline = monotonic + recommend_timeout
@@ -564,6 +576,13 @@ module Recapi
564
576
  key = key_for(user_id, anon_id)
565
577
  t = now_ms
566
578
  state = key.nil? ? UserState.new : load(key)
579
+ unless context_item_id.nil? || context_item_id == "" || History.id?(context_item_id)
580
+ _, _, rejected = state.history.wire(t)
581
+ # The message never quotes the id: a visitor may have written it. nil:
582
+ # not skipped in the list either, as no item can have this id.
583
+ cause = Error.new("invalid_request", "context_item_id #{ID_RULE}")
584
+ return fallback(cause, count, with_rejected(exclude, rejected), nil, tags_any, tags_all)
585
+ end
567
586
  if user_id && !state.restored && !state.history.empty? && !@api_key.start_with?(PUBLIC_KEY_PREFIX)
568
587
  state = restore(key, user_id, state, deadline, t)
569
588
  end
@@ -582,7 +601,7 @@ module Recapi
582
601
  )
583
602
  rec_id, items = parse_recommendations(response)
584
603
  rescue Error => e
585
- raise unless e.outage?
604
+ raise unless spare_the_page?(e)
586
605
 
587
606
  return fallback(e, count, excluded, context_item_id, tags_any, tags_all)
588
607
  end
@@ -646,9 +665,16 @@ module Recapi
646
665
  nil
647
666
  end
648
667
 
649
- # Non-personalised popular items, for pages without a user (no retry).
668
+ # Non-personalised popular items, for pages without a user (no retry). On a
669
+ # network error, timeout, 5xx, 429, 401 or 403 it logs the error and returns
670
+ # an empty list: hide the slot. Any other failure raises, as in recommend.
650
671
  def popular(count: DEFAULT_COUNT, tags_any: nil, tags_all: nil)
651
672
  fetch_popular(count, tags_any, tags_all, nil)
673
+ rescue Error => e
674
+ raise unless spare_the_page?(e)
675
+
676
+ log_list(e, "recapi: popular items failed, served no items: #{e.code}: #{e.message}")
677
+ []
652
678
  end
653
679
 
654
680
  # Creates or replaces items (hashes of the API's item fields: item_id,
@@ -892,17 +918,32 @@ module Recapi
892
918
  # A revoked key refuses every batch and the sender runs on with no backoff,
893
919
  # so $stderr gets one line a minute per kind (error code, or rejected
894
920
  # events): one line per outage would have aged out of the log by the time
895
- # someone looks. A logger given gets them all. Runs under @send_lock.
921
+ # someone looks. A logger given gets them all.
896
922
  def log_lost(kind, message)
897
- if @limit_lost_lines
898
- now = @clock.call
923
+ @logger.error(message) if line_due?(kind)
924
+ end
925
+
926
+ # A list call's failure, one per page view through a revoked key or an
927
+ # outage: limited like lost events on $stderr, one line a minute per code
928
+ # whichever call hit it. Its own kind, or a list line would mute the line
929
+ # saying events are being lost.
930
+ def log_list(error, message)
931
+ @logger.warn(message) if line_due?("list #{error.code}")
932
+ end
933
+
934
+ # Any app thread can get here, next to the sender: not while holding @mutex.
935
+ def line_due?(kind)
936
+ return true unless @limit_lost_lines
937
+
938
+ now = @clock.call
939
+ @mutex.synchronize do
899
940
  last = @lost_printed[kind]
900
941
  # abs: a clock set back must not mute the kind until it catches up.
901
- return if last && (now - last).abs < LOST_LINE_MS
942
+ next false if last && (now - last).abs < LOST_LINE_MS
902
943
 
903
944
  @lost_printed[kind] = now
945
+ true
904
946
  end
905
- @logger.error(message)
906
947
  end
907
948
 
908
949
  # Calls the block, retrying retryable errors with jittered exponential
@@ -925,7 +966,25 @@ module Recapi
925
966
 
926
967
  # --- recommendations ------------------------------------------------------
927
968
 
969
+ # Whether recommend and popular answer this failure with a list instead of
970
+ # raising it. An outage, a limit or a revoked key can start on a live site
971
+ # with no deploy, and a page must not pay for it: the log and the dashboard
972
+ # show it. What's left (a bad request, a reply that isn't the API's) can't
973
+ # start without a deploy, and a developer sees it on the first run.
974
+ def spare_the_page?(error)
975
+ error.outage? || error.status == 429 || key_refused?(error)
976
+ end
977
+
978
+ # A key or shop recapi won't serve: any other call fails too.
979
+ def key_refused?(error)
980
+ [401, 403].include?(error.status)
981
+ end
982
+
928
983
  def fallback(error, count, excluded, context_item_id, tags_any, tags_all)
984
+ if key_refused?(error)
985
+ log_list(error, "recapi: recommendations refused, served no items: #{error.code}: #{error.message}")
986
+ return Recommendations.new(recommendation_id: nil, fallback: true, items: [])
987
+ end
929
988
  # The requested length without the excluded items, so a few more are
930
989
  # asked for. 0 is the recommendations default; popular refuses it.
931
990
  n = count.to_i.zero? ? DEFAULT_COUNT : count.to_i
@@ -934,12 +993,13 @@ module Recapi
934
993
  begin
935
994
  popular = fetch_popular([n + skip.size, MAX_COUNT].min, tags_any, tags_all, recommend_timeout)
936
995
  rescue Error => e
937
- # recapi is down altogether: an empty list the page can hide beats an
938
- # exception that fails the whole page.
939
- @logger.warn("recapi: recommendations failed (#{error.message}), popular too, served no items: #{e.message}")
996
+ # recapi is down or the limit covers popular too: an empty list the page
997
+ # can hide beats an exception that fails the whole page.
998
+ log_list(error, "recapi: recommendations failed (#{error.code}: #{error.message}), popular too, " \
999
+ "served no items: #{e.code}: #{e.message}")
940
1000
  return Recommendations.new(recommendation_id: nil, fallback: true, items: [])
941
1001
  end
942
- @logger.warn("recapi: recommendations failed, served popular items: #{error.message}")
1002
+ log_list(error, "recapi: recommendations failed, served popular items: #{error.code}: #{error.message}")
943
1003
  items = popular.reject { |item| skip.key?(item.item_id) }.first(n)
944
1004
  Recommendations.new(recommendation_id: nil, fallback: true, items: items)
945
1005
  end
@@ -956,7 +1016,9 @@ module Recapi
956
1016
  snapshot = request("GET", path, query: query, timeout: (deadline - monotonic) / 2)
957
1017
  raise Error.new("invalid_response", "malformed history response") unless snapshot.is_a?(Hash)
958
1018
  rescue Error => e
959
- @logger.warn("recapi: could not restore the user's stored history: #{e.message}")
1019
+ # The same limit as the list's own line: a revoked key fails this first
1020
+ # on every recommend for a user with a local history.
1021
+ log_list(e, "recapi: could not restore the user's stored history: #{e.code}: #{e.message}")
960
1022
  return state
961
1023
  end
962
1024
  with_locks(key) do
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: recapi
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.7
4
+ version: 0.1.9
5
5
  platform: ruby
6
6
  authors:
7
7
  - recapi
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-11-04 00:00:00.000000000 Z
11
+ date: 2026-11-05 00:00:00.000000000 Z
12
12
  dependencies: []
13
13
  description: 'Ruby client for the recapi recommendation API: per-user history, event
14
14
  batching, retries, popular fallback. Standard library only.'