File size: 5,242 Bytes
1e92f2d |
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 |
import { createReadStream, createWriteStream } from 'fs'
import { createInterface } from 'readline'
import path from 'path'
import { EOL } from 'os'
const createEvent = (trace, ph, cat) => ({
name: trace.name,
// Category. We don't collect this for now.
cat: cat ?? '-',
ts: trace.timestamp,
// event category. We only use duration events (B/E) for now.
ph,
// process id. We don't collect this for now, putting arbitrary numbers.
pid: 1,
// thread id. We don't collect this for now, putting arbitrary numbers.
tid: 10,
args: trace.tags,
})
const cleanFilename = (filename) => {
if (filename.includes('&absolutePagePath=')) {
filename =
'page ' +
decodeURIComponent(
filename.replace(/.+&absolutePagePath=/, '').slice(0, -1)
)
}
filename = filename.replace(/.+!(?!$)/, '')
return filename
}
const getPackageName = (filename) => {
const match = /.+[\\/]node_modules[\\/]((?:@[^\\/]+[\\/])?[^\\/]+)/.exec(
cleanFilename(filename)
)
return match && match[1]
}
/**
* Create, reports spans recursively with its inner child spans.
*/
const reportSpanRecursively = (stream, trace, parentSpan) => {
// build-* span contains tags with path to the modules, trying to clean up if possible
const isBuildModule = trace.name.startsWith('build-module-')
if (isBuildModule) {
trace.packageName = getPackageName(trace.tags.name)
// replace name to cleaned up pkg name
trace.tags.name = trace.packageName
if (trace.children) {
const queue = [...trace.children]
trace.children = []
for (const e of queue) {
if (e.name.startsWith('build-module-')) {
const pkgName = getPackageName(e.tags.name)
if (!trace.packageName || pkgName !== trace.packageName) {
trace.children.push(e)
} else {
if (e.children) queue.push(...e.children)
}
}
}
}
}
/**
* interface TraceEvent {
* traceId: string;
* parentId: number;
* name: string;
* id: number;
* startTime: number;
* timestamp: number;
* duration: number;
* tags: Record<string, any>
* }
*/
stream.write(JSON.stringify(createEvent(trace, 'B')))
stream.write(',')
// Spans should be reported in chronological order
trace.children?.sort((a, b) => a.startTime - b.startTime)
trace.children?.forEach((childTrace) =>
reportSpanRecursively(stream, childTrace)
)
stream.write(
JSON.stringify(
createEvent(
{
...trace,
timestamp: trace.timestamp + trace.duration,
},
'E'
)
)
)
stream.write(',')
}
/**
* Read generated trace from file system, augment & sent it to the remote tracer.
*/
const collectTraces = async (filePath, outFilePath, metadata) => {
const readLineInterface = createInterface({
input: createReadStream(filePath),
crlfDelay: Infinity,
})
const writeStream = createWriteStream(outFilePath)
writeStream.write(`[${EOL}`)
const traces = new Map()
const rootTraces = []
// Input trace file contains newline-separated sets of traces, where each line is valid JSON
// type of Array<TraceEvent>. Read it line-by-line to manually reconstruct trace trees.
//
// We have to read through end of the trace -
// Trace events in the input file can appear out of order, so we need to remodel the shape of the span tree before reporting
for await (const line of readLineInterface) {
JSON.parse(line).forEach((trace) => traces.set(trace.id, trace))
}
// Link inner, child spans to the parents to reconstruct span with correct relations
for (const event of traces.values()) {
if (event.parentId) {
event.parent = traces.get(event.parentId)
if (event.parent) {
if (!event.parent.children) event.parent.children = []
event.parent.children.push(event)
}
}
if (!event.parent) {
rootTraces.push(event)
}
}
for (const trace of rootTraces) {
reportSpanRecursively(writeStream, trace)
}
writeStream.write(
JSON.stringify({
name: 'trace',
ph: 'M',
args: metadata,
})
)
writeStream.write(`${EOL}]`)
}
/**
* Naively validate, collect necessary args.
*/
const validateArgs = async () => {
// Collect necessary default metadata. Script should pass cli args as in order of
// - trace file to read
// - output file path (optional)
// - path to next.config.js (optional)
const [, , traceFilePath, outFile, configFilePath] = process.argv
const outFilePath = outFile ?? `${traceFilePath}.event`
const config = configFilePath
? (await import(path.resolve(process.cwd(), configFilePath))).default
: {}
if (!traceFilePath) {
throw new Error(
`Cannot collect traces without necessary metadata.
Try to run script with below args:
node trace-to-event-format.mjs tracefilepath [outfilepath] [configfilepath]`
)
}
const metadata = {
config,
}
return [traceFilePath, outFilePath, metadata]
}
validateArgs()
.then(([traceFilePath, outFilePath, metadata]) =>
collectTraces(traceFilePath, outFilePath, metadata)
)
.catch((e) => {
console.error(`Failed to generate traces`)
console.error(e)
})
|