-
-
Notifications
You must be signed in to change notification settings - Fork 768
/
Copy pathclient-applications-store.ts
464 lines (414 loc) · 14.3 KB
/
client-applications-store.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
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
import type EventEmitter from 'events';
import NotFoundError from '../error/notfound-error';
import type {
IClientApplication,
IClientApplications,
IClientApplicationsSearchParams,
IClientApplicationsStore,
} from '../types/stores/client-applications-store';
import type { Logger, LogProvider } from '../logger';
import type { Db } from './db';
import type { IApplicationOverview } from '../features/metrics/instance/models';
import { applySearchFilters } from '../features/feature-search/search-utils';
import type { IFlagResolver } from '../types';
import metricsHelper from '../util/metrics-helper';
import { DB_TIME } from '../metric-events';
const COLUMNS = [
'app_name',
'created_at',
'created_by',
'updated_at',
'description',
'strategies',
'url',
'color',
'icon',
];
const TABLE = 'client_applications';
const TABLE_USAGE = 'client_applications_usage';
const DEPRECATED_STRATEGIES = [
'gradualRolloutRandom',
'gradualRolloutSessionId',
'gradualRolloutUserId',
];
const mapRow: (any) => IClientApplication = (row) => ({
appName: row.app_name,
createdAt: row.created_at,
updatedAt: row.updated_at,
description: row.description,
strategies: row.strategies || [],
createdBy: row.created_by,
url: row.url,
color: row.color,
icon: row.icon,
lastSeen: row.last_seen,
announced: row.announced,
project: row.project,
environment: row.environment,
});
const reduceRows = (rows: any[]): IClientApplication[] => {
const appsObj = rows.reduce((acc, row) => {
// extracting project and environment from usage table
const { project, environment } = row;
const existingApp = acc[row.app_name];
if (existingApp) {
const existingProject = existingApp.usage.find(
(usage) => usage.project === project,
);
if (existingProject) {
existingProject.environments.push(environment);
} else {
existingApp.usage.push({
project: project,
environments: [environment],
});
}
} else {
acc[row.app_name] = {
...mapRow(row),
usage:
project && environment
? [
{
project,
environments: [environment],
},
]
: [],
};
}
return acc;
}, {});
return Object.values(appsObj);
};
const remapRow = (input) => {
const temp = {
app_name: input.appName,
updated_at: input.updatedAt || new Date(),
seen_at: input.lastSeen || new Date(),
description: input.description,
created_by: input.createdBy,
announced: input.announced,
url: input.url,
color: input.color,
icon: input.icon,
strategies: JSON.stringify(input.strategies),
};
Object.keys(temp).forEach((k) => {
if (temp[k] === undefined) {
// not using !temp[k] to allow false and null values to get through
delete temp[k];
}
});
return temp;
};
export default class ClientApplicationsStore
implements IClientApplicationsStore
{
private db: Db;
private logger: Logger;
private timer: Function;
private flagResolver: IFlagResolver;
constructor(
db: Db,
eventBus: EventEmitter,
getLogger: LogProvider,
flagResolver: IFlagResolver,
) {
this.db = db;
this.flagResolver = flagResolver;
this.logger = getLogger('client-applications-store.ts');
this.timer = (action: string) =>
metricsHelper.wrapTimer(eventBus, DB_TIME, {
store: 'client-applications',
action,
});
}
async upsert(details: Partial<IClientApplication>): Promise<void> {
const row = remapRow(details);
await this.db(TABLE).insert(row).onConflict('app_name').merge();
const usageRows = this.remapUsageRow(details);
await this.db(TABLE_USAGE)
.insert(usageRows)
.onConflict(['app_name', 'project', 'environment'])
.merge();
}
async bulkUpsert(apps: Partial<IClientApplication>[]): Promise<void> {
const rows = apps.map(remapRow);
const usageRows = apps.flatMap(this.remapUsageRow);
await this.db(TABLE).insert(rows).onConflict('app_name').merge();
await this.db(TABLE_USAGE)
.insert(usageRows)
.onConflict(['app_name', 'project', 'environment'])
.merge();
}
async exists(appName: string): Promise<boolean> {
const result = await this.db.raw(
`SELECT EXISTS(SELECT 1 FROM ${TABLE} WHERE app_name = ?) AS present`,
[appName],
);
const { present } = result.rows[0];
return present;
}
async getAll(): Promise<IClientApplication[]> {
const rows = await this.db
.select(COLUMNS)
.from(TABLE)
.orderBy('app_name', 'asc');
return rows.map(mapRow);
}
async getApplication(appName: string): Promise<IClientApplication> {
const row = await this.db
.select(COLUMNS)
.where('app_name', appName)
.from(TABLE)
.first();
if (!row) {
throw new NotFoundError(`Could not find appName=${appName}`);
}
return mapRow(row);
}
async deleteApplication(appName: string): Promise<void> {
return this.db(TABLE).where('app_name', appName).del();
}
async getApplications(
params: IClientApplicationsSearchParams,
): Promise<IClientApplications> {
const { limit, offset, sortOrder = 'asc', searchParams } = params;
const validatedSortOrder =
sortOrder === 'asc' || sortOrder === 'desc' ? sortOrder : 'asc';
const query = this.db
.with('applications', (qb) => {
applySearchFilters(qb, searchParams, [
'client_applications.app_name',
]);
qb.select([
...COLUMNS.map((column) => `${TABLE}.${column}`),
'project',
'environment',
this.db.raw(
`DENSE_RANK() OVER (ORDER BY client_applications.app_name ${validatedSortOrder}) AS rank`,
),
])
.from(TABLE)
.leftJoin(
TABLE_USAGE,
`${TABLE_USAGE}.app_name`,
`${TABLE}.app_name`,
);
})
.with(
'final_ranks',
this.db.raw(
'select row_number() over (order by min(rank)) as final_rank from applications group by app_name',
),
)
.with(
'total',
this.db.raw('select count(*) as total from final_ranks'),
)
.select('*')
.from('applications')
.joinRaw('CROSS JOIN total')
.whereBetween('rank', [offset + 1, offset + limit]);
const rows = await query;
if (rows.length !== 0) {
const applications = reduceRows(rows);
return {
applications,
total: Number(rows[0].total) || 0,
};
}
return {
applications: [],
total: 0,
};
}
async getUnannounced(): Promise<IClientApplication[]> {
const rows = await this.db(TABLE)
.select(COLUMNS)
.where('announced', false);
return rows.map(mapRow);
}
/** *
* Updates all rows that have announced = false to announced =true and returns the rows altered
* @return {[app]} - Apps that hadn't been announced
*/
async setUnannouncedToAnnounced(): Promise<IClientApplication[]> {
const rows = await this.db(TABLE)
.update({ announced: true })
.where('announced', false)
.whereNotNull('announced')
.returning(COLUMNS);
return rows.map(mapRow);
}
async delete(key: string): Promise<void> {
await this.db(TABLE).where('app_name', key).del();
}
async deleteAll(): Promise<void> {
await this.db(TABLE).del();
}
destroy(): void {}
async get(appName: string): Promise<IClientApplication> {
const row = await this.db
.select(COLUMNS)
.where('app_name', appName)
.from(TABLE)
.first();
if (!row) {
throw new NotFoundError(`Could not find appName=${appName}`);
}
return mapRow(row);
}
async getApplicationOverview(
appName: string,
): Promise<IApplicationOverview> {
const stopTimer = this.timer('getApplicationOverview');
const query = this.db
.with('metrics', (qb) => {
qb.select([
'cme.app_name',
'cme.environment',
'f.project',
this.db.raw(
'array_agg(DISTINCT cme.feature_name) as features',
),
])
.from('client_metrics_env as cme')
.where('cme.app_name', appName)
.leftJoin('features as f', 'f.name', 'cme.feature_name')
.groupBy('cme.app_name', 'cme.environment', 'f.project');
})
.with('instances', (qb) => {
qb.select([
'ci.app_name',
'ci.environment',
this.db.raw(
'COUNT(DISTINCT ci.instance_id) as unique_instance_count',
),
this.db.raw(
'ARRAY_AGG(DISTINCT ci.sdk_version) FILTER (WHERE ci.sdk_version IS NOT NULL) as sdk_versions',
),
this.db.raw('MAX(ci.last_seen) as latest_last_seen'),
])
.from('client_instances as ci')
.where('ci.app_name', appName)
.whereRaw("ci.last_seen >= NOW() - INTERVAL '24 hours'")
.groupBy('ci.app_name', 'ci.environment');
})
.select([
'm.project',
'm.environment',
'm.features',
'i.unique_instance_count',
'i.sdk_versions',
'i.latest_last_seen',
'ca.strategies',
])
.from('client_applications as ca')
.leftJoin('metrics as m', 'm.app_name', 'ca.app_name')
.leftJoin('instances as i', 'i.environment', 'm.environment')
.orderBy('m.environment', 'asc');
const rows = await query;
stopTimer();
if (!rows.length) {
throw new NotFoundError(`Could not find appName=${appName}`);
}
const existingStrategies: string[] = await this.db
.select('name')
.from('strategies')
.pluck('name');
return this.mapApplicationOverviewData(rows, existingStrategies);
}
mapApplicationOverviewData(
rows: any[],
existingStrategies: string[],
): IApplicationOverview {
const featureCount = new Set(rows.flatMap((row) => row.features)).size;
const missingStrategies: Set<string> = new Set();
const environments = rows.reduce((acc, row) => {
const {
environment,
unique_instance_count,
sdk_versions,
latest_last_seen,
project,
features,
strategies,
} = row;
if (!environment) return acc;
strategies?.forEach((strategy) => {
if (
!DEPRECATED_STRATEGIES.includes(strategy) &&
!existingStrategies.includes(strategy)
) {
missingStrategies.add(strategy);
}
});
const featuresNotMappedToProject = !project;
let env = acc.find((e) => e.name === environment);
if (!env) {
env = {
name: environment,
instanceCount: Number(unique_instance_count),
sdks: sdk_versions || [],
lastSeen: latest_last_seen,
issues: {
missingFeatures: featuresNotMappedToProject
? features
: [],
},
};
acc.push(env);
} else {
if (featuresNotMappedToProject) {
env.issues.missingFeatures = features;
}
}
return acc;
}, []);
environments.forEach((env) => {
env.sdks.sort();
});
return {
projects: [
...new Set(
rows
.filter((row) => row.project != null)
.map((row) => row.project),
),
],
featureCount,
environments,
issues: {
missingStrategies: [...missingStrategies],
},
};
}
private remapUsageRow = (input) => {
if (!input.projects || input.projects.length === 0) {
return [
{
app_name: input.appName,
project: '*',
environment: input.environment || '*',
},
];
} else {
return input.projects.map((project) => ({
app_name: input.appName,
project: project,
environment: input.environment || '*',
}));
}
};
async removeInactiveApplications(): Promise<number> {
const rows = await this.db(TABLE)
.whereRaw("seen_at < now() - interval '30 days'")
.del();
if (rows > 0) {
this.logger.debug(`Deleted ${rows} applications`);
}
return rows;
}
}