-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexample.js
288 lines (261 loc) · 7.62 KB
/
example.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
const LaunchDarkly = require("@launchdarkly/node-server-sdk");
const {
logger,
setLoggerLDClient,
getDefaultLogLevel,
setDefaultLogLevel,
} = require("./logger");
const { withLDContext, LD_CONTEXT } = require("./logger-transport");
const { withService, mergeLDContext } = require("./ld-context");
const { faker } = require("@faker-js/faker");
let ldClient = null;
const EAP_PREFIX = "allow-eap-";
const CONFIGURE_PREFIX = "config-";
const GLOBAL_PREFIX = "global-";
const TRACK_PREFIX = "track-";
/**
* Returns an initalized LaunchDarkly Client
* @returns {LaunchDarkly.LDClient}
*/
function initializeLaunchDarklyClient() {
return LaunchDarkly.init(process.env.LD_SDK_KEY, {
capacity: 10000,
flushInterval: 1,
logger: serviceLogger("launchdarkly-sdk"),
contextKeysCapacity: 10000,
contextKeysFlushInterval: 10,
application: {
id: "example-app",
name: "ExampleApp",
key: "example-app",
version: "0.7.0",
},
});
}
/**
* Returns an initialized LaunchDarkly Client as a singleton.
* Sets up event listeners and performs some wrapper specific setup
* @returns {LaunchDarkly.LDClient}
*/
function getLDClient() {
if (ldClient === null) {
ldClient = initializeLaunchDarklyClient();
setupEventListeners(ldClient);
setLoggerLDClient(ldClient);
}
return ldClient;
}
/**
* Wrapper around variation calls
* @param {LaunchDarkly.LDContext} context
* @param {string} flag
* @returns {[string, any][]}
*/
async function variation(
flag,
context = { kind: "user", anonymous: true, key: "example" },
fallback,
) {
const ld = getLDClient();
// this is where you can add logic such as loading overrides from a file
return ld.variation(flag, /* withService('app', context)*/ context, fallback);
}
/**
* Wrapper around variationDetail calls
* @param {LaunchDarkly.LDContext} context
* @param {string} flag
* @returns {[string, any][]}
*/
async function variationDetail(
flag,
context = { kind: "user", anonymous: true, key: "example" },
fallback,
) {
const ld = getLDClient();
return ld.variationDetail(flag, context, fallback);
}
/**
* Returns a map of multiple flags to their values
* @param {LaunchDarkly.LDUser} user
* @param {[string, any][]|Object} } flagsAndFallbacks
* @returns {any}
*/
async function variationMap(user, flagsAndFallbacks) {
const ld = getLDClient();
const entries = Array.isArray(flagsAndFallbacks)
? flagsAndFallbacks
: Object.entries(flagsAndFallbacks);
return Object.fromEntries(
await Promise.all(
entries.map(async ([flag, fallback]) => {
return [flag, await variation(flag, user, fallback)];
}),
),
);
}
/**
* Create a service logger
* @param {string} component
* @param {LaunchDarkly.LDContext...} contexts additional contexts to add to the logger
*/
function serviceLogger(component, ...contexts) {
return logger.child(withLDContext({}, withService(component, ...contexts)));
}
// listen of all EAPs discovered via flag naming convention
const earlyAccessPrograms = new Set();
// metric emulation
const trackedMetrics = new Set();
/**
* Get all early access program keys
* @returns {Set<String>}
*/
function getAllEarlyAccessPrograms() {
return earlyAccessPrograms;
}
/**
* Gets a list of early access programs a user is allowed to opt-in to
* @param {*} user
* @returns
*/
async function getAvailableEarlyAccessPrograms(user) {
const eaps = getAllEarlyAccessPrograms();
return Promise.all(
Array.from(eaps).map(async (v) => [
await variation(`${EAP_PREFIX}${v}`, user, false),
v,
]),
).then((results) => results.filter(([allow]) => allow).map(([_, v]) => v));
}
/**
* Get all tracked metrics
* @returns {Set<String>}
*/
function getTrackedMetrics() {
return trackedMetrics;
}
/*
* Emulate metrics based on tracked flags
* @param {LaunchDarkly.LDContext} ldContext
*/
async function emulateMetrics(ldContext, flagContext) {
const ldClient = getLDClient();
const mergedContext = mergeLDContext(ldContext, flagContext);
const metrics = await Promise.all(
Array.from(trackedMetrics.values()).map(async (key) => {
const value = await variation(key, mergedContext, {});
return [key, value];
}),
);
let didIt = false;
//logger.debug("emulating metrics", {metrics, mergedContext});
metrics
.filter(([_, config]) => !!config.key)
.forEach(([trackKey, config]) => {
let value = config.value;
//logger.debug("emulating metric", {key: config.key, config, value});
if (config.faker) {
const module = config.faker.module;
const options = config.faker.options;
const kind = config.faker.kind;
value = faker[module][kind](options);
}
ldClient.track(config.key, ldContext /*,config.data, config.value*/);
didIt = true;
logger.debug(`emulated metric: ${config.key}`, {
metricKey: config.key,
[LD_CONTEXT]: ldContext,
context: ldContext,
data: config.data,
flagKey: trackKey,
value,
});
});
if (didIt) {
// await ldClient.flush();
}
}
function setupEventListeners(client) {
client.once("ready", () => {
client.allFlagsState({ anonymous: true, key: "demo" }).then((state) => {
const flags = state.toJSON();
Object.keys(flags).forEach((key) => handleFlagUpdate({ key }));
});
});
client.on("update", handleFlagUpdate);
}
function handleFlagUpdate({ key }) {
if (key.startsWith(EAP_PREFIX)) {
handleEAP(key);
} else if (key.startsWith(TRACK_PREFIX)) {
handleMetric(key);
} else if (key.startsWith(CONFIGURE_PREFIX)) {
handleConfiguration(key);
}
}
// application configuration
const appConfig = new Map();
async function handleConfiguration(flag) {
const ld = getLDClient();
const key = stripPrefix(CONFIGURE_PREFIX, flag);
const user = {
kind: "service",
key: "app-config",
anonymous: true,
};
const logger = serviceLogger("config");
switch (key) {
// special handling: configure winston
case "log-verbosity":
/*const level = await variation(flag, user, getDefaultLogLevel() || "debug");
if (level !== undefined) {
setDefaultLogLevel(level);
logger.debug("set logging level to %s", level);
} else {
logger.error("invalid configuration value: %s %s", flag, level);
}*/
break;
default:
// set application configuration in a shared map
// this has a few downsides:
// - always calls variation, so flag status metrics are inaccurate
// - cant be targeted by user
// only makes sense for global/service/app level configurations
// we use a prefix to denote this
if (key.startsWith(GLOBAL_PREFIX)) {
const configKey = stripPrefix(GLOBAL_PREFIX, key);
const value = await variation(flag, user, appConfig.get(configKey));
appConfig.set(configKey, value);
logger.debug("set global config %s = %j", configKey, value);
}
break;
}
}
function handleEAP(flag) {
const eapKey = stripPrefix(EAP_PREFIX, flag);
const logger = serviceLogger("eap");
logger.debug("discovered early access program: %s", eapKey);
earlyAccessPrograms.add(eapKey);
}
function handleMetric(flag) {
const logger = serviceLogger("metric");
logger.debug("discovered metric emulation flag: %s", flag);
trackedMetrics.add(flag);
}
function stripPrefix(prefix, key) {
return key.substring(prefix.length);
}
function getConfig() {
return appConfig;
}
module.exports = {
getConfig,
initializeLaunchDarklyClient,
getLDClient,
variation,
variationMap,
variationDetail,
getAllEarlyAccessPrograms,
getAvailableEarlyAccessPrograms,
serviceLogger,
emulateMetrics,
};