Class: Shipeasy::Engine
- Inherits:
-
Object
- Object
- Shipeasy::Engine
- Defined in:
- lib/shipeasy/engine.rb
Overview
The heavyweight engine: owns the api key, HTTP transport, the blob cache, the background poll timer, init/init_once, local overrides, track, and see()/default-client wiring. Was ‘Shipeasy::SDK::FlagsClient` before 2.0; renamed to a clean top-level `Shipeasy::Engine` when the lightweight user-bound `Shipeasy::Client` became the primary front door.
Most apps never construct an Engine directly — ‘Shipeasy.configure { … }` builds and registers the one global engine for you. Construct one explicitly only for advanced/serverless flows (multiple keys, offline snapshots).
Defined Under Namespace
Classes: FlagDetail
Constant Summary collapse
- Eval =
Internal collaborators still live under Shipeasy::SDK; alias them so the body below can keep referring to them unqualified after the class moved out from under the SDK namespace.
Shipeasy::SDK::Eval
- Telemetry =
Shipeasy::SDK::Telemetry
- AnonId =
Shipeasy::SDK::AnonId
- See =
Shipeasy::SDK::See
- DEFAULT_BASE_URL =
"https://edge.shipeasy.dev"- DEFAULT_CDN_BASE =
CDN origin serving the static loader scripts (/sdk/bootstrap.js, /sdk/i18n/loader.js) — distinct from the edge API the blobs are fetched from.
"https://cdn.shipeasy.ai"- 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
-
#bind_attributes(user) ⇒ Object
Public hook for the bound Shipeasy::Client: normalise an attribute hash and apply the request-scoped anonymous_id merge ONCE, at Client construction, exactly as every per-call getter does internally.
-
#bootstrap_script_tag(user, anon_id: nil, i18n_profile: "en:prod", base_url: nil) ⇒ Object
Return the cross-platform SSR bootstrap <script> tag for a request: se-bootstrap.js reads its data-* attributes and hydrates window.__SE_BOOTSTRAP (and writes the anon cookie).
- #clear_overrides ⇒ Object
-
#control_flow_exception(err) ⇒ Object
(also: #controlFlowException)
Mark an exception as expected control flow — reports nothing.
- #destroy ⇒ Object
-
#evaluate(user) ⇒ Object
Batch-evaluate every loaded gate, config and experiment for
userinto a bootstrap payload (+{ “flags” => …, “configs” => …, “experiments” => …, “killswitches” => … }+) keyed to match the browser SDK’s window.__SE_BOOTSTRAP shape. - #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.
-
#get_killswitch(name, switch_key = nil) ⇒ Object
Read a killswitch from the cached flags blob.
-
#i18n_script_tag(client_key, profile: "en:prod", base_url: nil) ⇒ Object
Return the i18n loader <script> tag (framework-agnostic; the Rails view helper Shipeasy::I18n::ViewHelpers#i18n_script_tag is separate).
- #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) ⇒ Engine
constructor
A new instance of Engine.
-
#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.
-
#see(problem) ⇒ Object
Report a caught exception (or thrown non-exception).
-
#see_violation(name) ⇒ Object
(also: #seeViolation)
Report a non-exception problem.
- #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) ⇒ Engine
Returns a new instance of Engine.
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 64 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 |
# File 'lib/shipeasy/engine.rb', line 36 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("/") # Read-env tag. Used by telemetry below and stamped onto see() error # events so reports are attributable to an environment. @env = env # 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 # Engine.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 = [] # see() structured error reporting. Per-process spam guard, bound here so # repeated reports of the same issue collapse to one send. See see.rb. @see_limiter = See::Limiter.new # Register as the default client backing the module-level Shipeasy::SDK # .see/.see_violation funcs (last constructed wins — the server-SDK # analog of TS's shipeasy({key}) configure call). Shipeasy::SDK.set_default_client(self) 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. The client is immediately READY against an empty blob (so a missing gate resolves FLAG_NOT_FOUND, not CLIENT_NOT_READY — parity with the other SDKs). Seed it with override_flag / override_config / override_experiment, then call the normal getters.
97 98 99 100 101 102 103 104 105 106 |
# File 'lib/shipeasy/engine.rb', line 97 def self.for_testing(env: "prod") client = new( api_key: "test", env: env, disable_telemetry: true, test_mode: true, ) client.send(:load_snapshot, {}, {}) client 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.
119 120 121 122 |
# File 'lib/shipeasy/engine.rb', line 119 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.
126 127 128 129 130 |
# File 'lib/shipeasy/engine.rb', line 126 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
#bind_attributes(user) ⇒ Object
Public hook for the bound Shipeasy::Client: normalise an attribute hash and apply the request-scoped anonymous_id merge ONCE, at Client construction, exactly as every per-call getter does internally.
301 302 303 |
# File 'lib/shipeasy/engine.rb', line 301 def bind_attributes(user) with_anon_id(user) end |
#bootstrap_script_tag(user, anon_id: nil, i18n_profile: "en:prod", base_url: nil) ⇒ Object
Return the cross-platform SSR bootstrap <script> tag for a request: se-bootstrap.js reads its data-* attributes and hydrates window.__SE_BOOTSTRAP (and writes the anon cookie). No key is embedded.
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 |
# File 'lib/shipeasy/engine.rb', line 364 def bootstrap_script_tag(user, anon_id: nil, i18n_profile: "en:prod", base_url: nil) payload = evaluate(user) base = cdn_base(base_url) attrs = [ "data-se-bootstrap", attr("data-flags", JSON.generate(payload["flags"])), attr("data-configs", JSON.generate(payload["configs"])), attr("data-experiments", JSON.generate(payload["experiments"])), attr("data-killswitches", JSON.generate(payload["killswitches"])), attr("data-i18n-profile", i18n_profile || "en:prod"), attr("data-api-url", base), ] attrs << attr("data-anon-id", anon_id) if anon_id && !anon_id.empty? %(<script src="#{CGI.escapeHTML("#{base}/sdk/bootstrap.js")}" #{attrs.join(' ')}></script>) end |
#clear_overrides ⇒ Object
168 169 170 171 172 173 174 175 |
# File 'lib/shipeasy/engine.rb', line 168 def clear_overrides @mutex.synchronize do @flag_overrides.clear @config_overrides.clear @exp_overrides.clear end self end |
#control_flow_exception(err) ⇒ Object Also known as: controlFlowException
Mark an exception as expected control flow — reports nothing. Returns a ‘.because(reason)` tail (with optional `.extras` for local debug only).
462 463 464 |
# File 'lib/shipeasy/engine.rb', line 462 def control_flow_exception(err) See::ControlFlowChain.new(err) end |
#destroy ⇒ Object
188 189 190 191 |
# File 'lib/shipeasy/engine.rb', line 188 def destroy @timer&.kill @timer = nil end |
#evaluate(user) ⇒ Object
Batch-evaluate every loaded gate, config and experiment for user into a bootstrap payload (+{ “flags” => …, “configs” => …, “experiments”
> …, “killswitches” => … }+) keyed to match the browser SDK’s
window.__SE_BOOTSTRAP shape. Local overrides win. Killswitches are folded into per-gate evaluation, so the standalone killswitches map is empty for this SDK. No telemetry (a batch evaluate is not a per-flag exposure).
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 |
# File 'lib/shipeasy/engine.rb', line 330 def evaluate(user) u = with_anon_id(user) flags_blob, exps_blob, flag_ov, config_ov, exp_ov, sticky = @mutex.synchronize do [@flags_blob, @exps_blob, @flag_overrides.dup, @config_overrides.dup, @exp_overrides.dup, @sticky_store] end flags = {} (flags_blob&.dig("gates") || {}).each do |name, gate| flags[name] = flag_ov.key?(name) ? flag_ov[name] : Eval.eval_gate(gate, u) end configs = {} (flags_blob&.dig("configs") || {}).each do |name, entry| configs[name] = config_ov.key?(name) ? config_ov[name] : entry["value"] end experiments = {} (exps_blob&.dig("experiments") || {}).each do |name, exp| if exp_ov.key?(name) ov = exp_ov[name] experiments[name] = { "inExperiment" => true, "group" => ov[:group], "params" => ov[:params] } next end r = Eval.eval_experiment(exp, flags_blob, exps_blob, u, exp_name: name, sticky_store: sticky) experiments[name] = { "inExperiment" => r.in_experiment, "group" => r.group, "params" => r.params } end { "flags" => flags, "configs" => configs, "experiments" => experiments, "killswitches" => {} } end |
#get_config(name, decode = nil, default: nil) ⇒ Object
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 |
# File 'lib/shipeasy/engine.rb', line 244 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
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 |
# File 'lib/shipeasy/engine.rb', line 260 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
235 236 237 238 239 240 241 242 |
# File 'lib/shipeasy/engine.rb', line 235 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.
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 |
# File 'lib/shipeasy/engine.rb', line 207 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 |
#get_killswitch(name, switch_key = nil) ⇒ Object
Read a killswitch from the cached flags blob. Without switch_key, returns true when the whole killswitch is killed. With switch_key, returns true when that specific named per-key switch is on — and when the key isn’t configured on the killswitch, FALLS BACK to the top-level value (so an unconfigured key behaves exactly like the no-key call). Unknown killswitches return false. Not user-scoped.
311 312 313 314 315 316 317 318 319 320 321 322 |
# File 'lib/shipeasy/engine.rb', line 311 def get_killswitch(name, switch_key = nil) @telemetry.emit("ks", name) ks = @mutex.synchronize { @flags_blob&.dig("killswitches", name.to_s) } return false unless ks unless switch_key.nil? switches = ks["switches"] || {} key = switch_key.to_s return Eval.enabled?(switches[key]) if switches.key?(key) # key not configured → fall through to the top-level value end Eval.enabled?(ks["killed"]) end |
#i18n_script_tag(client_key, profile: "en:prod", base_url: nil) ⇒ Object
Return the i18n loader <script> tag (framework-agnostic; the Rails view helper Shipeasy::I18n::ViewHelpers#i18n_script_tag is separate). The loader fetches translations for the profile using the PUBLIC client key.
383 384 385 386 387 |
# File 'lib/shipeasy/engine.rb', line 383 def i18n_script_tag(client_key, profile: "en:prod", base_url: nil) base = cdn_base(base_url) %(<script src="#{CGI.escapeHTML("#{base}/sdk/i18n/loader.js")}" ) + %(#{attr('data-key', client_key)} #{attr('data-profile', profile || 'en:prod')}></script>) end |
#init ⇒ Object
132 133 134 135 136 137 |
# File 'lib/shipeasy/engine.rb', line 132 def init return if @test_mode fetch_all @initialized = true start_poll end |
#init_once ⇒ Object
139 140 141 142 143 144 |
# File 'lib/shipeasy/engine.rb', line 139 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.
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 |
# File 'lib/shipeasy/engine.rb', line 417 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).
181 182 183 184 185 186 |
# File 'lib/shipeasy/engine.rb', line 181 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
156 157 158 159 |
# File 'lib/shipeasy/engine.rb', line 156 def override_config(name, value) @mutex.synchronize { @config_overrides[name.to_s] = value } self end |
#override_experiment(name, group, params) ⇒ Object
161 162 163 164 165 166 |
# File 'lib/shipeasy/engine.rb', line 161 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.
151 152 153 154 |
# File 'lib/shipeasy/engine.rb', line 151 def override_flag(name, value) @mutex.synchronize { @flag_overrides[name.to_s] = (value ? true : false) } self end |
#see(problem) ⇒ Object
Report a caught exception (or thrown non-exception). Fire-and-forget; never blocks or throws into the request path. Terminate with ‘.to(outcome)`:
client.see(e).causes_the("checkout").to("use cached prices")
449 450 451 |
# File 'lib/shipeasy/engine.rb', line 449 def see(problem) See::Chain.new(problem, method(:dispatch_see)) end |
#see_violation(name) ⇒ Object Also known as: seeViolation
Report a non-exception problem. The name is a stable fingerprint key —put variable data in ‘.extras`, never in the name.
455 456 457 |
# File 'lib/shipeasy/engine.rb', line 455 def see_violation(name) See::Chain.new(See::Violation.new(name), method(:dispatch_see)) end |
#track(user_id, event_name, props = {}) ⇒ Object
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 |
# File 'lib/shipeasy/engine.rb', line 389 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 |