recapi 0.1.16 → 0.1.18

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 +7 -2
  3. data/lib/recapi.rb +73 -25
  4. metadata +2 -2
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 4630dc6459bcf8c5f8563c8d2725197ef77adea276bc85524363938c20ab8629
4
- data.tar.gz: 6a58b1472dd36ba98c5757b6c5a1a4c297e9417b9fc23e0bbcb125a71f633dd7
3
+ metadata.gz: 530b2c52be5b0482d1fb31197244cca58710fabc6f885071bd144c8ba62a94bc
4
+ data.tar.gz: 0ceba9e4fbd15106b7cbc1fb19816499eec84c9ec2f2d0ff84c587a934c24288
5
5
  SHA512:
6
- metadata.gz: 37f40070a0df5413ad196d63396be3aa4a3fad991e23daae7e5dbdb095dc803e278e6065c2047afd20466f3480be0e0904f7898903f1b1e5568a08bf43dc8ecb
7
- data.tar.gz: e40ee11a50b6aa926ac3ed147de9676b8a185914cdddb228345ebb0088f33255a652599972405a2ecf7449fb9792ae22bd5d62cff6fb1354b6533000702113cb
6
+ metadata.gz: ed858a1504228adf2a0523832cf85758a256e357575f78baeedf4755cfc3abef620f71c15efd3aa6b034475cc5ff54c87097ce416f06ada884e33e4b279cf948
7
+ data.tar.gz: ea85315a27410bf52646c16f57f600edc33b9851b461ae73e18bc8fdf87d7ee0f8e7a9fe49b2a6f528098b1170f9009dce9392b8871fcc39d39fb01d94248963
data/README.md CHANGED
@@ -28,7 +28,7 @@ line with your address): save it as `lib/recapi.rb` and
28
28
  `require Rails.root.join("lib/recapi").to_s` instead.
29
29
 
30
30
  ```sh
31
- curl -fLo lib/recapi.rb https://api.<your-domain>/sdk/ruby/recapi-0.1.16.rb
31
+ curl -fLo lib/recapi.rb https://api.<your-domain>/sdk/ruby/recapi-0.1.18.rb
32
32
  ```
33
33
 
34
34
  ## Quick start
@@ -86,7 +86,7 @@ and a log line.
86
86
 
87
87
  | Call | What it does |
88
88
  |---|---|
89
- | `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`. |
89
+ | `track(item_id, level, user_id:, anon_id:, recommendation_id:, value:, currency:)` | 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`. A purchase may carry `value:` (what the buyer paid for the line, an Integer or Float) and `currency:` (ISO 4217, such as `"EUR"`), kept for the sales figure of a lift test; a negative or non-finite value, one that is not a number, or a currency without a value or not of three letters, raises `ArgumentError`. |
90
90
  | `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). |
91
91
  | `close` | Stops the sender and sends what is queued, one try per batch. It runs by itself at exit, also for a classic Sinatra app (`ruby app.rb`), whose server runs from its own exit hook. Don't `track` while such an app loads, before its server starts: the client then closes before the first request, and every later `track` is sent on the page's thread. |
92
92
  | `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. |
@@ -138,6 +138,11 @@ so a visitor who never returns stays on disk (about 8 KB each): run
138
138
 
139
139
  ## Changes
140
140
 
141
+ - 2026-11-22: version 0.1.18. The saved history keeps, per product, the strongest
142
+ level reached (opened, in the cart, bought), and sends it with each list. Lists
143
+ don't use it yet; a history saved by an older version still loads.
144
+ - 2026-11-22: version 0.1.17. `track` takes `value:` and `currency:`, what the
145
+ buyer paid for a purchase's line, for the sales figure of a lift test.
141
146
  - 2026-11-19: version 0.1.16. `Recapi::Error#docs_url` is the errors page's
142
147
  section for an API error, and its message and the library's log lines end with it.
143
148
  - 2026-11-19: version 0.1.15. This page's links lead to recapi.io's public docs,
data/lib/recapi.rb CHANGED
@@ -25,7 +25,7 @@ rescue LoadError
25
25
  end
