Repository navigation
Expand file tree
/
Copy pathtelemetry.ts
More file actions
336 lines (316 loc) · 10.2 KB
/
Copy pathtelemetry.ts
File metadata and controls
336 lines (316 loc) · 10.2 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
import { AsyncLocalStorage } from "node:async_hooks";
import { randomUUID } from "node:crypto";
import { release } from "node:os";
import type { AppInstall } from "@bb/config/app-install";
import { DEFAULTS } from "@bb/config/defaults";
import type { ServerConfig } from "@bb/config/server";
import { readOrCreateSecretFile } from "@bb/secret-storage";
import type { AppSurface, RequestAppSurface } from "@bb/config/app-surface";
import type { RecordTelemetryEventRequest } from "@bb/server-contract";
import type { ServerLogger } from "../../types.js";
import {
TelemetryOutbox,
type TelemetryPropertyValue,
type TelemetryWireEvent,
} from "./telemetry-outbox.js";
const DEFAULT_FLUSH_INTERVAL_MS = 60_000;
const SEND_TIMEOUT_MS = 10_000;
const SHUTDOWN_FLUSH_TIMEOUT_MS = 3_000;
const MAX_BATCHES_PER_FLUSH = 10;
// v2: the ID kept in `telemetry-id` was sent by releases before 0.50.1
// without `$process_person_profile: false`, so PostHog holds a person profile
// for it and bills every later event from it as an identified event, flag or
// not. A fresh ID has no profile, so its events stay anonymous.
const TELEMETRY_ID_FILE_NAME = "telemetry-id-v2";
export type TelemetryAccessRoute = "connect" | "direct" | "loopback";
const telemetryRequestStorage = new AsyncLocalStorage<{
appSurface: RequestAppSurface;
accessRoute: TelemetryAccessRoute | null;
}>();
export type TelemetryInitiator =
| "user"
| "agent"
| "automation"
| "plugin"
| "system";
export type TelemetryEvent =
| { name: "app_started" }
| { name: "telemetry_disabled" }
| {
name: "plugin_installed";
properties: {
plugin_id: string | null;
provenance: "builtin" | "catalog" | "direct";
marketplace: string | null;
source_kind: "builtin" | "git" | "npm" | "path";
is_fresh_install: boolean;
entry_id: string | null;
};
}
| { name: "plugin_use"; properties: { plugin_id: string } }
| {
name: "recommendation";
properties: {
resource_type: "plugin";
resource_id: string;
recommendation_id: string;
action: "used";
};
}
| RecordTelemetryEventRequest;
/**
* Threads and messages are counted rather than sent one by one: the counts go
* out as one `usage_counts` event per day, provider and initiator.
*/
export interface TelemetryCounter {
name: "thread_created" | "message_sent";
provider: string;
initiator?: TelemetryInitiator;
}
/**
* bb's own telemetry interface. Events and counts are batched and sent to the
* bb telemetry endpoint (`BB_TELEMETRY_URL`, a Cloudflare Worker), which
* forwards them to the analytics backend; the backend can change there
* without an app release.
*/
export interface TelemetryService {
capture(event: TelemetryEvent): void;
count(counter: TelemetryCounter): void;
setEnabled(enabled: boolean): void;
isEnabled(): boolean;
/** Sends queued events and the counts of finished days. */
flush(): Promise<void>;
/** Sends everything, today's counts included, and stops the timer. */
stop(): Promise<void>;
}
interface CreateTelemetryServiceArgs {
url: string;
appInstall: AppInstall | null;
appSurface: AppSurface;
appVersion: string;
dataDir: string;
enabled: boolean;
telemetryEnabled: boolean;
logger: ServerLogger;
fetch?: typeof fetch;
now?: () => Date;
flushIntervalMs?: number;
}
const noopTelemetryService: TelemetryService = {
isEnabled: () => false,
capture: () => {},
count: () => {},
setEnabled: () => {},
flush: async () => {},
stop: async () => {},
};
export function createNoopTelemetryService(): TelemetryService {
return noopTelemetryService;
}
export function appInstallFromServerConfig(
config: Pick<
ServerConfig,
"BB_APP_INSTALL_KIND" | "BB_APP_SOURCE_COMMIT" | "BB_APP_SOURCE_ORIGIN"
>,
): AppInstall | null {
switch (config.BB_APP_INSTALL_KIND) {
case undefined:
return null;
case "desktop":
case "npm":
return { kind: config.BB_APP_INSTALL_KIND };
case "source":
if (
config.BB_APP_SOURCE_ORIGIN === "official" &&
config.BB_APP_SOURCE_COMMIT !== undefined
) {
return {
commit: config.BB_APP_SOURCE_COMMIT,
kind: "source",
origin: "official",
};
}
return {
kind: "source",
origin: config.BB_APP_SOURCE_ORIGIN === "fork" ? "fork" : "none",
};
}
}
function appInstallProperties(install: AppInstall | null) {
if (install === null) return { install_kind: "unmanaged" };
if (install.kind !== "source") return { install_kind: install.kind };
return { install_kind: "source", source_origin: install.origin };
}
export function runWithTelemetryRequest<T>(
request: {
appSurface: RequestAppSurface;
accessRoute: TelemetryAccessRoute | null;
},
callback: () => T,
): T {
return telemetryRequestStorage.run(request, callback);
}
function utcDay(date: Date): string {
return date.toISOString().slice(0, 10);
}
export async function createTelemetryService(
args: CreateTelemetryServiceArgs,
): Promise<TelemetryService> {
if (
!args.enabled ||
args.url.length === 0 ||
args.appVersion === DEFAULTS.appVersion
) {
return noopTelemetryService;
}
const distinctId = await readOrCreateSecretFile({
bytes: 16,
dataDir: args.dataDir,
encoding: "hex",
fileName: TELEMETRY_ID_FILE_NAME,
});
const fetchImpl = args.fetch ?? fetch;
const now = args.now ?? (() => new Date());
const outbox = await TelemetryOutbox.load(args.dataDir);
let telemetryEnabled = args.telemetryEnabled;
if (!telemetryEnabled) {
outbox.clear();
}
const osRelease = release();
const commonProperties = {
...appInstallProperties(args.appInstall),
app_version: args.appVersion,
arch: process.arch,
is_wsl:
process.platform === "linux" &&
osRelease.toLowerCase().includes("microsoft"),
node_version: process.version,
os_release: osRelease,
platform: process.platform,
};
// "sent" also covers a batch the endpoint rejected for good (400, 413),
// which would otherwise block the outbox forever.
async function send(events: TelemetryWireEvent[]): Promise<"sent" | "retry"> {
try {
const response = await fetchImpl(args.url, {
body: JSON.stringify({
v: 1,
install_id: distinctId,
common: commonProperties,
events,
}),
headers: { "content-type": "application/json" },
method: "POST",
signal: AbortSignal.timeout(SEND_TIMEOUT_MS),
});
if (response.ok) return "sent";
args.logger.debug(
{ status: response.status, events: events.length },
"Telemetry batch rejected",
);
// 404 means the endpoint is missing (not deployed yet, or moved), not
// that the batch is bad, so it is kept like a server error.
const retryable = [404, 408, 429];
return response.status >= 400 &&
response.status < 500 &&
!retryable.includes(response.status)
? "sent"
: "retry";
} catch (error) {
args.logger.debug(
{ err: error, events: events.length },
"Telemetry batch send failed",
);
return "retry";
}
}
// Flushes run one at a time so a batch is never sent twice concurrently.
let chain: Promise<void> = Promise.resolve();
function serialize(task: () => Promise<void>): Promise<void> {
const run = chain.then(task).catch((error: unknown) => {
args.logger.debug({ err: error }, "Telemetry flush failed");
});
chain = run;
return run;
}
async function drain(includeToday: boolean): Promise<void> {
for (let index = 0; index < MAX_BATCHES_PER_FLUSH; index += 1) {
const batch = outbox.takeBatch(includeToday ? null : utcDay(now()));
if (batch === null) break;
// On disk before it leaves, so a crash mid-send resends the same ids.
await outbox.persist();
if ((await send(batch)) === "retry") break;
outbox.settleInflight();
}
await outbox.persist();
}
const timer = setInterval(() => {
if (telemetryEnabled) void serialize(() => drain(false));
}, args.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS);
timer.unref();
return {
isEnabled: () => telemetryEnabled,
setEnabled(enabled: boolean): void {
const wasEnabled = telemetryEnabled;
telemetryEnabled = enabled;
if (wasEnabled && !enabled) {
// Send what was recorded while enabled (including
// telemetry_disabled), then keep nothing.
void serialize(async () => {
await drain(true);
outbox.clear();
await outbox.persist();
});
}
},
capture(event: TelemetryEvent): void {
if (!telemetryEnabled) return;
const request = telemetryRequestStorage.getStore();
// Every event's properties are flat strings, numbers and booleans.
const eventProperties = (
"properties" in event ? { ...event.properties } : {}
) as Record<string, TelemetryPropertyValue>;
outbox.enqueue({
id: randomUUID(),
name: event.name,
timestamp: now().toISOString(),
properties: {
...eventProperties,
app_surface: request?.appSurface ?? args.appSurface,
...(request?.accessRoute
? { access_route: request.accessRoute }
: {}),
},
});
},
count(counter: TelemetryCounter): void {
if (!telemetryEnabled) return;
outbox.count({
day: utcDay(now()),
provider: counter.provider,
initiator: counter.initiator ?? null,
field:
counter.name === "thread_created"
? "threads_created"
: "messages_sent",
});
},
flush(): Promise<void> {
if (!telemetryEnabled) return Promise.resolve();
return serialize(() => drain(false));
},
async stop(): Promise<void> {
clearInterval(timer);
if (!telemetryEnabled) return;
const flushed = serialize(() => drain(true));
await Promise.race([
flushed,
new Promise<void>((resolve) => {
setTimeout(resolve, SHUTDOWN_FLUSH_TIMEOUT_MS).unref();
}),
]);
// Whatever did not go out stays on disk for the next start.
await outbox.persist().catch(() => undefined);
},
};
}