-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathFeatureProbe.ts
More file actions
348 lines (310 loc) · 11.2 KB
/
Copy pathFeatureProbe.ts
File metadata and controls
348 lines (310 loc) · 11.2 KB
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
/*
* Copyright 2022 FeatureProbe
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
import { FPToggleDetail, FPConfig } from './type';
import { FPUser } from './FPUser';
import { Repository } from './Evaluate';
import { EventRecorder } from './Event';
import { Synchronizer } from './Sync';
import pino from 'pino';
import { io } from 'socket.io-client';
// import { DefaultEventsMap } from "@socket.io/component-emitter";
/**
* A client for the FeatureProbe API.
* Applications should instantiate a single {@link FeatureProbe} for the lifetime of their application.
*/
export class FeatureProbe {
private readonly _remoteUrl: string;
private readonly _togglesUrl: string;
private readonly _eventsUrl: string;
private readonly _realtimeUrl: string;
private readonly _serverSdkKey: string;
private readonly _refreshInterval: number;
private readonly _eventRecorder: EventRecorder;
private readonly _toggleSyncer: Synchronizer;
private readonly _repository: Repository;
private readonly _prerequisiteMaxDeep: number;
private readonly _logger: pino.Logger;
// private _socket?: Socket<DefaultEventsMap, DefaultEventsMap>;
get initialized(): boolean {
return this._repository.initialized;
}
/**
* Creates a new client instance that connects to FeatureProbe.
* Undefined optional parameters will be set as the default configurations.
*
* @param remoteUrl url for FeatureProbe api server
* @param togglesUrl url of FeatureProbe api server's toggle controller, leave it as blank to use the same api server as {@link remoteUrl}
* @param eventsUrl url of FeatureProbe api server's event report controller, leave it as blank to use the same api server as {@link remoteUrl}
* @param serverSdkKey key for your FeatureProbe environment
* @param refreshInterval interval between polls to refresh local toggles
* @param logger pino logger, if you want to use transport or advanced settings, please define one instance and pass to this param
*/
constructor(
{
serverSdkKey,
remoteUrl,
togglesUrl,
eventsUrl,
realtimeUrl,
refreshInterval = 1000,
prerequisiteMaxDeep = 20,
logger
}: FPConfig) {
if (!serverSdkKey) {
throw new Error('non empty serverSdkKey is required');
}
if (refreshInterval <= 0) {
throw new Error('refreshInterval is invalid');
}
if (!remoteUrl && !togglesUrl) {
throw new Error('remoteUrl or togglesUrl is required');
}
if (!remoteUrl && !eventsUrl) {
throw new Error('remoteUrl or eventsUrl is required');
}
if (!remoteUrl && !realtimeUrl) {
throw new Error('remoteUrl or realtimeUrl is required');
}
if (!remoteUrl && !togglesUrl && !eventsUrl) {
throw new Error('remoteUrl is required');
}
this._serverSdkKey = serverSdkKey;
this._refreshInterval = refreshInterval;
this._remoteUrl = new URL(remoteUrl ?? '').toString();
this._togglesUrl = new URL(togglesUrl ?? remoteUrl + '/api/server-sdk/toggles').toString();
this._eventsUrl = new URL(eventsUrl ?? remoteUrl + '/api/events').toString();
this._realtimeUrl = new URL(realtimeUrl ?? remoteUrl + '/realtime').toString();
this._logger = logger ?? pino({ name: 'FeatureProbe' });
this._repository = new Repository({});
this._eventRecorder = new EventRecorder(this._serverSdkKey, this._eventsUrl, this._refreshInterval, this._logger);
this._toggleSyncer = new Synchronizer(this._serverSdkKey, this._togglesUrl, this._refreshInterval, this._repository, this._logger);
this._prerequisiteMaxDeep = prerequisiteMaxDeep;
}
/**
* Initializes the toggle repository.
*
* @param startWait set time limit for initialization, if not set, this function won't be timeout
*/
public async start(startWait?: number) {
this.connectSocket();
const promises: [Promise<void>] = [this._toggleSyncer.start()];
let timeoutHandle: NodeJS.Timeout | undefined;
if (startWait != null) {
promises.push(new Promise((resolve, reject) => {
timeoutHandle = setTimeout(
() => reject(new Error(`Failed to initialize repository in ${startWait} ms`)),
startWait
);
}));
}
const start = new Date().valueOf();
await Promise.race(promises)
.then(() => {
clearTimeout(timeoutHandle);
this._logger.info(`FeatureProbe client started, initialization cost ${new Date().valueOf() - start} ms`);
})
.catch(e => this._logger.error('FeatureProbe client failed to initialize', e));
}
/**
* Closes the FeatureProbe client, this would properly clean the memory and report all events.
*/
public async close() {
await this._eventRecorder.stop();
this._toggleSyncer.stop();
this._repository.clear();
this._logger.flush();
}
/**
* Manually events push.
*/
public flush() {
this._eventRecorder.flush();
}
/**
* Gets the evaluated value of a boolean toggle.
* @param key toggle key
* @param user user to be evaluated
* @param defaultValue default return value
*/
public booleanValue(key: string, user: FPUser, defaultValue: boolean): boolean {
return this.toggleDetail(key, user, defaultValue, 'boolean').value as boolean;
}
/**
* Gets the evaluated value of a number toggle.
* @param key toggle key
* @param user user to be evaluated
* @param defaultValue default return value
*/
public numberValue(key: string, user: FPUser, defaultValue: number): number {
return this.toggleDetail(key, user, defaultValue, 'number').value as number;
}
/**
* Gets the evaluated value of a string toggle.
* @param key toggle key
* @param user user to be evaluated
* @param defaultValue default return value
*/
public stringValue(key: string, user: FPUser, defaultValue: string): string {
return this.toggleDetail(key, user, defaultValue, 'string').value as string;
}
/**
* Gets the evaluated value of a json toggle.
* @param key toggle key
* @param user user to be evaluated
* @param defaultValue default return value
*/
public jsonValue(key: string, user: FPUser, defaultValue: any): any {
return this.toggleDetail(key, user, defaultValue, 'object').value;
}
/**
* Gets the detailed evaluation results of a boolean toggle.
* @param key toggle key
* @param user user to be evaluated
* @param defaultValue default return value
*/
public booleanDetail(key: string, user: FPUser, defaultValue: boolean): FPToggleDetail {
return this.toggleDetail(key, user, defaultValue, 'boolean');
}
/**
* Gets the detailed evaluation results of a number toggle.
* @param key toggle key
* @param user user to be evaluated
* @param defaultValue default return value
*/
public numberDetail(key: string, user: FPUser, defaultValue: number): FPToggleDetail {
return this.toggleDetail(key, user, defaultValue, 'number');
}
/**
* Gets the detailed evaluation results of a string toggle.
* @param key toggle key
* @param user user to be evaluated
* @param defaultValue default return value
*/
public stringDetail(key: string, user: FPUser, defaultValue: string): FPToggleDetail {
return this.toggleDetail(key, user, defaultValue, 'string');
}
/**
* Gets the detailed evaluation results of a json toggle.
* @param key toggle key
* @param user user to be evaluated
* @param defaultValue default return value
*/
public jsonDetail(key: string, user: FPUser, defaultValue: object): FPToggleDetail {
return this.toggleDetail(key, user, defaultValue, 'object');
}
/**
* Record custom events, value is optional.
*/
public track(name: string, user: FPUser, value?: unknown): void {
this._eventRecorder.recordTrackEvent({
kind: 'custom',
name,
time: Date.now(),
value,
user: user.key,
});
}
private toggleDetail(key: string, user: FPUser, defaultValue: any, valueType: ToggleValueType): FPToggleDetail {
if (!this._repository.initialized) {
return {
value: defaultValue,
ruleIndex: null,
variationIndex: null,
version: null,
reason: 'not initialized'
} as FPToggleDetail;
}
const toggle = this._repository.getToggle(key);
if (toggle === undefined) {
return {
value: defaultValue,
ruleIndex: null,
variationIndex: null,
version: null,
reason: `toggle '${key}' not exist.`
} as FPToggleDetail;
}
const segments = this._repository.segments;
const toggles = this._repository.toggles;
const result = toggle.eval(user, toggles, segments, defaultValue, this._prerequisiteMaxDeep);
if (typeof result.value === valueType) {
const timestamp = Date.now();
this._eventRecorder.recordAccessEvent({
time: timestamp,
key: key,
value: result.value,
index: result.variationIndex ?? -1,
version: result.version ?? 0,
reason: result.reason
});
if (toggle.trackAccessEvents) {
this._eventRecorder.recordTrackEvent({
kind: 'access',
key: key,
user: user.key,
value: result.value,
variationIndex: result.variationIndex ?? -1,
version: result.version ?? 0,
time: timestamp,
ruleIndex: result.ruleIndex ?? null,
});
}
if (timestamp <= this._repository.debugUntilTime) {
this._eventRecorder.recordTrackEvent({
kind: 'debug',
key: key,
user: user.key,
userDetail: user,
value: result.value,
variationIndex: result.variationIndex ?? -1,
version: result.version ?? 0,
time: timestamp,
ruleIndex: result.ruleIndex ?? null,
});
}
return result;
} else {
return {
value: defaultValue,
ruleIndex: null,
variationIndex: null,
version: null,
reason: 'value type mismatch.'
} as FPToggleDetail;
}
}
private async connectSocket() {
const url = new URL(this._realtimeUrl);
this._logger?.info('connect socket to ' + this._realtimeUrl + ' ' + url.pathname);
const socket = io(this._realtimeUrl, { transports: ['websocket'], path: url.pathname });
socket.on('connect', () => {
this._logger?.info('connect socketio success');
socket.emit('register', { key: this._serverSdkKey });
});
socket.on('update', () => {
this._logger?.info('socketio recv update event');
(async () => {
await this._toggleSyncer.syncNow()
})()
});
socket.on('connect_error', (error: Error) => {
this._logger?.info(`socketio error ${error.message}`);
})
// this._socket = socket;
}
}
type ToggleValueType = 'boolean' | 'number' | 'string' | 'object';