recapi 0.1.12 → 0.1.14

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 +23 -2
  3. data/lib/recapi.rb +164 -66
  4. metadata +2 -2
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 5494f67d90d8ce8686f9036fd05c9f1549a2af21a3af16734d82415bcf98fcde
4
- data.tar.gz: e41d02f51ea550051320c17a5d2c93917caa9b9e87ae8b9cf1e626f2ff4ff353
3
+ metadata.gz: c186cf0df3db7d2776e851d0f4658a85808efaa8502374b95affe38142c99cd5
4
+ data.tar.gz: b14927279881bd3799bb8caed8203c7c9389869f999eaf980983b847b67e7ed8
5
5
  SHA512:
6
- metadata.gz: bf77268b88e6b47414b83d527afab3a6766683d06d6793298b8a246a0d613b4a51fc8116ffc42ae78ff9e4af20ee28f0177cc7cb1fd60cad3e49b9ec488176c8
7
- data.tar.gz: a69a0f1965f86bfeb71b33696cf5dd945b74c3cdbacab24c2e80bd0009129edb54ac92dba2a197d2dad5f7752ff0159dc190afc504dd452398f919d8af1c2233
6
+ metadata.gz: 0b42e390927a5e6b3d9d6bd85df4d45d0e8ce59081ae64a215f2174da1da42e45ed08855bdb47a41f3bec3c5e1f778a9ef51413f602d69afcfb733295c609a9c
7
+ data.tar.gz: 29fb702a44c2eed7dbda2c4a374c9919acc0874d7fe6482150189b5099958c76594c3f56c002f575dd74e8af24d75388f0b86fbe28db741442c3d8c7b40a69a0
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.12.rb
33
+ curl -fLo lib/recapi.rb https://api.<your-domain>/sdk/ruby/recapi-0.1.14.rb
34
34
  ```
35
35
 
36
36
  ## Quick start
@@ -60,6 +60,22 @@ end
60
60
 
61
61
  Ids may be strings or integers (an ActiveRecord id): they travel as strings.
62
62
 
63
+ ### Several rows in one call
64
+
65
+ A page with several rows asks them in one call, billed as one recommendation;
66
+ an item appears on one row only unless `allow_repeats: true`:
67
+
68
+ ```ruby
69
+ # One Recapi::Recommendations per list, in order.
70
+ similar, accessories = RECAPI.recommend_lists(user_id: current_user.id, exclude: cart_ids, lists: [
71
+ { placement: "product", count: 4, context_item_id: product.id },
72
+ { placement: "cart", count: 6, tags_any: ["accessories"] }
73
+ ])
74
+ ```
75
+
76
+ Each list takes `recommend`'s `placement`, `count`, `tags_any`, `tags_all`,
77
+ `exclude`, `context_item_id` and `discovery`; it fails and falls back as `recommend` does, row by row.
78
+
63
79
  ## Calls
64
80
 
65
81
  A refused argument (an invalid id or level) raises `ArgumentError`, except an
@@ -78,7 +94,7 @@ and a log line.
78
94
  | `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. |
