Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Better output formatting and error handling #71

Merged
merged 1 commit into from
Sep 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
[![slack](https://img.shields.io/badge/slack-styra-24b6e0.svg?logo=slack)](https://styracommunity.slack.com/)
[![Apache License](https://img.shields.io/badge/license-Apache%202.0-orange.svg)](https://www.apache.org/licenses/LICENSE-2.0)
[![Visual Studio Marketplace Version](https://img.shields.io/visual-studio-marketplace/v/Styra.vscode-styra?color=24b6e0)](#)
[![Coverage](https://img.shields.io/badge/Coverage-76%25-brightgreen)](#)
[![Coverage](https://img.shields.io/badge/Coverage-74%25-brightgreen)](#)
[![CI status](https://github.com/StyraInc/vscode-styra/actions/workflows/main.yaml/badge.svg)](https://github.com/StyraInc/vscode-styra/actions/workflows/main.yaml)
[![closed PRs](https://img.shields.io/github/issues-pr-closed-raw/StyraInc/vscode-styra)](https://github.com/StyraInc/vscode-styra/pulls?q=is%3Apr+is%3Aclosed)
<!--
Expand Down
213 changes: 189 additions & 24 deletions package-lock.json

Large diffs are not rendered by default.

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@
},
"configuration": {
"type": "object",
"title": "Styra Configuration",
"title": "Styra",
"properties": {
"styra.checkUpdateInterval": {
"type": "number",
Expand Down Expand Up @@ -312,6 +312,7 @@
"node-fetch": "^2.6.13",
"picomatch": "^2.3.1",
"semver": "^7.3.8",
"shell-escape": "^0.2.0"
"shell-escape": "^0.2.0",
"table": "^6.8.1"
}
}
2 changes: 1 addition & 1 deletion src/commands/eopa-preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ async function runPreview(args: utils.PreviewEnvironment, path: string, query: s
.build();

const result = await request.run();
utils.reportResult(utils.formatResults(result), eopaPreviewChannel);
utils.reportResult(utils.formatResults(result, query !== ''), eopaPreviewChannel);
} catch (e: unknown) {
utils.reportError(e);
}
Expand Down
20 changes: 14 additions & 6 deletions src/lib/eopaPreview/Preview.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as https from 'https';
import {APIError} from './errors';
import {default as fetch} from 'node-fetch';
import {FilesAndData} from './FilesAndData';
import {posix} from 'path';
Expand Down Expand Up @@ -119,13 +120,15 @@ export class PreviewRequest {
async run(): Promise<object> {
const reqUrl = new URL(this.apiRoot.toString());
reqUrl.pathname = posix.join(reqUrl.pathname, 'v0', 'preview', this.path);
let params = ['metrics'];
if (this.args.options !== undefined) {
const searchParams = reqUrl.searchParams;
for (const option of this.args.options) {
searchParams.append(option, 'true');
}
reqUrl.search = searchParams.toString();
params = params.concat(this.args.options);
}
const searchParams = reqUrl.searchParams;
for (const option of params) {
searchParams.append(option, 'true');
}
reqUrl.search = searchParams.toString();

const headers: PreviewHeaders = {};
const body: {[key: string]:any} = {}; // eslint-disable-line @typescript-eslint/no-explicit-any
Expand Down Expand Up @@ -162,6 +165,11 @@ export class PreviewRequest {
body: JSON.stringify(body),
agent: sslConfiguredAgent,
});
return await req.json();

const response = await req.json();
if (!req.ok) {
throw new APIError(req.status, response);
}
return response;
}
}
18 changes: 18 additions & 0 deletions src/lib/eopaPreview/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,21 @@ export class FileError extends Error {
return `Error in ${this.path}: ${this.original.name}`;
}
}

export class APIError extends Error {
body?: object;
responseCode: number;

constructor(responseCode: number, body?: object) {
const errBody = body as {message?: string, code: string};
if (body && errBody.message !== undefined && errBody.code !== undefined) {
super(`${errBody.code} (${responseCode}): ${errBody.message}`);
} else if (body && errBody.message !== undefined) {
super(`${responseCode}: ${errBody.message}`);
} else {
super(`General API error (${responseCode})`);
}
this.responseCode = responseCode;
this.body = body;
}
}
211 changes: 209 additions & 2 deletions src/lib/eopaPreview/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {basename, dirname, join, sep} from 'path';
import {EnvironmentError} from './errors';
import {expandPathsStandard, expandPathStandard} from './pathVars';
import {FilesAndData, fsFilesAndData} from './FilesAndData';
import {getBorderCharacters, table} from 'table';
import {TLSAuth, TokenAuth} from './auth';

export type PreviewEnvironment = {
Expand Down Expand Up @@ -34,6 +35,19 @@ export type Parser = (data: string) => (object|undefined);
export type AuthType = 'none' | 'bearer' | 'tls';
export type FileStrategy = 'all' | 'file';

export type Expression = {
location: {col: number, row: number},
text: string
value: unknown
}
export type Bindings = {
[key: string]: unknown
}
export type OpaResult = {
bindings?: Bindings
expressions?: Expression[]
}

const packageRegex = /package ([a-zA-Z_].*)(?! )$/s;

export function previewSettings(editor?: vscode.TextEditor, workspace?: readonly vscode.WorkspaceFolder[]): PreviewSettings {
Expand Down Expand Up @@ -142,8 +156,201 @@ export function getPackagePath(path: string): string {
return _path;
}

export function formatResults(results: object): string {
return JSON.stringify(results, undefined, ' ');
export function formatResults(results: object, selection:boolean, raw?: boolean): string {
if (raw) {
return JSON.stringify(results, null, 2);
}
const r = results as {result: object, metrics: {[key: string]: number}, printed: string, provenance: object};

let output = '';

if (r.provenance) {
output += `PROVENANCE\n==========\n${JSON.stringify(r.provenance, null, 2)}\n\n`;
}

if (r.metrics?.timer_query_compile_stage_resolve_refs_ns) {
output += `METRICS\n=======\n${metricTables(r.metrics)}`;
// output += `METRICS\n=======\n${Object.keys(r.metrics).map((k: string) => formatMetric(k, r.metrics[k])).join('\n')}\n\n`;
}

if (r.printed) {
output += `PRINTED\n=======\n${r.printed}\n\n`;
}

output += 'RESULT\n======\n';
if (r.metrics?.timer_regovm_eval_ns) {
output += `# Evaluated in ${getPrettyTime(r.metrics.timer_regovm_eval_ns)}\n`;
}
output += `${formatOutput(r.result, selection)}`;

return output;
}

export function formatOutput(results: unknown, selection: boolean) {
if (results) {
if (selection) {
let selectionResults: OpaResult[] = [];
if (Array.isArray(results)) {
selectionResults = results;
} else {
selectionResults = [results];
}
const nResults = 1;

if (nResults > 0) {
const result = selectionResults[0];

if (!result.bindings) {
// No variables bound. We’re looking at stand-alone expressions that
// reference values.
if (
nResults === 1 &&
result.expressions &&
result.expressions.length === 1
) {
// There’s one expression. Return the referenced value.
return JSON.stringify(result.expressions[0].value, null, 2);
}

// There are multiple expressions. Return a Rego rule body per
// expression.
return formatExpressionsOutput(selectionResults);
}
}

// Variables bound. We’re looking at a query. Return a Rego rule body per
// set of bindings (i.e., per result).
return formatQueryOutput(selectionResults);
} else if (typeof results === 'object') {
return JSON.stringify(results, null, 2);
}
}

return 'No Results found.';
}

function formatExpressionsOutput(results: OpaResult[]) {
const expressions = results.reduce((accumulator: Expression[], result: OpaResult) => {
if (result.expressions) {
result.expressions.forEach((x: Expression) => accumulator.push(x));
}

return accumulator;
}, []);

expressions.sort((a: Expression, b: Expression) => {
const rowDelta = a.location.row - b.location.row;
if (rowDelta === 0) {
return a.location.col - b.location.col;
}

return rowDelta;
});

const values = expressions.map((x, i) => {
const comment = `{\n # Expression ${i + 1}`;
const expression = `\n expression = ${JSON.stringify(x.text)}`;
const value = `\n value = ${shiftRight(x.value)}\n}`;

return `${comment}${expression}${value}`;
});

const nExpressions = expressions.length;
const expressionsString = nExpressions === 1 ? 'value' : 'values';
const comment = `# Found ${nExpressions} ${expressionsString}`;
const head = 'values_by_expression[expression] = value';
const body = `${values.join(' ')}`;

return `${comment}\n${head} ${body}`;
}

function formatQueryOutput(results: OpaResult[]): string {
const keyBindings = results[0].bindings;
if (keyBindings === undefined) {
return 'No bindings found.';
}
const resultName = makeUniqueResultName(keyBindings);
const keys = Object.keys(keyBindings).filter((key) => !/^\$\d+$/.test(key));

const ruleBodies = results.map((result, index) => {
const bindings = result.bindings;
let expressions = '';
if (bindings !== undefined) {
expressions = keys
.map((name) => ` ${name} = ${shiftRight(bindings[name])}`)
.join('\n');
}

return `{\n ${resultName} = "Result ${index + 1}"\n${expressions}\n}`;
});

const nResults = results.length;
const nResultsString = nResults === 1 ? 'result' : 'results';
const pairs = keys.map((x) => `"${x}":${x}`).join(',');
const comment = `# Found ${nResults} ${nResultsString}`;
const head = `variable_bindings_by_result[${resultName}] = {${pairs}}`;
const body = ruleBodies.join(' ');

return `${comment}\n${head} ${body}`;
}

function makeUniqueResultName(bindings?: Bindings) {
const baseName = 'result';
if (bindings === undefined) {
return baseName;
}

let name = baseName;
let count = 1;
while (name in bindings) {
name = new Array(++count).join('_') + baseName;
}

return name;
}

function shiftRight(object: unknown) {
return JSON.stringify(object, null, 2).split('\n').join('\n ');
}

function metricTables(metrics: {[key: string]: number}): string {
let output = '';
const counts: Array<[string, string]> = [['Name', 'Number']];
const timers: Array<[string, string]> = [['Name', 'Time']];
Object.keys(metrics).forEach((k: string) => {
const keyParts = k.split('_');
const keyType = keyParts.shift();
switch (keyType) {
case 'counter':
counts.push([keyParts.join(' '), metrics[k].toString()]);
break;
case 'timer':
if (keyParts[keyParts.length - 1] === 'ns') {
keyParts.pop();
}
timers.push([keyParts.join(' '), getPrettyTime(metrics[k])]);
break;
}
});
if (counts.length > 1) {
output += table(counts, {border: getBorderCharacters('norc'), header: {alignment: 'center', content: 'COUNTERS'}}) + '\n';
}
if (timers.length > 1) {
output += table(timers, {border: getBorderCharacters('norc'), header: {alignment: 'center', content: 'TIMERS'}}) + '\n';
}
return output;
}

export function getPrettyTime(ns: number): string {
const seconds = ns / 1e9;
if (seconds >= 1) {
return seconds.toString() + 's';
}
const milliseconds = ns / 1e6;
if (milliseconds >= 1) {
return milliseconds.toString() + 'ms';
}
return (ns / 1e3).toString() + 'µs';
}

/**
Expand Down
Loading