-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.mjs
211 lines (191 loc) · 8.17 KB
/
app.mjs
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
'use strict';
import { performance, PerformanceObserver } from 'node:perf_hooks'
import dotenv from 'dotenv';
import * as ld from '@launchdarkly/node-server-sdk';
import readline from 'readline';
import fetch from 'node-fetch';
import { program } from 'commander';
import { ansi256 } from 'ansis';
import ora from 'ora';
(async () => {
dotenv.config();
const about = 'This app measures the time to receive notification in client after a flag toggle.\n' +
'Use --help to see available parameters. If no args are provided, the app will attempt to use values in .env file.\n' +
'When ready, press "t" to run the test.\n'
program
.description(about)
.option('--sdkKey <sdkKey>', 'SDK key for the target LaunchDarkly Environment', null)
.option('--apiToken <apiToken>', 'The LaunchDarkly API token', null)
.option('--logLevel <logLevel>', 'The LaunchDarkly SDK logging level (debug, error, info, warn, none)', 'info')
.option('--projectKey <projectKey>', 'The LaunchDarkly Project key', null)
.option('--environmentKey <environmentKey>', 'The LaunchDarkly Environment key', null)
.option('--flagKey <flagKey>', 'The LaunchDarkly flag key to be toggled', null)
.option('--context <context>', 'The LaunchDarkly context used in SDK initialization', null)
.parse(process.argv);
const options = program.opts();
const sdkKey = options.sdkKey || process.env.LD_SDK_KEY;
const apiToken = options.apiToken || process.env.LD_API_TOKEN;
const projectKey = options.projectKey || process.env.LD_PROJECT;
const environmentKey = options.environmentKey || process.env.LD_ENVIRONMENT;
const flagKey = options.flagKey || process.env.LD_FLAG_KEY;
const context = options.context ? JSON.parse(options.context) : JSON.parse(process.env.LD_CONTEXT);
const og = console.log;
const ldOptions = {
logger: ld.basicLogger({
level: options.logLevel,
destination: logInfo
})
};
new PerformanceObserver((list, observer) => {
list.getEntries().forEach((entry) => {
logInfo(`${entry.name} took ${entry.duration} ms`);
});
performance.clearMarks();
performance.clearMeasures();
}).observe({ entryTypes: ["measure"], buffer: true })
const info = ansi256(50).bold;
const error = ansi256(198).bold;
const spinner = ora();
spinner.color = 'green';
let client;
let flagValue;
let flagLastModifiedInLD;
let testCount = 0;
let testIsRunning = false;
let runningAverage = 0;
readline.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);
process.stdin.on('keypress', keyPressed);
async function init() {
try {
// measure time to initialize the SDK
console.time('LaunchDarkly SDK Initialization');
client = ld.init(sdkKey, ldOptions);
await client.waitForInitialization({ timeout: 10 });
console.timeEnd('LaunchDarkly SDK Initialization');
// measure time to retrieve a flag after initialization
console.time('Initial flag retrieval after SDK initialization');
flagValue = await client.boolVariation(flagKey, context, false);
console.timeEnd('Initial flag retrieval after SDK initialization');
// ready to run test
showReadyMessage();
} catch (e) {
logError(`Error initializing app: ${e}`);
logInfo('Exiting app...');
process.exit();
}
}
async function keyPressed(str, key) {
if (key.ctrl && key.name == 'c') { // kill the app
spinner.stop();
logInfo('Exiting app...');
process.exit();
} else if (key.name == 't') {
if (!testIsRunning) {
spinner.stop();
await runFlagChangeDeliveryTest();
}
}
}
async function runFlagChangeDeliveryTest() {
try {
testIsRunning = true;
if (testCount == 0) {
client.on(`update:${flagKey}`, async () => {
const toggleReceivedDateTime = new Date(new Date().toUTCString());
const waitTime = 3000;
logInfo(`Flag update received by client at ${toggleReceivedDateTime.toISOString()}`);
setTimeout(() => {
const flagLastModifiedInLDDateTime = new Date(flagLastModifiedInLD);
logInfo(`Flag last updated in LD at ${flagLastModifiedInLDDateTime.toISOString()}`);
const diff = Math.abs(toggleReceivedDateTime.getTime() - flagLastModifiedInLDDateTime.getTime());
logInfo(`Time to deliver flag change to client: ${diff} ms`);
runningAverage += diff;
logInfo(`Average flag delivery time during tests: ${runningAverage / testCount} ms`);
testIsRunning = false;
showReadyMessage();
}, waitTime);
});
client.on('error', (err) => {
logError(`LDClient error: ${err}`);
testIsRunning = false;
throw err;
});
}
++testCount
logInfo(`Executing test run #${testCount}`);
// toggle the flag in LD
await toggleFlag(flagValue);
} catch (e) {
logError(`Error running test: ${e}`);
testIsRunning = false;
}
}
async function toggleFlag(currentFlagValue) {
logInfo('Toggling flag in LD...');
try {
const kind = currentFlagValue ? 'turnFlagOff' : 'turnFlagOn';
const ignoreConflicts = true; // force it
performance.mark('toggleFlag-start');
const response = await fetch(`https://app.launchdarkly.com/api/v2/flags/${projectKey}/${flagKey}?ignoreConflicts=${ignoreConflicts}&filterEnv=${environmentKey}`,
{
method: 'PATCH',
headers: {
'Content-Type': 'application/json; domain-model=launchdarkly.semanticpatch',
Authorization: `${apiToken}`
},
body: JSON.stringify({
'environmentKey': `${environmentKey}`,
'instructions': [{ 'kind': kind }]
})
});
if (!response.ok) {
const msg = `${response.status} ${response.statusText}`;
throw new Error(msg);
}
const json = await response.json();
const state = json.environments[`${environmentKey}`];
flagValue = state.on;
flagLastModifiedInLD = state.lastModified;
} catch (e) {
logError(`Error toggling flag: ${e}`);
throw e;
} finally {
performance.mark('toggleFlag-end');
performance.measure('Toggling flag in LD', 'toggleFlag-start', 'toggleFlag-end');
}
}
function showReadyMessage() {
spinner.text = "Ready to run test. Press 't' to start.";
spinner.start();
}
function logInfo(message, ...args) {
const options = {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
fractionalSecondDigits: 3
};
const stamp = new Date().toLocaleTimeString('en-US', options).replace(" ", "").replace(",", " ");
og(`${stamp} ${info("INFO")} ${message}`, ...args);
}
function logError(message, ...args) {
const options = {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
fractionalSecondDigits: 3
};
const stamp = new Date().toLocaleTimeString('en-US', options).replace(" ", "").replace(",", " ");
og(`${stamp} ${error("ERRO")} ${message}`, ...args);
}
console.log = logInfo;
console.error = logError;
await init();
})();