flagnetic 0.1.3 → 0.2.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.
- checksums.yaml +4 -4
- data/README.md +41 -15
- data/lib/flagnetic/client.rb +74 -22
- data/lib/flagnetic/detail.rb +6 -6
- data/lib/flagnetic/eval/evaluation.rb +25 -5
- data/lib/flagnetic/eval/operators.rb +5 -0
- data/lib/flagnetic/eval/regex_vm.rb +0 -2
- data/lib/flagnetic/eval/types.rb +3 -3
- data/lib/flagnetic/eval.rb +11 -0
- data/lib/flagnetic/event_batch.rb +9 -4
- data/lib/flagnetic/exposures.rb +41 -9
- data/lib/flagnetic/fallback_chain.rb +13 -10
- data/lib/flagnetic/logging.rb +4 -3
- data/lib/flagnetic/railtie.rb +0 -18
- data/lib/flagnetic/reporter.rb +5 -3
- data/lib/flagnetic/sse_parser.rb +4 -4
- data/lib/flagnetic/stream.rb +2 -1
- data/lib/flagnetic/summaries.rb +6 -6
- data/lib/flagnetic/transport.rb +22 -3
- data/lib/flagnetic/version.rb +4 -2
- data/lib/flagnetic/worker.rb +27 -14
- metadata +1 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 755646cb5b4153be37a92a4290828c2073f130cc151027a1b528c03d4a11a277
|
|
4
|
+
data.tar.gz: 6946737e94bc91ffadc13192d0fbf3e3121d2b38b209ce446b1e550c9d9d52fe
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 429ffa85b859158c7b518411682540c538b36329fbec3c149e9cce6bcb0cef6b8f1f458a7a7cd1481b7859836c3fe069d600586d16cfc5731b91eacdfcc3da74
|
|
7
|
+
data.tar.gz: 5d7ce39d7a4d9e1a5c57765039386720a82241c6b76f8a0744811fa88ec1e0b5488cf403033906612bf24de974bdb513ba2af1b050208b4d685a572278633067
|
data/README.md
CHANGED
|
@@ -29,15 +29,35 @@ if client.bool("new_checkout", default: false, context: { units: { user: "u-1001
|
|
|
29
29
|
end
|
|
30
30
|
```
|
|
31
31
|
|
|
32
|
-
Under Rails no initializer is needed: set `FLAGNETIC_SDK_KEY` and `FLAGNETIC_BASE_URL` and use `Flagnetic.client` (see [Rails](#rails)). In tests, `Flagnetic::Testing` serves the values you set without a server (see [Testing](#testing)).
|
|
32
|
+
The [quickstart](../../docs/sdks/ruby.md#quickstart) walks through these steps one at a time. Under Rails no initializer is needed: set `FLAGNETIC_SDK_KEY` and `FLAGNETIC_BASE_URL` and use `Flagnetic.client` (see [Rails](#rails)). In tests, `Flagnetic::Testing` serves the values you set without a server (see [Testing](#testing)).
|
|
33
33
|
|
|
34
34
|
## Propagation
|
|
35
35
|
|
|
36
|
-
A change saved in Flagnetic, a kill switch included, reaches a client holding the
|
|
36
|
+
A change saved in Flagnetic, a kill switch included, reaches a client holding the ruleset stream (the default) within **2 seconds at the 99th percentile**, whichever replica the change and the client each go through. With `stream: false`, or behind a proxy that blocks `text/event-stream`, it arrives at the next poll, within 30 seconds. Every pull request that changes this gem checks the 2 seconds against two real replicas.
|
|
37
|
+
|
|
38
|
+
## What 1.0 promises
|
|
39
|
+
|
|
40
|
+
From 1.0.0 the public API below changes only additively until 2.0: a name, a signature, an option, a returned type, an error class or a log event listed here is never removed or changed in a minor or patch release. A thing to be removed is deprecated in a minor (documented here and in the release notes, with what replaces it) and removed in the next major.
|
|
41
|
+
|
|
42
|
+
**The public API**
|
|
43
|
+
|
|
44
|
+
- `Flagnetic::Client`: `new` with the options in the table under [Client](#client), except `timing:`; the getters `bool`, `string`, `number`, `int`, `int_detail`, `json` and `detail`; `stage`, `status`, `ready`, `on_change`, `on_stage`, `reload`, `exposure`, `alias`, `flush`, `close`, `after_fork`, `local_overrides` and, on an offline client, `recorder`.
|
|
45
|
+
- `Flagnetic::Detail` and `Flagnetic::Status` with their members; `Flagnetic::REASONS`, `STAGES`, `ERROR_CODES` and `EVENTS` (a release may add a member, never remove one); `Flagnetic::VERSION`.
|
|
46
|
+
- `Flagnetic::LocalOverrides` (`set`, `remove`, `clear`, `list`) and `Flagnetic::Recorder` with the rows it returns.
|
|
47
|
+
- The errors `Flagnetic::Error`, `NotConfigured`, `LocalOverridesNotAllowed`, `LocalOverrideRefused` and `OfflineError`.
|
|
48
|
+
- `Flagnetic.client`, `client=`, `client_builder=` and `client?`.
|
|
49
|
+
- The log events in the table under [Events](#events), with their levels and fields (a release may add a field or an event, never rename or drop one), and the `logger:` contract: a callable receiving `(level, event, fields)` or a standard `Logger`; `Flagnetic::Logging.adapt` turns that option into a callable, for gems built on this one.
|
|
50
|
+
- `Flagnetic::Testing`: `offline`, `with_flags`, `with_ruleset`, `Helpers` and the offline client's `set` and `reload`.
|
|
51
|
+
- The Rails integration: every `config.flagnetic` setting under [Rails](#rails), and the controller helpers `flagnetic_context` and `flagnetic_anonymous_id`.
|
|
52
|
+
- `Flagnetic::Eval`, the evaluator: `Ruleset.decode` and the ruleset's `evaluate`, `evaluate_all`, `unsupported_rules`, `invalid_conditions` and `version`; `Context`, `Result`, `ExperimentDetail`, `Construct`, `DecodeError`, and `Eval::REASONS` and `ERROR_CODES`.
|
|
53
|
+
|
|
54
|
+
**Everything else is internal and changes without notice**: every other constant and class under `Flagnetic` (the transport, worker, stream, exposure and summary machinery, the store), the evaluator's hash, date, version and regular expression machinery and the structs a decoded ruleset is made of, the `timing:` option (a seam for this gem's tests), the railtie's methods and any method the list above does not name. They are private constants where Ruby can say so; do not reach them with `const_get` or `send`.
|
|
55
|
+
|
|
56
|
+
The wire is promised separately: the SDK reads ruleset `schema_version` 1 over `/sdk/v1`, both frozen since 0.1.0 ([compatibility](../../docs/sdks/compatibility.md)). The gem is released as 1.0.0 together with the server's 1.0.0, and supports the latest minor only: fixes, security fixes included, ship in the next release.
|
|
37
57
|
|
|
38
58
|
## Client
|
|
39
59
|
|
|
40
|
-
`Flagnetic::Client` is the server-mode client. It downloads the ruleset with the server key, holds it in memory, follows every change through the
|
|
60
|
+
`Flagnetic::Client` is the server-mode client. It downloads the ruleset with the server key, holds it in memory, follows every change through the ruleset stream (polling while the stream is down) and evaluates locally, so a getter never waits on the network and never raises. A stream is stable once it has delivered a heartbeat: one the server closes before that (a draining replica, a proxy that ends the stream early) is a failure like any other and the reconnect backs off, while the close of a stable stream waits 0 to 2 seconds.
|
|
41
61
|
|
|
42
62
|
```ruby
|
|
43
63
|
require "flagnetic"
|
|
@@ -48,6 +68,7 @@ client.ready(timeout: 5) # => :fresh, :last_good or :built_in
|
|
|
48
68
|
context = { units: { user: "u-1001" }, attributes: { plan: "pro" } }
|
|
49
69
|
client.bool("new_checkout", default: false, context: context)
|
|
50
70
|
client.int("max_items", default: 10, context: context) # a number flag, whole numbers only
|
|
71
|
+
client.int_detail("max_items", default: 10, context: context) # the same, with why it was served
|
|
51
72
|
detail = client.detail("new_checkout", default: false, context: context)
|
|
52
73
|
detail.value # => true
|
|
53
74
|
detail.reason # => :rule
|
|
@@ -59,7 +80,7 @@ A client key (`fn_cli_...`) is refused at construction with an `ArgumentError`.
|
|
|
59
80
|
|
|
60
81
|
| Option | Meaning |
|
|
61
82
|
|---|---|
|
|
62
|
-
| `stream:` | `false` turns the
|
|
83
|
+
| `stream:` | `false` turns the ruleset stream off; the ruleset is then polled every 30 s (default `true`). |
|
|
63
84
|
| `poll_interval:` | Seconds between polls while the stream is up (default 300, at least 30). |
|
|
64
85
|
| `request_timeout:` | Seconds per request (default 10). |
|
|
65
86
|
| `store:` | Path of a file keeping the last good ruleset across restarts. It is read at construction and rewritten on every accepted ruleset. The file is headed by a digest of the SDK key: one written under another key (another environment's, say) or under none is discarded with `store_failed`. |
|
|
@@ -69,15 +90,17 @@ A client key (`fn_cli_...`) is refused at construction with an `ArgumentError`.
|
|
|
69
90
|
| `flush_interval:` | Seconds between sends of the exposure and alias queue (default 2); 500 queued events are sent at once. |
|
|
70
91
|
| `summary_interval:` | Seconds between evaluation summaries (default 60). |
|
|
71
92
|
| `send_summaries:` | `false` stops counting and sending evaluation summaries. |
|
|
72
|
-
| `send_exposures:` | `false` makes `exposure` and `alias` send nothing (logged as `
|
|
93
|
+
| `send_exposures:` | `false` makes `exposure` and `alias` send nothing (logged as `exposures_off`). |
|
|
73
94
|
| `offline:`, `offline_file:` | A ruleset document (JSON text, a `Hash` or a callable returning one) or the path of one. No request is ever made, the stage is `:fresh`, and `reload` re-reads the source. |
|
|
74
95
|
| `allow_overrides:` | Enables local overrides. |
|
|
75
96
|
|
|
76
97
|
`stage` is `:fresh` while the latest attempt succeeded (a `304` included), `:last_good` while the held ruleset is older than the latest attempt (it came from an earlier success or from the store) and `:built_in` before any ruleset was received. `status` adds `stale_since`. `on_change` and `on_stage` register blocks and return a callable that removes them.
|
|
77
98
|
|
|
78
|
-
|
|
99
|
+
A ruleset stream answered 401 or 403 logs `key_revoked` and stays closed while the fetch is refused too; it is tried again after the first successful fetch that follows the refusal (after the second when it was refused at startup, since the first fetch then shows nothing new), so a restored key gets its stream back.
|
|
79
100
|
|
|
80
|
-
|
|
101
|
+
Every request, the ruleset stream included, goes through `Net::HTTP`, so the proxy configured for the process (`http_proxy`, `https_proxy`, `no_proxy`) applies.
|
|
102
|
+
|
|
103
|
+
After `fork` the child starts its own background thread on its first call, so a child that never evaluates opens no stream; `after_fork` starts it at once, so a worker that has not served a request yet already follows the stream.
|
|
81
104
|
|
|
82
105
|
Local overrides replace a flag's value inside this process and are refused in a protected environment:
|
|
83
106
|
|
|
@@ -102,7 +125,7 @@ client.flush(timeout: 5)
|
|
|
102
125
|
- **Evaluation summaries.** Every evaluation is counted per flag, variation and reason (`fallback` and `local_override` included, never a unit ID or a value) and sent every `summary_interval` as one or more `evaluation_summary` events of at most 1,000 rows, with the version of the ruleset held at the interval's end. A report that fails merges into the next one; one older than an hour is dropped.
|
|
103
126
|
- **Exposures.** Evaluating records nothing on its own. `exposure` sends the experiment block of the latest evaluation of that flag for that context, or nothing when it carried none (`exposure_skipped` at debug says why). A flag with automatic exposure sends one as it is evaluated. A repeat for the same experiment, unit and variation is sent once per `flush_interval`.
|
|
104
127
|
- **Aliases.** `alias` links the unit ID used before sign-up to the one after it; it changes no context.
|
|
105
|
-
- **Delivery.** Events go gzipped to `POST /sdk/v1/events` in batches of at most 500, each with a UUIDv7 event ID kept across retries, so the server drops a resend as a duplicate. An evaluation summary that is still unanswered when its flush ends is merged into the next window and sent under new IDs. A 429, a 5xx or a network error is retried with backoff (evaluation summaries wait for `Retry-After`, capped at five minutes); a 401 or 403 logs `key_revoked` and keeps the events; an event the server rejects is logged as `queue_dropped` and never sent again. The queue holds 10,000 events and drops the oldest beyond that. A string that is not valid UTF-8 (a unit ID taken from a cookie, say) is sent with each invalid byte replaced by U+FFFD; an event that still cannot be encoded is dropped alone, logged as `queue_dropped` with cause `not_serialisable` and the class of the error as `fault`, and costs no other event.
|
|
128
|
+
- **Delivery.** Events go gzipped to `POST /sdk/v1/events` in batches of at most 500, each with a UUIDv7 event ID kept across retries, so the server drops a resend as a duplicate. An evaluation summary that is still unanswered when its flush ends is merged into the next window and sent under new IDs. A 429, a 5xx or a network error is retried with backoff (evaluation summaries wait for `Retry-After`, capped at five minutes); a 401 or 403 logs `key_revoked` and keeps the events; an event the server rejects is logged as `queue_dropped` and never sent again. The queue holds 10,000 events and drops the oldest beyond that. Drops beyond that are logged as one `queue_dropped` per flush with the count. A string that is not valid UTF-8 (a unit ID taken from a cookie, say) is sent with each invalid byte replaced by U+FFFD; an event that still cannot be encoded is dropped alone, logged as `queue_dropped` with cause `not_serialisable` and the class of the error as `fault`, and costs no other event.
|
|
106
129
|
- `flush(timeout:)` sends what is queued and the current window and waits at most `timeout` seconds; `close(timeout:)` flushes first and then stops the background thread, both within the one `timeout`. A forked child starts with an empty queue and window.
|
|
107
130
|
|
|
108
131
|
An offline client sends nothing: it hands every summary, exposure and alias to its `recorder`.
|
|
@@ -113,8 +136,8 @@ Log events have stable names (`Flagnetic::EVENTS`); alert on the name, never on
|
|
|
113
136
|
|---|---|---|
|
|
114
137
|
| `ruleset_loaded` | info | `source` (`fetch`, `store`, `offline`), `ruleset_version`, `flags` |
|
|
115
138
|
| `fetch_failed` | warn (error offline) | `cause`, `stage` (`source` offline) |
|
|
116
|
-
| `
|
|
117
|
-
| `
|
|
139
|
+
| `stream_connected` | info | |
|
|
140
|
+
| `stream_dropped` | info after a server close of a stable stream, warn otherwise | `cause` |
|
|
118
141
|
| `stage_changed` | info to `fresh`, warn otherwise | `from`, `to` |
|
|
119
142
|
| `key_revoked` | error, once per source until it recovers | `status`, `source` (`fetch`, `stream`) |
|
|
120
143
|
| `schema_unsupported` | error, once | `schema_version`, `supported` |
|
|
@@ -128,11 +151,14 @@ Log events have stable names (`Flagnetic::EVENTS`); alert on the name, never on
|
|
|
128
151
|
| `listener_failed` | error | `cause` |
|
|
129
152
|
| `store_failed` | error | `path`, `cause` |
|
|
130
153
|
| `worker_failed` | error | `cause` |
|
|
131
|
-
| `exposure_skipped` | debug | `flag`, `cause` (`no_experiment`, `no_detail`, `repeat`) |
|
|
132
|
-
| `
|
|
133
|
-
| `
|
|
154
|
+
| `exposure_skipped` | debug | `flag`, `cause` (`no_experiment`, `no_detail`, `repeat`); once at warn with `cause` `closed` for an exposure or alias after `close` |
|
|
155
|
+
| `exposures_off` | warn | |
|
|
156
|
+
| `events_failed` | warn | `kind`, `events`, `retry_in`, `status`, `error` |
|
|
134
157
|
| `client_not_configured` | warn | `rails_env`: the Rails integration found no SDK key and base URL outside production and serves built-in defaults |
|
|
135
|
-
| `
|
|
158
|
+
| `operation_deprecated` | warn, once per operation and process | `operation` (`ruleset`, `stream`, `events`), `deprecation` (the header as received, e.g. `@1767225600`), `sunset` (the HTTP date, only when sent) |
|
|
159
|
+
| `queue_dropped` | warn | `kind` (`exposure_or_alias`, `evaluation_summary`), `cause` (`queue_full`, `not_serialisable`, `client_error`, `refused_by_the_platform`, `window_too_old`) and what was dropped (`fault` for `not_serialisable`) |
|
|
160
|
+
|
|
161
|
+
A server that deprecates an operation answers it with a `Deprecation` header (and a `Sunset` header when it names a date): the client logs `operation_deprecated` once for each operation and keeps working, so the log is how an application learns it should upgrade the gem before the sunset.
|
|
136
162
|
|
|
137
163
|
A ruleset from a newer server may hold constructs this SDK does not know. The client logs `rule_unsupported` once per flag and ruleset version, and the flag serves its default with the error code `inconsistent_ruleset`.
|
|
138
164
|
|
|
@@ -146,7 +172,7 @@ A condition this SDK cannot evaluate although the server accepted it, such as a
|
|
|
146
172
|
|
|
147
173
|
Under Rails the gem loads a railtie (nothing of it loads without Rails) that sets `Flagnetic.client` up without an initializer. The SDK key and base URL come from the first of `config.flagnetic.sdk_key` and `config.flagnetic.base_url`, the `FLAGNETIC_SDK_KEY` and `FLAGNETIC_BASE_URL` environment variables, and credentials (`flagnetic.sdk_key`, `flagnetic.base_url`). Without both and without `offline_file`, building the client in production raises `Flagnetic::NotConfigured`, naming what is missing and where to set it, so a deployment that lost its key fails at boot (in console, runner and rake, on first use) instead of serving built-in defaults to every user; in any other environment the client serves built-in defaults and logs `client_not_configured`.
|
|
148
174
|
|
|
149
|
-
A server or job process builds the client at boot and waits up to `ready_timeout` seconds for the ruleset; `rails console`, `rails runner` and rake build it on first use, so a task that never asks for a flag makes no request. Every forked child (Puma cluster mode, Unicorn) starts its own background thread
|
|
175
|
+
A server or job process builds the client at boot and waits up to `ready_timeout` seconds for the ruleset; `rails console`, `rails runner` and rake build it on first use, so a task that never asks for a flag makes no request. Every forked child (Puma cluster mode, Unicorn) starts its own background thread on its first call, and every process closes its client at exit, which flushes what it queued. Local overrides are allowed in every environment but production, where no setting enables them.
|
|
150
176
|
|
|
151
177
|
| `config.flagnetic.` | |
|
|
152
178
|
|---|---|
|
data/lib/flagnetic/client.rb
CHANGED
|
@@ -13,12 +13,14 @@ module Flagnetic
|
|
|
13
13
|
#
|
|
14
14
|
# Threads: the ruleset is a frozen object swapped under a mutex and read
|
|
15
15
|
# without locking, so getters never wait. One background thread runs the
|
|
16
|
-
#
|
|
16
|
+
# ruleset stream, polling and retries.
|
|
17
17
|
#
|
|
18
18
|
# Fork: the first call in a forked child (Puma cluster mode, Unicorn)
|
|
19
19
|
# sees the new process ID and starts the child's own background thread;
|
|
20
20
|
# the child keeps serving the ruleset it inherited meanwhile. after_fork
|
|
21
|
-
# starts it at once,
|
|
21
|
+
# starts it at once, for an application that wants a worker to follow the
|
|
22
|
+
# ruleset before its first call; a child that never evaluates opens no
|
|
23
|
+
# stream.
|
|
22
24
|
#
|
|
23
25
|
# Getters never raise: any failure serves the built-in default with
|
|
24
26
|
# reason fallback and a log event.
|
|
@@ -26,20 +28,23 @@ module Flagnetic
|
|
|
26
28
|
include FallbackChain
|
|
27
29
|
|
|
28
30
|
# Timing holds the delays and intervals of the background thread, in
|
|
29
|
-
# seconds,
|
|
31
|
+
# seconds, the random source of the stream's waits (nil: Random.new) and
|
|
32
|
+
# the monotonic and wall clocks (now, wall_now: callables a test replaces
|
|
33
|
+
# to move time).
|
|
30
34
|
# Only poll_interval and request_timeout are public options; the timing
|
|
31
35
|
# option exists for tests and is not part of the API.
|
|
32
36
|
Timing = Struct.new(:request_timeout, :fetch_base, :fetch_cap, :unauthorized_cap, :stream_base, :stream_cap,
|
|
33
37
|
:worker_stable, :close_jitter, :silence, :poll_connected, :poll_down, :event_retries,
|
|
34
|
-
:exposure_flush, :summary_flush, :random, keyword_init: true)
|
|
38
|
+
:exposure_flush, :summary_flush, :random, :now, :wall_now, keyword_init: true)
|
|
35
39
|
DEFAULT_TIMING = Timing.new(
|
|
36
40
|
request_timeout: 10, fetch_base: 1, fetch_cap: 300, unauthorized_cap: 900, stream_base: 1, stream_cap: 30,
|
|
37
41
|
worker_stable: 60, close_jitter: 2, silence: 45, poll_connected: 300, poll_down: 30, event_retries: [1, 2, 4],
|
|
38
|
-
exposure_flush: 2, summary_flush: 60
|
|
42
|
+
exposure_flush: 2, summary_flush: 60,
|
|
43
|
+
now: -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) }, wall_now: -> { Time.now }
|
|
39
44
|
).freeze
|
|
40
45
|
MIN_POLL_INTERVAL = 30
|
|
41
46
|
TYPES = %w[boolean string number json].freeze
|
|
42
|
-
private_constant :Timing, :DEFAULT_TIMING, :TYPES
|
|
47
|
+
private_constant :Timing, :DEFAULT_TIMING, :TYPES, :MIN_POLL_INTERVAL
|
|
43
48
|
|
|
44
49
|
# new constructs a client for a server key and the base URL of the
|
|
45
50
|
# instance. It fails loudly (ArgumentError) only for a client key and
|
|
@@ -56,7 +61,7 @@ module Flagnetic
|
|
|
56
61
|
# another key, or under none, is discarded with store_failed.
|
|
57
62
|
# - logger: a callable receiving (level, event, fields), or a Logger.
|
|
58
63
|
# Default: warn and above to $stderr.
|
|
59
|
-
# - stream: false disables the
|
|
64
|
+
# - stream: false disables the ruleset stream; polling then runs every
|
|
60
65
|
# 30 s.
|
|
61
66
|
# - poll_interval: seconds between safety polls while the stream is
|
|
62
67
|
# connected (default 300, at least 30).
|
|
@@ -96,7 +101,7 @@ module Flagnetic
|
|
|
96
101
|
@app_version = app_version&.to_s
|
|
97
102
|
init_state
|
|
98
103
|
log(:warn, :local_overrides_allowed) if allow_overrides
|
|
99
|
-
log(:warn, :
|
|
104
|
+
log(:warn, :exposures_off) unless @send_exposures
|
|
100
105
|
@timing = build_timing(poll_interval, request_timeout, flush_interval, summary_interval, timing)
|
|
101
106
|
|
|
102
107
|
if offline || offline_file
|
|
@@ -124,6 +129,12 @@ module Flagnetic
|
|
|
124
129
|
# type_mismatch rather than a truncated value.
|
|
125
130
|
def int(key, default:, context: nil) = serve(key, "number", default, context, int: true).value
|
|
126
131
|
|
|
132
|
+
# int_detail serves a number flag as int does, with why it was served:
|
|
133
|
+
# the value is narrowed to an Integer before the evaluation is counted
|
|
134
|
+
# or exposed, so a number that is not whole is counted as the fallback it
|
|
135
|
+
# serves and exposes nothing. default is an Integer.
|
|
136
|
+
def int_detail(key, default:, context: nil) = serve(key, "number", default, context, int: true)
|
|
137
|
+
|
|
127
138
|
# json serves a JSON flag's value, parsed and frozen, for context, or
|
|
128
139
|
# default.
|
|
129
140
|
def json(key, default:, context: nil) = serve(key, "json", default, context).value
|
|
@@ -205,6 +216,8 @@ module Flagnetic
|
|
|
205
216
|
# deduplication by event ID is what analysis relies on. It never raises.
|
|
206
217
|
def exposure(key, context: nil)
|
|
207
218
|
ensure_worker
|
|
219
|
+
return if closed_for_events?
|
|
220
|
+
|
|
208
221
|
@exposures&.exposure(context, key.to_s)
|
|
209
222
|
nil
|
|
210
223
|
rescue StandardError => e
|
|
@@ -219,6 +232,8 @@ module Flagnetic
|
|
|
219
232
|
# raises.
|
|
220
233
|
def alias(from_unit_type, from_unit_id, to_unit_type, to_unit_id)
|
|
221
234
|
ensure_worker
|
|
235
|
+
return if closed_for_events?
|
|
236
|
+
|
|
222
237
|
@exposures&.add_alias(from_unit_type, from_unit_id, to_unit_type, to_unit_id)
|
|
223
238
|
nil
|
|
224
239
|
rescue StandardError => e
|
|
@@ -262,9 +277,10 @@ module Flagnetic
|
|
|
262
277
|
|
|
263
278
|
# after_fork starts a forked child's background thread now rather than
|
|
264
279
|
# on the child's first call, so a worker that has not served a request
|
|
265
|
-
# yet already follows the
|
|
266
|
-
# that built the client and never raises.
|
|
267
|
-
#
|
|
280
|
+
# yet already follows the ruleset stream. It does nothing in the process
|
|
281
|
+
# that built the client and never raises. Nothing calls it by itself:
|
|
282
|
+
# a fork-per-job runner that never evaluates would open a stream per
|
|
283
|
+
# child.
|
|
268
284
|
def after_fork
|
|
269
285
|
ensure_worker unless @closed
|
|
270
286
|
nil
|
|
@@ -283,7 +299,7 @@ module Flagnetic
|
|
|
283
299
|
|
|
284
300
|
private
|
|
285
301
|
|
|
286
|
-
def now =
|
|
302
|
+
def now = @timing.now.call
|
|
287
303
|
|
|
288
304
|
def init_state
|
|
289
305
|
@mutex = Mutex.new
|
|
@@ -303,6 +319,8 @@ module Flagnetic
|
|
|
303
319
|
@once = {}
|
|
304
320
|
@unsupported_logged = {}
|
|
305
321
|
@invalid_logged = {}
|
|
322
|
+
@deprecations_mutex = Mutex.new
|
|
323
|
+
@deprecations_logged = Set.new
|
|
306
324
|
@pid = Process.pid
|
|
307
325
|
@closed = false
|
|
308
326
|
end
|
|
@@ -337,7 +355,7 @@ module Flagnetic
|
|
|
337
355
|
def start_online(sdk_key, base_url, store:, stream:, platform:)
|
|
338
356
|
@stream_enabled = stream
|
|
339
357
|
@transport = Transport.new(sdk_key: sdk_key, base_url: base_url, platform: platform,
|
|
340
|
-
timeout: @timing.request_timeout)
|
|
358
|
+
timeout: @timing.request_timeout, deprecated: method(:deprecation_seen))
|
|
341
359
|
build_reporters(@transport, nil)
|
|
342
360
|
@store = store && FileStore.new(store, sdk_key)
|
|
343
361
|
load_store if @store
|
|
@@ -362,6 +380,16 @@ module Flagnetic
|
|
|
362
380
|
app_version: @app_version, wake: -> { @worker&.wake })
|
|
363
381
|
end
|
|
364
382
|
|
|
383
|
+
# deprecation_seen logs a Deprecation header once per operation: the
|
|
384
|
+
# client lives as long as the process, so this is once per operation
|
|
385
|
+
# and process. The header is passed on as it came, with the Sunset when
|
|
386
|
+
# there is one, and the call is never refused for it.
|
|
387
|
+
def deprecation_seen(operation, header, sunset)
|
|
388
|
+
return unless @deprecations_mutex.synchronize { @deprecations_logged.add?(operation) }
|
|
389
|
+
|
|
390
|
+
log(:warn, :operation_deprecated, operation: operation, deprecation: header, **(sunset ? { sunset: sunset } : {}))
|
|
391
|
+
end
|
|
392
|
+
|
|
365
393
|
# log_hook adapts Client#log's keyword arguments to the (level, event,
|
|
366
394
|
# fields) callable Exposures and Summaries expect.
|
|
367
395
|
def log_hook(level, event, fields) = log(level, event, **fields)
|
|
@@ -474,7 +502,8 @@ module Flagnetic
|
|
|
474
502
|
end
|
|
475
503
|
|
|
476
504
|
def base(loaded, **fields)
|
|
477
|
-
Detail.new(ruleset_version: loaded&.ruleset&.version, received_at: loaded&.received_at,
|
|
505
|
+
Detail.new(ruleset_version: loaded&.ruleset&.version, received_at: loaded&.received_at,
|
|
506
|
+
stage: loaded ? loaded.stage : @stage, **fields)
|
|
478
507
|
end
|
|
479
508
|
|
|
480
509
|
def fallback(loaded, default, code)
|
|
@@ -517,6 +546,16 @@ module Flagnetic
|
|
|
517
546
|
end
|
|
518
547
|
end
|
|
519
548
|
|
|
549
|
+
# closed_for_events? tells whether an exposure or alias would only sit
|
|
550
|
+
# in a queue nothing sends any more; the first one after close is
|
|
551
|
+
# logged and none is recorded.
|
|
552
|
+
def closed_for_events?
|
|
553
|
+
return false unless @closed && @exposures && !@exposures.offline?
|
|
554
|
+
|
|
555
|
+
once(%i[exposure_skipped closed]) { log(:warn, :exposure_skipped, cause: "closed") }
|
|
556
|
+
true
|
|
557
|
+
end
|
|
558
|
+
|
|
520
559
|
def once(key)
|
|
521
560
|
first = @mutex.synchronize { @once.key?(key) ? false : (@once[key] = true) }
|
|
522
561
|
yield if first
|
|
@@ -538,20 +577,33 @@ module Flagnetic
|
|
|
538
577
|
end
|
|
539
578
|
|
|
540
579
|
ensure_worker
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
log(:warn, :override_refused, flag: key, reason: "protected", environment: loaded.ruleset.environment.key)
|
|
544
|
-
raise LocalOverrideRefused, "local override of #{key.inspect} refused: the environment " \
|
|
545
|
-
"#{loaded.ruleset.environment.key.inspect} is protected"
|
|
546
|
-
end
|
|
547
|
-
flag = loaded&.ruleset&.flag(key)
|
|
580
|
+
refuse_protected(key, @loaded)
|
|
581
|
+
flag = @loaded&.ruleset&.flag(key)
|
|
548
582
|
type = flag ? flag.type : Client.__send__(:type_of, value)
|
|
549
583
|
normalized = LocalOverrides.__send__(:normalize, type, value)
|
|
550
|
-
|
|
584
|
+
# Looked at again under the mutex a swap takes before it clears the
|
|
585
|
+
# overrides: one stored after a swap to a protected ruleset cleared
|
|
586
|
+
# them would be served once the environment is unprotected.
|
|
587
|
+
refused = @mutex.synchronize do
|
|
588
|
+
held = @loaded
|
|
589
|
+
next held if held&.ruleset&.protected?
|
|
590
|
+
|
|
591
|
+
@overrides = @overrides.merge(key => [type, normalized].freeze).freeze
|
|
592
|
+
nil
|
|
593
|
+
end
|
|
594
|
+
refuse_protected(key, refused)
|
|
551
595
|
log(:warn, :override_set, flag: key)
|
|
552
596
|
fire_change([key])
|
|
553
597
|
end
|
|
554
598
|
|
|
599
|
+
def refuse_protected(key, loaded)
|
|
600
|
+
return unless loaded&.ruleset&.protected?
|
|
601
|
+
|
|
602
|
+
log(:warn, :override_refused, flag: key, reason: "protected", environment: loaded.ruleset.environment.key)
|
|
603
|
+
raise LocalOverrideRefused, "local override of #{key.inspect} refused: the environment " \
|
|
604
|
+
"#{loaded.ruleset.environment.key.inspect} is protected"
|
|
605
|
+
end
|
|
606
|
+
|
|
555
607
|
def remove_local_overrides(keys)
|
|
556
608
|
removed = @mutex.synchronize do
|
|
557
609
|
gone = keys.nil? ? @overrides.keys : keys & @overrides.keys
|
data/lib/flagnetic/detail.rb
CHANGED
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
module Flagnetic
|
|
4
4
|
# REASONS are the evaluation reasons a Detail carries. The evaluator
|
|
5
|
-
# produces the first
|
|
6
|
-
# fallback.
|
|
7
|
-
#
|
|
8
|
-
REASONS = %i[rule rollout experiment override prerequisite_failed
|
|
5
|
+
# produces the first seven; the SDK produces local_override and
|
|
6
|
+
# fallback. An evaluator error serves the built-in default with reason
|
|
7
|
+
# fallback, so no Detail carries error.
|
|
8
|
+
REASONS = %i[rule rollout experiment override prerequisite_failed off fallthrough local_override
|
|
9
9
|
fallback].freeze
|
|
10
10
|
|
|
11
11
|
# STAGES are the steps of the fallback chain. built_in: no ruleset was
|
|
@@ -15,11 +15,11 @@ module Flagnetic
|
|
|
15
15
|
# included. An offline client is always fresh once its document loads.
|
|
16
16
|
STAGES = %i[built_in last_good fresh].freeze
|
|
17
17
|
|
|
18
|
-
# ERROR_CODES say why a Detail has reason fallback: the evaluator's
|
|
18
|
+
# ERROR_CODES say why a Detail has reason fallback: the evaluator's three,
|
|
19
19
|
# then type_mismatch (the flag's type differs from the getter's),
|
|
20
20
|
# no_ruleset (stage built_in) and general (an internal failure caught at
|
|
21
21
|
# the API boundary).
|
|
22
|
-
ERROR_CODES = %i[flag_not_found
|
|
22
|
+
ERROR_CODES = %i[flag_not_found prerequisite_cycle inconsistent_ruleset type_mismatch no_ruleset
|
|
23
23
|
general].freeze
|
|
24
24
|
|
|
25
25
|
# Detail is a served value and why it was served.
|
|
@@ -7,10 +7,11 @@ module Flagnetic
|
|
|
7
7
|
# ruleset, compiled once, and what the ruleset holds that this evaluator
|
|
8
8
|
# does not know.
|
|
9
9
|
class Index
|
|
10
|
-
# invalid_serves marks, by rule index, the
|
|
11
|
-
# break the invariants every
|
|
12
|
-
# Compiler#valid_experiment?), so
|
|
13
|
-
#
|
|
10
|
+
# invalid_serves marks, by rule index, the rollout and experiment
|
|
11
|
+
# serves that break the invariants every such serve holds (see
|
|
12
|
+
# Compiler#valid_rollout? and Compiler#valid_experiment?), so
|
|
13
|
+
# evaluation reaching one answers inconsistent_ruleset without
|
|
14
|
+
# checking them again.
|
|
14
15
|
CompiledFlag = Struct.new(:flag, :variations, :rules, :invalid_serves)
|
|
15
16
|
# CompiledCondition is a condition prepared once at decode time. error
|
|
16
17
|
# is set when it cannot be evaluated against this document; evaluating
|
|
@@ -78,7 +79,10 @@ module Flagnetic
|
|
|
78
79
|
def flag(flag)
|
|
79
80
|
variations = flag.variations.to_h { |v| [v.key, v.value] }.freeze
|
|
80
81
|
rules = flag.rules.map { |r| r.conditions.map { |c| compile(c) }.freeze }.freeze
|
|
81
|
-
invalid_serves = flag.rules.map
|
|
82
|
+
invalid_serves = flag.rules.map do |r|
|
|
83
|
+
(r.serve.kind == "rollout" && !valid_rollout?(r.serve)) ||
|
|
84
|
+
(r.serve.kind == "experiment" && !valid_experiment?(r.serve, variations))
|
|
85
|
+
end
|
|
82
86
|
Index::CompiledFlag.new(flag, variations, rules, invalid_serves.freeze).freeze
|
|
83
87
|
end
|
|
84
88
|
|
|
@@ -123,6 +127,13 @@ module Flagnetic
|
|
|
123
127
|
found << compiled.error if compiled.error && !compiled.unsupported && !found.include?(compiled.error)
|
|
124
128
|
end
|
|
125
129
|
|
|
130
|
+
# valid_rollout? reports whether a rollout serve holds what bucketing
|
|
131
|
+
# a unit relies on: a unit type and a salt, and a percentage within 0
|
|
132
|
+
# to 10000. The variation is checked when it is served.
|
|
133
|
+
def valid_rollout?(serve)
|
|
134
|
+
!serve.unit_type.empty? && !serve.salt.empty? && (0..BUCKETS).cover?(serve.percentage)
|
|
135
|
+
end
|
|
136
|
+
|
|
126
137
|
# valid_experiment? reports whether an experiment serve holds what
|
|
127
138
|
# assigning a unit to a variation relies on: an experiment key, a unit
|
|
128
139
|
# type and both salts; a traffic allocation within 0 to 10000; and at
|
|
@@ -180,6 +191,11 @@ module Flagnetic
|
|
|
180
191
|
type = types[cond.attribute]
|
|
181
192
|
return invalid(cond, "attribute #{cond.attribute.inspect} is not declared") unless type
|
|
182
193
|
|
|
194
|
+
unless Operators.known_type?(type)
|
|
195
|
+
return invalid(cond, "attribute #{cond.attribute.inspect}: unknown attribute type #{type.inspect}",
|
|
196
|
+
construct(:attribute_type, type))
|
|
197
|
+
end
|
|
198
|
+
|
|
183
199
|
match = Operators.compile(type, cond.op, cond.value)
|
|
184
200
|
Index::CompiledCondition.new(cond.kind, nil, cond.attribute, units.key?(cond.attribute), match).freeze
|
|
185
201
|
rescue Operators::Error => e
|
|
@@ -260,7 +276,11 @@ module Flagnetic
|
|
|
260
276
|
r = serve(cf, o.variation, reason: :override, override_influenced: true)
|
|
261
277
|
return r if r.reason == :error
|
|
262
278
|
|
|
279
|
+
# The shadow runs while the flag is still on the prerequisite path, so
|
|
280
|
+
# what it memoizes through a cycle must not outlive it.
|
|
281
|
+
saved = @memo.dup
|
|
263
282
|
shadow = body(cf)
|
|
283
|
+
@memo = saved
|
|
264
284
|
return r unless shadow.reason == :experiment
|
|
265
285
|
|
|
266
286
|
x = shadow.experiment.to_h.merge(variation: r.variation, override: true)
|
|
@@ -62,6 +62,11 @@ module Flagnetic
|
|
|
62
62
|
|
|
63
63
|
module_function
|
|
64
64
|
|
|
65
|
+
# known_type? reports whether this evaluator knows the attribute type.
|
|
66
|
+
def known_type?(type)
|
|
67
|
+
EXTRACT.key?(type)
|
|
68
|
+
end
|
|
69
|
+
|
|
65
70
|
# check returns why this evaluator cannot apply op with value to an
|
|
66
71
|
# attribute of type, or nil when it can: op must be defined for type
|
|
67
72
|
# and value must have the JSON type op needs. It does not reject what
|
|
@@ -8,8 +8,6 @@ module Flagnetic
|
|
|
8
8
|
# properties, or everything else when negated. It answers membership in
|
|
9
9
|
# constant time for ASCII and in logarithmic time otherwise.
|
|
10
10
|
class CharSet
|
|
11
|
-
attr_reader :ranges
|
|
12
|
-
|
|
13
11
|
def initialize(ranges, props, negated)
|
|
14
12
|
@ranges = ranges.freeze
|
|
15
13
|
@los = ranges.map(&:first).freeze
|
data/lib/flagnetic/eval/types.rb
CHANGED
|
@@ -45,9 +45,9 @@ module Flagnetic
|
|
|
45
45
|
# ERROR_CODES say why a result has reason error.
|
|
46
46
|
ERROR_CODES = %i[flag_not_found prerequisite_cycle inconsistent_ruleset].freeze
|
|
47
47
|
|
|
48
|
-
# Construct is an operator, a condition kind
|
|
49
|
-
# ruleset that this evaluator does not know. kind is
|
|
50
|
-
# :condition_kind or :
|
|
48
|
+
# Construct is an operator, a condition kind, a serve kind or an
|
|
49
|
+
# attribute type of a ruleset that this evaluator does not know. kind is
|
|
50
|
+
# :operator, :condition_kind, :serve_kind or :attribute_type.
|
|
51
51
|
Construct = Struct.new(:kind, :name) do
|
|
52
52
|
def as_json
|
|
53
53
|
{ "kind" => kind.to_s, "name" => name }
|
data/lib/flagnetic/eval.rb
CHANGED
|
@@ -33,6 +33,17 @@ module Flagnetic
|
|
|
33
33
|
# list. Strings compare byte-wise; numbers are IEEE 754
|
|
34
34
|
# doubles; regular expressions follow the policy in Regex. A unit type
|
|
35
35
|
# named as an attribute is a string attribute holding that unit's ID.
|
|
36
|
+
#
|
|
37
|
+
# The public surface is Ruleset (decode, evaluate, evaluate_all,
|
|
38
|
+
# unsupported_rules, invalid_conditions, version), Context, Result,
|
|
39
|
+
# ExperimentDetail, Construct, DecodeError, REASONS and ERROR_CODES.
|
|
40
|
+
# Everything else, the hash, date, version and regular expression
|
|
41
|
+
# machinery and the structs a decoded ruleset is made of, is internal
|
|
42
|
+
# and changes without notice.
|
|
36
43
|
module Eval
|
|
44
|
+
private_constant :Murmur3, :Semver, :Instant, :Regex, :Operators, :Values, :Index, :Compiler, :Evaluation,
|
|
45
|
+
:Document, :UnicodeTables, :Environment, :Attribute, :Segment, :Condition, :Flag, :Variation,
|
|
46
|
+
:Prerequisite, :Override, :Rule, :Serve, :Weight, :BUCKETS, :SCHEMA_VERSION, :SCOPE,
|
|
47
|
+
:CONDITION_KINDS, :SERVE_KINDS
|
|
37
48
|
end
|
|
38
49
|
end
|
|
@@ -127,13 +127,18 @@ module Flagnetic
|
|
|
127
127
|
end
|
|
128
128
|
end
|
|
129
129
|
|
|
130
|
-
# accepted decodes the 202 answer. A body that does not decode
|
|
131
|
-
#
|
|
132
|
-
#
|
|
130
|
+
# accepted decodes the 202 answer. A body that does not decode, or is
|
|
131
|
+
# not an object, leaves the counts unset, and a rejected list that is
|
|
132
|
+
# not a list of objects counts for none: the batch was accepted either
|
|
133
|
+
# way, so nothing is retried.
|
|
133
134
|
def accepted(response)
|
|
134
135
|
json = JSON.parse(response.body.to_s.byteslice(0, MAX_RESULT_BYTES))
|
|
136
|
+
return Outcome.new(kind: :accepted, status: 202, rejected: []) unless json.is_a?(Hash)
|
|
137
|
+
|
|
138
|
+
rejected = json["rejected"]
|
|
139
|
+
rejected = rejected.is_a?(Array) ? rejected.grep(Hash) : []
|
|
135
140
|
Outcome.new(kind: :accepted, status: 202, accepted: json["accepted"], duplicates: json["duplicates"],
|
|
136
|
-
dropped_rows: json["dropped_rows"], rejected:
|
|
141
|
+
dropped_rows: json["dropped_rows"], rejected: rejected)
|
|
137
142
|
rescue JSON::ParserError, TypeError
|
|
138
143
|
Outcome.new(kind: :accepted, status: 202, rejected: [])
|
|
139
144
|
end
|
data/lib/flagnetic/exposures.rb
CHANGED
|
@@ -59,6 +59,10 @@ module Flagnetic
|
|
|
59
59
|
@flushed_at = now
|
|
60
60
|
@revoked_logged = false
|
|
61
61
|
@send_mutex = Mutex.new
|
|
62
|
+
# Events dropped for a full queue since the last flush logged them:
|
|
63
|
+
# an outage fills the queue and every enqueue after it drops one, so
|
|
64
|
+
# the log carries one count per flush instead of one line per event.
|
|
65
|
+
@overflowed = 0
|
|
62
66
|
end
|
|
63
67
|
|
|
64
68
|
# offline? reports whether events go to the Recorder rather than to the
|
|
@@ -99,7 +103,7 @@ module Flagnetic
|
|
|
99
103
|
|
|
100
104
|
# add_alias enqueues an alias event linking two unit IDs.
|
|
101
105
|
def add_alias(from_unit_type, from_unit_id, to_unit_type, to_unit_id)
|
|
102
|
-
t =
|
|
106
|
+
t = wall_now
|
|
103
107
|
enqueue({ "type" => "alias", "event_id" => UUID.v7(time: t), "from_unit_type" => from_unit_type.to_s,
|
|
104
108
|
"from_unit_id" => from_unit_id.to_s, "to_unit_type" => to_unit_type.to_s,
|
|
105
109
|
"to_unit_id" => to_unit_id.to_s, "occurred_at" => EventBatch.format_time(t) })
|
|
@@ -133,6 +137,7 @@ module Flagnetic
|
|
|
133
137
|
def flush_once(budget)
|
|
134
138
|
return true if offline?
|
|
135
139
|
|
|
140
|
+
log_overflowed
|
|
136
141
|
deadline = now + budget
|
|
137
142
|
return true unless wait_for_send_lock(deadline)
|
|
138
143
|
|
|
@@ -168,7 +173,7 @@ module Flagnetic
|
|
|
168
173
|
skipped(key, "repeat")
|
|
169
174
|
return
|
|
170
175
|
end
|
|
171
|
-
t =
|
|
176
|
+
t = wall_now
|
|
172
177
|
coerced = begin
|
|
173
178
|
Eval::Context.__send__(:coerce, context)
|
|
174
179
|
rescue StandardError
|
|
@@ -233,13 +238,21 @@ module Flagnetic
|
|
|
233
238
|
# stability.
|
|
234
239
|
def fingerprint(context)
|
|
235
240
|
c = Eval::Context.__send__(:coerce, context)
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
241
|
+
# A unit ID goes through attribute_token like an attribute value, so
|
|
242
|
+
# an Integer 42 (which is no unit) and the String "42" (which is)
|
|
243
|
+
# stay apart.
|
|
244
|
+
units = c.units.sort.flat_map { |type, id| [part(type), part(attribute_token(id))] }
|
|
245
|
+
attributes = c.attributes.sort.map { |k, v| [part(k.to_s), part(attribute_token(v))] }.flatten
|
|
246
|
+
(units + [part("")] + attributes).join
|
|
239
247
|
rescue StandardError
|
|
240
248
|
context.object_id.to_s
|
|
241
249
|
end
|
|
242
250
|
|
|
251
|
+
# part prefixes a piece with its length, so no choice of pieces can join
|
|
252
|
+
# the same way as another: a separator would let a unit ID holding it
|
|
253
|
+
# collide with two units.
|
|
254
|
+
def part(string) = "#{string.bytesize}:#{string}"
|
|
255
|
+
|
|
243
256
|
def attribute_token(value)
|
|
244
257
|
case value
|
|
245
258
|
when String, Numeric, true, false then value.inspect
|
|
@@ -275,9 +288,7 @@ module Flagnetic
|
|
|
275
288
|
excess.positive? ? @queue.shift(excess).size : 0
|
|
276
289
|
end
|
|
277
290
|
@wake.call
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
log(:warn, :queue_dropped, kind: kind, cause: "queue_full", events: dropped, capacity: @capacity)
|
|
291
|
+
overflowed(dropped)
|
|
281
292
|
end
|
|
282
293
|
|
|
283
294
|
def take = @mutex.synchronize { @queue.dup.tap { @queue.clear } }
|
|
@@ -294,6 +305,17 @@ module Flagnetic
|
|
|
294
305
|
excess = @queue.size - @capacity
|
|
295
306
|
excess.positive? ? @queue.shift(excess).size : 0
|
|
296
307
|
end
|
|
308
|
+
overflowed(dropped)
|
|
309
|
+
end
|
|
310
|
+
|
|
311
|
+
def overflowed(dropped)
|
|
312
|
+
@mutex.synchronize { @overflowed += dropped } if dropped.positive?
|
|
313
|
+
end
|
|
314
|
+
|
|
315
|
+
# log_overflowed reports the events dropped for a full queue since it
|
|
316
|
+
# last did, as one line.
|
|
317
|
+
def log_overflowed
|
|
318
|
+
dropped = @mutex.synchronize { @overflowed.tap { @overflowed = 0 } }
|
|
297
319
|
return unless dropped.positive?
|
|
298
320
|
|
|
299
321
|
log(:warn, :queue_dropped, kind: kind, cause: "queue_full", events: dropped, capacity: @capacity)
|
|
@@ -304,8 +326,11 @@ module Flagnetic
|
|
|
304
326
|
return true if events.empty?
|
|
305
327
|
|
|
306
328
|
batches = EventBatch.pack(events, @transport.identity) { |_, err| report_unserialisable(err) }
|
|
329
|
+
settled = 0
|
|
307
330
|
batches.each_with_index do |group, i|
|
|
331
|
+
settled = i
|
|
308
332
|
result = attempt(group, deadline)
|
|
333
|
+
settled = i + 1
|
|
309
334
|
case result.kind
|
|
310
335
|
when :accepted
|
|
311
336
|
@backoff.reset
|
|
@@ -320,6 +345,13 @@ module Flagnetic
|
|
|
320
345
|
end
|
|
321
346
|
end
|
|
322
347
|
true
|
|
348
|
+
rescue StandardError
|
|
349
|
+
# What was taken and not answered goes back: the queue was emptied
|
|
350
|
+
# for this send, and a failure in reading an answer would otherwise
|
|
351
|
+
# drop every later batch with it. A failure in packing them puts back
|
|
352
|
+
# all that was taken.
|
|
353
|
+
put_back(batches ? batches[settled..].flatten(1) : events.to_a)
|
|
354
|
+
raise
|
|
323
355
|
end
|
|
324
356
|
|
|
325
357
|
# schedule_retry backs off on its own schedule rather than honouring
|
|
@@ -329,7 +361,7 @@ module Flagnetic
|
|
|
329
361
|
def schedule_retry(group, result)
|
|
330
362
|
wait = @backoff.next_delay(cap: @timing.fetch_cap)
|
|
331
363
|
@not_before = now + wait
|
|
332
|
-
|
|
364
|
+
log_events_failed(group, result, wait)
|
|
333
365
|
wait
|
|
334
366
|
end
|
|
335
367
|
|
|
@@ -6,10 +6,12 @@ module Flagnetic
|
|
|
6
6
|
# FallbackChain is the part of Client that holds the ruleset: it loads
|
|
7
7
|
# the store and offline documents, applies each fetch outcome and moves
|
|
8
8
|
# the stage. Every method is private; the background thread calls handle_fetch,
|
|
9
|
-
# held_version and key_revoked.
|
|
9
|
+
# held_version, stream_connected and key_revoked.
|
|
10
10
|
module FallbackChain
|
|
11
|
-
# Loaded is the held ruleset
|
|
12
|
-
|
|
11
|
+
# Loaded is the held ruleset, when it was received and the stage it is
|
|
12
|
+
# held at. The stage is part of it so that a getter, reading it once,
|
|
13
|
+
# never pairs a ruleset with the stage of another.
|
|
14
|
+
Loaded = Struct.new(:ruleset, :received_at, :stage, keyword_init: true)
|
|
13
15
|
|
|
14
16
|
private
|
|
15
17
|
|
|
@@ -22,7 +24,7 @@ module Flagnetic
|
|
|
22
24
|
raise OfflineError, "offline ruleset: #{cause}"
|
|
23
25
|
end
|
|
24
26
|
|
|
25
|
-
swap(ruleset, received_at:
|
|
27
|
+
swap(ruleset, received_at: @timing.wall_now.call, stage: :fresh, source: "offline")
|
|
26
28
|
rescue OfflineError
|
|
27
29
|
raise
|
|
28
30
|
rescue StandardError => e
|
|
@@ -78,11 +80,11 @@ module Flagnetic
|
|
|
78
80
|
# evaluation may have changed, local overrides dropped by a protected
|
|
79
81
|
# environment included.
|
|
80
82
|
def swap(ruleset, received_at:, stage:, source:)
|
|
81
|
-
# The ruleset and its stage change together,
|
|
82
|
-
# without the other.
|
|
83
|
+
# The ruleset and its stage change together, and a getter reads both
|
|
84
|
+
# from the one Loaded, so none sees one without the other.
|
|
83
85
|
previous, previous_stage = @mutex.synchronize do
|
|
84
86
|
p = [@loaded, @stage]
|
|
85
|
-
@loaded = Loaded.new(ruleset: ruleset, received_at: received_at).freeze
|
|
87
|
+
@loaded = Loaded.new(ruleset: ruleset, received_at: received_at, stage: stage).freeze
|
|
86
88
|
@stage = stage
|
|
87
89
|
p
|
|
88
90
|
end
|
|
@@ -133,6 +135,7 @@ module Flagnetic
|
|
|
133
135
|
previous = @mutex.synchronize do
|
|
134
136
|
p = @stage
|
|
135
137
|
@stage = stage
|
|
138
|
+
@loaded = Loaded.new(**@loaded.to_h, stage: stage).freeze if @loaded
|
|
136
139
|
p
|
|
137
140
|
end
|
|
138
141
|
stage_changed(previous, stage)
|
|
@@ -174,7 +177,7 @@ module Flagnetic
|
|
|
174
177
|
held = held_version
|
|
175
178
|
return fetch_failed("version #{ruleset.version} is below the held #{held}") if held && ruleset.version < held
|
|
176
179
|
|
|
177
|
-
changed = swap(ruleset, received_at:
|
|
180
|
+
changed = swap(ruleset, received_at: @timing.wall_now.call, stage: :fresh, source: "fetch")
|
|
178
181
|
succeeded
|
|
179
182
|
persist(json)
|
|
180
183
|
fire_change(changed)
|
|
@@ -198,7 +201,7 @@ module Flagnetic
|
|
|
198
201
|
# failed moves fresh to last_good and marks the held ruleset stale;
|
|
199
202
|
# last_good and built_in stay.
|
|
200
203
|
def failed
|
|
201
|
-
@mutex.synchronize { @stale_since ||=
|
|
204
|
+
@mutex.synchronize { @stale_since ||= @timing.wall_now.call }
|
|
202
205
|
move_to(:last_good) if @stage == :fresh
|
|
203
206
|
end
|
|
204
207
|
|
|
@@ -229,7 +232,7 @@ module Flagnetic
|
|
|
229
232
|
|
|
230
233
|
def stream_connected
|
|
231
234
|
@mutex.synchronize { @once.delete([:key_revoked, "stream"]) }
|
|
232
|
-
log(:info, :
|
|
235
|
+
log(:info, :stream_connected)
|
|
233
236
|
end
|
|
234
237
|
|
|
235
238
|
def persist(json)
|
data/lib/flagnetic/logging.rb
CHANGED
|
@@ -4,14 +4,15 @@ module Flagnetic
|
|
|
4
4
|
# EVENTS are the stable names of log events: alert on them. The fields
|
|
5
5
|
# each carries are listed in the README.
|
|
6
6
|
EVENTS = %i[
|
|
7
|
-
ruleset_loaded fetch_failed
|
|
7
|
+
ruleset_loaded fetch_failed stream_connected stream_dropped stage_changed key_revoked schema_unsupported
|
|
8
8
|
rule_unsupported condition_invalid override_set override_refused local_overrides_allowed type_mismatch
|
|
9
|
-
evaluation_failed listener_failed store_failed worker_failed queue_dropped exposure_skipped
|
|
10
|
-
|
|
9
|
+
evaluation_failed listener_failed store_failed worker_failed queue_dropped exposure_skipped events_failed
|
|
10
|
+
exposures_off client_not_configured operation_deprecated
|
|
11
11
|
].freeze
|
|
12
12
|
|
|
13
13
|
# LEVELS are the log levels, lowest first.
|
|
14
14
|
LEVELS = %i[debug info warn error].freeze
|
|
15
|
+
private_constant :LEVELS
|
|
15
16
|
|
|
16
17
|
# Logging adapts the logger option: a callable receiving
|
|
17
18
|
# (level, event, fields), or a standard library ::Logger (anything
|
data/lib/flagnetic/railtie.rb
CHANGED
|
@@ -71,7 +71,6 @@ module Flagnetic
|
|
|
71
71
|
def boot(app)
|
|
72
72
|
config = app.config.flagnetic
|
|
73
73
|
Flagnetic.client_builder = -> { build(app) }
|
|
74
|
-
Process.singleton_class.prepend(ForkHook) unless Process.singleton_class < ForkHook
|
|
75
74
|
start = config.start.nil? ? !one_off? : config.start
|
|
76
75
|
Flagnetic.client if start
|
|
77
76
|
end
|
|
@@ -85,13 +84,6 @@ module Flagnetic
|
|
|
85
84
|
client
|
|
86
85
|
end
|
|
87
86
|
|
|
88
|
-
# after_fork starts the background thread of a forked child: a Puma
|
|
89
|
-
# or Unicorn worker then follows the change stream before its first
|
|
90
|
-
# request. A client not built yet is left to be built on first use.
|
|
91
|
-
def after_fork
|
|
92
|
-
Flagnetic.client.after_fork if Flagnetic.client?
|
|
93
|
-
end
|
|
94
|
-
|
|
95
87
|
private
|
|
96
88
|
|
|
97
89
|
# new_client constructs the client the configuration describes.
|
|
@@ -148,15 +140,5 @@ module Flagnetic
|
|
|
148
140
|
@one_off || defined?(::Rails::Console) || defined?(::Rails::Command::RunnerCommand) ? true : false
|
|
149
141
|
end
|
|
150
142
|
end
|
|
151
|
-
|
|
152
|
-
# ForkHook runs Railtie.after_fork in every forked child (Ruby 3.1's
|
|
153
|
-
# Process._fork, which every fork goes through).
|
|
154
|
-
module ForkHook
|
|
155
|
-
def _fork
|
|
156
|
-
pid = super
|
|
157
|
-
Railtie.after_fork if pid.zero?
|
|
158
|
-
pid
|
|
159
|
-
end
|
|
160
|
-
end
|
|
161
143
|
end
|
|
162
144
|
end
|
data/lib/flagnetic/reporter.rb
CHANGED
|
@@ -21,7 +21,9 @@ module Flagnetic
|
|
|
21
21
|
|
|
22
22
|
private
|
|
23
23
|
|
|
24
|
-
def now =
|
|
24
|
+
def now = @timing.now.call
|
|
25
|
+
|
|
26
|
+
def wall_now = @timing.wall_now.call
|
|
25
27
|
|
|
26
28
|
# wait_for_send_lock waits for @send_mutex, up to deadline, so a flush
|
|
27
29
|
# bounded by its own budget never blocks on another flush already in
|
|
@@ -74,8 +76,8 @@ module Flagnetic
|
|
|
74
76
|
log(:error, :key_revoked, status: result.status, source: "events")
|
|
75
77
|
end
|
|
76
78
|
|
|
77
|
-
def
|
|
78
|
-
log(:warn, :
|
|
79
|
+
def log_events_failed(group, result, wait)
|
|
80
|
+
log(:warn, :events_failed, kind: kind, events: group.size, retry_in: wait.round(3), status: result.status,
|
|
79
81
|
error: result.error)
|
|
80
82
|
end
|
|
81
83
|
|
data/lib/flagnetic/sse_parser.rb
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
module Flagnetic
|
|
4
|
-
# SSEParser reads the text/event-stream format of the
|
|
4
|
+
# SSEParser reads the text/event-stream format of the ruleset stream by the
|
|
5
5
|
# WHATWG rules: CRLF, LF or CR end a line, even when split between reads;
|
|
6
6
|
# a blank line dispatches the event gathered so far; lines starting with
|
|
7
7
|
# a colon are comments; data lines join with newlines; the last event ID
|
|
@@ -32,8 +32,9 @@ module Flagnetic
|
|
|
32
32
|
@id = nil
|
|
33
33
|
end
|
|
34
34
|
|
|
35
|
-
# feed parses the next bytes of the stream, yielding [:event, Event]
|
|
36
|
-
#
|
|
35
|
+
# feed parses the next bytes of the stream, yielding [:event, Event]
|
|
36
|
+
# and [:comment, text] as they complete. A retry field is read and
|
|
37
|
+
# ignored: the worker backs off on its own schedule.
|
|
37
38
|
def feed(chunk, &)
|
|
38
39
|
bytes = chunk.b
|
|
39
40
|
if @skip_lf && !bytes.empty?
|
|
@@ -84,7 +85,6 @@ module Flagnetic
|
|
|
84
85
|
when "event" then @type = value
|
|
85
86
|
when "data" then append_data(value)
|
|
86
87
|
when "id" then @id = value unless value.include?("\u0000")
|
|
87
|
-
when "retry" then yield :retry, value.to_i if value.match?(/\A\d+\z/)
|
|
88
88
|
end
|
|
89
89
|
end
|
|
90
90
|
|
data/lib/flagnetic/stream.rb
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
require "net/http"
|
|
4
4
|
|
|
5
5
|
module Flagnetic
|
|
6
|
-
# Stream is one request of the
|
|
6
|
+
# Stream is one request of the ruleset stream, read on a thread of its own
|
|
7
7
|
# so that the worker can keep its timers while the stream is quiet. What
|
|
8
8
|
# happens is posted to the worker's inbox as [:stream, id, kind, ...]:
|
|
9
9
|
#
|
|
@@ -51,6 +51,7 @@ module Flagnetic
|
|
|
51
51
|
|
|
52
52
|
def read(http, response)
|
|
53
53
|
status = response.code.to_i
|
|
54
|
+
@transport.note_deprecation("stream", response)
|
|
54
55
|
post(:head, status)
|
|
55
56
|
return unless status == 200
|
|
56
57
|
|
data/lib/flagnetic/summaries.rb
CHANGED
|
@@ -35,7 +35,7 @@ module Flagnetic
|
|
|
35
35
|
@record = record
|
|
36
36
|
@ruleset_version = ruleset_version
|
|
37
37
|
@mutex = Mutex.new
|
|
38
|
-
@wall_start =
|
|
38
|
+
@wall_start = wall_now
|
|
39
39
|
@window_due_since = now
|
|
40
40
|
@current = Hash.new(0)
|
|
41
41
|
@kept = nil
|
|
@@ -95,7 +95,7 @@ module Flagnetic
|
|
|
95
95
|
@mutex.synchronize do
|
|
96
96
|
@current = Hash.new(0)
|
|
97
97
|
@kept = nil
|
|
98
|
-
@wall_start =
|
|
98
|
+
@wall_start = wall_now
|
|
99
99
|
@window_due_since = now
|
|
100
100
|
end
|
|
101
101
|
@backoff.reset
|
|
@@ -110,7 +110,7 @@ module Flagnetic
|
|
|
110
110
|
# report kept unless it began over an hour ago, and returns nil when
|
|
111
111
|
# nothing was evaluated.
|
|
112
112
|
def take_window
|
|
113
|
-
wall_end =
|
|
113
|
+
wall_end = wall_now
|
|
114
114
|
win, kept = @mutex.synchronize do
|
|
115
115
|
window = { start: @wall_start, end: wall_end, counts: @current }
|
|
116
116
|
held = @kept
|
|
@@ -127,7 +127,7 @@ module Flagnetic
|
|
|
127
127
|
def merge_kept(win, kept, wall_end)
|
|
128
128
|
age = wall_end - kept[:start]
|
|
129
129
|
if age > MAX_WINDOW_AGE
|
|
130
|
-
log(:warn, :queue_dropped, kind: kind, rows: kept[:counts].size, cause: "
|
|
130
|
+
log(:warn, :queue_dropped, kind: kind, rows: kept[:counts].size, cause: "window_too_old",
|
|
131
131
|
age: age.round(3))
|
|
132
132
|
return
|
|
133
133
|
end
|
|
@@ -226,7 +226,7 @@ module Flagnetic
|
|
|
226
226
|
end_t = en if end_t.nil? || en > end_t
|
|
227
227
|
e["counts"].each { |r| counts[[r["flag"], r["variation"], r["reason"].to_sym]] += r["count"] }
|
|
228
228
|
end
|
|
229
|
-
{ start: start_t ||
|
|
229
|
+
{ start: start_t || wall_now, end: end_t || wall_now, counts: counts }
|
|
230
230
|
end
|
|
231
231
|
|
|
232
232
|
# schedule_retry honours Retry-After, capped at the ordinary backoff
|
|
@@ -242,7 +242,7 @@ module Flagnetic
|
|
|
242
242
|
@backoff.next_delay(cap: @timing.fetch_cap)
|
|
243
243
|
end
|
|
244
244
|
@not_before = now + wait
|
|
245
|
-
|
|
245
|
+
log_events_failed(group, result, wait)
|
|
246
246
|
wait
|
|
247
247
|
end
|
|
248
248
|
|
data/lib/flagnetic/transport.rb
CHANGED
|
@@ -5,7 +5,7 @@ require "uri"
|
|
|
5
5
|
|
|
6
6
|
module Flagnetic
|
|
7
7
|
# Transport speaks the SDK API under SDK_API_PATH for one server key. Every
|
|
8
|
-
# request, the
|
|
8
|
+
# request, the ruleset stream included, goes through Net::HTTP, so the
|
|
9
9
|
# proxy the process is configured with (the http_proxy, https_proxy and
|
|
10
10
|
# no_proxy environment variables) applies to all of them.
|
|
11
11
|
class Transport
|
|
@@ -29,7 +29,13 @@ module Flagnetic
|
|
|
29
29
|
|
|
30
30
|
attr_reader :stream_uri, :timeout
|
|
31
31
|
|
|
32
|
-
|
|
32
|
+
# deprecated, when given, is called with an operation's name (ruleset,
|
|
33
|
+
# stream or events) and the raw Deprecation and Sunset header
|
|
34
|
+
# values of every answer that carries a Deprecation header; it decides
|
|
35
|
+
# how often to report. A failure of its own never reaches a request.
|
|
36
|
+
def initialize(sdk_key:, base_url:, platform:, timeout:, deprecated: nil, ruleset_limit: RULESET_LIMIT,
|
|
37
|
+
answer_limit: ANSWER_LIMIT)
|
|
38
|
+
@deprecated = deprecated
|
|
33
39
|
@ruleset_limit = ruleset_limit
|
|
34
40
|
@answer_limit = answer_limit
|
|
35
41
|
base = URI(base_url.to_s.chomp("/"))
|
|
@@ -67,6 +73,7 @@ module Flagnetic
|
|
|
67
73
|
h.request(request) do |response|
|
|
68
74
|
status = response.code.to_i
|
|
69
75
|
retry_after = response["Retry-After"]
|
|
76
|
+
note_deprecation("events", response)
|
|
70
77
|
body = begin
|
|
71
78
|
read_body(response, @answer_limit)
|
|
72
79
|
rescue BodyTooLarge
|
|
@@ -93,13 +100,25 @@ module Flagnetic
|
|
|
93
100
|
http_for(@ruleset_uri, @timeout).start do |h|
|
|
94
101
|
h.request(request) do |response|
|
|
95
102
|
status = response.code.to_i
|
|
103
|
+
note_deprecation("ruleset", response)
|
|
96
104
|
body = read_body(response, @ruleset_limit)
|
|
97
105
|
end
|
|
98
106
|
end
|
|
99
107
|
Response.new(status: status, body: body)
|
|
100
108
|
end
|
|
101
109
|
|
|
102
|
-
#
|
|
110
|
+
# note_deprecation reports a Deprecation header on an answer to
|
|
111
|
+
# operation. Every answer to a deprecated operation carries it, errors
|
|
112
|
+
# included, so it is read from the head before the body.
|
|
113
|
+
def note_deprecation(operation, response)
|
|
114
|
+
header = response["Deprecation"] or return
|
|
115
|
+
|
|
116
|
+
@deprecated&.call(operation, header, response["Sunset"])
|
|
117
|
+
rescue StandardError
|
|
118
|
+
nil
|
|
119
|
+
end
|
|
120
|
+
|
|
121
|
+
# stream_request is the ruleset stream's request; Last-Event-ID is the
|
|
103
122
|
# held version, so the platform emits only what is newer. The stream is
|
|
104
123
|
# asked for uncompressed: a compressed one would hold frames back until
|
|
105
124
|
# the compressor flushed.
|
data/lib/flagnetic/version.rb
CHANGED
|
@@ -1,16 +1,18 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
+
# Flagnetic is the Ruby SDK; see lib/flagnetic.rb.
|
|
3
4
|
module Flagnetic
|
|
4
|
-
VERSION = "0.
|
|
5
|
+
VERSION = "0.2.0"
|
|
5
6
|
|
|
6
7
|
# The schema_version range of the documents this SDK reads and the SDK API
|
|
7
8
|
# path it speaks. A ruleset outside the range is a fallback chain failure,
|
|
8
9
|
# logged once as schema_unsupported; every ruleset and events request asks
|
|
9
|
-
# for SCHEMA_VERSION_MAX in Flagnetic-Schema-Version (the
|
|
10
|
+
# for SCHEMA_VERSION_MAX in Flagnetic-Schema-Version (the ruleset stream
|
|
10
11
|
# carries no document). A change to any of these needs a row in
|
|
11
12
|
# docs/sdks/compatibility.md, and a new SDK_API_PATH is a new major
|
|
12
13
|
# VERSION.
|
|
13
14
|
SCHEMA_VERSION_MIN = 1
|
|
14
15
|
SCHEMA_VERSION_MAX = 1
|
|
15
16
|
SDK_API_PATH = "/sdk/v1"
|
|
17
|
+
private_constant :SCHEMA_VERSION_MIN, :SCHEMA_VERSION_MAX, :SDK_API_PATH
|
|
16
18
|
end
|
data/lib/flagnetic/worker.rb
CHANGED
|
@@ -4,7 +4,7 @@ require "json"
|
|
|
4
4
|
|
|
5
5
|
module Flagnetic
|
|
6
6
|
# Worker is a client's background thread. It fetches the ruleset after
|
|
7
|
-
# every (re)connect of the
|
|
7
|
+
# every (re)connect of the ruleset stream, on every event above the held
|
|
8
8
|
# version and on the poll interval, and retries with backoff; it flushes
|
|
9
9
|
# the exposure and alias queue and the evaluation summary window on
|
|
10
10
|
# their intervals. The stream
|
|
@@ -70,7 +70,7 @@ module Flagnetic
|
|
|
70
70
|
|
|
71
71
|
private
|
|
72
72
|
|
|
73
|
-
def now =
|
|
73
|
+
def now = @timing.now.call
|
|
74
74
|
|
|
75
75
|
# supervise runs the loop and starts it again, after a backoff, when it
|
|
76
76
|
# ends by an exception: step already absorbs failures of one turn, so
|
|
@@ -94,8 +94,10 @@ module Flagnetic
|
|
|
94
94
|
def run
|
|
95
95
|
@fetch_backoff = Backoff.new(base: @timing.fetch_base, cap: @timing.fetch_cap)
|
|
96
96
|
@stream_backoff = Backoff.new(base: @timing.stream_base, cap: @timing.stream_cap, random: @random)
|
|
97
|
-
@refused_backoff = Backoff.new(base: @timing.fetch_base, cap: @timing.unauthorized_cap)
|
|
98
97
|
@next_fetch = now
|
|
98
|
+
@stream_stopped = false
|
|
99
|
+
@fetch_successes = 0
|
|
100
|
+
@reopen_after = 0
|
|
99
101
|
@stream_due = @stream_enabled ? now : nil
|
|
100
102
|
@connected = false
|
|
101
103
|
@stable = false
|
|
@@ -198,17 +200,27 @@ module Flagnetic
|
|
|
198
200
|
end
|
|
199
201
|
end
|
|
200
202
|
|
|
201
|
-
# refused leaves a stream the key may not open closed,
|
|
202
|
-
#
|
|
203
|
-
#
|
|
203
|
+
# refused leaves a stream the key may not open closed, with no retry of
|
|
204
|
+
# its own: retrying a refused key on a timer only repeats the refusal.
|
|
205
|
+
# It is tried again after a later fetch succeeds, which shows a
|
|
206
|
+
# restored key or a refusal that was a proxy's. The fetch that follows
|
|
207
|
+
# a refusal at startup shows nothing the refusal did not, so then the
|
|
208
|
+
# one after it reopens the stream.
|
|
204
209
|
def refused(status)
|
|
205
210
|
close_stream
|
|
206
211
|
@client.__send__(:key_revoked, status, "stream")
|
|
207
|
-
@
|
|
212
|
+
stop_stream([@fetch_successes, 1].max)
|
|
213
|
+
end
|
|
214
|
+
|
|
215
|
+
# stop_stream keeps the stream closed until the fetch count passes
|
|
216
|
+
# after.
|
|
217
|
+
def stop_stream(after)
|
|
218
|
+
@stream_due = nil
|
|
219
|
+
@stream_stopped = true
|
|
220
|
+
@reopen_after = after
|
|
208
221
|
end
|
|
209
222
|
|
|
210
223
|
def connected
|
|
211
|
-
@refused_backoff.reset
|
|
212
224
|
@connected = true
|
|
213
225
|
@stable = false
|
|
214
226
|
@client.__send__(:stream_connected)
|
|
@@ -239,7 +251,7 @@ module Flagnetic
|
|
|
239
251
|
cause = "#{cause} before its first heartbeat"
|
|
240
252
|
end
|
|
241
253
|
close_stream
|
|
242
|
-
@client.__send__(:log, error ? :warn : :info, :
|
|
254
|
+
@client.__send__(:log, error ? :warn : :info, :stream_dropped, cause: cause)
|
|
243
255
|
delay = error ? @stream_backoff.next_delay : @random.rand * @timing.close_jitter
|
|
244
256
|
@stream_due = now + delay
|
|
245
257
|
@next_fetch = [@next_fetch, now + @timing.poll_down].min
|
|
@@ -259,6 +271,7 @@ module Flagnetic
|
|
|
259
271
|
when :ok
|
|
260
272
|
@fetch_backoff.reset
|
|
261
273
|
@next_fetch = now + (@connected ? @timing.poll_connected : @timing.poll_down)
|
|
274
|
+
@fetch_successes += 1
|
|
262
275
|
resume_stream
|
|
263
276
|
when :revoked
|
|
264
277
|
@next_fetch = now + @fetch_backoff.next_delay(cap: @timing.unauthorized_cap)
|
|
@@ -283,19 +296,19 @@ module Flagnetic
|
|
|
283
296
|
@event_retry += 1
|
|
284
297
|
end
|
|
285
298
|
|
|
286
|
-
# A revoked key closes the stream
|
|
287
|
-
#
|
|
299
|
+
# A revoked key closes the stream, which stays closed until a later
|
|
300
|
+
# fetch succeeds, as one refused on the stream itself does.
|
|
288
301
|
def close_revoked_stream
|
|
289
302
|
return unless @stream
|
|
290
303
|
|
|
291
304
|
close_stream
|
|
292
|
-
@
|
|
305
|
+
stop_stream(@fetch_successes)
|
|
293
306
|
end
|
|
294
307
|
|
|
295
308
|
def resume_stream
|
|
296
|
-
return unless @
|
|
309
|
+
return unless @stream_stopped && @fetch_successes > @reopen_after
|
|
297
310
|
|
|
298
|
-
@
|
|
311
|
+
@stream_stopped = false
|
|
299
312
|
@stream_due = now if @stream_enabled
|
|
300
313
|
end
|
|
301
314
|
|