recapi 0.1.11 → 0.1.13

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 +9 -2
  3. data/lib/recapi.rb +44 -12
  4. metadata +2 -2
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: ddfbe7da7e2ca36f680b013e06c795a516645d415329f1dc61892024e129d477
4
- data.tar.gz: dacd7f80f58ecda60c653380d73e63a396315f906339d9940941922a1ed6333e
3
+ metadata.gz: 5769a64399a93b1e4984f9a1f77ead8d65081b81c8d2db8323bb0034e04563ec
4
+ data.tar.gz: f3209ebf643aa1573b067b4778573c23a971efa12c81a9284fededeb14640561
5
5
  SHA512:
6
- metadata.gz: f5309158f3114f5d2d314045358364a9467a867aa4324e8650b6dc6269583de306c74e0f5a288f81cbfdf27adc75ca778a0f8d7d12a63710ac1c7c98158d4cfc
7
- data.tar.gz: 82124ece99593007209d5a4e040c7d1f6768d47ae6ee93a0892f734d83c964b5d10e34d7198badb53453cab39be36ee1bb2bf18d43ac802f62806ae8e525c780
6
+ metadata.gz: 56250877312b500b42d4d19ad940a22fc111c84a3011cbdec3d0474875a858bf10c417b22be839bdb634dd23f6cdfa9b4ccc947bc5b7c507788803f5cb7aed97
7
+ data.tar.gz: 3bdc9a2cc2e4f5c4944649213bb266a47c875670f920e7a361995dd1d8f29306c4d1f01a68ad4640ae4d02c4e65c8402b81b8b15cf080a32361b819b6c3c8c0c
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.11.rb
33
+ curl -fLo lib/recapi.rb https://api.<your-domain>/sdk/ruby/recapi-0.1.13.rb
34
34
  ```
35
35
 
36
36
  ## Quick start
@@ -78,7 +78,7 @@ and a log line.
78
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. |
79
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. |
80
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`. |
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. |
81
+ | `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
82
  | `delete_user(user_id)` | Erases a user's events in recapi and their state in the store, retried like events. |
83
83
 
84
84
  `Recapi::Client.new(api_key, base_url, store:, timeout:, flush_interval:,
@@ -124,6 +124,13 @@ so a visitor who never returns stays on disk (about 8 KB each): run
124
124
 
125
125
  ## Changes
126
126
 
127
+ - 2026-11-14: version 0.1.13. `upsert_items(items, merge: true)` changes only the
128
+ fields sent. A bad item no longer fails its batch of 1,000: the others are stored,
129
+ and `Recapi::RejectedItems` lists the refused ones once every request is sent.
130
+ - 2026-11-07: version 0.1.12. A saved history time ahead of the clock reads as now,
131
+ and a damaged weight is sent as the API's limit (1e6). A time months ahead, or a
132
+ weight past that limit, used to get a 400 on every list, and far enough past it
133
+ raised `FloatDomainError`: the note below now holds for those too.
127
134
  - 2026-11-07: version 0.1.11. A damaged stored state can't raise into your page
128
135
  or stop a visitor's history from saving. A shown entry of the wrong types
129
136
  costs that item's click credit, and a history time too big for a number
data/lib/recapi.rb CHANGED
@@ -25,7 +25,7 @@ rescue LoadError
25
25
  end
26
26
 
27
27
  module Recapi
28
- VERSION = "0.1.11"
28
+ VERSION = "0.1.13"
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.
@@ -35,6 +35,8 @@ module Recapi
35
35
  RECENT_SIZE = 20
36
36
  REJECTED_SIZE = 200
37
37
  MAX_ID_BYTES = 256
38
+ # The API answers 400 above this, which fails the list: a damaged score is sent as this.
39
+ MAX_REQUEST_WEIGHT = 1e6
38
40
  RATE = Math.log(2) / HALF_LIFE_SECONDS
39
41
  # Go's unicode.IsControl, which the API applies to every id: C0, DEL and C1.
40
42
  CONTROL = /[\u0000-\u001f\u007f-\u009f]/.freeze
@@ -108,9 +110,11 @@ module Recapi
108
110
  prune(t)
109
111
  end
110
112
 
111
- # [item, weight at now, t] by weight desc, ties by item id asc.
113
+ # [item, weight at now, t] by weight desc, ties by item id asc. A time ahead
114
+ # of now reads as now: a clock that ran ahead must not grow the weight past
115
+ # what the API takes.
112
116
  def ranked(now)
113
- entries = @top.map { |item, (s, t)| [item, s * History.decay(now - t), t] }
117
+ entries = @top.map { |item, (s, t)| [item, s * History.decay([0, now - t].max), t] }
114
118
  entries.sort_by { |item, w, _| [-w, item] }
115
119
  end
116
120
 
@@ -120,11 +124,12 @@ module Recapi
120
124
  end
121
125
 
122
126
  # The request's history and recent, and the rejected items. Weights are
123
- # decayed to now and rounded half up to 4 decimals like JS Math.round
124
- # (Ruby's round rounds half away from zero); ages are whole seconds, never negative.
127
+ # decayed to now, at most what the API accepts, and rounded half up to 4
128
+ # decimals like JS Math.round (Ruby's round rounds half away from zero); ages
129
+ # are whole seconds, never negative.
125
130
  def wire(now)
126
131
  history = ranked(now).first(TOP_K).map do |item, weight, t|
127
- [item, (weight * 1e4 + 0.5).floor / 1e4, [0, ((now - t) / 1000.0).floor].max]
132
+ [item, ([weight, MAX_REQUEST_WEIGHT].min * 1e4 + 0.5).floor / 1e4, [0, ((now - t) / 1000.0).floor].max]
128
133
  end
129
134
  [history, @recent.last(RECENT_SIZE).map(&:first), rejected_order]
130
135
  end
@@ -268,7 +273,10 @@ module Recapi
268
273
  def prune(now)
269
274
  return unless @top.size > TOP_K
270
275
 
271
- @top = ranked(now).first(TOP_K).to_h { |item, _, _| [item, @top[item]] }
276
+ # Read at the newest entry when an event arrives out of order: at the old
277
+ # 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]] }
272
280
  end
273
281
 
274
282
  def prune_rejected
@@ -305,6 +313,20 @@ module Recapi
305
313
  end
306
314
  end
307
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
+
308
330
  # One recommended or popular item. metadata is the object stored with the
309
331
  # item (name, picture, link, price...), nil when it has none.
310
332
  #
@@ -680,15 +702,25 @@ module Recapi
680
702
 
681
703
  # Creates or replaces items (hashes of the API's item fields: item_id,
682
704
  # tags, metadata...), 1,000 per request. Retried like events. Returns how
683
- # many were stored; an invalid item raises, and nothing of its batch of
684
- # 1,000 is stored.
685
- def upsert_items(items)
705
+ # many were stored. merge: true changes only the fields each item sends and
706
+ # keeps the others' stored values. An invalid item doesn't keep the others
707
+ # out: once every request is sent, RejectedItems lists the refused ones.
708
+ def upsert_items(items, merge: false)
686
709
  upserted = 0
687
- items.each_slice(MAX_ITEMS_PER_REQUEST) do |batch|
710
+ rejected = []
711
+ items.each_slice(MAX_ITEMS_PER_REQUEST).with_index do |batch, n|
688
712
  body = { "items" => batch.map { |item| item.to_h.transform_keys(&:to_s) } }
713
+ body["merge"] = true if merge # only when asked: an older API refuses the field
689
714
  response = with_retry { request("POST", "/v1/items:batch", body: body) }
690
- upserted += response.is_a?(Hash) ? response.fetch("upserted", 0).to_i : 0
715
+ next unless response.is_a?(Hash)
716
+
717
+ upserted += response.fetch("upserted", 0).to_i
718
+ Array(response["rejected"]).each do |r|
719
+ rejected << [(n * MAX_ITEMS_PER_REQUEST) + r["index"].to_i, r["error"].to_s]
720
+ end
691
721
  end
722
+ raise RejectedItems.new(upserted, rejected) unless rejected.empty?
723
+
692
724
  upserted
693
725
  end
694
726
 
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.11
4
+ version: 0.1.13
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-14 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.'