Class: Magick::Feature

Inherits:
Object
  • Object
show all
Defined in:
lib/magick/feature.rb

Constant Summary collapse

VALID_TYPES =
%i[boolean string number].freeze
VALID_STATUSES =
%i[active inactive deprecated].freeze
DISABLED_VALUES =

What "off" means per feature type — the value #disable writes.

{ boolean: false, string: '', number: 0 }.freeze
DEPENDENCIES_KEY =

Adapter keys holding the prerequisite set and the declaration that seeded it. Both live next to the feature's other state, so dependencies travel with the feature across processes and restarts.

'dependencies'
DECLARED_DEPENDENCIES_KEY =
'declared_dependencies'
UNKNOWN_DEPENDENCY_RECHECK_SECONDS =

How long a prerequisite that exists nowhere stays cached as "unknown" before the backend is probed again. Without it a misconfigured dependency would cost a Redis/DB round trip on every evaluation.

60.0

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, adapter_registry, **options) ⇒ Feature

Returns a new instance of Feature.



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/magick/feature.rb', line 28

def initialize(name, adapter_registry, **options)
  @name = name.to_s
  @adapter_registry = adapter_registry
  @type = (options[:type] || :boolean).to_sym
  @status = (options[:status] || :active).to_sym
  @default_value = options.fetch(:default_value, default_for_type)
  @description = options[:description]
  @display_name = options[:name] || options[:display_name]
  @group = options[:group]
  @targeting = {}
  # nil means this process declares nothing about dependencies, so it must
  # never overwrite what another process stored; [] is a real declaration
  # ("this feature has no prerequisites").
  @declared_dependencies = options[:dependencies] ? normalize_dependency_list(options[:dependencies]) : nil
  @dependencies = @declared_dependencies&.dup || []
  @stored_value_initialized = false # Track if @stored_value has been explicitly set

  # Performance optimizations: cache expensive checks
  @_targeting_empty = true # Will be updated after load_from_adapter
  @_rails_events_enabled = false # Cache Rails events availability (only enable in dev)
  @_perf_metrics_enabled = false # Cache performance metrics (disabled by default for speed)
  # Whether evaluations may ask the registry to re-read the shared backend
  # (Registry#refresh_if_stale!). A bare adapter, as some specs pass, cannot.
  @_source_refresh = adapter_registry.respond_to?(:refresh_if_stale!)

  validate_type!
  validate_default_value!
  load_from_adapter
  # Update targeting empty cache after loading
  @_targeting_empty = @targeting.empty?
  # Cache performance metrics availability (check once, not on every call)
  # Only enable if performance_metrics exists AND is actually being used
  @_perf_metrics_enabled = !Magick.performance_metrics.nil?
  # Save description and display_name to adapter if they were provided and not already in adapter
  
end

Instance Attribute Details

#adapter_registry ⇒ Object (readonly)

Returns the value of attribute adapter_registry.



25
26
27
# File 'lib/magick/feature.rb', line 25

def adapter_registry
  @adapter_registry
end

#default_value ⇒ Object (readonly)

Returns the value of attribute default_value.



25
26
27
# File 'lib/magick/feature.rb', line 25

def default_value
  @default_value
end

#description ⇒ Object (readonly)

Returns the value of attribute description.



25
26
27
# File 'lib/magick/feature.rb', line 25

def description
  @description
end

#display_name ⇒ Object (readonly)

Returns the value of attribute display_name.



25
26
27
# File 'lib/magick/feature.rb', line 25

def display_name
  @display_name
end

#group ⇒ Object (readonly)

Returns the value of attribute group.



25
26
27
# File 'lib/magick/feature.rb', line 25

def group
  @group
end

#name ⇒ Object (readonly)

Returns the value of attribute name.



25
26
27
# File 'lib/magick/feature.rb', line 25

def name
  @name
end

#status ⇒ Object (readonly)

Returns the value of attribute status.



25
26
27
# File 'lib/magick/feature.rb', line 25

def status
  @status
end

#targeting ⇒ Object (readonly)

Returns the value of attribute targeting.



25
26
27
# File 'lib/magick/feature.rb', line 25

def targeting
  @targeting
end

#type ⇒ Object (readonly)

Returns the value of attribute type.



25
26
27
# File 'lib/magick/feature.rb', line 25

def type
  @type
end

Instance Method Details

#add_dependency(dependency_name, user_id: nil) ⇒ Object

Prerequisites are stored with the rest of the feature's state, so a dependency added here is visible to every other process and survives a restart. Adding one already present is a no-op (no audit entry, no version).



527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
# File 'lib/magick/feature.rb', line 527

def add_dependency(dependency_name, user_id: nil)
  dep = normalize_dependency_name(dependency_name)
  return true if dependencies.include?(dep)

  record_change('add_dependency', { dependency: { added: dep } }, user_id: user_id) do
    write_dependencies(dependencies + [dep])

    # Rails 8+ event
    if defined?(Magick::Rails::Events) && Magick::Rails::Events.rails8?
      Magick::Rails::Events.dependency_added(name, dep)
    end
  end

  true
