Class: Shipeasy::SDK::FlagsClient
- Inherits:
-
Object
- Object
- Shipeasy::SDK::FlagsClient
- Defined in:
- lib/shipeasy/sdk/flags_client.rb
Defined Under Namespace
Classes: FlagDetail
Constant Summary collapse
- DEFAULT_BASE_URL =
"https://edge.shipeasy.dev"- REASON_CLIENT_NOT_READY =
Reason constants for FlagDetail#reason / get_flag_detail.
"CLIENT_NOT_READY"- REASON_FLAG_NOT_FOUND =
no blob fetched/loaded yet
"FLAG_NOT_FOUND"- REASON_OFF =
blob present, gate absent
"OFF"- REASON_OVERRIDE =
gate present but disabled/killed
"OVERRIDE"- REASON_RULE_MATCH =
answered by a local override
"RULE_MATCH"- REASON_DEFAULT =
evaluated true
"DEFAULT"
Class Method Summary collapse
-
.for_testing(env: "prod") ⇒ Object
Build a no-network, immediately-usable client for tests.
-
.from_file(path, env: "prod") ⇒ Object
Build an offline client from a JSON snapshot file.
-
.from_snapshot(flags: nil, experiments: nil, env: "prod") ⇒ Object
Build an offline client directly from already-parsed blobs (same shape as the /sdk/flags and /sdk/experiments response bodies).
Instance Method Summary collapse
- #clear_overrides ⇒ Object
- #destroy ⇒ Object
- #get_config(name, decode = nil, default: nil) ⇒ Object
- #get_experiment(name, user, default_params, decode = nil) ⇒ Object
- #get_flag(name, user, default: false) ⇒ Object
-
#get_flag_detail(name, user) ⇒ Object
Evaluate a flag and return why.
- #init ⇒ Object
- #init_once ⇒ Object
-
#initialize(api_key:, base_url: nil, env: "prod", disable_telemetry: false, telemetry_url: nil, test_mode: false, private_attributes: nil, sticky_store: nil) ⇒ FlagsClient
constructor
A new instance of FlagsClient.
-
#log_exposure(user_or_user_id, experiment_name) ⇒ Object
Emit an exposure event for an experiment at the server-side decision point (parity with the browser’s auto-exposure).
-
#on_change(callable = nil, &block) ⇒ Object
Register a listener fired after a background poll fetches NEW flag/config data (HTTP 200, not 304).
- #override_config(name, value) ⇒ Object
- #override_experiment(name, group, params) ⇒ Object
-
#override_flag(name, value) ⇒ Object
— Local overrides ————————————————- An override wins over the fetched blob in the matching getter.
- #track(user_id, event_name, props = {}) ⇒ Object
Constructor Details
#initialize(api_key:, base_url: nil, env: "prod", disable_telemetry: false, telemetry_url: nil, test_mode: false, private_attributes: nil, sticky_store: nil) ⇒ FlagsClient
Returns a new instance of FlagsClient.
15 16 17 18 19 20 21 22 23 24 25 26 27 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 |
# File 'lib/shipeasy/sdk/flags_client.rb', line 15 def initialize(api_key:, base_url: nil, env: "prod", disable_telemetry: false, telemetry_url: nil, test_mode: false, private_attributes: nil, sticky_store: nil) @api_key = api_key @base_url = (base_url || DEFAULT_BASE_URL).chomp("/") # Attribute names usable for targeting but stripped from every outbound # /collect payload (LD/Statsig privateAttributes). The server evaluates # locally so private attrs never leave for evaluation; the only egress is # track(), where the listed keys are dropped from the props bag. @private_attributes = (private_attributes || []).map(&:to_s) # Pluggable sticky-bucketing store (doc 20 §2). Absent ⇒ deterministic. # Threaded into get_experiment so an enrolled unit locks to its first # assigned variant. Built-in: InMemoryStickyStore. @sticky_store = sticky_store # Test mode: no network, ever. init/init_once/track become no-ops and # evaluation answers come purely from local overrides. Built via the # FlagsClient.for_testing factory; see clear_overrides / override_*. @test_mode = test_mode # Per-evaluation usage telemetry. ON by default; pass # disable_telemetry: true to opt out. See telemetry.rb. @telemetry = Telemetry.new( endpoint: telemetry_url || Telemetry::DEFAULT_TELEMETRY_URL, sdk_key: api_key, side: "server", env: env, disabled: disable_telemetry, ) @flags_blob = nil @exps_blob = nil @flags_etag = nil @exps_etag = nil @poll_interval = 30 @mutex = Mutex.new @timer = nil @initialized = false # Statsig-style local overrides. Keyed by resource name; an override, # when present, short-circuits the corresponding getter. Usable on any # client (test or live) for deterministic tests / local development. @flag_overrides = {} @config_overrides = {} @exp_overrides = {} # Change listeners — fired after a background poll returns NEW data # (HTTP 200, not 304). Never fired in test/offline mode. Guarded by # @mutex; see on_change / notify_change. @change_listeners = [] end |
Class Method Details
.for_testing(env: "prod") ⇒ Object
Build a no-network, immediately-usable client for tests. Telemetry is disabled, init/init_once/track are no-ops (never fetch), and no api_key is required. Seed it with override_flag / override_config / override_experiment, then call the normal getters.
64 65 66 67 68 69 70 71 |
# File 'lib/shipeasy/sdk/flags_client.rb', line 64 def self.for_testing(env: "prod") new( api_key: "test", env: env, disable_telemetry: true, test_mode: true, ) end |
.from_file(path, env: "prod") ⇒ Object
Build an offline client from a JSON snapshot file. The file holds the raw response bodies of the two SDK endpoints under “flags” and “experiments” keys:
{ "flags": <body of /sdk/flags>, "experiments": <body of /sdk/experiments> }
The returned client does ZERO network (reuses test_mode plumbing: init/init_once/track are no-ops, telemetry off) but, unlike a bare for_testing client, runs the REAL evaluator against the loaded blobs. Local overrides still apply on top. Handy for CI, air-gapped runs, and reproducing a production decision from a captured blob.
84 85 86 87 |
# File 'lib/shipeasy/sdk/flags_client.rb', line 84 def self.from_file(path, env: "prod") data = JSON.parse(File.read(path)) from_snapshot(flags: data["flags"], experiments: data["experiments"], env: env) end |
.from_snapshot(flags: nil, experiments: nil, env: "prod") ⇒ Object
Build an offline client directly from already-parsed blobs (same shape as the /sdk/flags and /sdk/experiments response bodies). See from_file.
91 92 93 94 95 |
# File 'lib/shipeasy/sdk/flags_client.rb', line 91 def self.from_snapshot(flags: nil, experiments: nil, env: "prod") client = for_testing(env: env) client.send(:load_snapshot, flags, experiments) client end |
Instance Method Details
#clear_overrides ⇒ Object
133 134 135 136 137 138 139 140 |
# File 'lib/shipeasy/sdk/flags_client.rb', line 133 def clear_overrides @mutex.synchronize do @flag_overrides.clear @config_overrides.clear @exp_overrides.clear end self end |
#destroy ⇒ Object
153 154 155 156 |
# File 'lib/shipeasy/sdk/flags_client.rb', line 153 def destroy @timer&.kill @timer = nil end |
#get_config(name, decode = nil, default: nil) ⇒ Object
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 |
# File 'lib/shipeasy/sdk/flags_client.rb', line 209 def get_config(name, decode = nil, default: nil) key = name.to_s has_override, override = @mutex.synchronize do [@config_overrides.key?(key), @config_overrides[key]] end if has_override return decode ? decode.call(override) : override end @telemetry.emit("config", name) entry = @mutex.synchronize { @flags_blob&.dig("configs", name) } return default unless entry value = entry["value"] decode ? decode.call(value) : value end |
#get_experiment(name, user, default_params, decode = nil) ⇒ Object
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 259 260 261 |
# File 'lib/shipeasy/sdk/flags_client.rb', line 225 def get_experiment(name, user, default_params, decode = nil) key = name.to_s override = @mutex.synchronize { @exp_overrides[key] } if override params = override[:params] params = decode.call(params) if decode return Eval::ExperimentResult.new( in_experiment: true, group: override[:group], params: params, ) end @telemetry.emit("experiment", name) flags_blob, exps_blob = @mutex.synchronize { [@flags_blob, @exps_blob] } exp = exps_blob&.dig("experiments", name) result = Eval.eval_experiment( exp, flags_blob, exps_blob, with_anon_id(user), exp_name: name.to_s, sticky_store: @sticky_store, ) result.params ||= default_params if result.in_experiment && decode begin result = Eval::ExperimentResult.new( in_experiment: true, group: result.group, params: decode.call(result.params), ) rescue => e warn "[shipeasy] get_experiment('#{name}') decode failed: #{e.}" return Eval::ExperimentResult.new(in_experiment: false, group: "control", params: default_params) end end result end |
#get_flag(name, user, default: false) ⇒ Object
200 201 202 203 204 205 206 207 |
# File 'lib/shipeasy/sdk/flags_client.rb', line 200 def get_flag(name, user, default: false) detail = get_flag_detail(name, user) if detail.reason == REASON_CLIENT_NOT_READY || detail.reason == REASON_FLAG_NOT_FOUND default else detail.value end end |
#get_flag_detail(name, user) ⇒ Object
Evaluate a flag and return why. Telemetry (“gate” beacon) is emitted exactly once here (steps 2–5), never on the OVERRIDE short-circuit.
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 |
# File 'lib/shipeasy/sdk/flags_client.rb', line 172 def get_flag_detail(name, user) key = name.to_s # 1. Override short-circuits before any telemetry (mirrors get_config). override = @mutex.synchronize { @flag_overrides[key] if @flag_overrides.key?(key) } return FlagDetail.new(value: override, reason: REASON_OVERRIDE) unless override.nil? @telemetry.emit("gate", name) flags_blob, gate = @mutex.synchronize { [@flags_blob, @flags_blob&.dig("gates", name)] } # 2. Not initialized — no blob fetched or loaded yet. return FlagDetail.new(value: false, reason: REASON_CLIENT_NOT_READY) if flags_blob.nil? # 3. Blob present but this gate isn't in it. return FlagDetail.new(value: false, reason: REASON_FLAG_NOT_FOUND) unless gate # 4. Gate present but disabled (or killswitched) — eval_gate would also # return false here, but the reason is OFF, not a rollout DEFAULT. if Eval.enabled?(gate["killswitch"]) || !Eval.enabled?(gate["enabled"]) return FlagDetail.new(value: false, reason: REASON_OFF) end # 5. Run the canonical evaluator; reason follows the boolean result. result = Eval.eval_gate(gate, with_anon_id(user)) FlagDetail.new(value: result, reason: result ? REASON_RULE_MATCH : REASON_DEFAULT) end |
#init ⇒ Object
97 98 99 100 101 102 |
# File 'lib/shipeasy/sdk/flags_client.rb', line 97 def init return if @test_mode fetch_all @initialized = true start_poll end |
#init_once ⇒ Object
104 105 106 107 108 109 |
# File 'lib/shipeasy/sdk/flags_client.rb', line 104 def init_once return if @test_mode return if @initialized fetch_all @initialized = true end |
#log_exposure(user_or_user_id, experiment_name) ⇒ Object
Emit an exposure event for an experiment at the server-side decision point (parity with the browser’s auto-exposure). The server is stateless and never auto-logs, so call this when you actually present the treatment. Re-evaluates the experiment for the user (a bare user_id string is wrapped as { “user_id” => id }); if enrolled, POSTs a single exposure to /collect. No-op in test mode or when the user isn’t enrolled.
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 |
# File 'lib/shipeasy/sdk/flags_client.rb', line 291 def log_exposure(user_or_user_id, experiment_name) return if @test_mode user = user_or_user_id.is_a?(Hash) ? user_or_user_id : { "user_id" => user_or_user_id.to_s } result = get_experiment(experiment_name, user, {}) return unless result.in_experiment u = user.transform_keys(&:to_s) payload = JSON.generate({ events: [{ type: "exposure", experiment: experiment_name.to_s, group: result.group, user_id: (u["user_id"] || u["anonymous_id"]).to_s, ts: (Time.now.to_f * 1000).to_i, }], }) Thread.new do post("/collect", payload) rescue => e warn "[shipeasy] log_exposure failed: #{e.}" end end |
#on_change(callable = nil, &block) ⇒ Object
Register a listener fired after a background poll fetches NEW flag/config data (HTTP 200, not 304). Accepts either a block or any callable (an object responding to #call). Returns an unsubscribe proc — call it to remove the listener. Never fires in test/offline mode (no poll thread).
146 147 148 149 150 151 |
# File 'lib/shipeasy/sdk/flags_client.rb', line 146 def on_change(callable = nil, &block) listener = callable || block raise ArgumentError, "on_change requires a block or callable" unless listener.respond_to?(:call) @mutex.synchronize { @change_listeners << listener } proc { @mutex.synchronize { @change_listeners.delete(listener) } } end |
#override_config(name, value) ⇒ Object
121 122 123 124 |
# File 'lib/shipeasy/sdk/flags_client.rb', line 121 def override_config(name, value) @mutex.synchronize { @config_overrides[name.to_s] = value } self end |
#override_experiment(name, group, params) ⇒ Object
126 127 128 129 130 131 |
# File 'lib/shipeasy/sdk/flags_client.rb', line 126 def override_experiment(name, group, params) @mutex.synchronize do @exp_overrides[name.to_s] = { group: group, params: params } end self end |
#override_flag(name, value) ⇒ Object
— Local overrides ————————————————- An override wins over the fetched blob in the matching getter. Setters are mutex-guarded so they’re safe to call alongside background polling on a live client.
116 117 118 119 |
# File 'lib/shipeasy/sdk/flags_client.rb', line 116 def override_flag(name, value) @mutex.synchronize { @flag_overrides[name.to_s] = (value ? true : false) } self end |
#track(user_id, event_name, props = {}) ⇒ Object
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 |
# File 'lib/shipeasy/sdk/flags_client.rb', line 263 def track(user_id, event_name, props = {}) return if @test_mode safe_props = strip_private(props) payload = JSON.generate({ events: [{ type: "metric", event_name: event_name, user_id: user_id.to_s, ts: (Time.now.to_f * 1000).to_i, **(safe_props.empty? ? {} : { properties: safe_props }), }], }) Thread.new do post("/collect", payload) rescue => e warn "[shipeasy] track failed: #{e.}" end end |