Skip to content

chore: defer machine ID resolution #161

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 19 commits into from
May 1, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@
"mongodb-log-writer": "^2.4.1",
"mongodb-redact": "^1.1.6",
"mongodb-schema": "^12.6.2",
"node-machine-id": "^1.1.12",
"node-machine-id": "1.1.12",
"openapi-fetch": "^0.13.5",
"simple-oauth2": "^5.1.0",
"yargs-parser": "^21.1.1",
Expand Down
58 changes: 58 additions & 0 deletions src/deferred-promise.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
type DeferredPromiseOptions<T> = {
timeout?: number;
onTimeout?: (resolve: (value: T) => void, reject: (reason: Error) => void) => void;
};

/** Creates a promise and exposes its resolve and reject methods, with an optional timeout. */
export class DeferredPromise<T> extends Promise<T> {
resolve: (value: T) => void;
reject: (reason: unknown) => void;
private timeoutId?: NodeJS.Timeout;

constructor(
executor: (resolve: (value: T) => void, reject: (reason: Error) => void) => void,
{ timeout, onTimeout }: DeferredPromiseOptions<T> = {}
) {
let resolveFn: (value: T) => void;
let rejectFn: (reason?: unknown) => void;

super((resolve, reject) => {
resolveFn = resolve;
rejectFn = reject;
});

// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
this.resolve = resolveFn!;
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
this.reject = rejectFn!;

if (timeout !== undefined && onTimeout) {
this.timeoutId = setTimeout(() => {
onTimeout(this.resolve, this.reject);
}, timeout);
}

executor(
(value: T) => {
if (this.timeoutId) clearTimeout(this.timeoutId);
this.resolve(value);
},
(reason: Error) => {
if (this.timeoutId) clearTimeout(this.timeoutId);
this.reject(reason);
}
);
}

static fromPromise<T>(promise: Promise<T>, options: DeferredPromiseOptions<T> = {}): DeferredPromise<T> {
return new DeferredPromise<T>((resolve, reject) => {
promise
.then((value) => {
resolve(value);
})
.catch((reason) => {
reject(reason as Error);
});
}, options);
}
}
4 changes: 4 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { config } from "./config.js";
import { Session } from "./session.js";
import { Server } from "./server.js";
import { packageInfo } from "./packageInfo.js";
import { Telemetry } from "./telemetry/telemetry.js";

