recapi 0.1.13 → 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 +19 -1
  3. data/lib/recapi.rb +135 -61
  4. metadata +2 -2
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 5769a64399a93b1e4984f9a1f77ead8d65081b81c8d2db8323bb0034e04563ec
4
- data.tar.gz: f3209ebf643aa1573b067b4778573c23a971efa12c81a9284fededeb14640561
3
+ metadata.gz: c186cf0df3db7d2776e851d0f4658a85808efaa8502374b95affe38142c99cd5
4
+ data.tar.gz: b14927279881bd3799bb8caed8203c7c9389869f999eaf980983b847b67e7ed8
5
5
  SHA512:
6
- metadata.gz: 56250877312b500b42d4d19ad940a22fc111c84a3011cbdec3d0474875a858bf10c417b22be839bdb634dd23f6cdfa9b4ccc947bc5b7c507788803f5cb7aed97
7
- data.tar.gz: 3bdc9a2cc2e4f5c4944649213bb266a47c875670f920e7a361995dd1d8f29306c4d1f01a68ad4640ae4d02c4e65c8402b81b8b15cf080a32361b819b6c3c8c0c
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.13.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
@@ -124,6 +140,8 @@ 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.
127
145
  - 2026-11-14: version 0.1.13. `upsert_items(items, merge: true)` changes only the
128
146
  fields sent. A bad item no longer fails its batch of 1,000: the others are stored,
129
147
  and `Recapi::RejectedItems` lists the refused ones once every request is sent.
data/lib/recapi.rb CHANGED
@@ -25,7 +25,7 @@ rescue LoadError
25
25
  end
26
26
 
27
27
  module Recapi
28
- VERSION = "0.1.13"
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.
@@ -423,6 +423,8 @@ module Recapi
423
423
  CLICK_WINDOW_MS = 24 * 60 * 60 * 1000
424
424
  # Shown items remembered per user.
425
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
426
428
  PUBLIC_KEY_PREFIX = "rk_pub_"
427
429
  # How long a recognised shared store keeps a user's state after its last
428
430
  # write. Far beyond the 24 hours of click credit, and by then a score has
@@ -592,64 +594,29 @@ module Recapi
592
594
  # a deploy.
593
595
  def recommend(user_id: nil, anon_id: nil, count: 0, placement: nil, tags_any: nil, tags_all: nil,
594
596
  exclude: nil, context_item_id: nil, discovery: nil)
595
- deadline = monotonic + recommend_timeout
596
- user_id, anon_id = check_ids(user_id: user_id, anon_id: anon_id)
597
- context_item_id = id_string(context_item_id)
598
- exclude = exclude&.map { |item| id_string(item) }
599
- key = key_for(user_id, anon_id)
600
- t = now_ms
601
- state = key.nil? ? UserState.new : load(key)
602
- unless context_item_id.nil? || context_item_id == "" || History.id?(context_item_id)
603
- _, _, rejected = state.history.wire(t)
604
- # The message never quotes the id: a visitor may have written it. nil:
605
- # not skipped in the list either, as no item can have this id.
606
- cause = Error.new("invalid_request", "context_item_id #{ID_RULE}")
607
- return fallback(cause, count, with_rejected(exclude, rejected), nil, tags_any, tags_all)
608
- end
609
- if user_id && !state.restored && !state.history.empty? && !@api_key.start_with?(PUBLIC_KEY_PREFIX)
610
- state = restore(key, user_id, state, deadline, t)
611
- end
612
- history, recent, rejected = state.history.wire(t)
613
- excluded = with_rejected(exclude, rejected)
614
- begin
615
- response = request(
616
- "POST", "/v1/recommendations",
617
- timeout: deadline - monotonic,
618
- body: compact(
619
- "user_id" => user_id, "anon_id" => anon_id, "placement" => placement,
620
- "count" => count.to_i.zero? ? nil : count, "tags_any" => non_empty(tags_any),
621
- "tags_all" => non_empty(tags_all), "exclude" => excluded, "context_item_id" => context_item_id,
622
- "history" => history, "recent" => recent, "discovery" => discovery
623
- )
624
- )
625
- rec_id, items = parse_recommendations(response)
626
- rescue Error => e
627
- raise unless spare_the_page?(e)
628
-
629
- 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
630
618
  end
631
-
632
- unless key.nil?
633
- with_locks(key) do
634
- state = load(key)
635
- items.each do |item|
636
- state.shown.delete(item.item_id)
637
- state.shown[item.item_id] = [rec_id, t]
638
- end
639
- state.shown.delete(state.shown.first[0]) while state.shown.size > MAX_SHOWN_ITEMS
640
- # Only trusted when we sent nothing; merged, never replacing what
641
- # was tracked while the request was in flight, and only once: a
642
- # concurrent first call may have merged it already.
643
- snapshot = response["history"]
644
- done = state.restored && !state.history.empty?
645
- if history.empty? && recent.empty? && snapshot.is_a?(Hash) && !done
646
- state.history = state.history.merge_snapshot(History.from_snapshot(snapshot), t)
647
- state.restored = true
648
- end
649
- save(key, state, t)
650
- end
651
- end
652
- Recommendations.new(recommendation_id: rec_id, fallback: false, items: items)
619
+ recommend_rows(user_id, anon_id, exclude, rows, allow_repeats, true)
653
620
  end
654
621
 
655
622
  # Call at login: the visitor's history and shown items become the user's.
@@ -1026,10 +993,117 @@ module Recapi
1026
993
  [401, 403].include?(error.status)
1027
994
  end
1028
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
+
1029
1103
  def fallback(error, count, excluded, context_item_id, tags_any, tags_all)
1030
1104
  if key_refused?(error)
1031
1105
  log_list(error, "recapi: recommendations refused, served no items: #{error.code}: #{error.message}")
1032
- return Recommendations.new(recommendation_id: nil, fallback: true, items: [])
1106
+ return Recommendations.new(recommendation_id: nil, fallback: true, items: []), true
1033
1107
  end
1034
1108
  # The requested length without the excluded items, so a few more are
1035
1109
  # asked for. 0 is the recommendations default; popular refuses it.
@@ -1043,11 +1117,11 @@ module Recapi
1043
1117
  # can hide beats an exception that fails the whole page.
1044
1118
  log_list(error, "recapi: recommendations failed (#{error.code}: #{error.message}), popular too, " \
1045
1119
  "served no items: #{e.code}: #{e.message}")
1046
- return Recommendations.new(recommendation_id: nil, fallback: true, items: [])
1120
+ return Recommendations.new(recommendation_id: nil, fallback: true, items: []), true
1047
1121
  end
1048
1122
  log_list(error, "recapi: recommendations failed, served popular items: #{error.code}: #{error.message}")
1049
1123
  items = popular.reject { |item| skip.key?(item.item_id) }.first(n)
1050
- Recommendations.new(recommendation_id: nil, fallback: true, items: items)
1124
+ [Recommendations.new(recommendation_id: nil, fallback: true, items: items), false]
1051
1125
  end
1052
1126
 
1053
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.13
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-14 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.'