end

#as_json(_options = nil) ⇒ Object

Wire-format serializer for control-plane APIs (e.g. the platform's /internal/panel/flags endpoints). The "targeting" key is ALWAYS present ({} = no targeting), array rules are arrays of strings, percentages are floats, and the internal :variants entry never appears inside targeting. Rails-idiomatic: render json: feature (or a collection) emits this.



798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
# File 'lib/magick/feature.rb', line 798

def as_json(_options = nil)
  {
    'name' => name,
    'display_name' => display_name,
    'group' => group,
    'type' => type.to_s,
    'status' => status.to_s,
    'value' => stored_value,
    'default_value' => default_value,
    'description' => description,
    'targeting' => TargetingPayload.serialize(targeting),
    'dependencies' => (@dependencies || []).map(&:to_s),
    # Variants live inside @targeting under the internal :variants key;
    # both the wire payload and the export read them from there.
    'variants' => TargetingPayload.deep_stringify(variants_for_export)
  }
end

#check_enabled(context = {}) ⇒ Object



115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/magick/feature.rb', line 115

def check_enabled(context = {})
  # Dup context to avoid mutating the caller's hash
  context = context.dup

  # Extract context from user object if provided
  # This allows Magick.enabled?(:feature, user: player) to work
  if context[:user]
    extracted = extract_context_from_object(context.delete(:user))
    # Merge extracted context, but don't override explicit values already in context
    extracted.each do |key, value|
      context[key] = value unless context.key?(key)
    end
  end

  # Fast path: check status first
  return false if status == :inactive
  return false if status == :deprecated && !context[:allow_deprecated]

  # Dependency check: a feature with unmet prerequisites evaluates as disabled,
  # regardless of its own configured state. Evaluation-only — prerequisite state
  # is never written into this feature.
  return false unless dependencies_satisfied?(context)

  # Fast path: skip targeting checks if targeting is empty (most common case)
  unless @_targeting_empty
    # Check exclusions FIRST — exclusions always take priority over inclusions
    return false if excluded?(context)

    # Check date/time range targeting
    return false if targeting[:date_range] && !date_range_active?(targeting[:date_range])

    # Check IP address targeting
    return false if targeting[:ip_address] && context[:ip_address] && !ip_address_matches?(context[:ip_address])

    # Check custom attributes
    return false if targeting[:custom_attributes] && !custom_attributes_match?(context,
                                                                               targeting[:custom_attributes])

    # Check complex conditions
    return false if targeting[:complex_conditions] && !complex_conditions_match?(context,
                                                                                 targeting[:complex_conditions])

    # Check user/group/role/percentage targeting
    targeting_result = check_targeting(context)
    return false if targeting_result.nil?
    # Targeting doesn't match - return false

    # Targeting matches - for boolean features, return true directly
    # For string/number features, still check the value
    return true if type == :boolean
    # For string/number, continue to check value below

  end

  # Get value and check based on type
  value = get_value(context)
  case type
  when :boolean
    value == true
  when :string
    !value.nil? && value != ''
  when :number
    value.to_f.positive?
  else
    false
  end
rescue StandardError => e
  # Return false on any error (fail-safe)
  warn "Magick: Error in check_enabled for '#{Magick::LogSafe.sanitize(name)}': #{Magick::LogSafe.sanitize(e.message)}" if defined?(::Rails) && ::Rails.env.development?
  false
end

#clear_variants ⇒ Object

Drops all variants. Absent variants and an empty variants list are different states: an empty list would leave a targeting hash that is no longer empty and so evaluates as "targeted, matched nothing".



867
868
869
870
871
872
873
874
875
876
877
878
879
880
# File 'lib/magick/feature.rb', line 867

def clear_variants
  return true if targeting[:variants].nil?

  record_change('clear_variants', { variants: [] }) do
    disable_targeting(:variants)

    # Rails 8+ event
    if defined?(Magick::Rails::Events) && Magick::Rails::Events.rails8?
      Magick::Rails::Events.variant_set(name, variants: [])
    end
  end

  true
end

#delete ⇒ Object



728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
# File 'lib/magick/feature.rb', line 728

def delete
  # Snapshot before the wipe so the recorded version captures the state
  # this feature had when it was deleted, not the emptied one.
  snapshot = to_h

  record_change('delete', { deleted: true }, snapshot: snapshot) do
    adapter_registry.delete(name)
    @stored_value = nil
    @stored_value_initialized = false # Reset initialization flag so get_value returns default_value
    @targeting = {}
    # Also remove from Magick.features if registered
    Magick.features.delete(name.to_s)
  end
  true
end

#dependencies ⇒ Object



573
574
575
# File 'lib/magick/feature.rb', line 573

def dependencies
  @dependencies || []
end

#disable(user_id: nil) ⇒ Object



673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
# File 'lib/magick/feature.rb', line 673

def disable(user_id: nil)
  # Same contract as #enable: nothing is cleared or written unless the whole
  # operation can go through.
  disabled_value = DISABLED_VALUES.fetch(type) do
    raise InvalidFeatureValueError, "Cannot disable feature of type #{type}"
  end
  changes = { value: { from: @stored_value, to: disabled_value }, targeting: { cleared: true } }

  record_change('disable', changes, user_id: user_id) do
    # Clear all targeting to disable globally
    @targeting = {}
    save_targeting

    set_value(disabled_value, user_id: user_id)

    # Ensure registered feature instance also has targeting cleared
    if Magick.features.key?(name)
      registered = Magick.features[name]
      registered.instance_variable_set(:@targeting, {})
    end

    # Rails 8+ event
    if defined?(Magick::Rails::Events) && Magick::Rails::Events.rails8?
      Magick::Rails::Events.feature_disabled_globally(name, user_id: user_id)
    end
  end

  true
end

#disable_custom_attribute(attribute_name) ⇒ Object



492
493
494
495
496
497
498
499
500
501
502
503
# File 'lib/magick/feature.rb', line 492

def disable_custom_attribute(attribute_name)
  record_change('disable_custom_attribute', targeting_change(:custom_attributes, removed: attribute_name)) do
    custom_attrs = targeting[:custom_attributes] || {}
    custom_attrs.delete(attribute_name.to_sym)
    if custom_attrs.empty?
      disable_targeting(:custom_attributes)
    else
      enable_targeting(:custom_attributes, custom_attrs)
    end
  end
  true
end

#disable_date_range ⇒ Object



452
453
454
455
456
457
# File 'lib/magick/feature.rb', line 452

def disable_date_range
  record_change('disable_date_range', targeting_change(:date_range)) do
    disable_targeting(:date_range)
  end
  true
end

#disable_for_group(group_name) ⇒ Object



281
282
283
284
285
286
# File 'lib/magick/feature.rb', line 281

def disable_for_group(group_name)
  record_change('disable_for_group', targeting_change(:group, removed: group_name)) do
    disable_targeting(:group, group_name)
  end
  true
end

#disable_for_role(role_name) ⇒ Object



295
296
297
298
299
300
# File 'lib/magick/feature.rb', line 295

def disable_for_role(role_name)
  record_change('disable_for_role', targeting_change(:role, removed: role_name)) do
    disable_targeting(:role, role_name)
  end
  true
end

#disable_for_tag(tag_name) ⇒ Object



309
310
311
312
313
314
# File 'lib/magick/feature.rb', line 309

def disable_for_tag(tag_name)
  record_change('disable_for_tag', targeting_change(:tag, removed: tag_name)) do
    disable_targeting(:tag, tag_name)
  end
  true
end

#disable_for_user(user_id) ⇒ Object



267
268
269
270
271
272
# File 'lib/magick/feature.rb', line 267

def disable_for_user(user_id)
  record_change('disable_for_user', targeting_change(:user, removed: user_id)) do
    disable_targeting(:user, user_id)
  end
  true
end

#disable_ip_addresses ⇒ Object



474
475
476
477
478
479
# File 'lib/magick/feature.rb', line 474

def disable_ip_addresses
  record_change('disable_ip_addresses', targeting_change(:ip_address)) do
    disable_targeting(:ip_address)
  end
  true
end

#disable_percentage_of_requests ⇒ Object



437
438
439
440
441
442
# File 'lib/magick/feature.rb', line 437

def disable_percentage_of_requests
  record_change('disable_percentage_of_requests', targeting_change(:percentage_requests)) do
    disable_targeting(:percentage_requests)
  end
  true
end

#disable_percentage_of_users ⇒ Object



413
414
415
416
417
418
# File 'lib/magick/feature.rb', line 413

def disable_percentage_of_users
  record_change('disable_percentage_of_users', targeting_change(:percentage_users)) do
    disable_targeting(:percentage_users)
  end
  true
end

#disabled?(context = {}) ⇒ Boolean

Returns:

  • (Boolean)


187
188
189
# File 'lib/magick/feature.rb', line 187

def disabled?(context = {})
  !enabled?(context)
end

#disabled_for?(object, **additional_context) ⇒ Boolean

Returns:

  • (Boolean)


199
200
201
# File 'lib/magick/feature.rb', line 199

def disabled_for?(object, **additional_context)
  !enabled_for?(object, **additional_context)
end

#enable(user_id: nil) ⇒ Object



649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
# File 'lib/magick/feature.rb', line 649

def enable(user_id: nil)
  # Validate the type BEFORE touching anything: a caller that catches this
  # must be able to rely on targeting and the stored value being untouched,
  # in this process and in the backend.
  validate_enableable!

  changes = { value: { from: @stored_value, to: true }, targeting: { cleared: true } }

  record_change('enable', changes, user_id: user_id) do
    # Clear all targeting to enable globally
    @targeting = {}
    save_targeting

    set_value(true, user_id: user_id)

    # Rails 8+ event
    if defined?(Magick::Rails::Events) && Magick::Rails::Events.rails8?
      Magick::Rails::Events.feature_enabled_globally(name, user_id: user_id)
    end
  end

  true
end

#enable_for_custom_attribute(attribute_name, values, operator: :equals) ⇒ Object



481
482
483
484
485
486
487
488
489
490
# File 'lib/magick/feature.rb', line 481

def enable_for_custom_attribute(attribute_name, values, operator: :equals)
  change = targeting_change(:custom_attributes,
                            added: { attribute: attribute_name, values: Array(values), operator: operator })
  record_change('enable_for_custom_attribute', change) do
    custom_attrs = targeting[:custom_attributes] || {}
    custom_attrs[attribute_name.to_sym] = { values: Array(values), operator: operator }
    enable_targeting(:custom_attributes, custom_attrs)
  end
  true
end

#enable_for_date_range(start_date, end_date) ⇒ Object



444
445
446
447
448
449
450
# File 'lib/magick/feature.rb', line 444

def enable_for_date_range(start_date, end_date)
  record_change('enable_for_date_range',
                targeting_change(:date_range, added: { start: start_date, end: end_date })) do
    enable_targeting(:date_range, { start: start_date, end: end_date })
  end
  true
end

#enable_for_group(group_name) ⇒ Object



274
275
276
277
278
279
# File 'lib/magick/feature.rb', line 274

def enable_for_group(group_name)
  record_change('enable_for_group', targeting_change(:group, added: group_name)) do
    enable_targeting(:group, group_name)
  end
  true
end

#enable_for_ip_addresses(ip_addresses) ⇒ Object



459
460
461
462
463
464
465
466
467
468
469
470
471
472
# File 'lib/magick/feature.rb', line 459

def enable_for_ip_addresses(ip_addresses)
  ips = Array(ip_addresses).map(&:to_s)
  record_change('enable_for_ip_addresses', targeting_change(:ip_address, added: ips)) do
    # ip_address is stored as a flat Array of strings; bypass the generic
    # enable_targeting path whose "array type" branch stringifies the
    # incoming array into a single '["x.y.z"]' entry.
    @targeting[:ip_address] ||= []
    ips.each do |str|
      @targeting[:ip_address] << str unless @targeting[:ip_address].include?(str)
    end
    save_targeting
  end
  true
end

#enable_for_role(role_name) ⇒ Object



288
289
290
291
292
293
# File 'lib/magick/feature.rb', line 288

def enable_for_role(role_name)
  record_change('enable_for_role', targeting_change(:role, added: role_name)) do
    enable_targeting(:role, role_name)
  end
  true
end

#enable_for_tag(tag_name) ⇒ Object



302
303
304
305
306
307
# File 'lib/magick/feature.rb', line 302

def enable_for_tag(tag_name)
  record_change('enable_for_tag', targeting_change(:tag, added: tag_name)) do
    enable_targeting(:tag, tag_name)
  end
  true
end

#enable_for_user(user_id) ⇒ Object



260
261
262
263
264
265
# File 'lib/magick/feature.rb', line 260

def enable_for_user(user_id)
  record_change('enable_for_user', targeting_change(:user, added: user_id)) do
    enable_targeting(:user, user_id)
  end
  true
end

#enable_percentage_of_requests(percentage) ⇒ Object



420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
# File 'lib/magick/feature.rb', line 420

def enable_percentage_of_requests(percentage)
  record_change('enable_percentage_of_requests', targeting_change(:percentage_requests, added: percentage.to_f)) do
    @targeting[:percentage_requests] = percentage.to_f
    save_targeting

    # Update registered feature instance if it exists
    Magick.features[name].instance_variable_set(:@targeting, @targeting.dup) if Magick.features.key?(name)

    # Rails 8+ event
    if defined?(Magick::Rails::Events) && Magick::Rails::Events.rails8?
      Magick::Rails::Events.targeting_added(name, targeting_type: :percentage_requests, targeting_value: percentage)
    end
  end

  true
end

#enable_percentage_of_users(percentage) ⇒ Object



396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
# File 'lib/magick/feature.rb', line 396

def enable_percentage_of_users(percentage)
  record_change('enable_percentage_of_users', targeting_change(:percentage_users, added: percentage.to_f)) do
    @targeting[:percentage_users] = percentage.to_f
    save_targeting

    # Update registered feature instance if it exists
    Magick.features[name].instance_variable_set(:@targeting, @targeting.dup) if Magick.features.key?(name)

    # Rails 8+ event
    if defined?(Magick::Rails::Events) && Magick::Rails::Events.rails8?
      Magick::Rails::Events.targeting_added(name, targeting_type: :percentage_users, targeting_value: percentage)
    end
  end

  true
end

#enabled?(context = {}) ⇒ Boolean

Returns:

  • (Boolean)


65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'lib/magick/feature.rb', line 65

def enabled?(context = {})
  refresh_from_source_if_stale

  # Check performance metrics dynamically (in case enabled after feature creation)
  # But cache the check result for performance
  perf_metrics = Magick.performance_metrics
  perf_metrics_enabled = !perf_metrics.nil?

  # Update cached flag if it changed
  @_perf_metrics_enabled = perf_metrics_enabled if @_perf_metrics_enabled != perf_metrics_enabled

  # Fast path: if performance metrics disabled, skip all overhead
  return check_enabled(context) unless perf_metrics_enabled

  # Performance metrics enabled: measure and record
  # Use inline timing to avoid function call overhead
  start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  result = check_enabled(context)
  duration = (Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time) * 1000 # milliseconds

  # Record metrics (fast path - minimal overhead)
  perf_metrics.record(name, 'enabled?', duration, success: true)

  # Rails 8+ events (only in development or when explicitly enabled)
  if @_rails_events_enabled
    if result
      Magick::Rails::Events.feature_enabled(name, context: context)
    else
      Magick::Rails::Events.feature_disabled(name, context: context)
    end
  end

  # Warn if deprecated (only if enabled)
  if status == :deprecated && result && !context[:allow_deprecated] && Magick.warn_on_deprecated
    warn "DEPRECATED: Feature '#{name}' is deprecated and will be removed."
    Magick::Rails::Events.deprecated_warning(name) if @_rails_events_enabled
  end

  result
rescue StandardError => e
  # Record error metrics if enabled
  if perf_metrics_enabled && perf_metrics
    duration = defined?(start_time) && start_time ? (Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time) * 1000 : 0.0
    perf_metrics.record(name, 'enabled?', duration, success: false)
  end
  # Return false on any error (fail-safe)
  warn "Magick: Error checking feature '#{Magick::LogSafe.sanitize(name)}': #{Magick::LogSafe.sanitize(e.message)}" if defined?(::Rails) && ::Rails.env.development?
  false
end

#enabled_for?(object, **additional_context) ⇒ Boolean

Returns:

  • (Boolean)


191
192
193
194
195
196
197
# File 'lib/magick/feature.rb', line 191

def enabled_for?(object, **additional_context)
  # Extract context from object
  context = extract_context_from_object(object)
  # Merge with any additional context provided
  context.merge!(additional_context)
  enabled?(context)
end

#exclude_group(group_name) ⇒ Object



346
347
348
349
350
351
# File 'lib/magick/feature.rb', line 346

def exclude_group(group_name)
  record_change('exclude_group', targeting_change(:excluded_groups, added: group_name)) do
    enable_targeting(:excluded_groups, group_name)
  end
  true
end

#exclude_ip_addresses(ip_addresses) ⇒ Object



374
375
376
377
378
379
380
381
382
383
384
385
386
387
# File 'lib/magick/feature.rb', line 374

def exclude_ip_addresses(ip_addresses)
  ips = Array(ip_addresses).map(&:to_s)
  record_change('exclude_ip_addresses', targeting_change(:excluded_ip_addresses, added: ips)) do
    # excluded_ip_addresses is stored as a flat Array of strings; bypass the
    # generic enable_targeting path whose "array type" branch stringifies the
    # incoming array into a single element.
    @targeting[:excluded_ip_addresses] ||= []
    ips.each do |str|
      @targeting[:excluded_ip_addresses] << str unless @targeting[:excluded_ip_addresses].include?(str)
    end
    save_targeting
  end
  true
end

#exclude_role(role_name) ⇒ Object



360
361
362
363
364
365
# File 'lib/magick/feature.rb', line 360

def exclude_role(role_name)
  record_change('exclude_role', targeting_change(:excluded_roles, added: role_name)) do
    enable_targeting(:excluded_roles, role_name)
  end
  true
end

#exclude_tag(tag_name) ⇒ Object



332
333
334
335
336
337
# File 'lib/magick/feature.rb', line 332

def exclude_tag(tag_name)
  record_change('exclude_tag', targeting_change(:excluded_tags, added: tag_name)) do
    enable_targeting(:excluded_tags, tag_name)
  end
  true
end

#exclude_user(user_id) ⇒ Object

--- Exclusion methods ---



318
319
320
321
322
323
# File 'lib/magick/feature.rb', line 318

def exclude_user(user_id)
  record_change('exclude_user', targeting_change(:excluded_users, added: user_id)) do
    enable_targeting(:excluded_users, user_id)
  end
  true
end

#get_value(context = {}) ⇒ Object



207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
# File 'lib/magick/feature.rb', line 207

def get_value(context = {})
  refresh_from_source_if_stale

  # Fast path: check targeting rules first (only if targeting exists)
  unless @_targeting_empty
    targeting_result = check_targeting(context)
    # If targeting matches (returns truthy), return the stored value
    # If targeting doesn't match (returns nil), continue to return default value
    unless targeting_result.nil?
      # Targeting matches - return stored value (or load it if not initialized)
      return @stored_value if @stored_value_initialized

      # Load from adapter
      loaded_value = load_value_from_adapter
      if loaded_value.nil?
        # Value not found in adapter, use default and cache it
        @stored_value = default_value
        @stored_value_initialized = true
        return default_value
      else
        # Value found in adapter, use it and mark as initialized
        @stored_value = loaded_value
        @stored_value_initialized = true
        return loaded_value
      end

    end
    # Targeting doesn't match - return default value
    return default_value
  end

  # Fast path: use cached value if initialized (avoid adapter calls)
  return @stored_value if @stored_value_initialized

  # Load from adapter if instance variable hasn't been initialized
  loaded_value = load_value_from_adapter
  if loaded_value.nil?
    # Value not found in adapter, use default and cache it
    @stored_value = default_value
    @stored_value_initialized = true
    default_value
  else
    # Value found in adapter, use it and mark as initialized
    @stored_value = loaded_value
    @stored_value_initialized = true
    loaded_value
  end
rescue StandardError => e
  # Return default value on error (fail-safe)
  warn "Magick: Error in get_value for '#{Magick::LogSafe.sanitize(name)}': #{Magick::LogSafe.sanitize(e.message)}" if defined?(::Rails) && ::Rails.env.development?
  default_value
end

#get_variant(context = {}) ⇒ Object



577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
# File 'lib/magick/feature.rb', line 577

def get_variant(context = {})
  refresh_from_source_if_stale
  return nil unless targeting[:variants]

  variants = targeting[:variants]
  return nil if variants.empty?
  return variants.first[:name] if variants.length == 1

  total_weight = variants.sum { |v| v[:weight] || 0 }
  return variants.first[:name] if total_weight.zero?

  # Deterministic assignment: use MD5 hash of feature_name + user_id
  # This ensures the same user always gets the same variant
  user_id = context[:user_id] || context[:user]&.respond_to?(:id) && context[:user].id
  if user_id
    hash = Digest::MD5.hexdigest("#{name}:variant:#{user_id}")
    bucket = hash[0..7].to_i(16) % total_weight
  else
    # No user context — fall back to random (e.g., anonymous requests)
    bucket = rand(total_weight)
  end

  current = 0
  variants.each do |variant|
    current += (variant[:weight] || 0)
    return variant[:name] if bucket < current
  end

  variants.last[:name]
end

#get_variant_value(context = {}) ⇒ Object



608
609
610
611
612
613
614
# File 'lib/magick/feature.rb', line 608

def get_variant_value(context = {})
  variant_name = get_variant(context)
  return nil unless variant_name

  variant = targeting[:variants]&.find { |v| v[:name] == variant_name }
  variant&.dig(:value)
end

#reload ⇒ Object

Reload feature state from adapter (useful when feature is changed externally)



754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
# File 'lib/magick/feature.rb', line 754

def reload
  load_from_adapter
  # Update targeting empty cache
  @_targeting_empty = @targeting.empty?
  # Update performance metrics flag (in case it was enabled after feature creation)
  @_perf_metrics_enabled = !Magick.performance_metrics.nil?
  # Update registered feature instance if it exists
  if Magick.features.key?(name)
    registered = Magick.features[name]
    registered.instance_variable_set(:@stored_value, @stored_value)
    registered.instance_variable_set(:@stored_value_initialized, @stored_value_initialized)
    registered.instance_variable_set(:@status, @status)
    registered.instance_variable_set(:@description, @description)
    registered.instance_variable_set(:@display_name, @display_name)
    registered.instance_variable_set(:@group, @group)
    registered.instance_variable_set(:@dependencies, dependencies.dup)
    registered.instance_variable_set(:@targeting, @targeting.dup)
    registered.instance_variable_set(:@_targeting_empty, @_targeting_empty)
    registered.instance_variable_set(:@_perf_metrics_enabled, @_perf_metrics_enabled)
  end
  true
end

#reload_from_source! ⇒ Object

Reload feature state from the shared, authoritative backend (ActiveRecord/ Redis), bypassing this process's local in-process memory cache. Used by the Admin UI so a toggle performed on another process/container is reflected immediately, without waiting for Pub/Sub cache invalidation to arrive.



748
749
750
751
# File 'lib/magick/feature.rb', line 748

def reload_from_source!
  adapter_registry.authoritative_get_all_data(name) if adapter_registry.respond_to?(:authoritative_get_all_data)
  reload
end

#remove_dependency(dependency_name, user_id: nil) ⇒ Object



543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
# File 'lib/magick/feature.rb', line 543

def remove_dependency(dependency_name, user_id: nil)
  dep = dependency_name.to_s
  return true unless dependencies.include?(dep)

  record_change('remove_dependency', { dependency: { removed: dep } }, user_id: user_id) do
    write_dependencies(dependencies - [dep])

    # Rails 8+ event
    if defined?(Magick::Rails::Events) && Magick::Rails::Events.rails8?
      Magick::Rails::Events.dependency_removed(name, dep)
    end
  end

  true
end

#remove_group_exclusion(group_name) ⇒ Object



353
354
355
356
357
358
# File 'lib/magick/feature.rb', line 353

def remove_group_exclusion(group_name)
  record_change('remove_group_exclusion', targeting_change(:excluded_groups, removed: group_name)) do
    disable_targeting(:excluded_groups, group_name)
  end
  true
end

#remove_ip_exclusion ⇒ Object



389
390
391
392
393
394
# File 'lib/magick/feature.rb', line 389

def remove_ip_exclusion
  record_change('remove_ip_exclusion', targeting_change(:excluded_ip_addresses)) do
    disable_targeting(:excluded_ip_addresses)
  end
  true
end

#remove_role_exclusion(role_name) ⇒ Object



367
368
369
370
371
372
# File 'lib/magick/feature.rb', line 367

def remove_role_exclusion(role_name)
  record_change('remove_role_exclusion', targeting_change(:excluded_roles, removed: role_name)) do
    disable_targeting(:excluded_roles, role_name)
  end
  true
end

#remove_tag_exclusion(tag_name) ⇒ Object



339
340
341
342
343
344
# File 'lib/magick/feature.rb', line 339

def remove_tag_exclusion(tag_name)
  record_change('remove_tag_exclusion', targeting_change(:excluded_tags, removed: tag_name)) do
    disable_targeting(:excluded_tags, tag_name)
  end
  true
end

#remove_user_exclusion(user_id) ⇒ Object



325
326
327
328
329
330
# File 'lib/magick/feature.rb', line 325

def remove_user_exclusion(user_id)
  record_change('remove_user_exclusion', targeting_change(:excluded_users, removed: user_id)) do
    disable_targeting(:excluded_users, user_id)
  end
  true
end

#replace_dependencies(list, user_id: nil) ⇒ Object

Wholesale prerequisite write: the list IS the new set, [] clears it. Used by import and by callers that manage the whole set at once.



561
562
563
564
565
566
567
568
569
570
571
# File 'lib/magick/feature.rb', line 561

def replace_dependencies(list, user_id: nil)
  new_list = normalize_dependency_list(list)
  return true if new_list == dependencies

  changes = { dependencies: { from: dependencies.dup, to: new_list.dup } }
  record_change('replace_dependencies', changes, user_id: user_id) do
    write_dependencies(new_list)
  end

  true
end

#replace_targeting(payload = nil, user_id: nil, **inline_rules) ⇒ Object

Wholesale, declarative targeting write: the payload IS the new targeting state. Keys absent from it are removed; {} clears all targeting. Accepts wire input leniently (string/symbol keys, plural aliases, scalars for lists, numeric strings) but validates strictly — unknown keys or invalid values raise InvalidTargetingError before any state is touched. The internal :variants entry is not part of the wire payload and survives the replace untouched. Accepts the payload as a positional hash or inline keywords (replace_targeting(user: [3])) — Ruby routes a braceless hash to keywords, so both spellings must land in the same place. Passing nothing raises (via normalize): clearing requires an explicit {}.

Raises:

  • (ArgumentError)


827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
# File 'lib/magick/feature.rb', line 827

def replace_targeting(payload = nil, user_id: nil, **inline_rules)
  raise ArgumentError, 'pass targeting either as a hash or inline, not both' if payload && inline_rules.any?

  normalized = TargetingPayload.normalize(payload || (inline_rules unless inline_rules.empty?))
  normalized[:variants] = targeting[:variants] if targeting[:variants]

  changes = {
    targeting: {
      from: TargetingPayload.serialize(targeting),
      to: TargetingPayload.serialize(normalized)
    }
  }
  record_change('replace_targeting', changes, user_id: user_id) do
    @targeting = normalized
    persist_targeting

    if defined?(Magick::Rails::Events) && Magick::Rails::Events.rails8?
      Magick::Rails::Events.feature_changed(name, changes: changes, user_id: user_id)
    end
  end
  true
end

#restore_snapshot!(data) ⇒ Object

Restore full feature state from a version snapshot (used by Versioning#rollback). Replaces value (including false/empty), status, group, the entire targeting hash and dependencies wholesale.



894
895
896
897
898
899
900
901
902
903
904
905
906
# File 'lib/magick/feature.rb', line 894

def restore_snapshot!(data)
  set_status(data[:status]) if data[:status]
  set_group(data[:group]) if data.key?(:group)

  value = data[:value]
  set_value(cast_value(value)) unless value.nil?

  @targeting = normalize_targeting(data[:targeting])
  save_targeting

  write_dependencies(normalize_dependency_list(data[:dependencies]))
  true
end

#save_targeting ⇒ Object



882
883
884
885
886
887
888
889
# File 'lib/magick/feature.rb', line 882

def save_targeting
  # Records only when called directly (e.g. Admin UI clearing variants);
  # when reached through a wrapping mutator the guard is active and this
  # just persists.
  record_change('update_targeting', { targeting: targeting.dup }) do
    persist_targeting
  end
end

#set_group(group_name) ⇒ Object



713
714
715
716
717
718
719
720
721
722
723
724
725
726
# File 'lib/magick/feature.rb', line 713

def set_group(group_name)
  new_group = group_name.nil? || group_name.to_s.strip.empty? ? nil : group_name.to_s.strip

  record_change('set_group', { group: { from: @group, to: new_group } }) do
    @group = new_group
    # Clear group from adapter by setting to nil (adapters handle this)
    adapter_registry.set(name, 'group', @group)

    # Update registered feature instance if it exists
    Magick.features[name].instance_variable_set(:@group, @group) if Magick.features.key?(name)
  end

  true
end

#set_status(new_status) ⇒ Object



703
704
705
706
707
708
709
710
711
# File 'lib/magick/feature.rb', line 703

def set_status(new_status)
  raise InvalidFeatureValueError, "Invalid status: #{new_status}" unless VALID_STATUSES.include?(new_status.to_sym)

  record_change('set_status', { status: { from: @status, to: new_status.to_sym } }) do
    @status = new_status.to_sym
    adapter_registry.set(name, 'status', status)
  end
  true
end

#set_value(value, user_id: nil) ⇒ Object



616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
# File 'lib/magick/feature.rb', line 616

def set_value(value, user_id: nil)
  old_value = @stored_value
  validate_value!(value)

  changes = { value: { from: old_value, to: value } }

  record_change('set_value', changes, user_id: user_id) do
    # Bulk write all metadata in a single adapter call instead of 7 separate calls
    data = { 'value' => value, 'type' => type, 'status' => status, 'default_value' => default_value }
    data['description'] = description if description
    data['display_name'] = display_name if display_name
    data['group'] = group if group
    adapter_registry.set_all_data(name, data)

    @stored_value = value
    @stored_value_initialized = true

    # Update registered feature instance if it exists
    if Magick.features.key?(name)
      registered = Magick.features[name]
      registered.instance_variable_set(:@stored_value, value)
      registered.instance_variable_set(:@stored_value_initialized, true)
      registered.instance_variable_set(:@targeting, @targeting.dup) if @targeting
    end

    if defined?(Magick::Rails::Events) && Magick::Rails::Events.rails8?
      Magick::Rails::Events.feature_changed(name, changes: changes, user_id: user_id)
    end
  end

  true
end

#set_variants(variants) ⇒ Object



505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
# File 'lib/magick/feature.rb', line 505

def set_variants(variants)
  variants_array = Array(variants).map do |v|
    v.is_a?(FeatureVariant) ? v : FeatureVariant.new(v[:name], v[:value], weight: v[:weight] || 0)
  end
  payload = variants_array.map(&:to_h)

  record_change('set_variants', { variants: payload }) do
    enable_targeting(:variants, payload)

    # Rails 8+ event
    if defined?(Magick::Rails::Events) && Magick::Rails::Events.rails8?
      Magick::Rails::Events.variant_set(name, variants: variants_array)
    end
  end

  true
end

#to_h ⇒ Object



777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
# File 'lib/magick/feature.rb', line 777

def to_h
  {
    name: name,
    display_name: display_name,
    group: group,
    type: type,
    status: status,
    value: stored_value,
    default_value: default_value,
    description: description,
    targeting: targeting,
    dependencies: (@dependencies || []).dup,
    variants: variants_for_export
  }
end

#value(context = {}) ⇒ Object



203
204
205
# File 'lib/magick/feature.rb', line 203

def value(context = {})
  get_value(context)
end

#variants_for_export ⇒ Object

The canonical list of this feature's variants, as plain hashes. Variants are stored inside @targeting under the internal :variants key (see #set_variants), so that is the only place to read them from. Tolerates the string keys an adapter round-trip can hand back.



854
855
856
857
858
859
860
861
862
# File 'lib/magick/feature.rb', line 854

def variants_for_export
  Array(targeting[:variants]).filter_map do |variant|
    next variant.to_h if variant.is_a?(FeatureVariant)
    next unless variant.is_a?(Hash)

    v = variant.transform_keys(&:to_sym)
    { name: v[:name], value: v[:value], weight: v[:weight] }
  end
end