featurehub-openfeature-node-sdk 0.0.0-stage → 1.0.1
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.
- package/LICENSE +21 -0
- package/README.md +218 -2
- package/dist/index.cjs +199 -0
- package/dist/index.d.cts +105 -0
- package/dist/index.d.ts +105 -0
- package/dist/index.js +179 -0
- package/package.json +69 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2022 FeatureHub
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,219 @@
|
|
|
1
|
-
#
|
|
1
|
+
# FeatureHub OpenFeature Provider — Node.js
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Official [OpenFeature](https://openfeature.dev) provider for [FeatureHub](https://featurehub.io), for Node.js servers.
|
|
4
|
+
|
|
5
|
+
Every OpenFeature resolution is served from the FeatureHub SDK's **local feature repository** — the full feature bundle is streamed, polled or refreshed in the background and evaluated in-memory. There are **no per-flag network calls**.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install featurehub-openfeature-node-sdk @openfeature/server-sdk
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { OpenFeature } from "@openfeature/server-sdk";
|
|
17
|
+
import { FeatureHubProvider } from "featurehub-openfeature-node-sdk";
|
|
18
|
+
|
|
19
|
+
await OpenFeature.setProviderAndWait(
|
|
20
|
+
new FeatureHubProvider({
|
|
21
|
+
host: "https://edge.featurehub.io",
|
|
22
|
+
apiKey: process.env.FEATUREHUB_CLIENT_API_KEY!, // client-evaluated (`*...`) recommended for servers
|
|
23
|
+
}),
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
const client = OpenFeature.getClient();
|
|
27
|
+
const enabled = await client.getBooleanValue("checkout-v2", false, {
|
|
28
|
+
targetingKey: "user-123",
|
|
29
|
+
country: "new_zealand",
|
|
30
|
+
});
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
With `FEATUREHUB_EDGE_URL` and `FEATUREHUB_CLIENT_API_KEY` set, `new FeatureHubProvider()` is enough: see [Environment variables](#environment-variables).
|
|
34
|
+
|
|
35
|
+
If your service evaluates with a single application-wide context, set it **before** registering the provider (via `OpenFeature.setContext`, or by passing it to `setProviderAndWait`): changing the context after registration re-requests the feature bundle for the changed context. Per-request contexts (the normal case for client-evaluated keys) are evaluated locally and are unaffected.
|
|
36
|
+
|
|
37
|
+
## API keys
|
|
38
|
+
|
|
39
|
+
- **Client-evaluated keys** (contain a `*`): the bundle — including rollout strategies — is delivered to the provider and every evaluation runs locally against the supplied context. Use this for services handling many different users; contexts are evaluated per call with no shared state.
|
|
40
|
+
- **Server-evaluated keys** (`default/...`): Edge evaluates the features for one context, which the provider holds for every OpenFeature client in the process, fetching them again when the context changes (honouring `ETag`/`304`). Every code path must use the same context: a resolution for a different context while another context's is in progress fails with `INVALID_CONTEXT`, rather than return the other context's values. If the features for a new context cannot be fetched, the resolution fails with `GENERAL` and the next one tries again. Use a client-evaluated key for services that evaluate for many users.
|
|
41
|
+
|
|
42
|
+
Resolutions report `SPLIT` for a percentage rollout and `TARGETING_MATCH` for any other matched strategy (including one FeatureHub applied for a server-evaluated key), each with the strategy id as `variant`; `STATIC` when no strategy applies; and `DISABLED`, with the code default, for a feature that has no value. A value supplied as a string (by a value interceptor, say) is converted to the type asked for: `"true"` and `"false"` for a boolean, a numeric string for a number. Errors use the standard OpenFeature codes (`FLAG_NOT_FOUND`, `TYPE_MISMATCH`, `PARSE_ERROR`, `INVALID_CONTEXT`, `PROVIDER_NOT_READY`, `PROVIDER_FATAL`). Flag metadata holds the feature's properties, plus `featureVersion` and `featureType`.
|
|
43
|
+
|
|
44
|
+
## Options
|
|
45
|
+
|
|
46
|
+
| Option | Description |
|
|
47
|
+
| --- | --- |
|
|
48
|
+
| `host` | FeatureHub Edge base URL. Defaults to `FEATUREHUB_EDGE_URL`. |
|
|
49
|
+
| `apiKey` | FeatureHub SDK API key (see above). Defaults to `FEATUREHUB_CLIENT_API_KEY`, else `FEATUREHUB_SERVER_API_KEY`. |
|
|
50
|
+
| `transport` | `"streaming"`, `"polling"` or `"passive"`. Without it (or the two options below), the mode comes from the environment, and is streaming if that does not say. |
|
|
51
|
+
| `pollIntervalMs` | REST active polling interval; implies `transport: "polling"`. |
|
|
52
|
+
| `cacheTimeToLiveMs` | REST passive cache TTL; implies `transport: "passive"`. |
|
|
53
|
+
| `waitForReadyMs` | How long `initialize` waits for readiness. Default 10s. |
|
|
54
|
+
| `configFactory` | Build the FeatureHub config yourself, to attach interceptors, stores and usage plugins (see below). |
|
|
55
|
+
|
|
56
|
+
### Environment variables
|
|
57
|
+
|
|
58
|
+
Anything not given in code comes from the environment, setting by setting, as for the FeatureHub Node SDK: `FEATUREHUB_EDGE_URL` for the host; `FEATUREHUB_CLIENT_API_KEY`, or else `FEATUREHUB_SERVER_API_KEY`, for the key; and, when no transport option is given, `FEATUREHUB_CONNECT_TYPE` (`active`, `passive` or `streaming`) with `FEATUREHUB_CONNECT_INTERVAL` (such as `30s`). An empty variable counts as not set. The SDK's other variables (timeouts, streaming retry delays) apply as well.
|
|
59
|
+
|
|
60
|
+
### Stores only
|
|
61
|
+
|
|
62
|
+
With no host and no key, in code or the environment, the provider runs from the features its config's stores supply, such as a local YAML file, and evaluates them locally. Give it a `configFactory` that builds the config with no connection:
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
import { EdgeFeatureHubConfig } from "featurehub-javascript-node-sdk";
|
|
66
|
+
import { LocalYamlFeatureStore, LocalYamlValueInterceptor } from "featurehub-yaml-interceptor";
|
|
67
|
+
|
|
68
|
+
const provider = new FeatureHubProvider({
|
|
69
|
+
configFactory: () => {
|
|
70
|
+
const config = new EdgeFeatureHubConfig();
|
|
71
|
+
new LocalYamlFeatureStore(config);
|
|
72
|
+
config.addValueInterceptor(new LocalYamlValueInterceptor());
|
|
73
|
+
return config;
|
|
74
|
+
},
|
|
75
|
+
});
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Giving only one of the host and key is an error.
|
|
79
|
+
|
|
80
|
+
## Tracking
|
|
81
|
+
|
|
82
|
+
`client.track(name, context, details)` records a FeatureHub named usage event, with the context's attributes and the details, for the usage plugins registered on the config (Segment, say; see [configFactory](#interceptors-stores-and-usage-plugins)). Without a usage plugin it goes nowhere.
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
client.track("checkout-complete", { targetingKey: "user-123" }, { value: 99.95, currency: "NZD" });
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
## Events
|
|
89
|
+
|
|
90
|
+
`PROVIDER_CONFIGURATION_CHANGED` is emitted with the keys of the features that changed: a new version, a feature added, or one deleted or no longer in a full set.
|
|
91
|
+
|
|
92
|
+
If the connection to FeatureHub stops for good once features have arrived (the API key is rejected, or FeatureHub says the environment is stale), the provider emits `PROVIDER_STALE`, once, and keeps resolving from the last features it received. This also happens if the connection stops with the very first response: initialisation succeeds, and `PROVIDER_STALE` follows `PROVIDER_READY`. If the connection is rejected before any features arrive, initialisation fails as `PROVIDER_FATAL`. A server-evaluated key's context change keeps resolving from the previous context's features until the new ones arrive, and emits no event.
|
|
93
|
+
|
|
94
|
+
## Migrating from the FeatureHub Node SDK
|
|
95
|
+
|
|
96
|
+
The provider is built on `featurehub-javascript-node-sdk`, so your features, API keys and rollout strategies carry over unchanged: only the code that reads them changes, from the SDK's API to OpenFeature's. Each feature is evaluated exactly as before.
|
|
97
|
+
|
|
98
|
+
### Setting up
|
|
99
|
+
|
|
100
|
+
Before:
|
|
101
|
+
|
|
102
|
+
```ts
|
|
103
|
+
import { EdgeFeatureHubConfig } from "featurehub-javascript-node-sdk";
|
|
104
|
+
|
|
105
|
+
const fhConfig = new EdgeFeatureHubConfig(); // FEATUREHUB_EDGE_URL and FEATUREHUB_CLIENT_API_KEY
|
|
106
|
+
await fhConfig.init().waitForReady();
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
After:
|
|
110
|
+
|
|
111
|
+
```ts
|
|
112
|
+
import { OpenFeature } from "@openfeature/server-sdk";
|
|
113
|
+
import { FeatureHubProvider } from "featurehub-openfeature-node-sdk";
|
|
114
|
+
|
|
115
|
+
await OpenFeature.setProviderAndWait(new FeatureHubProvider()); // the same variables
|
|
116
|
+
const client = OpenFeature.getClient();
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
| FeatureHub SDK | Provider |
|
|
120
|
+
| --- | --- |
|
|
121
|
+
| `new EdgeFeatureHubConfig(url, apiKey)` | `new FeatureHubProvider({ host, apiKey })`; either may come from the environment, as for the SDK |
|
|
122
|
+
| `new EdgeFeatureHubConfig()` with only stores (a local YAML file, say) | `new FeatureHubProvider({ configFactory })`, the factory attaching the stores ([Stores only](#stores-only)) |
|
|
123
|
+
| `fhConfig.streaming()` | `transport: "streaming"` |
|
|
124
|
+
| `fhConfig.restActive(30000)` | `pollIntervalMs: 30000` |
|
|
125
|
+
| `fhConfig.restPassive(30000)` | `cacheTimeToLiveMs: 30000` |
|
|
126
|
+
| `FEATUREHUB_CONNECT_TYPE`, `FEATUREHUB_CONNECT_INTERVAL` | read as by the SDK, when no transport option is given |
|
|
127
|
+
| `await fhConfig.init().waitForReady()` | `await OpenFeature.setProviderAndWait(provider)`; `waitForReadyMs` sets how long it waits |
|
|
128
|
+
| `fhConfig.close()` | `await OpenFeature.close()` |
|
|
129
|
+
|
|
130
|
+
### Contexts and reading features
|
|
131
|
+
|
|
132
|
+
The SDK builds a context and reads features from it. OpenFeature passes the context with each evaluation, and always returns the default you give when a feature is missing or has no value, where the SDK returns `undefined`.
|
|
133
|
+
|
|
134
|
+
Before:
|
|
135
|
+
|
|
136
|
+
```ts
|
|
137
|
+
const ctx = await fhConfig
|
|
138
|
+
.newContext()
|
|
139
|
+
.userKey("user-123")
|
|
140
|
+
.country(StrategyAttributeCountryName.NewZealand)
|
|
141
|
+
.attributeValue("plan", "enterprise")
|
|
142
|
+
.build();
|
|
143
|
+
|
|
144
|
+
if (ctx.isEnabled("checkout-v2")) {
|
|
145
|
+
const banner = ctx.getString("banner-text") ?? "Welcome";
|
|
146
|
+
}
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
After:
|
|
150
|
+
|
|
151
|
+
```ts
|
|
152
|
+
const context = { targetingKey: "user-123", country: "new_zealand", plan: "enterprise" };
|
|
153
|
+
|
|
154
|
+
if (await client.getBooleanValue("checkout-v2", false, context)) {
|
|
155
|
+
const banner = await client.getStringValue("banner-text", "Welcome", context);
|
|
156
|
+
}
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
| FeatureHub SDK | OpenFeature |
|
|
160
|
+
| --- | --- |
|
|
161
|
+
| `.userKey("user-123")` | `targetingKey: "user-123"` |
|
|
162
|
+
| `.sessionKey(id)` | `session: id` |
|
|
163
|
+
| `.country(...)`, `.device(...)`, `.platform(...)`, `.version(...)` | `country`, `device`, `platform`, `version`, as the enum's string value (`StrategyAttributeCountryName.NewZealand` is `"new_zealand"`) |
|
|
164
|
+
| `.attributeValue("plan", "enterprise")` | `plan: "enterprise"`; a list of strings, numbers, booleans or dates is fine, a nested object is `INVALID_CONTEXT`. Keys other than the well-known ones keep their case, and `fhubWhenActive` is ignored, as only a strategy may set it |
|
|
165
|
+
| a `Date` attribute value | the same `Date` (or a list of them); it is evaluated, and sent to FeatureHub, as UTC to the second |
|
|
166
|
+
| `ctx.isEnabled(key)`, `ctx.getFlag(key)`, `ctx.getBoolean(key)` | `client.getBooleanValue(key, false, context)` |
|
|
167
|
+
| `ctx.getString(key)` | `client.getStringValue(key, default, context)` |
|
|
168
|
+
| `ctx.getNumber(key)` | `client.getNumberValue(key, default, context)` |
|
|
169
|
+
| `ctx.getJson(key)` | `client.getObjectValue(key, default, context)`; the value must be a JSON object |
|
|
170
|
+
| `ctx.getRawJson(key)` | no equivalent: OpenFeature only gives the parsed object |
|
|
171
|
+
| `ctx.recordNamedUsage(name, params)` | `client.track(name, context, params)` ([Tracking](#tracking)) |
|
|
172
|
+
| `ctx.isSet(key)` | `get...Details(...)`: `errorCode` is `FLAG_NOT_FOUND` if the feature does not exist; `reason` is `DISABLED` if it exists with no value |
|
|
173
|
+
| the strategy that matched (`feature(key).getValue().strategyId`) | `details.variant`, with `details.reason` (`SPLIT`, `TARGETING_MATCH` or `STATIC`) |
|
|
174
|
+
| `feature(key).featureProperties` | `details.flagMetadata`, which also holds `featureVersion` and `featureType` |
|
|
175
|
+
| `feature(key).locked` | no equivalent |
|
|
176
|
+
|
|
177
|
+
With a server-evaluated key the SDK fetched features for each context you built. The provider holds a single context, and fetches again only when an evaluation's context differs from the last one. Evaluating a different context while another context's evaluation is in progress fails with `INVALID_CONTEXT`, so a client-evaluated key suits services that evaluate for many users.
|
|
178
|
+
|
|
179
|
+
### Listening for changes
|
|
180
|
+
|
|
181
|
+
| FeatureHub SDK | OpenFeature |
|
|
182
|
+
| --- | --- |
|
|
183
|
+
| `fhConfig.addReadinessListener(...)` | `client.addHandler(ProviderEvents.Ready, ...)`, and `client.providerStatus` |
|
|
184
|
+
| readiness `Failed` | `setProviderAndWait` rejects, and `providerStatus` is `FATAL` |
|
|
185
|
+
| `fhConfig.addConnectionEventListener(...)` | `client.addHandler(ProviderEvents.Stale, ...)` |
|
|
186
|
+
| `feature(key).addListener(...)` | `client.addHandler(ProviderEvents.ConfigurationChanged, (details) => ...)`; `details.flagsChanged` lists the keys, so read the ones you need again |
|
|
187
|
+
|
|
188
|
+
### Interceptors, stores and usage plugins
|
|
189
|
+
|
|
190
|
+
Value interceptors, feature stores and usage plugins are attached to the FeatureHub config, which the provider creates. Pass `configFactory` to create it yourself and attach them. The provider starts it, so do not call `init()`; it applies a transport option if you give one, and otherwise leaves the config's own mode (from the environment, or one you set on it):
|
|
191
|
+
|
|
192
|
+
```ts
|
|
193
|
+
import { EdgeFeatureHubConfig } from "featurehub-javascript-node-sdk";
|
|
194
|
+
import { LocalYamlValueInterceptor } from "featurehub-yaml-interceptor";
|
|
195
|
+
import { RedisSessionStoreUrl } from "featurehub-store-redis";
|
|
196
|
+
import { OpenTelemetryTrackerUsagePlugin } from "featurehub-usage-opentelemetry";
|
|
197
|
+
|
|
198
|
+
const provider = new FeatureHubProvider({
|
|
199
|
+
host: process.env.FEATUREHUB_EDGE_URL!,
|
|
200
|
+
apiKey: process.env.FEATUREHUB_CLIENT_API_KEY!,
|
|
201
|
+
configFactory: ({ host, apiKey }) => {
|
|
202
|
+
const config = new EdgeFeatureHubConfig(host, apiKey);
|
|
203
|
+
config.addValueInterceptor(new LocalYamlValueInterceptor());
|
|
204
|
+
config.addUsagePlugin(new OpenTelemetryTrackerUsagePlugin());
|
|
205
|
+
new RedisSessionStoreUrl("redis://localhost:6379", config);
|
|
206
|
+
return config;
|
|
207
|
+
},
|
|
208
|
+
});
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
A value an interceptor supplies as a string is converted to the type you ask for.
|
|
212
|
+
|
|
213
|
+
### What stays with the SDK
|
|
214
|
+
|
|
215
|
+
Keep using the SDK directly for anything OpenFeature has no place for: the repository itself (raw feature updates, `simpleFeatures()`), a feature's lock, raw JSON, and readiness details beyond the provider's status.
|
|
216
|
+
|
|
217
|
+
## License
|
|
218
|
+
|
|
219
|
+
MIT
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
FeatureHubProvider: () => FeatureHubProvider,
|
|
24
|
+
InvalidContextError: () => import_featurehub_openfeature_common2.InvalidContextError,
|
|
25
|
+
contextSignature: () => import_featurehub_openfeature_common2.contextSignature,
|
|
26
|
+
mapEvaluationContext: () => import_featurehub_openfeature_common2.mapEvaluationContext,
|
|
27
|
+
toContextRecord: () => import_featurehub_openfeature_common2.toContextRecord
|
|
28
|
+
});
|
|
29
|
+
module.exports = __toCommonJS(index_exports);
|
|
30
|
+
|
|
31
|
+
// src/provider.ts
|
|
32
|
+
var import_server_sdk = require("@openfeature/server-sdk");
|
|
33
|
+
var import_featurehub_javascript_node_sdk = require("featurehub-javascript-node-sdk");
|
|
34
|
+
var import_featurehub_openfeature_common = require("featurehub-openfeature-common");
|
|
35
|
+
function environment(name) {
|
|
36
|
+
const value = process.env[name]?.trim();
|
|
37
|
+
return value ? value : void 0;
|
|
38
|
+
}
|
|
39
|
+
var FeatureHubProvider = class extends import_featurehub_openfeature_common.FeatureHubProviderCore {
|
|
40
|
+
metadata = { name: "featurehub" };
|
|
41
|
+
runsOn = "server";
|
|
42
|
+
events = new import_server_sdk.OpenFeatureEventEmitter();
|
|
43
|
+
/**
|
|
44
|
+
* Server-evaluated keys only: the single shared evaluation context, held for
|
|
45
|
+
* the provider's lifetime. Holding exactly one keeps the SDK's internal
|
|
46
|
+
* reference count at 1 and lets the SDK reuse its evaluated bundle.
|
|
47
|
+
*/
|
|
48
|
+
sharedContext;
|
|
49
|
+
/** the context the shared context's features were fetched for */
|
|
50
|
+
builtSignature;
|
|
51
|
+
/** the context being resolved, while `inFlight` resolutions are in progress */
|
|
52
|
+
activeSignature;
|
|
53
|
+
inFlight = 0;
|
|
54
|
+
/** the fetch for `activeSignature`, which every resolution for it waits on */
|
|
55
|
+
building;
|
|
56
|
+
/**
|
|
57
|
+
* Settings not given in code come from the environment, setting by setting (featurehub-protocol.yaml
|
|
58
|
+
* providers.environment_variables): FEATUREHUB_EDGE_URL, then FEATUREHUB_CLIENT_API_KEY or else
|
|
59
|
+
* FEATUREHUB_SERVER_API_KEY, and, with no transport option, the node SDK's mode
|
|
60
|
+
* (FEATUREHUB_CONNECT_TYPE and FEATUREHUB_CONNECT_INTERVAL; streaming when neither is set).
|
|
61
|
+
*/
|
|
62
|
+
constructor(options = {}) {
|
|
63
|
+
super("FeatureHubProvider", options, {
|
|
64
|
+
host: options.host ?? environment("FEATUREHUB_EDGE_URL"),
|
|
65
|
+
apiKey: options.apiKey ?? environment("FEATUREHUB_CLIENT_API_KEY") ?? environment("FEATUREHUB_SERVER_API_KEY")
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
get eventSink() {
|
|
69
|
+
return this.events;
|
|
70
|
+
}
|
|
71
|
+
/** none: the node SDK's own, from FEATUREHUB_CONNECT_TYPE / FEATUREHUB_CONNECT_INTERVAL, else streaming */
|
|
72
|
+
get defaultTransport() {
|
|
73
|
+
return void 0;
|
|
74
|
+
}
|
|
75
|
+
createConfig() {
|
|
76
|
+
return new import_featurehub_javascript_node_sdk.EdgeFeatureHubConfig(this.host, this.apiKey);
|
|
77
|
+
}
|
|
78
|
+
async initialize(context) {
|
|
79
|
+
const deadline = Date.now() + this.waitForReadyMs;
|
|
80
|
+
const record = this.clientEval ? void 0 : (0, import_featurehub_openfeature_common.toContextRecord)(context);
|
|
81
|
+
const cfg = this.startConfig();
|
|
82
|
+
if (record !== void 0) {
|
|
83
|
+
this.sharedContext = cfg.context(record);
|
|
84
|
+
await this.within(deadline, this.sharedContext.build());
|
|
85
|
+
}
|
|
86
|
+
await this.awaitReady(cfg, Math.max(0, deadline - Date.now()));
|
|
87
|
+
if (record !== void 0) {
|
|
88
|
+
this.builtSignature = (0, import_featurehub_openfeature_common.contextSignature)(context);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
async onClose() {
|
|
92
|
+
await super.onClose();
|
|
93
|
+
this.sharedContext = void 0;
|
|
94
|
+
this.builtSignature = void 0;
|
|
95
|
+
this.activeSignature = void 0;
|
|
96
|
+
this.building = void 0;
|
|
97
|
+
}
|
|
98
|
+
async resolveBooleanEvaluation(flagKey, defaultValue, context, logger) {
|
|
99
|
+
return this.resolve(flagKey, context, "boolean", defaultValue, logger);
|
|
100
|
+
}
|
|
101
|
+
async resolveStringEvaluation(flagKey, defaultValue, context, logger) {
|
|
102
|
+
return this.resolve(flagKey, context, "string", defaultValue, logger);
|
|
103
|
+
}
|
|
104
|
+
async resolveNumberEvaluation(flagKey, defaultValue, context, logger) {
|
|
105
|
+
return this.resolve(flagKey, context, "number", defaultValue, logger);
|
|
106
|
+
}
|
|
107
|
+
async resolveObjectEvaluation(flagKey, defaultValue, context, logger) {
|
|
108
|
+
return this.resolve(flagKey, context, "object", defaultValue, logger);
|
|
109
|
+
}
|
|
110
|
+
resolve(flagKey, context, kind, defaultValue, logger) {
|
|
111
|
+
return this.resolveAsync(
|
|
112
|
+
flagKey,
|
|
113
|
+
kind,
|
|
114
|
+
defaultValue,
|
|
115
|
+
logger,
|
|
116
|
+
() => this.evaluate(flagKey, context)
|
|
117
|
+
);
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Captures a consistent evaluation of a flag.
|
|
121
|
+
*
|
|
122
|
+
* - client-evaluated keys: a fresh local context is created per resolution
|
|
123
|
+
* (no shared state) and the flag is evaluated in-memory.
|
|
124
|
+
* - server-evaluated keys: the one shared context is fetched again from Edge
|
|
125
|
+
* when the OpenFeature context changes, and the flag read once its features
|
|
126
|
+
* have arrived. While any resolution is in progress only its context may be
|
|
127
|
+
* resolved: another is refused, as it would be given the first's values.
|
|
128
|
+
*/
|
|
129
|
+
async evaluate(flagKey, context) {
|
|
130
|
+
if (this.clientEval) {
|
|
131
|
+
const ctx = this.config.context((0, import_featurehub_openfeature_common.toContextRecord)(context));
|
|
132
|
+
return (0, import_featurehub_openfeature_common.captureFeature)(ctx.feature(flagKey));
|
|
133
|
+
}
|
|
134
|
+
const signature = (0, import_featurehub_openfeature_common.contextSignature)(context);
|
|
135
|
+
if (this.inFlight > 0 && signature !== this.activeSignature) {
|
|
136
|
+
throw new import_featurehub_openfeature_common.ContextConflictError();
|
|
137
|
+
}
|
|
138
|
+
this.inFlight++;
|
|
139
|
+
this.activeSignature = signature;
|
|
140
|
+
try {
|
|
141
|
+
if (signature !== this.builtSignature) {
|
|
142
|
+
this.building ??= this.fetchContext(context, signature).finally(() => {
|
|
143
|
+
this.building = void 0;
|
|
144
|
+
});
|
|
145
|
+
await this.building;
|
|
146
|
+
}
|
|
147
|
+
return (0, import_featurehub_openfeature_common.captureFeature)(this.sharedContext.feature(flagKey));
|
|
148
|
+
} finally {
|
|
149
|
+
this.inFlight--;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Fetches the features for a new context into the shared context. Until they arrive the repository holds
|
|
154
|
+
* the previous context's, so a fetch that fails, or does not finish in time, fails the resolution, and the
|
|
155
|
+
* next resolution for the context tries again.
|
|
156
|
+
*/
|
|
157
|
+
async fetchContext(context, signature) {
|
|
158
|
+
const deadline = Date.now() + this.waitForReadyMs;
|
|
159
|
+
const cfg = this.config;
|
|
160
|
+
const ctx = this.sharedContext ?? cfg.context({});
|
|
161
|
+
this.sharedContext = ctx;
|
|
162
|
+
ctx.userKey(void 0);
|
|
163
|
+
ctx.clear();
|
|
164
|
+
ctx.attributes = (0, import_featurehub_openfeature_common.toContextRecord)(context);
|
|
165
|
+
await this.within(deadline, ctx.build());
|
|
166
|
+
const readiness = await cfg.waitForReady(Math.max(0, deadline - Date.now()));
|
|
167
|
+
if (readiness !== import_featurehub_javascript_node_sdk.Readyness.Ready) {
|
|
168
|
+
throw new Error(
|
|
169
|
+
`FeatureHub could not fetch the features for the new context within ${this.waitForReadyMs}ms (readiness: ${readiness}).`
|
|
170
|
+
);
|
|
171
|
+
}
|
|
172
|
+
this.builtSignature = signature;
|
|
173
|
+
}
|
|
174
|
+
/** waits for the work, or until the deadline, whichever is first; the readiness check that follows decides */
|
|
175
|
+
async within(deadline, work) {
|
|
176
|
+
let timer;
|
|
177
|
+
try {
|
|
178
|
+
await Promise.race([
|
|
179
|
+
work,
|
|
180
|
+
new Promise((resolve) => {
|
|
181
|
+
timer = setTimeout(resolve, Math.max(0, deadline - Date.now()));
|
|
182
|
+
})
|
|
183
|
+
]);
|
|
184
|
+
} finally {
|
|
185
|
+
clearTimeout(timer);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
// src/index.ts
|
|
191
|
+
var import_featurehub_openfeature_common2 = require("featurehub-openfeature-common");
|
|
192
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
193
|
+
0 && (module.exports = {
|
|
194
|
+
FeatureHubProvider,
|
|
195
|
+
InvalidContextError,
|
|
196
|
+
contextSignature,
|
|
197
|
+
mapEvaluationContext,
|
|
198
|
+
toContextRecord
|
|
199
|
+
});
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { Provider, ProviderMetadata, OpenFeatureEventEmitter, EvaluationContext, Logger, ResolutionDetails, JsonValue } from '@openfeature/server-sdk';
|
|
2
|
+
import { FeatureHubConfig } from 'featurehub-javascript-node-sdk';
|
|
3
|
+
import { FeatureHubProviderCore, BaseProviderOptions, ProviderEventSink, Transport } from 'featurehub-openfeature-common';
|
|
4
|
+
export { ContextAttribute, InvalidContextError, MappedContext, contextSignature, mapEvaluationContext, toContextRecord } from 'featurehub-openfeature-common';
|
|
5
|
+
|
|
6
|
+
interface FeatureHubProviderOptions extends BaseProviderOptions<FeatureHubProviderOptions> {
|
|
7
|
+
/**
|
|
8
|
+
* Base URL of FeatureHub Edge, e.g. `https://edge.featurehub.io` or `http://localhost:8553`. Defaults to
|
|
9
|
+
* `FEATUREHUB_EDGE_URL`.
|
|
10
|
+
*/
|
|
11
|
+
host?: string;
|
|
12
|
+
/**
|
|
13
|
+
* A FeatureHub SDK API key for the environment.
|
|
14
|
+
*
|
|
15
|
+
* - **client-evaluated keys** (containing `*`): the feature bundle (including
|
|
16
|
+
* rollout strategies) is streamed/polled to the provider and every
|
|
17
|
+
* evaluation is performed locally against the supplied context. This is
|
|
18
|
+
* the recommended mode for Node servers handling many different users.
|
|
19
|
+
* - **server-evaluated keys** (`default/...`): Edge evaluates the features
|
|
20
|
+
* for one context, which the provider holds for every OpenFeature client
|
|
21
|
+
* in the process. When the context changes, the features are fetched again
|
|
22
|
+
* for the new one. A resolution for a different context while another
|
|
23
|
+
* context's is in progress fails with INVALID_CONTEXT, rather than give
|
|
24
|
+
* either the other's values: use the same context everywhere, or a
|
|
25
|
+
* client-evaluated key for many users at once.
|
|
26
|
+
*
|
|
27
|
+
* Defaults to `FEATUREHUB_CLIENT_API_KEY`, else `FEATUREHUB_SERVER_API_KEY`. With no host and no key
|
|
28
|
+
* (in code or the environment), a `configFactory` can supply a config whose features come from stores.
|
|
29
|
+
*/
|
|
30
|
+
apiKey?: string;
|
|
31
|
+
/** How long `initialize` (and context changes) wait for readiness. Default 10s. */
|
|
32
|
+
waitForReadyMs?: number;
|
|
33
|
+
/**
|
|
34
|
+
* Build the FeatureHub config yourself, to attach value interceptors, feature stores and usage plugins.
|
|
35
|
+
* It is given the options with `host` and `apiKey` as resolved (from the environment if not in code).
|
|
36
|
+
*/
|
|
37
|
+
configFactory?: (options: FeatureHubProviderOptions) => FeatureHubConfig;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Official OpenFeature provider for FeatureHub (Node.js).
|
|
41
|
+
*
|
|
42
|
+
* The provider holds no evaluation logic of its own: it drives a
|
|
43
|
+
* [FeatureHubConfig]{@link FeatureHubConfig}, which keeps a local repository
|
|
44
|
+
* of the entire feature bundle up to date (streaming, polling or passive
|
|
45
|
+
* refresh), and every OpenFeature resolution is served from that local
|
|
46
|
+
* repository — never with a per-flag network call.
|
|
47
|
+
*/
|
|
48
|
+
declare class FeatureHubProvider extends FeatureHubProviderCore<FeatureHubProviderOptions> implements Provider {
|
|
49
|
+
readonly metadata: ProviderMetadata;
|
|
50
|
+
readonly runsOn: "server";
|
|
51
|
+
readonly events: OpenFeatureEventEmitter;
|
|
52
|
+
/**
|
|
53
|
+
* Server-evaluated keys only: the single shared evaluation context, held for
|
|
54
|
+
* the provider's lifetime. Holding exactly one keeps the SDK's internal
|
|
55
|
+
* reference count at 1 and lets the SDK reuse its evaluated bundle.
|
|
56
|
+
*/
|
|
57
|
+
private sharedContext?;
|
|
58
|
+
/** the context the shared context's features were fetched for */
|
|
59
|
+
private builtSignature;
|
|
60
|
+
/** the context being resolved, while `inFlight` resolutions are in progress */
|
|
61
|
+
private activeSignature;
|
|
62
|
+
private inFlight;
|
|
63
|
+
/** the fetch for `activeSignature`, which every resolution for it waits on */
|
|
64
|
+
private building;
|
|
65
|
+
/**
|
|
66
|
+
* Settings not given in code come from the environment, setting by setting (featurehub-protocol.yaml
|
|
67
|
+
* providers.environment_variables): FEATUREHUB_EDGE_URL, then FEATUREHUB_CLIENT_API_KEY or else
|
|
68
|
+
* FEATUREHUB_SERVER_API_KEY, and, with no transport option, the node SDK's mode
|
|
69
|
+
* (FEATUREHUB_CONNECT_TYPE and FEATUREHUB_CONNECT_INTERVAL; streaming when neither is set).
|
|
70
|
+
*/
|
|
71
|
+
constructor(options?: FeatureHubProviderOptions);
|
|
72
|
+
protected get eventSink(): ProviderEventSink;
|
|
73
|
+
/** none: the node SDK's own, from FEATUREHUB_CONNECT_TYPE / FEATUREHUB_CONNECT_INTERVAL, else streaming */
|
|
74
|
+
protected get defaultTransport(): Transport | undefined;
|
|
75
|
+
protected createConfig(): FeatureHubConfig;
|
|
76
|
+
initialize(context?: EvaluationContext): Promise<void>;
|
|
77
|
+
onClose(): Promise<void>;
|
|
78
|
+
resolveBooleanEvaluation(flagKey: string, defaultValue: boolean, context: EvaluationContext, logger: Logger): Promise<ResolutionDetails<boolean>>;
|
|
79
|
+
resolveStringEvaluation(flagKey: string, defaultValue: string, context: EvaluationContext, logger: Logger): Promise<ResolutionDetails<string>>;
|
|
80
|
+
resolveNumberEvaluation(flagKey: string, defaultValue: number, context: EvaluationContext, logger: Logger): Promise<ResolutionDetails<number>>;
|
|
81
|
+
resolveObjectEvaluation<T extends JsonValue>(flagKey: string, defaultValue: T, context: EvaluationContext, logger: Logger): Promise<ResolutionDetails<T>>;
|
|
82
|
+
private resolve;
|
|
83
|
+
/**
|
|
84
|
+
* Captures a consistent evaluation of a flag.
|
|
85
|
+
*
|
|
86
|
+
* - client-evaluated keys: a fresh local context is created per resolution
|
|
87
|
+
* (no shared state) and the flag is evaluated in-memory.
|
|
88
|
+
* - server-evaluated keys: the one shared context is fetched again from Edge
|
|
89
|
+
* when the OpenFeature context changes, and the flag read once its features
|
|
90
|
+
* have arrived. While any resolution is in progress only its context may be
|
|
91
|
+
* resolved: another is refused, as it would be given the first's values.
|
|
92
|
+
*/
|
|
93
|
+
private evaluate;
|
|
94
|
+
/**
|
|
95
|
+
* Fetches the features for a new context into the shared context. Until they arrive the repository holds
|
|
96
|
+
* the previous context's, so a fetch that fails, or does not finish in time, fails the resolution, and the
|
|
97
|
+
* next resolution for the context tries again.
|
|
98
|
+
*/
|
|
99
|
+
private fetchContext;
|
|
100
|
+
/** waits for the work, or until the deadline, whichever is first; the readiness check that follows decides */
|
|
101
|
+
private within;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export { FeatureHubProvider, type FeatureHubProviderOptions };
|
|
105
|
+
declare module 'featurehub-openfeature-node-sdk'
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { Provider, ProviderMetadata, OpenFeatureEventEmitter, EvaluationContext, Logger, ResolutionDetails, JsonValue } from '@openfeature/server-sdk';
|
|
2
|
+
import { FeatureHubConfig } from 'featurehub-javascript-node-sdk';
|
|
3
|
+
import { FeatureHubProviderCore, BaseProviderOptions, ProviderEventSink, Transport } from 'featurehub-openfeature-common';
|
|
4
|
+
export { ContextAttribute, InvalidContextError, MappedContext, contextSignature, mapEvaluationContext, toContextRecord } from 'featurehub-openfeature-common';
|
|
5
|
+
|
|
6
|
+
interface FeatureHubProviderOptions extends BaseProviderOptions<FeatureHubProviderOptions> {
|
|
7
|
+
/**
|
|
8
|
+
* Base URL of FeatureHub Edge, e.g. `https://edge.featurehub.io` or `http://localhost:8553`. Defaults to
|
|
9
|
+
* `FEATUREHUB_EDGE_URL`.
|
|
10
|
+
*/
|
|
11
|
+
host?: string;
|
|
12
|
+
/**
|
|
13
|
+
* A FeatureHub SDK API key for the environment.
|
|
14
|
+
*
|
|
15
|
+
* - **client-evaluated keys** (containing `*`): the feature bundle (including
|
|
16
|
+
* rollout strategies) is streamed/polled to the provider and every
|
|
17
|
+
* evaluation is performed locally against the supplied context. This is
|
|
18
|
+
* the recommended mode for Node servers handling many different users.
|
|
19
|
+
* - **server-evaluated keys** (`default/...`): Edge evaluates the features
|
|
20
|
+
* for one context, which the provider holds for every OpenFeature client
|
|
21
|
+
* in the process. When the context changes, the features are fetched again
|
|
22
|
+
* for the new one. A resolution for a different context while another
|
|
23
|
+
* context's is in progress fails with INVALID_CONTEXT, rather than give
|
|
24
|
+
* either the other's values: use the same context everywhere, or a
|
|
25
|
+
* client-evaluated key for many users at once.
|
|
26
|
+
*
|
|
27
|
+
* Defaults to `FEATUREHUB_CLIENT_API_KEY`, else `FEATUREHUB_SERVER_API_KEY`. With no host and no key
|
|
28
|
+
* (in code or the environment), a `configFactory` can supply a config whose features come from stores.
|
|
29
|
+
*/
|
|
30
|
+
apiKey?: string;
|
|
31
|
+
/** How long `initialize` (and context changes) wait for readiness. Default 10s. */
|
|
32
|
+
waitForReadyMs?: number;
|
|
33
|
+
/**
|
|
34
|
+
* Build the FeatureHub config yourself, to attach value interceptors, feature stores and usage plugins.
|
|
35
|
+
* It is given the options with `host` and `apiKey` as resolved (from the environment if not in code).
|
|
36
|
+
*/
|
|
37
|
+
configFactory?: (options: FeatureHubProviderOptions) => FeatureHubConfig;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Official OpenFeature provider for FeatureHub (Node.js).
|
|
41
|
+
*
|
|
42
|
+
* The provider holds no evaluation logic of its own: it drives a
|
|
43
|
+
* [FeatureHubConfig]{@link FeatureHubConfig}, which keeps a local repository
|
|
44
|
+
* of the entire feature bundle up to date (streaming, polling or passive
|
|
45
|
+
* refresh), and every OpenFeature resolution is served from that local
|
|
46
|
+
* repository — never with a per-flag network call.
|
|
47
|
+
*/
|
|
48
|
+
declare class FeatureHubProvider extends FeatureHubProviderCore<FeatureHubProviderOptions> implements Provider {
|
|
49
|
+
readonly metadata: ProviderMetadata;
|
|
50
|
+
readonly runsOn: "server";
|
|
51
|
+
readonly events: OpenFeatureEventEmitter;
|
|
52
|
+
/**
|
|
53
|
+
* Server-evaluated keys only: the single shared evaluation context, held for
|
|
54
|
+
* the provider's lifetime. Holding exactly one keeps the SDK's internal
|
|
55
|
+
* reference count at 1 and lets the SDK reuse its evaluated bundle.
|
|
56
|
+
*/
|
|
57
|
+
private sharedContext?;
|
|
58
|
+
/** the context the shared context's features were fetched for */
|
|
59
|
+
private builtSignature;
|
|
60
|
+
/** the context being resolved, while `inFlight` resolutions are in progress */
|
|
61
|
+
private activeSignature;
|
|
62
|
+
private inFlight;
|
|
63
|
+
/** the fetch for `activeSignature`, which every resolution for it waits on */
|
|
64
|
+
private building;
|
|
65
|
+
/**
|
|
66
|
+
* Settings not given in code come from the environment, setting by setting (featurehub-protocol.yaml
|
|
67
|
+
* providers.environment_variables): FEATUREHUB_EDGE_URL, then FEATUREHUB_CLIENT_API_KEY or else
|
|
68
|
+
* FEATUREHUB_SERVER_API_KEY, and, with no transport option, the node SDK's mode
|
|
69
|
+
* (FEATUREHUB_CONNECT_TYPE and FEATUREHUB_CONNECT_INTERVAL; streaming when neither is set).
|
|
70
|
+
*/
|
|
71
|
+
constructor(options?: FeatureHubProviderOptions);
|
|
72
|
+
protected get eventSink(): ProviderEventSink;
|
|
73
|
+
/** none: the node SDK's own, from FEATUREHUB_CONNECT_TYPE / FEATUREHUB_CONNECT_INTERVAL, else streaming */
|
|
74
|
+
protected get defaultTransport(): Transport | undefined;
|
|
75
|
+
protected createConfig(): FeatureHubConfig;
|
|
76
|
+
initialize(context?: EvaluationContext): Promise<void>;
|
|
77
|
+
onClose(): Promise<void>;
|
|
78
|
+
resolveBooleanEvaluation(flagKey: string, defaultValue: boolean, context: EvaluationContext, logger: Logger): Promise<ResolutionDetails<boolean>>;
|
|
79
|
+
resolveStringEvaluation(flagKey: string, defaultValue: string, context: EvaluationContext, logger: Logger): Promise<ResolutionDetails<string>>;
|
|
80
|
+
resolveNumberEvaluation(flagKey: string, defaultValue: number, context: EvaluationContext, logger: Logger): Promise<ResolutionDetails<number>>;
|
|
81
|
+
resolveObjectEvaluation<T extends JsonValue>(flagKey: string, defaultValue: T, context: EvaluationContext, logger: Logger): Promise<ResolutionDetails<T>>;
|
|
82
|
+
private resolve;
|
|
83
|
+
/**
|
|
84
|
+
* Captures a consistent evaluation of a flag.
|
|
85
|
+
*
|
|
86
|
+
* - client-evaluated keys: a fresh local context is created per resolution
|
|
87
|
+
* (no shared state) and the flag is evaluated in-memory.
|
|
88
|
+
* - server-evaluated keys: the one shared context is fetched again from Edge
|
|
89
|
+
* when the OpenFeature context changes, and the flag read once its features
|
|
90
|
+
* have arrived. While any resolution is in progress only its context may be
|
|
91
|
+
* resolved: another is refused, as it would be given the first's values.
|
|
92
|
+
*/
|
|
93
|
+
private evaluate;
|
|
94
|
+
/**
|
|
95
|
+
* Fetches the features for a new context into the shared context. Until they arrive the repository holds
|
|
96
|
+
* the previous context's, so a fetch that fails, or does not finish in time, fails the resolution, and the
|
|
97
|
+
* next resolution for the context tries again.
|
|
98
|
+
*/
|
|
99
|
+
private fetchContext;
|
|
100
|
+
/** waits for the work, or until the deadline, whichever is first; the readiness check that follows decides */
|
|
101
|
+
private within;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export { FeatureHubProvider, type FeatureHubProviderOptions };
|
|
105
|
+
declare module 'featurehub-openfeature-node-sdk'
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
// src/provider.ts
|
|
2
|
+
import { OpenFeatureEventEmitter } from "@openfeature/server-sdk";
|
|
3
|
+
import { EdgeFeatureHubConfig, Readyness } from "featurehub-javascript-node-sdk";
|
|
4
|
+
import {
|
|
5
|
+
captureFeature,
|
|
6
|
+
ContextConflictError,
|
|
7
|
+
contextSignature,
|
|
8
|
+
FeatureHubProviderCore,
|
|
9
|
+
toContextRecord
|
|
10
|
+
} from "featurehub-openfeature-common";
|
|
11
|
+
function environment(name) {
|
|
12
|
+
const value = process.env[name]?.trim();
|
|
13
|
+
return value ? value : void 0;
|
|
14
|
+
}
|
|
15
|
+
var FeatureHubProvider = class extends FeatureHubProviderCore {
|
|
16
|
+
metadata = { name: "featurehub" };
|
|
17
|
+
runsOn = "server";
|
|
18
|
+
events = new OpenFeatureEventEmitter();
|
|
19
|
+
/**
|
|
20
|
+
* Server-evaluated keys only: the single shared evaluation context, held for
|
|
21
|
+
* the provider's lifetime. Holding exactly one keeps the SDK's internal
|
|
22
|
+
* reference count at 1 and lets the SDK reuse its evaluated bundle.
|
|
23
|
+
*/
|
|
24
|
+
sharedContext;
|
|
25
|
+
/** the context the shared context's features were fetched for */
|
|
26
|
+
builtSignature;
|
|
27
|
+
/** the context being resolved, while `inFlight` resolutions are in progress */
|
|
28
|
+
activeSignature;
|
|
29
|
+
inFlight = 0;
|
|
30
|
+
/** the fetch for `activeSignature`, which every resolution for it waits on */
|
|
31
|
+
building;
|
|
32
|
+
/**
|
|
33
|
+
* Settings not given in code come from the environment, setting by setting (featurehub-protocol.yaml
|
|
34
|
+
* providers.environment_variables): FEATUREHUB_EDGE_URL, then FEATUREHUB_CLIENT_API_KEY or else
|
|
35
|
+
* FEATUREHUB_SERVER_API_KEY, and, with no transport option, the node SDK's mode
|
|
36
|
+
* (FEATUREHUB_CONNECT_TYPE and FEATUREHUB_CONNECT_INTERVAL; streaming when neither is set).
|
|
37
|
+
*/
|
|
38
|
+
constructor(options = {}) {
|
|
39
|
+
super("FeatureHubProvider", options, {
|
|
40
|
+
host: options.host ?? environment("FEATUREHUB_EDGE_URL"),
|
|
41
|
+
apiKey: options.apiKey ?? environment("FEATUREHUB_CLIENT_API_KEY") ?? environment("FEATUREHUB_SERVER_API_KEY")
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
get eventSink() {
|
|
45
|
+
return this.events;
|
|
46
|
+
}
|
|
47
|
+
/** none: the node SDK's own, from FEATUREHUB_CONNECT_TYPE / FEATUREHUB_CONNECT_INTERVAL, else streaming */
|
|
48
|
+
get defaultTransport() {
|
|
49
|
+
return void 0;
|
|
50
|
+
}
|
|
51
|
+
createConfig() {
|
|
52
|
+
return new EdgeFeatureHubConfig(this.host, this.apiKey);
|
|
53
|
+
}
|
|
54
|
+
async initialize(context) {
|
|
55
|
+
const deadline = Date.now() + this.waitForReadyMs;
|
|
56
|
+
const record = this.clientEval ? void 0 : toContextRecord(context);
|
|
57
|
+
const cfg = this.startConfig();
|
|
58
|
+
if (record !== void 0) {
|
|
59
|
+
this.sharedContext = cfg.context(record);
|
|
60
|
+
await this.within(deadline, this.sharedContext.build());
|
|
61
|
+
}
|
|
62
|
+
await this.awaitReady(cfg, Math.max(0, deadline - Date.now()));
|
|
63
|
+
if (record !== void 0) {
|
|
64
|
+
this.builtSignature = contextSignature(context);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
async onClose() {
|
|
68
|
+
await super.onClose();
|
|
69
|
+
this.sharedContext = void 0;
|
|
70
|
+
this.builtSignature = void 0;
|
|
71
|
+
this.activeSignature = void 0;
|
|
72
|
+
this.building = void 0;
|
|
73
|
+
}
|
|
74
|
+
async resolveBooleanEvaluation(flagKey, defaultValue, context, logger) {
|
|
75
|
+
return this.resolve(flagKey, context, "boolean", defaultValue, logger);
|
|
76
|
+
}
|
|
77
|
+
async resolveStringEvaluation(flagKey, defaultValue, context, logger) {
|
|
78
|
+
return this.resolve(flagKey, context, "string", defaultValue, logger);
|
|
79
|
+
}
|
|
80
|
+
async resolveNumberEvaluation(flagKey, defaultValue, context, logger) {
|
|
81
|
+
return this.resolve(flagKey, context, "number", defaultValue, logger);
|
|
82
|
+
}
|
|
83
|
+
async resolveObjectEvaluation(flagKey, defaultValue, context, logger) {
|
|
84
|
+
return this.resolve(flagKey, context, "object", defaultValue, logger);
|
|
85
|
+
}
|
|
86
|
+
resolve(flagKey, context, kind, defaultValue, logger) {
|
|
87
|
+
return this.resolveAsync(
|
|
88
|
+
flagKey,
|
|
89
|
+
kind,
|
|
90
|
+
defaultValue,
|
|
91
|
+
logger,
|
|
92
|
+
() => this.evaluate(flagKey, context)
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Captures a consistent evaluation of a flag.
|
|
97
|
+
*
|
|
98
|
+
* - client-evaluated keys: a fresh local context is created per resolution
|
|
99
|
+
* (no shared state) and the flag is evaluated in-memory.
|
|
100
|
+
* - server-evaluated keys: the one shared context is fetched again from Edge
|
|
101
|
+
* when the OpenFeature context changes, and the flag read once its features
|
|
102
|
+
* have arrived. While any resolution is in progress only its context may be
|
|
103
|
+
* resolved: another is refused, as it would be given the first's values.
|
|
104
|
+
*/
|
|
105
|
+
async evaluate(flagKey, context) {
|
|
106
|
+
if (this.clientEval) {
|
|
107
|
+
const ctx = this.config.context(toContextRecord(context));
|
|
108
|
+
return captureFeature(ctx.feature(flagKey));
|
|
109
|
+
}
|
|
110
|
+
const signature = contextSignature(context);
|
|
111
|
+
if (this.inFlight > 0 && signature !== this.activeSignature) {
|
|
112
|
+
throw new ContextConflictError();
|
|
113
|
+
}
|
|
114
|
+
this.inFlight++;
|
|
115
|
+
this.activeSignature = signature;
|
|
116
|
+
try {
|
|
117
|
+
if (signature !== this.builtSignature) {
|
|
118
|
+
this.building ??= this.fetchContext(context, signature).finally(() => {
|
|
119
|
+
this.building = void 0;
|
|
120
|
+
});
|
|
121
|
+
await this.building;
|
|
122
|
+
}
|
|
123
|
+
return captureFeature(this.sharedContext.feature(flagKey));
|
|
124
|
+
} finally {
|
|
125
|
+
this.inFlight--;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Fetches the features for a new context into the shared context. Until they arrive the repository holds
|
|
130
|
+
* the previous context's, so a fetch that fails, or does not finish in time, fails the resolution, and the
|
|
131
|
+
* next resolution for the context tries again.
|
|
132
|
+
*/
|
|
133
|
+
async fetchContext(context, signature) {
|
|
134
|
+
const deadline = Date.now() + this.waitForReadyMs;
|
|
135
|
+
const cfg = this.config;
|
|
136
|
+
const ctx = this.sharedContext ?? cfg.context({});
|
|
137
|
+
this.sharedContext = ctx;
|
|
138
|
+
ctx.userKey(void 0);
|
|
139
|
+
ctx.clear();
|
|
140
|
+
ctx.attributes = toContextRecord(context);
|
|
141
|
+
await this.within(deadline, ctx.build());
|
|
142
|
+
const readiness = await cfg.waitForReady(Math.max(0, deadline - Date.now()));
|
|
143
|
+
if (readiness !== Readyness.Ready) {
|
|
144
|
+
throw new Error(
|
|
145
|
+
`FeatureHub could not fetch the features for the new context within ${this.waitForReadyMs}ms (readiness: ${readiness}).`
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
this.builtSignature = signature;
|
|
149
|
+
}
|
|
150
|
+
/** waits for the work, or until the deadline, whichever is first; the readiness check that follows decides */
|
|
151
|
+
async within(deadline, work) {
|
|
152
|
+
let timer;
|
|
153
|
+
try {
|
|
154
|
+
await Promise.race([
|
|
155
|
+
work,
|
|
156
|
+
new Promise((resolve) => {
|
|
157
|
+
timer = setTimeout(resolve, Math.max(0, deadline - Date.now()));
|
|
158
|
+
})
|
|
159
|
+
]);
|
|
160
|
+
} finally {
|
|
161
|
+
clearTimeout(timer);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
// src/index.ts
|
|
167
|
+
import {
|
|
168
|
+
contextSignature as contextSignature2,
|
|
169
|
+
InvalidContextError,
|
|
170
|
+
mapEvaluationContext,
|
|
171
|
+
toContextRecord as toContextRecord2
|
|
172
|
+
} from "featurehub-openfeature-common";
|
|
173
|
+
export {
|
|
174
|
+
FeatureHubProvider,
|
|
175
|
+
InvalidContextError,
|
|
176
|
+
contextSignature2 as contextSignature,
|
|
177
|
+
mapEvaluationContext,
|
|
178
|
+
toContextRecord2 as toContextRecord
|
|
179
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,72 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "featurehub-openfeature-node-sdk",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.0.1",
|
|
4
|
+
"description": "Official OpenFeature provider for FeatureHub (Node.js). Evaluates flags locally via the FeatureHub SDK feature repository - streaming, polling or passive-refresh, never per-flag network calls.",
|
|
5
|
+
"author": "info@featurehub.io",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "dist/index.js",
|
|
8
|
+
"types": "dist/index.d.ts",
|
|
9
|
+
"module": "lib/index.js",
|
|
10
|
+
"homepage": "https://featurehub.io",
|
|
11
|
+
"repository": "github:featurehub-io/featurehub-javascript-sdk",
|
|
12
|
+
"license": "MIT",
|
|
13
|
+
"files": [
|
|
14
|
+
"dist"
|
|
15
|
+
],
|
|
16
|
+
"keywords": [
|
|
17
|
+
"feature-flag-api",
|
|
18
|
+
"feature-flag-sdk",
|
|
19
|
+
"feature-experimentation",
|
|
20
|
+
"feature-flag",
|
|
21
|
+
"flag",
|
|
22
|
+
"toggle",
|
|
23
|
+
"feature-toggle-api",
|
|
24
|
+
"remote-configuration",
|
|
25
|
+
"ab-testing",
|
|
26
|
+
"openfeature",
|
|
27
|
+
"openfeature-provider",
|
|
28
|
+
"featurehub"
|
|
29
|
+
],
|
|
30
|
+
"exports": {
|
|
31
|
+
".": {
|
|
32
|
+
"types": "./dist/index.d.ts",
|
|
33
|
+
"import": "./dist/index.js",
|
|
34
|
+
"require": "./dist/index.cjs"
|
|
35
|
+
}
|
|
36
|
+
},
|
|
37
|
+
"publishConfig": {
|
|
38
|
+
"provenance": true,
|
|
39
|
+
"access": "public"
|
|
40
|
+
},
|
|
41
|
+
"peerDependencies": {
|
|
42
|
+
"@openfeature/server-sdk": ">=1.23.0 <2"
|
|
43
|
+
},
|
|
44
|
+
"dependencies": {
|
|
45
|
+
"featurehub-openfeature-common": "^1.0.1",
|
|
46
|
+
"featurehub-javascript-node-sdk": "^2.1.0"
|
|
47
|
+
},
|
|
48
|
+
"devDependencies": {
|
|
49
|
+
"@openfeature/server-sdk": "^1.23.0",
|
|
50
|
+
"@types/node": "22.18.10",
|
|
51
|
+
"rimraf": "6.1.3",
|
|
52
|
+
"tsup": "8.5.0",
|
|
53
|
+
"typescript": "5.9.3",
|
|
54
|
+
"vite": "^7.3.8",
|
|
55
|
+
"vitest": "^3.2.7",
|
|
56
|
+
"featurehub-tsconfig": "0.0.0"
|
|
57
|
+
},
|
|
58
|
+
"engines": {
|
|
59
|
+
"node": ">=20.0.0"
|
|
60
|
+
},
|
|
61
|
+
"scripts": {
|
|
62
|
+
"build": "tsup",
|
|
63
|
+
"build:watch": "tsup --watch",
|
|
64
|
+
"clean": "rimraf node_modules dist",
|
|
65
|
+
"lint": "eslint .",
|
|
66
|
+
"lint:fix": "eslint --fix .",
|
|
67
|
+
"typecheck": "tsc --noEmit",
|
|
68
|
+
"test": "vitest run",
|
|
69
|
+
"test:watch": "vitest",
|
|
70
|
+
"test:coverage": "vitest run --coverage"
|
|
71
|
+
}
|
|
6
72
|
}
|