26
26
 
27
27
  module Recapi
28
- VERSION = "0.1.16"
28
+ VERSION = "0.1.18"
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.
@@ -63,7 +63,22 @@ module Recapi
63
63
  time?(value) && value >= 0
64
64
  end
65
65
 
66
- # top: item => [score, t]; recent: [[item, t]] oldest first; rejected:
66
+ # A strongest level read from JSON: an integer 1-10 (10.0 counts), else 0
67
+ # (unknown).
68
+ def self.level_of(value)
69
+ return 0 unless (value.is_a?(Integer) || value.is_a?(Float)) && value.finite? && value == value.truncate
70
+
71
+ value.between?(1, 10) ? value.to_i : 0
72
+ end
73
+
74
+ # The max level of two sides of one entry: unknown wins, since the unknown
75
+ # side may hold a purchase.
76
+ def self.strongest(a, b)
77
+ a.zero? || b.zero? ? 0 : [a, b].max
78
+ end
79
+
80
+ # top: item => [score, t, m], m the strongest level applied since the
81
+ # entry started (0 when unknown: an entry stored or sent without it); recent: [[item, t]] oldest first; rejected:
67
82
  # item => time of the newest rejection; last_t: the newest event applied
68
83
  # to the recent list (nil when unknown).
69
84
  attr_accessor :top, :recent, :rejected, :last_t
@@ -95,11 +110,11 @@ module Recapi
95
110
  current = @top[item]
96
111
  @top[item] =
97
112
  if current.nil?
98
- [level.to_f, t]
113
+ [level.to_f, t, level]
99
114
  elsif t >= current[1]
100
- [current[0] * History.decay(t - current[1]) + level, t]
115
+ [current[0] * History.decay(t - current[1]) + level, t, History.strongest(current[2], level)]
101
116
  else
102
- [current[0] + level * History.decay(current[1] - t), current[1]]
117
+ [current[0] + level * History.decay(current[1] - t), current[1], History.strongest(current[2], level)]
103
118
  end
104
119
  if @last_t.nil? || t >= @last_t
105
120
  @recent = @recent.reject { |entry| entry[0] == item }
@@ -110,12 +125,12 @@ module Recapi
110
125
  prune(t)
111
126
  end
112
127
 
113
- # [item, weight at now, t] by weight desc, ties by item id asc. A time ahead
128
+ # [item, weight at now, t, m] by weight desc, ties by item id asc. A time ahead
114
129
  # of now reads as now: a clock that ran ahead must not grow the weight past
115
130
  # what the API takes.
116
131
  def ranked(now)
117
- entries = @top.map { |item, (s, t)| [item, s * History.decay([0, now - t].max), t] }
118
- entries.sort_by { |item, w, _| [-w, item] }
132
+ entries = @top.map { |item, (s, t, m)| [item, s * History.decay([0, now - t].max), t, m] }
133
+ entries.sort_by { |item, w, _, _| [-w, item] }
119
134
  end
120
135
 
121
136
  # The rejected items, oldest mark first, ties by item id.
@@ -126,16 +141,19 @@ module Recapi
126
141
  # The request's history and recent, and the rejected items. Weights are
127
142
  # decayed to now, at most what the API accepts, and rounded half up to 4
128
143
  # decimals like JS Math.round (Ruby's round rounds half away from zero); ages
129
- # are whole seconds, never negative.
144
+ # are whole seconds, never negative. A fourth element is the entry's
145
+ # strongest level, left out when unknown.
130
146
  def wire(now)
131
- history = ranked(now).first(TOP_K).map do |item, weight, t|
132
- [item, ([weight, MAX_REQUEST_WEIGHT].min * 1e4 + 0.5).floor / 1e4, [0, ((now - t) / 1000.0).floor].max]
147
+ history = ranked(now).first(TOP_K).map do |item, weight, t, m|
148
+ entry = [item, ([weight, MAX_REQUEST_WEIGHT].min * 1e4 + 0.5).floor / 1e4, [0, ((now - t) / 1000.0).floor].max]
149
+ m.positive? ? entry << m : entry
133
150
  end
