Skip to content

Commit fa92af9

Browse files
authored
chore(logging): provide driver version for every connection MONGOSH-1000 (#1113)
TS requested that we provide a driver version for connection attempts from the embedded shell in Compass. This moves the driver version reporting to the service-provider-server package, which is a more natural place for it anyway.
1 parent 4fd7004 commit fa92af9

File tree

7 files changed

+48
-25
lines changed

7 files changed

+48
-25
lines changed

packages/cli-repl/src/cli-repl.ts

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -363,9 +363,7 @@ class CliRepl {
363363
if (!this.cliOptions.nodb && !this.cliOptions.quiet) {
364364
this.output.write(i18n.__(CONNECTING) + '\t\t' + this.clr(redactURICredentials(driverUri), ['bold', 'green']) + '\n');
365365
}
366-
const provider = await CliServiceProvider.connect(driverUri, driverOptions, this.cliOptions, this.bus);
367-
this.bus.emit('mongosh:driver-initialized', provider.driverMetadata);
368-
return provider;
366+
return await CliServiceProvider.connect(driverUri, driverOptions, this.cliOptions, this.bus);
369367
}
370368

371369
/** Return the file path used for the REPL history. */

packages/cli-repl/test/e2e.spec.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -871,11 +871,11 @@ describe('e2e', function() {
871871
});
872872

873873
it('includes information about the driver version', async() => {
874-
await eventually(async() => {
875-
const log = await readLogfile();
876-
expect(log.filter(logEntry => /Driver initialized/.test(logEntry.msg)))
877-
.to.have.lengthOf(1);
878-
});
874+
const connectionString = await testServer.connectionString();
875+
expect(await shell.executeLine(`connect(${JSON.stringify(connectionString)})`)).to.include('test');
876+
const log = await readLogfile();
877+
expect(log.filter(logEntry => typeof logEntry.attr?.driver?.version === 'string'))
878+
.to.have.lengthOf(1);
879879
});
880880
});
881881

