nanoflags 0.1.0 → 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/CHANGELOG.md +40 -20
- data/LICENSE +202 -202
- data/NOTICE +4 -4
- data/README.md +206 -152
- data/lib/nanoflags/client.rb +1225 -869
- data/lib/nanoflags/engine/js.rb +531 -531
- data/lib/nanoflags/engine/json.rb +200 -200
- data/lib/nanoflags/engine.rb +407 -407
- data/lib/nanoflags/evaluation_detail.rb +91 -87
- data/lib/nanoflags/http.rb +126 -119
- data/lib/nanoflags/keys.rb +14 -14
- data/lib/nanoflags/session.rb +137 -0
- data/lib/nanoflags/store.rb +59 -59
- data/lib/nanoflags/verify.rb +180 -180
- data/lib/nanoflags/version.rb +6 -6
- data/lib/nanoflags/websocket.rb +411 -0
- data/lib/nanoflags.rb +12 -10
- metadata +9 -6
data/README.md
CHANGED
|
@@ -1,152 +1,206 @@
|
|
|
1
|
-
# nanoflags (Ruby)
|
|
2
|
-
|
|
3
|
-
Server SDK for [NanoFlags](https://nanoflags.io) feature flags. Flags are evaluated **locally and synchronously**
|
|
4
|
-
against a signed, in-memory configuration bundle; a variation call never does I/O and never raises. Background
|
|
5
|
-
threads keep the bundle current: the edge
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
-
|
|
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
|
-
|
|
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
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
`
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
1
|
+
# nanoflags (Ruby)
|
|
2
|
+
|
|
3
|
+
Server SDK for [NanoFlags](https://nanoflags.io) feature flags. Flags are evaluated **locally and synchronously**
|
|
4
|
+
against a signed, in-memory configuration bundle; a variation call never does I/O and never raises. Background
|
|
5
|
+
threads keep the bundle current: the edge pushes each new revision over its live WebSocket (`/v1/live`); while no
|
|
6
|
+
socket can be opened, its event stream (`/v1/stream`) announces revisions that are then fetched with ETag
|
|
7
|
+
revalidation, with polling as the safety net. Test sessions (`x-nanoflags-session`) are resolved per request.
|
|
8
|
+
|
|
9
|
+
- Ruby 3.1+. No runtime dependencies (Net::HTTP, sockets, OpenSSL and JSON from the standard library; the WebSocket
|
|
10
|
+
client is a small built-in RFC 6455 implementation).
|
|
11
|
+
- Native port of the NanoFlags engine, checked against the TypeScript engine with the shared parity fixtures
|
|
12
|
+
(~22 000 cases in `packages/engine/fixtures/parity.json`, plus ~3 500 JavaScript corner cases with V8's error
|
|
13
|
+
messages in `go/internal/testdata/extra.json`): same values, reasons, rollout buckets and traces as every other SDK.
|
|
14
|
+
- Signature verification **on by default** for the hosted edge's embedded key list; unsigned or tampered bundles
|
|
15
|
+
are refused and the last good configuration stays in use.
|
|
16
|
+
- Thread-safe and fork-safe (Puma, Unicorn, Passenger, Resque, Sidekiq Swarm); an OpenFeature provider ships as
|
|
17
|
+
[`nanoflags-openfeature`](../nanoflags-openfeature/README.md).
|
|
18
|
+
|
|
19
|
+
## Install
|
|
20
|
+
|
|
21
|
+
```ruby
|
|
22
|
+
# Gemfile
|
|
23
|
+
gem "nanoflags"
|
|
24
|
+
gem "nanoflags-openfeature" # optional: OpenFeature
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Quickstart
|
|
28
|
+
|
|
29
|
+
```ruby
|
|
30
|
+
require "nanoflags"
|
|
31
|
+
|
|
32
|
+
FLAGS = NanoFlags::Client.new(
|
|
33
|
+
ENV.fetch("NANOFLAGS_SDK_KEY"), # nf_srv_… (server view) or nf_pub_… (client-exposed flags only)
|
|
34
|
+
service: "checkout-api" # shown in "which revision is each service running"
|
|
35
|
+
)
|
|
36
|
+
FLAGS.on_error { |e| Rails.logger.warn("nanoflags #{e.code}: #{e.message}") } # before the first load completes
|
|
37
|
+
FLAGS.wait_until_ready(5) # never raises; true once a configuration is in use
|
|
38
|
+
|
|
39
|
+
user = { key: current_user.id.to_s, plan: current_user.plan, country: "DE" }
|
|
40
|
+
if FLAGS.bool_variation("new-checkout", false, user)
|
|
41
|
+
# …
|
|
42
|
+
end
|
|
43
|
+
accent = FLAGS.string_variation("accent", "blue", user)
|
|
44
|
+
limit = FLAGS.number_variation("rate-limit", 100, user) # Integer for whole numbers, else Float
|
|
45
|
+
layout = FLAGS.json_variation("layout", { "cols" => 3 }, user) # Hash with String keys
|
|
46
|
+
|
|
47
|
+
d = FLAGS.bool_variation_detail("new-checkout", false, user)
|
|
48
|
+
puts d.value, d.reason, d.rule_id, d.revision # true rule_match beta 57
|
|
49
|
+
|
|
50
|
+
FLAGS.on_change { |e| puts "now on r#{e.revision} via #{e.transport}" }
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Create **one client per process** and share it between threads. Each variation takes the flag key, the value to
|
|
54
|
+
serve when the flag cannot be evaluated (no configuration yet, unknown flag, value of another type), and the
|
|
55
|
+
context: a Hash of JSON-like attributes (String or Symbol keys; Time and Date become ISO 8601 strings). `key` is the
|
|
56
|
+
stable identity used for percentage rollouts.
|
|
57
|
+
|
|
58
|
+
### Rails
|
|
59
|
+
|
|
60
|
+
```ruby
|
|
61
|
+
# config/initializers/nanoflags.rb
|
|
62
|
+
Rails.application.config.after_initialize do
|
|
63
|
+
NANOFLAGS = NanoFlags::Client.new(
|
|
64
|
+
Rails.application.credentials.nanoflags_sdk_key,
|
|
65
|
+
service: "web",
|
|
66
|
+
cache_path: Rails.root.join("tmp/nanoflags.json"), # optional: start from the last good bundle
|
|
67
|
+
logger: Rails.logger
|
|
68
|
+
)
|
|
69
|
+
end
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
### Puma, Unicorn, Passenger and other forking servers
|
|
73
|
+
|
|
74
|
+
The client is fork-safe: a forked worker keeps the configuration it inherited (it can evaluate immediately) and
|
|
75
|
+
restarts its own background threads (and opens its own live socket; the parent's connection is never touched) on its
|
|
76
|
+
first call; events queued before the fork are sent by the parent only. Cached test sessions are inherited.
|
|
77
|
+
To start the threads as soon as a worker boots, call `NanoFlags::Client.after_fork` from the server's hook:
|
|
78
|
+
|
|
79
|
+
```ruby
|
|
80
|
+
# config/puma.rb
|
|
81
|
+
on_worker_boot { NanoFlags::Client.after_fork }
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
With `preload_app!`, creating the client in the master is fine; pass `start: false` there if the master should not
|
|
85
|
+
open any connection, and start it in each worker: `on_worker_boot { FLAGS.start }` (a client created with
|
|
86
|
+
`start: false` does not start by itself).
|
|
87
|
+
|
|
88
|
+
### Test sessions (`x-nanoflags-session`)
|
|
89
|
+
|
|
90
|
+
A test session, created in the dashboard (**Scenarios → Shared test session**), pins a configuration snapshot and a
|
|
91
|
+
synthetic context to a token (`nf_ts_…`). A service that receives the token in the `x-nanoflags-session` header
|
|
92
|
+
evaluates against that snapshot, with the context `session.context.merge(your_context)`, for that request only.
|
|
93
|
+
Sampled events from a session carry its id. Shared test sessions are part of the Scale plan.
|
|
94
|
+
|
|
95
|
+
```ruby
|
|
96
|
+
# config/application.rb (any Rack app: `use NanoFlags::SessionMiddleware, FLAGS`)
|
|
97
|
+
config.middleware.use NanoFlags::SessionMiddleware, FLAGS # reads x-nanoflags-session, resolves it once per request
|
|
98
|
+
|
|
99
|
+
# a controller
|
|
100
|
+
flags = request.env["nanoflags.flags"] # or NanoFlags.flags_for(FLAGS) where there is no request
|
|
101
|
+
flags.bool_variation("checkout-v2", false, { key: current_user.id }) # session-scoped while the session is active
|
|
102
|
+
flags.active? # false when unknown, expired, revoked or not permitted here
|
|
103
|
+
|
|
104
|
+
# downstream calls join the session ({} outside one, always safe to merge)
|
|
105
|
+
Faraday.get(PRICING_URL, nil, NanoFlags.session_headers)
|
|
106
|
+
|
|
107
|
+
# jobs: pass the token along and resolve it in the worker
|
|
108
|
+
PriceJob.perform_async(order.id, NanoFlags.current_session)
|
|
109
|
+
NanoFlags.with_session(token) { NanoFlags.flags_for(FLAGS).bool_variation("checkout-v2", false, { key: user_id }) }
|
|
110
|
+
|
|
111
|
+
# or directly
|
|
112
|
+
s = FLAGS.session(request.headers["x-nanoflags-session"], service: "checkout-api")
|
|
113
|
+
s.id; s.expires_at; s.revision
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
- `FLAGS.session(token, service:)` asks the edge once per token and service (`GET /v1/session`, the token in
|
|
117
|
+
`X-NanoFlags-Session`, `service` in `X-NanoFlags-Service`, default: the client's `service`) and caches the answer
|
|
118
|
+
until the session expires. Unknown tokens are remembered for 15 s, failed lookups for 3 s (`:session` errors).
|
|
119
|
+
Concurrent requests with the same new token wait for one lookup.
|
|
120
|
+
- It **never raises**. Without an active session the evaluator behaves exactly like the client, so one code path
|
|
121
|
+
serves normal traffic and tests. When a session expires mid-flight, `active?` turns false and evaluations continue on
|
|
122
|
+
the published configuration.
|
|
123
|
+
- The current session lives in fiber storage (`Fiber[]`, inherited by threads and fibers started inside it on Ruby
|
|
124
|
+
3.2+; fiber-local on 3.1). Nothing is stored on the client. The middleware's session ends when `call` returns.
|
|
125
|
+
- A session changes which snapshot and context an evaluation uses. It grants no data access and must not be used for
|
|
126
|
+
authorization. Client keys only receive client-exposed flags, in sessions too. Session bundles are not signed;
|
|
127
|
+
verification does not apply to them. A revoked session keeps working in a process that cached it until it expires.
|
|
128
|
+
|
|
129
|
+
### Sidekiq and other threaded workers
|
|
130
|
+
|
|
131
|
+
Use the same process-wide client from every job; evaluations are lock-free reads of the current bundle. Call
|
|
132
|
+
`FLAGS.close` on shutdown only if you need the final telemetry flush synchronously (an `at_exit` hook does it too).
|
|
133
|
+
|
|
134
|
+
## API
|
|
135
|
+
|
|
136
|
+
| | |
|
|
137
|
+
| --- | --- |
|
|
138
|
+
| `NanoFlags::Client.new(sdk_key, base_url:, service:, poll_interval:, streaming:, live:, live_poll_interval:, live_url:, bootstrap:, cache_path:, store:, events:, verify:, on_change:, on_error:, logger:, start:, http:, request_timeout:)` | the client |
|
|
139
|
+
| `bool_variation` / `string_variation` / `number_variation` / `json_variation(key, default, context = nil)` | typed value |
|
|
140
|
+
| `*_variation_detail(...)` → `NanoFlags::EvaluationDetail` | `value`, `reason` (`rule_match`, `default`, `off`, `flag_not_found`, `error`), `rule_index`, `rule_id`, `in_rollout`, `bucket`, `revision`, `trace`, `error`, `json`, `type_name` |
|
|
141
|
+
| `evaluate(key, default, context)` | engine result without a type check |
|
|
142
|
+
| `all_flags(context)` / `all_flags_detail(context)` | every flag of the loaded configuration (no telemetry) |
|
|
143
|
+
| `wait_until_ready(timeout)` → `true`/`false` | blocks until a configuration is in use or the first load failed |
|
|
144
|
+
| `status` (`"not-ready"` / `"ready"` / `"stale"`), `revision`, `transport` (`:live` / `:stream` / `:poll`), `initialized?`, `last_error` | state |
|
|
145
|
+
| `session(token, service: nil)` → `NanoFlags::SessionEvaluator` | test session: the typed variations, `evaluate`, `active?`, `id`, `expires_at`, `revision` |
|
|
146
|
+
| `NanoFlags::SessionMiddleware`, `NanoFlags.with_session(token) { }`, `.flags_for(client)`, `.current_session`, `.session_headers`, `NanoFlags::SESSION_HEADER` | request-scoped test sessions |
|
|
147
|
+
| `on(:change \| :error \| :status) { … }`, `on_change { … }`, `on_error { … }` → unsubscribe lambda | listeners |
|
|
148
|
+
| `refresh`, `flush`, `close`, `start`, `NanoFlags::Client.after_fork` | revalidate now, send telemetry now, stop, start, restart after fork |
|
|
149
|
+
|
|
150
|
+
`base_url` defaults to the hosted edge `https://edge.nanoflags.io`. Errors are delivered to `on_error` as
|
|
151
|
+
`NanoFlags::Error` with a `code`: `:network`, `:unauthorized`, `:http`, `:invalid_bundle`, `:store`, `:config`,
|
|
152
|
+
`:signature`, `:engine`, `:session`, `:environment_deleted`. Nothing is ever raised from a variation call.
|
|
153
|
+
|
|
154
|
+
## Behaviour
|
|
155
|
+
|
|
156
|
+
- **Fallbacks and staleness.** Until a configuration loads, variations return your default. Once loaded, the last
|
|
157
|
+
good configuration stays in use through network failures (`status` becomes `"stale"`).
|
|
158
|
+
- **Live updates.** The client keeps one WebSocket to `/v1/live` open (subprotocol `nanoflags.v1`, the key in the
|
|
159
|
+
`Authorization` header, never in the URL), the same protocol as the JavaScript, Python, Go and Java SDKs. The edge
|
|
160
|
+
sends the current bundle on connect (`hello`) and every new revision as it is published (`rev`); each pushed bundle
|
|
161
|
+
is verified exactly like a fetched one before it is used (a push that does not verify changes nothing and triggers
|
|
162
|
+
a regular request). A text `ping` every ~30 s detects dead connections; sockets are replaced after ~50 min.
|
|
163
|
+
Reconnects back off 1 s, 2 s, 4 s … up to 5 min. While the socket is healthy, polling only runs every
|
|
164
|
+
`live_poll_interval` (300 s) as a safety net. Close code **4004** means the environment was deleted: the last
|
|
165
|
+
bundle stays in use, `status` becomes `"stale"`, an `:environment_deleted` error is reported and the client stops
|
|
166
|
+
reconnecting (the poll keeps reporting the key). `live: false` skips the socket.
|
|
167
|
+
- **Fallback.** While no socket can be opened (a proxy that refuses upgrades, an older edge), the client keeps
|
|
168
|
+
`GET /v1/stream` open; each `revision` event makes it fetch `/v1/bundle` with `If-None-Match`, verify and swap the
|
|
169
|
+
bundle atomically. A `revoked` event stops the stream (the poll keeps reporting the key as rejected). Polling every
|
|
170
|
+
`poll_interval` (30 s; `0` disables it) catches anything both miss; after failures it retries after 1 s, 2 s, 4 s …
|
|
171
|
+
up to the poll interval. Stream reconnects back off up to 30 s. HTTP and the WebSocket honour `HTTPS_PROXY` /
|
|
172
|
+
`NO_PROXY` (a CONNECT tunnel) and `SSL_CERT_FILE`. `streaming: false` uses polling only.
|
|
173
|
+
- **Signature verification.** Every bundle is checked (Ed25519 over the canonical string, by `kid`) before it can
|
|
174
|
+
replace the current one. With the hosted edge this is on by default with the embedded production keys
|
|
175
|
+
(`NanoFlags::OFFICIAL_SIGNING_KEYS`) and unsigned bundles are refused; a bundle naming an unknown `kid` (key
|
|
176
|
+
rotation) loads `GET /v1/keys` once (at most once a minute). For a self-hosted edge pass
|
|
177
|
+
`verify: { public_keys: [jwk], require: true }` (or `verify: true` to use the edge's `/v1/keys`); `verify: false`
|
|
178
|
+
turns it off. Bundles signed for another environment than the first accepted one are refused. The raw signed bytes
|
|
179
|
+
are hashed exactly as served, never a re-serialisation.
|
|
180
|
+
- **Persistence and bootstrap.** `cache_path: "tmp/flags.json"` keeps the last good bundle (atomic write, mode 0600)
|
|
181
|
+
and restores it on start as `"stale"` until the edge confirms it; a restored copy is verified again and ignored if
|
|
182
|
+
it does not verify. `store:` takes any object with `get` / `set(text)` (`NanoFlags::Store::Cache.new(Rails.cache)`
|
|
183
|
+
shares it through an ActiveSupport cache). `bootstrap:` takes a bundle (Hash or JSON text) to serve immediately.
|
|
184
|
+
- **Engine version.** Bundles produced for a newer evaluation engine (`bundle.engine` > `NanoFlags::Engine::VERSION`)
|
|
185
|
+
are refused (`:engine`) and the current configuration stays in use: upgrade the gem.
|
|
186
|
+
- **Telemetry.** A sampled 10 % of evaluations are sent every 10 s, plus a service report every 60 s. Context
|
|
187
|
+
**values never leave the process** by default: only the names (and value types) of the attributes the flag's rules
|
|
188
|
+
use, e.g. `{"plan" => "string"}`. `events: { redact: ->(ctx) { … } }` customises this; `events: false` turns it off.
|
|
189
|
+
- **Threads.** The bundle is replaced as a single reference, so concurrent evaluations always see one consistent
|
|
190
|
+
revision. Listeners run on the client's background threads. `close` stops everything after a final flush.
|
|
191
|
+
|
|
192
|
+
## Development
|
|
193
|
+
|
|
194
|
+
```sh
|
|
195
|
+
bundle install
|
|
196
|
+
bundle exec rake # unit, parity and local HTTP tests (no key, no network)
|
|
197
|
+
NANOFLAGS_LIVE=1 bundle exec rake # adds read-only checks against the hosted edge (public demo key): bundle, live socket, stream
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
`test/test_parity.rb` runs the shared engine fixtures (`../../packages/engine/fixtures/parity.json` and
|
|
201
|
+
`../../go/internal/testdata/extra.json`, or `NANOFLAGS_PARITY_FIXTURES` / `NANOFLAGS_EXTRA_FIXTURES`).
|
|
202
|
+
|
|
203
|
+
## License
|
|
204
|
+
|
|
205
|
+
Apache License 2.0 — see [LICENSE](LICENSE) and [NOTICE](NOTICE). The NanoFlags name and logo are not covered by
|
|
206
|
+
the license.
|