134
151
  [history, @recent.last(RECENT_SIZE).map(&:first), rejected_order]
135
152
  end
136
153
 
137
154
  # A history from the server's snapshot, skipping invalid entries. Each top
138
- # entry is a score at as_of, each rejected item a mark at as_of. last_t
155
+ # entry is a score at as_of with its strongest level (unknown when absent
156
+ # or not 1-10), each rejected item a mark at as_of. last_t
139
157
  # stays unknown: as_of is the server clock, and a local clock behind it
140
158
  # would see every new event as out of order.
141
159
  def self.from_snapshot(snapshot)
@@ -144,7 +162,9 @@ module Recapi
144
162
 
145
163
  as_of = snapshot["as_of"]
146
164
  list(snapshot["top"]).each do |e|
147
- state.top[e[0]] = [e[1].to_f, as_of] if e.is_a?(Array) && e.size >= 2 && id?(e[0]) && weight?(e[1])
165
+ next unless e.is_a?(Array) && e.size >= 2 && id?(e[0]) && weight?(e[1])
166
+
167
+ state.top[e[0]] = [e[1].to_f, as_of, level_of(e[2])]
148
168
  end
149
169
  list(snapshot["recent"]).each do |item|
150
170
  state.recent << [item, as_of] if id?(item) && state.recent.none? { |entry| entry[0] == item }
@@ -157,21 +177,23 @@ module Recapi
157
177
  end
158
178
 
159
179
  # The union of two histories built from disjoint events. Top scores add
160
- # up, expressed at the later of the two times; the recent lists are
180
+ # up, expressed at the later of the two times, with the strongest of the
181
+ # two levels; the recent lists are
161
182
  # interleaved by time (self first on ties); rejection marks are united, and
162
183
  # a mark older than the item's merged entry is dropped, otherwise the item
163
184
  # leaves the top and the recent list.
164
185
  def merge(other, now)
165
186
  out = History.new
166
187
  out.top = @top.dup
167
- other.top.each do |item, (s, t)|
188
+ other.top.each do |item, (s, t, m)|
168
189
  mine = out.top[item]
169
190
  if mine.nil?
170
- out.top[item] = [s, t]
191
+ out.top[item] = [s, t, m]
171
192
  next
172
193
  end
173
194
  later = [t, mine[1]].max
174
- out.top[item] = [s * History.decay(later - t) + mine[0] * History.decay(later - mine[1]), later]
195
+ score = s * History.decay(later - t) + mine[0] * History.decay(later - mine[1])
196
+ out.top[item] = [score, later, History.strongest(m, mine[2])]
175
197
  end
176
198
 
177
199
  out.rejected = @rejected.dup
@@ -211,22 +233,30 @@ module Recapi
211
233
  end
212
234
 
213
235
  # The JSON-safe stored form (raw scores), shaped like sdk/python's.
236
+ # "maxLevel" is each top entry's strongest level, in top's order (0
237
+ # unknown): a key of its own, not a fourth element, so a library from
238
+ # before it still reads the state (it refuses a top entry of another size).
214
239
  def encode
215
240
  {
216
241
  "top" => @top.map { |item, (s, t)| [item, s, t] },
217
242
  "recent" => @recent.map { |item, t| [item, t] },
218
243
  "rejected" => @rejected.map { |item, t| [item, t] },
219
- "lastT" => @last_t
244
+ "lastT" => @last_t,
245
+ "maxLevel" => @top.map { |_, (_, _, m)| m }
220
246
  }
221
247
  end
222
248
 
223
249
  # Inverse of encode; nil for any malformed field. A state stored before
224
- # rejections existed has no "rejected".
250
+ # rejections existed has no "rejected". "maxLevel" is read leniently:
251
+ # absent, not a list or not as long as top, every level is unknown; a value
252
+ # that is not a level 1-10 is unknown.
225
253
  def self.decode(raw)
226
254
  return nil unless valid_encoding?(raw)
227
255
 
228
256
  state = new