79
95
  | `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. |
80
96
  | `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`. |
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. |
97
+ | `upsert_items(items, merge:)` | Creates or replaces items (hashes of `item_id`, `title`, `tags`, `metadata`…), 1,000 per request, retried like events. Returns how many were stored. With `merge: true` each item changes only the fields it sends and the others keep their stored values (a tags-only sync keeps the title and metadata); to clear a field, replace the item. A bad item doesn't keep the others out: once every request is sent, `Recapi::RejectedItems` (an `invalid_request` `Recapi::Error`) is raised with `upserted` and `rejected`, `[index in items, message]` pairs. |
82
98
  | `delete_user(user_id)` | Erases a user's events in recapi and their state in the store, retried like events. |
83
99
 
84
100
  `Recapi::Client.new(api_key, base_url, store:, timeout:, flush_interval:,
@@ -124,6 +140,11 @@ so a visitor who never returns stays on disk (about 8 KB each): run
124
140
 
125
141
  ## Changes
126
142
 
143
+ - 2026-11-15: version 0.1.14. `recommend_lists` asks a page's rows in one call,
144
+ billed as one recommendation.
145
+ - 2026-11-14: version 0.1.13. `upsert_items(items, merge: true)` changes only the
146
+ fields sent. A bad item no longer fails its batch of 1,000: the others are stored,
147
+ and `Recapi::RejectedItems` lists the refused ones once every request is sent.
127
148
  - 2026-11-07: version 0.1.12. A saved history time ahead of the clock reads as now,
128
149
  and a damaged weight is sent as the API's limit (1e6). A time months ahead, or a
129
150
  weight past that limit, used to get a 400 on every list, and far enough past it
data/lib/recapi.rb CHANGED
@@ -25,7 +25,7 @@ rescue LoadError
25
25
  end
26
26
 
27
27
  module Recapi
28
- VERSION = "0.1.12"
28
+ VERSION = "0.1.14"
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.
@@ -313,6 +313,20 @@ module Recapi
313
313
  end
314
314
  end
315
315
 
316
+ # upsert_items' error when the API refused some items: the others were
317
+ # stored (status is the reply's, 200). rejected holds [index in the
318
+ # caller's list, message] pairs.
319
+ class RejectedItems < Error
320
+ attr_reader :upserted, :rejected
321
+
322
+ def initialize(upserted, rejected)
323
+ index, error = rejected.first
324
+ super("invalid_request", "#{rejected.size} items refused, the first items[#{index}]: #{error}", status: 200)
325
+ @upserted = upserted
326
+ @rejected = rejected
327
+ end
328
+ end
329
+
316
330
  # One recommended or popular item. metadata is the object stored with the
317
331
  # item (name, picture, link, price...), nil when it has none.
318
332
  #
@@ -409,6 +423,8 @@ module Recapi
409
423
  CLICK_WINDOW_MS = 24 * 60 * 60 * 1000
410
424
  # Shown items remembered per user.
411
425
  MAX_SHOWN_ITEMS = 100
426
+ # What a list of recommend_lists may give.
427
+ LIST_FIELDS = %i[placement count tags_any tags_all exclude context_item_id discovery].freeze
412
428
  PUBLIC_KEY_PREFIX = "rk_pub_"
413
429
  # How long a recognised shared store keeps a user's state after its last
414
430
  # write. Far beyond the 24 hours of click credit, and by then a score has
@@ -578,64 +594,29 @@ module Recapi
578
594
  # a deploy.
579
595
  def recommend(user_id: nil, anon_id: nil, count: 0, placement: nil, tags_any: nil, tags_all: nil,
580
596
  exclude: nil, context_item_id: nil, discovery: nil)
581
- deadline = monotonic + recommend_timeout
582
- user_id, anon_id = check_ids(user_id: user_id, anon_id: anon_id)
583
- context_item_id = id_string(context_item_id)
584
- exclude = exclude&.map { |item| id_string(item) }
585
- key = key_for(user_id, anon_id)
586
- t = now_ms
587
- state = key.nil? ? UserState.new : load(key)
588
- unless context_item_id.nil? || context_item_id == "" || History.id?(context_item_id)
589
- _, _, rejected = state.history.wire(t)
590
- # The message never quotes the id: a visitor may have written it. nil:
591
- # not skipped in the list either, as no item can have this id.
592
- cause = Error.new("invalid_request", "context_item_id #{ID_RULE}")
593
- return fallback(cause, count, with_rejected(exclude, rejected), nil, tags_any, tags_all)
594
- end
595
- if user_id && !state.restored && !state.history.empty? && !@api_key.start_with?(PUBLIC_KEY_PREFIX)
596
- state = restore(key, user_id, state, deadline, t)
597
- end
598
- history, recent, rejected = state.history.wire(t)
599
- excluded = with_rejected(exclude, rejected)
600
- begin
601
- response = request(
602
- "POST", "/v1/recommendations",
603
- timeout: deadline - monotonic,
604
- body: compact(
605
- "user_id" => user_id, "anon_id" => anon_id, "placement" => placement,
606
- "count" => count.to_i.zero? ? nil : count, "tags_any" => non_empty(tags_any),
607
- "tags_all" => non_empty(tags_all), "exclude" => excluded, "context_item_id" => context_item_id,
608
- "history" => history, "recent" => recent, "discovery" => discovery
609
- )
610
- )
611
- rec_id, items = parse_recommendations(response)
612
- rescue Error => e
613
- raise unless spare_the_page?(e)
614
-
615
- return fallback(e, count, excluded, context_item_id, tags_any, tags_all)
597
+ row = { placement: placement, count: count, tags_any: tags_any, tags_all: tags_all, exclude: exclude,
598
+ context_item_id: context_item_id, discovery: discovery }
599
+ recommend_rows(user_id, anon_id, nil, [row], false, false)[0]
600
+ end
601
+
602
+ # One Recommendations per entry of lists (hashes of recommend's placement,
603
+ # count, tags_any, tags_all, exclude, context_item_id and discovery), in
604
+ # order, from one call: a page's rows send the history once and are billed
605
+ # as one recommendation. exclude applies to every list. A list holds none
606
+ # of the items of the lists before it unless allow_repeats. It fails and
607
+ # falls back as recommend does: each list then holds popular items, asked
608
+ # list by list, and once popular fails the lists after it are empty.
609
+ def recommend_lists(lists:, user_id: nil, anon_id: nil, exclude: nil, allow_repeats: false)
610
+ raise ArgumentError, "at least one list is required" if lists.nil? || lists.empty?
611
+
612
+ rows = lists.map do |list|
613
+ row = list.to_h.transform_keys(&:to_sym)
614
+ unknown = row.keys - LIST_FIELDS
615
+ raise ArgumentError, "unknown list field: #{unknown.first}" unless unknown.empty?
616
+
617
+ row
616
618
  end
617
-
618
- unless key.nil?
619
- with_locks(key) do
620
- state = load(key)
621
- items.each do |item|
622
- state.shown.delete(item.item_id)
623
- state.shown[item.item_id] = [rec_id, t]
624
- end
625
- state.shown.delete(state.shown.first[0]) while state.shown.size > MAX_SHOWN_ITEMS
626
- # Only trusted when we sent nothing; merged, never replacing what
627
- # was tracked while the request was in flight, and only once: a
628
- # concurrent first call may have merged it already.
629
- snapshot = response["history"]
630
- done = state.restored && !state.history.empty?
631
- if history.empty? && recent.empty? && snapshot.is_a?(Hash) && !done
632
- state.history = state.history.merge_snapshot(History.from_snapshot(snapshot), t)
633
- state.restored = true
634
- end
635
- save(key, state, t)
636
- end
637
- end
638
- Recommendations.new(recommendation_id: rec_id, fallback: false, items: items)
619
+ recommend_rows(user_id, anon_id, exclude, rows, allow_repeats, true)
639
620
  end
640
621
 
641
622
  # Call at login: the visitor's history and shown items become the user's.
@@ -688,15 +669,25 @@ module Recapi
688
669
 
689
670
  # Creates or replaces items (hashes of the API's item fields: item_id,
690
671
  # tags, metadata...), 1,000 per request. Retried like events. Returns how
691
- # many were stored; an invalid item raises, and nothing of its batch of
692
- # 1,000 is stored.
693
- def upsert_items(items)
672
+ # many were stored. merge: true changes only the fields each item sends and
673
+ # keeps the others' stored values. An invalid item doesn't keep the others
674
+ # out: once every request is sent, RejectedItems lists the refused ones.
675
+ def upsert_items(items, merge: false)
694
676
  upserted = 0
695
- items.each_slice(MAX_ITEMS_PER_REQUEST) do |batch|
677
+ rejected = []
678
+ items.each_slice(MAX_ITEMS_PER_REQUEST).with_index do |batch, n|
696
679
  body = { "items" => batch.map { |item| item.to_h.transform_keys(&:to_s) } }
680
+ body["merge"] = true if merge # only when asked: an older API refuses the field
697
681
  response = with_retry { request("POST", "/v1/items:batch", body: body) }
698
- upserted += response.is_a?(Hash) ? response.fetch("upserted", 0).to_i : 0
682
+ next unless response.is_a?(Hash)
683
+
684
+ upserted += response.fetch("upserted", 0).to_i
685
+ Array(response["rejected"]).each do |r|
686
+ rejected << [(n * MAX_ITEMS_PER_REQUEST) + r["index"].to_i, r["error"].to_s]
687
+ end
699
688
  end
689
+ raise RejectedItems.new(upserted, rejected) unless rejected.empty?
690
+
700
691
  upserted
701
692
  end
702
693
 
@@ -1002,10 +993,117 @@ module Recapi
1002
993
  [401, 403].include?(error.status)
1003
994
  end
1004
995
 
996
+ # recommend (one row, several false) and recommend_lists. shared is the
997
+ # call's own exclude, sent once for every row.
998
+ def recommend_rows(user_id, anon_id, shared, rows, repeats, several)
999
+ deadline = monotonic + recommend_timeout
1000
+ user_id, anon_id = check_ids(user_id: user_id, anon_id: anon_id)
1001
+ shared = shared&.map { |item| id_string(item) }
1002
+ rows = rows.map do |row|
1003
+ row.merge(context_item_id: id_string(row[:context_item_id]),
1004
+ exclude: row[:exclude]&.map { |item| id_string(item) })
1005
+ end
1006
+ # One list sends its exclude as the call's.
1007
+ shared, rows = rows[0][:exclude], [rows[0].merge(exclude: nil)] unless several
1008
+ key = key_for(user_id, anon_id)
1009
+ t = now_ms
1010
+ state = key.nil? ? UserState.new : load(key)
1011
+ bad = rows.index do |row|
1012
+ !(row[:context_item_id].nil? || row[:context_item_id] == "" || History.id?(row[:context_item_id]))
1013
+ end
1014
+ unless bad.nil?
1015
+ _, _, rejected = state.history.wire(t)
1016
+ # The message never quotes the id: a visitor may have written it. nil:
1017
+ # not skipped in the list either, as no item can have this id.
1018
+ rows[bad] = rows[bad].merge(context_item_id: nil)
1019
+ cause = Error.new("invalid_request", "context_item_id #{ID_RULE}")
1020
+ return fallbacks(cause, rows, with_rejected(shared, rejected), repeats)
1021
+ end
1022
+ if user_id && !state.restored && !state.history.empty? && !@api_key.start_with?(PUBLIC_KEY_PREFIX)
1023
+ state = restore(key, user_id, state, deadline, t)
1024
+ end
1025
+ history, recent, rejected = state.history.wire(t)
1026
+ excluded = with_rejected(shared, rejected)
1027
+ fields = if several
1028
+ placements = rows.map { |row| compact(row_fields(row, row[:exclude]).merge("discovery" => row[:discovery])) }
1029
+ { "placements" => placements, "exclude" => excluded, "allow_repeats" => repeats ? true : nil }
1030
+ else
1031
+ row_fields(rows[0], excluded)
1032
+ end
1033
+ begin
1034
+ response = request(
1035
+ "POST", "/v1/recommendations",
1036
+ timeout: deadline - monotonic,
1037
+ body: compact(
1038
+ "user_id" => user_id, "anon_id" => anon_id, **fields, "history" => history, "recent" => recent,
1039
+ "discovery" => several ? nil : rows[0][:discovery]
1040
+ )
1041
+ )
1042
+ lists = several ? (response["lists"] if response.is_a?(Hash)) : [response]
1043
+ unless lists.is_a?(Array) && lists.size == rows.size
1044
+ raise Error.new("invalid_response", "malformed recommendations response")
1045
+ end
1046
+
1047
+ results = lists.map { |list| parse_recommendations(list) }
1048
+ rescue Error => e
1049
+ raise unless spare_the_page?(e)
1050
+
1051
+ return fallbacks(e, rows, excluded, repeats)
1052
+ end
1053
+
1054
+ unless key.nil?
1055
+ with_locks(key) do
1056
+ state = load(key)
1057
+ results.each do |rec_id, items|
1058
+ items.each do |item|
1059
+ state.shown.delete(item.item_id)
1060
+ state.shown[item.item_id] = [rec_id, t]
1061
+ end
1062
+ end
1063
+ state.shown.delete(state.shown.first[0]) while state.shown.size > MAX_SHOWN_ITEMS
1064
+ # Only trusted when we sent nothing; merged, never replacing what
1065
+ # was tracked while the request was in flight, and only once: a
1066
+ # concurrent first call may have merged it already.
1067
+ snapshot = response["history"]
1068
+ done = state.restored && !state.history.empty?
1069
+ if history.empty? && recent.empty? && snapshot.is_a?(Hash) && !done
1070
+ state.history = state.history.merge_snapshot(History.from_snapshot(snapshot), t)
1071
+ state.restored = true
1072
+ end
1073
+ save(key, state, t)
1074
+ end
1075
+ end
1076
+ results.map { |rec_id, items| Recommendations.new(recommendation_id: rec_id, fallback: false, items: items) }
1077
+ end
1078
+
1079
+ # A list's own fields: the request itself for one list, a placements entry for several.
1080
+ def row_fields(row, exclude)
1081
+ { "placement" => row[:placement], "count" => row[:count].to_i.zero? ? nil : row[:count],
1082
+ "tags_any" => non_empty(row[:tags_any]), "tags_all" => non_empty(row[:tags_all]), "exclude" => exclude,
1083
+ "context_item_id" => row[:context_item_id] }
1084
+ end
1085
+
1086
+ # Each row of a failed call answered with popular items, a call per row:
1087
+ # excluded and the row's own exclude are skipped, and so, unless repeats,
1088
+ # are the items of the rows before it. Once popular fails (or the key is
1089
+ # refused), the rows after it are empty without asking.
1090
+ def fallbacks(error, rows, excluded, repeats)
1091
+ shown = []
1092
+ failed = false
1093
+ rows.map do |row|
1094
+ next Recommendations.new(recommendation_id: nil, fallback: true, items: []) if failed
1095
+
1096
+ result, failed = fallback(error, row[:count], (excluded || []) + (row[:exclude] || []) + shown,
1097
+ row[:context_item_id], row[:tags_any], row[:tags_all])
1098
+ shown.concat(result.items.map(&:item_id)) unless repeats
1099
+ result
1100
+ end
1101
+ end
1102
+
1005
1103
  def fallback(error, count, excluded, context_item_id, tags_any, tags_all)
1006
1104
  if key_refused?(error)
1007
1105
  log_list(error, "recapi: recommendations refused, served no items: #{error.code}: #{error.message}")
1008
- return Recommendations.new(recommendation_id: nil, fallback: true, items: [])
1106
+ return Recommendations.new(recommendation_id: nil, fallback: true, items: []), true
1009
1107
  end
1010
1108
  # The requested length without the excluded items, so a few more are
1011
1109
  # asked for. 0 is the recommendations default; popular refuses it.
@@ -1019,11 +1117,11 @@ module Recapi
1019
1117
  # can hide beats an exception that fails the whole page.
1020
1118
  log_list(error, "recapi: recommendations failed (#{error.code}: #{error.message}), popular too, " \
1021
1119
  "served no items: #{e.code}: #{e.message}")
1022
- return Recommendations.new(recommendation_id: nil, fallback: true, items: [])
1120
+ return Recommendations.new(recommendation_id: nil, fallback: true, items: []), true
1023
1121
  end
1024
1122
  log_list(error, "recapi: recommendations failed, served popular items: #{error.code}: #{error.message}")
1025
1123
  items = popular.reject { |item| skip.key?(item.item_id) }.first(n)
1026
- Recommendations.new(recommendation_id: nil, fallback: true, items: items)
1124
+ [Recommendations.new(recommendation_id: nil, fallback: true, items: items), false]
1027
1125
  end
1028
1126
 
1029
1127
  # Merges recapi's stored history into a local one that lacks it (a fresh
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.12
4
+ version: 0.1.14
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-07 00:00:00.000000000 Z
11
+ date: 2026-11-15 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.'