@flagdock/node 0.0.0-stage → 0.1.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 +59 -2
- package/dist/index.d.ts +141 -0
- package/dist/index.js +424 -0
- package/package.json +58 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Flagdock
|
|
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,60 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @flagdock/node
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[Flagdock](https://flagdock.com) feature flags for Node.js services.
|
|
4
|
+
|
|
5
|
+
It is a provider for the [OpenFeature](https://openfeature.dev) server SDK. It downloads your
|
|
6
|
+
environment's rules once, answers every flag check from memory with no network call, follows
|
|
7
|
+
changes over a live stream, and keeps serving the last rules it had if Flagdock can't be reached.
|
|
8
|
+
|
|
9
|
+
## Quickstart
|
|
10
|
+
|
|
11
|
+
1. Install:
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
npm install @flagdock/node @openfeature/server-sdk
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
2. Create a **server** SDK key in the Flagdock console (SDK keys page) and put it in your
|
|
18
|
+
app's environment as `FLAGDOCK_KEY`.
|
|
19
|
+
|
|
20
|
+
3. Check a flag:
|
|
21
|
+
|
|
22
|
+
```ts
|
|
23
|
+
import { OpenFeature } from '@openfeature/server-sdk';
|
|
24
|
+
import { FlagdockProvider } from '@flagdock/node';
|
|
25
|
+
|
|
26
|
+
await OpenFeature.setProviderAndWait(
|
|
27
|
+
new FlagdockProvider({ key: process.env.FLAGDOCK_KEY!, appName: 'checkout-api' }),
|
|
28
|
+
);
|
|
29
|
+
|
|
30
|
+
const flags = OpenFeature.getClient();
|
|
31
|
+
if (await flags.getBooleanValue('new-checkout', false, { targetingKey: user.id, plan: user.plan })) {
|
|
32
|
+
// the new code path
|
|
33
|
+
}
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Server keys can read your targeting rules, so keep them on the server. For web pages use
|
|
37
|
+
[`@flagdock/web`](https://www.npmjs.com/package/@flagdock/web) with a browser key.
|
|
38
|
+
|
|
39
|
+
## Options
|
|
40
|
+
|
|
41
|
+
| Option | Default | What it does |
|
|
42
|
+
| --- | --- | --- |
|
|
43
|
+
| `key` | (required) | A server SDK key (`hbf_srv_…`) for one environment. |
|
|
44
|
+
| `appName` | | Name shown under "Connected apps" in the console. |
|
|
45
|
+
| `snapshotFile` | | Keeps the last rules on disk, so a restart during an outage still has flags. |
|
|
46
|
+
| `bootstrapFile` | | A ruleset JSON file to start from when nothing else is available. |
|
|
47
|
+
| `pollIntervalMs` | `15000` | How often to ask for changes while the live stream is down. |
|
|
48
|
+
| `staleAfterMs` | `300000` | How long without a sync before the provider reports itself stale. |
|
|
49
|
+
| `startTimeoutMs` | `10000` | How long `initialize` waits for the first download. |
|
|
50
|
+
| `usageIntervalMs` | `60000` | How often usage counts are sent; `0` turns reporting off. |
|
|
51
|
+
| `url`, `fallbackUrls` | Flagdock edge, then control plane | Where the rules come from. |
|
|
52
|
+
|
|
53
|
+
## More
|
|
54
|
+
|
|
55
|
+
- `provider.rotateKey(newKey)` switches keys without a restart.
|
|
56
|
+
- `provider.explain(flagKey, context)` returns the answer plus what every rule looked at.
|
|
57
|
+
- `flags.track('order-completed', { targetingKey: user.id }, { value: order.total })` reports a
|
|
58
|
+
goal event, which the console uses to compare the values of a flag.
|
|
59
|
+
|
|
60
|
+
MIT licensed. Questions: info@flagdock.com
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { OpenFeatureEventEmitter, type EvaluationContext, type JsonValue, type Logger, type Provider, type ResolutionDetails } from '@openfeature/server-sdk';
|
|
2
|
+
import { type Resolution, type TraceStep } from '@flagdock/core';
|
|
3
|
+
export interface FlagdockOptions {
|
|
4
|
+
/** A server SDK key (`hbf_srv_…`) for one environment. */
|
|
5
|
+
key: string;
|
|
6
|
+
/** Where to get the rules from. Defaults to the Flagdock edge, `https://edge.flagdock.com`. */
|
|
7
|
+
url?: string;
|
|
8
|
+
/**
|
|
9
|
+
* More places to get the rules from, tried in order when `url` cannot be reached or answers
|
|
10
|
+
* with a server error: for example the edge first in `url`, then the control plane here.
|
|
11
|
+
* The provider stays with whichever answered last. When `url` is left out this defaults to
|
|
12
|
+
* the Flagdock control plane, `https://app.flagdock.com`.
|
|
13
|
+
*/
|
|
14
|
+
fallbackUrls?: string[];
|
|
15
|
+
/**
|
|
16
|
+
* Path of a ruleset JSON file to start from when the server cannot be
|
|
17
|
+
* reached at startup, so a cold start with no network still has flags.
|
|
18
|
+
*/
|
|
19
|
+
bootstrapFile?: string;
|
|
20
|
+
/**
|
|
21
|
+
* Path where the provider keeps the last rules it downloaded. After a restart with the
|
|
22
|
+
* server unreachable it starts from this file, so a deploy during an outage still gets the
|
|
23
|
+
* newest rules this machine ever saw. Tried before `bootstrapFile`. The file holds targeting
|
|
24
|
+
* rules, so keep it out of public folders.
|
|
25
|
+
*/
|
|
26
|
+
snapshotFile?: string;
|
|
27
|
+
/** How often to ask for changes while the live stream is down. Default 15 seconds. */
|
|
28
|
+
pollIntervalMs?: number;
|
|
29
|
+
/** How long without a successful sync before the provider reports itself stale. Default 5 minutes. */
|
|
30
|
+
staleAfterMs?: number;
|
|
31
|
+
/** How long `initialize` waits for the first download. Default 10 seconds. */
|
|
32
|
+
startTimeoutMs?: number;
|
|
33
|
+
/** Name shown under "Connected apps" in the console, for example `checkout-api`. */
|
|
34
|
+
appName?: string;
|
|
35
|
+
/** How often usage counts are sent. Default 60 seconds; 0 turns reporting off. */
|
|
36
|
+
usageIntervalMs?: number;
|
|
37
|
+
/** Replace `fetch`, mainly for tests. */
|
|
38
|
+
fetch?: typeof fetch;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* OpenFeature provider for Flagdock.
|
|
42
|
+
*
|
|
43
|
+
* It downloads the environment's rules once, keeps them in memory and answers
|
|
44
|
+
* every flag check from there with no network call. A live stream tells it
|
|
45
|
+
* when to download again; if the stream drops it polls until it is back. If
|
|
46
|
+
* the server becomes unreachable it keeps serving the last rules it had.
|
|
47
|
+
*/
|
|
48
|
+
export declare class FlagdockProvider implements Provider {
|
|
49
|
+
private readonly options;
|
|
50
|
+
readonly metadata: {
|
|
51
|
+
readonly name: "flagdock";
|
|
52
|
+
};
|
|
53
|
+
readonly runsOn: "server";
|
|
54
|
+
readonly events: OpenFeatureEventEmitter;
|
|
55
|
+
private ruleset;
|
|
56
|
+
private key;
|
|
57
|
+
private rulesFrom;
|
|
58
|
+
private snapshotWrite;
|
|
59
|
+
private etag;
|
|
60
|
+
private lastSync;
|
|
61
|
+
private stale;
|
|
62
|
+
private closed;
|
|
63
|
+
private streamUp;
|
|
64
|
+
private streamAbort;
|
|
65
|
+
private pollTimer;
|
|
66
|
+
private staleTimer;
|
|
67
|
+
private syncing;
|
|
68
|
+
private syncAgain;
|
|
69
|
+
private readonly usage;
|
|
70
|
+
private readonly activity;
|
|
71
|
+
private readonly instanceId;
|
|
72
|
+
private usageTimer;
|
|
73
|
+
private readonly usageIntervalMs;
|
|
74
|
+
private readonly bases;
|
|
75
|
+
/** Index in `bases` of the place that answered last. */
|
|
76
|
+
private current;
|
|
77
|
+
/** The newest version the stream announced, asked for by number so every cache serves that one. */
|
|
78
|
+
private announced;
|
|
79
|
+
private readonly fetchFn;
|
|
80
|
+
private readonly pollIntervalMs;
|
|
81
|
+
private readonly staleAfterMs;
|
|
82
|
+
private readonly startTimeoutMs;
|
|
83
|
+
constructor(options: FlagdockOptions);
|
|
84
|
+
/** Where the rules in memory came from: the server, the snapshot file or the bootstrap file. */
|
|
85
|
+
get rulesSource(): 'server' | 'snapshot' | 'bootstrap' | undefined;
|
|
86
|
+
/** When the provider last heard from the server, or undefined if it never has. */
|
|
87
|
+
get lastSyncedAt(): Date | undefined;
|
|
88
|
+
/**
|
|
89
|
+
* Switches to another SDK key without a restart: create the new key in the console, call this,
|
|
90
|
+
* then revoke the old one. The rules in memory stay in use the whole time.
|
|
91
|
+
*/
|
|
92
|
+
rotateKey(key: string): Promise<void>;
|
|
93
|
+
/** Version of the rules currently in memory, or undefined before the first load. */
|
|
94
|
+
get rulesetVersion(): number | undefined;
|
|
95
|
+
initialize(): Promise<void>;
|
|
96
|
+
onClose(): Promise<void>;
|
|
97
|
+
/**
|
|
98
|
+
* Sends the usage counted so far. Runs on a timer and on close; call it
|
|
99
|
+
* yourself before a short-lived process exits. Never throws.
|
|
100
|
+
*/
|
|
101
|
+
flushUsage(): Promise<void>;
|
|
102
|
+
/**
|
|
103
|
+
* Reports that a person did something, such as placing an order. Flagdock compares how often people
|
|
104
|
+
* reach a flag's goal depending on the value they got. Called by OpenFeature's `client.track(name, context, { value })`.
|
|
105
|
+
* Needs the person's ID (targetingKey) in the context; without one the event is dropped.
|
|
106
|
+
*/
|
|
107
|
+
track(trackingEventName: string, context?: EvaluationContext, trackingEventDetails?: {
|
|
108
|
+
value?: number;
|
|
109
|
+
}): void;
|
|
110
|
+
private headers;
|
|
111
|
+
/**
|
|
112
|
+
* Calls the place that answered last, then the others in order. A network error or a server
|
|
113
|
+
* error (5xx) moves on to the next; any other answer is final.
|
|
114
|
+
*/
|
|
115
|
+
private request;
|
|
116
|
+
private download;
|
|
117
|
+
/** Written to a temporary file first, so a crash never leaves half a snapshot. Failing to write is not fatal. */
|
|
118
|
+
private saveSnapshot;
|
|
119
|
+
private synced;
|
|
120
|
+
private checkStale;
|
|
121
|
+
/** At most one download runs at a time; a request that arrives meanwhile triggers one more afterwards. */
|
|
122
|
+
private sync;
|
|
123
|
+
private startPolling;
|
|
124
|
+
private stopPolling;
|
|
125
|
+
private runStream;
|
|
126
|
+
private onStreamEvent;
|
|
127
|
+
private resolve;
|
|
128
|
+
/**
|
|
129
|
+
* Explains what a flag returns for one context and why: the answer plus what each rule looked at.
|
|
130
|
+
* For debugging; it is not counted as usage. Returns null before the first rules arrive.
|
|
131
|
+
*/
|
|
132
|
+
explain(flagKey: string, context: EvaluationContext): {
|
|
133
|
+
resolution: Resolution;
|
|
134
|
+
trace: TraceStep[];
|
|
135
|
+
rulesetVersion: number;
|
|
136
|
+
} | null;
|
|
137
|
+
resolveBooleanEvaluation(flagKey: string, defaultValue: boolean, context: EvaluationContext, _logger?: Logger): Promise<ResolutionDetails<boolean>>;
|
|
138
|
+
resolveStringEvaluation(flagKey: string, defaultValue: string, context: EvaluationContext, _logger?: Logger): Promise<ResolutionDetails<string>>;
|
|
139
|
+
resolveNumberEvaluation(flagKey: string, defaultValue: number, context: EvaluationContext, _logger?: Logger): Promise<ResolutionDetails<number>>;
|
|
140
|
+
resolveObjectEvaluation<T extends JsonValue>(flagKey: string, defaultValue: T, context: EvaluationContext, _logger?: Logger): Promise<ResolutionDetails<T>>;
|
|
141
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,424 @@
|
|
|
1
|
+
import { readFile, rename, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { ErrorCode, OpenFeatureEventEmitter, ProviderEvents, } from '@openfeature/server-sdk';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { ActivityLog, evaluate, UsageCounter } from '@flagdock/core';
|
|
5
|
+
const SDK_NAME = 'node';
|
|
6
|
+
const SDK_VERSION = '0.1.1';
|
|
7
|
+
const DEFAULT_URL = 'https://edge.flagdock.com';
|
|
8
|
+
const DEFAULT_FALLBACK_URL = 'https://app.flagdock.com';
|
|
9
|
+
async function readRuleset(file) {
|
|
10
|
+
try {
|
|
11
|
+
const parsed = JSON.parse(await readFile(file, 'utf8'));
|
|
12
|
+
if (typeof parsed.version !== 'number' || typeof parsed.flags !== 'object' || parsed.flags === null)
|
|
13
|
+
return undefined;
|
|
14
|
+
return { audiences: {}, ...parsed };
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return undefined;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
const ERROR_CODES = {
|
|
21
|
+
FLAG_NOT_FOUND: ErrorCode.FLAG_NOT_FOUND,
|
|
22
|
+
TYPE_MISMATCH: ErrorCode.TYPE_MISMATCH,
|
|
23
|
+
GENERAL: ErrorCode.GENERAL,
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* OpenFeature provider for Flagdock.
|
|
27
|
+
*
|
|
28
|
+
* It downloads the environment's rules once, keeps them in memory and answers
|
|
29
|
+
* every flag check from there with no network call. A live stream tells it
|
|
30
|
+
* when to download again; if the stream drops it polls until it is back. If
|
|
31
|
+
* the server becomes unreachable it keeps serving the last rules it had.
|
|
32
|
+
*/
|
|
33
|
+
export class FlagdockProvider {
|
|
34
|
+
options;
|
|
35
|
+
metadata = { name: 'flagdock' };
|
|
36
|
+
runsOn = 'server';
|
|
37
|
+
events = new OpenFeatureEventEmitter();
|
|
38
|
+
ruleset;
|
|
39
|
+
key;
|
|
40
|
+
rulesFrom;
|
|
41
|
+
snapshotWrite = Promise.resolve();
|
|
42
|
+
etag;
|
|
43
|
+
lastSync = 0;
|
|
44
|
+
stale = false;
|
|
45
|
+
closed = false;
|
|
46
|
+
streamUp = false;
|
|
47
|
+
streamAbort;
|
|
48
|
+
pollTimer;
|
|
49
|
+
staleTimer;
|
|
50
|
+
syncing;
|
|
51
|
+
syncAgain = false;
|
|
52
|
+
usage = new UsageCounter();
|
|
53
|
+
activity = new ActivityLog();
|
|
54
|
+
instanceId = randomUUID();
|
|
55
|
+
usageTimer;
|
|
56
|
+
usageIntervalMs;
|
|
57
|
+
bases;
|
|
58
|
+
/** Index in `bases` of the place that answered last. */
|
|
59
|
+
current = 0;
|
|
60
|
+
/** The newest version the stream announced, asked for by number so every cache serves that one. */
|
|
61
|
+
announced;
|
|
62
|
+
fetchFn;
|
|
63
|
+
pollIntervalMs;
|
|
64
|
+
staleAfterMs;
|
|
65
|
+
startTimeoutMs;
|
|
66
|
+
constructor(options) {
|
|
67
|
+
this.options = options;
|
|
68
|
+
if (!options.key)
|
|
69
|
+
throw new Error('FlagdockProvider needs a server SDK key');
|
|
70
|
+
this.key = options.key;
|
|
71
|
+
const fallbacks = options.fallbackUrls ?? (options.url ? [] : [DEFAULT_FALLBACK_URL]);
|
|
72
|
+
this.bases = [options.url ?? DEFAULT_URL, ...fallbacks].map((u) => u.replace(/\/+$/, ''));
|
|
73
|
+
this.fetchFn = options.fetch ?? fetch;
|
|
74
|
+
this.pollIntervalMs = options.pollIntervalMs ?? 15_000;
|
|
75
|
+
this.staleAfterMs = options.staleAfterMs ?? 5 * 60_000;
|
|
76
|
+
this.startTimeoutMs = options.startTimeoutMs ?? 10_000;
|
|
77
|
+
this.usageIntervalMs = options.usageIntervalMs ?? 60_000;
|
|
78
|
+
}
|
|
79
|
+
/** Where the rules in memory came from: the server, the snapshot file or the bootstrap file. */
|
|
80
|
+
get rulesSource() {
|
|
81
|
+
return this.rulesFrom;
|
|
82
|
+
}
|
|
83
|
+
/** When the provider last heard from the server, or undefined if it never has. */
|
|
84
|
+
get lastSyncedAt() {
|
|
85
|
+
return this.lastSync ? new Date(this.lastSync) : undefined;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Switches to another SDK key without a restart: create the new key in the console, call this,
|
|
89
|
+
* then revoke the old one. The rules in memory stay in use the whole time.
|
|
90
|
+
*/
|
|
91
|
+
async rotateKey(key) {
|
|
92
|
+
if (!key)
|
|
93
|
+
throw new Error('rotateKey needs the new SDK key');
|
|
94
|
+
this.key = key;
|
|
95
|
+
this.etag = undefined;
|
|
96
|
+
// The stream reconnects on its own with the new key.
|
|
97
|
+
this.streamAbort?.abort();
|
|
98
|
+
await this.sync();
|
|
99
|
+
}
|
|
100
|
+
/** Version of the rules currently in memory, or undefined before the first load. */
|
|
101
|
+
get rulesetVersion() {
|
|
102
|
+
return this.ruleset?.version;
|
|
103
|
+
}
|
|
104
|
+
async initialize() {
|
|
105
|
+
let firstError;
|
|
106
|
+
try {
|
|
107
|
+
await this.download(AbortSignal.timeout(this.startTimeoutMs));
|
|
108
|
+
}
|
|
109
|
+
catch (err) {
|
|
110
|
+
firstError = err;
|
|
111
|
+
// Newest first: what this machine last downloaded, then what shipped with the app.
|
|
112
|
+
for (const [from, file] of [['snapshot', this.options.snapshotFile], ['bootstrap', this.options.bootstrapFile]]) {
|
|
113
|
+
if (!file || this.ruleset)
|
|
114
|
+
continue;
|
|
115
|
+
const loaded = await readRuleset(file);
|
|
116
|
+
if (loaded) {
|
|
117
|
+
this.ruleset = loaded;
|
|
118
|
+
this.rulesFrom = from;
|
|
119
|
+
}
|
|
120
|
+
else if (from === 'bootstrap') {
|
|
121
|
+
throw new Error(`Flagdock could not read its bootstrap file ${file}`);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
// Keep trying in the background either way; a later success fixes a bad start.
|
|
126
|
+
this.staleTimer = setInterval(() => this.checkStale(), Math.min(30_000, this.staleAfterMs));
|
|
127
|
+
this.staleTimer.unref();
|
|
128
|
+
void this.runStream();
|
|
129
|
+
if (this.usageIntervalMs > 0) {
|
|
130
|
+
this.usageTimer = setInterval(() => void this.flushUsage(), this.usageIntervalMs);
|
|
131
|
+
this.usageTimer.unref();
|
|
132
|
+
}
|
|
133
|
+
if (!this.ruleset) {
|
|
134
|
+
this.startPolling();
|
|
135
|
+
throw new Error(`Flagdock could not load its rules: ${firstError instanceof Error ? firstError.message : String(firstError)}`);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
async onClose() {
|
|
139
|
+
this.closed = true;
|
|
140
|
+
this.streamAbort?.abort();
|
|
141
|
+
if (this.pollTimer)
|
|
142
|
+
clearInterval(this.pollTimer);
|
|
143
|
+
if (this.staleTimer)
|
|
144
|
+
clearInterval(this.staleTimer);
|
|
145
|
+
if (this.usageTimer)
|
|
146
|
+
clearInterval(this.usageTimer);
|
|
147
|
+
if (this.usageIntervalMs > 0)
|
|
148
|
+
await this.flushUsage();
|
|
149
|
+
await this.snapshotWrite;
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Sends the usage counted so far. Runs on a timer and on close; call it
|
|
153
|
+
* yourself before a short-lived process exits. Never throws.
|
|
154
|
+
*/
|
|
155
|
+
async flushUsage() {
|
|
156
|
+
const counts = this.usage.drain();
|
|
157
|
+
const activity = this.activity.drain();
|
|
158
|
+
try {
|
|
159
|
+
const res = await this.request('/api/v1/sdk/usage', {
|
|
160
|
+
method: 'POST',
|
|
161
|
+
headers: this.headers({ 'content-type': 'application/json' }),
|
|
162
|
+
body: JSON.stringify({
|
|
163
|
+
app: {
|
|
164
|
+
name: this.options.appName ?? 'node-app',
|
|
165
|
+
instanceId: this.instanceId,
|
|
166
|
+
sdk: SDK_NAME,
|
|
167
|
+
sdkVersion: SDK_VERSION,
|
|
168
|
+
...(this.ruleset ? { rulesetVersion: this.ruleset.version } : {}),
|
|
169
|
+
},
|
|
170
|
+
counts,
|
|
171
|
+
...(activity.exposures.length > 0 ? { exposures: activity.exposures } : {}),
|
|
172
|
+
...(activity.events.length > 0 ? { events: activity.events } : {}),
|
|
173
|
+
}),
|
|
174
|
+
signal: AbortSignal.timeout(5000),
|
|
175
|
+
});
|
|
176
|
+
if (!res.ok)
|
|
177
|
+
throw new Error(String(res.status));
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
this.usage.restore(counts);
|
|
181
|
+
this.activity.restore(activity);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Reports that a person did something, such as placing an order. Flagdock compares how often people
|
|
186
|
+
* reach a flag's goal depending on the value they got. Called by OpenFeature's `client.track(name, context, { value })`.
|
|
187
|
+
* Needs the person's ID (targetingKey) in the context; without one the event is dropped.
|
|
188
|
+
*/
|
|
189
|
+
track(trackingEventName, context, trackingEventDetails) {
|
|
190
|
+
const user = context?.targetingKey;
|
|
191
|
+
if (this.usageIntervalMs <= 0 || typeof user !== 'string' || user === '')
|
|
192
|
+
return;
|
|
193
|
+
this.activity.track(trackingEventName, user, trackingEventDetails?.value);
|
|
194
|
+
}
|
|
195
|
+
// --- Keeping the rules up to date -------------------------------------------------------------
|
|
196
|
+
headers(extra = {}) {
|
|
197
|
+
return { authorization: `Bearer ${this.key}`, ...extra };
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Calls the place that answered last, then the others in order. A network error or a server
|
|
201
|
+
* error (5xx) moves on to the next; any other answer is final.
|
|
202
|
+
*/
|
|
203
|
+
async request(path, init) {
|
|
204
|
+
let lastError;
|
|
205
|
+
for (let i = 0; i < this.bases.length; i++) {
|
|
206
|
+
const index = (this.current + i) % this.bases.length;
|
|
207
|
+
try {
|
|
208
|
+
const res = await this.fetchFn(`${this.bases[index]}${path}`, init);
|
|
209
|
+
if (res.status >= 500 && i < this.bases.length - 1) {
|
|
210
|
+
lastError = new Error(`${this.bases[index]} answered ${res.status}`);
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
213
|
+
this.current = index;
|
|
214
|
+
return res;
|
|
215
|
+
}
|
|
216
|
+
catch (err) {
|
|
217
|
+
if (init.signal?.aborted)
|
|
218
|
+
throw err;
|
|
219
|
+
lastError = err;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
throw lastError;
|
|
223
|
+
}
|
|
224
|
+
async download(signal) {
|
|
225
|
+
const wanted = this.announced !== undefined && this.announced !== this.ruleset?.version ? `?version=${this.announced}` : '';
|
|
226
|
+
const res = await this.request(`/api/v1/sdk/ruleset${wanted}`, {
|
|
227
|
+
headers: this.headers(this.etag ? { 'if-none-match': this.etag } : {}),
|
|
228
|
+
signal: signal ?? AbortSignal.timeout(10_000),
|
|
229
|
+
});
|
|
230
|
+
if (res.status === 304) {
|
|
231
|
+
this.synced();
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
if (!res.ok)
|
|
235
|
+
throw new Error(`the server answered ${res.status} to the rules download`);
|
|
236
|
+
const next = (await res.json());
|
|
237
|
+
const changed = this.ruleset !== undefined && this.ruleset.version !== next.version;
|
|
238
|
+
const previous = this.ruleset;
|
|
239
|
+
this.ruleset = next;
|
|
240
|
+
this.rulesFrom = 'server';
|
|
241
|
+
this.saveSnapshot(next);
|
|
242
|
+
this.etag = res.headers.get('etag') ?? undefined;
|
|
243
|
+
this.synced();
|
|
244
|
+
if (changed) {
|
|
245
|
+
const flagsChanged = [...new Set([...Object.keys(previous.flags), ...Object.keys(next.flags)])].filter((k) => JSON.stringify(previous.flags[k]) !== JSON.stringify(next.flags[k]));
|
|
246
|
+
// A changed audience can alter any flag, so then we name none rather than guess.
|
|
247
|
+
const audiencesChanged = JSON.stringify(previous.audiences) !== JSON.stringify(next.audiences);
|
|
248
|
+
this.events.emit(ProviderEvents.ConfigurationChanged, audiencesChanged ? {} : { flagsChanged });
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
/** Written to a temporary file first, so a crash never leaves half a snapshot. Failing to write is not fatal. */
|
|
252
|
+
saveSnapshot(ruleset) {
|
|
253
|
+
const file = this.options.snapshotFile;
|
|
254
|
+
if (!file)
|
|
255
|
+
return;
|
|
256
|
+
this.snapshotWrite = this.snapshotWrite.then(async () => {
|
|
257
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
258
|
+
try {
|
|
259
|
+
await writeFile(tmp, JSON.stringify(ruleset), { mode: 0o600 });
|
|
260
|
+
await rename(tmp, file);
|
|
261
|
+
}
|
|
262
|
+
catch {
|
|
263
|
+
// A read-only disk must not take flag checks down with it.
|
|
264
|
+
}
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
synced() {
|
|
268
|
+
this.lastSync = Date.now();
|
|
269
|
+
if (this.stale) {
|
|
270
|
+
this.stale = false;
|
|
271
|
+
this.events.emit(ProviderEvents.Ready, { message: 'Flagdock is back in sync' });
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
checkStale() {
|
|
275
|
+
if (this.stale || this.closed || Date.now() - this.lastSync < this.staleAfterMs)
|
|
276
|
+
return;
|
|
277
|
+
this.stale = true;
|
|
278
|
+
this.events.emit(ProviderEvents.Stale, { message: 'Flagdock has not reached its server for a while; serving the last known rules' });
|
|
279
|
+
}
|
|
280
|
+
/** At most one download runs at a time; a request that arrives meanwhile triggers one more afterwards. */
|
|
281
|
+
sync() {
|
|
282
|
+
if (this.syncing) {
|
|
283
|
+
this.syncAgain = true;
|
|
284
|
+
return this.syncing;
|
|
285
|
+
}
|
|
286
|
+
this.syncing = (async () => {
|
|
287
|
+
try {
|
|
288
|
+
do {
|
|
289
|
+
this.syncAgain = false;
|
|
290
|
+
await this.download().catch(() => undefined);
|
|
291
|
+
} while (this.syncAgain && !this.closed);
|
|
292
|
+
}
|
|
293
|
+
finally {
|
|
294
|
+
this.syncing = undefined;
|
|
295
|
+
}
|
|
296
|
+
})();
|
|
297
|
+
return this.syncing;
|
|
298
|
+
}
|
|
299
|
+
startPolling() {
|
|
300
|
+
if (this.pollTimer || this.closed)
|
|
301
|
+
return;
|
|
302
|
+
this.pollTimer = setInterval(() => void this.sync(), this.pollIntervalMs);
|
|
303
|
+
this.pollTimer.unref();
|
|
304
|
+
}
|
|
305
|
+
stopPolling() {
|
|
306
|
+
if (this.pollTimer)
|
|
307
|
+
clearInterval(this.pollTimer);
|
|
308
|
+
this.pollTimer = undefined;
|
|
309
|
+
}
|
|
310
|
+
async runStream() {
|
|
311
|
+
let wait = 500;
|
|
312
|
+
while (!this.closed) {
|
|
313
|
+
this.streamAbort = new AbortController();
|
|
314
|
+
try {
|
|
315
|
+
const res = await this.fetchFn(`${this.bases[this.current]}/api/v1/sdk/stream`, {
|
|
316
|
+
headers: this.headers({ accept: 'text/event-stream' }),
|
|
317
|
+
signal: this.streamAbort.signal,
|
|
318
|
+
});
|
|
319
|
+
if (!res.ok || !res.body)
|
|
320
|
+
throw new Error(`stream answered ${res.status}`);
|
|
321
|
+
this.streamUp = true;
|
|
322
|
+
this.stopPolling();
|
|
323
|
+
wait = 500;
|
|
324
|
+
const decoder = new TextDecoder();
|
|
325
|
+
let buffer = '';
|
|
326
|
+
for await (const chunk of res.body) {
|
|
327
|
+
buffer += decoder.decode(chunk, { stream: true });
|
|
328
|
+
let end;
|
|
329
|
+
while ((end = buffer.indexOf('\n\n')) >= 0) {
|
|
330
|
+
this.onStreamEvent(buffer.slice(0, end));
|
|
331
|
+
buffer = buffer.slice(end + 2);
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
catch {
|
|
336
|
+
// Fall through to polling and a later reconnect, at the next place in the list.
|
|
337
|
+
if (!this.streamUp && this.bases.length > 1)
|
|
338
|
+
this.current = (this.current + 1) % this.bases.length;
|
|
339
|
+
}
|
|
340
|
+
this.streamUp = false;
|
|
341
|
+
if (this.closed)
|
|
342
|
+
return;
|
|
343
|
+
this.startPolling();
|
|
344
|
+
await new Promise((r) => setTimeout(r, wait).unref());
|
|
345
|
+
wait = Math.min(wait * 2, 30_000);
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
onStreamEvent(block) {
|
|
349
|
+
const lines = block.split('\n');
|
|
350
|
+
const event = lines.find((l) => l.startsWith('event:'))?.slice(6).trim();
|
|
351
|
+
if (event !== 'ruleset-changed') {
|
|
352
|
+
// A heartbeat still proves the server is reachable and nothing has changed.
|
|
353
|
+
if (this.ruleset)
|
|
354
|
+
this.synced();
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
const data = lines.find((l) => l.startsWith('data:'))?.slice(5).trim();
|
|
358
|
+
let version;
|
|
359
|
+
try {
|
|
360
|
+
version = JSON.parse(data ?? '{}').version;
|
|
361
|
+
}
|
|
362
|
+
catch {
|
|
363
|
+
version = undefined;
|
|
364
|
+
}
|
|
365
|
+
if (version !== undefined && version === this.ruleset?.version)
|
|
366
|
+
this.synced();
|
|
367
|
+
else {
|
|
368
|
+
if (version !== undefined && version > (this.announced ?? 0))
|
|
369
|
+
this.announced = version;
|
|
370
|
+
void this.sync();
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
// --- Answering flag checks: memory only, no I/O ------------------------------------------------
|
|
374
|
+
resolve(flagKey, defaultValue, context, kind) {
|
|
375
|
+
if (!this.ruleset) {
|
|
376
|
+
return { value: defaultValue, reason: 'ERROR', errorCode: ErrorCode.PROVIDER_NOT_READY, errorMessage: 'Flagdock has no rules yet' };
|
|
377
|
+
}
|
|
378
|
+
const r = evaluate(this.ruleset, flagKey, context, defaultValue, kind);
|
|
379
|
+
if (this.usageIntervalMs > 0) {
|
|
380
|
+
this.usage.record(flagKey, r.valueKey);
|
|
381
|
+
// Who got which value, so goals can be compared. Only for people the app identifies.
|
|
382
|
+
if (r.valueKey !== undefined && typeof context.targetingKey === 'string' && context.targetingKey !== '')
|
|
383
|
+
this.activity.expose(flagKey, r.valueKey, context.targetingKey);
|
|
384
|
+
}
|
|
385
|
+
if (r.reason === 'ERROR') {
|
|
386
|
+
return {
|
|
387
|
+
value: defaultValue,
|
|
388
|
+
reason: 'ERROR',
|
|
389
|
+
errorCode: ERROR_CODES[r.errorCode ?? 'GENERAL'] ?? ErrorCode.GENERAL,
|
|
390
|
+
...(r.errorMessage ? { errorMessage: r.errorMessage } : {}),
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
return {
|
|
394
|
+
value: r.value,
|
|
395
|
+
reason: this.stale ? 'STALE' : r.reason,
|
|
396
|
+
...(r.valueKey !== undefined ? { variant: r.valueKey } : {}),
|
|
397
|
+
flagMetadata: { rulesetVersion: this.ruleset.version, ...(r.ruleId ? { ruleId: r.ruleId } : {}) },
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
/**
|
|
401
|
+
* Explains what a flag returns for one context and why: the answer plus what each rule looked at.
|
|
402
|
+
* For debugging; it is not counted as usage. Returns null before the first rules arrive.
|
|
403
|
+
*/
|
|
404
|
+
explain(flagKey, context) {
|
|
405
|
+
if (!this.ruleset)
|
|
406
|
+
return null;
|
|
407
|
+
const trace = [];
|
|
408
|
+
const resolution = evaluate(this.ruleset, flagKey, context, null, undefined, trace);
|
|
409
|
+
return { resolution, trace, rulesetVersion: this.ruleset.version };
|
|
410
|
+
}
|
|
411
|
+
async resolveBooleanEvaluation(flagKey, defaultValue, context, _logger) {
|
|
412
|
+
return this.resolve(flagKey, defaultValue, context, 'boolean');
|
|
413
|
+
}
|
|
414
|
+
async resolveStringEvaluation(flagKey, defaultValue, context, _logger) {
|
|
415
|
+
return this.resolve(flagKey, defaultValue, context, 'string');
|
|
416
|
+
}
|
|
417
|
+
async resolveNumberEvaluation(flagKey, defaultValue, context, _logger) {
|
|
418
|
+
return this.resolve(flagKey, defaultValue, context, 'number');
|
|
419
|
+
}
|
|
420
|
+
async resolveObjectEvaluation(flagKey, defaultValue, context, _logger) {
|
|
421
|
+
return this.resolve(flagKey, defaultValue, context, 'json');
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,60 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@flagdock/node",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Flagdock feature flags for Node.js: an OpenFeature server provider that downloads the rules once and evaluates in memory",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"feature-flags",
|
|
7
|
+
"feature-toggles",
|
|
8
|
+
"openfeature",
|
|
9
|
+
"openfeature-provider",
|
|
10
|
+
"flagdock",
|
|
11
|
+
"node"
|
|
12
|
+
],
|
|
13
|
+
"license": "MIT",
|
|
14
|
+
"author": "Flagdock",
|
|
15
|
+
"homepage": "https://flagdock.com",
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "git+https://github.com/paleka/flagsystem.git",
|
|
19
|
+
"directory": "packages/node-sdk"
|
|
20
|
+
},
|
|
21
|
+
"bugs": {
|
|
22
|
+
"email": "info@flagdock.com"
|
|
23
|
+
},
|
|
24
|
+
"type": "module",
|
|
25
|
+
"main": "./dist/index.js",
|
|
26
|
+
"types": "./dist/index.d.ts",
|
|
27
|
+
"exports": {
|
|
28
|
+
".": {
|
|
29
|
+
"types": "./dist/index.d.ts",
|
|
30
|
+
"default": "./dist/index.js"
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"files": [
|
|
34
|
+
"dist",
|
|
35
|
+
"!dist/**/*.map",
|
|
36
|
+
"!dist/*.tsbuildinfo",
|
|
37
|
+
"README.md",
|
|
38
|
+
"LICENSE"
|
|
39
|
+
],
|
|
40
|
+
"scripts": {
|
|
41
|
+
"build": "tsc -b"
|
|
42
|
+
},
|
|
43
|
+
"dependencies": {
|
|
44
|
+
"@flagdock/core": "0.1.1"
|
|
45
|
+
},
|
|
46
|
+
"peerDependencies": {
|
|
47
|
+
"@openfeature/server-sdk": "^1.17.0"
|
|
48
|
+
},
|
|
49
|
+
"devDependencies": {
|
|
50
|
+
"@openfeature/server-sdk": "^1.17.0",
|
|
51
|
+
"@flagdock/server": "0.1.0"
|
|
52
|
+
},
|
|
53
|
+
"sideEffects": false,
|
|
54
|
+
"engines": {
|
|
55
|
+
"node": ">=18"
|
|
56
|
+
},
|
|
57
|
+
"publishConfig": {
|
|
58
|
+
"access": "public"
|
|
59
|
+
}
|
|
60
|
+
}
|