in addons/addon-base-raas/packages/base-raas-services/lib/costs/costs-service.js [40:134]
async getIndividualEnvironmentOrProjCost(requestContext, query) {
// ensure that the caller has permissions to read the cost
// Perform default condition checks to make sure the user is active and has allowed roles
const allowIfHasCorrectRoles = (reqContext, { action }) =>
allowIfHasRole(reqContext, { action, resource: 'environment-or-project-cost' }, ['admin', 'researcher']);
await this.assertAuthorized(
requestContext,
{ action: 'read', conditions: [allowIfActive, allowIfHasCorrectRoles] },
query,
);
const { env, scEnv, proj, groupByUser, groupByEnv, groupByService, numberOfDaysInPast } = query;
const [environmentService, environmentScService, costApiCacheService] = await this.service([
'environmentService',
'environmentScService',
'costApiCacheService',
]);
if (groupByUser === 'true' && groupByEnv === 'true' && groupByService === 'true') {
return 'Can not groupByUser, groupByEnv, and groupByService. Please pick at most 2 out of the 3.';
}
let indexId = '';
if (proj) {
indexId = proj;
} else if (env) {
// The following will only succeed if the user has permissions to access the specified environment
const result = await environmentService.mustFind(requestContext, { id: env });
indexId = result.indexId;
} else if (scEnv) {
// The following will only succeed if the user has permissions to access the specified service catalog based environment
const result = await environmentScService.mustFind(requestContext, { id: scEnv, fields: ['indexId'] });
indexId = result.indexId;
}
const cacheResponse = await costApiCacheService.find(requestContext, { indexId, query: JSON.stringify(query) });
if (cacheResponse) {
const updatedAt = new Date(cacheResponse.updatedAt);
const now = new Date();
const elapsedHours = (now - updatedAt) / 1000 / 60 / 60;
if (elapsedHours < 12) {
return JSON.parse(cacheResponse.result);
}
}
let filter = {};
if (proj) {
filter = {
Tags: {
Key: 'Proj',
Values: [proj],
},
};
} else {
filter = {
Tags: {
Key: 'Env',
Values: [env || scEnv],
},
};
}
const groupBy = [];
if (groupByService === 'true') {
groupBy.push({
Type: 'DIMENSION',
Key: 'SERVICE',
});
}
if (groupByUser === 'true') {
groupBy.push({
Type: 'TAG',
Key: 'CreatedBy',
});
}
if (groupByEnv === 'true') {
groupBy.push({
Type: 'TAG',
Key: 'Env',
});
}
const response = await this.callAwsCostExplorerApi(requestContext, indexId, numberOfDaysInPast, filter, groupBy);
if (response) {
const rawCacheData = {
indexId,
query: JSON.stringify(query),
result: JSON.stringify(response),
};
await costApiCacheService.create(requestContext, rawCacheData);
}
return response || [];
}