star_gates 0.3.1 → 0.4.0

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.
@@ -1,6 +1,13 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module StarGates
4
+ # A named entry point: a feature decides whether the primary path runs, a
5
+ # circuit guards it, and the fallback answers when it does not.
6
+ #
7
+ # The fallback runs when the primary is unavailable: the feature is off for
8
+ # the context, the circuit refuses, the primary raises, or the time budget
9
+ # runs out. Without a fallback, `call` raises UnavailableError whose
10
+ # `refusal` says which, with the primary's exception as its `cause`.
4
11
  class Gate
5
12
  attr_reader :name, :feature, :circuit, :run_block, :fallback_block
6
13
 
@@ -13,34 +20,20 @@ module StarGates
13
20
  end
14
21
 
15
22
  def call(context = {})
16
- # Use the new state-specific execute method if feature supports it
17
- if feature.respond_to?(:execute)
18
- result = if circuit
19
- circuit.call { feature.execute(context) { execute_run_block(context) } }
20
- else
21
- feature.execute(context) { execute_run_block(context) }
22
- end
23
-
24
- # If feature returns nil (disabled), execute fallback
25
- return result unless result.nil?
26
-
27
- execute_fallback(context)
28
- else
29
- # Fallback to old behavior for compatibility
30
- return execute_fallback(context) unless feature_enabled?(context)
31
-
32
- if circuit
33
- circuit.call { execute_run_block(context) }
34
- else
35
- execute_run_block(context)
36
- end
23
+ error = nil
24
+ refusal, result = begin
25
+ execute_primary(context)
26
+ rescue StandardError => e
27
+ error = e
28
+ [refusal_for(e), nil]
37
29
  end
38
- rescue StarGates::UnavailableError, StandardError
39
- execute_fallback(context)
30
+ return result unless refusal
31
+
32
+ execute_fallback(context, refusal, error)
40
33
  end
41
34
 
42
35
  def enabled_for?(context = {})
43
- feature_enabled?(context) && !circuit_open?
36
+ feature_enabled?(context) && !open?
44
37
  end
45
38
 
46
39
  def open?
@@ -54,47 +47,66 @@ module StarGates
54
47
  def status
55
48
  {
56
49
  name: name,
57
- feature_enabled: feature&.enabled? || true,
50
+ feature_enabled: feature.nil? || feature.enabled?,
58
51
  feature_status: feature.respond_to?(:status) ? feature.status : nil,
59
- circuit_open: circuit&.open? || false,
60
- last_failure: circuit&.last_failure_time
52
+ circuit_open: open?,
53
+ last_failure_at: circuit&.last_failure_at
61
54
  }
62
55
  end
63
56
 
64
57
  private
65
58
 
59
+ # [nil, result] when the primary ran, [refusal, nil] when it did not.
60
+ def execute_primary(context)
61
+ return execute_feature(context) if feature.respond_to?(:execute)
62
+ return [:ineligible, nil] unless feature_enabled?(context)
63
+
64
+ [nil, with_circuit { execute_run_block(context) }]
65
+ end
66
+
67
+ def execute_feature(context)
68
+ executed = false
69
+ result = with_circuit do
70
+ feature.execute(context) do
71
+ executed = true
72
+ execute_run_block(context)
73
+ end
74
+ end
75
+
76
+ executed ? [nil, result] : [:ineligible, nil]
77
+ end
78
+
79
+ def refusal_for(error)
80
+ case error
81
+ when BreakerMachines::CircuitRefusedError then error.refusal
82
+ when UnavailableError then error.refusal
83
+ else :failed
84
+ end
85
+ end
86
+
87
+ def with_circuit(&block)
88
+ circuit ? circuit.call(&block) : block.call
89
+ end
90
+
66
91
  def feature_enabled?(context)
67
92
  return true unless feature
68
93
 
69
94
  feature.enabled_for?(context)
70
95
  end
