Skip to content

Commit 6c714b3

Browse files
committed
fix: add telemetry
1 parent 4fd4a6f commit 6c714b3

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

src/telemetry/telemetry.ts

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,10 @@ import { MACHINE_METADATA } from "./constants.js";
77
import { EventCache } from "./eventCache.js";
88
import nodeMachineId from "node-machine-id";
99
import { getDeviceId } from "@mongodb-js/device-id";
10+
import fs from "fs/promises";
11+
import os from "os";
12+
import path from "path";
13+
import { randomUUID } from "crypto";
1014

1115
type EventResult = {
1216
success: boolean;
@@ -15,6 +19,26 @@ type EventResult = {
1519

1620
export const DEVICE_ID_TIMEOUT = 3000;
1721

22+
async function fileExists(filepath: string): Promise<boolean> {
23+
try {
24+
await fs.stat(filepath);
25+
return true;
26+
} catch {
27+
return false;
28+
}
29+
}
30+
31+
async function isContainerEnv(): Promise<boolean> {
32+
if (await fileExists("/.dockerenv")) {
33+
return true;
34+
}
35+
return process.env.container != "";
36+
}
37+
38+
function containerIdFilePath(): string {
39+
return path.join(os.homedir(), ".mongodb", "container", ".containerId");
40+
}
41+
1842
export class Telemetry {
1943
private isBufferingEvents: boolean = true;
2044
/** Resolves when the device ID is retrieved or timeout occurs */
@@ -74,6 +98,22 @@ export class Telemetry {
7498
abortSignal: this.deviceIdAbortController.signal,
7599
});
76100

101+
const containerEnv = await isContainerEnv();
102+
103+
if (containerEnv) {
104+
const filePath = containerIdFilePath();
105+
const exists = await fileExists(filePath);
106+
let content: string;
107+
if (exists) {
108+
content = await fs.readFile(filePath, "utf8");
109+
} else {
110+
content = randomUUID().toString();
111+
await fs.mkdir(path.dirname(filePath), { recursive: true });
112+
await fs.writeFile(filePath, content, "utf8");
113+
}
114+
this.commonProperties.container_id = content;
115+
}
116+
77117
this.commonProperties.device_id = await this.deviceIdPromise;
78118

79119
this.isBufferingEvents = false;

src/telemetry/types.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,4 +71,5 @@ export type CommonProperties = {
7171
config_atlas_auth?: TelemetryBoolSet;
7272
config_connection_string?: TelemetryBoolSet;
7373
session_id?: string;
74+
container_id?: string;
7475
} & CommonStaticProperties;

0 commit comments

Comments
 (0)