-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathcommand.ts
More file actions
267 lines (241 loc) · 7.53 KB
/
Copy pathcommand.ts
File metadata and controls
267 lines (241 loc) · 7.53 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
import * as fs from "node:fs/promises";
import * as os from "node:os";
import * as path from "node:path";
import * as vscode from "vscode";
import { throwIfAborted, toError } from "../../error/errorUtils";
import { withCancellableProgress } from "../../progress";
import { toUtcDateString, validateUtcDateInput } from "../../util/date";
import { listTelemetryFilesForRange, streamTelemetryEvents } from "./files";
import {
TELEMETRY_RANGE_PRESETS,
createCustomDateRange,
createPresetDateRange,
type TelemetryDateRange,
type TelemetryRangePresetId,
} from "./range";
import { writeJsonArrayExport } from "./writers/json";
import { writeOtlpZipExport } from "./writers/otlp/writer";
import type { Logger } from "../../logging/logger";
import type { TelemetryContext } from "../event";
interface FormatPick extends vscode.QuickPickItem {
readonly id: "json" | "otlp";
}
interface RangePick extends vscode.QuickPickItem {
readonly id: TelemetryRangePresetId | "custom";
}
interface FormatOutput {
readonly ext: string;
readonly filters: NonNullable<vscode.SaveDialogOptions["filters"]>;
}
interface ExportSummary {
readonly filesScanned: number;
readonly eventCount: number;
}
const FORMAT_PICKS: readonly FormatPick[] = [
{
id: "json",
label: "JSON array",
detail: "Single JSON document for human inspection or compliance review.",
},
{
id: "otlp",
label: "OTLP/JSON zip",
detail:
"Zip containing logs.json, traces.json, and metrics.json for OTLP endpoints.",
},
];
const CUSTOM_RANGE_PICK: RangePick = {
id: "custom",
label: "Custom range…",
detail: "Choose inclusive UTC start and end dates.",
};
const FORMAT_OUTPUT: Record<FormatPick["id"], FormatOutput> = {
json: { ext: "json", filters: { "JSON files": ["json"] } },
otlp: { ext: "otlp.zip", filters: { "Zip files": ["zip"] } },
};
export async function runExportTelemetryCommand(
telemetryDir: string,
logger: Logger,
flushTelemetry: () => Promise<void>,
context: TelemetryContext,
): Promise<void> {
const range = await promptDateRange();
if (!range) return;
const format = await promptFormat();
if (!format) return;
const outputUri = await promptSavePath(range, format.id);
if (!outputUri) return;
const onCleanupError = (err: unknown, target: string) =>
logger.warn("Failed to delete telemetry export temp file", target, err);
const onStagingCleanupError = (err: unknown, target: string) =>
logger.warn(
"Failed to delete telemetry export staging directory",
target,
err,
);
// Flush + list run inside the progress callback so the on-disk snapshot
// is taken right before streaming and the user can cancel a long flush.
const result = await withCancellableProgress(
async ({ signal, progress }): Promise<ExportSummary> => {
progress.report({ message: "Flushing buffered events..." });
await flushTelemetry();
throwIfAborted(signal);
progress.report({ message: "Locating telemetry files..." });
const filePaths = await listTelemetryFilesForRange(telemetryDir, range);
if (filePaths.length === 0) {
return { filesScanned: 0, eventCount: 0 };
}
progress.report({ message: "Writing export..." });
const events = (async function* () {
for await (const event of streamTelemetryEvents(filePaths, range)) {
throwIfAborted(signal);
yield event;
}
})();
let eventCount: number;
if (format.id === "json") {
eventCount = await writeJsonArrayExport(
outputUri.fsPath,
events,
onCleanupError,
);
} else {
const counts = await writeOtlpZipExport(
outputUri.fsPath,
events,
context,
{
signal,
onTempCleanupError: onCleanupError,
onStagingCleanupError,
},
);
eventCount = counts.logs + counts.traces + counts.metrics;
}
return { filesScanned: filePaths.length, eventCount };
},
{
location: vscode.ProgressLocation.Notification,
title: "Exporting Coder telemetry",
cancellable: true,
},
);
if (!result.ok) {
if (result.cancelled) return;
logger.error("Telemetry export failed", result.error);
vscode.window.showErrorMessage(
`Telemetry export failed: ${toError(result.error).message}`,
);
return;
}
const { filesScanned, eventCount } = result.value;
if (filesScanned === 0) {
vscode.window.showInformationMessage(
`No telemetry files found for ${range.label}.`,
);
return;
}
if (eventCount === 0) {
await notifyNoEventsMatched(range, outputUri, logger);
return;
}
await notifyExportSuccess(outputUri, eventCount, logger);
}
async function notifyExportSuccess(
outputUri: vscode.Uri,
eventCount: number,
logger: Logger,
): Promise<void> {
const action = await vscode.window.showInformationMessage(
`Exported ${eventCount} telemetry event(s) to ${outputUri.fsPath}.`,
"Reveal in File Explorer",
);
if (action !== "Reveal in File Explorer") return;
try {
await vscode.commands.executeCommand("revealFileInOS", outputUri);
} catch (err) {
logger.warn("Failed to reveal exported telemetry file", err);
}
}
async function notifyNoEventsMatched(
range: TelemetryDateRange,
outputUri: vscode.Uri,
logger: Logger,
): Promise<void> {
// Remove the empty file the writer just created so the user isn't left
// with an unwanted artifact.
await fs
.rm(outputUri.fsPath, { force: true })
.catch((err) =>
logger.warn(
"Failed to remove empty telemetry export",
outputUri.fsPath,
err,
),
);
vscode.window.showInformationMessage(
`No telemetry events matched ${range.label}.`,
);
}
async function promptDateRange(): Promise<TelemetryDateRange | undefined> {
const pick = await vscode.window.showQuickPick(
[...TELEMETRY_RANGE_PRESETS, CUSTOM_RANGE_PICK],
{
title: "Export Telemetry: Date Range",
placeHolder: "Select telemetry date range",
ignoreFocusOut: true,
},
);
if (!pick) return undefined;
if (pick.id === "custom") return promptCustomDateRange();
return createPresetDateRange(pick.id);
}
async function promptCustomDateRange(): Promise<
TelemetryDateRange | undefined
> {
const todayUtc = toUtcDateString(new Date());
const startDate = await vscode.window.showInputBox({
title: "Export Telemetry: Custom Start Date",
prompt: `Start date in UTC (YYYY-MM-DD). Today in UTC is ${todayUtc}; your local date may differ.`,
value: todayUtc,
validateInput: validateUtcDateInput,
ignoreFocusOut: true,
});
if (startDate === undefined) return undefined;
const endDate = await vscode.window.showInputBox({
title: "Export Telemetry: Custom End Date",
prompt: `End date in UTC (YYYY-MM-DD, inclusive). Today in UTC is ${todayUtc}.`,
value: startDate,
validateInput: (value) => {
const invalidDate = validateUtcDateInput(value);
if (invalidDate !== undefined) return invalidDate;
// YYYY-MM-DD strings sort lexicographically as calendar dates.
if (value < startDate) {
return "End date must be on or after start date.";
}
return undefined;
},
ignoreFocusOut: true,
});
if (endDate === undefined) return undefined;
return createCustomDateRange(startDate, endDate);
}
function promptFormat(): Thenable<FormatPick | undefined> {
return vscode.window.showQuickPick(FORMAT_PICKS, {
title: "Export Telemetry: Format",
placeHolder: "Select export format",
ignoreFocusOut: true,
});
}
function promptSavePath(
range: TelemetryDateRange,
format: FormatPick["id"],
): Thenable<vscode.Uri | undefined> {
const { ext, filters } = FORMAT_OUTPUT[format];
const defaultName = `coder-telemetry-${range.filenamePart}.${ext}`;
return vscode.window.showSaveDialog({
defaultUri: vscode.Uri.file(path.join(os.homedir(), defaultName)),
filters,
title: "Save Telemetry Export",
});
}