71
96
 
72
- def circuit_open?
73
- circuit&.open? || false
74
- end
75
-
76
97
  def execute_run_block(context)
77
98
  return unless run_block
78
99
 
79
- if run_block.arity == 1
80
- run_block.call(context)
81
- else
82
- run_block.call
83
- end
100
+ run_block.arity == 1 ? run_block.call(context) : run_block.call
84
101
  end
85
102
 
86
- def execute_fallback(context)
87
- return raise_unavailable unless fallback_block
88
-
89
- if fallback_block.arity == 1
90
- fallback_block.call(context)
91
- else
92
- fallback_block.call
103
+ def execute_fallback(context, refusal, error)
104
+ unless fallback_block
105
+ raise UnavailableError.new(name, refusal, "Gate #{name} is unavailable (#{refusal}) and has no fallback"),
106
+ cause: error
93
107
  end
94
- end
95
108
 
96
- def raise_unavailable
97
- raise StarGates::UnavailableError, "Gate #{name} is unavailable and no fallback is defined"
109
+ fallback_block.arity == 1 ? fallback_block.call(context) : fallback_block.call
98
110
  end
99
111
  end
100
112
  end
@@ -4,7 +4,26 @@ require_relative '../events/feature_events'
4
4
 
5
5
  module StarGates
6
6
  module Hexagonal
7
+ # A feature's event-sourced state. Each command answers the event it
8
+ # recorded, or a refusal symbol and changes nothing: :already_created,
9
+ # :invalid_transition (no such event between those states), :stale_state
10
+ # (the feature is not in `from_state`).
11
+ #
12
+ # States and event names are Symbols. A String (or any other type) is a
13
+ # TypeError raised before anything changes: the aggregate never stores a
14
+ # name it would later fail to match. Wire adapters convert at their own
15
+ # boundary (JsonrpcRailsAdapter does).
16
+ #
17
+ # `version` counts the events the store holds: replayed and saved ones.
7
18
  class FeatureAggregate
19
+ TRANSITIONS = {
20
+ disabled: { rollout_canary: :canary, enable: :enabled },
21
+ canary: { enable: :enabled, disable: :disabled },
22
+ enabled: { disable: :disabled, rollout_canary: :canary }
23
+ }.freeze
24
+ TRANSITIONS_KEPT = 50
25
+ RECORDS_KEPT = 100
26
+
8
27
  attr_reader :id, :version, :uncommitted_events
9
28
 
10
29
  def initialize(id, events = [])
@@ -19,12 +38,13 @@ module StarGates
19
38
 
20
39
  # Command: Create feature
21
40
  def create(rollout: 0, group: nil, metadata: {})
22
- raise ArgumentError, 'Feature already exists' if created?
41
+ Rollout.validated(rollout)
42
+ return :already_created if created?
23
43
 
