@atomist/org-visualizer
Version:
Organization Visualizer using Atomist project scanning
267 lines • 13.3 kB
JavaScript
;
/*
* Copyright © 2019 Atomist, Inc.
*
* 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.
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const automation_client_1 = require("@atomist/automation-client");
const sdm_core_1 = require("@atomist/sdm-core");
const sdm_pack_fingerprints_1 = require("@atomist/sdm-pack-fingerprints");
const bodyParser = require("body-parser");
const _ = require("lodash");
const path = require("path");
const swaggerUi = require("swagger-ui-express");
const yaml = require("yamljs");
const analytics_1 = require("../analysis/offline/spider/analytics");
const repoTree_1 = require("../aspect/repoTree");
const categories_1 = require("../customize/categories");
const treeUtils_1 = require("../tree/treeUtils");
const auth_1 = require("./auth");
const buildFingerprintTree_1 = require("./buildFingerprintTree");
const wellKnownReporters_1 = require("./wellKnownReporters");
/**
* Expose the public API routes, returning JSON.
* Also expose Swagger API documentation.
*/
function api(clientFactory, store, aspectRegistry) {
const serveSwagger = sdm_core_1.isInLocalMode();
const docRoute = "/api-docs";
const routesToSuggestOnStartup = serveSwagger ? [{ title: "Swagger", route: docRoute }] : [];
return {
routesToSuggestOnStartup,
customizer: (express, ...handlers) => {
express.use(bodyParser.json()); // to support JSON-encoded bodies
express.use(bodyParser.urlencoded({
extended: true,
}));
if (serveSwagger) {
exposeSwaggerDoc(express, docRoute);
}
auth_1.configureAuth(express);
exposeIdealAndProblemSetting(express, aspectRegistry);
exposeAspectMetadata(express, store);
exposeListFingerprints(express, store);
exposeFingerprintByType(express, aspectRegistry, store);
exposeFingerprintByTypeAndName(express, aspectRegistry, clientFactory, store);
exposeDrift(express, aspectRegistry, clientFactory);
// In memory queries against returns
express.options("/api/v1/:workspace_id/filter/:name", auth_1.corsHandler());
express.get("/api/v1/:workspace_id/filter/:name", [auth_1.corsHandler(), ...auth_1.authHandlers()], (req, res) => __awaiter(this, void 0, void 0, function* () {
try {
const allQueries = wellKnownReporters_1.WellKnownReporters;
const q = allQueries[req.params.name];
if (!q) {
throw new Error(`No query named '${req.params.name}'`);
}
const cannedQuery = q(Object.assign({}, req.query));
const repos = yield store.loadInWorkspace(req.query.workspace || req.params.workspace_id);
const relevantRepos = repos.filter(ar => req.query.owner ? ar.analysis.id.owner === req.params.owner : true);
const data = yield cannedQuery.toSunburstTree(() => relevantRepos.map(r => r.analysis));
return res.json({ tree: data });
}
catch (e) {
automation_client_1.logger.warn("Error occurred getting report: %s %s", e.message, e.stack);
res.sendStatus(500);
}
}));
// Calculate and persist entropy for this fingerprint
express.put("/api/v1/:workspace/entropy/:type/:name", ...handlers, (req, res) => __awaiter(this, void 0, void 0, function* () {
yield analytics_1.computeAnalyticsForFingerprintKind(store, req.params.workspace, req.params.type, req.params.name);
res.sendStatus(201);
}));
},
};
}
exports.api = api;
function exposeSwaggerDoc(express, docRoute) {
const swaggerDocPath = path.join(__dirname, "..", "..", "swagger.yaml");
const swaggerDocument = yaml.load(swaggerDocPath);
express.use(docRoute, swaggerUi.serve, swaggerUi.setup(swaggerDocument));
}
function exposeAspectMetadata(express, store) {
// Return the aspects metadata
express.options("/api/v1/:workspace_id/aspects", auth_1.corsHandler());
express.get("/api/v1/:workspace_id/aspects", [auth_1.corsHandler(), ...auth_1.authHandlers()], (req, res) => __awaiter(this, void 0, void 0, function* () {
try {
const workspaceId = req.params.workspace_id || "local";
const fingerprintUsage = yield store.fingerprintUsageForType(workspaceId);
const reports = categories_1.getAspectReports(fingerprintUsage, workspaceId);
automation_client_1.logger.debug("Returning aspect reports for '%s': %j", workspaceId, reports);
const count = yield store.distinctRepoCount(workspaceId);
const at = yield store.latestTimestamp(workspaceId);
res.json({
list: reports,
analyzed: {
repo_count: count,
at,
},
});
}
catch (e) {
automation_client_1.logger.warn("Error occurred getting aspect metadata: %s %s", e.message, e.stack);
res.sendStatus(500);
}
}));
}
function exposeListFingerprints(express, store) {
// Return all fingerprints
express.options("/api/v1/:workspace_id/fingerprints", auth_1.corsHandler());
express.get("/api/v1/:workspace_id/fingerprints", [auth_1.corsHandler(), ...auth_1.authHandlers()], (req, res) => __awaiter(this, void 0, void 0, function* () {
try {
const workspaceId = req.params.workspace_id || "local";
const fingerprintUsage = yield store.fingerprintUsageForType(workspaceId);
automation_client_1.logger.debug("Returning fingerprints for '%s': %j", workspaceId, fingerprintUsage);
res.json({ list: fingerprintUsage });
}
catch (e) {
automation_client_1.logger.warn("Error occurred getting fingerprints: %s %s", e.message, e.stack);
res.sendStatus(500);
}
}));
}
function exposeFingerprintByType(express, aspectRegistry, store) {
express.options("/api/v1/:workspace_id/fingerprint/:type", auth_1.corsHandler());
express.get("/api/v1/:workspace_id/fingerprint/:type", [auth_1.corsHandler(), ...auth_1.authHandlers()], (req, res) => __awaiter(this, void 0, void 0, function* () {
try {
const workspaceId = req.params.workspace_id || "*";
const type = req.params.type;
const fps = yield store.fingerprintUsageForType(workspaceId, type);
fillInAspectNamesInList(aspectRegistry, fps);
automation_client_1.logger.debug("Returning fingerprints of type for '%s': %j", workspaceId, fps);
res.json({
list: fps,
analyzed: {
count: fps.length,
variants: _.sumBy(fps, "variants"),
},
});
}
catch (e) {
automation_client_1.logger.warn("Error occurred getting fingerprints: %s %s", e.message, e.stack);
res.sendStatus(500);
}
}));
}
function exposeFingerprintByTypeAndName(express, aspectRegistry, clientFactory, store) {
express.options("/api/v1/:workspace_id/fingerprint/:type/:name", auth_1.corsHandler());
express.get("/api/v1/:workspace_id/fingerprint/:type/:name", [auth_1.corsHandler(), ...auth_1.authHandlers()], (req, res) => __awaiter(this, void 0, void 0, function* () {
const workspaceId = req.params.workspace_id;
const fingerprintType = req.params.type;
const fingerprintName = req.params.name;
const byName = req.params.name !== "*";
const showPresence = req.query.presence === "true";
const showProgress = req.query.progress === "true";
const trim = req.query.trim === "true";
const byOrg = req.query.byOrg === "true";
const otherLabel = req.query.otherLabel === "true";
try {
const pt = yield buildFingerprintTree_1.buildFingerprintTree({ aspectRegistry, clientFactory }, {
showPresence,
otherLabel,
showProgress,
byOrg,
trim,
fingerprintType,
fingerprintName,
workspaceId,
byName,
});
const ideal = yield store.loadIdeal(workspaceId, fingerprintType, fingerprintName);
let target;
if (sdm_pack_fingerprints_1.isConcreteIdeal(ideal)) {
const aspect = aspectRegistry.aspectOf(fingerprintType);
if (!!aspect && !!aspect.toDisplayableFingerprint) {
target = Object.assign({}, ideal.ideal, { value: aspect.toDisplayableFingerprint(ideal.ideal) });
}
}
res.json(Object.assign({}, pt, { target }));
}
catch (e) {
automation_client_1.logger.warn("Error occurred getting one fingerprint: %s %s", e.message, e.stack);
res.sendStatus(500);
}
}));
}
function exposeDrift(express, aspectRegistry, clientFactory) {
express.options("/api/v1/:workspace_id/drift", auth_1.corsHandler());
express.get("/api/v1/:workspace_id/drift", [auth_1.corsHandler(), ...auth_1.authHandlers()], (req, res) => __awaiter(this, void 0, void 0, function* () {
try {
const type = req.query.type;
const skewTree = type ?
yield repoTree_1.driftTreeForSingleAspect(req.params.workspace_id, type, clientFactory) :
yield repoTree_1.driftTree(req.params.workspace_id, clientFactory);
fillInAspectNames(aspectRegistry, skewTree.tree);
return res.json(skewTree);
}
catch (err) {
automation_client_1.logger.warn("Error occurred getting drift report: %s %s", err.message, err.stack);
res.sendStatus(500);
}
}));
}
function exposeIdealAndProblemSetting(express, aspectRegistry) {
// Set an ideal
express.options("/api/v1/:workspace_id/ideal/:id", auth_1.corsHandler());
express.put("/api/v1/:workspace_id/ideal/:id", [auth_1.corsHandler(), ...auth_1.authHandlers()], (req, res) => __awaiter(this, void 0, void 0, function* () {
yield aspectRegistry.idealStore.setIdeal(req.params.workspace_id, req.params.id);
automation_client_1.logger.info(`Set ideal to ${req.params.id}`);
res.sendStatus(201);
}));
// Note this fingerprint as a problem
express.options("/api/v1/:workspace_id/problem/:id", auth_1.corsHandler());
express.put("/api/v1/:workspace_id/problem/:id", [auth_1.corsHandler(), ...auth_1.authHandlers()], (req, res) => __awaiter(this, void 0, void 0, function* () {
yield aspectRegistry.problemStore.noteProblem(req.params.workspace_id, req.params.id);
automation_client_1.logger.info(`Set problem at ${req.params.id}`);
res.sendStatus(201);
}));
}
/**
* Any nodes that have type and name should be given the fingerprint name from the aspect if possible
*/
function fillInAspectNames(aspectRegistry, tree) {
treeUtils_1.visit(tree, n => {
const t = n;
if (t.name && t.type) {
if (t.name && t.type) {
const aspect = aspectRegistry.aspectOf(t.type);
if (aspect && aspect.toDisplayableFingerprintName) {
n.name = aspect.toDisplayableFingerprintName(n.name);
}
}
}
return true;
});
}
/**
* Fill in aspect names
*/
function fillInAspectNamesInList(aspectRegistry, fingerprints) {
fingerprints.forEach(fp => {
const aspect = aspectRegistry.aspectOf(fp.type);
if (!!aspect && !!aspect.toDisplayableFingerprintName) {
fp.displayName = aspect.toDisplayableFingerprintName(fp.name);
}
// This is going to be needed for the invocation of the command handlers to set targets
fp.fingerprint = `${fp.type}::${fp.name}`;
});
}
//# sourceMappingURL=api.js.map