-
-
Notifications
You must be signed in to change notification settings - Fork 656
/
frontend-api-controller.ts
271 lines (248 loc) · 9.73 KB
/
frontend-api-controller.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
import { Request, Response } from 'express';
import Controller from '../../routes/controller';
import { IUnleashConfig, IUnleashServices, NONE } from '../../types';
import { Logger } from '../../logger';
import { IApiUser } from '../../types/api-user';
import {
ClientMetricsSchema,
createRequestSchema,
createResponseSchema,
emptyResponse,
getStandardResponses,
FrontendApiClientSchema,
FrontendApiFeatureSchema,
frontendApiFeaturesSchema,
FrontendApiFeaturesSchema,
} from '../../openapi';
import { Context } from 'unleash-client';
import { enrichContextWithIp } from './index';
import { corsOriginMiddleware } from '../../middleware';
import NotImplementedError from '../../error/not-implemented-error';
import NotFoundError from '../../error/notfound-error';
import rateLimit from 'express-rate-limit';
import { minutesToMilliseconds } from 'date-fns';
import isEqual from 'lodash.isequal';
import { diff } from 'json-diff';
interface ApiUserRequest<
PARAM = any,
ResBody = any,
ReqBody = any,
ReqQuery = any,
> extends Request<PARAM, ResBody, ReqBody, ReqQuery> {
user: IApiUser;
}
type Services = Pick<
IUnleashServices,
'settingService' | 'frontendApiService' | 'openApiService'
>;
export default class FrontendAPIController extends Controller {
private readonly logger: Logger;
private services: Services;
constructor(config: IUnleashConfig, services: Services) {
super(config);
this.logger = config.getLogger('frontend-api-controller.ts');
this.services = services;
// Support CORS requests for the frontend endpoints.
// Preflight requests are handled in `app.ts`.
this.app.use(corsOriginMiddleware(services, config));
this.route({
method: 'get',
path: '',
handler: this.getFrontendApiFeatures,
permission: NONE,
middleware: [
this.services.openApiService.validPath({
tags: ['Frontend API'],
operationId: 'getFrontendFeatures',
responses: {
200: createResponseSchema('frontendApiFeaturesSchema'),
...getStandardResponses(401, 404),
},
summary:
'Retrieve enabled feature toggles for the provided context.',
description:
'This endpoint returns the list of feature toggles that the frontend API evaluates to enabled for the given context. Context values are provided as query parameters. If the Frontend API is disabled 404 is returned.',
}),
],
});
this.route({
method: 'post',
path: '',
handler: FrontendAPIController.endpointNotImplemented,
permission: NONE,
});
this.route({
method: 'get',
path: '/client/features',
handler: FrontendAPIController.endpointNotImplemented,
permission: NONE,
});
this.route({
method: 'post',
path: '/client/metrics',
handler: this.registerFrontendApiMetrics,
permission: NONE,
middleware: [
this.services.openApiService.validPath({
tags: ['Frontend API'],
summary: 'Register client usage metrics',
description: `Registers usage metrics. Stores information about how many times each toggle was evaluated to enabled and disabled within a time frame. If provided, this operation will also store data on how many times each feature toggle's variants were displayed to the end user. If the Frontend API is disabled 404 is returned.`,
operationId: 'registerFrontendMetrics',
requestBody: createRequestSchema('clientMetricsSchema'),
responses: {
200: emptyResponse,
204: emptyResponse,
...getStandardResponses(400, 401, 404),
},
}),
rateLimit({
windowMs: minutesToMilliseconds(1),
max: config.metricsRateLimiting.frontendMetricsMaxPerMinute,
validate: false,
standardHeaders: true,
legacyHeaders: false,
}),
],
});
this.route({
method: 'post',
path: '/client/register',
handler: this.registerFrontendApiClient,
permission: NONE,
middleware: [
this.services.openApiService.validPath({
tags: ['Frontend API'],
summary: 'Register a client SDK',
description:
'This is for future use. Currently Frontend client registration is not supported. Returning 200 for clients that expect this status code. If the Frontend API is disabled 404 is returned.',
operationId: 'registerFrontendClient',
requestBody: createRequestSchema('frontendApiClientSchema'),
responses: {
200: emptyResponse,
...getStandardResponses(400, 401, 404),
},
}),
rateLimit({
windowMs: minutesToMilliseconds(1),
max: config.metricsRateLimiting
.frontendRegisterMaxPerMinute,
validate: false,
standardHeaders: true,
legacyHeaders: false,
}),
],
});
this.route({
method: 'get',
path: '/health',
handler: FrontendAPIController.endpointNotImplemented,
permission: NONE,
});
this.route({
method: 'get',
path: '/internal-backstage/prometheus',
handler: FrontendAPIController.endpointNotImplemented,
permission: NONE,
});
}
private static async endpointNotImplemented(
req: ApiUserRequest,
res: Response,
) {
const error = new NotImplementedError(
'The frontend API does not support this endpoint.',
);
res.status(error.statusCode).json(error);
}
private async getFrontendApiFeatures(
req: ApiUserRequest,
res: Response<FrontendApiFeaturesSchema>,
) {
if (!this.config.flagResolver.isEnabled('embedProxy')) {
throw new NotFoundError();
}
let toggles: FrontendApiFeatureSchema[];
let newToggles: FrontendApiFeatureSchema[] = [];
if (this.config.flagResolver.isEnabled('globalFrontendApiCache')) {
[toggles, newToggles] = await Promise.all([
this.services.frontendApiService.getFrontendApiFeatures(
req.user,
FrontendAPIController.createContext(req),
),
this.services.frontendApiService.getNewFrontendApiFeatures(
req.user,
FrontendAPIController.createContext(req),
),
]);
const sortedToggles = toggles.sort((a, b) =>
a.name.localeCompare(b.name),
);
const sortedNewToggles = newToggles.sort((a, b) =>
a.name.localeCompare(b.name),
);
if (!isEqual(sortedToggles, sortedNewToggles)) {
this.logger.warn(
`old features and new features are different. Old count ${
toggles.length
}, new count ${newToggles.length}, projects ${
req.user.projects
}, environment ${req.user.environment}, diff ${diff(
sortedToggles,
sortedNewToggles,
)}`,
);
}
} else {
toggles =
await this.services.frontendApiService.getFrontendApiFeatures(
req.user,
FrontendAPIController.createContext(req),
);
}
const returnedToggles = this.config.flagResolver.isEnabled(
'returnGlobalFrontendApiCache',
)
? newToggles
: toggles;
res.set('Cache-control', 'no-cache');
this.services.openApiService.respondWithValidation(
200,
res,
frontendApiFeaturesSchema.$id,
{ toggles: returnedToggles },
);
}
private async registerFrontendApiMetrics(
req: ApiUserRequest<unknown, unknown, ClientMetricsSchema>,
res: Response,
) {
if (!this.config.flagResolver.isEnabled('embedProxy')) {
throw new NotFoundError();
}
if (this.config.flagResolver.isEnabled('disableMetrics')) {
res.sendStatus(204);
return;
}
await this.services.frontendApiService.registerFrontendApiMetrics(
req.user,
req.body,
req.ip,
);
res.sendStatus(200);
}
private async registerFrontendApiClient(
req: ApiUserRequest<unknown, unknown, FrontendApiClientSchema>,
res: Response<string>,
) {
if (!this.config.flagResolver.isEnabled('embedProxy')) {
throw new NotFoundError();
}
// Client registration is not yet supported by @unleash/proxy,
// but proxy clients may still expect a 200 from this endpoint.
res.sendStatus(200);
}
private static createContext(req: ApiUserRequest): Context {
const { query } = req;
return enrichContextWithIp(query, req.ip);
}
}