24
44
  event = Events::FeatureCreated.new(
25
45
  aggregate_id: @id,
26
46
  data: {
27
- rollout_percentage: parse_rollout(rollout),
47
+ rollout_percentage: rollout,
28
48
  group_matcher: group,
29
49
  metadata: metadata
30
50
  }
@@ -35,9 +55,9 @@ module StarGates
35
55
 
36
56
  # Command: Change state
37
57
  def change_state(from_state, to_state, event_name, context = {})
38
- unless can_transition?(from_state, to_state, event_name)
39
- raise InvalidTransitionError, "Cannot transition from #{from_state} to #{to_state} via #{event_name}"
40
- end
58
+ { from_state:, to_state:, event_name: }.each { |name, value| symbol!(name, value) }
59
+ return :invalid_transition unless TRANSITIONS.dig(from_state, event_name) == to_state
60
+ return :stale_state unless from_state == current_state
41
61
 
42
62
  event = Events::FeatureStateChanged.new(
43
63
  aggregate_id: @id,
@@ -117,8 +137,9 @@ module StarGates
117
137
  @state[:evaluations] || []
118
138
  end
119
139
 
120
- # Mark events as committed
140
+ # The store now holds the uncommitted events.
121
141
  def mark_events_as_committed
142
+ @version += @uncommitted_events.size
122
143
  @uncommitted_events.clear
123
144
  end
124
145
 
@@ -133,20 +154,17 @@ module StarGates
133
154
 
134
155
  # Load from snapshot
135
156
  def self.from_snapshot(snapshot, events_since_snapshot = [])
136
- aggregate = allocate
137
- aggregate.instance_variable_set(:@id, snapshot[:id])
138
- aggregate.instance_variable_set(:@version, snapshot[:version])
139
- aggregate.instance_variable_set(:@state, snapshot[:state].dup)
140
- aggregate.instance_variable_set(:@uncommitted_events, [])
141
-
142
- # Apply events since snapshot
143
- events_since_snapshot.each { |event| aggregate.apply_event(event, from_history: true) }
144
-
145
- aggregate
157
+ new(snapshot[:id]).tap { |aggregate| aggregate.__send__(:restore, snapshot, events_since_snapshot) }
146
158
  end
147
159
 
148
160
  private
149
161
 
162
+ def restore(snapshot, events)
163
+ @version = snapshot[:version]
164
+ @state = snapshot[:state].dup
165
+ events.each { |event| apply_event(event, from_history: true) }
166
+ end
167
+
150
168
  def apply_event(event, from_history: false)
151
169
  case event
152
170
  when Events::FeatureCreated
@@ -163,6 +181,7 @@ module StarGates
163
181
 
164
182
  @version += 1 if from_history
165
183
  @uncommitted_events << event unless from_history
184
+ event
166
185
  end
167
186
 
168
187
  def apply_feature_created(event)
@@ -179,72 +198,47 @@ module StarGates
179
198
 
180
199
  def apply_state_changed(event)
181
200
  @state[:current_state] = event.to_state
182
- @state[:transitions] ||= []
183
- @state[:transitions] << {
201
+ @state[:transitions] = append(:transitions, TRANSITIONS_KEPT, {
184
202
  from_state: event.from_state,
185
203
  to_state: event.to_state,
186
204
  event_name: event.event_name,
187
205
  context: event.context,
188
206
  occurred_at: event.occurred_at
189
- }
190
-
191
- # Keep only last 50 transitions for memory efficiency
192
- @state[:transitions] = @state[:transitions].last(50) if @state[:transitions].size > 50
207
+ })
193
208
  end
194
209
 
195
210
  def apply_configuration_changed(event)
196
- @state[:configuration] ||= {}
197
- @state[:configuration].merge!(event.configuration_changes)
211
+ @state[:configuration] = configuration.merge(event.configuration_changes)
198
212
  end
199
213
 
200
214
  def apply_execution_recorded(event)
201
- @state[:executions] ||= []
202
- @state[:executions] << {
215
+ @state[:executions] = append(:executions, RECORDS_KEPT, {
203
216
  context: event.context,
204
217
  result: event.result,
205
218
  execution_time: event.execution_time,
206
219
  occurred_at: event.occurred_at
207
- }
208
-
209
- # Keep only last 100 executions
210
- @state[:executions] = @state[:executions].last(100) if @state[:executions].size > 100
220
+ })
211
221
  end
212
222
 
213
223
  def apply_evaluation_recorded(event)
214
- @state[:evaluations] ||= []
215
- @state[:evaluations] << {
224
+ @state[:evaluations] = append(:evaluations, RECORDS_KEPT, {
216
225
  context: event.context,
217
226
  eligible: event.eligible,
218
227
  reason: event.reason,
219
228
  occurred_at: event.occurred_at
220
- }
221
-
222
- # Keep only last 100 evaluations
223
- @state[:evaluations] = @state[:evaluations].last(100) if @state[:evaluations].size > 100
229
+ })
224
230
  end
225
231
 
226
- def can_transition?(from_state, to_state, event_name)
227
- # Define valid transitions
228
- valid_transitions = {
229
- disabled: { rollout_canary: :canary, enable: :enabled },
230
- canary: { enable: :enabled, disable: :disabled },
231
- enabled: { disable: :disabled, rollout_canary: :canary }
232
- }
233
-
234
- allowed_transitions = valid_transitions[from_state.to_sym] || {}
235
- allowed_transitions[event_name.to_sym] == to_state.to_sym
232
+ # A new list, so a snapshot taken earlier keeps its own.
233
+ def append(key, kept, record)
234
+ [*@state[key], record].last(kept)
236
235
  end
237
236
 
238
- def parse_rollout(rollout)
239
- case rollout
240
- when Numeric, String
241
- rollout.to_i
242
- else
243
- 0
244
- end
245
- end
237
+ def symbol!(name, value)
238
+ return if value.is_a?(Symbol)
246
239
 
247
- class InvalidTransitionError < StandardError; end
240
+ raise TypeError, "#{name} must be a Symbol, got #{value.inspect}"
241
+ end
248
242
  end
249
243
  end
250
244
  end
@@ -17,17 +17,12 @@ module StarGates
17
17
  FeatureAggregate.new(feature_id, events)
18
18
  end
19
19
 
20
- # Save feature aggregate to event store
20
+ # Stores the aggregate's uncommitted events and answers how many, or
21
+ # :version_conflict (the aggregate keeps them; nothing is stored).
21
22
  def save(aggregate, expected_version: nil)
22
- return if aggregate.uncommitted_events.empty?
23
-
24
- @event_store.append(
25
- aggregate.id,
26
- aggregate.uncommitted_events,
27
- expected_version: expected_version
28
- )
29
-
30
- aggregate.mark_events_as_committed
23
+ stored = @event_store.append(aggregate.id, aggregate.uncommitted_events, expected_version: expected_version)
24
+ aggregate.mark_events_as_committed if stored.is_a?(Integer)
25
+ stored
31
26
  end
32
27
 
33
28
  # Find or create feature aggregate
@@ -40,28 +35,11 @@ module StarGates
40
35
  @event_store.get_version(feature_id).positive?
41
36
  end
42
37
 
43
- # Get all feature IDs that have events
44
- def all_feature_ids
45
- # This would need to be implemented by the event store adapter
46
- # For now, we'll return an empty array as this requires scanning
47
- []
48
- end
49
-
50
- # Get features by state (requires read model/projection)
51
- def find_by_state(state)
52
- # This would typically be implemented using a read model/projection
53
- # For now, we'll raise an error to indicate this needs a projection
54
- raise NotImplementedError, 'Use FeatureProjection to query by state'
55
- end
56
-
57
38
  # Health check
58
39
  def healthy?
59
40
  @event_store.respond_to?(:healthy?) ? @event_store.healthy? : true
60
41
  end
61
42
 
62
- private
63
-
64
- attr_reader :event_store
65
43
  end
66
44
  end
67
45
  end
@@ -5,6 +5,9 @@ require_relative '../projections/feature_projection'
5
5
 
6
6
  module StarGates
7
7
  module Hexagonal
8
+ # Commands answer the aggregate, or a refusal symbol and change nothing:
9
+ # :not_found, the aggregate's own refusals (:invalid_transition,
10
+ # :stale_state) and the store's (:version_conflict).
8
11
  class FeatureService
9
12
  def initialize(repository:, projection:, event_store:)
10
13
  @repository = repository
@@ -13,52 +16,32 @@ module StarGates
13
16
  setup_event_subscriptions
14
17
  end
15
18
 
16
- # Commands
19
+ # The feature, created unless it exists. A creation that loses a race
20
+ # answers the winner's feature.
17
21
  def create_feature(feature_id, rollout: 0, group: nil, metadata: {})
18
22
  aggregate = @repository.find_or_create(feature_id)
23
+ return aggregate if aggregate.created?
19
24
 
20
- unless aggregate.created?
21
- aggregate.create(rollout: rollout, group: group, metadata: metadata)
22
- @repository.save(aggregate)
23
- end
24
-
25
- aggregate
25
+ aggregate.create(rollout: rollout, group: group, metadata: metadata)
26
+ saved = @repository.save(aggregate, expected_version: aggregate.version)
27
+ saved.is_a?(Symbol) ? @repository.find(feature_id) : aggregate
26
28
  end
27
29
 
28
30
  def change_feature_state(feature_id, from_state, to_state, event_name, context = {})
29
- aggregate = @repository.find(feature_id)
30
- raise FeatureNotFoundError, "Feature #{feature_id} not found" unless aggregate
31
-
32
- aggregate.change_state(from_state, to_state, event_name, context)
33
- @repository.save(aggregate)
34
-
35
- aggregate
31
+ command(feature_id) { |aggregate| aggregate.change_state(from_state, to_state, event_name, context) }
36
32
  end
37
33
 
38
34
  def update_feature_configuration(feature_id, changes)
39
- aggregate = @repository.find(feature_id)
40
- raise FeatureNotFoundError, "Feature #{feature_id} not found" unless aggregate
41
-
42
- aggregate.update_configuration(changes)
43
- @repository.save(aggregate)
44
-
45
- aggregate
35
+ command(feature_id) { |aggregate| aggregate.update_configuration(changes) }
46
36
  end
47
37
 
38
+ # `execution_time` in Integer nanoseconds.
48
39
  def record_feature_execution(feature_id, context, result, execution_time)
49
- aggregate = @repository.find(feature_id)
50
- return unless aggregate # Silently skip if feature doesn't exist
51
-
52
- aggregate.record_execution(context, result, execution_time)
53
- @repository.save(aggregate)
40
+ command(feature_id) { |aggregate| aggregate.record_execution(context, result, execution_time) }
54
41
  end
55
42
 
56
43
  def record_feature_evaluation(feature_id, context, eligible, reason)
57
- aggregate = @repository.find(feature_id)
58
- return unless aggregate # Silently skip if feature doesn't exist
59
-
60
- aggregate.record_evaluation(context, eligible, reason)
61
- @repository.save(aggregate)
44
+ command(feature_id) { |aggregate| aggregate.record_evaluation(context, eligible, reason) }
62
45
  end
63
46
 
64
47
  # Queries (delegated to projection)
@@ -82,6 +65,10 @@ module StarGates
82
65
  @projection.recent_transitions(limit: limit)
83
66
  end
84
67
 
68
+ def transition_count
69
+ @projection.transition_count
70
+ end
71
+
85
72
  def feature_exists?(feature_id)
86
73
  @projection.feature_exists?(feature_id)
87
74
  end
@@ -108,14 +95,25 @@ module StarGates
108
95
 
109
96
  private
110
97
 
98
+ # Loads the aggregate, applies the block's command and saves it under
99
+ # the version it was loaded at, so a concurrent writer is refused.
100
+ def command(feature_id)
101
+ aggregate = @repository.find(feature_id)
102
+ return :not_found unless aggregate
103
+
104
+ outcome = yield aggregate
105
+ return outcome if outcome.is_a?(Symbol)
106
+
107
+ saved = @repository.save(aggregate, expected_version: aggregate.version)
108
+ saved.is_a?(Symbol) ? saved : aggregate
109
+ end
110
+
111
111
  def setup_event_subscriptions
112
112
  # Subscribe to all events to update projections
113
113
  @event_store.subscribe do |event|
114
114
  @projection.handle_event(event)
115
115
  end
116
116
  end
117
-
118
- class FeatureNotFoundError < StandardError; end
119
117
  end
120
118
  end
121
119
  end
@@ -2,7 +2,13 @@
2
2
 
3
3
  module StarGates
4
4
  # Optional JSON-RPC adapter using jsonrpc-rails gem
5
- # Include this in your Rails controllers when jsonrpc-rails is available
5
+ # Include this in your Rails controllers when jsonrpc-rails is available.
6
+ # It defines no method ActionController::Base has, so including it never
7
+ # changes how Rails dispatches the controller.
8
+ # A refused command answers invalid_params with the refusal symbol as its
9
+ # error; `executionTime` is Integer nanoseconds. Wall-clock instants on the
10
+ # wire stay ISO 8601 strings: Integer nanoseconds since the epoch exceed
11
+ # what a JavaScript client reads exactly.
6
12
  module JsonrpcRailsAdapter
7
13
  def self.available?
8
14
  defined?(JSON_RPC) && defined?(ActionController::Base)
@@ -14,8 +20,11 @@ module StarGates
14
20
  raise LoadError, "jsonrpc-rails gem is required. Add 'gem \"jsonrpc-rails\"' to your Gemfile"
15
21
  end
16
22
 
17
- # Main JSON-RPC request handler
18
- def process
23
+ # The JSON-RPC action: route to it (`to: 'features#handle_jsonrpc'`). It
24
+ # is not named `process`, which is Rails' own dispatch entry point
25
+ # (`process(action, *args)`): a module method of that name would sit
26
+ # between the controller and ActionController::Base and replace it.
27
+ def handle_jsonrpc
19
28
  if jsonrpc_params_batch?
20
29
  # Handle batch requests
21
30
  responses = jsonrpc_params.filter_map { |req| handle_single_request(req) }
@@ -135,6 +144,7 @@ module StarGates
135
144
  context = params['context'] || {}
136
145
 
137
146
  aggregate = feature_service.change_feature_state(feature_id, from_state, to_state, event_name, context)
147
+ return refused(aggregate) if aggregate.is_a?(Symbol)
138
148
 
139
149
  {
140
150
  featureId: aggregate.id,
@@ -153,11 +163,12 @@ module StarGates
153
163
  feature_id = params['featureId']
154
164
  context = params['context'] || {}
155
165
 
156
- start_time = Time.now
166
+ started = StarGates.monotonic_time
157
167
  result = yield if block_given? # Allow caller to provide execution block
158
- execution_time = ((Time.now - start_time) * 1000).round(2) # ms
168
+ execution_time = StarGates.monotonic_time - started
159
169
 
160
- feature_service.record_feature_execution(feature_id, context, result, execution_time)
170
+ recorded = feature_service.record_feature_execution(feature_id, context, result, execution_time)
171
+ return refused(recorded) if recorded.is_a?(Symbol)
161
172
 
162
173
  {
163
174
  featureId: feature_id,
@@ -177,7 +188,8 @@ module StarGates
177
188
  eligible = params['eligible'] || false
178
189
  reason = params['reason'] || 'No reason provided'
179
190
 
180
- feature_service.record_feature_evaluation(feature_id, context, eligible, reason)
191
+ recorded = feature_service.record_feature_evaluation(feature_id, context, eligible, reason)
192
+ return refused(recorded) if recorded.is_a?(Symbol)
181
193
 
182
194
  {
183
195
  featureId: feature_id,
@@ -228,6 +240,11 @@ module StarGates
228
240
  JSON_RPC::JsonRpcError.build(:internal_error, data: { error: e.message })
229
241
  end
230
242
 
243
+ # A refused command, its refusal symbol as the error data.
244
+ def refused(refusal)
245
+ JSON_RPC::JsonRpcError.build(:invalid_params, data: { error: refusal.to_s })
246
+ end
247
+
231
248
  # Helper methods
232
249
  def validate_required_params(params, required_keys)
233
250
  missing_keys = required_keys - params.keys