-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathindex.ts
More file actions
79 lines (69 loc) · 2.18 KB
/
index.ts
File metadata and controls
79 lines (69 loc) · 2.18 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
import {
getCodspeedRunnerMode,
getGitDir,
getInstrumentMode,
InstrumentHooks,
mongoMeasurement,
SetupInstrumentsRequestBody,
SetupInstrumentsResponse,
tryIntrospect,
} from "@codspeed/core";
import path from "path";
import { get as getStackTrace } from "stack-trace";
import { Bench } from "tinybench";
import { fileURLToPath } from "url";
import { setupCodspeedAnalysisBench } from "./analysis";
import { getOrCreateUriMap } from "./uri";
import { setupCodspeedWalltimeBench } from "./walltime";
tryIntrospect();
export function withCodSpeed(bench: Bench): Bench {
const codspeedRunnerMode = getCodspeedRunnerMode();
if (codspeedRunnerMode === "disabled") {
return bench;
}
const rootCallingFile = getCallingFile();
// Compute and register URI for bench
const uriMap = getOrCreateUriMap(bench);
const rawAdd = bench.add;
bench.add = (name, fn, opts?) => {
const callingFile = getCallingFile();
let uri = callingFile;
if (bench.name !== undefined) {
uri += `::${bench.name}`;
}
uri += `::${name}`;
uriMap.set(name, uri);
return rawAdd.bind(bench)(name, fn, opts);
};
const instrumentMode = getInstrumentMode();
if (instrumentMode === "analysis") {
setupCodspeedAnalysisBench(bench, rootCallingFile);
} else if (instrumentMode === "walltime") {
setupCodspeedWalltimeBench(bench, rootCallingFile);
}
return bench;
}
function getCallingFile(): string {
const stack = getStackTrace();
let callingFile = stack[2].getFileName(); // [here, withCodSpeed, actual caller]
const gitDir = getGitDir(callingFile);
if (gitDir === undefined) {
throw new Error("Could not find a git repository");
}
if (callingFile.startsWith("file://")) {
callingFile = fileURLToPath(callingFile);
}
return path.relative(gitDir, callingFile);
}
/**
* Dynamically setup the CodSpeed instruments.
*/
export async function setupInstruments(
body: SetupInstrumentsRequestBody
): Promise<SetupInstrumentsResponse> {
if (!InstrumentHooks.isInstrumented()) {
console.warn("[CodSpeed] No instrumentation found, using default mongoUrl");
return { remoteAddr: body.mongoUrl };
}
return await mongoMeasurement.setupInstruments(body);
}