try {
const session = new Session({
Expand All @@ -19,9 +20,12 @@ try {
version: packageInfo.version,
});

const telemetry = Telemetry.create(session, config);

const server = new Server({
mcpServer,
session,
telemetry,
userConfig: config,
});

Expand Down
1 change: 1 addition & 0 deletions src/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export const LogId = {
telemetryEmitSuccess: mongoLogId(1_002_004),
telemetryMetadataError: mongoLogId(1_002_005),
telemetryDeviceIdFailure: mongoLogId(1_002_006),
telemetryDeviceIdTimeout: mongoLogId(1_002_007),

toolExecute: mongoLogId(1_003_001),
toolExecuteFailure: mongoLogId(1_003_002),
Expand Down
6 changes: 4 additions & 2 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export interface ServerOptions {
session: Session;
userConfig: UserConfig;
mcpServer: McpServer;
telemetry: Telemetry;
}

export class Server {
Expand All @@ -25,10 +26,10 @@ export class Server {
public readonly userConfig: UserConfig;
private readonly startTime: number;

constructor({ session, mcpServer, userConfig }: ServerOptions) {
constructor({ session, mcpServer, userConfig, telemetry }: ServerOptions) {
this.startTime = Date.now();
this.session = session;
this.telemetry = new Telemetry(session, userConfig);
this.telemetry = telemetry;
this.mcpServer = mcpServer;
this.userConfig = userConfig;
}
Expand Down Expand Up @@ -93,6 +94,7 @@ export class Server {
}

async close(): Promise<void> {
await this.telemetry.close();
await this.session.close();
await this.mcpServer.close();
}
Expand Down
3 changes: 1 addition & 2 deletions src/telemetry/constants.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import { packageInfo } from "../packageInfo.js";
import { type CommonStaticProperties } from "./types.js";
import { getDeviceId } from "./device-id.js";

/**
* Machine-specific metadata formatted for telemetry
*/
export const MACHINE_METADATA: CommonStaticProperties = {
device_id: getDeviceId(),
mcp_server_version: packageInfo.version,
mcp_server_name: packageInfo.mcpServerName,
platform: process.platform,
Expand Down
21 changes: 0 additions & 21 deletions src/telemetry/device-id.ts

This file was deleted.

2 changes: 1 addition & 1 deletion src/telemetry/eventCache.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { BaseEvent } from "./types.js";
import { LRUCache } from "lru-cache";
import { BaseEvent } from "./types.js";

/**
* Singleton class for in-memory telemetry event caching
Expand Down
95 changes: 89 additions & 6 deletions src/telemetry/telemetry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,101 @@ import logger, { LogId } from "../logger.js";
import { ApiClient } from "../common/atlas/apiClient.js";
import { MACHINE_METADATA } from "./constants.js";
import { EventCache } from "./eventCache.js";
import { createHmac } from "crypto";
import nodeMachineId from "node-machine-id";
import { DeferredPromise } from "../deferred-promise.js";

type EventResult = {
success: boolean;
error?: Error;
};

export const DEVICE_ID_TIMEOUT = 3000;

export class Telemetry {
private readonly commonProperties: CommonProperties;
private isBufferingEvents: boolean = true;
/** Resolves when the device ID is retrieved or timeout occurs */
public deviceIdPromise: DeferredPromise<string> | undefined;
private eventCache: EventCache;
private getRawMachineId: () => Promise<string>;

constructor(
private constructor(
private readonly session: Session,
private readonly userConfig: UserConfig,
private readonly eventCache: EventCache = EventCache.getInstance()
private readonly commonProperties: CommonProperties,
{ eventCache, getRawMachineId }: { eventCache: EventCache; getRawMachineId: () => Promise<string> }
) {
this.commonProperties = {
...MACHINE_METADATA,
};
this.eventCache = eventCache;
this.getRawMachineId = getRawMachineId;
}

static create(
Copy link
Collaborator Author

@gagik gagik Apr 29, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

while this is not asyncronous. I'm using create(...) to make it clear there are associated side effects

session: Session,
userConfig: UserConfig,
{
commonProperties = { ...MACHINE_METADATA },
eventCache = EventCache.getInstance(),

// eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
getRawMachineId = () => nodeMachineId.machineId(true),
}: {
eventCache?: EventCache;
getRawMachineId?: () => Promise<string>;
commonProperties?: CommonProperties;
} = {}
): Telemetry {
const instance = new Telemetry(session, userConfig, commonProperties, { eventCache, getRawMachineId });

void instance.start();
return instance;
}

private async start(): Promise<void> {
if (!this.isTelemetryEnabled()) {
return;
}
this.deviceIdPromise = DeferredPromise.fromPromise(this.getDeviceId(), {
timeout: DEVICE_ID_TIMEOUT,
onTimeout: (resolve) => {
resolve("unknown");
logger.debug(LogId.telemetryDeviceIdTimeout, "telemetry", "Device ID retrieval timed out");
},
});
this.commonProperties.device_id = await this.deviceIdPromise;

this.isBufferingEvents = false;
}

public async close(): Promise<void> {
this.deviceIdPromise?.resolve("unknown");
this.isBufferingEvents = false;
await this.emitEvents(this.eventCache.getEvents());
}

/**
* @returns A hashed, unique identifier for the running device or `"unknown"` if not known.
*/
private async getDeviceId(): Promise<string> {
try {
if (this.commonProperties.device_id) {
return this.commonProperties.device_id;
}

const originalId: string = await this.getRawMachineId();

// Create a hashed format from the all uppercase version of the machine ID
// to match it exactly with the denisbrodbeck/machineid library that Atlas CLI uses.
const hmac = createHmac("sha256", originalId.toUpperCase());

/** This matches the message used to create the hashes in Atlas CLI */
const DEVICE_ID_HASH_MESSAGE = "atlascli";

hmac.update(DEVICE_ID_HASH_MESSAGE);
return hmac.digest("hex");
} catch (error) {
logger.debug(LogId.telemetryDeviceIdFailure, "telemetry", String(error));
return "unknown";
}
}

/**
Expand Down Expand Up @@ -78,6 +156,11 @@ export class Telemetry {
* Falls back to caching if both attempts fail
*/
private async emit(events: BaseEvent[]): Promise<void> {
if (this.isBufferingEvents) {
this.eventCache.appendEvents(events);
return;
}

const cachedEvents = this.eventCache.getEvents();
const allEvents = [...cachedEvents, ...events];

Expand Down
1 change: 0 additions & 1 deletion src/telemetry/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@ export type ServerEvent = TelemetryEvent<ServerEventProperties>;
* Interface for static properties, they can be fetched once and reused.
*/
export type CommonStaticProperties = {
device_id?: string;
mcp_server_version: string;
mcp_server_name: string;
platform: string;
Expand Down
6 changes: 6 additions & 0 deletions tests/integration/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { UserConfig } from "../../src/config.js";
import { McpError } from "@modelcontextprotocol/sdk/types.js";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { Session } from "../../src/session.js";
import { Telemetry } from "../../src/telemetry/telemetry.js";
import { config } from "../../src/config.js";

interface ParameterInfo {
Expand Down Expand Up @@ -56,9 +57,14 @@ export function setupIntegrationTest(getUserConfig: () => UserConfig): Integrati
apiClientSecret: userConfig.apiClientSecret,
});

userConfig.telemetry = "disabled";

const telemetry = Telemetry.create(session, userConfig);

mcpServer = new Server({
session,
userConfig,
telemetry,
mcpServer: new McpServer({
name: "test-server",
version: "5.2.3",
Expand Down
29 changes: 29 additions & 0 deletions tests/integration/telemetry.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { createHmac } from "crypto";
import { Telemetry } from "../../src/telemetry/telemetry.js";
import { Session } from "../../src/session.js";
import { config } from "../../src/config.js";
import nodeMachineId from "node-machine-id";

describe("Telemetry", () => {
it("should resolve the actual machine ID", async () => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
const actualId: string = await nodeMachineId.machineId(true);

const actualHashedId = createHmac("sha256", actualId.toUpperCase()).update("atlascli").digest("hex");

const telemetry = Telemetry.create(
new Session({
apiBaseUrl: "",
}),
config
);

expect(telemetry.getCommonProperties().device_id).toBe(undefined);
expect(telemetry["isBufferingEvents"]).toBe(true);

await telemetry.deviceIdPromise;

expect(telemetry.getCommonProperties().device_id).toBe(actualHashedId);
expect(telemetry["isBufferingEvents"]).toBe(false);
});
});
2 changes: 0 additions & 2 deletions tests/integration/tools/mongodb/mongodbHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,6 @@ export function setupMongoDBIntegrationTest(): MongoDBIntegrationTest {
let dbsDir = path.join(tmpDir, "mongodb-runner", "dbs");
for (let i = 0; i < 10; i++) {
try {
// TODO: Fix this type once mongodb-runner is updated.
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

drive-by

mongoCluster = await MongoCluster.start({
tmpDir: dbsDir,
logDir: path.join(tmpDir, "mongodb-runner", "logs"),
Expand Down
Loading
Loading