activeitem 0.0.26 → 0.0.27

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: cbaab4f038aa32c3a5680afa9adfa01cc4fd8a408210fe8abc2e82d414ef7215
4
- data.tar.gz: 42434a3dcb2d806924e9dddcc21a8f4bf576b07b9a5dc8791e16414fe10fa796
3
+ metadata.gz: 1c11222732807109d8a6fb40c6e6471005443ec071ad575595c9c5e4de53af4a
4
+ data.tar.gz: d96ab28bb664c7f471e29badc04ab3d48fc441a985fc3211616044cb0c397c9d
5
5
  SHA512:
6
- metadata.gz: ca84f380d89e04a0bf6e5450b30bcbb7b8a0fcae47c867db9b6a7339fc6d5b5ae3d9abdc80e49ee9006869b6dcbd7443e1dc1bbc1f874726673d8c07295dbc14
7
- data.tar.gz: b6325bf77e8f99ce2f2ecf4ba92a86ff592d828d1b920a6b4d9af546f743d9ffd28cf78011a192224905f527561f67bfd2162b85affabdc61845ab1072faf82a
6
+ metadata.gz: 622690879edcc3362a1003ac71037e3d2582e9d11e45146b9840eb7473850b76025397d4757ce8ced6b30e58933ee16be9c9d4a5ec56eb454861d24c32cdf7df
7
+ data.tar.gz: 42b0c3bd56c5f3e5411844ae073f75397389c241baf9da8aff8aa43331270d32b6630c4015eb6b8cbea64b79e32244da06d15d716b50a7d3d575d492937cb4cb
data/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.0.27
4
+
5
+ ### Added
6
+
7
+ - **Atomic counters: `Model.update_counters`, `#increment!`, `#decrement!`** (Fizzy #2075). `save` SETs the value the record read, so concurrent `opens + 1` saves lost counts and apps hand-wrote `update_item` with `ADD`. These send one UpdateItem that ADDs to the stored value, map names through `to_dynamo_key`, set `updatedAt` (and `createdAt` / `_recent_pk` if missing; `touch: false` skips them), and rebuild the record from `ALL_NEW`.
8
+
9
+ ```ruby
10
+ ShareLink.update_counters(id, opens: 1, visitors: 1) # upserts, like ADD
11
+ ShareLink.update_counters(id, { opens: 1 }, if_exists: true) # nil when the row is missing
12
+ link.increment!(:opens, :visitors, set: { last_opened_at: t }, set_if_missing: { first_opened_at: t })
13
+ ```
14
+
15
+ `increment!` only touches a row that still exists (returns `false` otherwise), and leaves the touched attributes clean. Undeclared names passed to `update_counters` are used verbatim as DynamoDB attribute names. AccessDenied is wrapped in `ActiveItem::AccessDeniedError`.
16
+
3
17
  ## 0.0.26
4
18
 
5
19
  Scope hardening from the Posh Nosh security review (Fizzy #2004). Several of these change behavior; see **Changed**.
data/README.md CHANGED
@@ -87,6 +87,37 @@ lowercased characters and whose sort key is the whole lowercased value, then
87
87
  `begins_with` on the sort key. `begins_with` on a non-key attribute works too, but
88
88
  it's a filter, so DynamoDB still reads every item in the query or scan.
89
89
 
90
+ ### Counters
91
+
92
+ `save` SETs the value the record read, so two requests saving `opens + 1` at
93
+ once lose one. Counters use one UpdateItem with DynamoDB's `ADD` instead, which
94
+ adds to whatever is stored:
95
+
96
+ ```ruby
97
+ ShareLink.update_counters(id, opens: 1, visitors: 1) # no read; creates the row if missing
98
+ ShareLink.update_counters(id, { opens: 1 }, if_exists: true) # nil instead of creating a row
99
+ ShareLink.update_counters(id, { opens: 1 }, set: { last_opened_at: t }, set_if_missing: { first_opened_at: t })
100
+
101
+ link.increment!(:opens) # refreshed from the stored row
102
+ link.increment!(:opens, :visitors, by: 2, set: { last_opened_at: t })
103
+ link.decrement!(:stock) # negative amounts work too
104
+ ```
105
+
106
+ - `update_counters` returns the row as stored after the update, or `nil` when
107
+ `if_exists: true` and the row is missing. Without `if_exists` a missing row is
108
+ created holding just the counters (that's how `ADD` works).
109
+ - `increment!` / `decrement!` only update a row that still exists. They return
110
+ the record, or `false` if the row was deleted. The touched attributes are
111
+ refreshed and left clean; other unsaved changes are kept.
112
+ - `set:` SETs attributes in the same write (`nil` removes one), and
113
+ `set_if_missing:` SETs only attributes that are absent (`if_not_exists`).
114
+ - Every write sets `updatedAt`, and sets `createdAt` and `_recent_pk` if missing.
115
+ `update_counters(..., touch: false)` leaves all three out.
116
+ - Declared attributes map through `to_dynamo_key` / `dynamo_attribute_map`. Class-level
117
+ names that aren't declared attributes are used verbatim, e.g.
118
+ `update_counters(day, 'n:page:/pricing' => 1)`.
119
+ - Counters don't run validations or callbacks, and aren't enrolled in `transaction`.
120
+
90
121
  ### Associations
91
122
 
92
123
  ```ruby
@@ -18,6 +18,7 @@ module ActiveItem
18
18
  include Associations
19
19
  include Embeddable
20
20
  include Logging
21
+ include Counters
21
22
 
22
23
  define_model_callbacks :save, :create, :update, :destroy, :initialize, :validation
23
24
 
@@ -0,0 +1,187 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveItem
4
+ # Atomic counters: one UpdateItem that ADDs to numeric attributes, so two
5
+ # writers incrementing at the same time both count. `save` can't do this; it
6
+ # SETs the value the record read.
7
+ #
8
+ # @example Class level, no read; creates the row if it's missing
9
+ # ShareLink.update_counters(id, opens: 1, visitors: 1)
10
+ #
11
+ # @example Only touch a row that exists
12
+ # ShareLink.update_counters(id, { opens: 1 }, if_exists: true) # => nil when missing
13
+ #
14
+ # @example Instance level, refreshes the record from the stored row
15
+ # link.increment!(:opens, set: { last_opened_at: t }, set_if_missing: { first_opened_at: t })
16
+ # link.decrement!(:stock, by: 2)
17
+ module Counters
18
+ def self.included(base)
19
+ base.extend(ClassMethods)
20
+ end
21
+
22
+ # Class-level counter API.
23
+ module ClassMethods
24
+ # ADD `counters` to the row with this id in one UpdateItem, without reading
25
+ # it first. Amounts may be negative.
26
+ #
27
+ # Declared attributes are mapped through `to_dynamo_key`; any other name
28
+ # (e.g. "n:page:/pricing") is used as the DynamoDB attribute name verbatim.
29
+ # `updatedAt` is set, and `createdAt` and `_recent_pk` are set only if
30
+ # missing, unless `touch: false`.
31
+ #
32
+ # @param set [Hash] attributes to SET alongside the counters (nil REMOVEs)
33
+ # @param set_if_missing [Hash] attributes to SET only if absent (if_not_exists)
34
+ # @param if_exists [Boolean] condition on the row existing instead of creating it
35
+ # @param touch [Boolean] false leaves updatedAt, createdAt and _recent_pk alone
36
+ # @return [ActiveItem::Base, nil] the row as stored after the update, or nil
37
+ # when `if_exists: true` and there is no such row
38
+ def update_counters(id, counters = nil, set: {}, set_if_missing: {}, if_exists: false, touch: true, **more_counters)
39
+ counters = (counters || {}).merge(more_counters)
40
+ item = counter_update_item(id, counters, set: set, set_if_missing: set_if_missing, if_exists: if_exists, touch: touch)
41
+ item && instantiate(item)
42
+ end
43
+
44
+ private
45
+
46
+ # Runs the UpdateItem and returns the raw ALL_NEW item, or nil when the
47
+ # `if_exists` condition failed.
48
+ def counter_update_item(id, counters, set:, set_if_missing:, if_exists:, touch: true)
49
+ raise_embedded_error!(:update_counters) if respond_to?(:embedded?) && embedded?
50
+ raise ArgumentError, 'update_counters needs an id' if id.nil? || id.to_s.empty?
51
+ raise ArgumentError, 'update_counters needs at least one counter' if counters.empty?
52
+
53
+ dynamodb.update_item(counter_update_params(id, counters, set, set_if_missing, if_exists, touch)).attributes
54
+ rescue Aws::DynamoDB::Errors::ConditionalCheckFailedException
55
+ raise unless if_exists
56
+
57
+ nil
58
+ rescue Aws::DynamoDB::Errors::AccessDeniedException => e
59
+ raise_access_denied('UpdateItem', e)
60
+ end
61
+
62
+ def counter_update_params(id, counters, set, set_if_missing, if_exists, touch)
63
+ names = {}
64
+ values = {}
65
+ sets = []
66
+ removes = []
67
+ adds = []
68
+ claimed = {}
69
+ claim = lambda do |name|
70
+ dynamo_key = counter_dynamo_key(name)
71
+ raise ArgumentError, "#{dynamo_key} appears more than once in update_counters" if claimed.key?(dynamo_key)
72
+
73
+ claimed[dynamo_key] = true
74
+ placeholder = "#a#{claimed.size}"
75
+ names[placeholder] = dynamo_key
76
+ placeholder
77
+ end
78
+
79
+ claimed[primary_key.to_s] = true
80
+ timestamps = touch ? { 'updatedAt' => '#updatedAt', 'createdAt' => '#createdAt', '_recent_pk' => '#recentPk' } : {}
81
+ timestamps.each_key { |key| claimed[key] = true }
82
+
83
+ counters.each do |name, amount|
84
+ raise ArgumentError, "counter #{name} needs a numeric amount, got #{amount.inspect}" unless amount.is_a?(Numeric)
85
+
86
+ placeholder = claim.call(name)
87
+ values[":#{placeholder[1..]}"] = amount
88
+ adds << "#{placeholder} :#{placeholder[1..]}"
89
+ end
90
+
91
+ set.each do |name, value|
92
+ placeholder = claim.call(name)
93
+ if value.nil?
94
+ removes << placeholder
95
+ else
96
+ values[":#{placeholder[1..]}"] = value
97
+ sets << "#{placeholder} = :#{placeholder[1..]}"
98
+ end
99
+ end
100
+
101
+ set_if_missing.each do |name, value|
102
+ raise ArgumentError, "set_if_missing #{name} needs a value" if value.nil?
103
+
104
+ placeholder = claim.call(name)
105
+ values[":#{placeholder[1..]}"] = value
106
+ sets << "#{placeholder} = if_not_exists(#{placeholder}, :#{placeholder[1..]})"
107
+ end
108
+
109
+ if touch
110
+ timestamps.each { |key, placeholder| names[placeholder] = key }
111
+ values[':now'] = Time.now.utc.iso8601
112
+ values[':recentPk'] = 'ALL'
113
+ sets.unshift('#updatedAt = :now', '#createdAt = if_not_exists(#createdAt, :now)',
114
+ '#recentPk = if_not_exists(#recentPk, :recentPk)')
115
+ end
116
+
117
+ expression = "ADD #{adds.join(', ')}"
118
+ expression = "SET #{sets.join(', ')} #{expression}" if sets.any?
119
+ expression += " REMOVE #{removes.join(', ')}" if removes.any?
120
+
121
+ params = {
122
+ table_name: table_name,
123
+ key: { primary_key.to_s => id },
124
+ update_expression: expression,
125
+ expression_attribute_names: names,
126
+ expression_attribute_values: values,
127
+ return_values: 'ALL_NEW'
128
+ }
129
+ if if_exists
130
+ names['#pk'] = primary_key.to_s
131
+ params[:condition_expression] = 'attribute_exists(#pk)'
132
+ end
133
+ params
134
+ end
135
+
136
+ # Declared (or explicitly mapped) attributes go through to_dynamo_key;
137
+ # anything else is already a DynamoDB attribute name.
138
+ def counter_dynamo_key(name)
139
+ name = name.to_s
140
+ return to_dynamo_key(name) if attribute_names.include?(name) || dynamo_attribute_map.key?(name)
141
+
142
+ name
143
+ end
144
+ end
145
+
146
+ # ADD `by` to each attribute on the stored row in one UpdateItem, then
147
+ # refresh those attributes (and the timestamps) from what was stored. The
148
+ # touched attributes are left clean; other unsaved changes are kept.
149
+ #
150
+ # Only updates a row that still exists: a deleted record is not brought
151
+ # back by its counter.
152
+ #
153
+ # @return [self, false] false when the row no longer exists
154
+ def increment!(*attributes, by: 1, set: {}, set_if_missing: {})
155
+ raise ArgumentError, 'increment! needs at least one attribute' if attributes.empty?
156
+ raise ArgumentError, "Cannot increment a new #{self.class.name}; save it first" if new_record?
157
+
158
+ attributes = attributes.map(&:to_s)
159
+ touched = attributes + set.keys.map(&:to_s) + set_if_missing.keys.map(&:to_s)
160
+ undeclared = touched - self.class.attribute_names
161
+ raise ArgumentError, "#{self.class.name} has no attribute #{undeclared.join(', ')}" if undeclared.any?
162
+
163
+ counters = attributes.to_h { |name| [name, by] }
164
+ item = self.class.send(:counter_update_item, id, counters, set: set, set_if_missing: set_if_missing, if_exists: true)
165
+ return false unless item
166
+
167
+ refresh_counter_attributes(item, touched)
168
+ self
169
+ end
170
+
171
+ # increment! with the amount negated.
172
+ def decrement!(*attributes, by: 1, set: {}, set_if_missing: {})
173
+ increment!(*attributes, by: -by, set: set, set_if_missing: set_if_missing)
174
+ end
175
+
176
+ private
177
+
178
+ def refresh_counter_attributes(item, touched)
179
+ fresh = self.class.instantiate(item)
180
+ touched.each { |name| instance_variable_set("@#{name}", fresh.instance_variable_get("@#{name}")) }
181
+ @created_at = fresh.created_at
182
+ @updated_at = fresh.updated_at
183
+ @dbrecord = fresh.dbrecord
184
+ clear_attribute_changes(touched)
185
+ end
186
+ end
187
+ end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module ActiveItem
4
- VERSION = '0.0.26'
4
+ VERSION = '0.0.27'
5
5
  end
data/lib/activeitem.rb CHANGED
@@ -15,6 +15,7 @@ require_relative 'active_item/composed_of'
15
15
  require_relative 'active_item/validations'
16
16
  require_relative 'active_item/transaction'
17
17
  require_relative 'active_item/pagination'
18
+ require_relative 'active_item/counters'
18
19
  require_relative 'active_item/base'
19
20
 
20
21
  # ActiveRecord-style ORM for Amazon DynamoDB.
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: activeitem
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.0.26
4
+ version: 0.0.27
5
5
  platform: ruby
6
6
  authors:
7
7
  - Andy Davis
@@ -9,7 +9,7 @@ authors:
9
9
  autorequire:
10
10
  bindir: bin
11
11
  cert_chain: []
12
- date: 2026-11-16 00:00:00.000000000 Z
12
+ date: 2026-11-24 00:00:00.000000000 Z
13
13
  dependencies:
14
14
  - !ruby/object:Gem::Dependency
15
15
  name: activemodel
@@ -160,6 +160,7 @@ files:
160
160
  - lib/active_item/begins_with.rb
161
161
  - lib/active_item/composed_of.rb
162
162
  - lib/active_item/configuration.rb
163
+ - lib/active_item/counters.rb
163
164
  - lib/active_item/database_helpers.rb
164
165
  - lib/active_item/embeddable.rb
165
166
  - lib/active_item/embedded_collection.rb