@satee/openfeature-provider 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +177 -2
- package/dist/flag-file.d.ts +22 -0
- package/dist/flag-file.js +107 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/provider.d.ts +26 -0
- package/dist/provider.js +256 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +1 -0
- package/package.json +57 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Satee
|
|
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,178 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @satee/openfeature-provider
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
An [OpenFeature](https://openfeature.dev) provider for reading Satee feature flags in Node.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npm install @openfeature/server-sdk @satee/openfeature-provider
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
`@openfeature/server-sdk` is a peer dependency, so install it alongside the provider.
|
|
12
|
+
|
|
13
|
+
## Use
|
|
14
|
+
|
|
15
|
+
Set `SATEE_SDK_KEY` to the key from the Setup page in Satee, then, in an ES module:
|
|
16
|
+
|
|
17
|
+
```js
|
|
18
|
+
import { OpenFeature } from "@openfeature/server-sdk";
|
|
19
|
+
import { SateeProvider } from "@satee/openfeature-provider";
|
|
20
|
+
|
|
21
|
+
const sdkKey = process.env.SATEE_SDK_KEY;
|
|
22
|
+
await OpenFeature.setProviderAndWait(new SateeProvider({ sdkKey }));
|
|
23
|
+
|
|
24
|
+
const flags = OpenFeature.getClient();
|
|
25
|
+
const on = await flags.getBooleanValue("new-checkout", false);
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Every Satee flag is boolean. Reading a flag is a lookup in memory and never waits on the network.
|
|
29
|
+
|
|
30
|
+
[`examples/`](examples) has runnable versions of this snippet, of event handlers, and of shutting down on `SIGTERM`.
|
|
31
|
+
|
|
32
|
+
## Options
|
|
33
|
+
|
|
34
|
+
| Option | Default | Meaning |
|
|
35
|
+
| ---------------- | -------------------------------- | -------------------------------------------------------------------------------------------------- |
|
|
36
|
+
| `sdkKey` | required | the server key from the Setup page, with its `satee_server_` prefix |
|
|
37
|
+
| `pollIntervalMs` | `5000` | time between polls; values below `1000` are raised to `1000`, and `NaN` or `Infinity` means `5000` |
|
|
38
|
+
| `baseUrl` | `https://flags.satee.dev` | another host, such as a local server in tests |
|
|
39
|
+
| `logger` | warnings and errors to `console` | an object with `debug`, `info`, `warn` and `error` |
|
|
40
|
+
|
|
41
|
+
The SDK key is for server code only. Never ship it in browser code: anyone who has it can read every flag.
|
|
42
|
+
|
|
43
|
+
A missing key, or one that is not `satee_server_` followed by the 24-character secret, throws from the constructor, and so
|
|
44
|
+
does a browser key (`satee_client_`). That is the only time the provider throws: a wrong key is a deployment mistake,
|
|
45
|
+
and it is best caught at start.
|
|
46
|
+
|
|
47
|
+
## How it behaves
|
|
48
|
+
|
|
49
|
+
The provider downloads your flag file at start and then checks it every `pollIntervalMs`. A check that finds no
|
|
50
|
+
change costs one small request. A change made in Satee reaches the file about a second later, so the poll interval
|
|
51
|
+
is what your app waits for.
|
|
52
|
+
|
|
53
|
+
- **At start**, `setProviderAndWait` resolves as soon as the first file loads, trying once a second for up to 5
|
|
54
|
+
seconds. A `404` or `403` ends the wait at once. It never rejects.
|
|
55
|
+
- **When flags change**, the provider swaps in the new set at once and emits `ConfigurationChanged` with the keys of
|
|
56
|
+
the flags that changed. An evaluation sees the old set or the new one, never a mix.
|
|
57
|
+
- **A file that fails its checks** is ignored, and the flags already loaded stay in place. That includes broken JSON,
|
|
58
|
+
a flag whose default is not one of its variants, an older revision, targeting rules, and a file over 4 MiB. Each
|
|
59
|
+
such file is logged once as a warning, and it counts as a failed poll.
|
|
60
|
+
- **A flag that is not in the file** returns the default you passed, with the error code `FLAG_NOT_FOUND`. Asking for
|
|
61
|
+
a flag as anything other than a boolean returns your default with `TYPE_MISMATCH`.
|
|
62
|
+
|
|
63
|
+
### When Satee cannot be reached
|
|
64
|
+
|
|
65
|
+
The provider keeps serving the last good flags it has, keeps trying, and tells you through events. Each problem is
|
|
66
|
+
reported once, when it starts, not on every failed poll.
|
|
67
|
+
|
|
68
|
+
- **Nothing loaded within 5 seconds of start**: `setProviderAndWait` resolves anyway. The SDK emits `Ready` as it
|
|
69
|
+
resolves, and the provider emits `Error` with "Could not load flags yet" straight after. Every flag returns the
|
|
70
|
+
default you passed, with `PROVIDER_NOT_READY`. Polling carries on at the normal interval. Until that `Error`
|
|
71
|
+
arrives, on the tick after the `await`, `providerStatus` still reads `READY`, so check for the `Error` event or
|
|
72
|
+
evaluate a flag rather than reading the status. A handler added after the failure gets the SDK's replay of the
|
|
73
|
+
`Error`, without the message.
|
|
74
|
+
- **No successful poll for 60 seconds** after flags were loaded: on the first failed poll 60 seconds or more after the
|
|
75
|
+
last successful one, the provider emits `Stale` with "Could not refresh flags; serving the last good values", and
|
|
76
|
+
keeps serving them. It does not emit `Stale` while an `Error` is already reported.
|
|
77
|
+
- **The key is not found (`404`)**: the provider emits `Error` with "SDK key not found. Check SATEE_SDK_KEY." if no
|
|
78
|
+
flags were loaded yet, or "SDK key no longer valid" if they were. Loaded flags keep being served; with none, every
|
|
79
|
+
flag returns `PROVIDER_NOT_READY`. Polling slows to once a minute, or to `pollIntervalMs` if that is longer.
|
|
80
|
+
- **The request is refused (`403`)**: the same, with "Request refused (403). Check SATEE_SDK_KEY and the base URL." A
|
|
81
|
+
firewall between your app and Satee can also cause this.
|
|
82
|
+
- **Any successful poll** afterwards, including one that finds no change, emits `Ready` and returns polling to the
|
|
83
|
+
normal interval.
|
|
84
|
+
|
|
85
|
+
The provider never enters the fatal state, so a key that starts working again needs no restart.
|
|
86
|
+
|
|
87
|
+
It logs each `Error` at `error`, each `Stale` and each ignored file at `warn`, a recovery at `info`, and every other
|
|
88
|
+
failed poll at `debug`. The default logger prints only warnings and errors. Log lines name a key by its last four
|
|
89
|
+
characters and never include the key or the file URL.
|
|
90
|
+
|
|
91
|
+
[`examples/events.js`](examples/events.js) shows a handler for each of these events.
|
|
92
|
+
|
|
93
|
+
## Node support
|
|
94
|
+
|
|
95
|
+
Node 22.12 or later. The package is ESM only, and CommonJS can load it with `require()`.
|
|
96
|
+
|
|
97
|
+
## TypeScript
|
|
98
|
+
|
|
99
|
+
The package ships its own types for TypeScript 5.8 or later, and they pass with `"strict": true` and
|
|
100
|
+
`"skipLibCheck": false`. CI type-checks these settings with TypeScript 5.8 and the latest TypeScript, against the
|
|
101
|
+
lowest and the latest `@openfeature/server-sdk` the peer range allows:
|
|
102
|
+
|
|
103
|
+
- `"module": "nodenext"`, from an ES module, top-level `await` included.
|
|
104
|
+
- `"module": "nodenext"`, from CommonJS (a `.cts` file). TypeScript 5.7 and earlier refuse to import an ES module
|
|
105
|
+
from CommonJS, and so does `"module": "node16"` on any version.
|
|
106
|
+
- `"moduleResolution": "bundler"`.
|
|
107
|
+
|
|
108
|
+
`"moduleResolution": "node10"` (the old `"node"`) cannot see the package's `exports` and is not supported.
|
|
109
|
+
|
|
110
|
+
## Reading the file directly
|
|
111
|
+
|
|
112
|
+
The provider reads one JSON file per key, in the [flagd](https://flagd.dev) flag format, without targeting rules. The
|
|
113
|
+
URL holds a hash of the key, never the key itself: the first 32 hex characters of the SHA-256 of `satee-flags-v1:`
|
|
114
|
+
followed by the key without its `satee_server_` prefix. `/v1/` is the version of the file format. To see what your app
|
|
115
|
+
gets, copy the flag file URL from the Setup page in Satee:
|
|
116
|
+
|
|
117
|
+
```sh
|
|
118
|
+
curl "<flag file URL from the Setup page>"
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
Or build the URL from the key:
|
|
122
|
+
|
|
123
|
+
```sh
|
|
124
|
+
KEY="${SATEE_SDK_KEY#satee_server_}"
|
|
125
|
+
curl "https://flags.satee.dev/v1/$(printf 'satee-flags-v1:%s' "$KEY" | shasum -a 256 | cut -c1-32)/flags.json"
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
## Development
|
|
129
|
+
|
|
130
|
+
CI runs these commands in this order. Run them the same way before opening a pull request:
|
|
131
|
+
|
|
132
|
+
```sh
|
|
133
|
+
npm ci
|
|
134
|
+
npm run lint
|
|
135
|
+
npm run typecheck
|
|
136
|
+
npm test
|
|
137
|
+
npm run build
|
|
138
|
+
npm run examples
|
|
139
|
+
node -e 'require("./dist/index.js")'
|
|
140
|
+
npm pack --dry-run
|
|
141
|
+
npm run check:types
|
|
142
|
+
npm run check:consumers
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
`npm run format` fixes formatting and safe lint findings in place. Node versions before 22.18 need
|
|
146
|
+
`NODE_OPTIONS=--experimental-strip-types` to run the tests, the examples and `check:live`.
|
|
147
|
+
|
|
148
|
+
`npm run check:live` reads a real file from `https://flags.satee.dev` and checks that the
|
|
149
|
+
provider serves it. Set `SATEE_SDK_KEY` to a key for that host, and `SATEE_BASE_URL` to point at another one.
|
|
150
|
+
|
|
151
|
+
`src/flag-file.ts` holds the file handling a browser provider can share: it imports nothing from `node:`, and the caller
|
|
152
|
+
passes in the SHA-256 function. Its import of `@openfeature/flagd-core` still reaches a Node built-in: flagd-core's
|
|
153
|
+
CommonJS build requires `object-hash`, which requires `crypto`. A browser provider needs one of two ways out: a bundler
|
|
154
|
+
that picks `object-hash`'s browser build, or an evaluator other than flagd-core.
|
|
155
|
+
|
|
156
|
+
## Releasing
|
|
157
|
+
|
|
158
|
+
Pushing a tag `v<version>` on main, matching `package.json`, runs `.github/workflows/publish.yml`. One job reruns the
|
|
159
|
+
checks and packs the package without any npm credentials. A second job, in the `npm` environment, publishes that exact
|
|
160
|
+
tarball through npm trusted publishing, so no npm token is stored anywhere. The `npm` environment accepts only `v*` tags
|
|
161
|
+
and waits for a maintainer to approve the run. The npm trusted publisher entry names this repository, `publish.yml` and
|
|
162
|
+
the `npm` environment, so renaming any of them breaks publishing until the entry is updated.
|
|
163
|
+
|
|
164
|
+
```sh
|
|
165
|
+
npm version patch
|
|
166
|
+
git push origin main --follow-tags
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
## Versioning
|
|
170
|
+
|
|
171
|
+
The package follows [semver](https://semver.org). While it is at 0.x, the minor number is the breaking one: a minor
|
|
172
|
+
release (`0.x.0`) may break the API, and a patch release (`0.x.y`) never does. Pin it with a tilde range, such as
|
|
173
|
+
`~0.1.0`. On a 0.x version the caret range `npm install` writes, `^0.1.0`, also stops before the next minor, so the
|
|
174
|
+
default is safe too. Read the [changelog](CHANGELOG.md) before a minor upgrade.
|
|
175
|
+
|
|
176
|
+
## License
|
|
177
|
+
|
|
178
|
+
[MIT](LICENSE)
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { FlagdCore } from "@openfeature/flagd-core";
|
|
2
|
+
import type { Logger } from "@openfeature/server-sdk";
|
|
3
|
+
type Flag = {
|
|
4
|
+
state?: unknown;
|
|
5
|
+
variants: Record<string, unknown>;
|
|
6
|
+
defaultVariant: string;
|
|
7
|
+
metadata?: unknown;
|
|
8
|
+
};
|
|
9
|
+
export type FlagSet = {
|
|
10
|
+
readonly revision: number;
|
|
11
|
+
readonly flags: Readonly<Record<string, Flag>>;
|
|
12
|
+
readonly evaluator: FlagdCore;
|
|
13
|
+
};
|
|
14
|
+
export declare class FlagFileError extends Error {
|
|
15
|
+
name: string;
|
|
16
|
+
}
|
|
17
|
+
export type Sha256Hex = (text: string) => Promise<string>;
|
|
18
|
+
export declare function flagFilePath(secret: string, sha256Hex: Sha256Hex): Promise<string>;
|
|
19
|
+
export declare function readBody(response: Response): Promise<string>;
|
|
20
|
+
export declare function parseFlagFile(body: string, heldRevision: number | undefined, logger: Logger): FlagSet;
|
|
21
|
+
export declare function changedKeys(before: FlagSet["flags"], after: FlagSet["flags"]): string[];
|
|
22
|
+
export {};
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { FlagdCore } from "@openfeature/flagd-core";
|
|
2
|
+
const MAX_BODY_BYTES = 4 * 1024 * 1024;
|
|
3
|
+
export class FlagFileError extends Error {
|
|
4
|
+
name = "FlagFileError";
|
|
5
|
+
}
|
|
6
|
+
// The URL carries a hash rather than the key, so the key stays out of access logs and bucket listings.
|
|
7
|
+
export async function flagFilePath(secret, sha256Hex) {
|
|
8
|
+
const hash = await sha256Hex(`satee-flags-v1:${secret}`);
|
|
9
|
+
if (!/^[0-9a-f]{64}$/.test(hash))
|
|
10
|
+
throw new FlagFileError("hash is not SHA-256 hex");
|
|
11
|
+
const pathId = hash.slice(0, 32);
|
|
12
|
+
return `/v1/${pathId}/flags.json`;
|
|
13
|
+
}
|
|
14
|
+
export async function readBody(response) {
|
|
15
|
+
if (Number(response.headers.get("content-length")) > MAX_BODY_BYTES) {
|
|
16
|
+
await response.body?.cancel();
|
|
17
|
+
throw new FlagFileError("file is larger than 4 MiB");
|
|
18
|
+
}
|
|
19
|
+
if (!response.body)
|
|
20
|
+
return "";
|
|
21
|
+
const decoder = new TextDecoder("utf-8", { ignoreBOM: true });
|
|
22
|
+
let text = "";
|
|
23
|
+
let size = 0;
|
|
24
|
+
const reader = response.body.getReader();
|
|
25
|
+
for (;;) {
|
|
26
|
+
const { done, value } = await reader.read();
|
|
27
|
+
if (done)
|
|
28
|
+
break;
|
|
29
|
+
size += value.byteLength;
|
|
30
|
+
if (size > MAX_BODY_BYTES) {
|
|
31
|
+
await reader.cancel();
|
|
32
|
+
throw new FlagFileError("file is larger than 4 MiB");
|
|
33
|
+
}
|
|
34
|
+
text += decoder.decode(value, { stream: true });
|
|
35
|
+
}
|
|
36
|
+
return text + decoder.decode();
|
|
37
|
+
}
|
|
38
|
+
const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
39
|
+
// Compares values as JSON.parse produces them, so key order does not matter.
|
|
40
|
+
function jsonEqual(a, b) {
|
|
41
|
+
if (Array.isArray(a) || Array.isArray(b)) {
|
|
42
|
+
return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((v, i) => jsonEqual(v, b[i]));
|
|
43
|
+
}
|
|
44
|
+
if (!isObject(a) || !isObject(b))
|
|
45
|
+
return Object.is(a, b);
|
|
46
|
+
const keys = Object.keys(a);
|
|
47
|
+
return keys.length === Object.keys(b).length && keys.every((k) => Object.hasOwn(b, k) && jsonEqual(a[k], b[k]));
|
|
48
|
+
}
|
|
49
|
+
const hasTargeting = (flag) => isObject(flag) && Object.hasOwn(flag, "targeting") && !jsonEqual(flag.targeting, {});
|
|
50
|
+
const isFlag = (flag) => isObject(flag) &&
|
|
51
|
+
isObject(flag.variants) &&
|
|
52
|
+
typeof flag.defaultVariant === "string" &&
|
|
53
|
+
Object.hasOwn(flag.variants, flag.defaultVariant);
|
|
54
|
+
const FLAG_FIELDS = ["state", "variants", "defaultVariant", "metadata"];
|
|
55
|
+
export function parseFlagFile(body, heldRevision, logger) {
|
|
56
|
+
let file;
|
|
57
|
+
try {
|
|
58
|
+
file = JSON.parse(body);
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
throw new FlagFileError("file is not valid JSON");
|
|
62
|
+
}
|
|
63
|
+
if (!isObject(file) || !isObject(file.flags) || "$evaluators" in file) {
|
|
64
|
+
throw new FlagFileError("file is not a Satee flag file");
|
|
65
|
+
}
|
|
66
|
+
if (Object.values(file.flags).some(hasTargeting))
|
|
67
|
+
throw new FlagFileError("file carries targeting rules");
|
|
68
|
+
// Targeting is JSON Logic that flagd-core runs on the event loop, where a few hundred bytes can
|
|
69
|
+
// block it for minutes. flagd-core reads keys this check cannot see (inherited through a flag's
|
|
70
|
+
// "__proto__"), so it gets a body holding only the fields copied here.
|
|
71
|
+
const flagsOnly = Object.fromEntries(Object.entries(file.flags).map(([key, flag]) => [
|
|
72
|
+
key,
|
|
73
|
+
isObject(flag)
|
|
74
|
+
? Object.fromEntries(FLAG_FIELDS.filter((f) => Object.hasOwn(flag, f)).map((f) => [f, flag[f]]))
|
|
75
|
+
: flag,
|
|
76
|
+
]));
|
|
77
|
+
const invalid = Object.keys(flagsOnly).find((key) => !isFlag(flagsOnly[key]));
|
|
78
|
+
if (invalid !== undefined)
|
|
79
|
+
throw new FlagFileError(`flag "${invalid}" needs variants and a defaultVariant among them`);
|
|
80
|
+
const revision = isObject(file.metadata) ? file.metadata.revision : undefined;
|
|
81
|
+
if (typeof revision !== "number" || !Number.isInteger(revision)) {
|
|
82
|
+
throw new FlagFileError("file has no integer metadata.revision");
|
|
83
|
+
}
|
|
84
|
+
if (heldRevision !== undefined && revision < heldRevision) {
|
|
85
|
+
throw new FlagFileError(`revision ${revision} is older than the held revision ${heldRevision}`);
|
|
86
|
+
}
|
|
87
|
+
const evaluator = new FlagdCore(undefined, {
|
|
88
|
+
debug: () => { },
|
|
89
|
+
info: () => { },
|
|
90
|
+
warn: (...args) => logger.warn("Satee: flagd:", ...args),
|
|
91
|
+
error: (...args) => logger.error("Satee: flagd:", ...args),
|
|
92
|
+
});
|
|
93
|
+
try {
|
|
94
|
+
evaluator.setConfigurations(JSON.stringify({ flags: flagsOnly, metadata: file.metadata }));
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
throw new FlagFileError("file is not a valid flagd configuration");
|
|
98
|
+
}
|
|
99
|
+
return { revision, flags: flagsOnly, evaluator };
|
|
100
|
+
}
|
|
101
|
+
export function changedKeys(before, after) {
|
|
102
|
+
return [...new Set([...Object.keys(before), ...Object.keys(after)])].filter((key) => {
|
|
103
|
+
const was = Object.hasOwn(before, key) ? before[key] : undefined;
|
|
104
|
+
const now = Object.hasOwn(after, key) ? after[key] : undefined;
|
|
105
|
+
return !jsonEqual(was, now);
|
|
106
|
+
});
|
|
107
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { SateeProvider, type SateeProviderOptions } from "./provider.ts";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { SateeProvider } from "./provider.js";
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { type EvaluationContext, type JsonValue, type Logger, OpenFeatureEventEmitter, type Provider, type ResolutionDetails } from "@openfeature/server-sdk";
|
|
2
|
+
import { type Sha256Hex } from "./flag-file.ts";
|
|
3
|
+
export type SateeProviderOptions = {
|
|
4
|
+
sdkKey: string | undefined;
|
|
5
|
+
pollIntervalMs?: number;
|
|
6
|
+
baseUrl?: string;
|
|
7
|
+
logger?: Logger;
|
|
8
|
+
};
|
|
9
|
+
/** Lets tests shorten the waits that the public options do not expose. */
|
|
10
|
+
export declare const testTiming: unique symbol;
|
|
11
|
+
export declare const sha256Hex: Sha256Hex;
|
|
12
|
+
export declare class SateeProvider implements Provider {
|
|
13
|
+
#private;
|
|
14
|
+
readonly metadata: {
|
|
15
|
+
readonly name: "Satee";
|
|
16
|
+
};
|
|
17
|
+
readonly runsOn = "server";
|
|
18
|
+
readonly events: OpenFeatureEventEmitter;
|
|
19
|
+
constructor(options: SateeProviderOptions);
|
|
20
|
+
initialize(): Promise<void>;
|
|
21
|
+
onClose(): Promise<void>;
|
|
22
|
+
resolveBooleanEvaluation(key: string, defaultValue: boolean, context: EvaluationContext, logger: Logger): Promise<ResolutionDetails<boolean>>;
|
|
23
|
+
resolveStringEvaluation(key: string, defaultValue: string, context: EvaluationContext, logger: Logger): Promise<ResolutionDetails<string>>;
|
|
24
|
+
resolveNumberEvaluation(key: string, defaultValue: number, context: EvaluationContext, logger: Logger): Promise<ResolutionDetails<number>>;
|
|
25
|
+
resolveObjectEvaluation<T extends JsonValue>(key: string, defaultValue: T, context: EvaluationContext, logger: Logger): Promise<ResolutionDetails<T>>;
|
|
26
|
+
}
|
package/dist/provider.js
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
3
|
+
import { ErrorCode, OpenFeatureEventEmitter, ProviderEvents, StandardResolutionReasons, } from "@openfeature/server-sdk";
|
|
4
|
+
import { changedKeys, FlagFileError, flagFilePath, parseFlagFile, readBody, } from "./flag-file.js";
|
|
5
|
+
import { VERSION } from "./version.js";
|
|
6
|
+
const KEY_PREFIX = "satee_server_";
|
|
7
|
+
const BROWSER_KEY_PREFIX = "satee_client_";
|
|
8
|
+
const SECRET_FORMAT = /^[1-9A-HJ-NP-Za-km-z]{24}$/;
|
|
9
|
+
const REQUEST_TIMEOUT_MS = 5000;
|
|
10
|
+
const MAX_TIMER_MS = 2 ** 31 - 1;
|
|
11
|
+
/** Lets tests shorten the waits that the public options do not expose. */
|
|
12
|
+
export const testTiming = Symbol("satee.testTiming");
|
|
13
|
+
const DEFAULT_TIMING = {
|
|
14
|
+
minPollMs: 1000,
|
|
15
|
+
startupMs: 5000,
|
|
16
|
+
startupRetryMs: 1000,
|
|
17
|
+
staleAfterMs: 60_000,
|
|
18
|
+
refusedPollMs: 60_000,
|
|
19
|
+
};
|
|
20
|
+
const REFUSED_MESSAGE = "Request refused (403). Check SATEE_SDK_KEY and the base URL.";
|
|
21
|
+
const consoleLogger = {
|
|
22
|
+
debug: () => { },
|
|
23
|
+
info: () => { },
|
|
24
|
+
warn: (...args) => console.warn(...args),
|
|
25
|
+
error: (...args) => console.error(...args),
|
|
26
|
+
};
|
|
27
|
+
export const sha256Hex = async (text) => createHash("sha256").update(text).digest("hex");
|
|
28
|
+
// Never the message of other errors: fetch puts the whole URL, path id included, in some of them.
|
|
29
|
+
function describeFailure(error) {
|
|
30
|
+
if (error instanceof FlagFileError)
|
|
31
|
+
return error.message;
|
|
32
|
+
if (!(error instanceof Error))
|
|
33
|
+
return "unknown error";
|
|
34
|
+
const code = error.cause?.code;
|
|
35
|
+
return typeof code === "string" ? `${error.name}: ${code}` : error.name;
|
|
36
|
+
}
|
|
37
|
+
export class SateeProvider {
|
|
38
|
+
metadata = { name: "Satee" };
|
|
39
|
+
runsOn = "server";
|
|
40
|
+
events = new OpenFeatureEventEmitter();
|
|
41
|
+
#url;
|
|
42
|
+
#keyHint;
|
|
43
|
+
#logger;
|
|
44
|
+
#pollIntervalMs;
|
|
45
|
+
#timing;
|
|
46
|
+
#closed = new AbortController();
|
|
47
|
+
#held;
|
|
48
|
+
#etag = null;
|
|
49
|
+
#rejected;
|
|
50
|
+
#timer;
|
|
51
|
+
#lastSuccessAt = 0;
|
|
52
|
+
#refused = false;
|
|
53
|
+
#episode;
|
|
54
|
+
constructor(options) {
|
|
55
|
+
const sdkKey = options?.sdkKey;
|
|
56
|
+
if (typeof sdkKey === "string" && sdkKey.startsWith(BROWSER_KEY_PREFIX)) {
|
|
57
|
+
throw new Error("This is a browser key. Use the server key from the Setup page.");
|
|
58
|
+
}
|
|
59
|
+
if (typeof sdkKey !== "string" ||
|
|
60
|
+
!sdkKey.startsWith(KEY_PREFIX) ||
|
|
61
|
+
!SECRET_FORMAT.test(sdkKey.slice(KEY_PREFIX.length))) {
|
|
62
|
+
throw new Error(`Satee SDK key is missing or is not a server key ("${KEY_PREFIX}" followed by 24 characters). Set SATEE_SDK_KEY to the key from the Setup page.`);
|
|
63
|
+
}
|
|
64
|
+
const baseUrl = (options.baseUrl ?? "https://flags.satee.dev").replace(/\/+$/, "");
|
|
65
|
+
const secret = sdkKey.slice(KEY_PREFIX.length);
|
|
66
|
+
this.#url = flagFilePath(secret, sha256Hex).then((path) => `${baseUrl}${path}`);
|
|
67
|
+
// The first poll reports a rejection; until then it must not reach Node as unhandled, with the key in it.
|
|
68
|
+
this.#url.catch(() => { });
|
|
69
|
+
this.#keyHint = `key ending ${secret.slice(-4)}`;
|
|
70
|
+
this.#logger = neverThrowing(options.logger ?? consoleLogger);
|
|
71
|
+
this.#timing = { ...DEFAULT_TIMING, ...options[testTiming] };
|
|
72
|
+
const requested = options.pollIntervalMs;
|
|
73
|
+
const interval = requested !== undefined && Number.isFinite(requested) ? requested : 5000;
|
|
74
|
+
this.#pollIntervalMs = Math.min(MAX_TIMER_MS, Math.max(this.#timing.minPollMs, interval));
|
|
75
|
+
}
|
|
76
|
+
async initialize() {
|
|
77
|
+
this.#closed = new AbortController();
|
|
78
|
+
const { signal } = this.#closed;
|
|
79
|
+
this.#episode = undefined;
|
|
80
|
+
this.#refused = false;
|
|
81
|
+
const deadline = Date.now() + this.#timing.startupMs;
|
|
82
|
+
let result;
|
|
83
|
+
for (;;) {
|
|
84
|
+
const attemptAt = Date.now();
|
|
85
|
+
result = await this.#poll(signal, Math.max(1, deadline - attemptAt));
|
|
86
|
+
if (signal.aborted)
|
|
87
|
+
return;
|
|
88
|
+
const retryAt = Math.max(Date.now(), attemptAt + this.#timing.startupRetryMs);
|
|
89
|
+
if (result.kind !== "failed" || retryAt >= deadline)
|
|
90
|
+
break;
|
|
91
|
+
this.#logFailedPoll(result);
|
|
92
|
+
await sleep(Math.max(0, retryAt - Date.now()), undefined, { signal }).catch(() => { });
|
|
93
|
+
if (signal.aborted)
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
// The SDK marks the provider ready once this resolves, so a start-up Error must come after that.
|
|
97
|
+
setImmediate(() => this.#settle(result, signal, true));
|
|
98
|
+
}
|
|
99
|
+
async onClose() {
|
|
100
|
+
this.#closed.abort();
|
|
101
|
+
clearTimeout(this.#timer);
|
|
102
|
+
}
|
|
103
|
+
// Each start owns its signal, so a poll that outlives a close cannot revive polling after a restart.
|
|
104
|
+
#scheduleNextPoll(signal) {
|
|
105
|
+
if (signal.aborted)
|
|
106
|
+
return;
|
|
107
|
+
const delay = this.#refused ? Math.max(this.#pollIntervalMs, this.#timing.refusedPollMs) : this.#pollIntervalMs;
|
|
108
|
+
this.#timer = setTimeout(async () => {
|
|
109
|
+
this.#settle(await this.#poll(signal), signal, false);
|
|
110
|
+
}, delay).unref();
|
|
111
|
+
}
|
|
112
|
+
#settle(result, signal, atStartup) {
|
|
113
|
+
if (signal.aborted)
|
|
114
|
+
return;
|
|
115
|
+
try {
|
|
116
|
+
this.#report(result, atStartup);
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
// A throwing logger or event handler must not stop polling.
|
|
120
|
+
}
|
|
121
|
+
finally {
|
|
122
|
+
this.#scheduleNextPoll(signal);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
#report(result, atStartup) {
|
|
126
|
+
if (result.kind === "loaded" || result.kind === "unchanged") {
|
|
127
|
+
this.#lastSuccessAt = Date.now();
|
|
128
|
+
this.#refused = false;
|
|
129
|
+
if (this.#episode) {
|
|
130
|
+
this.#episode = undefined;
|
|
131
|
+
this.#logger.info(`Satee: flags for ${this.#keyHint} are loading again`);
|
|
132
|
+
this.events.emit(ProviderEvents.Ready);
|
|
133
|
+
}
|
|
134
|
+
if (result.kind === "loaded" && !atStartup && result.changed.length > 0) {
|
|
135
|
+
this.events.emit(ProviderEvents.ConfigurationChanged, { flagsChanged: result.changed });
|
|
136
|
+
}
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
if (result.kind === "refused") {
|
|
140
|
+
this.#refused = true;
|
|
141
|
+
if (result.status === 403)
|
|
142
|
+
this.#begin("error", REFUSED_MESSAGE);
|
|
143
|
+
else
|
|
144
|
+
this.#begin("error", this.#held ? "SDK key no longer valid" : "SDK key not found. Check SATEE_SDK_KEY.");
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
this.#logFailedPoll(result);
|
|
148
|
+
if (!this.#held) {
|
|
149
|
+
if (atStartup)
|
|
150
|
+
this.#begin("error", "Could not load flags yet", result.reason);
|
|
151
|
+
}
|
|
152
|
+
else if (Date.now() - this.#lastSuccessAt >= this.#timing.staleAfterMs) {
|
|
153
|
+
this.#begin("stale", "Could not refresh flags; serving the last good values", result.reason);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
#logFailedPoll(result) {
|
|
157
|
+
if (result.ignoredFile)
|
|
158
|
+
this.#logger.warn(`Satee: ignored a flag file for ${this.#keyHint} (${result.reason})`);
|
|
159
|
+
else
|
|
160
|
+
this.#logger.debug(`Satee: poll failed for ${this.#keyHint} (${result.reason})`);
|
|
161
|
+
}
|
|
162
|
+
// An episode runs from the first failure to the next successful poll. A problem is not reported again while it
|
|
163
|
+
// persists, and Stale never replaces an Error.
|
|
164
|
+
#begin(kind, message, reason) {
|
|
165
|
+
const current = this.#episode;
|
|
166
|
+
if (current && (kind === "stale" || current.message === message))
|
|
167
|
+
return;
|
|
168
|
+
this.#episode = { kind, message };
|
|
169
|
+
const line = `Satee: ${message} (${this.#keyHint}${reason ? `, ${reason}` : ""})`;
|
|
170
|
+
if (kind === "error") {
|
|
171
|
+
this.#logger.error(line);
|
|
172
|
+
this.events.emit(ProviderEvents.Error, { message });
|
|
173
|
+
}
|
|
174
|
+
else {
|
|
175
|
+
this.#logger.warn(line);
|
|
176
|
+
this.events.emit(ProviderEvents.Stale, { message });
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
async #poll(signal, timeoutMs = REQUEST_TIMEOUT_MS) {
|
|
180
|
+
const headers = { "User-Agent": `satee-openfeature-node/${VERSION}` };
|
|
181
|
+
if (this.#etag !== null)
|
|
182
|
+
headers["If-None-Match"] = this.#etag;
|
|
183
|
+
let etag = null;
|
|
184
|
+
try {
|
|
185
|
+
const response = await fetch(await this.#url, {
|
|
186
|
+
headers,
|
|
187
|
+
signal: AbortSignal.any([AbortSignal.timeout(Math.min(REQUEST_TIMEOUT_MS, timeoutMs)), signal]),
|
|
188
|
+
});
|
|
189
|
+
etag = response.headers.get("etag");
|
|
190
|
+
if (response.status === 304 || (response.status === 200 && etag !== null && etag === this.#etag)) {
|
|
191
|
+
await response.body?.cancel();
|
|
192
|
+
return { kind: "unchanged" };
|
|
193
|
+
}
|
|
194
|
+
if (response.status !== 200) {
|
|
195
|
+
await response.body?.cancel();
|
|
196
|
+
if (response.status === 403 || response.status === 404)
|
|
197
|
+
return { kind: "refused", status: response.status };
|
|
198
|
+
return { kind: "failed", reason: `HTTP ${response.status}` };
|
|
199
|
+
}
|
|
200
|
+
const next = parseFlagFile(await readBody(response), this.#held?.revision, this.#logger);
|
|
201
|
+
if (signal.aborted)
|
|
202
|
+
return { kind: "failed", reason: "closed" };
|
|
203
|
+
const changed = changedKeys(this.#held?.flags ?? {}, next.flags);
|
|
204
|
+
this.#held = next;
|
|
205
|
+
this.#etag = etag;
|
|
206
|
+
this.#rejected = undefined;
|
|
207
|
+
return { kind: "loaded", changed };
|
|
208
|
+
}
|
|
209
|
+
catch (error) {
|
|
210
|
+
const reason = describeFailure(error);
|
|
211
|
+
const ignoredFile = error instanceof FlagFileError && this.#rejected !== (etag ?? reason);
|
|
212
|
+
if (ignoredFile)
|
|
213
|
+
this.#rejected = etag ?? reason;
|
|
214
|
+
return { kind: "failed", reason, ignoredFile };
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
resolveBooleanEvaluation(key, defaultValue, context, logger) {
|
|
218
|
+
return this.#resolve((flags) => flags.resolveBooleanEvaluation(key, defaultValue, context, logger), defaultValue);
|
|
219
|
+
}
|
|
220
|
+
resolveStringEvaluation(key, defaultValue, context, logger) {
|
|
221
|
+
return this.#resolve((flags) => flags.resolveStringEvaluation(key, defaultValue, context, logger), defaultValue);
|
|
222
|
+
}
|
|
223
|
+
resolveNumberEvaluation(key, defaultValue, context, logger) {
|
|
224
|
+
return this.#resolve((flags) => flags.resolveNumberEvaluation(key, defaultValue, context, logger), defaultValue);
|
|
225
|
+
}
|
|
226
|
+
resolveObjectEvaluation(key, defaultValue, context, logger) {
|
|
227
|
+
return this.#resolve((flags) => flags.resolveObjectEvaluation(key, defaultValue, context, logger), defaultValue);
|
|
228
|
+
}
|
|
229
|
+
async #resolve(evaluate, defaultValue) {
|
|
230
|
+
const held = this.#held;
|
|
231
|
+
if (!held) {
|
|
232
|
+
return {
|
|
233
|
+
value: defaultValue,
|
|
234
|
+
reason: StandardResolutionReasons.ERROR,
|
|
235
|
+
errorCode: ErrorCode.PROVIDER_NOT_READY,
|
|
236
|
+
errorMessage: "Satee flags are not loaded yet",
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
return evaluate(held.evaluator);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
// A logger that throws must not cost the event that follows its line, so each call is contained.
|
|
243
|
+
function neverThrowing(logger) {
|
|
244
|
+
const contain = (write) => (...args) => {
|
|
245
|
+
try {
|
|
246
|
+
write.apply(logger, args);
|
|
247
|
+
}
|
|
248
|
+
catch { }
|
|
249
|
+
};
|
|
250
|
+
return {
|
|
251
|
+
debug: contain(logger.debug),
|
|
252
|
+
info: contain(logger.info),
|
|
253
|
+
warn: contain(logger.warn),
|
|
254
|
+
error: contain(logger.error),
|
|
255
|
+
};
|
|
256
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const VERSION = "0.1.0";
|
package/dist/version.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const VERSION = "0.1.0";
|
package/package.json
CHANGED
|
@@ -1,6 +1,59 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@satee/openfeature-provider",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "OpenFeature provider for reading Satee feature flags in Node",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"openfeature",
|
|
7
|
+
"feature-flags",
|
|
8
|
+
"satee"
|
|
9
|
+
],
|
|
10
|
+
"homepage": "https://github.com/satee-dev/openfeature-provider-node#readme",
|
|
11
|
+
"bugs": "https://github.com/satee-dev/openfeature-provider-node/issues",
|
|
12
|
+
"repository": {
|
|
13
|
+
"type": "git",
|
|
14
|
+
"url": "git+https://github.com/satee-dev/openfeature-provider-node.git"
|
|
15
|
+
},
|
|
16
|
+
"license": "MIT",
|
|
17
|
+
"author": "Satee",
|
|
18
|
+
"type": "module",
|
|
19
|
+
"exports": {
|
|
20
|
+
".": {
|
|
21
|
+
"types": "./dist/index.d.ts",
|
|
22
|
+
"import": "./dist/index.js",
|
|
23
|
+
"default": "./dist/index.js"
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
"files": [
|
|
27
|
+
"dist"
|
|
28
|
+
],
|
|
29
|
+
"engines": {
|
|
30
|
+
"node": ">=22.12"
|
|
31
|
+
},
|
|
32
|
+
"publishConfig": {
|
|
33
|
+
"access": "public"
|
|
34
|
+
},
|
|
35
|
+
"scripts": {
|
|
36
|
+
"lint": "biome check .",
|
|
37
|
+
"format": "biome check --write .",
|
|
38
|
+
"typecheck": "tsc -p tsconfig.json",
|
|
39
|
+
"test": "node --test \"test/**/*.test.ts\"",
|
|
40
|
+
"build": "tsc -p tsconfig.build.json",
|
|
41
|
+
"examples": "node test/run-examples.ts",
|
|
42
|
+
"check:live": "node test/check-live.ts",
|
|
43
|
+
"check:types": "npm run build && attw --pack . --profile node16 --ignore-rules cjs-resolves-to-esm",
|
|
44
|
+
"check:consumers": "npm run build && node test/run-consumers.ts"
|
|
45
|
+
},
|
|
46
|
+
"devDependencies": {
|
|
47
|
+
"@arethetypeswrong/cli": "0.18.5",
|
|
48
|
+
"@biomejs/biome": "2.6.9",
|
|
49
|
+
"@openfeature/server-sdk": "1.23.0",
|
|
50
|
+
"@types/node": "22.20.7",
|
|
51
|
+
"typescript": "7.0.2"
|
|
52
|
+
},
|
|
53
|
+
"dependencies": {
|
|
54
|
+
"@openfeature/flagd-core": "5.0.0"
|
|
55
|
+
},
|
|
56
|
+
"peerDependencies": {
|
|
57
|
+
"@openfeature/server-sdk": "^1.23.0"
|
|
58
|
+
}
|
|
59
|
+
}
|