-
Notifications
You must be signed in to change notification settings - Fork 96
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
Changes from 14 commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
80e71af
fix
gagik 9022a61
fix: use non-native dependency and defer machine ID resolution
gagik 2dfb0a1
fix: always handle process rejections
gagik ab2909e
fix: close telemetry
gagik 79c8d16
fix: remove UUID check
gagik cbb905c
fix: resolve instead of reject in case of timeout
gagik 9be3e12
fix: remove ESLint warnings
gagik 5348a3a
fix: use npm with inspect
gagik c869d63
fix: remove jest types
gagik e0339a4
fix: use proper ESM with jest
gagik 80bc86e
Merge branch 'gagik/esm-jest' of github.com:mongodb-js/mongodb-mcp-se…
gagik 189e97d
wip
gagik 8575d9a
fix: adjust mocks to fit ESM
gagik 9d49948
Merge branch 'main' of github.com:mongodb-js/mongodb-mcp-server into …
gagik 5d981ee
fix: changes from feedback
gagik 89c3568
Merge branch 'main' of github.com:mongodb-js/mongodb-mcp-server into …
gagik bc57a97
fix: remove old implementation
gagik 8816bef
fix: remove assertions
gagik c611836
Merge branch 'main' into gagik/use-machine-id
gagik File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
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) { | ||
this.timeoutId = setTimeout(() => { | ||
onTimeout?.(this.resolve, this.reject); | ||
gagik marked this conversation as resolved.
Show resolved
Hide resolved
|
||
}, timeout); | ||
} | ||
|
||
if (executor) { | ||
gagik marked this conversation as resolved.
Show resolved
Hide resolved
|
||
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); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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( | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. while this is not asyncronous. I'm using |
||
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 `undefined` if not known. | ||
gagik marked this conversation as resolved.
Show resolved
Hide resolved
|
||
*/ | ||
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"; | ||
} | ||
} | ||
|
||
/** | ||
|
@@ -48,6 +126,7 @@ export class Telemetry { | |
public getCommonProperties(): CommonProperties { | ||
return { | ||
...this.commonProperties, | ||
device_id: this.commonProperties.device_id, | ||
gagik marked this conversation as resolved.
Show resolved
Hide resolved
|
||
mcp_client_version: this.session.agentRunner?.version, | ||
mcp_client_name: this.session.agentRunner?.name, | ||
session_id: this.session.sessionId, | ||
|
@@ -78,6 +157,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]; | ||
|
||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do we need the assertions here?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
yeah, this is more of a late intialization assertion. typescript isn't smart enough to understand they're being set in the constructor
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Not sure why though - when testing locally, I don't see it complaining when I remove the assertions - in what situations are you seeing errors?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
okay I'm realizing now the assertions were leftover from an older implementation that had a different structure; removed them now. as we assert them later on instead.