-
Notifications
You must be signed in to change notification settings - Fork 242
Expand file tree
/
Copy pathbitrot.js
More file actions
executable file
·411 lines (372 loc) · 12.5 KB
/
bitrot.js
File metadata and controls
executable file
·411 lines (372 loc) · 12.5 KB
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
#!/usr/bin/env node
/*
* Copyright Elasticsearch B.V. and other contributors where applicable.
* Licensed under the BSD 2-Clause License; you may not use this file except in
* compliance with the BSD 2-Clause License.
*/
'use strict'
// Compare .tav.yml, docs/supported-technologies.asciidoc, and the current
// releases of modules instrumented by the Elastic Node.js APM agent to:
// - list inconsistencies between TAV-tested and "supported", and
// - list new releases of modules that the agent doesn't yet support
//
// Usage:
// node dev-utils/bitrot.js [MODULE-NAME...]
const { execSync } = require('child_process')
const fs = require('fs')
const dashdash = require('dashdash')
const ecsFormat = require('@elastic/ecs-pino-format')
const pino = require('pino')
const semver = require('semver')
const yaml = require('js-yaml')
let log = null
let rotCount = 0
const EXCUSE_FROM_SUPPORTED_TECHNOLOGIES_DOC = {
'@elastic/elasticsearch-canary': true, // we test this for advance warning for '@elastic/elasticsearch', but don't explicitly support the canary versions
'body-parser': true, // instrumented to support express
finalhandler: true, // instrumented to support express
got: true, // got@12 is pure ESM so we state support up to got@11 only
'mimic-response': true, // we instrument a single old version to indirectly support an old version of 'got'
mongojs: true, // last release was in 2019, we aren't going to add effort to this module now
'': null
}
const EXCUSE_FROM_TAV = {
'@elastic/elasticsearch-canary': true,
got: true, // got@12 is pure ESM so we state support up to got@11 only
hapi: true, // we deprecated 'hapi' (in favour of '@hapi/hapi')
jade: true, // we deprecated 'jade' (in favour of 'pug')
'mimic-response': true, // we instrument a single old version to indirectly support an old version of 'got'
mongojs: true, // last release was in 2019, we aren't going to add effort to this module now
'': null
}
// ---- caching
const gCachePath = '/tmp/apm-agent-nodejs-bitrot.cache.json'
let gCache = null
function ensureCacheLoaded (ns) {
if (gCache === null) {
try {
gCache = JSON.parse(fs.readFileSync(gCachePath))
} catch (loadErr) {
log.debug(loadErr, 'could not load cache')
gCache = {}
}
}
if (!(ns in gCache)) {
gCache[ns] = {}
}
return gCache[ns]
}
function saveCache () {
if (gCache !== null) {
fs.writeFileSync(gCachePath, JSON.stringify(gCache, null, 2))
}
}
// ---- minimal ANSI styling support (from bunyan)
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
// Suggested colors (some are unreadable in common cases):
// - Good: cyan, yellow (limited use, poor visibility on white background),
// bold, green, magenta, red
// - Bad: blue (not visible on cmd.exe), grey (same color as background on
// Solarized Dark theme from <https://github.com/altercation/solarized>, see
// issue #160)
var colors = {
bold: [1, 22],
italic: [3, 23],
underline: [4, 24],
inverse: [7, 27],
white: [37, 39],
grey: [90, 39],
black: [30, 39],
blue: [34, 39],
cyan: [36, 39],
green: [32, 39],
magenta: [35, 39],
red: [31, 39],
yellow: [33, 39]
}
function stylizeWithColor (str, color) {
if (!str) { return '' }
var codes = colors[color]
if (codes) {
return '\x1B[' + codes[0] + 'm' + str + '\x1B[' + codes[1] + 'm'
} else {
return str
}
}
function stylizeWithoutColor (str, color) {
return str
}
let stylize = stylizeWithColor
// ---- support functions
function rot (moduleName, s) {
rotCount++
console.log(`${stylize(moduleName, 'bold')} bitrot: ${s}`)
}
// Process docs/supported-technologies.asciidoc into an array of:
// {name: '<module name>', versions: '<version range>'}
//
// Note that the tables in this file don't seem to follow the AsciiDoc table
// syntax described here:
// https://docs.asciidoctor.org/asciidoc/latest/tables/build-a-basic-table/
// I don't know why the difference. This parsing supports just the limited form
// I see in supported-technologies.asciidoc.
function loadSupportedDoc () {
const docPath = 'docs/supported-technologies.asciidoc'
var html = fs.readFileSync(docPath, 'utf8')
var rows = []
var state = null // null | 'thead' | 'tbody'
html.split(/\n/g).forEach(function (line) {
if (!line.startsWith('|')) {
// no op
} else if (state === null) {
if (line.startsWith('|===')) {
state = 'thead'
}
} else if (state === 'thead') {
state = 'tbody'
} else if (state === 'tbody') {
if (line.startsWith('|===')) {
state = null
} else {
// Examples:
// |https://www.npmjs.com/package/generic-pool[generic-pool] | ^2.0.0 \|\| ^3.1.0 |Used by a lot of ...
// |https://www.npmjs.com/package/bluebird[bluebird] |>=2.0.0 <4.0.0 |
var escapePlaceholder = '6B1EC7E1-B273-40E9-94C4-197A59B55E24'
var cells = line
.trim()
.slice(1) // remove leading '|'
.replace(/\\\|/g, escapePlaceholder)
.split(/\s*\|\s*/g)
.map(c => c.replace(new RegExp(escapePlaceholder, 'g'), '|'))
.filter(c => c.length > 0)
rows.push(cells)
}
}
})
// log.trace({rows}, `${docPath} table rows`)
// The tables in supported-technologies.asciidoc have the module
// name in the first column, and version range in the second. There
// are two forms of the first cell to parse:
// [ '<<hapi,hapi>>', '>=9.0.0 <19.0.0' ],
// [ '<<hapi,@hapi/hapi>>', '>=17.9.0 <20.0.0' ],
// [ '<<koa,Koa>> via koa-router or @koa/router', '>=5.2.0 <10.0.0' ],
// [ '<<restify,Restify>>', '>=5.2.0' ],
// [ '<<lambda,AWS Lambda>>', 'N/A' ],
// ['https://www.npmjs.com/package/jade[jade]', '>=0.5.6']
//
// The entries in the "Frameworks" table use the names of internal links in
// these docs. The anchor name is *sometimes* the same name as the npm
// module, but sometimes not.
var results = []
let match
rows.forEach(function (row) {
if (row[1] === 'N/A') {
// skip
} else if (row[0].includes('<<')) {
match = /^\s*<<([\w-]+),(.*?)>>/.exec(row[0])
if (!match) {
throw new Error(`could not parse this table cell text from docs/supported-technologies.asciidoc: ${JSON.stringify(row[0])}`)
}
var moduleNames
if (match[1] === 'nextjs') {
moduleNames = ['next']
} else if (match[2] === '@hapi/hapi') {
moduleNames = [match[2]]
} else if (match[2] === '@opentelemetry/api') {
moduleNames = [match[2]]
} else if (match[1] === 'koa') {
moduleNames = ['koa-router', '@koa/router']
} else if (match[1] === 'azure-functions') {
moduleNames = [] // Azure Functions compat isn't about an NPM package version.
} else {
moduleNames = [match[1]]
}
moduleNames.forEach(n => {
results.push({ name: n, versions: row[1] })
})
} else {
match = /^https:\/\/.*\[(.*)\]$/.exec(row[0].trim())
if (!match) {
throw new Error(`could not parse this table cell text from docs/supported-technologies.asciidoc: ${JSON.stringify(row[0])}`)
}
results.push({ name: match[1], versions: row[1] })
}
})
return results
}
function getNpmInfo (name) {
const CACHE_TIMEOUT_MS = 30 * 60 * 1000 // 30 minutes
const cache = ensureCacheLoaded('npmInfo')
const cacheEntry = cache[name]
if (cacheEntry) {
if (cacheEntry.timestamp + CACHE_TIMEOUT_MS > Date.now()) {
return cacheEntry.value
} else {
delete cache[name]
}
}
// Limited security guard on exec'ing given `name`.
const PKG_NAME_RE = /^(@[\w_.-]+\/)?([\w_.-]+)$/
if (!PKG_NAME_RE.test(name)) {
throw new Error(`${JSON.stringify(name)} does not look like a valid npm package name`)
}
const stdout = execSync(`npm info -j "${name}"`)
const npmInfo = JSON.parse(stdout)
cache[name] = {
timestamp: Date.now(),
value: npmInfo
}
saveCache()
return npmInfo
}
function bitrot (moduleNames) {
log.debug({ moduleNames }, 'bitrot')
var tavYmls = [
yaml.load(fs.readFileSync('.tav.yml', 'utf8')),
yaml.load(fs.readFileSync('./test/opentelemetry-bridge/.tav.yml', 'utf8')),
yaml.load(fs.readFileSync('./test/opentelemetry-metrics/fixtures/.tav.yml', 'utf8')),
yaml.load(fs.readFileSync('test/instrumentation/modules/next/a-nextjs-app/.tav.yml', 'utf8'))
]
var supported = loadSupportedDoc()
// Merge into one data structure we can iterate through.
var rangesFromName = {}
var ensureKey = (name) => {
if (!(name in rangesFromName)) {
rangesFromName[name] = { tavRanges: [], supRanges: [] }
}
}
tavYmls.forEach(tavYml => {
for (const [label, tavInfo] of Object.entries(tavYml)) {
var name = tavInfo.name || label
ensureKey(name)
rangesFromName[name].tavRanges.push(tavInfo.versions)
}
})
for (const supInfo of supported) {
ensureKey(supInfo.name)
rangesFromName[supInfo.name].supRanges.push(supInfo.versions)
}
// Reduce to `moduleNames` if given.
if (moduleNames && moduleNames.length > 0) {
var allNames = Object.keys(rangesFromName)
moduleNames.forEach(name => {
if (!(name in rangesFromName)) {
throw new Error(`unknown module name: ${name} (known module names: ${allNames.join(', ')})`)
}
})
allNames.forEach(name => {
if (!moduleNames.includes(name)) {
delete rangesFromName[name]
}
})
}
log.debug({ rangesFromName }, 'rangesFromName')
// Check each module name.
var namesToCheck = Object.keys(rangesFromName).sort()
namesToCheck.forEach(name => {
var npmInfo = getNpmInfo(name)
log.trace({ name, 'dist-tags': npmInfo['dist-tags'], time: npmInfo.time }, 'npmInfo')
// If the current latest version is in the supported and
// tav ranges, then all is good.
var latest = npmInfo['dist-tags'].latest
var tavGood = false
if (EXCUSE_FROM_TAV[name]) {
tavGood = true
} else {
for (const range of rangesFromName[name].tavRanges) {
if (semver.satisfies(latest, range, { includePrerelease: true })) {
tavGood = true
break
}
}
}
var supGood = false
if (EXCUSE_FROM_SUPPORTED_TECHNOLOGIES_DOC[name]) {
supGood = true
} else {
for (const range of rangesFromName[name].supRanges) {
if (semver.satisfies(latest, range, { includePrerelease: true })) {
supGood = true
break
}
}
}
if (tavGood && supGood) {
log.debug(`latest ${name}@${latest} is in tav and supported ranges (a good thing)`)
return
}
var issues = []
if (!tavGood) {
issues.push(`is not in .tav.yml ranges (${rangesFromName[name].tavRanges.join(', ')})`)
}
if (!supGood) {
issues.push(`is not in supported-technologies.asciidoc ranges (${rangesFromName[name].supRanges.join(', ')})`)
}
rot(name, `latest ${name}@${latest} (released ${npmInfo.time[latest].split('T')[0]}): ${issues.join(', ')}`)
})
}
// ---- mainline
const options = [
{
names: ['verbose', 'v'],
type: 'bool',
help: 'Verbose log output. (Pipe to `ecslog` to format.)'
},
{
names: ['help', 'h'],
type: 'bool',
help: 'Print this help and exit.'
}
]
function main (argv) {
var parser = dashdash.createParser({ options })
try {
var opts = parser.parse(argv)
} catch (e) {
console.error('help: error: %s', e.message)
process.exit(1)
}
if (opts.help) {
var help = parser.help().trimRight()
process.stdout.write(`Synopsis:
dev-utils/bitrot.js [OPTIONS]
Description:
Compare ".tav.yml", "docs/supported-technologies.asciidoc"
and the current releases of instrumented modules to list
new releases that are not (yet) supported by the APM agent.
Options:
${help}
Exit status:
0 No bitrot was found.
1 There was an unexpected error.
3 Bitrot was found.
`)
process.exit(0)
}
stylize = process.stdout.isTTY ? stylizeWithColor : stylizeWithoutColor
log = pino({
name: 'bitrot',
base: {}, // Don't want pid and hostname fields.
level: opts.verbose ? 'trace' : 'warn',
serializers: {
err: pino.stdSerializers.err,
req: pino.stdSerializers.req,
res: pino.stdSerializers.res
},
...ecsFormat({ apmIntegration: false })
}, pino.destination(1))
const moduleNames = opts._args
try {
bitrot(moduleNames)
} catch (err) {
log.debug(err)
console.error(`bitrot: error: ${err.message}`)
process.exit(1)
}
if (rotCount > 0) {
process.exit(3)
}
}
if (require.main === module) {
main(process.argv)
}