zenmanage 1.0.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.
Files changed (42) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +27 -0
  3. data/CODE_OF_CONDUCT.md +84 -0
  4. data/CONTRIBUTING.md +22 -0
  5. data/LICENSE +21 -0
  6. data/README.md +382 -0
  7. data/SECURITY.md +9 -0
  8. data/examples/caching.rb +58 -0
  9. data/examples/context_based_flags.rb +45 -0
  10. data/examples/defaults.rb +62 -0
  11. data/examples/percentage_rollouts.rb +37 -0
  12. data/examples/rails_integration.rb +74 -0
  13. data/examples/simple_flags.rb +41 -0
  14. data/lib/generators/zenmanage/install/install_generator.rb +18 -0
  15. data/lib/generators/zenmanage/install/templates/initializer.rb +23 -0
  16. data/lib/zenmanage/api_client.rb +264 -0
  17. data/lib/zenmanage/attribute.rb +55 -0
  18. data/lib/zenmanage/cache/base.rb +46 -0
  19. data/lib/zenmanage/cache/filesystem_cache.rb +88 -0
  20. data/lib/zenmanage/cache/memory_cache.rb +63 -0
  21. data/lib/zenmanage/cache/null_cache.rb +22 -0
  22. data/lib/zenmanage/config_builder.rb +215 -0
  23. data/lib/zenmanage/configuration.rb +118 -0
  24. data/lib/zenmanage/context.rb +125 -0
  25. data/lib/zenmanage/defaults_collection.rb +68 -0
  26. data/lib/zenmanage/errors.rb +21 -0
  27. data/lib/zenmanage/flag.rb +200 -0
  28. data/lib/zenmanage/flag_manager.rb +197 -0
  29. data/lib/zenmanage/hash_access.rb +72 -0
  30. data/lib/zenmanage/rails/controller_helpers.rb +85 -0
  31. data/lib/zenmanage/rails/middleware.rb +34 -0
  32. data/lib/zenmanage/rails/railtie.rb +60 -0
  33. data/lib/zenmanage/rollout.rb +45 -0
  34. data/lib/zenmanage/rollout_bucket.rb +40 -0
  35. data/lib/zenmanage/rule.rb +142 -0
  36. data/lib/zenmanage/rule_engine.rb +156 -0
  37. data/lib/zenmanage/rule_store.rb +164 -0
  38. data/lib/zenmanage/target.rb +37 -0
  39. data/lib/zenmanage/version.rb +6 -0
  40. data/lib/zenmanage/webhook.rb +89 -0
  41. data/lib/zenmanage.rb +183 -0
  42. metadata +216 -0
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ # examples/defaults.rb
4
+ #
5
+ # Shows how to configure default flag values used when a flag is not found,
6
+ # both as inline defaults and via DefaultsCollection.
7
+ #
8
+ # Usage:
9
+ # ZENMANAGE_ENVIRONMENT_TOKEN=srv_... ruby examples/defaults.rb
10
+
11
+ require_relative "../lib/zenmanage"
12
+
13
+ config = Zenmanage::ConfigBuilder.create
14
+ .with_environment_token(ENV.fetch("ZENMANAGE_ENVIRONMENT_TOKEN", "srv_demo_token"))
15
+ .with_cache_backend("null")
16
+ .build
17
+
18
+ client = Zenmanage::Client.new(config)
19
+
20
+ # ── Inline defaults ───────────────────────────────────────────────────────────
21
+ puts "=== Inline Defaults ==="
22
+
23
+ # Boolean
24
+ flag = client.flags.single("unknown-bool-flag", false)
25
+ puts "unknown-bool-flag → #{flag.as_bool}"
26
+
27
+ # String
28
+ flag = client.flags.single("unknown-string-flag", "control")
29
+ puts "unknown-string-flag → #{flag.as_string}"
30
+
31
+ # Number
32
+ flag = client.flags.single("unknown-number-flag", 5)
33
+ puts "unknown-number-flag → #{flag.as_number}"
34
+
35
+ # JSON (Hash and Array defaults are both typed as json, not stringified)
36
+ flag = client.flags.single("unknown-json-flag", { "mode" => "light" })
37
+ puts "unknown-json-flag → #{flag.as_json}"
38
+
39
+ # ── DefaultsCollection ────────────────────────────────────────────────────────
40
+ puts "\n=== DefaultsCollection ==="
41
+
42
+ defaults = Zenmanage::DefaultsCollection.from_hash(
43
+ "feature-a" => true,
44
+ "feature-b" => "variant-b",
45
+ "feature-c" => 42,
46
+ "feature-d" => { "mode" => "light" },
47
+ )
48
+
49
+ flags = client.flags.with_defaults(defaults)
50
+
51
+ puts "feature-a → #{flags.single("feature-a").as_bool}"
52
+ puts "feature-b → #{flags.single("feature-b").as_string}"
53
+ puts "feature-c → #{flags.single("feature-c").as_number}"
54
+ puts "feature-d → #{flags.single("feature-d").as_json}"
55
+
56
+ # ── Raises when no default available ─────────────────────────────────────────
57
+ puts "\n=== Error Handling ==="
58
+ begin
59
+ client.flags.single("completely-unknown")
60
+ rescue Zenmanage::EvaluationError => e
61
+ puts "EvaluationError raised as expected: #{e.message}"
62
+ end
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ # examples/percentage_rollouts.rb
4
+ #
5
+ # Shows how percentage-based rollouts work. Users are bucketed deterministically
6
+ # using CRC32 so the same user always gets the same experience.
7
+ #
8
+ # Usage:
9
+ # ZENMANAGE_ENVIRONMENT_TOKEN=srv_... ruby examples/percentage_rollouts.rb
10
+
11
+ require_relative "../lib/zenmanage"
12
+
13
+ # Demonstrate the bucketing algorithm directly ────────────────────────────────
14
+ salt = "my-feature-salt"
15
+
16
+ puts "Bucketing 10 users into a 50% rollout:"
17
+ 10.times do |i|
18
+ id = "user-#{i}"
19
+ bucket = Zenmanage::RolloutBucket.in_bucket?(salt, id, 50)
20
+ puts " #{id.ljust(12)} → #{bucket ? "IN rollout" : "NOT in rollout"}"
21
+ end
22
+
23
+ # Demonstrate with a live client ──────────────────────────────────────────────
24
+ config = Zenmanage::ConfigBuilder.create
25
+ .with_environment_token(ENV.fetch("ZENMANAGE_ENVIRONMENT_TOKEN", "srv_demo_token"))
26
+ .with_cache_backend("null")
27
+ .build
28
+
29
+ client = Zenmanage::Client.new(config)
30
+
31
+ puts "\nLive flag evaluation across users:"
32
+ %w[user-0 user-1 user-2 user-3].each do |uid|
33
+ ctx = Zenmanage::Context.single("user", uid)
34
+ flags = client.flags.with_context(ctx)
35
+ flag = flags.single("rollout-feature", false)
36
+ puts " #{uid.ljust(10)} → #{flag.enabled? ? "ENABLED" : "disabled"}"
37
+ end
@@ -0,0 +1,74 @@
1
+ # frozen_string_literal: true
2
+
3
+ # examples/rails_integration.rb
4
+ #
5
+ # Demonstrates how to integrate the Zenmanage SDK into a Rails application.
6
+ # In a real app, the following code would be spread across:
7
+ # - config/initializers/zenmanage.rb
8
+ # - app/controllers/application_controller.rb
9
+ # - any view or controller file
10
+
11
+ # ── config/initializers/zenmanage.rb ─────────────────────────────────────────
12
+ # With ZENMANAGE_ENVIRONMENT_TOKEN set, no code is needed: the Railtie configures
13
+ # the gem. To keep settings in your app, run `bin/rails generate zenmanage:install`
14
+ # or write:
15
+ #
16
+ # Zenmanage.configure do |c|
17
+ # c.environment_token = Rails.application.credentials.zenmanage_environment_token
18
+ # c.cache_ttl = 900 # 15 minutes
19
+ # end
20
+
21
+ # ── config/routes.rb ─────────────────────────────────────────────────────────
22
+ # Optional: apply changes as soon as they're published. Set ZENMANAGE_WEBHOOK_SECRET.
23
+ #
24
+ # mount Zenmanage::Webhook::Endpoint.new => "/zenmanage/webhook"
25
+
26
+ # ── app/controllers/products_controller.rb ───────────────────────────────────
27
+ # `zen_flags` and `feature_enabled?` are available in every controller and view.
28
+ # With a `current_user`, flags are evaluated for that user.
29
+ #
30
+ # class ProductsController < ApplicationController
31
+ # def show
32
+ # # Boolean check
33
+ # @new_layout = feature_enabled?("new-product-layout")
34
+ #
35
+ # # String variant (A/B test)
36
+ # @checkout_variant = zen_flags.single("checkout-flow", "default").as_string
37
+ #
38
+ # # Number flag
39
+ # @max_recommendations = zen_flags.single("max-recommendations", 5).as_number
40
+ # end
41
+ # end
42
+
43
+ # ── app/controllers/application_controller.rb ────────────────────────────────
44
+ # Optional: choose what's sent as the context.
45
+ #
46
+ # class ApplicationController < ActionController::Base
47
+ # private
48
+ #
49
+ # def zenmanage_context
50
+ # return unless current_user
51
+ #
52
+ # Zenmanage::Context.single("user", current_user.id.to_s)
53
+ # end
54
+ # end
55
+
56
+ # ── app/views/products/show.html.erb ─────────────────────────────────────────
57
+ #
58
+ # <% if feature_enabled?("promotional-banner") %>
59
+ # <%= render "shared/promo_banner" %>
60
+ # <% end %>
61
+
62
+ # ── Jobs, mailers and models ─────────────────────────────────────────────────
63
+ #
64
+ # Zenmanage.flags.single("new-export", false).enabled?
65
+
66
+ # ── Sinatra or plain Rack ────────────────────────────────────────────────────
67
+ #
68
+ # client = Zenmanage::Client.new(config)
69
+ # use Zenmanage::Rails::Middleware, client
70
+ #
71
+ # # In a request:
72
+ # flags = env["zenmanage.flags"]
73
+
74
+ puts "See inline comments for Rails integration examples."
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ # examples/simple_flags.rb
4
+ #
5
+ # Demonstrates basic boolean, string, number, and json flag evaluation without context.
6
+ #
7
+ # Usage:
8
+ # ZENMANAGE_ENVIRONMENT_TOKEN=srv_... ruby examples/simple_flags.rb
9
+
10
+ require_relative "../lib/zenmanage"
11
+
12
+ config = Zenmanage::ConfigBuilder.create
13
+ .with_environment_token(ENV.fetch("ZENMANAGE_ENVIRONMENT_TOKEN", "srv_demo_token"))
14
+ .with_cache_backend("null") # disable caching for demo
15
+ .build
16
+
17
+ client = Zenmanage::Client.new(config)
18
+ flags = client.flags
19
+
20
+ # ── Boolean flag ──────────────────────────────────────────────────────────────
21
+ flag = flags.single("dark-mode", false)
22
+ puts "dark-mode enabled? → #{flag.enabled?}"
23
+ puts "dark-mode as_bool → #{flag.as_bool}"
24
+
25
+ # ── String variant flag ───────────────────────────────────────────────────────
26
+ layout = flags.single("checkout-layout", "control")
27
+ puts "checkout-layout → #{layout.as_string}"
28
+
29
+ # ── Number flag ───────────────────────────────────────────────────────────────
30
+ max_items = flags.single("max-items", 10)
31
+ puts "max-items → #{max_items.as_number}"
32
+
33
+ # ── JSON flag ─────────────────────────────────────────────────────────────────
34
+ theme_config = flags.single("theme-config", { "mode" => "light" })
35
+ puts "theme-config → #{theme_config.as_json}"
36
+
37
+ # ── List all flags ────────────────────────────────────────────────────────────
38
+ puts "\nAll flags:"
39
+ flags.all.each do |f|
40
+ puts " #{f.key} (#{f.type}): #{f.value}"
41
+ end
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails/generators"
4
+
5
+ module Zenmanage
6
+ module Generators
7
+ # `bin/rails generate zenmanage:install`
8
+ class InstallGenerator < ::Rails::Generators::Base
9
+ source_root File.expand_path("templates", __dir__)
10
+
11
+ desc "Creates config/initializers/zenmanage.rb"
12
+
13
+ def create_initializer
14
+ template "initializer.rb", "config/initializers/zenmanage.rb"
15
+ end
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Settings left out here come from the ZENMANAGE_* environment variables, so with
4
+ # ZENMANAGE_ENVIRONMENT_TOKEN set this file is optional.
5
+ Zenmanage.configure do |config|
6
+ # Your environment's server key (it starts with srv_). Keep it out of source control.
7
+ config.environment_token = ENV.fetch("ZENMANAGE_ENVIRONMENT_TOKEN", nil) ||
8
+ Rails.application.credentials.zenmanage_environment_token
9
+
10
+ # How long, in seconds, flag rules are used before they are fetched again.
11
+ # config.cache_ttl = 3600
12
+
13
+ # "memory" (default), "filesystem" (shared by processes on one machine) or "null".
14
+ # config.cache_backend = "filesystem"
15
+ # config.cache_directory = Rails.root.join("tmp/cache/zenmanage").to_s
16
+
17
+ # config.enable_usage_reporting = true
18
+ end
19
+
20
+ # To apply changes as soon as they are published, add a webhook for this environment in
21
+ # Zenmanage, set ZENMANAGE_WEBHOOK_SECRET to its signing secret, and add to config/routes.rb:
22
+ #
23
+ # mount Zenmanage::Webhook::Endpoint.new => "/zenmanage/webhook"
@@ -0,0 +1,264 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "uri"
5
+ require "json"
6
+ require "openssl"
7
+
8
+ module Zenmanage
9
+ # HTTP client that communicates with the Zenmanage API.
10
+ #
11
+ # The client fetches flag rules in two steps:
12
+ # 1. Calls `/v1/flag-json` to obtain a CDN URL.
13
+ # 2. Fetches the rules JSON from that CDN URL.
14
+ #
15
+ # Both steps are retried up to three times with exponential back-off.
16
+ # Usage reporting fires-and-forgets and never raises on failure.
17
+ #
18
+ # Every request identifies the SDK in `X-ZEN-CLIENT-AGENT` as
19
+ # `zenmanage-ruby/<version>`, or `zenmanage-rails/<version>` when Rails is loaded.
20
+ class ApiClient
21
+ DEFAULT_API_ENDPOINT = "https://api.zenmanage.com"
22
+ RULES_PATH = "/v1/flag-json"
23
+ MAX_RETRIES = 3
24
+ RETRY_DELAY_SECONDS = 0.1
25
+ RUBY_CLIENT_AGENT = "zenmanage-ruby"
26
+ RAILS_CLIENT_AGENT = "zenmanage-rails"
27
+ HTTP_TIMEOUT = 10
28
+
29
+ # Errors that indicate a transient network/connection failure and are
30
+ # worth retrying. Deliberately narrower than `StandardError` so that an
31
+ # unexpected error unrelated to connectivity (e.g. a bug, or a test
32
+ # double misbehaving) surfaces as a single logged failure instead of
33
+ # being silently retried into a duplicate request.
34
+ RETRYABLE_USAGE_ERRORS = [
35
+ Net::OpenTimeout,
36
+ Net::ReadTimeout,
37
+ Errno::ECONNRESET,
38
+ Errno::ECONNREFUSED,
39
+ Errno::ETIMEDOUT,
40
+ Errno::EHOSTUNREACH,
41
+ SocketError,
42
+ EOFError,
43
+ IOError,
44
+ OpenSSL::SSL::SSLError,
45
+ ].freeze
46
+
47
+ # @param environment_token [String]
48
+ # @param api_endpoint [String]
49
+ # @param logger [#debug, #info, #warn, #error]
50
+ # @param enable_usage_reporting [Boolean]
51
+ # @param sdk_version [String, nil]
52
+ # @param client_agent [String, nil]
53
+ def initialize(
54
+ environment_token:,
55
+ api_endpoint: DEFAULT_API_ENDPOINT,
56
+ logger: NullLogger.new,
57
+ enable_usage_reporting: true,
58
+ sdk_version: nil,
59
+ client_agent: nil
60
+ )
61
+ @environment_token = environment_token
62
+ @api_endpoint = api_endpoint.chomp("/")
63
+ @logger = logger
64
+ @enable_usage_reporting = enable_usage_reporting
65
+ @sdk_version = resolve_sdk_version(sdk_version)
66
+ @client_agent = resolve_client_agent(client_agent)
67
+ end
68
+
69
+ # Fetch all flag rules from the API.
70
+ #
71
+ # @return [Hash] parsed rules response (`{ "version" => ..., "flags" => [...] }`)
72
+ # @raise [FetchRulesError] after all retries are exhausted
73
+ # @raise [InvalidRulesError] on malformed responses
74
+ def get_rules
75
+ last_error = nil
76
+
77
+ MAX_RETRIES.times do |attempt|
78
+ if attempt.positive?
79
+ delay = RETRY_DELAY_SECONDS * (2**(attempt - 1))
80
+ @logger.warn("Failed to fetch rules, retrying (attempt #{attempt + 1}/#{MAX_RETRIES}, delay #{delay}s)")
81
+ sleep(delay)
82
+ end
83
+
84
+ cdn_url = fetch_cdn_url
85
+ @logger.debug("Fetching rules from CDN: #{cdn_url}")
86
+
87
+ body = http_get(cdn_url, headers: cdn_headers)
88
+ data = JSON.parse(body)
89
+
90
+ unless data.is_a?(Hash) && data.key?("version") && data["flags"].is_a?(Array)
91
+ raise InvalidRulesError, "Invalid rules response format"
92
+ end
93
+
94
+ @logger.info("Successfully fetched rules (#{data["flags"].length} flags)")
95
+ return data
96
+ rescue InvalidRulesError
97
+ raise
98
+ rescue StandardError => e
99
+ last_error = e
100
+ @logger.warn("Error fetching rules (attempt #{attempt + 1}): #{e.message}")
101
+ end
102
+
103
+ raise FetchRulesError, "Failed to fetch rules after #{MAX_RETRIES} attempts: #{last_error&.message}"
104
+ end
105
+
106
+ # Report flag usage to the API (fire-and-forget, never raises).
107
+ #
108
+ # @param flag_key [String]
109
+ # @param context [Context, nil]
110
+ # @param default_value [Boolean, String, Numeric, Hash, Array, nil] fallback value the caller used, if any
111
+ # @return [Thread, nil] the background thread doing the reporting, or nil
112
+ # when usage reporting is disabled. Callers can `join` it to wait
113
+ # deterministically for the report to finish (e.g. in tests); its `value` is
114
+ # the API's response, or nil if the request couldn't be sent.
115
+ def report_usage(flag_key, context = nil, default_value = nil)
116
+ unless @enable_usage_reporting
117
+ @logger.debug("Usage reporting disabled, skipping for flag: #{flag_key}")
118
+ return
119
+ end
120
+
121
+ Thread.new { send_usage(flag_key, context, default_value) }
122
+ end
123
+
124
+ private
125
+
126
+ # @return [Net::HTTPResponse, nil]
127
+ def send_usage(flag_key, context, default_value)
128
+ attempt = 0
129
+ begin
130
+ attempt += 1
131
+ response = post_usage(flag_key, usage_headers(flag_key, context, default_value))
132
+ log_usage_response(flag_key, response)
133
+ response
134
+ rescue *RETRYABLE_USAGE_ERRORS => e
135
+ if attempt < MAX_RETRIES
136
+ sleep(RETRY_DELAY_SECONDS * (2**(attempt - 1)))
137
+ retry
138
+ end
139
+ @logger.warn("Failed to report usage for flag '#{flag_key}' after #{MAX_RETRIES} attempts: #{e.message}")
140
+ nil
141
+ rescue StandardError => e
142
+ @logger.warn("Failed to report usage for flag '#{flag_key}': #{e.message}")
143
+ nil
144
+ end
145
+ end
146
+
147
+ # A rejected report isn't retried: the API would reject it again.
148
+ def log_usage_response(flag_key, response)
149
+ if response.is_a?(Net::HTTPSuccess)
150
+ @logger.debug("Reported usage for flag: #{flag_key}")
151
+ else
152
+ @logger.warn("Usage report for flag '#{flag_key}' was rejected: HTTP #{response.code}")
153
+ end
154
+ end
155
+
156
+ # Headers for a usage report, including the context and the default value
157
+ # the caller fell back to when either applies.
158
+ #
159
+ # @return [Hash{String => String}]
160
+ def usage_headers(flag_key, context, default_value)
161
+ headers = base_headers
162
+ headers["X-ZEN-CONTEXT"] = header_json(context.to_h) if context && should_send_context?(context)
163
+ return headers if default_value.nil?
164
+
165
+ begin
166
+ headers["X-ZEN-DEFAULT-VALUE"] = header_json({ flag_key => default_value })
167
+ rescue StandardError => e
168
+ @logger.debug("Failed to encode usage default value: #{e.message}")
169
+ end
170
+
171
+ headers
172
+ end
173
+
174
+ # HTTP headers aren't a safe place for raw UTF-8, so non-ASCII text is escaped.
175
+ def header_json(value)
176
+ JSON.generate(value, ascii_only: true)
177
+ end
178
+
179
+ def post_usage(flag_key, headers)
180
+ uri = URI.parse("#{@api_endpoint}/v1/flags/#{URI.encode_www_form_component(flag_key)}/usage")
181
+ req = Net::HTTP::Post.new(uri)
182
+ headers.each { |k, v| req[k] = v }
183
+ build_http(uri).request(req)
184
+ end
185
+
186
+ # Fetch the CDN URL from the API metadata endpoint.
187
+ def fetch_cdn_url
188
+ url = "#{@api_endpoint}#{RULES_PATH}"
189
+ body = http_get(url, headers: base_headers)
190
+ meta = JSON.parse(body)
191
+
192
+ unless meta.is_a?(Hash) && meta.dig("data", "cdn") && meta.dig("data", "path")
193
+ raise InvalidRulesError, "API response missing cdn or path fields"
194
+ end
195
+
196
+ cdn = meta["data"]["cdn"]
197
+ path = meta["data"]["path"]
198
+
199
+ raise InvalidRulesError, "cdn or path fields are not strings" unless cdn.is_a?(String) && path.is_a?(String)
200
+ raise InvalidRulesError, "CDN URL must use HTTPS" unless cdn.start_with?("https://")
201
+
202
+ cdn + path
203
+ end
204
+
205
+ def http_get(url, headers: {})
206
+ uri = URI.parse(url)
207
+ http = build_http(uri)
208
+ req = Net::HTTP::Get.new(uri)
209
+ headers.each { |k, v| req[k] = v }
210
+ response = http.request(req)
211
+
212
+ raise FetchRulesError, "HTTP #{response.code} from #{url}" unless response.is_a?(Net::HTTPSuccess)
213
+
214
+ response.body
215
+ end
216
+
217
+ def build_http(uri)
218
+ http = Net::HTTP.new(uri.host, uri.port)
219
+ http.use_ssl = uri.scheme == "https"
220
+ http.open_timeout = HTTP_TIMEOUT
221
+ http.read_timeout = HTTP_TIMEOUT
222
+ http
223
+ end
224
+
225
+ def base_headers
226
+ {
227
+ "Accept" => "application/json",
228
+ "Content-Type" => "application/json",
229
+ "X-ZEN-API-KEY" => @environment_token,
230
+ "X-ZEN-CLIENT-AGENT" => client_agent_header,
231
+ }
232
+ end
233
+
234
+ # The CDN is told which SDK is asking, but never given the API key.
235
+ def cdn_headers
236
+ { "Accept" => "application/json", "X-ZEN-CLIENT-AGENT" => client_agent_header }
237
+ end
238
+
239
+ def client_agent_header
240
+ "#{@client_agent}/#{@sdk_version}"
241
+ end
242
+
243
+ def should_send_context?(context)
244
+ !(
245
+ context.type == "anonymous" &&
246
+ context.name.nil? &&
247
+ context.identifier.nil? &&
248
+ context.attributes.empty?
249
+ )
250
+ end
251
+
252
+ def resolve_client_agent(agent)
253
+ return agent if agent && !agent.empty?
254
+
255
+ # `::Rails`, not `Rails`: inside this module the bare name is Zenmanage::Rails,
256
+ # which is always defined.
257
+ defined?(::Rails::Railtie) ? RAILS_CLIENT_AGENT : RUBY_CLIENT_AGENT
258
+ end
259
+
260
+ def resolve_sdk_version(version)
261
+ version && !version.empty? ? version : VERSION
262
+ end
263
+ end
264
+ end
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Zenmanage
4
+ # Represents an attribute value in a context.
5
+ #
6
+ # @example Single value
7
+ # Zenmanage::Attribute.new("plan", ["pro"])
8
+ #
9
+ # @example Multiple values
10
+ # Zenmanage::Attribute.new("country", ["US", "CA"])
11
+ class Attribute
12
+ attr_reader :key, :values
13
+
14
+ # @param key [String] attribute name (e.g., "plan", "country")
15
+ # @param values [Array<String>] one or more attribute values
16
+ def initialize(key, values = [])
17
+ @key = key
18
+ @values = Array(values).map(&:to_s)
19
+ end
20
+
21
+ # @return [Boolean] whether this attribute has the given key and optional value
22
+ def matches?(attr_key, value = nil)
23
+ return false unless @key == attr_key
24
+ return true if value.nil?
25
+
26
+ @values.include?(value.to_s)
27
+ end
28
+
29
+ # @return [Hash]
30
+ def to_h
31
+ {
32
+ "key" => @key,
33
+ "values" => @values.map { |v| { "value" => v } },
34
+ }
35
+ end
36
+
37
+ # Rails serializers pass an options argument.
38
+ #
39
+ # @return [Hash]
40
+ def as_json(*)
41
+ to_h
42
+ end
43
+
44
+ # @return [String] e.g. `"plan:pro,enterprise"`
45
+ def to_s
46
+ "#{@key}:#{@values.join(",")}"
47
+ end
48
+
49
+ # @param data [Hash]
50
+ # @return [Attribute]
51
+ def self.from_hash(data)
52
+ new(HashAccess.value(data, :key, ""), HashAccess.attribute_values(data))
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Zenmanage
4
+ module Cache
5
+ # Abstract base class for cache backends.
6
+ #
7
+ # Subclass this to create a custom cache backend and pass it via
8
+ # {ConfigBuilder#with_cache_backend} or directly to {FlagManager}.
9
+ class Base
10
+ # Retrieve a cached value.
11
+ #
12
+ # @param key [String]
13
+ # @return [String, nil]
14
+ def get(key)
15
+ raise NotImplementedError, "#{self.class}#get not implemented"
16
+ end
17
+
18
+ # Store a value in the cache.
19
+ #
20
+ # @param key [String]
21
+ # @param value [String] JSON string to cache
22
+ # @param ttl [Integer, nil] time-to-live in seconds; +nil+ means no expiry
23
+ def set(key, value, ttl = nil)
24
+ raise NotImplementedError, "#{self.class}#set not implemented"
25
+ end
26
+
27
+ # @param key [String]
28
+ # @return [Boolean]
29
+ def exist?(key)
30
+ !get(key).nil?
31
+ end
32
+
33
+ # Delete a cached entry.
34
+ #
35
+ # @param key [String]
36
+ def delete(key)
37
+ raise NotImplementedError, "#{self.class}#delete not implemented"
38
+ end
39
+
40
+ # Flush all cached entries.
41
+ def clear
42
+ raise NotImplementedError, "#{self.class}#clear not implemented"
43
+ end
44
+ end
45
+ end
46
+ end