Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
{
"rust-analyzer.cargo.target": "wasm32-unknown-unknown",
"rust-analyzer.cargo.features": [],
"rust-analyzer.cargo.extraEnv": {
"PROTOC":"/opt/homebrew/bin/protoc"
},
"protoc": {
"options": ["-I/${workspaceRoot}/confidence-resolver/protos"]
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ message ResolverStateUriResponse {
string signed_uri = 1;
// At what time the state uri expires
google.protobuf.Timestamp expire_time = 2;
// The account the referenced state belongs to
string account = 3;
}

// Request to get the resolver state for the whole account
Expand Down
10 changes: 10 additions & 0 deletions openfeature-provider/js/.editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
root = true

[*]
end_of_line = lf
insert_final_newline = true

[*.{js,json,yml}]
charset = utf-8
indent_style = space
indent_size = 2
4 changes: 4 additions & 0 deletions openfeature-provider/js/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/.yarn/** linguist-vendored
/.yarn/releases/* binary
/.yarn/plugins/**/* binary
/.pnp.* binary linguist-generated
10 changes: 10 additions & 0 deletions openfeature-provider/js/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/sdks
!.yarn/versions
node_modules/
src/proto/
dist/
.env.test
1 change: 1 addition & 0 deletions openfeature-provider/js/.yarnrc.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
nodeLinker: node-modules
146 changes: 146 additions & 0 deletions openfeature-provider/js/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
## @spotify-confidence/openfeature-server-provider-local

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.

### Features
- Local flag evaluation via WASM (no per-eval network calls)
- Automatic state refresh and batched flag log flushing
- Pluggable `fetch` with retries, timeouts and routing
- Optional logging using `debug`

### Requirements
- Node.js 18+ (built-in `fetch`) or provide a compatible `fetch`
- WebAssembly support (Node 18+/modern browsers)

---

## Installation

```bash
yarn add @spotify-confidence/openfeature-server-provider-local

# Optional: enable logs by installing the peer dependency
yarn add debug
```

Notes:
- `debug` is an optional peer. Install it if you want logs. Without it, logging is a no-op.
- Types and bundling are ESM-first; Node is supported, and a browser build is provided for modern bundlers.

---

## Quick start (Node)

```ts
import { OpenFeature } from '@openfeature/server-sdk';
import { createConfidenceServerProvider } from '@spotify-confidence/openfeature-server-provider-local';

const provider = createConfidenceServerProvider({
flagClientSecret: process.env.CONFIDENCE_FLAG_CLIENT_SECRET!,
apiClientId: process.env.CONFIDENCE_API_CLIENT_ID!,
apiClientSecret: process.env.CONFIDENCE_API_CLIENT_SECRET!,
// initializeTimeout?: number
// flushInterval?: number
// fetch?: typeof fetch (Node <18 or custom transport)
});

// Wait for the provider to be ready (fetches initial resolver state)
await OpenFeature.setProviderAndWait(provider);

const client = OpenFeature.getClient();

// Evaluate a boolean flag
const details = await client.getBooleanDetails('my-flag', false, { targetingKey: 'user-123' });
console.log(details.value, details.reason);

// Evaluate a nested value from an object flag using dot-path
// e.g. flag key "experiments" with payload { groupA: { ratio: 0.5 } }
const ratio = await client.getNumberValue('experiments.groupA.ratio', 0, { targetingKey: 'user-123' });

// On shutdown, flush any pending logs
await provider.onClose();
```

---

## Options

- `flagClientSecret` (string, required): The flag client secret used during evaluation.
- `apiClientId` (string, required): OAuth client ID for Confidence IAM.
- `apiClientSecret` (string, required): OAuth client secret for Confidence IAM.
- `initializeTimeout` (number, optional): Max ms to wait for initial state fetch. Defaults to 30_000.
- `flushInterval` (number, optional): Interval in ms for sending evaluation logs. Defaults to 10_000.
- `fetch` (optional): Custom `fetch` implementation. Required for Node < 18; for Node 18+ you can omit.

The provider periodically:
- Refreshes resolver state (default every 30s)
- Flushes flag evaluation logs to the backend

---

## Logging (optional)

Logging uses the `debug` library if present; otherwise, all log calls are no-ops.

Namespaces:
- Core: `cnfd:*`
- Fetch/middleware: `cnfd:fetch:*` (e.g. retries, auth renewals, request summaries)

Enable logs:

- Node:
```bash
DEBUG=cnfd:* node app.js
# or narrower
DEBUG=cnfd:info,cnfd:error,cnfd:fetch:* node app.js
```

- Browser (in DevTools console):
```js
localStorage.debug = 'cnfd:*';
```

Install `debug` if you haven’t:

```bash
yarn add debug
```

---

## WebAssembly asset notes

- Node: the WASM (`confidence_resolver.wasm`) is resolved from the installed package automatically; no extra config needed.
- 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.

---

## Using in browsers

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).

---

## Testing

- You can inject a custom `fetch` via the `fetch` option to stub network behavior in tests.
- The provider batches logs; call `await provider.onClose()` in tests to flush them deterministically.

---

## Troubleshooting

- Provider stuck in NOT_READY/ERROR:
- Verify `apiClientId`/`apiClientSecret` and `flagClientSecret` are correct.
- Ensure outbound access to Confidence endpoints and GCS.
- Enable `DEBUG=cnfd:*` for more detail.

- No logs appear:
- Install `debug` and enable the appropriate namespaces.
- Check that your environment variable/`localStorage.debug` is set before your app initializes the provider.

---

## License

See the root `LICENSE`.
61 changes: 61 additions & 0 deletions openfeature-provider/js/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
{
"name": "@spotify-confidence/openfeature-server-provider-local",
"version": "0.0.0",
"private": true,
"description": "Spotify Confidence Open Feature provider",
"type": "module",
"files": [
"dist"
],
"main": "./dist/index.node.js",
"module": "./dist/index.browser.js",
"types": "./dist/index.node.d.ts",
"exports": {
".": {
"node": {
"types": "./dist/index.node.d.ts",
"default": "./dist/index.node.js"
},
"browser": {
"types": "./dist/index.browser.d.ts",
"default": "./dist/index.browser.js"
},
"default": {
"types": "./dist/index.node.d.ts",
"default": "./dist/index.node.js"
}
},
"./package.json": "./package.json"
},
"scripts": {
"build": "tsdown",
"dev": "tsdown --watch",
"test": "vitest",
"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"
},
"dependencies": {
"@bufbuild/protobuf": "^2.9.0"
},
"devDependencies": {
"@openfeature/core": "^1.9.0",
"@openfeature/server-sdk": "^1.19.0",
"@types/debug": "^4",
"@types/node": "^24.0.1",
"@vitest/coverage-v8": "^3.2.4",
"debug": "^4.4.3",
"dotenv": "^17.2.2",
"rolldown": "1.0.0-beta.38",
"ts-proto": "^2.7.3",
"tsdown": "latest",
"vitest": "^3.2.4"
},
"peerDependencies": {
"debug": "^4.4.3"
},
"peerDependenciesMeta": {
"debug": {
"optional": true
}
},
"packageManager": "yarn@4.6.0"
}
92 changes: 92 additions & 0 deletions openfeature-provider/js/proto/api.proto
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
syntax = "proto3";

import "google/protobuf/struct.proto";
import "google/protobuf/timestamp.proto";

message ResolveFlagsRequest {
// If non-empty, the specific flags are resolved, otherwise all flags
// available to the client will be resolved.
repeated string flags = 1;

// An object that contains data used in the flag resolve. For example,
// the targeting key e.g. the id of the randomization unit, other attributes
// like country or version that are used for targeting.
google.protobuf.Struct evaluation_context = 2;

// Credentials for the client. It is used to identify the client and find
// the flags that are available to it.
string client_secret = 3;

// Determines whether the flags should be applied directly as part of the
// resolve, or delayed until `ApplyFlag` is called. A flag is typically
// applied when it is used, if this occurs much later than the resolve, then
// `apply` should likely be set to false.
bool apply = 4;

// Information about the SDK used to initiate the request.
// Sdk sdk = 5;
}

message ResolveFlagsResponse {
// The list of all flags that could be resolved. Note: if any flag was
// archived it will not be included in this list.
repeated ResolvedFlag resolved_flags = 1;

// An opaque token that is used when `apply` is set to false in `ResolveFlags`.
// When `apply` is set to false, the token must be passed to `ApplyFlags`.
bytes resolve_token = 2;

// Unique identifier for this particular resolve request.
string resolve_id = 3;
}


message ResolvedFlag {
// The id of the flag that as resolved.
string flag = 1;

// The id of the resolved variant has the format `flags/abc/variants/xyz`.
string variant = 2;

// The value corresponding to the variant. It will always be a json object,
// for example `{ "color": "red", "size": 12 }`.
google.protobuf.Struct value = 3;

// The schema of the value that was returned. For example:
// ```
// {
// "schema": {
// "color": { "stringSchema": {} },
// "size": { "intSchema": {} }
// }
// }
// ```
// types.v1.FlagSchema.StructFlagSchema flag_schema = 4;

// The reason to why the flag could be resolved or not.
ResolveReason reason = 5;
}


enum ResolveReason {
// Unspecified enum.
RESOLVE_REASON_UNSPECIFIED = 0;
// The flag was successfully resolved because one rule matched.
RESOLVE_REASON_MATCH = 1;
// The flag could not be resolved because no rule matched.
RESOLVE_REASON_NO_SEGMENT_MATCH = 2;
// The flag could not be resolved because the matching rule had no variant
// that could be assigned.
RESOLVE_REASON_NO_TREATMENT_MATCH = 3 [deprecated = true];
// The flag could not be resolved because it was archived.
RESOLVE_REASON_FLAG_ARCHIVED = 4;
// The flag could not be resolved because the targeting key field was invalid
RESOLVE_REASON_TARGETING_KEY_ERROR = 5;
// Unknown error occurred during the resolve
RESOLVE_REASON_ERROR = 6;
}

message SetResolverStateRequest {
bytes state = 1;
string account_id = 2;
}
14 changes: 14 additions & 0 deletions openfeature-provider/js/proto/messages.proto
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
syntax = "proto3";

message Void {}

message Request {
bytes data = 1;
}

message Response {
oneof result {
bytes data = 1;
string error = 2;
}
}
Loading
Loading