forked from newrelic/newrelic-quickstarts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild-validate-quickstart-artifact.ts
168 lines (131 loc) · 5.1 KB
/
build-validate-quickstart-artifact.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
import * as fs from 'fs';
import * as yaml from 'js-yaml';
import get from 'lodash/get';
import Quickstart from "./lib/Quickstart";
import DataSource from "./lib/DataSource";
import Alert from "./lib/Alert";
import Dashboard from "./lib/Dashboard";
import Ajv, { type ErrorObject } from 'ajv';
import { passedProcessArguments } from './lib/helpers';
import { ArtifactDataSourceConfig, ArtifactDashboardConfig, ArtifactQuickstartConfig, ArtifactAlertConfig } from './types/Artifact';
type ArtifactSchema = Record<string, unknown>;
type InvalidItem = {
value: unknown;
component: unknown;
error: ErrorObject;
}
type ArtifactComponents = {
quickstarts: ArtifactQuickstartConfig[],
dataSources: ArtifactDataSourceConfig[],
alerts: ArtifactAlertConfig,
dashboards: ArtifactDashboardConfig
}
type Artifact = ArtifactComponents | {
dataSourceIds: string[]
}
const getSchema = (filepath: string): ArtifactSchema => {
return yaml.load(
fs.readFileSync(filepath).toString('utf8')
) as ArtifactSchema;
};
// NOTE: we could run these in parallel to speed up the script
export const getArtifactComponents = (): ArtifactComponents => {
const quickstarts = Quickstart
.getAll()
.map((quickstart) => quickstart.transformForArtifact());
console.log(`[*] Found ${quickstarts.length} quickstarts`);
const dataSources = DataSource
.getAll()
.map((dataSource) => dataSource.transformForArtifact());
console.log(`[*] Found ${dataSources.length} dataSources`);
const alerts = Alert.getAll().reduce((acc, alert) => {
const conditions = alert.transformForArtifact()
return { ...acc, ...conditions }
}, {});
console.log(`[*] Found ${Object.keys(alerts).length} alerts`);
const dashboards = Dashboard.getAll().reduce((acc, dash) => {
const dashboard = dash.transformForArtifact()
return { ...acc, ...dashboard }
}, {});
console.log(`[*] Found ${Object.keys(dashboards).length} dashboards`);
return {
quickstarts,
dataSources,
alerts,
dashboards
}
};
export const getDataSourceIds = (filepath: string, communityDataSources: ArtifactComponents['dataSources']): string[] => {
const coreDataSourceIds = yaml.load(
fs.readFileSync(filepath).toString('utf8')
) as string[];
const communityDataSourceIds = communityDataSources.map((dataSource) => dataSource.id);
return [...coreDataSourceIds, ...communityDataSourceIds];
}
export const validateArtifact = (schema: ArtifactSchema, artifact: Artifact): ErrorObject[] => {
const ajv = new Ajv({ allErrors: true });
ajv.validate(schema, artifact);
return ajv.errors ?? [];
}
const main = (shouldOutputArtifact: boolean = false) => {
const schema = getSchema('./schema/artifact.json');
const components = getArtifactComponents();
const dataSourceIds = getDataSourceIds('./schema/core-datasource-ids.json', components.dataSources);
const artifact = { ...components, dataSourceIds };
const errors = validateArtifact(schema, artifact);
if (errors.length) {
const invalidItems = getInvalidItems(errors, artifact);
printErrors(invalidItems);
process.exit(1);
}
console.log('[*] Validation succeeded');
if (shouldOutputArtifact) {
outputArtifact(artifact);
}
}
const outputArtifact = (artifact: Artifact) => {
console.log('[*] Outputting the artifact');
try {
fs.mkdirSync('./build', { recursive: true });
// Dump the artifact to artifact.json
fs.writeFileSync('./build/artifact.json', JSON.stringify(artifact));
// Copy the schema to schema.json
fs.copyFileSync('./schema/artifact.json', './build/schema.json');
} catch (e) {
console.error('Error writing artifact to file:', e);
process.exit(1);
}
}
const getInvalidItems = (errors: ErrorObject[], artifact: ArtifactSchema): InvalidItem[] => {
return errors.map((error) => {
// Get the path to the invalid value from the error `instancePath`.
// NOTE: we're using `slice(1)` here to remove the leading `/` in the path.
const invalidValuePath = error.instancePath.split('/').slice(1);
const value = get(artifact, invalidValuePath);
// Get the specific "component" (e.g. the alert or dashboard) that contains
// the invalid value. This makes the assumption that the first two parts of
// the "path" are the component type and the index in the array.
const component = get(artifact, invalidValuePath.slice(0, 2));
return { value, component, error };
});
}
const printErrors = (invalidItems: InvalidItem[]): void => {
console.error('*** Validation failed. See errors below. ***');
console.error('--------------------------------------------');
invalidItems.forEach(({ value, component, error }, idx) => {
console.error(`Error #${idx + 1}:`, error);
console.error('');
console.error('Received value:', value);
console.error('');
if (component !== value) {
console.error('Invalid component:', component);
}
if (idx < invalidItems.length - 1) {
console.error('************************************');
}
});
}
if (require.main === module) {
const shouldOutputArtifact = passedProcessArguments().includes('--output-artifact');
main(shouldOutputArtifact);
}