packages/logging/src/setup-logger-and-telemetry.spec.ts

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,6 @@ describe('setupLoggerAndTelemetry', () => {
5757
bus.emit('mongosh:api-call', { method: 'auth', class: 'Database', db: 'test-1603986682000', arguments: { } });
5858
bus.emit('mongosh:api-call', { method: 'redactable', arguments: { filter: { email: '[email protected]' } } });
5959
bus.emit('mongosh:evaluate-input', { input: '1+1' });
60-
bus.emit('mongosh:driver-initialized', { driver: { name: 'nodejs', version: '3.6.1' } });
6160

6261
const circular: any = {};
6362
circular.circular = circular;
@@ -87,6 +86,12 @@ describe('setupLoggerAndTelemetry', () => {
8786
bus.emit('mongosh-snippets:snippet-command', { args: ['install', 'foo'] });
8887
bus.emit('mongosh-snippets:transform-error', { error: 'failed', addition: 'oh no', name: 'foo' });
8988

89+
const connAttemptData = {
90+
driver: { name: 'nodejs', version: '3.6.1' },
91+
serviceProviderVersion: '1.0.0',
92+
host: 'localhost'
93+
};
94+
bus.emit('mongosh-sp:connect-attempt-initialized', connAttemptData);
9095
bus.emit('mongosh-sp:connect-heartbeat-failure', { connectionId: 'localhost', failure: new Error('cause'), isFailFast: true, isKnownServer: true });
9196
bus.emit('mongosh-sp:connect-heartbeat-succeeded', { connectionId: 'localhost' });
9297
bus.emit('mongosh-sp:connect-fail-early');
@@ -128,8 +133,6 @@ describe('setupLoggerAndTelemetry', () => {
128133
expect(logOutput[i++].attr.arguments.filter.email).to.equal('<email>');
129134
expect(logOutput[i].msg).to.equal('Evaluating input');
130135
expect(logOutput[i++].attr.input).to.equal('1+1');
131-
expect(logOutput[i].msg).to.equal('Driver initialized');
132-
expect(logOutput[i++].attr.driver.version).to.equal('3.6.1');
133136
expect(logOutput[i].msg).to.equal('Performed API call');
134137
expect(logOutput[i++].attr._inspected).to.match(/circular/);
135138
expect(logOutput[i++].msg).to.equal('Start loading CLI scripts');
@@ -169,6 +172,8 @@ describe('setupLoggerAndTelemetry', () => {
169172
expect(logOutput[i++].attr).to.deep.equal({ args: ['install', 'foo'] });
170173
expect(logOutput[i].msg).to.equal('Rewrote error message');
171174
expect(logOutput[i++].attr).to.deep.equal({ error: 'failed', addition: 'oh no', name: 'foo' });
175+
expect(logOutput[i].msg).to.equal('Initiating connection attempt');
176+
expect(logOutput[i++].attr).to.deep.equal(connAttemptData);
172177
expect(logOutput[i].msg).to.equal('Server heartbeat failure');
173178
expect(logOutput[i++].attr).to.deep.equal({ connectionId: 'localhost', failure: 'cause', isFailFast: true, isKnownServer: true });
174179
expect(logOutput[i].msg).to.equal('Server heartbeat succeeded');

packages/logging/src/setup-logger-and-telemetry.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import type {
2525
SnippetsNpmLookupEvent,
2626
SnippetsRunNpmEvent,
2727
SnippetsTransformErrorEvent,
28+
SpConnectAttemptInitializedEvent,
2829
SpConnectHeartbeatFailureEvent,
2930
SpConnectHeartbeatSucceededEvent,
3031
SpResolveSrvErrorEvent,
@@ -125,10 +126,6 @@ export function setupLoggerAndTelemetry(
125126
}
126127
});
127128

128-
bus.on('mongosh:driver-initialized', function(driverMetadata: any) {
129-
log.info('MONGOSH', mongoLogId(1_000_000_004), 'connect', 'Driver initialized', driverMetadata);
130-
});
131-
132129
bus.on('mongosh:new-user', function(id: string, enableTelemetry: boolean) {
133130
userId = id;
134131
telemetry = enableTelemetry;
@@ -373,6 +370,10 @@ export function setupLoggerAndTelemetry(
373370
deprecatedApiCalls.clear();
374371
});
375372

373+
bus.on('mongosh-sp:connect-attempt-initialized', function(ev: SpConnectAttemptInitializedEvent) {
374+
log.info('MONGOSH-SP', mongoLogId(1_000_000_042), 'connect', 'Initiating connection attempt', ev);
375+
});
376+
376377
bus.on('mongosh-sp:connect-heartbeat-failure', function(ev: SpConnectHeartbeatFailureEvent) {
377378
log.warn('MONGOSH-SP', mongoLogId(1_000_000_034), 'connect', 'Server heartbeat failure', {
378379
...ev,

packages/service-provider-server/src/cli-service-provider.spec.ts

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,12 @@ describe('CliServiceProvider', () => {
4747
db() {}
4848
close() {}
4949
topology: any;
50+
get options(): any {
51+
return {
52+
metadata: { driver: { name: 'nodejs', version: '3.6.1' } },
53+
hosts: ['localhost']
54+
};
55+
}
5056
}
5157

5258
it('connects once when no AutoEncryption set', async() => {
@@ -850,7 +856,8 @@ describe('CliServiceProvider', () => {
850856
const info = await serviceProvider.getConnectionInfo();
851857
expect(info.extraInfo.is_atlas).to.equal(false);
852858
expect(info.extraInfo.is_localhost).to.equal(true);
853-
expect(dbStub.command).to.have.callCount(4);
859+
expect(info.extraInfo.fcv).to.equal(undefined);
860+
expect(dbStub.command).to.have.callCount(5);
854861
});
855862
});
856863
});

packages/service-provider-server/src/cli-service-provider.ts

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ type ConnectionInfo = {
118118
topology: any;
119119
extraInfo: ExtraConnectionInfo;
120120
};
121-
type ExtraConnectionInfo = ReturnType<typeof getConnectInfo>;
121+
type ExtraConnectionInfo = ReturnType<typeof getConnectInfo> & { fcv?: string };
122122

123123
/**
124124
* Default driver options we always use.
@@ -149,6 +149,11 @@ const DEFAULT_BASE_OPTIONS: OperationOptions = Object.freeze({
149149
async function connectWithFailFast(client: MongoClient, bus: MongoshBus): Promise<void> {
150150
const failedConnections = new Map<string, Error>();
151151
let failEarlyClosePromise: Promise<void> | null = null;
152+
bus.emit('mongosh-sp:connect-attempt-initialized', {
153+
driver: client.options.metadata.driver,
154+
serviceProviderVersion: require('../package.json').version,
155+
host: client.options.srvHost ?? client.options.hosts.join(',')
156+
});
152157

153158
const heartbeatFailureListener = ({ failure, connectionId }: ServerHeartbeatFailedEvent) => {
154159
const topologyDescription: TopologyDescription | undefined = (client as any).topology?.description;
@@ -407,9 +412,10 @@ class CliServiceProvider extends ServiceProviderCore implements ServiceProvider
407412
}
408413
const topology = this.getTopology();
409414
const { version } = require('../package.json');
410-
const [cmdLineOpts = null, atlasVersion = null] = await Promise.all([
415+
const [cmdLineOpts = null, atlasVersion = null, fcv = null] = await Promise.all([
411416
this.runCommandWithCheck('admin', { getCmdLineOpts: 1 }, this.baseCmdOptions).catch(() => {}),
412-
this.runCommandWithCheck('admin', { atlasVersion: 1 }, this.baseCmdOptions).catch(() => {})
417+
this.runCommandWithCheck('admin', { atlasVersion: 1 }, this.baseCmdOptions).catch(() => {}),
418+
this.runCommandWithCheck('admin', { getParameter: 1, featureCompatibilityVersion: 1 }, this.baseCmdOptions).catch(() => {})
413419
]);
414420

415421
const extraConnectionInfo = getConnectInfo(
@@ -424,7 +430,10 @@ class CliServiceProvider extends ServiceProviderCore implements ServiceProvider
424430
return {
425431
buildInfo: buildInfo,
426432
topology: topology,
427-
extraInfo: extraConnectionInfo
433+
extraInfo: {
434+
...extraConnectionInfo,
435+
fcv: fcv?.featureCompatibilityVersion?.version
436+
}
428437
};
429438
}
430439

packages/types/src/index.ts

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,12 @@ export interface SnippetsTransformErrorEvent {
134134
name: string;
135135
}
136136

137+
export interface SpConnectAttemptInitializedEvent {
138+
driver: { name: string, version: string };
139+
serviceProviderVersion: string;
140+
host: string;
141+
}
142+
137143
export interface SpConnectHeartbeatFailureEvent {
138144
connectionId: string;
139145
failure: Error;
@@ -188,11 +194,6 @@ export interface MongoshBusEventsMap {
188194
* or the used database changed.
189195
*/
190196
'mongosh:connect': (ev: ConnectEvent) => void;
191-
/**
192-
* Signals the creation of a new Mongo client with metadata provided
193-
* by the underlying driver implementation.
194-
*/
195-
'mongosh:driver-initialized': (driverMetadata: any) => void;
196197
/**
197198
* Signals that the shell is started by a new user.
198199
*/
@@ -338,6 +339,8 @@ export interface MongoshBusEventsMap {
338339
/** Signals that a snippet has modified an error message. */
339340
'mongosh-snippets:transform-error': (ev: SnippetsTransformErrorEvent) => void;
340341

342+
/** Signals that a connection attempt is about to be performed. */
343+
'mongosh-sp:connect-attempt-initialized': (ev: SpConnectAttemptInitializedEvent) => void;
341344
/** Signals that communicating to a specific server during connection did not succeed. */
342345
'mongosh-sp:connect-heartbeat-failure': (ev: SpConnectHeartbeatFailureEvent) => void;
343346
/** Signals that communicating to a specific server during connection succeeded. */

0 commit comments

Comments
 (0)