229
- raw["top"].each { |item, s, t| state.top[item] = [s.to_f, t] }
257
+ levels = raw["maxLevel"]
258
+ levels = [] unless levels.is_a?(Array) && levels.size == raw["top"].size
259
+ raw["top"].each_with_index { |(item, s, t), i| state.top[item] = [s.to_f, t, level_of(levels[i])] }
230
260
  state.recent = raw["recent"].map { |item, t| [item, t] }
231
261
  raw.fetch("rejected", []).each { |item, t| state.rejected[item] = t }
232
262
  state.last_t = raw["lastT"]
@@ -275,8 +305,8 @@ module Recapi
275
305
 
276
306
  # Read at the newest entry when an event arrives out of order: at the old
277
307
  # event's time ranked would flatten the newer entries to their score.
278
- at = [now, *@top.values.map(&:last)].max
279
- @top = ranked(at).first(TOP_K).to_h { |item, _, _| [item, @top[item]] }
308
+ at = [now, *@top.values.map { |entry| entry[1] }].max
309
+ @top = ranked(at).first(TOP_K).to_h { |item, _, _, _| [item, @top[item]] }
280
310
  end
281
311
 
282
312
  def prune_rejected
@@ -518,11 +548,14 @@ module Recapi
518
548
  # again until a positive event on it). recommendation_id overrides the
519
549
  # automatic attribution. Ids may be strings or integers. An item_id the API
520
550
  # would refuse raises nothing: a page often takes it from a visitor's URL, so
521
- # the event is dropped and logged instead.
522
- def track(item_id, level, user_id: nil, anon_id: nil, recommendation_id: nil)
551
+ # the event is dropped and logged instead. value is what was paid for a
552
+ # purchase's line (nil for none, 0 for a free line), currency its ISO 4217
553
+ # code; a currency needs a value.
554
+ def track(item_id, level, user_id: nil, anon_id: nil, recommendation_id: nil, value: nil, currency: nil)
523
555
  level = level_value(level)
524
556
  user_id, anon_id, recommendation_id = check_ids(user_id: user_id, anon_id: anon_id,
525
557
  recommendation_id: recommendation_id)
558
+ check_amount(value, currency)
526
559
  item_id = id_string(item_id)
527
560
  # A crafted link must not fail the page. Nothing is kept: in the history it
528
561
  # would make the API refuse every later list. The line never quotes the
@@ -550,7 +583,8 @@ module Recapi
550
583
  end
551
584
  enqueue(compact(
552
585
  "item_id" => item_id, "level" => level, "user_id" => user_id, "anon_id" => anon_id,
553
- "recommendation_id" => attributed, "timestamp" => iso(t), "event_id" => SecureRandom.uuid
586
+ "recommendation_id" => attributed, "value" => value, "currency" => currency,
587
+ "timestamp" => iso(t), "event_id" => SecureRandom.uuid
554
588
  ))
555
589
  nil
556
590
  end
@@ -1459,6 +1493,20 @@ module Recapi
1459
1493
  end
1460
1494
  end
1461
1495
 
1496
+ # Refuses what the API would refuse in the event: a value that is not a
1497
+ # number of at least 0 (true and "12" are not numbers), a currency that is
1498
+ # not three letters or has no value.
1499
+ def check_amount(value, currency)
1500
+ unless value.nil? || ((value.is_a?(Integer) || value.is_a?(Float)) && value >= 0 && value.finite?)
1501
+ raise ArgumentError, "value must be a number of at least 0"
1502
+ end
1503
+ return if currency.nil?
1504
+ raise ArgumentError, "currency needs a value" if value.nil?
1505
+ return if currency.is_a?(String) && currency.match?(/\A[A-Za-z]{3}\z/)
1506
+
1507
+ raise ArgumentError, "currency must be three letters (ISO 4217)"
1508
+ end
1509
+
1462
1510
  def escape(id)
1463
1511
  URI.encode_www_form_component(id).gsub("+", "%20")
1464
1512
  end
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.16
4
+ version: 0.1.18
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-19 00:00:00.000000000 Z
11
+ date: 2026-11-22 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.'