Skip to content

Commit 58893d6

Browse files
feat: js local resolver (#32)
1 parent 123db6a commit 58893d6

30 files changed

+4584
-4
lines changed

.vscode/settings.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
{
22
"rust-analyzer.cargo.target": "wasm32-unknown-unknown",
33
"rust-analyzer.cargo.features": [],
4+
"rust-analyzer.cargo.extraEnv": {
5+
"PROTOC":"/opt/homebrew/bin/protoc"
6+
},
47
"protoc": {
58
"options": ["-I/${workspaceRoot}/confidence-resolver/protos"]
69
}

confidence-resolver/protos/confidence/flags/admin/v1/resolver.proto

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,8 @@ message ResolverStateUriResponse {
5656
string signed_uri = 1;
5757
// At what time the state uri expires
5858
google.protobuf.Timestamp expire_time = 2;
59+
// The account the referenced state belongs to
60+
string account = 3;
5961
}
6062

6163
// Request to get the resolver state for the whole account
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
root = true
2+
3+
[*]
4+
end_of_line = lf
5+
insert_final_newline = true
6+
7+
[*.{js,json,yml}]
8+
charset = utf-8
9+
indent_style = space
10+
indent_size = 2
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
/.yarn/** linguist-vendored
2+
/.yarn/releases/* binary
3+
/.yarn/plugins/**/* binary
4+
/.pnp.* binary linguist-generated

openfeature-provider/js/.gitignore

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
.yarn/*
2+
!.yarn/patches
3+
!.yarn/plugins
4+
!.yarn/releases
5+
!.yarn/sdks
6+
!.yarn/versions
7+
node_modules/
8+
src/proto/
9+
dist/
10+
.env.test
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
nodeLinker: node-modules

openfeature-provider/js/README.md

Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
## @spotify-confidence/openfeature-server-provider-local
2+
3+
OpenFeature provider for the Spotify Confidence resolver (local mode, powered by WebAssembly). It periodically fetches resolver state, evaluates flags locally, and flushes evaluation logs to the Confidence backend.
4+
5+
### Features
6+
- Local flag evaluation via WASM (no per-eval network calls)
7+
- Automatic state refresh and batched flag log flushing
8+
- Pluggable `fetch` with retries, timeouts and routing
9+
- Optional logging using `debug`
10+
11+
### Requirements
12+
- Node.js 18+ (built-in `fetch`) or provide a compatible `fetch`
13+
- WebAssembly support (Node 18+/modern browsers)
14+
15+
---
16+
17+
## Installation
18+
19+
```bash
20+
yarn add @spotify-confidence/openfeature-server-provider-local
21+
22+
# Optional: enable logs by installing the peer dependency
23+
yarn add debug
24+
```
25+
26+
Notes:
27+
- `debug` is an optional peer. Install it if you want logs. Without it, logging is a no-op.
28+
- Types and bundling are ESM-first; Node is supported, and a browser build is provided for modern bundlers.
29+
30+
---
31+
32+
## Quick start (Node)
33+
34+
```ts
35+
import { OpenFeature } from '@openfeature/server-sdk';
36+
import { createConfidenceServerProvider } from '@spotify-confidence/openfeature-server-provider-local';
37+
38+
const provider = createConfidenceServerProvider({
39+
flagClientSecret: process.env.CONFIDENCE_FLAG_CLIENT_SECRET!,
40+
apiClientId: process.env.CONFIDENCE_API_CLIENT_ID!,
41+
apiClientSecret: process.env.CONFIDENCE_API_CLIENT_SECRET!,
42+
// initializeTimeout?: number
43+
// flushInterval?: number
44+
// fetch?: typeof fetch (Node <18 or custom transport)
45+
});
46+
47+
// Wait for the provider to be ready (fetches initial resolver state)
48+
await OpenFeature.setProviderAndWait(provider);
49+
50+
const client = OpenFeature.getClient();
51+
52+
// Evaluate a boolean flag
53+
const details = await client.getBooleanDetails('my-flag', false, { targetingKey: 'user-123' });
54+
console.log(details.value, details.reason);
55+
56+
// Evaluate a nested value from an object flag using dot-path
57+
// e.g. flag key "experiments" with payload { groupA: { ratio: 0.5 } }
58+
const ratio = await client.getNumberValue('experiments.groupA.ratio', 0, { targetingKey: 'user-123' });
59+
60+
// On shutdown, flush any pending logs
61+
await provider.onClose();
62+
```
63+
64+
---
65+
66+
## Options
67+
68+
- `flagClientSecret` (string, required): The flag client secret used during evaluation.
69+
- `apiClientId` (string, required): OAuth client ID for Confidence IAM.
70+
- `apiClientSecret` (string, required): OAuth client secret for Confidence IAM.
71+
- `initializeTimeout` (number, optional): Max ms to wait for initial state fetch. Defaults to 30_000.
72+
- `flushInterval` (number, optional): Interval in ms for sending evaluation logs. Defaults to 10_000.
73+
- `fetch` (optional): Custom `fetch` implementation. Required for Node < 18; for Node 18+ you can omit.
74+
75+
The provider periodically:
76+
- Refreshes resolver state (default every 30s)
77+
- Flushes flag evaluation logs to the backend
78+
79+
---
80+
81+
## Logging (optional)
82+
83+
Logging uses the `debug` library if present; otherwise, all log calls are no-ops.
84+
85+
Namespaces:
86+
- Core: `cnfd:*`
87+
- Fetch/middleware: `cnfd:fetch:*` (e.g. retries, auth renewals, request summaries)
88+
89+
Enable logs:
90+
91+
- Node:
92+
```bash
93+
DEBUG=cnfd:* node app.js
94+
# or narrower
95+
DEBUG=cnfd:info,cnfd:error,cnfd:fetch:* node app.js
96+
```
97+
98+
- Browser (in DevTools console):
99+
```js
100+
localStorage.debug = 'cnfd:*';
101+
```
102+
103+
Install `debug` if you haven’t:
104+
105+
```bash
106+
yarn add debug
107+
```
108+
109+
---
110+
111+
## WebAssembly asset notes
112+
113+
- Node: the WASM (`confidence_resolver.wasm`) is resolved from the installed package automatically; no extra config needed.
114+
- Browser: the ESM build resolves the WASM via `new URL('confidence_resolver.wasm', import.meta.url)` so modern bundlers (Vite/Rollup/Webpack 5 asset modules) will include it. If your bundler does not, configure it to treat the `.wasm` file as a static asset.
115+
116+
---
117+
118+
## Using in browsers
119+
120+
The package exports a browser ESM build that compiles the WASM via streaming and uses the global `fetch`. Integrate it with your OpenFeature SDK variant for the web similarly to Node, then register the provider before evaluation. Credentials must be available to the runtime (e.g. through your app’s configuration layer).
121+
122+
---
123+
124+
## Testing
125+
126+
- You can inject a custom `fetch` via the `fetch` option to stub network behavior in tests.
127+
- The provider batches logs; call `await provider.onClose()` in tests to flush them deterministically.
128+
129+
---
130+
131+
## Troubleshooting
132+
133+
- Provider stuck in NOT_READY/ERROR:
134+
- Verify `apiClientId`/`apiClientSecret` and `flagClientSecret` are correct.
135+
- Ensure outbound access to Confidence endpoints and GCS.
136+
- Enable `DEBUG=cnfd:*` for more detail.
137+
138+
- No logs appear:
139+
- Install `debug` and enable the appropriate namespaces.
140+
- Check that your environment variable/`localStorage.debug` is set before your app initializes the provider.
141+
142+
---
143+
144+
## License
145+
146+
See the root `LICENSE`.
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
{
2+
"name": "@spotify-confidence/openfeature-server-provider-local",
3+
"version": "0.0.0",
4+
"private": true,
5+
"description": "Spotify Confidence Open Feature provider",
6+
"type": "module",
7+
"files": [
8+
"dist"
9+
],
10+
"main": "./dist/index.node.js",
11+
"module": "./dist/index.browser.js",
12+
"types": "./dist/index.node.d.ts",
13+
"exports": {
14+
".": {
15+
"node": {
16+
"types": "./dist/index.node.d.ts",
17+
"default": "./dist/index.node.js"
18+
},
19+
"browser": {
20+
"types": "./dist/index.browser.d.ts",
21+
"default": "./dist/index.browser.js"
22+
},
23+
"default": {
24+
"types": "./dist/index.node.d.ts",
25+
"default": "./dist/index.node.js"
26+
}
27+
},
28+
"./package.json": "./package.json"
29+
},
30+
"scripts": {
31+
"build": "tsdown",
32+
"dev": "tsdown --watch",
33+
"test": "vitest",
34+
"proto:gen": "rm -rf src/proto && mkdir -p src/proto && protoc --plugin=node_modules/.bin/protoc-gen-ts_proto --ts_proto_opt useOptionals=messages --ts_proto_opt esModuleInterop=true --ts_proto_out src/proto -Iproto api.proto messages.proto"
35+
},
36+
"dependencies": {
37+
"@bufbuild/protobuf": "^2.9.0"
38+
},
39+
"devDependencies": {
40+
"@openfeature/core": "^1.9.0",
41+
"@openfeature/server-sdk": "^1.19.0",
42+
"@types/debug": "^4",
43+
"@types/node": "^24.0.1",
44+
"@vitest/coverage-v8": "^3.2.4",
45+
"debug": "^4.4.3",
46+
"dotenv": "^17.2.2",
47+
"rolldown": "1.0.0-beta.38",
48+
"ts-proto": "^2.7.3",
49+
"tsdown": "latest",
50+
"vitest": "^3.2.4"
51+
},
52+
"peerDependencies": {
53+
"debug": "^4.4.3"
54+
},
55+
"peerDependenciesMeta": {
56+
"debug": {
57+
"optional": true
58+
}
59+
},
60+
"packageManager": "yarn@4.6.0"
61+
}
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
syntax = "proto3";
2+
3+
import "google/protobuf/struct.proto";
4+
import "google/protobuf/timestamp.proto";
5+
6+
message ResolveFlagsRequest {
7+
// If non-empty, the specific flags are resolved, otherwise all flags
8+
// available to the client will be resolved.
9+
repeated string flags = 1;
10+
11+
// An object that contains data used in the flag resolve. For example,
12+
// the targeting key e.g. the id of the randomization unit, other attributes
13+
// like country or version that are used for targeting.
14+
google.protobuf.Struct evaluation_context = 2;
15+
16+
// Credentials for the client. It is used to identify the client and find
17+
// the flags that are available to it.
18+
string client_secret = 3;
19+
20+
// Determines whether the flags should be applied directly as part of the
21+
// resolve, or delayed until `ApplyFlag` is called. A flag is typically
22+
// applied when it is used, if this occurs much later than the resolve, then
23+
// `apply` should likely be set to false.
24+
bool apply = 4;
25+
26+
// Information about the SDK used to initiate the request.
27+
// Sdk sdk = 5;
28+
}
29+
30+
message ResolveFlagsResponse {
31+
// The list of all flags that could be resolved. Note: if any flag was
32+
// archived it will not be included in this list.
33+
repeated ResolvedFlag resolved_flags = 1;
34+
35+
// An opaque token that is used when `apply` is set to false in `ResolveFlags`.
36+
// When `apply` is set to false, the token must be passed to `ApplyFlags`.
37+
bytes resolve_token = 2;
38+
39+
// Unique identifier for this particular resolve request.
40+
string resolve_id = 3;
41+
}
42+
43+
44+
message ResolvedFlag {
45+
// The id of the flag that as resolved.
46+
string flag = 1;
47+
48+
// The id of the resolved variant has the format `flags/abc/variants/xyz`.
49+
string variant = 2;
50+
51+
// The value corresponding to the variant. It will always be a json object,
52+
// for example `{ "color": "red", "size": 12 }`.
53+
google.protobuf.Struct value = 3;
54+
55+
// The schema of the value that was returned. For example:
56+
// ```
57+
// {
58+
// "schema": {
59+
// "color": { "stringSchema": {} },
60+
// "size": { "intSchema": {} }
61+
// }
62+
// }
63+
// ```
64+
// types.v1.FlagSchema.StructFlagSchema flag_schema = 4;
65+
66+
// The reason to why the flag could be resolved or not.
67+
ResolveReason reason = 5;
68+
}
69+
70+
71+
enum ResolveReason {
72+
// Unspecified enum.
73+
RESOLVE_REASON_UNSPECIFIED = 0;
74+
// The flag was successfully resolved because one rule matched.
75+
RESOLVE_REASON_MATCH = 1;
76+
// The flag could not be resolved because no rule matched.
77+
RESOLVE_REASON_NO_SEGMENT_MATCH = 2;
78+
// The flag could not be resolved because the matching rule had no variant
79+
// that could be assigned.
80+
RESOLVE_REASON_NO_TREATMENT_MATCH = 3 [deprecated = true];
81+
// The flag could not be resolved because it was archived.
82+
RESOLVE_REASON_FLAG_ARCHIVED = 4;
83+
// The flag could not be resolved because the targeting key field was invalid
84+
RESOLVE_REASON_TARGETING_KEY_ERROR = 5;
85+
// Unknown error occurred during the resolve
86+
RESOLVE_REASON_ERROR = 6;
87+
}
88+
89+
message SetResolverStateRequest {
90+
bytes state = 1;
91+
string account_id = 2;
92+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
syntax = "proto3";
2+
3+
message Void {}
4+
5+
message Request {
6+
bytes data = 1;
7+
}
8+
9+
message Response {
10+
oneof result {
11+
bytes data = 1;
12+
string error = 2;
13+
}
14+
}

0 commit comments

Comments
 (0)