Skip to content

chore: switch to @mongodb-js/device-id #2446

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 11 commits into from
Jun 2, 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
8 changes: 8 additions & 0 deletions package-lock.json

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

2 changes: 2 additions & 0 deletions packages/logging/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"node": ">=14.15.1"
},
"dependencies": {
"@mongodb-js/device-id": "^0.2.1",
"@mongodb-js/devtools-connect": "^3.4.1",
"@mongosh/errors": "2.4.0",
"@mongosh/history": "2.4.6",
Expand All @@ -29,6 +30,7 @@
"@mongodb-js/eslint-config-mongosh": "^1.0.0",
"@mongodb-js/prettier-config-devtools": "^1.0.1",
"@mongodb-js/tsconfig-mongosh": "^1.0.0",
"@segment/analytics-node": "^1.3.0",
"depcheck": "^1.4.7",
"eslint": "^7.25.0",
"prettier": "^2.8.8",
Expand Down
62 changes: 51 additions & 11 deletions packages/logging/src/logging-and-telemetry.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@ import type { Writable } from 'stream';
import type { MongoshLoggingAndTelemetry } from '.';
import { setupLoggingAndTelemetry } from '.';
import type { LoggingAndTelemetry } from './logging-and-telemetry';
import { getDeviceId } from './logging-and-telemetry';
import sinon from 'sinon';
import type { MongoshLoggingAndTelemetryArguments } from './types';
import { getDeviceId } from '@mongodb-js/device-id';
import { getMachineId } from 'native-machine-id';

describe('MongoshLoggingAndTelemetry', function () {
let logOutput: any[];
Expand Down Expand Up @@ -253,6 +254,7 @@ describe('MongoshLoggingAndTelemetry', function () {
});

it('automatically sets up device ID for telemetry', async function () {
const abortController = new AbortController();
const loggingAndTelemetry = setupLoggingAndTelemetry({
...testLoggingArguments,
bus,
Expand All @@ -263,7 +265,10 @@ describe('MongoshLoggingAndTelemetry', function () {

bus.emit('mongosh:new-user', { userId, anonymousId: userId });

const deviceId = await getDeviceId();
const deviceId = await getDeviceId({
getMachineId: () => getMachineId({ raw: true }),
abortSignal: abortController.signal,
});

await (loggingAndTelemetry as LoggingAndTelemetry).setupTelemetryPromise;

Expand All @@ -283,6 +288,50 @@ describe('MongoshLoggingAndTelemetry', function () {
]);
});

it('resolves device ID setup when flushed', async function () {
const loggingAndTelemetry = setupLoggingAndTelemetry({
...testLoggingArguments,
bus,
deviceId: undefined,
});
sinon
// eslint-disable-next-line @typescript-eslint/no-var-requires
.stub(require('native-machine-id'), 'getMachineId')
.resolves(
new Promise((resolve) => setTimeout(resolve, 10_000).unref())
);

loggingAndTelemetry.attachLogger(logger);

// Start the device ID setup
const setupPromise = (loggingAndTelemetry as LoggingAndTelemetry)
.setupTelemetryPromise;

// Flush before it completes
loggingAndTelemetry.flush();

// Emit an event that would trigger analytics
bus.emit('mongosh:new-user', { userId, anonymousId: userId });

await setupPromise;

// Should still identify but with unknown device ID
expect(analyticsOutput).deep.equal([
[
'identify',
{
anonymousId: userId,
traits: {
device_id: 'unknown',
platform: process.platform,
arch: process.arch,
session_id: logId,
},
},
],
]);
});

it('only delays analytic outputs, not logging', async function () {
// eslint-disable-next-line @typescript-eslint/no-empty-function
let resolveTelemetry: (value: unknown) => void = () => {};
Expand Down Expand Up @@ -1184,13 +1233,4 @@ describe('MongoshLoggingAndTelemetry', function () {
],
]);
});

describe('getDeviceId()', function () {
it('is consistent on the same machine', async function () {
const idA = await getDeviceId();
const idB = await getDeviceId();

expect(idA).equals(idB);
});
});
});
75 changes: 25 additions & 50 deletions packages/logging/src/logging-and-telemetry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,40 +53,7 @@ import type {
MongoshLoggingAndTelemetryArguments,
MongoshTrackingProperties,
} from './types';
import { createHmac } from 'crypto';

/**
* @returns A hashed, unique identifier for the running device or `"unknown"` if not known.
*/
export async function getDeviceId({
onError,
}: {
onError?: (error: Error) => void;
} = {}): Promise<string | 'unknown'> {
try {
// 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 originalId: string =
// eslint-disable-next-line @typescript-eslint/no-var-requires
await require('native-machine-id').getMachineId({
raw: true,
});

if (!originalId) {
return 'unknown';
}
const hmac = createHmac('sha256', originalId);

/** 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) {
onError?.(error as Error);
return 'unknown';
}
}
import { getDeviceId } from '@mongodb-js/device-id';

export function setupLoggingAndTelemetry(
props: MongoshLoggingAndTelemetryArguments
Expand Down Expand Up @@ -125,11 +92,11 @@ export class LoggingAndTelemetry implements MongoshLoggingAndTelemetry {
private isBufferingTelemetryEvents = false;

private deviceId: string | undefined;
/** @internal */

/** @internal Used for awaiting the telemetry setup in tests. */
public setupTelemetryPromise: Promise<void> = Promise.resolve();

// eslint-disable-next-line @typescript-eslint/no-empty-function
private resolveDeviceId: (value: string) => void = () => {};
private readonly telemetrySetupAbort: AbortController = new AbortController();

constructor({
bus,
Expand Down Expand Up @@ -160,26 +127,34 @@ export class LoggingAndTelemetry implements MongoshLoggingAndTelemetry {
}

public flush(): void {
// Run any telemetry events even if device ID hasn't been resolved yet
this.runAndClearPendingTelemetryEvents();

// Run any other pending events with the set or dummy log for telemetry purposes.
this.runAndClearPendingBusEvents();

this.resolveDeviceId('unknown');
// Abort setup, which will cause the device ID to be set to 'unknown'
// and run any remaining telemetry events
this.telemetrySetupAbort.abort();
}

private async setupTelemetry(): Promise<void> {
if (!this.deviceId) {
this.deviceId = await Promise.race([
getDeviceId({
onError: (error) =>
this.bus.emit('mongosh:error', error, 'telemetry'),
}),
new Promise<string>((resolve) => {
this.resolveDeviceId = resolve;
}),
]);
try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const getMachineId = require('native-machine-id').getMachineId;
this.deviceId = await getDeviceId({
getMachineId: () => getMachineId({ raw: true }),
onError: (reason, error) => {
if (reason === 'abort') {
return;
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
this.bus.emit('mongosh:error', error, 'telemetry');
},
abortSignal: this.telemetrySetupAbort.signal,
});
} catch (error) {
this.deviceId = 'unknown';
this.bus.emit('mongosh:error', error as Error, 'telemetry');
}
}

this.runAndClearPendingTelemetryEvents();
Expand Down