-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathlogs.ts
More file actions
101 lines (86 loc) · 2.27 KB
/
logs.ts
File metadata and controls
101 lines (86 loc) · 2.27 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
import { env, isCI } from "std-env";
import { TaskContext } from "vitest";
import { DockerDiagnostics, getDockerDiagnostics } from "./docker";
import { StartedTestContainer } from "testcontainers";
let setupOrder = 0;
export function logSetup(resource: string, metadata: Record<string, unknown>) {
const order = setupOrder++;
if (!isCI) {
return;
}
console.log(
JSON.stringify({
type: "setup",
order,
resource,
timestamp: new Date().toISOString(),
...metadata,
})
);
}
export function getContainerMetadata(container: StartedTestContainer) {
return {
containerName: container.getName(),
containerId: container.getId().slice(0, 12),
containerNetworkNames: container.getNetworkNames(),
};
}
export function getTaskMetadata(task: TaskContext["task"]) {
return {
testName: task.name,
};
}
let cleanupOrder = 0;
let activeCleanups = 0;
/**
* Logs the cleanup of a resource.
* @param resource - The resource that is being cleaned up.
* @param promise - The cleanup promise to await..
*/
export async function logCleanup(
resource: string,
promise: Promise<unknown>,
metadata: Record<string, unknown> = {}
) {
const start = new Date();
const order = cleanupOrder++;
const activeAtStart = ++activeCleanups;
let error: unknown = null;
try {
await promise;
} catch (err) {
error = err instanceof Error ? err.message : String(err);
}
const end = new Date();
const durationMs = end.getTime() - start.getTime();
const activeAtEnd = --activeCleanups;
const parallel = activeAtStart > 1 || activeAtEnd > 0;
if (!isCI) {
return;
}
let dockerDiagnostics: DockerDiagnostics = {};
// Only run docker diagnostics if there was an error or cleanup took longer than 5s
if (error || durationMs > 5000 || env.DOCKER_DIAGNOSTICS) {
try {
dockerDiagnostics = await getDockerDiagnostics();
} catch (diagnosticErr) {
console.error("Failed to get docker diagnostics:", diagnosticErr);
}
}
console.log(
JSON.stringify({
type: "cleanup",
order,
resource,
durationMs,
start: start.toISOString(),
end: end.toISOString(),
parallel,
error,
activeAtStart,
activeAtEnd,
...metadata,
...dockerDiagnostics,
})
);
}