-
-
Notifications
You must be signed in to change notification settings - Fork 655
/
frontend-api-service.ts
306 lines (266 loc) · 9.47 KB
/
frontend-api-service.ts
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
import { IUnleashConfig, IUnleashServices, IUnleashStores } from '../../types';
import { Logger } from '../../logger';
import { ClientMetricsSchema, FrontendApiFeatureSchema } from '../../openapi';
import ApiUser, { IApiUser } from '../../types/api-user';
import {
Context,
InMemStorageProvider,
Unleash,
UnleashEvents,
} from 'unleash-client';
import { ApiTokenType } from '../../types/models/api-token';
import {
FrontendSettings,
frontendSettingsKey,
} from '../../types/settings/frontend-settings';
import { validateOrigins } from '../../util';
import { BadDataError, InvalidTokenError } from '../../error';
import {
FUNCTION_TIME,
FRONTEND_API_REPOSITORY_CREATED,
PROXY_REPOSITORY_CREATED,
} from '../../metric-events';
import { FrontendApiRepository } from './frontend-api-repository';
import { GlobalFrontendApiCache } from './global-frontend-api-cache';
import { ProxyRepository } from './proxy-repository';
import metricsHelper from '../../util/metrics-helper';
export type Config = Pick<
IUnleashConfig,
'getLogger' | 'frontendApi' | 'frontendApiOrigins' | 'eventBus'
>;
export type Stores = Pick<IUnleashStores, 'segmentReadModel'>;
export type Services = Pick<
IUnleashServices,
| 'featureToggleServiceV2'
| 'clientMetricsServiceV2'
| 'settingService'
| 'configurationRevisionService'
>;
export class FrontendApiService {
private readonly config: Config;
private readonly logger: Logger;
private readonly stores: Stores;
private readonly services: Services;
private readonly globalFrontendApiCache: GlobalFrontendApiCache;
/**
* This is intentionally a Promise because we want to be able to await
* until the client (which might be being created by a different request) is ready
* Check this test that fails if we don't use a Promise: frontend-api.concurrency.e2e.test.ts
*/
private readonly clients: Map<ApiUser['secret'], Promise<Unleash>> =
new Map();
private readonly newClients: Map<ApiUser['secret'], Promise<Unleash>> =
new Map();
private cachedFrontendSettings?: FrontendSettings;
private timer: Function;
constructor(
config: Config,
stores: Stores,
services: Services,
globalFrontendApiCache: GlobalFrontendApiCache,
) {
this.config = config;
this.logger = config.getLogger('services/frontend-api-service.ts');
this.stores = stores;
this.services = services;
this.globalFrontendApiCache = globalFrontendApiCache;
this.timer = (functionName) =>
metricsHelper.wrapTimer(config.eventBus, FUNCTION_TIME, {
className: 'FrontendApiService',
functionName,
});
}
async getFrontendApiFeatures(
token: IApiUser,
context: Context,
): Promise<FrontendApiFeatureSchema[]> {
const stopTimer = this.timer('getFrontendApiFeatures');
const client = await this.clientForFrontendApiToken(token);
const definitions = client.getFeatureToggleDefinitions() || [];
const sessionId = context.sessionId || String(Math.random());
const resultDefinitions = definitions
.filter((feature) =>
client.isEnabled(feature.name, {
...context,
sessionId,
}),
)
.map((feature) => ({
name: feature.name,
enabled: Boolean(feature.enabled),
variant: client.getVariant(feature.name, {
...context,
sessionId,
}),
impressionData: Boolean(feature.impressionData),
}));
stopTimer();
return resultDefinitions;
}
async getNewFrontendApiFeatures(
token: IApiUser,
context: Context,
): Promise<FrontendApiFeatureSchema[]> {
const stopTimer = this.timer('getNewFrontendApiFeatures');
const client = await this.newClientForFrontendApiToken(token);
const definitions = client.getFeatureToggleDefinitions() || [];
const sessionId = context.sessionId || String(Math.random());
const resultDefinitions = definitions
.filter((feature) => {
const enabled = client.isEnabled(feature.name, {
...context,
sessionId,
});
return enabled;
})
.map((feature) => ({
name: feature.name,
enabled: Boolean(feature.enabled),
variant: client.getVariant(feature.name, {
...context,
sessionId,
}),
impressionData: Boolean(feature.impressionData),
}));
stopTimer();
return resultDefinitions;
}
async registerFrontendApiMetrics(
token: IApiUser,
metrics: ClientMetricsSchema,
ip: string,
): Promise<void> {
FrontendApiService.assertExpectedTokenType(token);
const environment =
this.services.clientMetricsServiceV2.resolveMetricsEnvironment(
token as ApiUser,
metrics,
);
await this.services.clientMetricsServiceV2.registerClientMetrics(
{
...metrics,
environment,
},
ip,
);
}
private async clientForFrontendApiToken(token: IApiUser): Promise<Unleash> {
FrontendApiService.assertExpectedTokenType(token);
let client = this.clients.get(token.secret);
if (!client) {
client = this.createClientForFrontendApiToken(token);
this.clients.set(token.secret, client);
this.config.eventBus.emit(PROXY_REPOSITORY_CREATED);
}
return client;
}
private async newClientForFrontendApiToken(
token: IApiUser,
): Promise<Unleash> {
FrontendApiService.assertExpectedTokenType(token);
let newClient = this.newClients.get(token.secret);
if (!newClient) {
newClient = this.createNewClientForFrontendApiToken(token);
this.newClients.set(token.secret, newClient);
this.config.eventBus.emit(FRONTEND_API_REPOSITORY_CREATED);
}
return newClient;
}
private async createClientForFrontendApiToken(
token: IApiUser,
): Promise<Unleash> {
const repository = new ProxyRepository(
this.config,
this.stores,
this.services,
token,
);
const client = new Unleash({
appName: 'proxy',
url: 'unused',
storageProvider: new InMemStorageProvider(),
disableMetrics: true,
repository,
disableAutoStart: true,
skipInstanceCountWarning: true,
});
client.on(UnleashEvents.Error, (error) => {
this.logger.error('We found an event error', error);
});
await client.start();
return client;
}
private async createNewClientForFrontendApiToken(
token: IApiUser,
): Promise<Unleash> {
const repository = new FrontendApiRepository(
this.config,
this.globalFrontendApiCache,
token,
);
const client = new Unleash({
appName: 'frontend-api',
url: 'unused',
storageProvider: new InMemStorageProvider(),
disableMetrics: true,
repository,
disableAutoStart: true,
skipInstanceCountWarning: true,
});
client.on(UnleashEvents.Error, (error) => {
this.logger.error('We found an event error', error);
});
await client.start();
return client;
}
async deleteClientForFrontendApiToken(secret: string): Promise<void> {
const clientPromise = this.clients.get(secret);
if (clientPromise) {
const client = await clientPromise;
client.destroy();
this.clients.delete(secret);
}
}
stopAll(): void {
this.clients.forEach((promise) => promise.then((c) => c.destroy()));
}
private static assertExpectedTokenType({ type }: IApiUser) {
if (!(type === ApiTokenType.FRONTEND || type === ApiTokenType.ADMIN)) {
throw new InvalidTokenError();
}
}
async setFrontendSettings(
value: FrontendSettings,
createdBy: string,
createdByUserId: number,
): Promise<void> {
const error = validateOrigins(value.frontendApiOrigins);
if (error) {
throw new BadDataError(error);
}
await this.services.settingService.insert(
frontendSettingsKey,
value,
createdBy,
createdByUserId,
false,
);
}
async fetchFrontendSettings(): Promise<FrontendSettings> {
try {
this.cachedFrontendSettings =
await this.services.settingService.get(frontendSettingsKey, {
frontendApiOrigins: this.config.frontendApiOrigins,
});
} catch (error) {
this.logger.debug('Unable to fetch frontend settings', error);
}
return this.cachedFrontendSettings;
}
async getFrontendSettings(useCache = true): Promise<FrontendSettings> {
if (useCache && this.cachedFrontendSettings) {
return this.cachedFrontendSettings;
}
return this.fetchFrontendSettings();
}
}