From a480f74355e08a8f0f224ebf8e73904d63f4d5dd Mon Sep 17 00:00:00 2001 From: Paula Stachova Date: Wed, 26 Jun 2024 13:44:35 +0200 Subject: [PATCH 01/24] start --- packages/compass-telemetry/src/events.ts | 122 ++++++++++++++++++ .../compass-telemetry/src/generic-track.ts | 36 ++++-- packages/compass-telemetry/src/index.ts | 3 +- packages/compass-telemetry/src/ipc-track.ts | 10 +- packages/compass-telemetry/src/provider.tsx | 15 +-- packages/compass-telemetry/src/types.ts | 22 ++++ 6 files changed, 180 insertions(+), 28 deletions(-) create mode 100644 packages/compass-telemetry/src/events.ts create mode 100644 packages/compass-telemetry/src/types.ts diff --git a/packages/compass-telemetry/src/events.ts b/packages/compass-telemetry/src/events.ts new file mode 100644 index 00000000000..3f6b21ccf16 --- /dev/null +++ b/packages/compass-telemetry/src/events.ts @@ -0,0 +1,122 @@ +// TODO: remove +// these lists are here only for the purpose of review +// let me know if any of these are categorized wrong! + +export type ConnectionScopeEvents = [ + | 'Aggregation Canceled' + | 'Aggregation Edited' + | 'Aggregation Executed' + | 'Aggregation Explained' + | 'Aggregation Export Opened' + | 'Aggregation Exported' + | 'Aggregation Opened' + | 'Aggregation Saved' + | 'Aggregation Saved As View' + | 'Aggregation Side Panel Opened' + | 'Aggregation Timed Out' + | 'Aggregation Use Case Added' + | 'Aggregation Use Case Saved' + | 'AI Prompt Submitted' + | 'AI Query Feedback' + | 'AI Response Failed' + | 'AI Response Generated' + | 'Bulk Delete Executed' + | 'Bulk Delete Opened' + | 'Bulk Update Executed' + | 'Bulk Update Favorited' + | 'Bulk Update Opened' + | 'Collection Created' + | 'Connection Attempt' + | 'Connection Failed' + | 'CurrentOp showOperationDetails' + | 'Database Created' + | 'Delete Export Opened' + | 'Delete Exported' + | 'DetailView hideOperationDetails' + | 'DetailView killOp' + | 'Document Cloned' + | 'Document Copied' + | 'Document Deleted' + | 'Document Inserted' + | 'Document Updated' + | 'Editor Type Changed' + | 'Explain Plan Executed' + | 'Export Completed' + | 'Export Opened' + | 'Query Edited' + | 'Query Executed' + | 'Query Export Opened' + | 'Query Exported' + | 'Query History Closed' + | 'Query History Favorite Added' + | 'Query History Favorite Copied' + | 'Query History Favorite Removed' + | 'Query History Favorite Used' + | 'Query History Favorites' + | 'Query History Opened' + | 'Query History Recent' + | 'Query History Recent Used' + | 'Query Results Refreshed' + | 'Import Completed' + | 'Import Error Log Opened' + | 'Import Opened' + | 'Index Create Opened' + | 'Index Created' + | 'Index Dropped' + | 'Index Edited' + | 'My Queries Search' + | 'New Connection' + | 'Performance Advisor Clicked' + | 'Performance Paused' + | 'Performance Resumed' + | 'PipelineAI Feedback' + | 'Schema Analyzed' + | 'Schema Validation Added' + | 'Schema Validation Edited' + | 'Schema Validation Updated' + | 'Shell Opened' + | `Shell ${string}` + | 'Switch View Type' + | 'Update Export Opened' + | 'Update Exported' + | 'View Updated' + // unsure + | 'Focus Mode Closed' + | 'Focus Mode Opened' + | 'Guide Cue Dismissed' + | 'Guide Cue Group Dismissed' +]; + +export type GeneralScopeEvents = [ + | 'Application Launched' + | 'Application Restart Accepted' + | 'Atlas Link Clicked' + | 'Atlas Sign In Error' + | 'Atlas Sign In Success' + | 'Atlas Sign Out' + | 'Autoupdate Accepted' + | 'Autoupdate Disabled' + | 'Autoupdate Dismissed' + | 'Autoupdate Enabled' + | 'My Queries Filter' + | 'My Queries Sort' + | 'Theme Changed' + | 'Error Fetching Attributes' + | 'Aggregation Deleted' + | 'Aggregation Copied' + | 'First Contentful Paint' + | 'Largest Contentful Paint' + | 'First Input Delay' + | 'Cumulative Layout Shift' + | 'Time to First Byte' + // unsure + | 'Screen' // this is a maybe. + | 'Connection Exported' + | 'Connection Imported' + | 'Keytar Secrets Migration Failed' + | 'Signal Action Button Clicked' + | 'Signal Closed' + | 'Signal Link Clicked' + | 'Signal Opened' + | 'Signal Shown' +]; diff --git a/packages/compass-telemetry/src/generic-track.ts b/packages/compass-telemetry/src/generic-track.ts index 104206914e4..4c2fce60e30 100644 --- a/packages/compass-telemetry/src/generic-track.ts +++ b/packages/compass-telemetry/src/generic-track.ts @@ -1,16 +1,17 @@ import { type Logger, mongoLogId } from '@mongodb-js/compass-logging/provider'; - -export type TrackProps = Record | (() => Record); -export type TrackFunction = (event: string, properties?: TrackProps) => void; +import type { TrackFunction, AsyncTrackFunction } from './types'; export interface TelemetryPreferences { getPreferences(): { trackUsageStatistics: boolean }; } +export type TelemetryConnectionInfoHook = () => { id: string }; + export interface TelemetryServiceOptions { - sendTrack: (event: string, properties: Record) => void; + sendTrack: TrackFunction; logger?: Logger; preferences?: TelemetryPreferences; + useConnectionInfo?: TelemetryConnectionInfoHook; } export const createTrack = ({ @@ -18,10 +19,11 @@ export const createTrack = ({ logger: { log, debug }, preferences, }: TelemetryServiceOptions & { logger: Logger }) => { - const trackAsync = async ( - event: string, - properties: TrackProps = {} - ): Promise => { + const trackAsync: AsyncTrackFunction = async ( + event, + parameters, + connectionInfo + ) => { // Note that this preferences check is mainly a performance optimization, // since the main process telemetry code also checks this preference value, // so it is safe to fall back to 'true'. @@ -31,9 +33,9 @@ export const createTrack = ({ return; } - if (typeof properties === 'function') { + if (typeof parameters === 'function') { try { - properties = await properties(); + parameters = await parameters(); } catch (error) { // When an error arises during the fetching of properties, // for instance if we can't fetch host information, @@ -55,10 +57,20 @@ export const createTrack = ({ return; } } - sendTrack(event, properties); + + if (typeof parameters === 'object' && connectionInfo) { + parameters.connection_id = connectionInfo.id; + } + + console.log('TRACK', { + event, + connection_id: (parameters as { connection_id?: string }).connection_id, + }); + + sendTrack(event, parameters || {}); }; - const track = (...args: [string, TrackProps?]) => { + const track: TrackFunction = (...args) => { void Promise.resolve() .then(() => trackAsync(...args)) .catch((error) => debug('track failed', error)); diff --git a/packages/compass-telemetry/src/index.ts b/packages/compass-telemetry/src/index.ts index fd8acfc1230..36309c16853 100644 --- a/packages/compass-telemetry/src/index.ts +++ b/packages/compass-telemetry/src/index.ts @@ -1,2 +1,3 @@ export { createIpcTrack, createIpcSendTrack } from './ipc-track'; -export type { TrackFunction, TelemetryServiceOptions } from './generic-track'; +export type { TelemetryServiceOptions } from './generic-track'; +export type { TrackFunction, TrackParameters } from './types'; diff --git a/packages/compass-telemetry/src/ipc-track.ts b/packages/compass-telemetry/src/ipc-track.ts index 9cd530bf847..1165c7baa5d 100644 --- a/packages/compass-telemetry/src/ipc-track.ts +++ b/packages/compass-telemetry/src/ipc-track.ts @@ -1,11 +1,7 @@ import { type HadronIpcRenderer } from 'hadron-ipc'; -import { - type TelemetryPreferences, - type TrackFunction, - type TrackProps, - createTrack, -} from './generic-track'; +import { type TelemetryPreferences, createTrack } from './generic-track'; import { createLogger, type Logger } from '@mongodb-js/compass-logging'; +import type { TrackFunction } from './types'; function emit( ipc: HadronIpcRenderer | null | undefined, @@ -37,7 +33,7 @@ export function createIpcSendTrack() { // eslint-disable-next-line @typescript-eslint/no-var-requires require('hadron-ipc').ipcRenderer; - const sendTrack = (event: string, properties: TrackProps) => + const sendTrack: TrackFunction = (event, properties) => emit(ipc, 'compass:track', { event, properties }); return sendTrack; diff --git a/packages/compass-telemetry/src/provider.tsx b/packages/compass-telemetry/src/provider.tsx index 814beaf18ff..5a119e6c0f0 100644 --- a/packages/compass-telemetry/src/provider.tsx +++ b/packages/compass-telemetry/src/provider.tsx @@ -1,11 +1,8 @@ import React, { useRef } from 'react'; import { createServiceLocator } from 'hadron-app-registry'; -import { - createTrack, - type TelemetryServiceOptions, - type TrackFunction, -} from './generic-track'; +import { createTrack, type TelemetryServiceOptions } from './generic-track'; import { useLogger } from '@mongodb-js/compass-logging/provider'; +import type { TrackFunction, TrackParameters } from './types'; const noop = () => { // noop @@ -57,7 +54,7 @@ type FirstArgument = F extends (...args: [infer A, ...any]) => any ? A : never; -export function withTelemetry< +function withTelemetry< T extends ((...args: any[]) => any) | { new (...args: any[]): any } >(ReactComponent: T): React.FunctionComponent, 'track'>> { const WithTelemetry = ( @@ -69,6 +66,8 @@ export function withTelemetry< return WithTelemetry; } +export { withTelemetry }; + /** * Hook that allows to track telemetry events as a side effect of dependencies changing. * @@ -79,7 +78,7 @@ export function withTelemetry< * * @example * useTrackOnChange((track) => { - * if (isShellOpen) { track('Shell Opened') } + * if (isShellOpen) { track('Shell Opened', {}, { id: 'connection123' }) } * }, [isShellOpen], { skipOnMount: true }); */ export function useTrackOnChange( @@ -100,4 +99,4 @@ export function useTrackOnChange( }, [...dependencies, track, options.skipOnMount]); } -export type { TrackFunction }; +export type { TrackFunction, TrackParameters }; diff --git a/packages/compass-telemetry/src/types.ts b/packages/compass-telemetry/src/types.ts new file mode 100644 index 00000000000..bfa97b7c370 --- /dev/null +++ b/packages/compass-telemetry/src/types.ts @@ -0,0 +1,22 @@ +export type EventsPayload = Record; + +export type TelemetryConnectionInfo = { + id: string; +}; + +export type TrackParameters = + | EventsPayload + | (() => Promise) + | (() => EventsPayload); + +export type TrackFunction = ( + event: string, + parameters?: TrackParameters, + connectionInfo?: TelemetryConnectionInfo +) => void; + +export type AsyncTrackFunction = ( + event: string, + parameters?: TrackParameters, + connectionInfo?: TelemetryConnectionInfo +) => Promise; From d3587a40715dea9302da0e7e8611eaddea540caf Mon Sep 17 00:00:00 2001 From: Paula Stachova Date: Wed, 26 Jun 2024 14:13:28 +0200 Subject: [PATCH 02/24] part 1 --- .../pipeline-editor.tsx | 16 ++- .../components/stage-editor/stage-editor.tsx | 29 ++-- .../src/modules/aggregation.ts | 36 +++-- .../modules/pipeline-builder/stage-editor.ts | 129 ++++++++++++------ .../src/modules/saved-pipeline.ts | 62 ++++++--- packages/compass-explain-plan/src/index.ts | 2 + .../stores/explain-plan-modal-store.spec.ts | 7 + .../src/stores/explain-plan-modal-store.ts | 34 +++-- .../compass-explain-plan/src/stores/index.ts | 6 +- .../src/components/modal.tsx | 50 +++++-- 10 files changed, 262 insertions(+), 109 deletions(-) diff --git a/packages/compass-aggregations/src/components/pipeline-builder-workspace/pipeline-as-text-workspace/pipeline-editor.tsx b/packages/compass-aggregations/src/components/pipeline-builder-workspace/pipeline-as-text-workspace/pipeline-editor.tsx index aa1a8fa9499..c5ee866344c 100644 --- a/packages/compass-aggregations/src/components/pipeline-builder-workspace/pipeline-as-text-workspace/pipeline-editor.tsx +++ b/packages/compass-aggregations/src/components/pipeline-builder-workspace/pipeline-as-text-workspace/pipeline-editor.tsx @@ -21,6 +21,7 @@ import { changeEditorValue } from '../../../modules/pipeline-builder/text-editor import type { PipelineParserError } from '../../../modules/pipeline-builder/pipeline-parser/utils'; import { useAutocompleteFields } from '@mongodb-js/compass-field-store'; import { useTelemetry } from '@mongodb-js/compass-telemetry/provider'; +import { useConnectionInfoAccess } from '@mongodb-js/compass-connections/provider'; const containerStyles = css({ position: 'relative', @@ -80,6 +81,7 @@ export const PipelineEditor: React.FunctionComponent = ({ }) => { const fields = useAutocompleteFields(namespace); const track = useTelemetry(); + const connectionInfoAccess = useConnectionInfoAccess(); const editorInitialValueRef = useRef(pipelineText); const editorCurrentValueRef = useRef(pipelineText); editorCurrentValueRef.current = pipelineText; @@ -100,13 +102,17 @@ export const PipelineEditor: React.FunctionComponent = ({ !!editorCurrentValueRef.current && editorCurrentValueRef.current !== editorInitialValueRef.current ) { - track('Aggregation Edited', { - num_stages, - editor_view_type: 'text', - }); + track( + 'Aggregation Edited', + { + num_stages, + editor_view_type: 'text', + }, + connectionInfoAccess.getCurrentConnectionInfo() + ); editorInitialValueRef.current = editorCurrentValueRef.current; } - }, [num_stages, track]); + }, [num_stages, track, connectionInfoAccess]); const annotations: Annotation[] = useMemo(() => { return syntaxErrors diff --git a/packages/compass-aggregations/src/components/stage-editor/stage-editor.tsx b/packages/compass-aggregations/src/components/stage-editor/stage-editor.tsx index afdab0506f6..6ec3bb581ea 100644 --- a/packages/compass-aggregations/src/components/stage-editor/stage-editor.tsx +++ b/packages/compass-aggregations/src/components/stage-editor/stage-editor.tsx @@ -25,6 +25,7 @@ import type { RootState } from '../../modules'; import type { PipelineParserError } from '../../modules/pipeline-builder/pipeline-parser/utils'; import { useAutocompleteFields } from '@mongodb-js/compass-field-store'; import { useTelemetry } from '@mongodb-js/compass-telemetry/provider'; +import { useConnectionInfoAccess } from '@mongodb-js/compass-connections/provider'; const editorContainerStyles = css({ display: 'flex', @@ -97,6 +98,7 @@ export const StageEditor = ({ editorRef, }: StageEditorProps) => { const track = useTelemetry(); + const connectionInfoAccess = useConnectionInfoAccess(); const darkMode = useDarkMode(); const editorInitialValueRef = useRef(stageValue); const editorCurrentValueRef = useRef(stageValue); @@ -136,16 +138,27 @@ export const StageEditor = ({ !!editorCurrentValueRef.current && editorCurrentValueRef.current !== editorInitialValueRef.current ) { - track('Aggregation Edited', { - num_stages: num_stages, - stage_index: index + 1, - stage_action: 'stage_content_changed', - stage_name: stageOperator, - editor_view_type: editor_view_type, - }); + track( + 'Aggregation Edited', + { + num_stages: num_stages, + stage_index: index + 1, + stage_action: 'stage_content_changed', + stage_name: stageOperator, + editor_view_type: editor_view_type, + }, + connectionInfoAccess.getCurrentConnectionInfo() + ); editorInitialValueRef.current = editorCurrentValueRef.current; } - }, [track, num_stages, index, stageOperator, editor_view_type]); + }, [ + track, + num_stages, + index, + stageOperator, + editor_view_type, + connectionInfoAccess, + ]); return (
> => { return async ( dispatch, getState, - { pipelineBuilder, instance, dataService, track } + { pipelineBuilder, instance, dataService, track, connectionInfoAccess } ) => { const pipeline = getPipelineFromBuilderState(getState(), pipelineBuilder); @@ -309,10 +309,14 @@ export const runAggregation = (): PipelineBuilderThunkAction> => { type: ActionTypes.RunAggregation, pipeline, }); - track('Aggregation Executed', () => ({ - num_stages: pipeline.length, - editor_view_type: mapPipelineModeToEditorViewType(getState()), - })); + track( + 'Aggregation Executed', + () => ({ + num_stages: pipeline.length, + editor_view_type: mapPipelineModeToEditorViewType(getState()), + }), + connectionInfoAccess.getCurrentConnectionInfo() + ); return dispatch(fetchAggregationData()); }; }; @@ -363,8 +367,12 @@ export const cancelAggregation = (): PipelineBuilderThunkAction< void, Actions > => { - return (dispatch, getState, { track }) => { - track('Aggregation Canceled'); + return (dispatch, getState, { track, connectionInfoAccess }) => { + track( + 'Aggregation Canceled', + {}, + connectionInfoAccess.getCurrentConnectionInfo() + ); const { aggregation: { abortController }, } = getState(); @@ -387,7 +395,13 @@ const fetchAggregationData = ( return async ( dispatch, getState, - { preferences, logger: { log, mongoLogId }, track, globalAppRegistry } + { + preferences, + logger: { log, mongoLogId }, + track, + connectionInfoAccess, + globalAppRegistry, + } ) => { const { namespace, @@ -470,7 +484,11 @@ const fetchAggregationData = ( page, }); if ((e as MongoServerError).codeName === 'MaxTimeMSExpired') { - track('Aggregation Timed Out', { max_time_ms: maxTimeMS ?? null }); + track( + 'Aggregation Timed Out', + { max_time_ms: maxTimeMS ?? null }, + connectionInfoAccess.getCurrentConnectionInfo() + ); } log.warn( mongoLogId(1001000106), diff --git a/packages/compass-aggregations/src/modules/pipeline-builder/stage-editor.ts b/packages/compass-aggregations/src/modules/pipeline-builder/stage-editor.ts index e421b578672..999a410a534 100644 --- a/packages/compass-aggregations/src/modules/pipeline-builder/stage-editor.ts +++ b/packages/compass-aggregations/src/modules/pipeline-builder/stage-editor.ts @@ -534,7 +534,11 @@ export const changeStageOperator = ( string | undefined, ChangeStageOperatorAction > => { - return (dispatch, getState, { pipelineBuilder, track }) => { + return ( + dispatch, + getState, + { pipelineBuilder, track, connectionInfoAccess } + ) => { const { env, comments, @@ -569,13 +573,17 @@ export const changeStageOperator = ( stage.changeOperator(newVal); - track('Aggregation Edited', { - num_stages: pipelineFromStore(stages).length, - stage_action: 'stage_renamed', - stage_name: stage.operator, - stage_index: idxInPipeline + 1, - editor_view_type: mapPipelineModeToEditorViewType(getState()), - }); + track( + 'Aggregation Edited', + { + num_stages: pipelineFromStore(stages).length, + stage_action: 'stage_renamed', + stage_name: stage.operator, + stage_index: idxInPipeline + 1, + editor_view_type: mapPipelineModeToEditorViewType(getState()), + }, + connectionInfoAccess.getCurrentConnectionInfo() + ); dispatch({ type: StageEditorActionTypes.StageOperatorChange, id, stage }); @@ -643,7 +651,11 @@ export const changeStageCollapsed = ( export const addStage = ( after?: number ): PipelineBuilderThunkAction => { - return (dispatch, getState, { pipelineBuilder, track }) => { + return ( + dispatch, + getState, + { pipelineBuilder, track, connectionInfoAccess } + ) => { const { pipelineBuilder: { stageEditor: { stages }, @@ -657,12 +669,16 @@ export const addStage = ( }); const stage = pipelineBuilder.addStage(addAfterIdxInPipeline); - track('Aggregation Edited', { - num_stages: pipelineFromStore(stages).length, - stage_action: 'stage_added', - stage_index: stage.id + 1, - editor_view_type: mapPipelineModeToEditorViewType(getState()), - }); + track( + 'Aggregation Edited', + { + num_stages: pipelineFromStore(stages).length, + stage_action: 'stage_added', + stage_index: stage.id + 1, + editor_view_type: mapPipelineModeToEditorViewType(getState()), + }, + connectionInfoAccess.getCurrentConnectionInfo() + ); dispatch({ type: StageEditorActionTypes.StageAdded, after: addAfter, @@ -674,7 +690,11 @@ export const addStage = ( export const removeStage = ( at: number ): PipelineBuilderThunkAction => { - return (dispatch, getState, { pipelineBuilder, track }) => { + return ( + dispatch, + getState, + { pipelineBuilder, track, connectionInfoAccess } + ) => { const { pipelineBuilder: { stageEditor: { stages }, @@ -689,13 +709,17 @@ export const removeStage = ( pipelineBuilder.cancelPreviewForStage(idxInPipeline); const stage = pipelineBuilder.removeStage(idxInPipeline); - track('Aggregation Edited', { - num_stages: pipelineFromStore(stages).length, - stage_action: 'stage_deleted', - stage_name: stage.operator, - stage_index: idxInPipeline + 1, - editor_view_type: mapPipelineModeToEditorViewType(getState()), - }); + track( + 'Aggregation Edited', + { + num_stages: pipelineFromStore(stages).length, + stage_action: 'stage_deleted', + stage_name: stage.operator, + stage_index: idxInPipeline + 1, + editor_view_type: mapPipelineModeToEditorViewType(getState()), + }, + connectionInfoAccess.getCurrentConnectionInfo() + ); dispatch({ type: StageEditorActionTypes.StageRemoved, at }); dispatch(loadPreviewForStagesFrom(at)); void dispatch(fetchExplainForPipeline()); @@ -706,7 +730,11 @@ export const moveStage = ( from: number, to: number ): PipelineBuilderThunkAction => { - return (dispatch, getState, { pipelineBuilder, track }) => { + return ( + dispatch, + getState, + { pipelineBuilder, track, connectionInfoAccess } + ) => { if (from === to) { return; } @@ -742,13 +770,17 @@ export const moveStage = ( if (pipelineWasNotModified) { dispatch({ type: StageEditorActionTypes.StageMoved, from, to }); } else { - track('Aggregation Edited', { - num_stages: pipelineFromStore(stages).length, - stage_action: 'stage_reordered', - stage_name: stageAtFromIdx.stageOperator, - stage_index: stageAtFromIdx.idxInPipeline + 1, - editor_view_type: mapPipelineModeToEditorViewType(getState()), - }); + track( + 'Aggregation Edited', + { + num_stages: pipelineFromStore(stages).length, + stage_action: 'stage_reordered', + stage_name: stageAtFromIdx.stageOperator, + stage_index: stageAtFromIdx.idxInPipeline + 1, + editor_view_type: mapPipelineModeToEditorViewType(getState()), + }, + connectionInfoAccess.getCurrentConnectionInfo() + ); pipelineBuilder.moveStage(stageAtFromIdx.idxInPipeline, toIdxInPipeline); dispatch({ type: StageEditorActionTypes.StageMoved, from, to }); @@ -872,7 +904,11 @@ export const convertWizardToStage = ( void, WizardChangeAction | WizardToStageAction > => { - return (dispatch, getState, { pipelineBuilder, track }) => { + return ( + dispatch, + getState, + { pipelineBuilder, track, connectionInfoAccess } + ) => { const { pipelineBuilder: { stageEditor: { stages }, @@ -903,16 +939,25 @@ export const convertWizardToStage = ( stage.changeValue(formatWizardValue(itemAtIdx.value as string)); - track('Aggregation Edited', { - num_stages: pipelineFromStore(stages).length + 1, - stage_action: 'stage_added', - stage_name: stage.operator, - stage_index: afterStageIndex + 1, - editor_view_type: 'stage', - }); - track('Aggregation Use Case Saved', { - stage_name: stage.operator, - }); + const connectionInfo = connectionInfoAccess.getCurrentConnectionInfo(); + track( + 'Aggregation Edited', + { + num_stages: pipelineFromStore(stages).length + 1, + stage_action: 'stage_added', + stage_name: stage.operator, + stage_index: afterStageIndex + 1, + editor_view_type: 'stage', + }, + connectionInfo + ); + track( + 'Aggregation Use Case Saved', + { + stage_name: stage.operator, + }, + connectionInfo + ); dispatch({ type: StageEditorActionTypes.WizardToStageClicked, diff --git a/packages/compass-aggregations/src/modules/saved-pipeline.ts b/packages/compass-aggregations/src/modules/saved-pipeline.ts index 2d1856108e6..0fccaa96060 100644 --- a/packages/compass-aggregations/src/modules/saved-pipeline.ts +++ b/packages/compass-aggregations/src/modules/saved-pipeline.ts @@ -164,7 +164,11 @@ export const openStoredPipeline = ( */ export const saveCurrentPipeline = (): PipelineBuilderThunkAction => - async (dispatch, getState, { pipelineBuilder, pipelineStorage, track }) => { + async ( + dispatch, + getState, + { pipelineBuilder, pipelineStorage, track, connectionInfoAccess } + ) => { if (getState().id === '') { dispatch(createId()); } @@ -205,21 +209,26 @@ export const saveCurrentPipeline = } })(); - track('Aggregation Saved', { - id: savedPipeline.id, - num_stages: stagesLength, - editor_view_type: mapPipelineModeToEditorViewType(getState()), - }); + track( + 'Aggregation Saved', + { + id: savedPipeline.id, + num_stages: stagesLength, + editor_view_type: mapPipelineModeToEditorViewType(getState()), + }, + connectionInfoAccess.getCurrentConnectionInfo() + ); dispatch(updatePipelineList()); }; export const confirmOpenPipeline = (pipelineData: SavedPipeline): PipelineBuilderThunkAction => - async (dispatch, getState, { track }) => { + async (dispatch, getState, { track, connectionInfoAccess }) => { const isModified = getState().isModified; + const connectionInfo = connectionInfoAccess.getCurrentConnectionInfo(); if (isModified) { - track('Screen', { name: 'restore_pipeline_modal' }); + track('Screen', { name: 'restore_pipeline_modal' }, connectionInfo); const confirmed = await showConfirmation({ title: 'Are you sure you want to open this pipeline?', description: @@ -230,18 +239,27 @@ export const confirmOpenPipeline = return; } } - track('Aggregation Opened', { - id: pipelineData.id, - editor_view_type: mapPipelineModeToEditorViewType(getState()), - screen: 'aggregations', - }); + track( + 'Aggregation Opened', + { + id: pipelineData.id, + editor_view_type: mapPipelineModeToEditorViewType(getState()), + screen: 'aggregations', + }, + connectionInfo + ); void dispatch(openStoredPipeline(pipelineData)); }; export const confirmDeletePipeline = (pipelineId: string): PipelineBuilderThunkAction => - async (dispatch, getState, { pipelineStorage, track }) => { - track('Screen', { name: 'delete_pipeline_modal' }); + async ( + dispatch, + getState, + { pipelineStorage, track, connectionInfoAccess } + ) => { + const connectionInfo = connectionInfoAccess.getCurrentConnectionInfo(); + track('Screen', { name: 'delete_pipeline_modal' }, connectionInfo); const confirmed = await showConfirmation({ title: 'Are you sure you want to delete this pipeline?', description: @@ -252,11 +270,15 @@ export const confirmDeletePipeline = if (!confirmed) { return; } - track('Aggregation Deleted', { - id: pipelineId, - editor_view_type: mapPipelineModeToEditorViewType(getState()), - screen: 'aggregations', - }); + track( + 'Aggregation Deleted', + { + id: pipelineId, + editor_view_type: mapPipelineModeToEditorViewType(getState()), + screen: 'aggregations', + }, + connectionInfo + ); await pipelineStorage?.delete(pipelineId); dispatch(updatePipelineList()); }; diff --git a/packages/compass-explain-plan/src/index.ts b/packages/compass-explain-plan/src/index.ts index 7158cf5d091..2879f3cbf07 100644 --- a/packages/compass-explain-plan/src/index.ts +++ b/packages/compass-explain-plan/src/index.ts @@ -2,6 +2,7 @@ import ExplainPlanModal from './components/explain-plan-modal'; import { activatePlugin } from './stores'; import { registerHadronPlugin } from 'hadron-app-registry'; import { + connectionInfoAccessLocator, dataServiceLocator, type DataServiceLocator, } from '@mongodb-js/compass-connections/provider'; @@ -18,6 +19,7 @@ const ExplainPlanModalPlugin = registerHadronPlugin( { logger: createLoggerLocator('EXPLAIN-PLAN-MODAL-UI'), track: createTelemetryLocator(), + connectionInfoAccess: connectionInfoAccessLocator, dataService: dataServiceLocator as DataServiceLocator< 'explainAggregate' | 'explainFind' | 'isCancelError' >, diff --git a/packages/compass-explain-plan/src/stores/explain-plan-modal-store.spec.ts b/packages/compass-explain-plan/src/stores/explain-plan-modal-store.spec.ts index 64b80b3d94f..1d6d61aec3e 100644 --- a/packages/compass-explain-plan/src/stores/explain-plan-modal-store.spec.ts +++ b/packages/compass-explain-plan/src/stores/explain-plan-modal-store.spec.ts @@ -8,6 +8,7 @@ import { activatePlugin } from './'; import { expect } from 'chai'; import type { Document } from 'mongodb'; import Sinon from 'sinon'; +import type { ConnectionInfo } from '../../../connection-info/dist'; const localAppRegistry = new AppRegistry(); @@ -80,6 +81,12 @@ describe('explain plan modal store', function () { mongoLogId() {}, } as any, track: () => {}, + connectionInfoAccess: { + getCurrentConnectionInfo: () => + ({ + id: 'TEST', + } as ConnectionInfo), + }, preferences: { getPreferences() { return { maxTimeMS: 0 }; diff --git a/packages/compass-explain-plan/src/stores/explain-plan-modal-store.ts b/packages/compass-explain-plan/src/stores/explain-plan-modal-store.ts index 72d826860d1..6a6b4d15a08 100644 --- a/packages/compass-explain-plan/src/stores/explain-plan-modal-store.ts +++ b/packages/compass-explain-plan/src/stores/explain-plan-modal-store.ts @@ -176,10 +176,18 @@ export const openExplainPlanModal = ( return async ( dispatch, getState, - { dataService, preferences, track, logger: { log, mongoLogId } } + { + dataService, + preferences, + track, + connectionInfoAccess, + logger: { log, mongoLogId }, + } ) => { const { id: fetchId, signal } = getAbortSignal(); + const connectionInfo = connectionInfoAccess.getCurrentConnectionInfo(); + let rawExplainPlan = null; let explainPlan = null; @@ -233,10 +241,14 @@ export const openExplainPlanModal = ( throw err; } - track('Aggregation Explained', { - num_stages: pipeline.length, - index_used: explainPlan.usedIndexes.length > 0, - }); + track( + 'Aggregation Explained', + { + num_stages: pipeline.length, + index_used: explainPlan.usedIndexes.length > 0, + }, + connectionInfo + ); } if (event.query) { @@ -273,10 +285,14 @@ export const openExplainPlanModal = ( throw err; } - track('Explain Plan Executed', { - with_filter: Object.entries(filter).length > 0, - index_used: explainPlan.usedIndexes.length > 0, - }); + track( + 'Explain Plan Executed', + { + with_filter: Object.entries(filter).length > 0, + index_used: explainPlan.usedIndexes.length > 0, + }, + connectionInfo + ); } dispatch({ diff --git a/packages/compass-explain-plan/src/stores/index.ts b/packages/compass-explain-plan/src/stores/index.ts index 5cc97689afc..b015ebf5b01 100644 --- a/packages/compass-explain-plan/src/stores/index.ts +++ b/packages/compass-explain-plan/src/stores/index.ts @@ -9,7 +9,10 @@ import { import type { AggregateOptions, Document, FindOptions } from 'mongodb'; import type AppRegistry from 'hadron-app-registry'; import type { CollectionTabPluginMetadata } from '@mongodb-js/compass-collection'; -import type { DataService } from '@mongodb-js/compass-connections/provider'; +import type { + ConnectionInfoAccess, + DataService, +} from '@mongodb-js/compass-connections/provider'; import type { Logger } from '@mongodb-js/compass-logging/provider'; import type { PreferencesAccess } from 'compass-preferences-model/provider'; @@ -44,6 +47,7 @@ export type ExplainPlanModalServices = { >; logger: Logger; track: TrackFunction; + connectionInfoAccess: ConnectionInfoAccess; preferences: PreferencesAccess; localAppRegistry: AppRegistry; }; diff --git a/packages/compass-export-to-language/src/components/modal.tsx b/packages/compass-export-to-language/src/components/modal.tsx index 736b7b96f9d..04ca4fb9e3c 100644 --- a/packages/compass-export-to-language/src/components/modal.tsx +++ b/packages/compass-export-to-language/src/components/modal.tsx @@ -1,4 +1,4 @@ -import React, { useEffect, useMemo, useState } from 'react'; +import React, { useCallback, useEffect, useMemo, useState } from 'react'; import { connect } from 'react-redux'; import { InfoModal, @@ -23,6 +23,7 @@ import { countAggregationStagesInString } from '../modules/count-aggregation-sta import { usePreference } from 'compass-preferences-model/provider'; import { prettify } from '@mongodb-js/compass-editor'; import { closeModal } from '../stores'; +import { useConnectionInfoAccess } from '@mongodb-js/compass-connections/provider'; type LanguageOption = { displayName: string; @@ -100,6 +101,7 @@ const ExportToLanguageModal: React.FunctionComponent< } > = ({ modalOpen, onModalClose, inputExpression, uri, namespace }) => { const track = useTelemetry(); + const connectionInfoAccess = useConnectionInfoAccess(); const [outputLanguage, setOutputLanguage] = useState('python'); const [includeImports, setIncludeImports] = useState(false); @@ -154,16 +156,21 @@ const ExportToLanguageModal: React.FunctionComponent< : 'Aggregation Export Opened'; if (modalOpen && !wasOpen) { - track(trackingEvent, { - ...stageCountForTelemetry(inputExpression), - }); - track('Screen', { name: 'export_to_language_modal' }); + const connectionInfo = connectionInfoAccess.getCurrentConnectionInfo(); + track( + trackingEvent, + { + ...stageCountForTelemetry(inputExpression), + }, + connectionInfo + ); + track('Screen', { name: 'export_to_language_modal' }, connectionInfo); } setWasOpen(modalOpen); - }, [modalOpen, wasOpen, mode, inputExpression, track]); + }, [modalOpen, wasOpen, mode, inputExpression, track, connectionInfoAccess]); - function trackCopiedOutput() { + const trackCopiedOutput = useCallback(() => { const trackingEvent = mode === 'Update Query' ? 'Update Exported' @@ -173,14 +180,27 @@ const ExportToLanguageModal: React.FunctionComponent< ? 'Query Exported' : 'Aggregation Exported'; - track(trackingEvent, { - language: outputLanguage, - with_import_statements: includeImports, - with_drivers_syntax: includeDrivers, - with_builders: useBuilders, - ...stageCountForTelemetry(inputExpression), - }); - } + track( + trackingEvent, + { + language: outputLanguage, + with_import_statements: includeImports, + with_drivers_syntax: includeDrivers, + with_builders: useBuilders, + ...stageCountForTelemetry(inputExpression), + }, + connectionInfoAccess.getCurrentConnectionInfo() + ); + }, [ + track, + connectionInfoAccess, + outputLanguage, + includeImports, + includeDrivers, + useBuilders, + inputExpression, + mode, + ]); const prettyInput = useMemo(() => { return prettify(input, 'javascript-expression'); From 4be7f44e10705a15fb8aa58e5b56029d3258554e Mon Sep 17 00:00:00 2001 From: Paula Stachova Date: Wed, 26 Jun 2024 17:05:43 +0200 Subject: [PATCH 03/24] part 2 --- .../aggregation-side-panel/index.tsx | 16 ++- packages/compass-aggregations/src/index.ts | 1 + .../src/modules/aggregation.spec.ts | 1 + .../src/modules/create-view/index.ts | 14 +- .../modules/pipeline-builder/pipeline-ai.ts | 58 +++++--- .../src/modules/side-panel.ts | 18 ++- .../src/stores/create-view.spec.ts | 4 + .../src/stores/create-view.ts | 8 +- .../compass-crud/src/stores/crud-store.ts | 132 ++++++++++++------ .../src/components/query-ai.tsx | 18 ++- packages/compass-query-bar/src/index.tsx | 2 + .../src/stores/ai-query-reducer.ts | 58 +++++--- .../src/stores/query-bar-store.ts | 9 +- 13 files changed, 243 insertions(+), 96 deletions(-) diff --git a/packages/compass-aggregations/src/components/aggregation-side-panel/index.tsx b/packages/compass-aggregations/src/components/aggregation-side-panel/index.tsx index 48841e0e72d..ff3cb0d553c 100644 --- a/packages/compass-aggregations/src/components/aggregation-side-panel/index.tsx +++ b/packages/compass-aggregations/src/components/aggregation-side-panel/index.tsx @@ -18,6 +18,7 @@ import { FeedbackLink } from './feedback-link'; import { addWizard } from '../../modules/pipeline-builder/stage-editor'; import { UseCaseCard } from './stage-wizard-use-cases'; import { useTelemetry } from '@mongodb-js/compass-telemetry/provider'; +import { useConnectionInfoAccess } from '@mongodb-js/compass-connections/provider'; const containerStyles = css({ height: '100%', @@ -79,6 +80,7 @@ export const AggregationSidePanel = ({ onSelectUseCase, }: AggregationSidePanelProps) => { const track = useTelemetry(); + const connectionInfoAccess = useConnectionInfoAccess(); const [searchText, setSearchText] = useState(''); const darkMode = useDarkMode(); @@ -104,12 +106,16 @@ export const AggregationSidePanel = ({ return; } onSelectUseCase(id, useCase.stageOperator); - track('Aggregation Use Case Added', { - drag_and_drop: false, - stage_name: useCase.stageOperator, - }); + track( + 'Aggregation Use Case Added', + { + drag_and_drop: false, + stage_name: useCase.stageOperator, + }, + connectionInfoAccess.getCurrentConnectionInfo() + ); }, - [onSelectUseCase, track] + [onSelectUseCase, track, connectionInfoAccess] ); return ( diff --git a/packages/compass-aggregations/src/index.ts b/packages/compass-aggregations/src/index.ts index ce700eed905..e073412cc8f 100644 --- a/packages/compass-aggregations/src/index.ts +++ b/packages/compass-aggregations/src/index.ts @@ -69,6 +69,7 @@ export const CreateViewPlugin = registerHadronPlugin( connectionsManager: connectionsManagerLocator, logger: createLoggerLocator('COMPASS-CREATE-VIEW-UI'), track: createTelemetryLocator(), + connectionInfoAccess: connectionInfoAccessLocator, workspaces: workspacesServiceLocator, } ); diff --git a/packages/compass-aggregations/src/modules/aggregation.spec.ts b/packages/compass-aggregations/src/modules/aggregation.spec.ts index 50748522149..7414126a540 100644 --- a/packages/compass-aggregations/src/modules/aggregation.spec.ts +++ b/packages/compass-aggregations/src/modules/aggregation.spec.ts @@ -41,6 +41,7 @@ const getMockedStore = ( preferences: defaultPreferencesInstance, logger: createNoopLogger(), track: createNoopTrack(), + connectionInfoAccess: { getCurrentConnectionInfo: () => {} }, }) ) ); diff --git a/packages/compass-aggregations/src/modules/create-view/index.ts b/packages/compass-aggregations/src/modules/create-view/index.ts index e8b00714ac0..93ba92cf2aa 100644 --- a/packages/compass-aggregations/src/modules/create-view/index.ts +++ b/packages/compass-aggregations/src/modules/create-view/index.ts @@ -202,7 +202,13 @@ export const createView = (): CreateViewThunkAction> => { return async ( dispatch, getState, - { globalAppRegistry, connectionsManager, track, workspaces } + { + globalAppRegistry, + connectionsManager, + track, + connectionInfoAccess, + workspaces, + } ) => { const { name: viewName, @@ -227,7 +233,11 @@ export const createView = (): CreateViewThunkAction> => { options ); const ns = `${database}.${viewName}`; - track('Aggregation Saved As View', { num_stages: viewPipeline.length }); + track( + 'Aggregation Saved As View', + { num_stages: viewPipeline.length }, + connectionInfoAccess.getCurrentConnectionInfo() + ); globalAppRegistry.emit('view-created', ns, { connectionId, }); diff --git a/packages/compass-aggregations/src/modules/pipeline-builder/pipeline-ai.ts b/packages/compass-aggregations/src/modules/pipeline-builder/pipeline-ai.ts index 5aed1b59f45..f120b3aa488 100644 --- a/packages/compass-aggregations/src/modules/pipeline-builder/pipeline-ai.ts +++ b/packages/compass-aggregations/src/modules/pipeline-builder/pipeline-ai.ts @@ -14,6 +14,7 @@ import type { AtlasServiceError } from '@mongodb-js/atlas-service/renderer'; import type { Logger } from '@mongodb-js/compass-logging/provider'; import { mongoLogId } from '@mongodb-js/compass-logging/provider'; import type { TrackFunction } from '@mongodb-js/compass-telemetry'; +import type { ConnectionInfo } from '@mongodb-js/compass-connections/provider'; const emptyPipelineError = 'No pipeline was returned. Please try again with a different prompt.'; @@ -160,6 +161,7 @@ type FailedResponseTrackMessage = { errorName: string; errorCode?: string; requestId: string; + connectionInfo: ConnectionInfo; track: TrackFunction; } & Pick; @@ -171,6 +173,7 @@ function trackAndLogFailed({ errorCode, log, requestId, + connectionInfo, track, }: FailedResponseTrackMessage) { log.warn( @@ -185,13 +188,17 @@ function trackAndLogFailed({ requestId, } ); - track('AI Response Failed', { - editor_view_type, - error_code: errorCode || '', - status_code: statusCode, - error_name: errorName, - request_id: requestId, - }); + track( + 'AI Response Failed', + { + editor_view_type, + error_code: errorCode || '', + status_code: statusCode, + error_name: errorName, + request_id: requestId, + }, + connectionInfo + ); } export const runAIPipelineGeneration = ( @@ -209,6 +216,7 @@ export const runAIPipelineGeneration = ( preferences, logger: { log, mongoLogId }, track, + connectionInfoAccess, } ) => { const { @@ -220,6 +228,8 @@ export const runAIPipelineGeneration = ( dataService: { dataService }, } = getState(); + const connectionInfo = connectionInfoAccess.getCurrentConnectionInfo(); + const provideSampleDocuments = preferences.getPreferences().enableGenAISampleDocumentPassing; @@ -232,12 +242,16 @@ export const runAIPipelineGeneration = ( const abortController = new AbortController(); const { id: requestId, signal } = getAbortSignal(); - track('AI Prompt Submitted', () => ({ - editor_view_type, - user_input_length: userInput.length, - request_id: requestId, - has_sample_documents: provideSampleDocuments, - })); + track( + 'AI Prompt Submitted', + () => ({ + editor_view_type, + user_input_length: userInput.length, + request_id: requestId, + has_sample_documents: provideSampleDocuments, + }), + connectionInfo + ); dispatch({ type: AIPipelineActionTypes.AIPipelineStarted, @@ -293,6 +307,7 @@ export const runAIPipelineGeneration = ( track, log, requestId, + connectionInfo, }); // We're going to reset input state with this error, show the error in the // toast instead @@ -341,6 +356,7 @@ export const runAIPipelineGeneration = ( track, log, requestId, + connectionInfo, }); dispatch({ type: AIPipelineActionTypes.AIPipelineFailed, @@ -363,12 +379,16 @@ export const runAIPipelineGeneration = ( } ); - track('AI Response Generated', () => ({ - editor_view_type, - syntax_errors: !!(pipelineBuilder.syntaxError?.length > 0), - query_shape: pipelineBuilder.stages.map((stage) => stage.operator), - request_id: requestId, - })); + track( + 'AI Response Generated', + () => ({ + editor_view_type, + syntax_errors: !!(pipelineBuilder.syntaxError?.length > 0), + query_shape: pipelineBuilder.stages.map((stage) => stage.operator), + request_id: requestId, + }), + connectionInfo + ); dispatch({ type: AIPipelineActionTypes.LoadGeneratedPipeline, diff --git a/packages/compass-aggregations/src/modules/side-panel.ts b/packages/compass-aggregations/src/modules/side-panel.ts index d5e39ae37d9..4df84ed2ef4 100644 --- a/packages/compass-aggregations/src/modules/side-panel.ts +++ b/packages/compass-aggregations/src/modules/side-panel.ts @@ -37,7 +37,11 @@ export const toggleSidePanel = (): PipelineBuilderThunkAction< void, SidePanelToggledAction > => { - return (dispatch, getState, { pipelineBuilder, track }) => { + return ( + dispatch, + getState, + { pipelineBuilder, track, connectionInfoAccess } + ) => { const { sidePanel: { isPanelOpen }, } = getState(); @@ -46,10 +50,14 @@ export const toggleSidePanel = (): PipelineBuilderThunkAction< // When user is opening the panel if (willPanelBeOpen) { - track('Aggregation Side Panel Opened', { - num_stages: getPipelineFromBuilderState(getState(), pipelineBuilder) - .length, - }); + track( + 'Aggregation Side Panel Opened', + { + num_stages: getPipelineFromBuilderState(getState(), pipelineBuilder) + .length, + }, + connectionInfoAccess.getCurrentConnectionInfo() + ); } // Persist the state of the stage wizard side panel for other tabs or for diff --git a/packages/compass-aggregations/src/stores/create-view.spec.ts b/packages/compass-aggregations/src/stores/create-view.spec.ts index f544673c9c7..e90bfe69351 100644 --- a/packages/compass-aggregations/src/stores/create-view.spec.ts +++ b/packages/compass-aggregations/src/stores/create-view.spec.ts @@ -25,6 +25,9 @@ describe('CreateViewStore [Store]', function () { let appRegistryEmitSpy: Sinon.SinonSpy; const logger = {} as any; const track = () => {}; + const connectionInfoAccess = { + getCurrentConnectionInfo: () => ({ id: 'TEST' }), + }; const createViewStub = Sinon.stub(); const dataService = { createView: createViewStub, @@ -48,6 +51,7 @@ describe('CreateViewStore [Store]', function () { connectionsManager, logger, track, + connectionInfoAccess, workspaces, }, createActivateHelpers() diff --git a/packages/compass-aggregations/src/stores/create-view.ts b/packages/compass-aggregations/src/stores/create-view.ts index 76cbc42c8fe..b00b2d75390 100644 --- a/packages/compass-aggregations/src/stores/create-view.ts +++ b/packages/compass-aggregations/src/stores/create-view.ts @@ -7,7 +7,10 @@ import reducer, { open } from '../modules/create-view'; import type AppRegistry from 'hadron-app-registry'; import type { Logger } from '@mongodb-js/compass-logging/provider'; import type { WorkspacesService } from '@mongodb-js/compass-workspaces/provider'; -import type { ConnectionsManager } from '@mongodb-js/compass-connections/provider'; +import type { + ConnectionInfoAccess, + ConnectionsManager, +} from '@mongodb-js/compass-connections/provider'; import type { ActivateHelpers } from 'hadron-app-registry'; import type { TrackFunction } from '@mongodb-js/compass-telemetry'; @@ -16,6 +19,7 @@ type CreateViewServices = { connectionsManager: ConnectionsManager; logger: Logger; track: TrackFunction; + connectionInfoAccess: ConnectionInfoAccess; workspaces: WorkspacesService; }; @@ -52,6 +56,7 @@ export function activateCreateViewPlugin( connectionsManager, logger, track, + connectionInfoAccess, workspaces, }: CreateViewServices, { on, cleanup }: ActivateHelpers @@ -61,6 +66,7 @@ export function activateCreateViewPlugin( connectionsManager, logger, track, + connectionInfoAccess, workspaces, }); diff --git a/packages/compass-crud/src/stores/crud-store.ts b/packages/compass-crud/src/stores/crud-store.ts index 8fe25894d2e..9ad22db639e 100644 --- a/packages/compass-crud/src/stores/crud-store.ts +++ b/packages/compass-crud/src/stores/crud-store.ts @@ -335,6 +335,7 @@ class CrudStoreImpl fieldStoreService: FieldStoreService; logger: Logger; track: TrackFunction; + connectionInfoAccess: ConnectionInfoAccess; instance: MongoDBInstance; connectionScopedAppRegistry: ConnectionScopedAppRegistry; queryBar: QueryBarService; @@ -349,6 +350,7 @@ class CrudStoreImpl | 'preferences' | 'logger' | 'track' + | 'connectionInfoAccess' | 'fieldStoreService' | 'connectionScopedAppRegistry' | 'queryBar' @@ -366,6 +368,7 @@ class CrudStoreImpl this.preferences = services.preferences; this.logger = services.logger; this.track = services.track; + this.connectionInfoAccess = services.connectionInfoAccess; this.instance = services.instance; this.fieldStoreService = services.fieldStoreService; this.connectionScopedAppRegistry = services.connectionScopedAppRegistry; @@ -478,7 +481,11 @@ class CrudStoreImpl * @returns {Boolean} If the copy succeeded. */ copyToClipboard(doc: Document) { - this.track('Document Copied', { mode: this.modeForTelemetry() }); + this.track( + 'Document Copied', + { mode: this.modeForTelemetry() }, + this.connectionInfoAccess.getCurrentConnectionInfo() + ); const documentEJSON = doc.toEJSON(); // eslint-disable-next-line no-undef void navigator.clipboard.writeText(documentEJSON); @@ -490,7 +497,11 @@ class CrudStoreImpl * @param {Document} doc - The hadron document. */ async removeDocument(doc: Document) { - this.track('Document Deleted', { mode: this.modeForTelemetry() }); + this.track( + 'Document Deleted', + { mode: this.modeForTelemetry() }, + this.connectionInfoAccess.getCurrentConnectionInfo() + ); const id = doc.getId(); if (id !== undefined) { doc.emit('remove-start'); @@ -558,7 +569,11 @@ class CrudStoreImpl * @param {Document} doc - The hadron document. */ async updateDocument(doc: Document) { - this.track('Document Updated', { mode: this.modeForTelemetry() }); + this.track( + 'Document Updated', + { mode: this.modeForTelemetry() }, + this.connectionInfoAccess.getCurrentConnectionInfo() + ); try { doc.emit('update-start'); // We add the shard keys here, if there are any, because that is @@ -624,7 +639,11 @@ class CrudStoreImpl * @param {Document} doc - The hadron document. */ async replaceDocument(doc: Document) { - this.track('Document Updated', { mode: this.modeForTelemetry() }); + this.track( + 'Document Updated', + { mode: this.modeForTelemetry() }, + this.connectionInfoAccess.getCurrentConnectionInfo() + ); try { doc.emit('update-start'); @@ -863,7 +882,11 @@ class CrudStoreImpl const hadronDoc = new HadronDocument(doc); if (clone) { - this.track('Document Cloned', { mode: this.modeForTelemetry() }); + this.track( + 'Document Cloned', + { mode: this.modeForTelemetry() }, + this.connectionInfoAccess.getCurrentConnectionInfo() + ); // We need to remove the _id or we will get an duplicate key error on // insert, and we currently do not allow editing of the _id field. for (const element of hadronDoc.elements) { @@ -922,9 +945,13 @@ class CrudStoreImpl } async openBulkUpdateModal(updateText?: string) { - this.track('Bulk Update Opened', { - isUpdatePreviewSupported: this.state.isUpdatePreviewSupported, - }); + this.track( + 'Bulk Update Opened', + { + isUpdatePreviewSupported: this.state.isUpdatePreviewSupported, + }, + this.connectionInfoAccess.getCurrentConnectionInfo() + ); await this.updateBulkUpdatePreview(updateText ?? INITIAL_BULK_UPDATE_TEXT); this.setState({ @@ -1068,9 +1095,13 @@ class CrudStoreImpl } async runBulkUpdate() { - this.track('Bulk Update Executed', { - isUpdatePreviewSupported: this.state.isUpdatePreviewSupported, - }); + this.track( + 'Bulk Update Executed', + { + isUpdatePreviewSupported: this.state.isUpdatePreviewSupported, + }, + this.connectionInfoAccess.getCurrentConnectionInfo() + ); this.closeBulkUpdateModal(); @@ -1247,10 +1278,14 @@ class CrudStoreImpl const docs = HadronDocument.FromEJSONArray( this.state.insert.jsonDoc ?? '' ).map((doc) => doc.generateObject()); - this.track('Document Inserted', { - mode: this.state.insert.jsonView ? 'json' : 'field-by-field', - multiple: docs.length > 1, - }); + this.track( + 'Document Inserted', + { + mode: this.state.insert.jsonView ? 'json' : 'field-by-field', + multiple: docs.length > 1, + }, + this.connectionInfoAccess.getCurrentConnectionInfo() + ); try { await this.dataService.insertMany(this.state.ns, docs); @@ -1297,10 +1332,14 @@ class CrudStoreImpl * view to insert. */ async insertDocument() { - this.track('Document Inserted', { - mode: this.state.insert.jsonView ? 'json' : 'field-by-field', - multiple: false, - }); + this.track( + 'Document Inserted', + { + mode: this.state.insert.jsonView ? 'json' : 'field-by-field', + multiple: false, + }, + this.connectionInfoAccess.getCurrentConnectionInfo() + ); let doc: BSONObject; @@ -1452,21 +1491,25 @@ class CrudStoreImpl if (onApply) { const { isTimeSeries, isReadonly } = this.state; - this.track('Query Executed', { - has_projection: - !!query.project && Object.keys(query.project).length > 0, - has_skip: (query.skip ?? 0) > 0, - has_sort: !!query.sort && Object.keys(query.sort).length > 0, - has_limit: (query.limit ?? 0) > 0, - has_collation: !!query.collation, - changed_maxtimems: query.maxTimeMS !== DEFAULT_INITIAL_MAX_TIME_MS, - collection_type: isTimeSeries - ? 'time-series' - : isReadonly - ? 'readonly' - : 'collection', - used_regex: objectContainsRegularExpression(query.filter ?? {}), - }); + this.track( + 'Query Executed', + { + has_projection: + !!query.project && Object.keys(query.project).length > 0, + has_skip: (query.skip ?? 0) > 0, + has_sort: !!query.sort && Object.keys(query.sort).length > 0, + has_limit: (query.limit ?? 0) > 0, + has_collation: !!query.collation, + changed_maxtimems: query.maxTimeMS !== DEFAULT_INITIAL_MAX_TIME_MS, + collection_type: isTimeSeries + ? 'time-series' + : isReadonly + ? 'readonly' + : 'collection', + used_regex: objectContainsRegularExpression(query.filter ?? {}), + }, + this.connectionInfoAccess.getCurrentConnectionInfo() + ); } // pass the signal so that the queries can close their own cursors and @@ -1702,7 +1745,10 @@ class CrudStoreImpl } openBulkDeleteDialog() { - this.track('Bulk Delete Opened'); + this.track( + 'Bulk Delete Opened', + this.connectionInfoAccess.getCurrentConnectionInfo() + ); const PREVIEW_DOCS = 5; @@ -1767,7 +1813,10 @@ class CrudStoreImpl } async runBulkDelete() { - this.track('Bulk Delete Executed'); + this.track( + 'Bulk Delete Executed', + this.connectionInfoAccess.getCurrentConnectionInfo() + ); const { affected } = this.state.bulkDelete; this.closeBulkDeleteDialog(); @@ -1807,9 +1856,13 @@ class CrudStoreImpl } async saveUpdateQuery(name: string): Promise { - this.track('Bulk Update Favorited', { - isUpdatePreviewSupported: this.state.isUpdatePreviewSupported, - }); + this.track( + 'Bulk Update Favorited', + { + isUpdatePreviewSupported: this.state.isUpdatePreviewSupported, + }, + this.connectionInfoAccess.getCurrentConnectionInfo() + ); const { filter } = this.queryBar.getLastAppliedQuery('crud'); let update; @@ -1884,6 +1937,7 @@ export function activateDocumentsPlugin( preferences, logger, track, + connectionInfoAccess, favoriteQueryStorage: favoriteQueryStorageAccess?.getStorage(), recentQueryStorage: recentQueryStorageAccess?.getStorage(), fieldStoreService, diff --git a/packages/compass-query-bar/src/components/query-ai.tsx b/packages/compass-query-bar/src/components/query-ai.tsx index 9d589a33621..626b27e72ea 100644 --- a/packages/compass-query-bar/src/components/query-ai.tsx +++ b/packages/compass-query-bar/src/components/query-ai.tsx @@ -13,10 +13,12 @@ import { import { useLogger } from '@mongodb-js/compass-logging/provider'; import { useTelemetry } from '@mongodb-js/compass-telemetry/provider'; import { isEqualDefaultQuery } from '../utils/query'; +import { useConnectionInfoAccess } from '@mongodb-js/compass-connections/provider'; const useOnSubmitFeedback = (lastAIQueryRequestId: string | null) => { const logger = useLogger('AI-QUERY-UI'); const track = useTelemetry(); + const connectionInfoAccess = useConnectionInfoAccess(); return useCallback( (feedback: 'positive' | 'negative', text: string) => { const { log, mongoLogId } = logger; @@ -26,11 +28,15 @@ const useOnSubmitFeedback = (lastAIQueryRequestId: string | null) => { text, }); - track('AI Query Feedback', () => ({ - feedback, - text, - request_id: lastAIQueryRequestId, - })); + track( + 'AI Query Feedback', + () => ({ + feedback, + text, + request_id: lastAIQueryRequestId, + }), + connectionInfoAccess.getCurrentConnectionInfo() + ); openToast('query-ai-feedback-submitted', { variant: 'success', @@ -38,7 +44,7 @@ const useOnSubmitFeedback = (lastAIQueryRequestId: string | null) => { timeout: 10_000, }); }, - [logger, lastAIQueryRequestId, track] + [logger, lastAIQueryRequestId, track, connectionInfoAccess] ); }; diff --git a/packages/compass-query-bar/src/index.tsx b/packages/compass-query-bar/src/index.tsx index dba1c72d5e2..5caa176d90a 100644 --- a/packages/compass-query-bar/src/index.tsx +++ b/packages/compass-query-bar/src/index.tsx @@ -2,6 +2,7 @@ import React from 'react'; import { registerHadronPlugin } from 'hadron-app-registry'; import { activatePlugin } from './stores/query-bar-store'; import { + connectionInfoAccessLocator, dataServiceLocator, type DataServiceLocator, } from '@mongodb-js/compass-connections/provider'; @@ -52,6 +53,7 @@ const QueryBarPlugin = registerHadronPlugin( preferences: preferencesLocator, logger: createLoggerLocator('COMPASS-QUERY-BAR-UI'), track: createTelemetryLocator(), + connectionInfoAccess: connectionInfoAccessLocator, atlasAiService: atlasAiServiceLocator, atlasAuthService: atlasAuthServiceLocator, favoriteQueryStorageAccess: favoriteQueryStorageAccessLocator, diff --git a/packages/compass-query-bar/src/stores/ai-query-reducer.ts b/packages/compass-query-bar/src/stores/ai-query-reducer.ts index f7530728493..0c6c7c43ee3 100644 --- a/packages/compass-query-bar/src/stores/ai-query-reducer.ts +++ b/packages/compass-query-bar/src/stores/ai-query-reducer.ts @@ -16,6 +16,7 @@ import type { AtlasServiceError } from '@mongodb-js/atlas-service/renderer'; import type { Logger } from '@mongodb-js/compass-logging/provider'; import { mongoLogId } from '@mongodb-js/compass-logging/provider'; import type { TrackFunction } from '@mongodb-js/compass-telemetry'; +import type { ConnectionInfo } from '@mongodb-js/compass-connections/provider'; type AIQueryStatus = 'ready' | 'fetching' | 'success'; @@ -115,6 +116,7 @@ type FailedResponseTrackMessage = { log: Logger['log']; track: TrackFunction; requestId: string; + connectionInfo: ConnectionInfo; }; function trackAndLogFailed({ @@ -125,6 +127,7 @@ function trackAndLogFailed({ log, track, requestId, + connectionInfo, }: FailedResponseTrackMessage) { log.warn(mongoLogId(1_001_000_198), 'AIQuery', 'AI query request failed', { statusCode, @@ -133,13 +136,17 @@ function trackAndLogFailed({ errorCode, requestId, }); - track('AI Response Failed', () => ({ - editor_view_type: 'find', - error_name: errorName, - status_code: statusCode, - error_code: errorCode ?? '', - request_id: requestId, - })); + track( + 'AI Response Failed', + () => ({ + editor_view_type: 'find', + error_name: errorName, + status_code: statusCode, + error_code: errorCode ?? '', + request_id: requestId, + }), + connectionInfo + ); } export const runAIQuery = ( @@ -157,6 +164,7 @@ export const runAIQuery = ( preferences, atlasAiService, logger: { log }, + connectionInfoAccess, track, } ) => { @@ -165,12 +173,18 @@ export const runAIQuery = ( const abortController = new AbortController(); const { id: requestId, signal } = getAbortSignal(); - track('AI Prompt Submitted', () => ({ - editor_view_type: 'find', - user_input_length: userInput.length, - has_sample_documents: provideSampleDocuments, - request_id: requestId, - })); + const connectionInfo = connectionInfoAccess.getCurrentConnectionInfo(); + + track( + 'AI Prompt Submitted', + () => ({ + editor_view_type: 'find', + user_input_length: userInput.length, + has_sample_documents: provideSampleDocuments, + request_id: requestId, + }), + connectionInfo + ); const { aiQuery: { aiQueryRequestId: existingRequestId }, @@ -234,6 +248,7 @@ export const runAIQuery = ( log, track, requestId, + connectionInfo, }); // We're going to reset input state with this error, show the error in the // toast instead @@ -286,6 +301,7 @@ export const runAIQuery = ( log, track, requestId, + connectionInfo, }); dispatch({ type: AIQueryActionTypes.AIQueryFailed, @@ -314,6 +330,7 @@ export const runAIQuery = ( log, track, requestId, + connectionInfo, }); return; } @@ -326,6 +343,7 @@ export const runAIQuery = ( log, track, requestId, + connectionInfo, }); dispatch({ type: AIQueryActionTypes.AIQueryFailed, @@ -351,11 +369,15 @@ export const runAIQuery = ( shape: Object.keys(generatedFields), } ); - track('AI Response Generated', () => ({ - editor_view_type: 'find', - query_shape: Object.keys(generatedFields), - request_id: requestId, - })); + track( + 'AI Response Generated', + () => ({ + editor_view_type: 'find', + query_shape: Object.keys(generatedFields), + request_id: requestId, + }), + connectionInfo + ); dispatch({ type: AIQueryActionTypes.AIQuerySucceeded, diff --git a/packages/compass-query-bar/src/stores/query-bar-store.ts b/packages/compass-query-bar/src/stores/query-bar-store.ts index b6b1d6fecff..70a1dbcf532 100644 --- a/packages/compass-query-bar/src/stores/query-bar-store.ts +++ b/packages/compass-query-bar/src/stores/query-bar-store.ts @@ -7,7 +7,10 @@ import { import thunk from 'redux-thunk'; import type { AnyAction } from 'redux'; import type { ThunkAction, ThunkDispatch } from 'redux-thunk'; -import type { DataService } from '@mongodb-js/compass-connections/provider'; +import type { + ConnectionInfoAccess, + DataService, +} from '@mongodb-js/compass-connections/provider'; import { DEFAULT_FIELD_VALUES } from '../constants/query-bar-store'; import { mapQueryToFormFields } from '../utils/query'; import { @@ -45,6 +48,7 @@ type QueryBarServices = { preferences: PreferencesAccess; logger: Logger; track: TrackFunction; + connectionInfoAccess: ConnectionInfoAccess; atlasAuthService: AtlasAuthService; atlasAiService: AtlasAiService; favoriteQueryStorageAccess?: FavoriteQueryStorageAccess; @@ -78,6 +82,7 @@ export type QueryBarExtraArgs = { recentQueryStorage?: RecentQueryStorage; logger: Logger; track: TrackFunction; + connectionInfoAccess: ConnectionInfoAccess; atlasAiService: AtlasAiService; }; @@ -120,6 +125,7 @@ export function activatePlugin( preferences, logger, track, + connectionInfoAccess, atlasAuthService, atlasAiService, favoriteQueryStorageAccess, @@ -154,6 +160,7 @@ export function activatePlugin( preferences, logger, track, + connectionInfoAccess, atlasAiService, } ); From 3ce7b8643250c297434b9b14daba778219e7668f Mon Sep 17 00:00:00 2001 From: Paula Stachova Date: Wed, 26 Jun 2024 17:38:27 +0200 Subject: [PATCH 04/24] part 3 --- .../modules/pipeline-builder/pipeline-mode.ts | 7 +++++- .../src/stores/create-view.spec.ts | 3 ++- .../src/connection-info-provider.tsx | 25 +++++++++++++++++++ .../src/components/current-op-component.jsx | 14 ++++++++--- .../compass-telemetry/src/generic-track.ts | 8 +++--- packages/compass/src/app/utils/telemetry.ts | 9 ++++--- packages/databases-collections/src/index.ts | 7 +++++- .../src/modules/create-namespace.ts | 7 +++++- .../src/stores/create-namespace.ts | 2 ++ 9 files changed, 67 insertions(+), 15 deletions(-) diff --git a/packages/compass-aggregations/src/modules/pipeline-builder/pipeline-mode.ts b/packages/compass-aggregations/src/modules/pipeline-builder/pipeline-mode.ts index 7c368cdc784..c45390b7265 100644 --- a/packages/compass-aggregations/src/modules/pipeline-builder/pipeline-mode.ts +++ b/packages/compass-aggregations/src/modules/pipeline-builder/pipeline-mode.ts @@ -65,7 +65,11 @@ const reducer: Reducer = (state = INITIAL_STATE, action) => { export const changePipelineMode = ( newMode: PipelineMode ): PipelineBuilderThunkAction => { - return (dispatch, getState, { pipelineBuilder, track }) => { + return ( + dispatch, + getState, + { pipelineBuilder, track, connectionInfoAccess } + ) => { if (newMode === getState().pipelineBuilder.pipelineMode) { return; } @@ -94,6 +98,7 @@ export const changePipelineMode = ( track('Editor Type Changed', { num_stages, editor_view_type: mapPipelineModeToEditorViewType(getState()), + connectionInfoAccess, }); dispatch(updatePipelinePreview()); diff --git a/packages/compass-aggregations/src/stores/create-view.spec.ts b/packages/compass-aggregations/src/stores/create-view.spec.ts index e90bfe69351..6117a041a8c 100644 --- a/packages/compass-aggregations/src/stores/create-view.spec.ts +++ b/packages/compass-aggregations/src/stores/create-view.spec.ts @@ -2,6 +2,7 @@ import AppRegistry, { createActivateHelpers } from 'hadron-app-registry'; import { activateCreateViewPlugin } from './create-view'; import { expect } from 'chai'; import { + type ConnectionInfoAccess, ConnectionsManager, type DataService, } from '@mongodb-js/compass-connections/provider'; @@ -27,7 +28,7 @@ describe('CreateViewStore [Store]', function () { const track = () => {}; const connectionInfoAccess = { getCurrentConnectionInfo: () => ({ id: 'TEST' }), - }; + } as ConnectionInfoAccess; const createViewStub = Sinon.stub(); const dataService = { createView: createViewStub, diff --git a/packages/compass-connections/src/connection-info-provider.tsx b/packages/compass-connections/src/connection-info-provider.tsx index 0fa714dc9c2..588d1aea8f7 100644 --- a/packages/compass-connections/src/connection-info-provider.tsx +++ b/packages/compass-connections/src/connection-info-provider.tsx @@ -73,3 +73,28 @@ export const connectionInfoAccessLocator = createServiceLocator( useConnectionInfoAccess, 'connectionInfoAccessLocator' ); + +type FirstArgument = F extends (...args: [infer A, ...any]) => any + ? A + : F extends { new (...args: [infer A, ...any]): any } + ? A + : never; + +function withConnectionInfoAccess< + T extends ((...args: any[]) => any) | { new (...args: any[]): any } +>( + ReactComponent: T +): React.FunctionComponent, 'connectionInfoAccess'>> { + const WithTelemetry = ( + props: Omit, 'connectionInfoAccess'> & React.Attributes + ) => { + const connectionInfoAccess = useConnectionInfoAccess(); + return React.createElement(ReactComponent, { + ...props, + connectionInfoAccess, + }); + }; + return WithTelemetry; +} + +export { withConnectionInfoAccess }; diff --git a/packages/compass-serverstats/src/components/current-op-component.jsx b/packages/compass-serverstats/src/components/current-op-component.jsx index 5d0fd30e278..a17af94ee28 100644 --- a/packages/compass-serverstats/src/components/current-op-component.jsx +++ b/packages/compass-serverstats/src/components/current-op-component.jsx @@ -4,6 +4,9 @@ const PropTypes = require('prop-types'); const Actions = require('../actions'); const DBErrorStore = require('../stores/dberror-store'); const { withTelemetry } = require('@mongodb-js/compass-telemetry/provider'); +const { + withConnectionInfoAccess, +} = require('@mongodb-js/compass-connections/provider'); // const debug = require('debug')('mongodb-compass:server-stats:current-op-component'); @@ -97,7 +100,11 @@ class CurrentOpComponent extends React.Component { * @param {Object} data - The row data. */ showOperationDetails(data) { - this.props.track('CurrentOp showOperationDetails'); + this.props.track( + 'CurrentOp showOperationDetails', + {}, + this.props.connectionInfoAccess.getCurrentConnectionInfo() + ); Actions.showOperationDetails(data); } @@ -186,9 +193,10 @@ class CurrentOpComponent extends React.Component { CurrentOpComponent.propTypes = { store: PropTypes.any.isRequired, interval: PropTypes.number.isRequired, - track: PropTypes.any, + track: PropTypes.any.isRequired, + connectionInfoAccess: PropTypes.any.isRequired, }; CurrentOpComponent.displayName = 'CurrentOpComponent'; -module.exports = withTelemetry(CurrentOpComponent); +module.exports = withTelemetry(withConnectionInfoAccess(CurrentOpComponent)); diff --git a/packages/compass-telemetry/src/generic-track.ts b/packages/compass-telemetry/src/generic-track.ts index 4c2fce60e30..dd9a6805a88 100644 --- a/packages/compass-telemetry/src/generic-track.ts +++ b/packages/compass-telemetry/src/generic-track.ts @@ -62,10 +62,10 @@ export const createTrack = ({ parameters.connection_id = connectionInfo.id; } - console.log('TRACK', { - event, - connection_id: (parameters as { connection_id?: string }).connection_id, - }); + // console.log('TRACK', { + // event, + // connection_id: (parameters as { connection_id?: string }).connection_id, + // }); sendTrack(event, parameters || {}); }; diff --git a/packages/compass/src/app/utils/telemetry.ts b/packages/compass/src/app/utils/telemetry.ts index 96172df3cc9..1f10bf152f7 100644 --- a/packages/compass/src/app/utils/telemetry.ts +++ b/packages/compass/src/app/utils/telemetry.ts @@ -151,17 +151,18 @@ async function getConnectionData({ } export function trackConnectionAttemptEvent( - { favorite, lastUsed }: Pick, + connectionInfo: ConnectionInfo, { debug }: Logger, track: TrackFunction ): void { try { + const { favorite, lastUsed } = connectionInfo; const trackEvent = { is_favorite: Boolean(favorite), is_recent: Boolean(lastUsed && !favorite), is_new: !lastUsed, }; - track('Connection Attempt', trackEvent); + track('Connection Attempt', trackEvent, connectionInfo); } catch (error) { debug('trackConnectionAttemptEvent failed', error); } @@ -200,7 +201,7 @@ export function trackNewConnectionEvent( } export function trackConnectionFailedEvent( - connectionInfo: Pick | null, + connectionInfo: ConnectionInfo | null, connectionError: Error & Partial>, { debug }: Logger, track: TrackFunction @@ -216,7 +217,7 @@ export function trackConnectionFailedEvent( }; return trackEvent; }; - track('Connection Failed', callback); + track('Connection Failed', callback, connectionInfo ?? undefined); } catch (error) { debug('trackConnectionFailedEvent failed', error); } diff --git a/packages/databases-collections/src/index.ts b/packages/databases-collections/src/index.ts index 48a7ec84091..091f10f27a6 100644 --- a/packages/databases-collections/src/index.ts +++ b/packages/databases-collections/src/index.ts @@ -1,7 +1,10 @@ import { registerHadronPlugin } from 'hadron-app-registry'; import { createLoggerLocator } from '@mongodb-js/compass-logging/provider'; import { createTelemetryLocator } from '@mongodb-js/compass-telemetry/provider'; -import { connectionsManagerLocator } from '@mongodb-js/compass-connections/provider'; +import { + connectionInfoAccessLocator, + connectionsManagerLocator, +} from '@mongodb-js/compass-connections/provider'; import { mongoDBInstancesManagerLocator } from '@mongodb-js/compass-app-stores/provider'; import { CollectionsPlugin } from './collections-plugin'; import { @@ -40,6 +43,7 @@ export const CreateNamespacePlugin = registerHadronPlugin( logger: createLoggerLocator('COMPASS-CREATE-NAMESPACE-UI'), track: createTelemetryLocator(), connectionsManager: connectionsManagerLocator, + connectionInfoAccess: connectionInfoAccessLocator, instancesManager: mongoDBInstancesManagerLocator, workspaces: workspacesServiceLocator, } @@ -54,6 +58,7 @@ export const DropNamespacePlugin = registerHadronPlugin( { logger: createLoggerLocator('COMPASS-DROP-NAMESPACE-UI'), track: createTelemetryLocator(), + connectionInfoAccess: connectionInfoAccessLocator, connectionsManager: connectionsManagerLocator, } ); diff --git a/packages/databases-collections/src/modules/create-namespace.ts b/packages/databases-collections/src/modules/create-namespace.ts index 4ca74e8f4f0..9d3d8e59e97 100644 --- a/packages/databases-collections/src/modules/create-namespace.ts +++ b/packages/databases-collections/src/modules/create-namespace.ts @@ -359,6 +359,7 @@ export const createNamespace = ( connectionsManager, logger: { debug }, track, + connectionInfoAccess, workspaces, } ) => { @@ -391,7 +392,11 @@ export const createNamespace = ( expires: !!data.options.expireAfterSeconds, }; - track(`${kind} Created`, trackEvent); + track( + `${kind} Created`, + trackEvent, + connectionInfoAccess.getCurrentConnectionInfo() + ); globalAppRegistry.emit('collection-created', namespace, { connectionId, diff --git a/packages/databases-collections/src/stores/create-namespace.ts b/packages/databases-collections/src/stores/create-namespace.ts index db0385e759c..714fb06ce5d 100644 --- a/packages/databases-collections/src/stores/create-namespace.ts +++ b/packages/databases-collections/src/stores/create-namespace.ts @@ -1,5 +1,6 @@ import type AppRegistry from 'hadron-app-registry'; import { + type ConnectionInfoAccess, ConnectionsManagerEvents, type ConnectionsManager, type DataService, @@ -33,6 +34,7 @@ export type CreateNamespaceServices = { globalAppRegistry: AppRegistry; logger: Logger; track: TrackFunction; + connectionInfoAccess: ConnectionInfoAccess; workspaces: ReturnType; }; From b5026f6d05ed2a9fb963c7a47a8c041976101ee0 Mon Sep 17 00:00:00 2001 From: Paula Stachova Date: Wed, 26 Jun 2024 18:05:09 +0200 Subject: [PATCH 05/24] part 4 - use connectionRepository in the plugins --- packages/compass-aggregations/src/index.ts | 3 ++- .../src/modules/create-view/index.ts | 4 ++-- .../compass-aggregations/src/stores/create-view.ts | 8 ++++---- .../src/components/connections-provider.tsx | 6 ++++++ packages/compass-import-export/src/index.ts | 2 ++ packages/databases-collections/src/index.ts | 10 ++++------ .../src/modules/create-namespace.ts | 4 ++-- .../src/stores/create-namespace.ts | 4 ++-- 8 files changed, 24 insertions(+), 17 deletions(-) diff --git a/packages/compass-aggregations/src/index.ts b/packages/compass-aggregations/src/index.ts index e073412cc8f..7c4d12f05c4 100644 --- a/packages/compass-aggregations/src/index.ts +++ b/packages/compass-aggregations/src/index.ts @@ -27,6 +27,7 @@ import { preferencesLocator } from 'compass-preferences-model/provider'; import { atlasAuthServiceLocator } from '@mongodb-js/atlas-service/provider'; import { atlasAiServiceLocator } from '@mongodb-js/compass-generative-ai/provider'; import { pipelineStorageLocator } from '@mongodb-js/my-queries-storage/provider'; +import { connectionRepositoryLocator } from '@mongodb-js/compass-connections/dist/components/connections-provider'; export const CompassAggregationsHadronPlugin = registerHadronPlugin( { @@ -67,9 +68,9 @@ export const CreateViewPlugin = registerHadronPlugin( }, { connectionsManager: connectionsManagerLocator, + connectionRepository: connectionRepositoryLocator, logger: createLoggerLocator('COMPASS-CREATE-VIEW-UI'), track: createTelemetryLocator(), - connectionInfoAccess: connectionInfoAccessLocator, workspaces: workspacesServiceLocator, } ); diff --git a/packages/compass-aggregations/src/modules/create-view/index.ts b/packages/compass-aggregations/src/modules/create-view/index.ts index 93ba92cf2aa..0b6b3e5c736 100644 --- a/packages/compass-aggregations/src/modules/create-view/index.ts +++ b/packages/compass-aggregations/src/modules/create-view/index.ts @@ -205,8 +205,8 @@ export const createView = (): CreateViewThunkAction> => { { globalAppRegistry, connectionsManager, + connectionRepository, track, - connectionInfoAccess, workspaces, } ) => { @@ -236,7 +236,7 @@ export const createView = (): CreateViewThunkAction> => { track( 'Aggregation Saved As View', { num_stages: viewPipeline.length }, - connectionInfoAccess.getCurrentConnectionInfo() + connectionRepository.getConnectionInfoById(connectionId) ); globalAppRegistry.emit('view-created', ns, { connectionId, diff --git a/packages/compass-aggregations/src/stores/create-view.ts b/packages/compass-aggregations/src/stores/create-view.ts index b00b2d75390..1e2be55519d 100644 --- a/packages/compass-aggregations/src/stores/create-view.ts +++ b/packages/compass-aggregations/src/stores/create-view.ts @@ -8,7 +8,7 @@ import type AppRegistry from 'hadron-app-registry'; import type { Logger } from '@mongodb-js/compass-logging/provider'; import type { WorkspacesService } from '@mongodb-js/compass-workspaces/provider'; import type { - ConnectionInfoAccess, + ConnectionRepository, ConnectionsManager, } from '@mongodb-js/compass-connections/provider'; import type { ActivateHelpers } from 'hadron-app-registry'; @@ -17,9 +17,9 @@ import type { TrackFunction } from '@mongodb-js/compass-telemetry'; type CreateViewServices = { globalAppRegistry: AppRegistry; connectionsManager: ConnectionsManager; + connectionRepository: ConnectionRepository; logger: Logger; track: TrackFunction; - connectionInfoAccess: ConnectionInfoAccess; workspaces: WorkspacesService; }; @@ -54,9 +54,9 @@ export function activateCreateViewPlugin( { globalAppRegistry, connectionsManager, + connectionRepository, logger, track, - connectionInfoAccess, workspaces, }: CreateViewServices, { on, cleanup }: ActivateHelpers @@ -64,9 +64,9 @@ export function activateCreateViewPlugin( const store = configureStore({ globalAppRegistry, connectionsManager, + connectionRepository, logger, track, - connectionInfoAccess, workspaces, }); diff --git a/packages/compass-connections/src/components/connections-provider.tsx b/packages/compass-connections/src/components/connections-provider.tsx index 83b3f9a4cb4..38f70699cec 100644 --- a/packages/compass-connections/src/components/connections-provider.tsx +++ b/packages/compass-connections/src/components/connections-provider.tsx @@ -2,6 +2,7 @@ import React, { useContext, useEffect, useRef } from 'react'; import { useConnectionsManagerContext } from '../provider'; import { useConnections as useConnectionsStore } from '../stores/connections-store'; import { useConnectionRepository as useConnectionsRepositoryState } from '../hooks/use-connection-repository'; +import { createServiceLocator } from 'hadron-app-registry'; const ConnectionsStoreContext = React.createContext; export { areConnectionsEqual } from '../hooks/use-connection-repository'; diff --git a/packages/compass-import-export/src/index.ts b/packages/compass-import-export/src/index.ts index 88022bfc490..49dc80d7959 100644 --- a/packages/compass-import-export/src/index.ts +++ b/packages/compass-import-export/src/index.ts @@ -8,6 +8,7 @@ import { workspacesServiceLocator } from '@mongodb-js/compass-workspaces/provide import { preferencesLocator } from 'compass-preferences-model/provider'; import { createLoggerLocator } from '@mongodb-js/compass-logging/provider'; import { createTelemetryLocator } from '@mongodb-js/compass-telemetry/provider'; +import { connectionRepositoryLocator } from '@mongodb-js/compass-connections/dist/components/connections-provider'; /** * The import plugin. @@ -20,6 +21,7 @@ export const ImportPlugin = registerHadronPlugin( }, { connectionsManager: connectionsManagerLocator, + connectionRepository: connectionRepositoryLocator, workspaces: workspacesServiceLocator, preferences: preferencesLocator, logger: createLoggerLocator('COMPASS-IMPORT-UI'), diff --git a/packages/databases-collections/src/index.ts b/packages/databases-collections/src/index.ts index 091f10f27a6..d74fde1cc73 100644 --- a/packages/databases-collections/src/index.ts +++ b/packages/databases-collections/src/index.ts @@ -1,10 +1,7 @@ import { registerHadronPlugin } from 'hadron-app-registry'; import { createLoggerLocator } from '@mongodb-js/compass-logging/provider'; import { createTelemetryLocator } from '@mongodb-js/compass-telemetry/provider'; -import { - connectionInfoAccessLocator, - connectionsManagerLocator, -} from '@mongodb-js/compass-connections/provider'; +import { connectionsManagerLocator } from '@mongodb-js/compass-connections/provider'; import { mongoDBInstancesManagerLocator } from '@mongodb-js/compass-app-stores/provider'; import { CollectionsPlugin } from './collections-plugin'; import { @@ -22,6 +19,7 @@ import { favoriteQueryStorageAccessLocator, pipelineStorageLocator, } from '@mongodb-js/my-queries-storage/provider'; +import { connectionRepositoryLocator } from '@mongodb-js/compass-connections/dist/components/connections-provider'; export const CollectionsWorkspaceTab: WorkspaceComponent<'Collections'> = { name: 'Collections' as const, @@ -43,7 +41,7 @@ export const CreateNamespacePlugin = registerHadronPlugin( logger: createLoggerLocator('COMPASS-CREATE-NAMESPACE-UI'), track: createTelemetryLocator(), connectionsManager: connectionsManagerLocator, - connectionInfoAccess: connectionInfoAccessLocator, + connectionRepository: connectionRepositoryLocator, instancesManager: mongoDBInstancesManagerLocator, workspaces: workspacesServiceLocator, } @@ -58,7 +56,7 @@ export const DropNamespacePlugin = registerHadronPlugin( { logger: createLoggerLocator('COMPASS-DROP-NAMESPACE-UI'), track: createTelemetryLocator(), - connectionInfoAccess: connectionInfoAccessLocator, + connectionRepository: connectionRepositoryLocator, connectionsManager: connectionsManagerLocator, } ); diff --git a/packages/databases-collections/src/modules/create-namespace.ts b/packages/databases-collections/src/modules/create-namespace.ts index 9d3d8e59e97..957a0d09a13 100644 --- a/packages/databases-collections/src/modules/create-namespace.ts +++ b/packages/databases-collections/src/modules/create-namespace.ts @@ -357,9 +357,9 @@ export const createNamespace = ( { globalAppRegistry, connectionsManager, + connectionRepository, logger: { debug }, track, - connectionInfoAccess, workspaces, } ) => { @@ -395,7 +395,7 @@ export const createNamespace = ( track( `${kind} Created`, trackEvent, - connectionInfoAccess.getCurrentConnectionInfo() + connectionRepository.getConnectionInfoById(connectionId) ); globalAppRegistry.emit('collection-created', namespace, { diff --git a/packages/databases-collections/src/stores/create-namespace.ts b/packages/databases-collections/src/stores/create-namespace.ts index 714fb06ce5d..fc3fdca228b 100644 --- a/packages/databases-collections/src/stores/create-namespace.ts +++ b/packages/databases-collections/src/stores/create-namespace.ts @@ -1,9 +1,9 @@ import type AppRegistry from 'hadron-app-registry'; import { - type ConnectionInfoAccess, ConnectionsManagerEvents, type ConnectionsManager, type DataService, + type ConnectionRepository, } from '@mongodb-js/compass-connections/provider'; import type { MongoDBInstance } from 'mongodb-instance-model'; import type { Logger } from '@mongodb-js/compass-logging'; @@ -30,11 +30,11 @@ type NS = ReturnType; export type CreateNamespaceServices = { connectionsManager: ConnectionsManager; + connectionRepository: ConnectionRepository; instancesManager: MongoDBInstancesManager; globalAppRegistry: AppRegistry; logger: Logger; track: TrackFunction; - connectionInfoAccess: ConnectionInfoAccess; workspaces: ReturnType; }; From 2e3ece9fb6c02c5dbaa9bc35408fc3a8056b3d39 Mon Sep 17 00:00:00 2001 From: Paula Stachova Date: Wed, 26 Jun 2024 18:24:58 +0200 Subject: [PATCH 06/24] part 5 --- .../src/modules/export.ts | 88 +++++++++++-------- .../src/stores/export-store.ts | 8 +- .../query-history-button-popover.tsx | 7 +- .../components/query-history/recent-list.tsx | 21 +++-- .../src/components/query-option.tsx | 10 ++- 5 files changed, 88 insertions(+), 46 deletions(-) diff --git a/packages/compass-import-export/src/modules/export.ts b/packages/compass-import-export/src/modules/export.ts index 96ee1b4e2dd..ac2de382fe9 100644 --- a/packages/compass-import-export/src/modules/export.ts +++ b/packages/compass-import-export/src/modules/export.ts @@ -133,11 +133,15 @@ type OpenExportAction = { export const openExport = ( exportOptions: Omit ): ExportThunkAction => { - return (dispatch, _getState, { track }) => { - track('Export Opened', { - type: exportOptions.aggregation ? 'aggregation' : 'query', - origin: exportOptions.origin, - }); + return (dispatch, _getState, { track, connectionRepository }) => { + track( + 'Export Opened', + { + type: exportOptions.aggregation ? 'aggregation' : 'query', + origin: exportOptions.origin, + }, + connectionRepository.getConnectionInfoById(exportOptions.connectionId) + ); dispatch({ type: ExportActionTypes.OpenExport, ...exportOptions, @@ -350,7 +354,13 @@ export const runExport = ({ return async ( dispatch, getState, - { connectionsManager, preferences, track, logger: { log, mongoLogId } } + { + connectionsManager, + connectionRepository, + preferences, + track, + logger: { log, mongoLogId }, + } ) => { let outputWriteStream: fs.WriteStream; try { @@ -515,36 +525,42 @@ export const runExport = ({ const aborted = !!( exportAbortController.signal.aborted || exportResult?.aborted ); - track('Export Completed', { - type: aggregation ? 'aggregation' : 'query', - all_docs: exportFullCollection, - has_projection: - exportFullCollection || aggregation || !_query - ? undefined - : queryHasProjection(_query), - field_option: - exportFullCollection || - aggregation || - (_query && queryHasProjection(_query)) - ? undefined - : selectedFieldOption, - file_type: fileType, - json_format: fileType === 'json' ? jsonFormatVariant : undefined, - field_count: - selectedFieldOption === 'select-fields' - ? fieldsIncludedCount - : undefined, - fields_added_count: - selectedFieldOption === 'select-fields' ? fieldsAddedCount : undefined, - fields_not_selected_count: - selectedFieldOption === 'select-fields' - ? fieldsExcludedCount - : undefined, - number_of_docs: exportResult?.docsWritten, - success: exportSucceeded, - stopped: aborted, - duration: Date.now() - startTime, - }); + track( + 'Export Completed', + { + type: aggregation ? 'aggregation' : 'query', + all_docs: exportFullCollection, + has_projection: + exportFullCollection || aggregation || !_query + ? undefined + : queryHasProjection(_query), + field_option: + exportFullCollection || + aggregation || + (_query && queryHasProjection(_query)) + ? undefined + : selectedFieldOption, + file_type: fileType, + json_format: fileType === 'json' ? jsonFormatVariant : undefined, + field_count: + selectedFieldOption === 'select-fields' + ? fieldsIncludedCount + : undefined, + fields_added_count: + selectedFieldOption === 'select-fields' + ? fieldsAddedCount + : undefined, + fields_not_selected_count: + selectedFieldOption === 'select-fields' + ? fieldsExcludedCount + : undefined, + number_of_docs: exportResult?.docsWritten, + success: exportSucceeded, + stopped: aborted, + duration: Date.now() - startTime, + }, + connectionRepository.getConnectionInfoById(connectionId) + ); if (!exportSucceeded) { return; diff --git a/packages/compass-import-export/src/stores/export-store.ts b/packages/compass-import-export/src/stores/export-store.ts index bc09eaeb269..b7422e15f53 100644 --- a/packages/compass-import-export/src/stores/export-store.ts +++ b/packages/compass-import-export/src/stores/export-store.ts @@ -7,7 +7,10 @@ import { closeExport, exportReducer, openExport } from '../modules/export'; import type { PreferencesAccess } from 'compass-preferences-model'; import type { Logger } from '@mongodb-js/compass-logging/provider'; import type { ActivateHelpers } from 'hadron-app-registry'; -import type { ConnectionsManager } from '@mongodb-js/compass-connections/provider'; +import type { + ConnectionRepository, + ConnectionsManager, +} from '@mongodb-js/compass-connections/provider'; import type { TrackFunction } from '@mongodb-js/compass-telemetry'; export function configureStore(services: ExportPluginServices) { @@ -26,6 +29,7 @@ export type RootExportState = ReturnType< export type ExportPluginServices = { globalAppRegistry: AppRegistry; connectionsManager: ConnectionsManager; + connectionRepository: ConnectionRepository; preferences: PreferencesAccess; logger: Logger; track: TrackFunction; @@ -55,6 +59,7 @@ export function activatePlugin( { globalAppRegistry, connectionsManager, + connectionRepository, preferences, logger, track, @@ -64,6 +69,7 @@ export function activatePlugin( const store = configureStore({ globalAppRegistry, connectionsManager, + connectionRepository, preferences, logger, track, diff --git a/packages/compass-query-bar/src/components/query-history-button-popover.tsx b/packages/compass-query-bar/src/components/query-history-button-popover.tsx index 5cd780239eb..3c6295ca91f 100644 --- a/packages/compass-query-bar/src/components/query-history-button-popover.tsx +++ b/packages/compass-query-bar/src/components/query-history-button-popover.tsx @@ -14,6 +14,7 @@ import { type TrackFunction, } from '@mongodb-js/compass-telemetry/provider'; import { fetchSavedQueries } from '../stores/query-bar-reducer'; +import { useConnectionInfoAccess } from '@mongodb-js/compass-connections/provider'; const openQueryHistoryButtonStyles = css( { @@ -42,13 +43,15 @@ const QueryHistoryButtonPopover = ({ onOpenPopover: () => void; }) => { const [isOpen, setIsOpen] = React.useState(false); + const connectionInfoAccess = useConnectionInfoAccess(); useTrackOnChange( (track: TrackFunction) => { + const connectionInfo = connectionInfoAccess.getCurrentConnectionInfo(); if (isOpen) { - track('Query History Opened'); + track('Query History Opened', {}, connectionInfo); } else { - track('Query History Closed'); + track('Query History Closed', {}, connectionInfo); } }, [isOpen], diff --git a/packages/compass-query-bar/src/components/query-history/recent-list.tsx b/packages/compass-query-bar/src/components/query-history/recent-list.tsx index 415dd07cfec..16b525e7e45 100644 --- a/packages/compass-query-bar/src/components/query-history/recent-list.tsx +++ b/packages/compass-query-bar/src/components/query-history/recent-list.tsx @@ -23,6 +23,7 @@ import { SaveQueryForm } from './save-query-form'; import { formatQuery, copyToClipboard, getQueryAttributes } from '../../utils'; import type { BaseQuery } from '../../constants/query-properties'; import { useTelemetry } from '@mongodb-js/compass-telemetry/provider'; +import { useConnectionInfoAccess } from '@mongodb-js/compass-connections/provider'; type RecentActions = { onFavorite: (query: RecentQuery, name: string) => Promise; @@ -43,6 +44,7 @@ const RecentItem = ({ isReadonly: boolean; }) => { const track = useTelemetry(); + const connectionInfoAccess = useConnectionInfoAccess(); const readOnlyCompass = usePreference('readOnly'); const isUpdateQuery = !!query.update; const isDisabled = isUpdateQuery && (isReadonly || readOnlyCompass); @@ -61,9 +63,13 @@ const RecentItem = ({ onUpdateRecentChoosen(); } - track('Query History Recent Used', { - isUpdateQuery, - }); + track( + 'Query History Recent Used', + { + isUpdateQuery, + }, + connectionInfoAccess.getCurrentConnectionInfo() + ); onApply(attributes); }, [ isDisabled, @@ -72,6 +78,7 @@ const RecentItem = ({ onApply, attributes, onUpdateRecentChoosen, + connectionInfoAccess, ]); const onCardClick = useCallback( @@ -88,10 +95,14 @@ const RecentItem = ({ const onSaveQuery = useCallback( (name: string) => { - track('Query History Favorite Added', { isUpdateQuery }); + track( + 'Query History Favorite Added', + { isUpdateQuery }, + connectionInfoAccess.getCurrentConnectionInfo() + ); void onFavorite(query, name); }, - [track, isUpdateQuery, onFavorite, query] + [track, isUpdateQuery, onFavorite, query, connectionInfoAccess] ); return ( diff --git a/packages/compass-query-bar/src/components/query-option.tsx b/packages/compass-query-bar/src/components/query-option.tsx index 9aac56e458c..bf79d36d9ed 100644 --- a/packages/compass-query-bar/src/components/query-option.tsx +++ b/packages/compass-query-bar/src/components/query-option.tsx @@ -17,6 +17,7 @@ import { changeField } from '../stores/query-bar-reducer'; import type { QueryProperty } from '../constants/query-properties'; import type { RootState } from '../stores/query-bar-store'; import { useTelemetry } from '@mongodb-js/compass-telemetry/provider'; +import { useConnectionInfoAccess } from '@mongodb-js/compass-connections/provider'; const queryOptionStyles = css({ display: 'flex', @@ -122,6 +123,7 @@ const QueryOption: React.FunctionComponent = ({ disabled = false, }) => { const track = useTelemetry(); + const connectionInfoAccess = useConnectionInfoAccess(); const darkMode = useDarkMode(); const editorInitialValueRef = useRef(value); const editorCurrentValueRef = useRef(value); @@ -146,10 +148,14 @@ const QueryOption: React.FunctionComponent = ({ editorCurrentValueRef.current !== editorInitialValueRef.current && (editorInitialValueRef.current || editorCurrentValueRef.current !== '{}') ) { - track('Query Edited', { option_name: name }); + track( + 'Query Edited', + { option_name: name }, + connectionInfoAccess.getCurrentConnectionInfo() + ); editorInitialValueRef.current = editorCurrentValueRef.current; } - }, [track, name]); + }, [track, name, connectionInfoAccess]); return (
Date: Thu, 27 Jun 2024 13:52:29 +0200 Subject: [PATCH 07/24] part 6 --- packages/compass-aggregations/src/index.ts | 2 +- packages/compass-connections/src/provider.ts | 1 + .../src/components/crud-toolbar.tsx | 10 ++- packages/compass-import-export/src/index.ts | 2 +- .../src/modules/import.ts | 82 ++++++++++++------- .../src/stores/import-store.ts | 8 +- .../create-index-modal/create-index-modal.tsx | 15 +++- packages/compass-indexes/src/index.ts | 2 + .../src/modules/create-index/index.ts | 8 +- packages/compass-indexes/src/modules/index.ts | 2 + .../src/modules/search-indexes.ts | 38 ++++++--- .../src/stores/create-index.ts | 18 +++- .../query-history/favorite-list.tsx | 33 +++++--- .../src/components/query-history/index.tsx | 7 +- packages/compass-telemetry/src/events.ts | 6 +- packages/databases-collections/src/index.ts | 2 +- 16 files changed, 162 insertions(+), 74 deletions(-) diff --git a/packages/compass-aggregations/src/index.ts b/packages/compass-aggregations/src/index.ts index 7c4d12f05c4..8644a7dfcfd 100644 --- a/packages/compass-aggregations/src/index.ts +++ b/packages/compass-aggregations/src/index.ts @@ -27,7 +27,7 @@ import { preferencesLocator } from 'compass-preferences-model/provider'; import { atlasAuthServiceLocator } from '@mongodb-js/atlas-service/provider'; import { atlasAiServiceLocator } from '@mongodb-js/compass-generative-ai/provider'; import { pipelineStorageLocator } from '@mongodb-js/my-queries-storage/provider'; -import { connectionRepositoryLocator } from '@mongodb-js/compass-connections/dist/components/connections-provider'; +import { connectionRepositoryLocator } from '@mongodb-js/compass-connections/provider'; export const CompassAggregationsHadronPlugin = registerHadronPlugin( { diff --git a/packages/compass-connections/src/provider.ts b/packages/compass-connections/src/provider.ts index 890d4a3d4ee..d6bf28fd8e7 100644 --- a/packages/compass-connections/src/provider.ts +++ b/packages/compass-connections/src/provider.ts @@ -90,6 +90,7 @@ export { type ConnectionRepository, useConnectionRepository, areConnectionsEqual, + connectionRepositoryLocator, } from './components/connections-provider'; export * from './connection-info-provider'; diff --git a/packages/compass-crud/src/components/crud-toolbar.tsx b/packages/compass-crud/src/components/crud-toolbar.tsx index 755122f89d7..eb428ebce6f 100644 --- a/packages/compass-crud/src/components/crud-toolbar.tsx +++ b/packages/compass-crud/src/components/crud-toolbar.tsx @@ -19,6 +19,7 @@ import { usePreference } from 'compass-preferences-model/provider'; import UpdateMenu from './update-data-menu'; import DeleteMenu from './delete-data-menu'; import { QueryBar } from '@mongodb-js/compass-query-bar'; +import { useConnectionInfoAccess } from '@mongodb-js/compass-connections/provider'; const crudQueryBarStyles = css({ width: '100%', @@ -139,6 +140,7 @@ const CrudToolbar: React.FunctionComponent = ({ querySkip, }) => { const track = useTelemetry(); + const connectionInfoAccess = useConnectionInfoAccess(); const isImportExportEnabled = usePreference('enableImportExport'); const displayedDocumentCount = useMemo( @@ -147,9 +149,13 @@ const CrudToolbar: React.FunctionComponent = ({ ); const onClickRefreshDocuments = useCallback(() => { - track('Query Results Refreshed'); + track( + 'Query Results Refreshed', + {}, + connectionInfoAccess.getCurrentConnectionInfo() + ); refreshDocuments(); - }, [refreshDocuments, track]); + }, [refreshDocuments, track, connectionInfoAccess]); const prevButtonDisabled = useMemo(() => page === 0, [page]); const nextButtonDisabled = useMemo( diff --git a/packages/compass-import-export/src/index.ts b/packages/compass-import-export/src/index.ts index 49dc80d7959..27882ec1170 100644 --- a/packages/compass-import-export/src/index.ts +++ b/packages/compass-import-export/src/index.ts @@ -8,7 +8,7 @@ import { workspacesServiceLocator } from '@mongodb-js/compass-workspaces/provide import { preferencesLocator } from 'compass-preferences-model/provider'; import { createLoggerLocator } from '@mongodb-js/compass-logging/provider'; import { createTelemetryLocator } from '@mongodb-js/compass-telemetry/provider'; -import { connectionRepositoryLocator } from '@mongodb-js/compass-connections/dist/components/connections-provider'; +import { connectionRepositoryLocator } from '@mongodb-js/compass-connections/provider'; /** * The import plugin. diff --git a/packages/compass-import-export/src/modules/import.ts b/packages/compass-import-export/src/modules/import.ts index 8d3e140f32a..66ea5018b59 100644 --- a/packages/compass-import-export/src/modules/import.ts +++ b/packages/compass-import-export/src/modules/import.ts @@ -191,6 +191,7 @@ export const startImport = (): ImportThunkAction> => { getState, { connectionsManager, + connectionRepository, globalAppRegistry: appRegistry, workspaces, track, @@ -216,6 +217,9 @@ export const startImport = (): ImportThunkAction> => { }, } = getState(); + const connectionInfo = + connectionRepository.getConnectionInfoById(connectionId); + const ignoreBlanks = ignoreBlanks_ && fileType === FILE_TYPES.CSV; const fileSize = fileStats?.size || 0; const fields: Record = {}; @@ -351,18 +355,22 @@ export const startImport = (): ImportThunkAction> => { progressCallback.flush(); } catch (err: any) { - track('Import Completed', { - duration: Date.now() - startTime, - delimiter: fileType === 'csv' ? delimiter ?? ',' : undefined, - newline: fileType === 'csv' ? newline : undefined, - file_type: fileType, - all_fields: exclude.length === 0, - stop_on_error_selected: stopOnErrors, - number_of_docs: err.result.docsWritten, - success: !err, - aborted: abortSignal.aborted, - ignore_empty_strings: fileType === 'csv' ? ignoreBlanks : undefined, - }); + track( + 'Import Completed', + { + duration: Date.now() - startTime, + delimiter: fileType === 'csv' ? delimiter ?? ',' : undefined, + newline: fileType === 'csv' ? newline : undefined, + file_type: fileType, + all_fields: exclude.length === 0, + stop_on_error_selected: stopOnErrors, + number_of_docs: err.result.docsWritten, + success: !err, + aborted: abortSignal.aborted, + ignore_empty_strings: fileType === 'csv' ? ignoreBlanks : undefined, + }, + connectionInfo + ); log.error(mongoLogId(1001000081), 'Import', 'Import failed', { ns, @@ -381,18 +389,22 @@ export const startImport = (): ImportThunkAction> => { errorLogWriteStream?.close(); } - track('Import Completed', { - duration: Date.now() - startTime, - delimiter: fileType === 'csv' ? delimiter ?? ',' : undefined, - newline: fileType === 'csv' ? newline : undefined, - file_type: fileType, - all_fields: exclude.length === 0, - stop_on_error_selected: stopOnErrors, - number_of_docs: result.docsWritten, - success: true, - aborted: result.aborted, - ignore_empty_strings: fileType === 'csv' ? ignoreBlanks : undefined, - }); + track( + 'Import Completed', + { + duration: Date.now() - startTime, + delimiter: fileType === 'csv' ? delimiter ?? ',' : undefined, + newline: fileType === 'csv' ? newline : undefined, + file_type: fileType, + all_fields: exclude.length === 0, + stop_on_error_selected: stopOnErrors, + number_of_docs: result.docsWritten, + success: true, + aborted: result.aborted, + ignore_empty_strings: fileType === 'csv' ? ignoreBlanks : undefined, + }, + connectionInfo + ); log.info(mongoLogId(1001000082), 'Import', 'Import completed', { ns, @@ -403,9 +415,13 @@ export const startImport = (): ImportThunkAction> => { const openErrorLogFilePathActionHandler = errorLogFilePath ? () => { if (errorLogFilePath) { - track('Import Error Log Opened', { - errorCount: errors.length, - }); + track( + 'Import Error Log Opened', + { + errorCount: errors.length, + }, + connectionInfo + ); void openFile(errorLogFilePath); } } @@ -855,7 +871,7 @@ export const openImport = ({ namespace: string; origin: 'menu' | 'crud-toolbar' | 'empty-state'; }): ImportThunkAction => { - return (dispatch, getState, { track }) => { + return (dispatch, getState, { track, connectionRepository }) => { const { status } = getState().import; if (status === 'STARTED') { dispatch({ @@ -863,9 +879,13 @@ export const openImport = ({ }); return; } - track('Import Opened', { - origin, - }); + track( + 'Import Opened', + { + origin, + }, + connectionRepository.getConnectionInfoById(connectionId) + ); dispatch({ type: OPEN, namespace, connectionId }); }; }; diff --git a/packages/compass-import-export/src/stores/import-store.ts b/packages/compass-import-export/src/stores/import-store.ts index d692f362a87..31fef8f3a61 100644 --- a/packages/compass-import-export/src/stores/import-store.ts +++ b/packages/compass-import-export/src/stores/import-store.ts @@ -6,7 +6,10 @@ import thunk from 'redux-thunk'; import { cancelImport, importReducer, openImport } from '../modules/import'; import type { WorkspacesService } from '@mongodb-js/compass-workspaces/provider'; import type { Logger } from '@mongodb-js/compass-logging/provider'; -import type { ConnectionsManager } from '@mongodb-js/compass-connections/provider'; +import type { + ConnectionRepository, + ConnectionsManager, +} from '@mongodb-js/compass-connections/provider'; import type { ActivateHelpers } from 'hadron-app-registry'; import type { TrackFunction } from '@mongodb-js/compass-telemetry'; @@ -16,6 +19,7 @@ export type ImportPluginServices = { logger: Logger; track: TrackFunction; connectionsManager: ConnectionsManager; + connectionRepository: ConnectionRepository; }; export function configureStore(services: ImportPluginServices) { @@ -52,6 +56,7 @@ export function activatePlugin( { globalAppRegistry, connectionsManager, + connectionRepository, workspaces, logger, track, @@ -64,6 +69,7 @@ export function activatePlugin( logger, track, connectionsManager, + connectionRepository, }); addCleanup(() => { diff --git a/packages/compass-indexes/src/components/create-index-modal/create-index-modal.tsx b/packages/compass-indexes/src/components/create-index-modal/create-index-modal.tsx index c4a5e3d9133..265ba1ebce6 100644 --- a/packages/compass-indexes/src/components/create-index-modal/create-index-modal.tsx +++ b/packages/compass-indexes/src/components/create-index-modal/create-index-modal.tsx @@ -23,6 +23,7 @@ import { useTrackOnChange, type TrackFunction, } from '@mongodb-js/compass-telemetry/provider'; +import { useConnectionInfoAccess } from '@mongodb-js/compass-connections/provider'; type CreateIndexModalProps = React.ComponentProps & { isVisible: boolean; @@ -44,6 +45,7 @@ function CreateIndexModal({ closeCreateIndexModal, ...props }: CreateIndexModalProps) { + const connectionInfoAccess = useConnectionInfoAccess(); const onSetOpen = useCallback( (open) => { if (!open) { @@ -55,11 +57,16 @@ function CreateIndexModal({ useTrackOnChange( (track: TrackFunction) => { + const connectionInfo = connectionInfoAccess.getCurrentConnectionInfo(); if (isVisible) { - track('Screen', { name: 'create_index_modal' }); - track('Index Create Opened', { - atlas_search: false, - }); + track('Screen', { name: 'create_index_modal' }, connectionInfo); + track( + 'Index Create Opened', + { + atlas_search: false, + }, + connectionInfo + ); } }, [isVisible], diff --git a/packages/compass-indexes/src/index.ts b/packages/compass-indexes/src/index.ts index 3b9e4420b2b..a71641470e1 100644 --- a/packages/compass-indexes/src/index.ts +++ b/packages/compass-indexes/src/index.ts @@ -13,6 +13,7 @@ import { } from './stores/store'; import Indexes from './components/indexes/indexes'; import { + connectionInfoAccessLocator, dataServiceLocator, type DataServiceLocator, } from '@mongodb-js/compass-connections/provider'; @@ -63,6 +64,7 @@ export const CreateIndexPlugin = registerHadronPlugin( dataService: dataServiceLocator as DataServiceLocator<'createIndex'>, logger: createLoggerLocator('COMPASS-INDEXES-UI'), track: createTelemetryLocator(), + connectionInfoAccess: connectionInfoAccessLocator, } ); diff --git a/packages/compass-indexes/src/modules/create-index/index.ts b/packages/compass-indexes/src/modules/create-index/index.ts index efb1cb615c7..41d2c4aa91b 100644 --- a/packages/compass-indexes/src/modules/create-index/index.ts +++ b/packages/compass-indexes/src/modules/create-index/index.ts @@ -106,7 +106,7 @@ export const createIndex = (): CreateIndexThunkAction> => { return async ( dispatch, getState, - { dataService, localAppRegistry, track } + { dataService, localAppRegistry, track, connectionInfoAccess } ) => { const state = getState(); const spec = {} as CreateIndexSpec; @@ -243,7 +243,11 @@ export const createIndex = (): CreateIndexThunkAction> => { try { await dataService.createIndex(ns, spec as IndexSpecification, options); - track('Index Created', trackEvent); + track( + 'Index Created', + trackEvent, + connectionInfoAccess.getCurrentConnectionInfo() + ); dispatch(resetForm()); dispatch(toggleInProgress(false)); dispatch(toggleIsVisible(false)); diff --git a/packages/compass-indexes/src/modules/index.ts b/packages/compass-indexes/src/modules/index.ts index 9f561de2523..9a3b4e549bb 100644 --- a/packages/compass-indexes/src/modules/index.ts +++ b/packages/compass-indexes/src/modules/index.ts @@ -13,6 +13,7 @@ import namespace from './namespace'; import type { ThunkAction, ThunkDispatch } from 'redux-thunk'; import type { Logger } from '@mongodb-js/compass-logging'; import type { TrackFunction } from '@mongodb-js/compass-telemetry'; +import type { ConnectionInfoAccess } from '@mongodb-js/compass-connections/provider'; const reducer = combineReducers({ isWritable, @@ -34,6 +35,7 @@ export type IndexesExtraArgs = { localAppRegistry: AppRegistry; logger: Logger; track: TrackFunction; + connectionInfoAccess: ConnectionInfoAccess; }; export type IndexesThunkDispatch = ThunkDispatch< RootState, diff --git a/packages/compass-indexes/src/modules/search-indexes.ts b/packages/compass-indexes/src/modules/search-indexes.ts index f508129c702..7ded17fe313 100644 --- a/packages/compass-indexes/src/modules/search-indexes.ts +++ b/packages/compass-indexes/src/modules/search-indexes.ts @@ -387,7 +387,7 @@ export const createIndex = ({ type?: string; definition: Document; }): IndexesThunkAction> => { - return async function (dispatch, getState, { track }) { + return async function (dispatch, getState, { track, connectionInfoAccess }) { const { namespace, dataService } = getState(); dispatch({ type: ActionTypes.CreateSearchIndexStarted }); @@ -420,10 +420,14 @@ export const createIndex = ({ } dispatch({ type: ActionTypes.CreateSearchIndexSucceeded }); - track('Index Created', { - atlas_search: true, - type, - }); + track( + 'Index Created', + { + atlas_search: true, + type, + }, + connectionInfoAccess.getCurrentConnectionInfo() + ); openToast('search-index-creation-in-progress', { title: `Your index ${name} is in progress.`, @@ -445,7 +449,7 @@ export const updateIndex = ({ type?: string; definition: Document; }): IndexesThunkAction> => { - return async function (dispatch, getState, { track }) { + return async function (dispatch, getState, { track, connectionInfoAccess }) { const { namespace, dataService, @@ -464,9 +468,13 @@ export const updateIndex = ({ dispatch({ type: ActionTypes.UpdateSearchIndexStarted }); await dataService?.updateSearchIndex(namespace, name, definition); dispatch({ type: ActionTypes.UpdateSearchIndexSucceeded }); - track('Index Edited', { - atlas_search: true, - }); + track( + 'Index Edited', + { + atlas_search: true, + }, + connectionInfoAccess.getCurrentConnectionInfo() + ); openToast('search-index-update-in-progress', { title: `Your index ${name} is being updated.`, dismissible: true, @@ -563,7 +571,7 @@ export const showConfirmation = showConfirmationModal; export const dropSearchIndex = ( name: string ): IndexesThunkAction> => { - return async function (dispatch, getState, { track }) { + return async function (dispatch, getState, { track, connectionInfoAccess }) { const { namespace, dataService } = getState(); if (!dataService) { return; @@ -583,9 +591,13 @@ export const dropSearchIndex = ( try { await dataService.dropSearchIndex(namespace, name); - track('Index Dropped', { - atlas_search: true, - }); + track( + 'Index Dropped', + { + atlas_search: true, + }, + connectionInfoAccess.getCurrentConnectionInfo() + ); openToast('search-index-delete-in-progress', { title: `Your index ${name} is being deleted.`, dismissible: true, diff --git a/packages/compass-indexes/src/stores/create-index.ts b/packages/compass-indexes/src/stores/create-index.ts index ff47c711921..551a14d2d89 100644 --- a/packages/compass-indexes/src/stores/create-index.ts +++ b/packages/compass-indexes/src/stores/create-index.ts @@ -8,6 +8,7 @@ import type AppRegistry from 'hadron-app-registry'; import type { DataService } from 'mongodb-data-service'; import type { Logger } from '@mongodb-js/compass-logging'; import type { TrackFunction } from '@mongodb-js/compass-telemetry'; +import type { ConnectionInfoAccess } from '@mongodb-js/compass-connections/provider'; type CreateIndexPluginOptions = Pick< CollectionTabPluginMetadata, @@ -18,20 +19,33 @@ export type CreateIndexPluginServices = { globalAppRegistry: AppRegistry; localAppRegistry: AppRegistry; dataService: Pick; + connectionInfoAccess: ConnectionInfoAccess; logger: Logger; track: TrackFunction; }; export function activatePlugin( { namespace, serverVersion }: CreateIndexPluginOptions, - { localAppRegistry, dataService, logger, track }: CreateIndexPluginServices, + { + localAppRegistry, + dataService, + logger, + track, + connectionInfoAccess, + }: CreateIndexPluginServices, { on, cleanup }: ActivateHelpers ) { const store = createStore( reducer, { namespace, serverVersion }, applyMiddleware( - thunk.withExtraArgument({ localAppRegistry, dataService, logger, track }) + thunk.withExtraArgument({ + localAppRegistry, + dataService, + logger, + track, + connectionInfoAccess, + }) ) ); diff --git a/packages/compass-query-bar/src/components/query-history/favorite-list.tsx b/packages/compass-query-bar/src/components/query-history/favorite-list.tsx index 9cbc81b275c..eeada773310 100644 --- a/packages/compass-query-bar/src/components/query-history/favorite-list.tsx +++ b/packages/compass-query-bar/src/components/query-history/favorite-list.tsx @@ -19,6 +19,7 @@ import type { RootState } from '../../stores/query-bar-store'; import { OpenBulkUpdateActionButton } from './query-item/query-item-action-buttons'; import { usePreference } from 'compass-preferences-model/provider'; import { useTelemetry } from '@mongodb-js/compass-telemetry/provider'; +import { useConnectionInfoAccess } from '@mongodb-js/compass-connections/provider'; export type FavoriteActions = { onApply: (query: BaseQuery) => void; @@ -37,17 +38,22 @@ const FavoriteItem = ({ isReadonly: boolean; }) => { const track = useTelemetry(); + const connectionInfoAccess = useConnectionInfoAccess(); const readOnlyCompass = usePreference('readOnly'); const isUpdateQuery = !!query.update; const isDisabled = isUpdateQuery && (isReadonly || readOnlyCompass); const attributes = useMemo(() => getQueryAttributes(query), [query]); const onCardClick = useCallback(() => { - track('Query History Favorite Used', { - id: query._id, - screen: 'documents', - isUpdateQuery, - }); + track( + 'Query History Favorite Used', + { + id: query._id, + screen: 'documents', + isUpdateQuery, + }, + connectionInfoAccess.getCurrentConnectionInfo() + ); if (isDisabled) { return; @@ -66,16 +72,21 @@ const FavoriteItem = ({ onApply, attributes, onUpdateFavoriteChoosen, + connectionInfoAccess, ]); const onDeleteClick = useCallback(() => { - track('Query History Favorite Removed', { - id: query._id, - screen: 'documents', - isUpdateQuery, - }); + track( + 'Query History Favorite Removed', + { + id: query._id, + screen: 'documents', + isUpdateQuery, + }, + connectionInfoAccess.getCurrentConnectionInfo() + ); onDelete(query._id); - }, [track, query._id, isUpdateQuery, onDelete]); + }, [track, query._id, isUpdateQuery, onDelete, connectionInfoAccess]); return ( { const [tab, setTab] = useState('recent'); + const connectionInfoAccess = useConnectionInfoAccess(); useTrackOnChange( (track: TrackFunction) => { + const connectionInfo = connectionInfoAccess.getCurrentConnectionInfo(); if (tab === 'favorite') { - track('Query History Favorites'); + track('Query History Favorites', {}, connectionInfo); } else { - track('Query History Recent'); + track('Query History Recent', {}, connectionInfo); } }, [tab], diff --git a/packages/compass-telemetry/src/events.ts b/packages/compass-telemetry/src/events.ts index 3f6b21ccf16..bb1288576c4 100644 --- a/packages/compass-telemetry/src/events.ts +++ b/packages/compass-telemetry/src/events.ts @@ -49,9 +49,8 @@ export type ConnectionScopeEvents = [ | 'Query Exported' | 'Query History Closed' | 'Query History Favorite Added' - | 'Query History Favorite Copied' - | 'Query History Favorite Removed' - | 'Query History Favorite Used' + | 'Query History Favorite Removed' // depends! this one can be from 'my_queries' or from 'documents' screen + | 'Query History Favorite Used' // depends! this one can be from 'my_queries' or from 'documents' screen | 'Query History Favorites' | 'Query History Opened' | 'Query History Recent' @@ -102,6 +101,7 @@ export type GeneralScopeEvents = [ | 'My Queries Sort' | 'Theme Changed' | 'Error Fetching Attributes' + | 'Query History Favorite Copied' // this is from 'my_queries' screen | 'Aggregation Deleted' | 'Aggregation Copied' | 'First Contentful Paint' diff --git a/packages/databases-collections/src/index.ts b/packages/databases-collections/src/index.ts index d74fde1cc73..76921c0149c 100644 --- a/packages/databases-collections/src/index.ts +++ b/packages/databases-collections/src/index.ts @@ -19,7 +19,7 @@ import { favoriteQueryStorageAccessLocator, pipelineStorageLocator, } from '@mongodb-js/my-queries-storage/provider'; -import { connectionRepositoryLocator } from '@mongodb-js/compass-connections/dist/components/connections-provider'; +import { connectionRepositoryLocator } from '@mongodb-js/compass-connections/provider'; export const CollectionsWorkspaceTab: WorkspaceComponent<'Collections'> = { name: 'Collections' as const, From e3d955f0e5c086bf11e3715543bfd318727db972 Mon Sep 17 00:00:00 2001 From: Paula Stachova Date: Thu, 27 Jun 2024 15:40:45 +0200 Subject: [PATCH 08/24] part 7 --- .../pipeline-toolbar/pipeline-ai.tsx | 18 ++++++++++++------ .../src/components/export-modal.spec.tsx | 4 ++++ packages/compass-import-export/src/index.ts | 1 + .../src/modules/export.spec.ts | 10 +++++++++- .../src/modules/import.spec.ts | 8 +++++++- .../src/stores/export-store.spec.tsx | 14 +++++++++++--- .../src/stores/import-store.spec.tsx | 14 +++++++++++--- packages/compass-indexes/src/index.ts | 1 + .../compass-indexes/src/stores/drop-index.tsx | 14 +++++++++++--- .../validation-editor/validation-editor.tsx | 15 +++++++++++++-- .../compass-schema-validation/src/index.ts | 2 ++ .../src/modules/index.ts | 6 +++++- .../src/modules/zero-state.ts | 8 ++++++-- .../src/stores/store.ts | 15 +++++++++++++-- .../src/components/compass-schema.tsx | 10 ++++++---- packages/compass-schema/src/index.ts | 2 ++ packages/compass-schema/src/stores/store.ts | 13 +++++++++++-- .../src/components/server-stats-toolbar.tsx | 9 ++++++--- packages/compass-telemetry/src/events.ts | 2 +- packages/compass/src/app/components/home.tsx | 1 + packages/compass/src/app/utils/telemetry.ts | 5 +++-- 21 files changed, 136 insertions(+), 36 deletions(-) diff --git a/packages/compass-aggregations/src/components/pipeline-toolbar/pipeline-ai.tsx b/packages/compass-aggregations/src/components/pipeline-toolbar/pipeline-ai.tsx index 2adf8ac084a..b93451a7034 100644 --- a/packages/compass-aggregations/src/components/pipeline-toolbar/pipeline-ai.tsx +++ b/packages/compass-aggregations/src/components/pipeline-toolbar/pipeline-ai.tsx @@ -15,10 +15,12 @@ import type { RootState } from '../../modules'; import { useLogger } from '@mongodb-js/compass-logging/provider'; import { getPipelineStageOperatorsFromBuilderState } from '../../modules/pipeline-builder/builder-helpers'; import { useTelemetry } from '@mongodb-js/compass-telemetry/provider'; +import { useConnectionInfoAccess } from '@mongodb-js/compass-connections/provider'; const useOnSubmitFeedback = (lastAIPipelineRequestId: string | null) => { const logger = useLogger('AI-PIPELINE-UI'); const track = useTelemetry(); + const connectionInfoAccess = useConnectionInfoAccess(); return useCallback( (feedback: 'positive' | 'negative', text: string) => { const { log, mongoLogId } = logger; @@ -33,11 +35,15 @@ const useOnSubmitFeedback = (lastAIPipelineRequestId: string | null) => { } ); - track('PipelineAI Feedback', () => ({ - feedback, - request_id: lastAIPipelineRequestId, - text, - })); + track( + 'PipelineAI Feedback', + () => ({ + feedback, + request_id: lastAIPipelineRequestId, + text, + }), + connectionInfoAccess.getCurrentConnectionInfo() + ); openToast('pipeline-ai-feedback-submitted', { variant: 'success', @@ -45,7 +51,7 @@ const useOnSubmitFeedback = (lastAIPipelineRequestId: string | null) => { timeout: 10_000, }); }, - [logger, track, lastAIPipelineRequestId] + [logger, track, lastAIPipelineRequestId, connectionInfoAccess] ); }; diff --git a/packages/compass-import-export/src/components/export-modal.spec.tsx b/packages/compass-import-export/src/components/export-modal.spec.tsx index 7f71b556ff6..e68b052fa2a 100644 --- a/packages/compass-import-export/src/components/export-modal.spec.tsx +++ b/packages/compass-import-export/src/components/export-modal.spec.tsx @@ -9,6 +9,7 @@ import { closeExport, openExport } from '../modules/export'; import { createNoopLogger } from '@mongodb-js/compass-logging/provider'; import { createNoopTrack } from '@mongodb-js/compass-telemetry/provider'; +import { type ConnectionRepository } from '@mongodb-js/compass-connections/provider'; function renderModal(exportState: any = {}) { // TODO: mutating state directly doesn't guarantee that we are testing the @@ -20,6 +21,9 @@ function renderModal(exportState: any = {}) { globalAppRegistry: {}, logger: createNoopLogger(), track: createNoopTrack(), + connectionRepository: { + getConnectionInfoById: () => ({ id: 'TEST' }), + } as unknown as ConnectionRepository, } as any); const state = store.getState(); state.export = { diff --git a/packages/compass-import-export/src/index.ts b/packages/compass-import-export/src/index.ts index 27882ec1170..6370b4bb90a 100644 --- a/packages/compass-import-export/src/index.ts +++ b/packages/compass-import-export/src/index.ts @@ -40,6 +40,7 @@ export const ExportPlugin = registerHadronPlugin( }, { connectionsManager: connectionsManagerLocator, + connectionRepository: connectionRepositoryLocator, preferences: preferencesLocator, logger: createLoggerLocator('COMPASS-EXPORT-UI'), track: createTelemetryLocator(), diff --git a/packages/compass-import-export/src/modules/export.spec.ts b/packages/compass-import-export/src/modules/export.spec.ts index 4ab0377f4dd..7a863021e10 100644 --- a/packages/compass-import-export/src/modules/export.spec.ts +++ b/packages/compass-import-export/src/modules/export.spec.ts @@ -26,7 +26,10 @@ import { import { createSandboxFromDefaultPreferences } from 'compass-preferences-model'; import { createNoopLogger } from '@mongodb-js/compass-logging/provider'; import { createNoopTrack } from '@mongodb-js/compass-telemetry/provider'; -import { ConnectionsManager } from '@mongodb-js/compass-connections/provider'; +import { + ConnectionsManager, + type ConnectionRepository, +} from '@mongodb-js/compass-connections/provider'; import { type PreferencesAccess } from 'compass-preferences-model/provider'; const logger = createNoopLogger(); @@ -38,11 +41,15 @@ const dataService = { const connectionsManager = new ConnectionsManager({ logger: logger.log.unbound, }); +const connectionRepository = { + getConnectionInfoById: () => ({ id: 'TEST' }), +} as unknown as ConnectionRepository; const mockServices: ExportPluginServices = { connectionsManager, globalAppRegistry: new AppRegistry(), logger: createNoopLogger(), track: createNoopTrack(), + connectionRepository, preferences: {} as PreferencesAccess, }; @@ -346,6 +353,7 @@ describe('export [module]', function () { logger, track, connectionsManager, + connectionRepository, }); }); diff --git a/packages/compass-import-export/src/modules/import.spec.ts b/packages/compass-import-export/src/modules/import.spec.ts index 59790283fe2..9b673f833f6 100644 --- a/packages/compass-import-export/src/modules/import.spec.ts +++ b/packages/compass-import-export/src/modules/import.spec.ts @@ -6,7 +6,10 @@ import { configureStore, } from '../stores/import-store'; import { createNoopLogger } from '@mongodb-js/compass-logging/provider'; -import { ConnectionsManager } from '@mongodb-js/compass-connections/provider'; +import { + type ConnectionRepository, + ConnectionsManager, +} from '@mongodb-js/compass-connections/provider'; import { AppRegistry } from 'hadron-app-registry'; import { type WorkspacesService } from '@mongodb-js/compass-workspaces/provider'; import { createNoopTrack } from '@mongodb-js/compass-telemetry/provider'; @@ -20,6 +23,9 @@ const mockServices = { track, connectionsManager: new ConnectionsManager({ logger: logger.log.unbound }), workspaces: {} as WorkspacesService, + connectionRepository: { + getConnectionInfoById: () => ({ id: 'TEST' }), + } as unknown as ConnectionRepository, } as ImportPluginServices; describe('import [module]', function () { diff --git a/packages/compass-import-export/src/stores/export-store.spec.tsx b/packages/compass-import-export/src/stores/export-store.spec.tsx index 141d9312ccb..54d74d85cd8 100644 --- a/packages/compass-import-export/src/stores/export-store.spec.tsx +++ b/packages/compass-import-export/src/stores/export-store.spec.tsx @@ -1,7 +1,10 @@ import { createActivateHelpers } from 'hadron-app-registry'; import AppRegistry from 'hadron-app-registry'; import { activatePlugin } from './export-store'; -import { ConnectionsManager } from '@mongodb-js/compass-connections/provider'; +import { + type ConnectionRepository, + ConnectionsManager, +} from '@mongodb-js/compass-connections/provider'; import { createNoopLogger } from '@mongodb-js/compass-logging/provider'; import { createNoopTrack } from '@mongodb-js/compass-telemetry/provider'; import { expect } from 'chai'; @@ -13,6 +16,7 @@ describe('ExportStore [Store]', function () { let globalAppRegistry: AppRegistry; let connectionsManager: ConnectionsManager; const preferences = {} as PreferencesAccess; + const connectionId = 'TEST'; beforeEach(function () { const logger = createNoopLogger(); @@ -21,6 +25,9 @@ describe('ExportStore [Store]', function () { connectionsManager = new ConnectionsManager({ logger: logger.log.unbound, }); + const connectionRepository = { + getConnectionInfoById: () => ({ id: connectionId }), + } as unknown as ConnectionRepository; ({ store, deactivate } = activatePlugin( {}, @@ -30,6 +37,7 @@ describe('ExportStore [Store]', function () { logger, track, preferences, + connectionRepository, }, createActivateHelpers() )); @@ -52,9 +60,9 @@ describe('ExportStore [Store]', function () { globalAppRegistry.emit( 'open-export', { namespace: 'test.coll', origin: 'menu' }, - { connectionId: 'TEST' } + { connectionId } ); - expect(store.getState().export.connectionId).to.equal('TEST'); + expect(store.getState().export.connectionId).to.equal(connectionId); expect(store.getState().export.namespace).to.equal('test.coll'); }); }); diff --git a/packages/compass-import-export/src/stores/import-store.spec.tsx b/packages/compass-import-export/src/stores/import-store.spec.tsx index e1383f115f3..74e922b269d 100644 --- a/packages/compass-import-export/src/stores/import-store.spec.tsx +++ b/packages/compass-import-export/src/stores/import-store.spec.tsx @@ -1,7 +1,10 @@ import { createActivateHelpers } from 'hadron-app-registry'; import AppRegistry from 'hadron-app-registry'; import { activatePlugin } from './import-store'; -import { ConnectionsManager } from '@mongodb-js/compass-connections/provider'; +import { + type ConnectionRepository, + ConnectionsManager, +} from '@mongodb-js/compass-connections/provider'; import { type WorkspacesService } from '@mongodb-js/compass-workspaces/provider'; import { createNoopLogger } from '@mongodb-js/compass-logging/provider'; import { createNoopTrack } from '@mongodb-js/compass-telemetry/provider'; @@ -13,6 +16,7 @@ describe('ImportStore [Store]', function () { let globalAppRegistry: AppRegistry; let connectionsManager: ConnectionsManager; let workspaces: WorkspacesService; + const connectionId = 'TEST'; beforeEach(function () { const logger = createNoopLogger(); @@ -21,6 +25,9 @@ describe('ImportStore [Store]', function () { connectionsManager = new ConnectionsManager({ logger: logger.log.unbound, }); + const connectionRepository = { + getConnectionInfoById: () => ({ id: connectionId }), + } as unknown as ConnectionRepository; ({ store, deactivate } = activatePlugin( {}, @@ -30,6 +37,7 @@ describe('ImportStore [Store]', function () { logger, track, workspaces, + connectionRepository, }, createActivateHelpers() )); @@ -52,9 +60,9 @@ describe('ImportStore [Store]', function () { globalAppRegistry.emit( 'open-import', { namespace: 'test.coll', origin: 'menu' }, - { connectionId: 'TEST' } + { connectionId } ); - expect(store.getState().import.connectionId).to.equal('TEST'); + expect(store.getState().import.connectionId).to.equal(connectionId); expect(store.getState().import.namespace).to.equal('test.coll'); }); }); diff --git a/packages/compass-indexes/src/index.ts b/packages/compass-indexes/src/index.ts index a71641470e1..324e0ddbf8c 100644 --- a/packages/compass-indexes/src/index.ts +++ b/packages/compass-indexes/src/index.ts @@ -78,5 +78,6 @@ export const DropIndexPlugin = registerHadronPlugin( dataService: dataServiceLocator as DataServiceLocator<'dropIndex'>, logger: createLoggerLocator('COMPASS-INDEXES-UI'), track: createTelemetryLocator(), + connectionInfoAccess: connectionInfoAccessLocator, } ); diff --git a/packages/compass-indexes/src/stores/drop-index.tsx b/packages/compass-indexes/src/stores/drop-index.tsx index 9f3ef322e24..041622e683b 100644 --- a/packages/compass-indexes/src/stores/drop-index.tsx +++ b/packages/compass-indexes/src/stores/drop-index.tsx @@ -10,24 +10,32 @@ import type { CollectionTabPluginMetadata } from '@mongodb-js/compass-collection import type { DataService } from 'mongodb-data-service'; import type { Logger } from '@mongodb-js/compass-logging/provider'; import type { TrackFunction } from '@mongodb-js/compass-telemetry'; +import type { ConnectionInfoAccess } from '@mongodb-js/compass-connections/provider'; type DropIndexInitialProps = Pick; type DropIndexServices = { localAppRegistry: AppRegistry; dataService: Pick; + connectionInfoAccess: ConnectionInfoAccess; logger: Logger; track: TrackFunction; }; export function activatePlugin( { namespace }: DropIndexInitialProps, - { localAppRegistry, dataService, track }: DropIndexServices, + { + localAppRegistry, + dataService, + track, + connectionInfoAccess, + }: DropIndexServices, { on, cleanup, signal }: ActivateHelpers ) { on(localAppRegistry, 'open-drop-index-modal', async (indexName: string) => { try { - track('Screen', { name: 'drop_index_modal' }); + const connectionInfo = connectionInfoAccess.getCurrentConnectionInfo(); + track('Screen', { name: 'drop_index_modal' }, connectionInfo); const confirmed = await showConfirmation({ variant: 'danger', title: 'Drop Index', @@ -41,7 +49,7 @@ export function activatePlugin( return; } await dataService.dropIndex(namespace, indexName); - track('Index Dropped', { atlas_search: false }); + track('Index Dropped', { atlas_search: false }, connectionInfo); localAppRegistry.emit('refresh-regular-indexes'); openToast('drop-index-success', { variant: 'success', diff --git a/packages/compass-schema-validation/src/components/validation-editor/validation-editor.tsx b/packages/compass-schema-validation/src/components/validation-editor/validation-editor.tsx index 56f77310703..016e91481ed 100644 --- a/packages/compass-schema-validation/src/components/validation-editor/validation-editor.tsx +++ b/packages/compass-schema-validation/src/components/validation-editor/validation-editor.tsx @@ -28,6 +28,10 @@ import type { } from '../../modules/validation'; import { checkValidator } from '../../modules/validation'; import { ActionSelector, LevelSelector } from '../validation-selectors'; +import { + type ConnectionInfoAccess, + withConnectionInfoAccess, +} from '@mongodb-js/compass-connections/provider'; const validationEditorStyles = css({ padding: spacing[3], @@ -117,6 +121,7 @@ export type ValidationEditorProps = { isEditable: boolean; darkMode?: boolean; track: TrackFunction; + connectionInfoAccess: ConnectionInfoAccess; }; /** @@ -178,7 +183,11 @@ class ValidationEditor extends Component { typeof checkedValidator.validator === 'object' && !!checkedValidator.validator?.$jsonSchema, }; - this.props.track('Schema Validation Edited', trackEvent); + this.props.track( + 'Schema Validation Edited', + trackEvent, + this.props.connectionInfoAccess.getCurrentConnectionInfo() + ); } /** @@ -313,5 +322,7 @@ class ValidationEditor extends Component { } export default withTelemetry( - withDarkMode(ValidationEditor) + withConnectionInfoAccess( + withDarkMode(ValidationEditor) + ) ); diff --git a/packages/compass-schema-validation/src/index.ts b/packages/compass-schema-validation/src/index.ts index 3cd3f8f8c3b..699568f1737 100644 --- a/packages/compass-schema-validation/src/index.ts +++ b/packages/compass-schema-validation/src/index.ts @@ -2,6 +2,7 @@ import { onActivated } from './stores'; import CompassSchemaValidation from './components/compass-schema-validation'; import { registerHadronPlugin } from 'hadron-app-registry'; import { + connectionInfoAccessLocator, dataServiceLocator, type DataServiceLocator, } from '@mongodb-js/compass-connections/provider'; @@ -20,6 +21,7 @@ export const CompassSchemaValidationHadronPlugin = registerHadronPlugin( dataService: dataServiceLocator as DataServiceLocator< 'aggregate' | 'collectionInfo' | 'updateCollection' >, + connectionInfoAccess: connectionInfoAccessLocator, instance: mongoDBInstanceLocator, preferences: preferencesLocator, logger: createLoggerLocator('COMPASS-SCHEMA-VALIDATION-UI'), diff --git a/packages/compass-schema-validation/src/modules/index.ts b/packages/compass-schema-validation/src/modules/index.ts index 8c3376bb51a..f0592fd6cbd 100644 --- a/packages/compass-schema-validation/src/modules/index.ts +++ b/packages/compass-schema-validation/src/modules/index.ts @@ -23,7 +23,10 @@ import type { EditModeAction, EditModeState } from './edit-mode'; import editMode, { INITIAL_STATE as EDIT_MODE_STATE } from './edit-mode'; import type { ThunkAction } from 'redux-thunk'; import type { PreferencesAccess } from 'compass-preferences-model'; -import type { DataService } from '@mongodb-js/compass-connections/provider'; +import type { + ConnectionInfoAccess, + DataService, +} from '@mongodb-js/compass-connections/provider'; import type AppRegistry from 'hadron-app-registry'; import type { Logger } from '@mongodb-js/compass-logging/provider'; import type { TrackFunction } from '@mongodb-js/compass-telemetry'; @@ -61,6 +64,7 @@ export type SchemaValidationExtraArgs = { DataService, 'aggregate' | 'collectionInfo' | 'updateCollection' >; + connectionInfoAccess: ConnectionInfoAccess; preferences: PreferencesAccess; globalAppRegistry: AppRegistry; logger: Logger; diff --git a/packages/compass-schema-validation/src/modules/zero-state.ts b/packages/compass-schema-validation/src/modules/zero-state.ts index 22d2b70b09d..fcb98f5f5b1 100644 --- a/packages/compass-schema-validation/src/modules/zero-state.ts +++ b/packages/compass-schema-validation/src/modules/zero-state.ts @@ -48,9 +48,13 @@ export const zeroStateChanged = ( export const changeZeroState = ( isZeroState: boolean ): SchemaValidationThunkAction => { - return (dispatch, _getState, { track }) => { + return (dispatch, _getState, { track, connectionInfoAccess }) => { if (isZeroState === false) { - track('Schema Validation Added'); + track( + 'Schema Validation Added', + {}, + connectionInfoAccess.getCurrentConnectionInfo() + ); } return dispatch(zeroStateChanged(isZeroState)); }; diff --git a/packages/compass-schema-validation/src/stores/store.ts b/packages/compass-schema-validation/src/stores/store.ts index bb30e1bfea3..38510cf10cf 100644 --- a/packages/compass-schema-validation/src/stores/store.ts +++ b/packages/compass-schema-validation/src/stores/store.ts @@ -8,7 +8,10 @@ import { editModeChanged } from '../modules/edit-mode'; import semver from 'semver'; import type { CollectionTabPluginMetadata } from '@mongodb-js/compass-collection'; import type { ActivateHelpers, AppRegistry } from 'hadron-app-registry'; -import type { DataService } from '@mongodb-js/compass-connections/provider'; +import type { + ConnectionInfoAccess, + DataService, +} from '@mongodb-js/compass-connections/provider'; import type { MongoDBInstance } from '@mongodb-js/compass-app-stores/provider'; import type { PreferencesAccess } from 'compass-preferences-model'; import type { Logger } from '@mongodb-js/compass-logging/provider'; @@ -25,6 +28,7 @@ type SchemaValidationServices = { DataService, 'aggregate' | 'collectionInfo' | 'updateCollection' >; + connectionInfoAccess: ConnectionInfoAccess; preferences: PreferencesAccess; instance: MongoDBInstance; logger: Logger; @@ -36,7 +40,12 @@ export function configureStore( state: Partial, services: Pick< SchemaValidationServices, - 'globalAppRegistry' | 'dataService' | 'preferences' | 'logger' | 'track' + | 'globalAppRegistry' + | 'dataService' + | 'preferences' + | 'logger' + | 'track' + | 'connectionInfoAccess' > ) { return createStore( @@ -57,6 +66,7 @@ export function onActivated( { globalAppRegistry, dataService, + connectionInfoAccess, preferences, instance, logger, @@ -77,6 +87,7 @@ export function onActivated( }, { dataService, + connectionInfoAccess, preferences, globalAppRegistry, logger, diff --git a/packages/compass-schema/src/components/compass-schema.tsx b/packages/compass-schema/src/components/compass-schema.tsx index 231c85f8b07..6b4d47ff6b1 100644 --- a/packages/compass-schema/src/components/compass-schema.tsx +++ b/packages/compass-schema/src/components/compass-schema.tsx @@ -337,7 +337,7 @@ const FieldList: React.FunctionComponent<{ const nbsp = '\u00a0'; const title = 'Atlas’ Performance Advisor.'; const PerformanceAdvisorBanner = () => { - const { atlasMetadata } = useConnectionInfo(); + const connectionInfo = useConnectionInfo(); const track = useTelemetry(); return ( @@ -348,10 +348,12 @@ const PerformanceAdvisorBanner = () => { Insight {nbsp}or{nbsp} - {atlasMetadata ? ( + {connectionInfo.atlasMetadata ? ( track('Performance Advisor Clicked')} + href={getAtlasPerformanceAdvisorLink(connectionInfo.atlasMetadata)} + onClick={() => + track('Performance Advisor Clicked', {}, connectionInfo) + } hideExternalIcon > {title} diff --git a/packages/compass-schema/src/index.ts b/packages/compass-schema/src/index.ts index 0701e840424..61f58c67228 100644 --- a/packages/compass-schema/src/index.ts +++ b/packages/compass-schema/src/index.ts @@ -1,4 +1,5 @@ import { + connectionInfoAccessLocator, dataServiceLocator, type DataServiceLocator, } from '@mongodb-js/compass-connections/provider'; @@ -27,6 +28,7 @@ export const CompassSchemaHadronPlugin = registerHadronPlugin( preferences: preferencesLocator, fieldStoreService: fieldStoreServiceLocator, queryBar: queryBarServiceLocator, + connectionInfoAccess: connectionInfoAccessLocator, } ); export const CompassSchemaPlugin = { diff --git a/packages/compass-schema/src/stores/store.ts b/packages/compass-schema/src/stores/store.ts index 1debaaf7b54..9485a1250e9 100644 --- a/packages/compass-schema/src/stores/store.ts +++ b/packages/compass-schema/src/stores/store.ts @@ -20,7 +20,10 @@ import { import { capMaxTimeMSAtPreferenceLimit } from 'compass-preferences-model/provider'; import { openToast } from '@mongodb-js/compass-components'; import type { CollectionTabPluginMetadata } from '@mongodb-js/compass-collection'; -import type { DataService as OriginalDataService } from '@mongodb-js/compass-connections/provider'; +import type { + ConnectionInfoAccess, + DataService as OriginalDataService, +} from '@mongodb-js/compass-connections/provider'; import type { ActivateHelpers } from 'hadron-app-registry'; import type AppRegistry from 'hadron-app-registry'; import { configureActions } from '../actions'; @@ -57,6 +60,7 @@ function resultId(): number { export type DataService = Pick; export type SchemaPluginServices = { dataService: DataService; + connectionInfoAccess: ConnectionInfoAccess; localAppRegistry: Pick; globalAppRegistry: Pick; logger: Logger; @@ -127,6 +131,7 @@ export function activateSchemaPlugin( preferences, fieldStoreService, queryBar, + connectionInfoAccess, }: SchemaPluginServices, { on, cleanup }: ActivateHelpers ) { @@ -261,7 +266,11 @@ export function activateSchemaPlugin( geo_data: schema ? schemaContainsGeoData(schema) : false, analysis_time_ms: analysisTimeMS, }); - track('Schema Analyzed', trackEvent); + track( + 'Schema Analyzed', + trackEvent, + connectionInfoAccess.getCurrentConnectionInfo() + ); }, startAnalysis: async function (this: SchemaStore) { diff --git a/packages/compass-serverstats/src/components/server-stats-toolbar.tsx b/packages/compass-serverstats/src/components/server-stats-toolbar.tsx index 24dd265e705..8ea26d269fa 100644 --- a/packages/compass-serverstats/src/components/server-stats-toolbar.tsx +++ b/packages/compass-serverstats/src/components/server-stats-toolbar.tsx @@ -13,6 +13,7 @@ import { useTelemetry } from '@mongodb-js/compass-telemetry/provider'; import Actions from '../actions'; import ServerStatsStore from '../stores/server-stats-graphs-store'; +import { useConnectionInfoAccess } from '@mongodb-js/compass-connections/provider'; const serverStatsToolbarStyles = css({ display: 'flex', @@ -57,6 +58,7 @@ type ServerStatsToolbarProps = { function ServerStatsToolbar({ eventDispatcher }: ServerStatsToolbarProps) { const track = useTelemetry(); + const connectionInfoAccess = useConnectionInfoAccess(); const darkMode = useDarkMode(); const [time, setTime] = useState('00:00:00'); @@ -71,14 +73,15 @@ function ServerStatsToolbar({ eventDispatcher }: ServerStatsToolbarProps) { }, [eventDispatcher]); const onPlayPauseClicked = useCallback(() => { + const connectionInfo = connectionInfoAccess.getCurrentConnectionInfo(); if (isPaused) { - track('Performance Resumed'); + track('Performance Resumed', {}, connectionInfo); } else { - track('Performance Paused'); + track('Performance Paused', {}, connectionInfo); } setPaused(!isPaused); Actions.pause(); - }, [isPaused, track]); + }, [isPaused, track, connectionInfoAccess]); return (
, + connectionInfo: ConnectionInfo, dataService: Pick, { debug }: Logger, track: TrackFunction @@ -194,7 +195,7 @@ export function trackNewConnectionEvent( }; return trackEvent; }; - track('New Connection', callback); + track('New Connection', callback, connectionInfo); } catch (error) { debug('trackNewConnectionEvent failed', error); } From fa566235a5a428e0975efda542d3d161648e8bd9 Mon Sep 17 00:00:00 2001 From: Paula Stachova Date: Thu, 27 Jun 2024 15:56:29 +0200 Subject: [PATCH 09/24] part 8 --- .../src/modules/update-view.ts | 17 ++++++++++------- .../src/stores/create-view.spec.ts | 10 +++++----- .../src/modules/validation.ts | 12 ++++++++++-- .../src/stores/store.spec.ts | 5 +++++ .../compass-schema/src/stores/store.spec.ts | 5 +++++ .../src/components/detailview-component.tsx | 10 ++++++---- packages/compass-shell/src/index.ts | 4 ++++ packages/compass-shell/src/stores/store.ts | 14 ++++++++++++-- packages/compass-telemetry/src/events.ts | 1 - packages/compass/src/app/components/home.tsx | 1 - .../src/items-grid.tsx | 10 ++++++++-- 11 files changed, 65 insertions(+), 24 deletions(-) diff --git a/packages/compass-aggregations/src/modules/update-view.ts b/packages/compass-aggregations/src/modules/update-view.ts index 3a5688829dc..f1e07d1357e 100644 --- a/packages/compass-aggregations/src/modules/update-view.ts +++ b/packages/compass-aggregations/src/modules/update-view.ts @@ -101,8 +101,7 @@ export const updateView = (): PipelineBuilderThunkAction> => { return; } - const { id: connectionId } = - connectionInfoAccess.getCurrentConnectionInfo(); + const connectionInfo = connectionInfoAccess.getCurrentConnectionInfo(); const viewPipeline = getPipelineFromBuilderState( getState(), @@ -115,13 +114,17 @@ export const updateView = (): PipelineBuilderThunkAction> => { try { await ds!.updateCollection(viewNamespace, options); - track('View Updated', { - num_stages: viewPipeline.length, - editor_view_type: mapPipelineModeToEditorViewType(state), - }); + track( + 'View Updated', + { + num_stages: viewPipeline.length, + editor_view_type: mapPipelineModeToEditorViewType(state), + }, + connectionInfo + ); debug('selecting namespace', viewNamespace); globalAppRegistry.emit('view-edited', viewNamespace); - workspaces.openCollectionWorkspace(connectionId, viewNamespace); + workspaces.openCollectionWorkspace(connectionInfo.id, viewNamespace); } catch (e: any) { debug('Unexpected error updating view', e); dispatch(updateViewErrorOccured(e)); diff --git a/packages/compass-aggregations/src/stores/create-view.spec.ts b/packages/compass-aggregations/src/stores/create-view.spec.ts index 6117a041a8c..51957e95750 100644 --- a/packages/compass-aggregations/src/stores/create-view.spec.ts +++ b/packages/compass-aggregations/src/stores/create-view.spec.ts @@ -2,9 +2,9 @@ import AppRegistry, { createActivateHelpers } from 'hadron-app-registry'; import { activateCreateViewPlugin } from './create-view'; import { expect } from 'chai'; import { - type ConnectionInfoAccess, ConnectionsManager, type DataService, + type ConnectionRepository, } from '@mongodb-js/compass-connections/provider'; import { changeViewName, createView } from '../modules/create-view'; import Sinon from 'sinon'; @@ -26,9 +26,6 @@ describe('CreateViewStore [Store]', function () { let appRegistryEmitSpy: Sinon.SinonSpy; const logger = {} as any; const track = () => {}; - const connectionInfoAccess = { - getCurrentConnectionInfo: () => ({ id: 'TEST' }), - } as ConnectionInfoAccess; const createViewStub = Sinon.stub(); const dataService = { createView: createViewStub, @@ -38,6 +35,9 @@ describe('CreateViewStore [Store]', function () { const workspaces = { openCollectionWorkspace: openCollectionWorkspaceStub, } as unknown as WorkspacesService; + const connectionRepository = { + getConnectionInfoById: () => {}, + } as unknown as ConnectionRepository; beforeEach(function () { globalAppRegistry = new AppRegistry(); @@ -50,9 +50,9 @@ describe('CreateViewStore [Store]', function () { { globalAppRegistry, connectionsManager, + connectionRepository, logger, track, - connectionInfoAccess, workspaces, }, createActivateHelpers() diff --git a/packages/compass-schema-validation/src/modules/validation.ts b/packages/compass-schema-validation/src/modules/validation.ts index 0cdb01d56dd..a98c34f5541 100644 --- a/packages/compass-schema-validation/src/modules/validation.ts +++ b/packages/compass-schema-validation/src/modules/validation.ts @@ -456,7 +456,11 @@ export function validationFromCollection( export const saveValidation = ( validation: Validation ): SchemaValidationThunkAction> => { - return async (dispatch, getState, { dataService, track }) => { + return async ( + dispatch, + getState, + { dataService, track, connectionInfoAccess } + ) => { const state = getState(); const namespace = state.namespace; const checkedValidator = checkValidator(validation.validator); @@ -471,7 +475,11 @@ export const saveValidation = ( validation_action: validation.validationAction, validation_level: validation.validationLevel, }; - track('Schema Validation Updated', trackEvent); + track( + 'Schema Validation Updated', + trackEvent, + connectionInfoAccess.getCurrentConnectionInfo() + ); try { await dataService.updateCollection( `${namespace.database}.${namespace.collection}`, diff --git a/packages/compass-schema-validation/src/stores/store.spec.ts b/packages/compass-schema-validation/src/stores/store.spec.ts index 116f12ba577..bdc8f0f9b70 100644 --- a/packages/compass-schema-validation/src/stores/store.spec.ts +++ b/packages/compass-schema-validation/src/stores/store.spec.ts @@ -20,6 +20,7 @@ import { onActivated } from './store'; import { createSandboxFromDefaultPreferences } from 'compass-preferences-model'; import { createNoopLogger } from '@mongodb-js/compass-logging/provider'; import { createNoopTrack } from '@mongodb-js/compass-telemetry/provider'; +import type { ConnectionInfoAccess } from '@mongodb-js/compass-connections/provider'; const topologyDescription = { type: 'Unknown', @@ -45,6 +46,9 @@ describe('Schema Validation Store', function () { let store: Store; let deactivate: null | (() => void) = null; const globalAppRegistry = new AppRegistry(); + const connectionInfoAccess = { + getCurrentConnectionInfo: () => {}, + } as ConnectionInfoAccess; beforeEach(async function () { const activateResult = onActivated( @@ -56,6 +60,7 @@ describe('Schema Validation Store', function () { preferences: await createSandboxFromDefaultPreferences(), logger: createNoopLogger(), track: createNoopTrack(), + connectionInfoAccess, }, createActivateHelpers() ); diff --git a/packages/compass-schema/src/stores/store.spec.ts b/packages/compass-schema/src/stores/store.spec.ts index 096ed700631..f08d4617d25 100644 --- a/packages/compass-schema/src/stores/store.spec.ts +++ b/packages/compass-schema/src/stores/store.spec.ts @@ -8,6 +8,7 @@ import { createSandboxFromDefaultPreferences } from 'compass-preferences-model'; import { createNoopLogger } from '@mongodb-js/compass-logging/provider'; import type { FieldStoreService } from '@mongodb-js/compass-field-store'; import { createNoopTrack } from '@mongodb-js/compass-telemetry/provider'; +import type { ConnectionInfoAccess } from '@mongodb-js/compass-connections/provider'; const dummyLogger = createNoopLogger('TEST'); const dummyTrack = createNoopTrack(); @@ -31,6 +32,9 @@ describe('Schema Store', function () { const globalAppRegistry = new AppRegistry(); const dataService = 'test'; const namespace = 'db.coll'; + const connectionInfoAccess = { + getCurrentConnectionInfo: () => {}, + } as ConnectionInfoAccess; beforeEach(async function () { const plugin = activateSchemaPlugin( @@ -46,6 +50,7 @@ describe('Schema Store', function () { preferences: await createSandboxFromDefaultPreferences(), fieldStoreService: mockFieldStoreService, queryBar: mockQueryBar as any, + connectionInfoAccess, }, createActivateHelpers() ); diff --git a/packages/compass-serverstats/src/components/detailview-component.tsx b/packages/compass-serverstats/src/components/detailview-component.tsx index 23359122f60..ed7f0bee980 100644 --- a/packages/compass-serverstats/src/components/detailview-component.tsx +++ b/packages/compass-serverstats/src/components/detailview-component.tsx @@ -3,6 +3,7 @@ import { Button, Icon } from '@mongodb-js/compass-components'; import { useTelemetry } from '@mongodb-js/compass-telemetry/provider'; import Actions from '../actions'; +import { useConnectionInfoAccess } from '@mongodb-js/compass-connections/provider'; function removeMS(key: string, value: any) { if (key === 'ms_running') { @@ -25,6 +26,7 @@ export function DetailViewComponent() { const [data, setData] = useState(null); const track = useTelemetry(); + const connectionInfoAccess = useConnectionInfoAccess(); useEffect(() => { const unsubscribeShowOperationDetails = Actions.showOperationDetails.listen( @@ -45,15 +47,15 @@ export function DetailViewComponent() { }, []); const hideOperationDetails = useCallback(() => { - track('DetailView hideOperationDetails'); + track('DetailView hideOperationDetails', {}, connectionInfoAccess.getCurrentConnectionInfo()); Actions.hideOperationDetails(); - }, [track]); + }, [track, connectionInfoAccess]); const onKillOp = useCallback(() => { - track('DetailView killOp'); + track('DetailView killOp', {}, connectionInfoAccess.getCurrentConnectionInfo()); if (data?.opid !== undefined) Actions.killOp(data.opid); hideOperationDetails(); - }, [data, track, hideOperationDetails]); + }, [data, track, hideOperationDetails, connectionInfoAccess]); if (!data) { return null; diff --git a/packages/compass-shell/src/index.ts b/packages/compass-shell/src/index.ts index 87353600fbf..b185bf9835f 100644 --- a/packages/compass-shell/src/index.ts +++ b/packages/compass-shell/src/index.ts @@ -4,8 +4,10 @@ import { createTelemetryLocator } from '@mongodb-js/compass-telemetry/provider'; import { ShellPlugin, onActivated } from './plugin'; import { registerHadronPlugin } from 'hadron-app-registry'; import { + type ConnectionInfoAccess, dataServiceLocator, type DataService, + connectionInfoAccessLocator, } from '@mongodb-js/compass-connections/provider'; import { preferencesLocator, @@ -20,6 +22,7 @@ export const CompassShellPlugin = registerHadronPlugin< logger: () => Logger; track: () => TrackFunction; dataService: () => DataService; + connectionInfoAccess: () => ConnectionInfoAccess; preferences: () => PreferencesAccess; } >( @@ -32,6 +35,7 @@ export const CompassShellPlugin = registerHadronPlugin< logger: createLoggerLocator('COMPASS-SHELL'), track: createTelemetryLocator(), dataService: dataServiceLocator, + connectionInfoAccess: connectionInfoAccessLocator, preferences: preferencesLocator, } ); diff --git a/packages/compass-shell/src/stores/store.ts b/packages/compass-shell/src/stores/store.ts index a1166ffbe0a..b2708929b6e 100644 --- a/packages/compass-shell/src/stores/store.ts +++ b/packages/compass-shell/src/stores/store.ts @@ -7,7 +7,10 @@ import { setupLoggerAndTelemetry } from '@mongosh/logging'; import type { Logger } from '@mongodb-js/compass-logging/provider'; import type { PreferencesAccess } from 'compass-preferences-model'; import type AppRegistry from 'hadron-app-registry'; -import type { DataService } from '@mongodb-js/compass-connections/provider'; +import type { + ConnectionInfoAccess, + DataService, +} from '@mongodb-js/compass-connections/provider'; import type { TrackFunction } from '@mongodb-js/compass-telemetry'; export default class CompassShellStore { @@ -25,12 +28,14 @@ export default class CompassShellStore { logger: { log, debug }, track, dataService, + connectionInfoAccess, preferences, }: { globalAppRegistry: AppRegistry; logger: Logger; track: TrackFunction; dataService: DataService; + connectionInfoAccess: ConnectionInfoAccess; preferences: PreferencesAccess; }): () => void { debug('activated'); @@ -54,7 +59,12 @@ export default class CompassShellStore { // Prefix Segment events with `Shell ` to avoid event name collisions. // We always enable telemetry here, since the track call will // already check whether Compass telemetry is enabled or not. - track: ({ event, properties }) => track(`Shell ${event}`, properties), + track: ({ event, properties }) => + track( + `Shell ${event}`, + properties, + connectionInfoAccess.getCurrentConnectionInfo() + ), flush: () => { return Promise.resolve(); // not needed }, diff --git a/packages/compass-telemetry/src/events.ts b/packages/compass-telemetry/src/events.ts index 00012302d49..c16cf2effa4 100644 --- a/packages/compass-telemetry/src/events.ts +++ b/packages/compass-telemetry/src/events.ts @@ -72,7 +72,6 @@ export type ConnectionScopeEvents = [ | 'Schema Validation Added' | 'Schema Validation Edited' | 'Schema Validation Updated' - | 'Shell Opened' | `Shell ${string}` | 'Switch View Type' | 'Update Export Opened' diff --git a/packages/compass/src/app/components/home.tsx b/packages/compass/src/app/components/home.tsx index f16623a66f9..b85a3d549d6 100644 --- a/packages/compass/src/app/components/home.tsx +++ b/packages/compass/src/app/components/home.tsx @@ -28,7 +28,6 @@ import { ConnectionsManagerProvider, ConnectionsManager, type ConnectionInfo, - useConnectionInfoAccess, } from '@mongodb-js/compass-connections/provider'; import type { DataService } from 'mongodb-data-service'; import React, { diff --git a/packages/databases-collections-list/src/items-grid.tsx b/packages/databases-collections-list/src/items-grid.tsx index d3c7efc3643..e2b5dba4942 100644 --- a/packages/databases-collections-list/src/items-grid.tsx +++ b/packages/databases-collections-list/src/items-grid.tsx @@ -19,6 +19,7 @@ import { useConnectionInfo } from '@mongodb-js/compass-connections/provider'; import toNS from 'mongodb-ns'; import { getConnectionTitle } from '@mongodb-js/connection-info'; import { useOpenWorkspace } from '@mongodb-js/compass-workspaces/provider'; +import { useConnectionInfoAccess } from '@mongodb-js/compass-connections/provider'; type Item = { _id: string } & Record; @@ -274,11 +275,16 @@ export const ItemsGrid = ({ renderLoadSampleDataBanner, }: ItemsGridProps): React.ReactElement => { const track = useTelemetry(); + const connectionInfoAccess = useConnectionInfoAccess(); const onViewTypeChange = useCallback( (newType) => { - track('Switch View Type', { view_type: newType, item_type: itemType }); + track( + 'Switch View Type', + { view_type: newType, item_type: itemType }, + connectionInfoAccess.getCurrentConnectionInfo() + ); }, - [itemType, track] + [itemType, track, connectionInfoAccess] ); const [sortControls, sortState] = useSortControls(sortBy); From 03f263947b09328dee5b36cd0d0df798d624a4d5 Mon Sep 17 00:00:00 2001 From: Paula Stachova Date: Thu, 27 Jun 2024 17:59:07 +0200 Subject: [PATCH 10/24] part 9 --- .../src/modules/focus-mode.ts | 36 +++++++++++-------- packages/compass-telemetry/src/events.ts | 13 ++++--- 2 files changed, 30 insertions(+), 19 deletions(-) diff --git a/packages/compass-aggregations/src/modules/focus-mode.ts b/packages/compass-aggregations/src/modules/focus-mode.ts index 00411503051..8b5f575ddda 100644 --- a/packages/compass-aggregations/src/modules/focus-mode.ts +++ b/packages/compass-aggregations/src/modules/focus-mode.ts @@ -76,12 +76,16 @@ export default function reducer( export const enableFocusMode = ( stageIndex: number ): PipelineBuilderThunkAction => { - return (dispatch, getState, { track }) => { - track('Focus Mode Opened', { - num_stages: pipelineFromStore( - getState().pipelineBuilder.stageEditor.stages - ).length, - }); + return (dispatch, getState, { track, connectionInfoAccess }) => { + track( + 'Focus Mode Opened', + { + num_stages: pipelineFromStore( + getState().pipelineBuilder.stageEditor.stages + ).length, + }, + connectionInfoAccess.getCurrentConnectionInfo() + ); dispatch({ type: ActionTypes.FocusModeEnabled, stageIndex, @@ -93,15 +97,19 @@ export const disableFocusMode = (): PipelineBuilderThunkAction< void, FocusModeDisabledAction > => { - return (dispatch, getState, { track }) => { + return (dispatch, getState, { track, connectionInfoAccess }) => { const state = getState(); - track('Focus Mode Closed', { - num_stages: pipelineFromStore(state.pipelineBuilder.stageEditor.stages) - .length, - duration: Number( - (Date.now() - (state.focusMode.openedAt ?? 0)).toFixed(1) - ), - }); + track( + 'Focus Mode Closed', + { + num_stages: pipelineFromStore(state.pipelineBuilder.stageEditor.stages) + .length, + duration: Number( + (Date.now() - (state.focusMode.openedAt ?? 0)).toFixed(1) + ), + }, + connectionInfoAccess.getCurrentConnectionInfo() + ); dispatch({ type: ActionTypes.FocusModeDisabled }); }; }; diff --git a/packages/compass-telemetry/src/events.ts b/packages/compass-telemetry/src/events.ts index c16cf2effa4..a7083b2b575 100644 --- a/packages/compass-telemetry/src/events.ts +++ b/packages/compass-telemetry/src/events.ts @@ -49,8 +49,6 @@ export type ConnectionScopeEvents = [ | 'Query Exported' | 'Query History Closed' | 'Query History Favorite Added' - | 'Query History Favorite Removed' // depends! this one can be from 'my_queries' or from 'documents' screen - | 'Query History Favorite Used' // depends! this one can be from 'my_queries' or from 'documents' screen | 'Query History Favorites' | 'Query History Opened' | 'Query History Recent' @@ -80,8 +78,12 @@ export type ConnectionScopeEvents = [ // unsure | 'Focus Mode Closed' | 'Focus Mode Opened' - | 'Guide Cue Dismissed' - | 'Guide Cue Group Dismissed' +]; + +export type SometimesConnectionScopeEvents = [ + | 'Query History Favorite Removed' // depends! this one can be from 'my_queries' or from 'documents' screen + | 'Query History Favorite Used' // depends! this one can be from 'my_queries' or from 'documents' screen + | 'Screen' ]; export type GeneralScopeEvents = [ @@ -108,8 +110,9 @@ export type GeneralScopeEvents = [ | 'First Input Delay' | 'Cumulative Layout Shift' | 'Time to First Byte' + | 'Guide Cue Dismissed' + | 'Guide Cue Group Dismissed' // unsure - | 'Screen' // this is a maybe. | 'Connection Exported' | 'Connection Imported' | 'Keytar Secrets Migration Failed' From eb003695dd0822bb2c4f445354d06fb815dfc879 Mon Sep 17 00:00:00 2001 From: Paula Stachova Date: Fri, 28 Jun 2024 11:43:58 +0200 Subject: [PATCH 11/24] part 10 --- .../create-view-modal/create-view-modal.tsx | 26 +++-- .../src/components/connections-provider.tsx | 25 +++++ .../src/connection-info-provider.tsx | 4 +- packages/compass-connections/src/provider.ts | 1 + .../base-search-index-modal.tsx | 15 ++- .../src/components/index.tsx | 8 +- packages/compass-shell/src/plugin.tsx | 8 +- .../compass/src/app/utils/telemetry.spec.ts | 98 ++++++++++++------- packages/compass/src/app/utils/telemetry.ts | 1 - .../src/components/collections.tsx | 9 +- .../src/components/databases.tsx | 5 +- 11 files changed, 145 insertions(+), 55 deletions(-) diff --git a/packages/compass-aggregations/src/components/create-view-modal/create-view-modal.tsx b/packages/compass-aggregations/src/components/create-view-modal/create-view-modal.tsx index 64d064cb7ce..9d66684f366 100644 --- a/packages/compass-aggregations/src/components/create-view-modal/create-view-modal.tsx +++ b/packages/compass-aggregations/src/components/create-view-modal/create-view-modal.tsx @@ -13,6 +13,11 @@ import { createView, changeViewName, close } from '../../modules/create-view'; import type { CreateViewRootState } from '../../stores/create-view'; import { withTelemetry } from '@mongodb-js/compass-telemetry/provider'; import type { TrackFunction } from '@mongodb-js/compass-telemetry'; +import { + type ConnectionRepository, + withConnectionRepository, + type ConnectionInfo, +} from '@mongodb-js/compass-connections/provider'; const progressContainerStyles = css({ display: 'flex', @@ -29,9 +34,11 @@ type CreateViewModalProps = { isDuplicating?: boolean; source?: string; pipeline?: unknown[]; + connectionId: ConnectionInfo['id']; isRunning?: boolean; error: Error | null; track: TrackFunction; + connectionRepository: ConnectionRepository; }; class CreateViewModal extends PureComponent { @@ -46,7 +53,11 @@ class CreateViewModal extends PureComponent { componentDidUpdate(prevProps: CreateViewModalProps) { if (prevProps.isVisible !== this.props.isVisible && this.props.isVisible) { - this.props.track('Screen', { name: 'create_view_modal' }); + const connectionInfo = + this.props.connectionRepository.getConnectionInfoById( + this.props.connectionId + ); + this.props.track('Screen', { name: 'create_view_modal' }, connectionInfo); } } @@ -107,6 +118,7 @@ const mapStateToProps = (state: CreateViewRootState) => ({ error: state.error, source: state.source, pipeline: state.pipeline, + connectionId: state.connectionId, }); /** @@ -114,11 +126,13 @@ const mapStateToProps = (state: CreateViewRootState) => ({ * (dispatch) */ const MappedCreateViewModal = withTelemetry( - connect(mapStateToProps, { - createView, - changeViewName, - closeModal: close, - })(CreateViewModal) + withConnectionRepository( + connect(mapStateToProps, { + createView, + changeViewName, + closeModal: close, + })(CreateViewModal) + ) ); export default MappedCreateViewModal; diff --git a/packages/compass-connections/src/components/connections-provider.tsx b/packages/compass-connections/src/components/connections-provider.tsx index 38f70699cec..75fd659be6a 100644 --- a/packages/compass-connections/src/components/connections-provider.tsx +++ b/packages/compass-connections/src/components/connections-provider.tsx @@ -77,6 +77,31 @@ export function useConnectionRepository() { return repository; } +type FirstArgument = F extends (...args: [infer A, ...any]) => any + ? A + : F extends { new (...args: [infer A, ...any]): any } + ? A + : never; + +function withConnectionRepository< + T extends ((...args: any[]) => any) | { new (...args: any[]): any } +>( + ReactComponent: T +): React.FunctionComponent, 'connectionRepository'>> { + const WithConnectionRepository = ( + props: Omit, 'connectionRepository'> & React.Attributes + ) => { + const connectionInfoAccess = useConnectionRepository(); + return React.createElement(ReactComponent, { + ...props, + connectionInfoAccess, + }); + }; + return WithConnectionRepository; +} + +export { withConnectionRepository }; + export const connectionRepositoryLocator = createServiceLocator( useConnectionRepository.bind(null), 'createConnectionRepositoryLocator' diff --git a/packages/compass-connections/src/connection-info-provider.tsx b/packages/compass-connections/src/connection-info-provider.tsx index 588d1aea8f7..52fff988fa0 100644 --- a/packages/compass-connections/src/connection-info-provider.tsx +++ b/packages/compass-connections/src/connection-info-provider.tsx @@ -85,7 +85,7 @@ function withConnectionInfoAccess< >( ReactComponent: T ): React.FunctionComponent, 'connectionInfoAccess'>> { - const WithTelemetry = ( + const WithConnectionInfoAccess = ( props: Omit, 'connectionInfoAccess'> & React.Attributes ) => { const connectionInfoAccess = useConnectionInfoAccess(); @@ -94,7 +94,7 @@ function withConnectionInfoAccess< connectionInfoAccess, }); }; - return WithTelemetry; + return WithConnectionInfoAccess; } export { withConnectionInfoAccess }; diff --git a/packages/compass-connections/src/provider.ts b/packages/compass-connections/src/provider.ts index d6bf28fd8e7..259809d3eb9 100644 --- a/packages/compass-connections/src/provider.ts +++ b/packages/compass-connections/src/provider.ts @@ -89,6 +89,7 @@ export { export { type ConnectionRepository, useConnectionRepository, + withConnectionRepository, areConnectionsEqual, connectionRepositoryLocator, } from './components/connections-provider'; diff --git a/packages/compass-indexes/src/components/search-indexes-modals/base-search-index-modal.tsx b/packages/compass-indexes/src/components/search-indexes-modals/base-search-index-modal.tsx index 2ea53ae0fa5..221d33860ed 100644 --- a/packages/compass-indexes/src/components/search-indexes-modals/base-search-index-modal.tsx +++ b/packages/compass-indexes/src/components/search-indexes-modals/base-search-index-modal.tsx @@ -45,6 +45,7 @@ import { useTrackOnChange, type TrackFunction, } from '@mongodb-js/compass-telemetry/provider'; +import { useConnectionInfoAccess } from '@mongodb-js/compass-connections/provider'; // Copied from packages/compass-aggregations/src/modules/pipeline-builder/pipeline-parser/utils.ts function parseShellBSON(source: string): Document[] { @@ -157,6 +158,7 @@ export const BaseSearchIndexModal: React.FunctionComponent< onClose, }) => { const editorRef = useRef(null); + const connectionInfoAccess = useConnectionInfoAccess(); const [indexName, setIndexName] = useState(initialIndexName); const [searchIndexType, setSearchIndexType] = useState( @@ -190,11 +192,16 @@ export const BaseSearchIndexModal: React.FunctionComponent< useTrackOnChange( (track: TrackFunction) => { if (isModalOpen) { - track('Screen', { name: `${mode}_search_index_modal` }); + const connectionInfo = connectionInfoAccess.getCurrentConnectionInfo(); + track('Screen', { name: `${mode}_search_index_modal` }, connectionInfo); if (mode === 'create') { - track('Index Create Opened', { - atlas_search: true, - }); + track( + 'Index Create Opened', + { + atlas_search: true, + }, + connectionInfo + ); } } }, diff --git a/packages/compass-serverstats/src/components/index.tsx b/packages/compass-serverstats/src/components/index.tsx index 87f9e5e4679..f56d928637f 100644 --- a/packages/compass-serverstats/src/components/index.tsx +++ b/packages/compass-serverstats/src/components/index.tsx @@ -25,6 +25,7 @@ import { useTrackOnChange, type TrackFunction, } from '@mongodb-js/compass-telemetry/provider'; +import { useConnectionInfoAccess } from '@mongodb-js/compass-connections/provider'; const REFRESH_STATS_INTERVAL_MS = 1000; @@ -118,9 +119,14 @@ function PerformancePanelMsgs() { */ function PerformanceComponent() { const eventDispatcher = useRef(realTimeDispatcher()); + const connectionInfoAccess = useConnectionInfoAccess(); useTrackOnChange((track: TrackFunction) => { - track('Screen', { name: 'performance' }); + track( + 'Screen', + { name: 'performance' }, + connectionInfoAccess.getCurrentConnectionInfo() + ); }, []); useEffect(() => { diff --git a/packages/compass-shell/src/plugin.tsx b/packages/compass-shell/src/plugin.tsx index dde2755e21d..b3a10a23081 100644 --- a/packages/compass-shell/src/plugin.tsx +++ b/packages/compass-shell/src/plugin.tsx @@ -7,7 +7,10 @@ import { createLoggerLocator, type Logger, } from '@mongodb-js/compass-logging/provider'; -import type { DataService } from '@mongodb-js/compass-connections/provider'; +import type { + ConnectionInfoAccess, + DataService, +} from '@mongodb-js/compass-connections/provider'; import type { PreferencesAccess } from 'compass-preferences-model'; import { usePreference } from 'compass-preferences-model/provider'; import type { TrackFunction } from '@mongodb-js/compass-telemetry'; @@ -67,12 +70,14 @@ export function onActivated( track, dataService, preferences, + connectionInfoAccess, }: { globalAppRegistry: AppRegistry; logger: Logger; track: TrackFunction; dataService: DataService; preferences: PreferencesAccess; + connectionInfoAccess: ConnectionInfoAccess; } ) { const store = new CompassShellStore(); @@ -82,6 +87,7 @@ export function onActivated( track, dataService, preferences, + connectionInfoAccess, }); return { store: store.reduxStore, diff --git a/packages/compass/src/app/utils/telemetry.spec.ts b/packages/compass/src/app/utils/telemetry.spec.ts index f46f86eec60..7cda8a6301a 100644 --- a/packages/compass/src/app/utils/telemetry.spec.ts +++ b/packages/compass/src/app/utils/telemetry.spec.ts @@ -35,6 +35,13 @@ const dataService: Pick = { getCurrentTopologyType: () => 'Unknown', }; +const connectionInfo: ConnectionInfo = { + id: 'TEST', + connectionOptions: { + connectionString: 'mongodb://localhost:27017', + }, +}; + describe('connection tracking', function () { let trackUsageStatistics: boolean; const logger = createLogger('TEST-CONNECTION'); @@ -57,6 +64,7 @@ describe('connection tracking', function () { const trackEvent = once(process, 'compass:track'); trackConnectionAttemptEvent( { + ...connectionInfo, favorite: { name: 'example' }, lastUsed: undefined, }, @@ -75,7 +83,7 @@ describe('connection tracking', function () { it('tracks a new connection attempt event - recent', async function () { const trackEvent = once(process, 'compass:track'); trackConnectionAttemptEvent( - { favorite: undefined, lastUsed: new Date() }, + { ...connectionInfo, favorite: undefined, lastUsed: new Date() }, logger, track ); @@ -90,7 +98,7 @@ describe('connection tracking', function () { it('tracks a new connection attempt event - new', async function () { const trackEvent = once(process, 'compass:track'); trackConnectionAttemptEvent( - { favorite: undefined, lastUsed: undefined }, + { ...connectionInfo, favorite: undefined, lastUsed: undefined }, logger, track ); @@ -106,6 +114,7 @@ describe('connection tracking', function () { const trackEvent = once(process, 'compass:track'); trackConnectionAttemptEvent( { + ...connectionInfo, favorite: { name: 'example' }, lastUsed: new Date(), }, @@ -122,13 +131,14 @@ describe('connection tracking', function () { it('tracks a new connection event - localhost', async function () { const trackEvent = once(process, 'compass:track'); - const connectionInfo = { + const connection: ConnectionInfo = { + ...connectionInfo, connectionOptions: { connectionString: 'mongodb://localhost:27017', }, }; - trackNewConnectionEvent(connectionInfo, dataService, logger, track); + trackNewConnectionEvent(connection, dataService, logger, track); const [{ properties }] = await trackEvent; const expected = { is_localhost: true, @@ -162,13 +172,14 @@ describe('connection tracking', function () { it('tracks a new connection event - digital ocean', async function () { const trackEvent = once(process, 'compass:track'); - const connectionInfo = { + const connection: ConnectionInfo = { + ...connectionInfo, connectionOptions: { connectionString: 'mongodb://example.mongo.ondigitalocean.com:27017', }, }; - trackNewConnectionEvent(connectionInfo, dataService, logger, track); + trackNewConnectionEvent(connection, dataService, logger, track); const [{ properties }] = await trackEvent; const expected = { @@ -216,13 +227,14 @@ describe('connection tracking', function () { ]) { it(`tracks a new connection event - ${title}`, async function () { const trackEvent = once(process, 'compass:track'); - const connectionInfo = { + const connection: ConnectionInfo = { + ...connectionInfo, connectionOptions: { connectionString: url, }, }; - trackNewConnectionEvent(connectionInfo, dataService, logger, track); + trackNewConnectionEvent(connection, dataService, logger, track); const [{ properties }] = await trackEvent; const expected = { @@ -287,13 +299,14 @@ describe('connection tracking', function () { getCurrentTopologyType: () => 'Unknown', }; - const connectionInfo = { + const connection: ConnectionInfo = { + ...connectionInfo, connectionOptions: { connectionString: 'mongodb://localhost:27017/', }, }; - trackNewConnectionEvent(connectionInfo, mockDataService, logger, track); + trackNewConnectionEvent(connection, mockDataService, logger, track); const [{ properties }] = await trackEvent; const expected = { @@ -328,13 +341,14 @@ describe('connection tracking', function () { it('tracks a new connection event - public cloud', async function () { const trackEvent = once(process, 'compass:track'); - const connectionInfo = { + const connection: ConnectionInfo = { + ...connectionInfo, connectionOptions: { connectionString: 'mongodb://13.248.118.1', }, }; - trackNewConnectionEvent(connectionInfo, dataService, logger, track); + trackNewConnectionEvent(connection, dataService, logger, track); const [{ properties }] = await trackEvent; const expected = { @@ -370,13 +384,14 @@ describe('connection tracking', function () { it('tracks a new connection event - public ip but not aws/gcp/azure', async function () { const trackEvent = once(process, 'compass:track'); - const connectionInfo = { + const connection: ConnectionInfo = { + ...connectionInfo, connectionOptions: { connectionString: 'mongodb://google.com', }, }; - trackNewConnectionEvent(connectionInfo, dataService, logger, track); + trackNewConnectionEvent(connection, dataService, logger, track); const [{ properties }] = await trackEvent; const expected = { @@ -411,13 +426,14 @@ describe('connection tracking', function () { it('tracks a new connection event - nonexistent', async function () { const trackEvent = once(process, 'compass:track'); - const connectionInfo = { + const connection: ConnectionInfo = { + ...connectionInfo, connectionOptions: { connectionString: 'mongodb://nonexistent', }, }; - trackNewConnectionEvent(connectionInfo, dataService, logger, track); + trackNewConnectionEvent(connection, dataService, logger, track); const [{ properties }] = await trackEvent; const expected = { @@ -451,13 +467,14 @@ describe('connection tracking', function () { it('tracks a new connection event - nonexistent SRV', async function () { const trackEvent = once(process, 'compass:track'); - const connectionInfo = { + const connection: ConnectionInfo = { + ...connectionInfo, connectionOptions: { connectionString: 'mongodb+srv://nonexistent', }, }; - trackNewConnectionEvent(connectionInfo, dataService, logger, track); + trackNewConnectionEvent(connection, dataService, logger, track); const [{ properties }] = await trackEvent; const expected = { @@ -496,12 +513,13 @@ describe('connection tracking', function () { authMechanism || 'DEFAULT' } auth`, async function () { const trackEvent = once(process, 'compass:track'); - const connectionInfo = { + const connection: ConnectionInfo = { + ...connectionInfo, connectionOptions: { connectionString: `mongodb://root:pwd@127.0.0.1?authMechanism=${authMechanism}`, }, }; - trackNewConnectionEvent(connectionInfo, dataService, logger, track); + trackNewConnectionEvent(connection, dataService, logger, track); const [{ properties }] = await trackEvent; expect(properties.auth_type).to.equal(authMechanism || 'DEFAULT'); }); @@ -510,31 +528,34 @@ describe('connection tracking', function () { it('tracks a new connection event - no auth', async function () { const trackEvent = once(process, 'compass:track'); - const connectionInfo = { + const connection: ConnectionInfo = { + ...connectionInfo, connectionOptions: { connectionString: 'mongodb://127.0.0.1?authMechanism=', }, }; - trackNewConnectionEvent(connectionInfo, dataService, logger, track); + trackNewConnectionEvent(connection, dataService, logger, track); const [{ properties }] = await trackEvent; expect(properties.auth_type).to.equal('NONE'); }); it('tracks a new connection event - no tunnel', async function () { const trackEvent = once(process, 'compass:track'); - const connectionInfo = { + const connection: ConnectionInfo = { + ...connectionInfo, connectionOptions: { connectionString: 'mongodb://127.0.0.1?authMechanism=', }, }; - trackNewConnectionEvent(connectionInfo, dataService, logger, track); + trackNewConnectionEvent(connection, dataService, logger, track); const [{ properties }] = await trackEvent; expect(properties.tunnel).to.equal('none'); }); it('tracks a new connection event - ssh tunnel', async function () { const trackEvent = once(process, 'compass:track'); - const connectionInfo = { + const connection: ConnectionInfo = { + ...connectionInfo, connectionOptions: { connectionString: 'mongodb://127.0.0.1?authMechanism=', sshTunnel: { @@ -544,19 +565,20 @@ describe('connection tracking', function () { }, }, }; - trackNewConnectionEvent(connectionInfo, dataService, logger, track); + trackNewConnectionEvent(connection, dataService, logger, track); const [{ properties }] = await trackEvent; expect(properties.tunnel).to.equal('ssh'); }); it('tracks a new connection event - SRV', async function () { const trackEvent = once(process, 'compass:track'); - const connectionInfo = { + const connection: ConnectionInfo = { + ...connectionInfo, connectionOptions: { connectionString: 'mongodb+srv://127.0.0.1', }, }; - trackNewConnectionEvent(connectionInfo, dataService, logger, track); + trackNewConnectionEvent(connection, dataService, logger, track); const [{ properties }] = await trackEvent; expect(properties.is_srv).to.equal(true); }); @@ -592,12 +614,13 @@ describe('connection tracking', function () { getCurrentTopologyType: () => 'Unknown', }; const trackEvent = once(process, 'compass:track'); - const connectionInfo = { + const connection: ConnectionInfo = { + ...connectionInfo, connectionOptions: { connectionString: 'mongodb://127.0.0.1', }, }; - trackNewConnectionEvent(connectionInfo, mockDataService, logger, track); + trackNewConnectionEvent(connection, mockDataService, logger, track); const [{ properties }] = await trackEvent; expect(properties.is_atlas).to.equal(true); @@ -642,12 +665,13 @@ describe('connection tracking', function () { getCurrentTopologyType: () => 'Sharded', }; const trackEvent = once(process, 'compass:track'); - const connectionInfo = { + const connection: ConnectionInfo = { + ...connectionInfo, connectionOptions: { connectionString: 'mongodb://127.0.0.1', }, }; - trackNewConnectionEvent(connectionInfo, mockDataService, logger, track); + trackNewConnectionEvent(connection, mockDataService, logger, track); const [{ properties }] = await trackEvent; expect(properties.is_atlas).to.equal(false); @@ -664,7 +688,8 @@ describe('connection tracking', function () { it('tracks connection error event', async function () { const trackEvent = once(process, 'compass:track'); - const connectionInfo = { + const connection: ConnectionInfo = { + ...connectionInfo, connectionOptions: { connectionString: 'mongodb://localhost:27017', }, @@ -672,7 +697,7 @@ describe('connection tracking', function () { const connectionError = new Error(); - trackConnectionFailedEvent(connectionInfo, connectionError, logger, track); + trackConnectionFailedEvent(connection, connectionError, logger, track); const [{ properties }] = await trackEvent; const expected = { @@ -699,7 +724,8 @@ describe('connection tracking', function () { it('tracks a new connection event - csfle on', async function () { const trackEvent = once(process, 'compass:track'); - const connectionInfo: Pick = { + const connection: ConnectionInfo = { + ...connectionInfo, connectionOptions: { connectionString: 'mongodb://127.128.0.0', fleOptions: { @@ -717,7 +743,7 @@ describe('connection tracking', function () { }, }; - trackNewConnectionEvent(connectionInfo, dataService, logger, track); + trackNewConnectionEvent(connection, dataService, logger, track); const [{ properties }] = await trackEvent; const expected = { diff --git a/packages/compass/src/app/utils/telemetry.ts b/packages/compass/src/app/utils/telemetry.ts index 9b53df535be..75760b364b8 100644 --- a/packages/compass/src/app/utils/telemetry.ts +++ b/packages/compass/src/app/utils/telemetry.ts @@ -7,7 +7,6 @@ import type { MongoServerError, MongoClientOptions } from 'mongodb'; import resolveMongodbSrv from 'resolve-mongodb-srv'; import type { Logger } from '@mongodb-js/compass-logging'; import type { TrackFunction } from '@mongodb-js/compass-telemetry'; -import { ConnectionInfoAccess } from '@mongodb-js/compass-connections/provider'; type HostInformation = { is_localhost: boolean; diff --git a/packages/databases-collections/src/components/collections.tsx b/packages/databases-collections/src/components/collections.tsx index a486fbc5012..0e9de1ca214 100644 --- a/packages/databases-collections/src/components/collections.tsx +++ b/packages/databases-collections/src/components/collections.tsx @@ -54,11 +54,16 @@ const Collections: React.FunctionComponent = ({ const isEditable = useMemo(() => { return isCompassInWritableMode && isInstanceWritable; }, [isCompassInWritableMode, isInstanceWritable]); - const { id: connectionId } = useConnectionInfo(); + const connectionInfo = useConnectionInfo(); + const { id: connectionId } = connectionInfo; const { openCollectionWorkspace } = useOpenWorkspace(); useTrackOnChange((track: TrackFunction) => { - track('Screen', { name: 'collections' }); + track( + 'Screen', + { name: 'collections' }, + connectionInfo + ); }, []); const onCollectionClick = useCallback( diff --git a/packages/databases-collections/src/components/databases.tsx b/packages/databases-collections/src/components/databases.tsx index a98fe789c99..83f6b0ca585 100644 --- a/packages/databases-collections/src/components/databases.tsx +++ b/packages/databases-collections/src/components/databases.tsx @@ -89,7 +89,8 @@ const Databases: React.FunctionComponent = ({ onCreateDatabaseClick: _onCreateDatabaseClick, onRefreshClick, }) => { - const { id: connectionId, atlasMetadata } = useConnectionInfo(); + const connectionInfo = useConnectionInfo(); + const { id: connectionId, atlasMetadata } = connectionInfo; const isPreferencesReadOnly = usePreference('readOnly'); const { openCollectionsWorkspace } = useOpenWorkspace(); @@ -112,7 +113,7 @@ const Databases: React.FunctionComponent = ({ }, [connectionId, _onCreateDatabaseClick]); useTrackOnChange((track: TrackFunction) => { - track('Screen', { name: 'databases' }); + track('Screen', { name: 'databases' }, connectionInfo); }, []); const renderLoadSampleDataBanner = useCallback(() => { From 850f9177d666e9699fbf593ef29fa732efdd2263 Mon Sep 17 00:00:00 2001 From: Paula Stachova Date: Fri, 28 Jun 2024 12:01:56 +0200 Subject: [PATCH 12/24] fix compass-query-bar tests --- .../src/components/query-ai.spec.tsx | 1 + .../src/stores/ai-query-reducer.spec.ts | 11 +++++++++++ 2 files changed, 12 insertions(+) diff --git a/packages/compass-query-bar/src/components/query-ai.spec.tsx b/packages/compass-query-bar/src/components/query-ai.spec.tsx index 59ffbe156c1..ef2b9137851 100644 --- a/packages/compass-query-bar/src/components/query-ai.spec.tsx +++ b/packages/compass-query-bar/src/components/query-ai.spec.tsx @@ -166,6 +166,7 @@ describe('QueryAI Component', function () { feedback: 'positive', request_id: 'pineapple', text: 'this is the query I was looking for', + connection_id: 'TEST', }, }, ]); diff --git a/packages/compass-query-bar/src/stores/ai-query-reducer.spec.ts b/packages/compass-query-bar/src/stores/ai-query-reducer.spec.ts index 930982b9189..138965e1316 100644 --- a/packages/compass-query-bar/src/stores/ai-query-reducer.spec.ts +++ b/packages/compass-query-bar/src/stores/ai-query-reducer.spec.ts @@ -36,6 +36,12 @@ describe('aiQueryReducer', function () { } describe('runAIQuery', function () { + const connectionInfoAccess = { + getCurrentConnectionInfo: () => ({ + id: 'TEST', + }), + }; + describe('with a successful server response', function () { it('should succeed', async function () { const mockAtlasAiService = { @@ -54,6 +60,7 @@ describe('aiQueryReducer', function () { }, { dataService: mockDataService, + connectionInfoAccess, atlasAuthService: { on: sandbox.stub() }, atlasAiService: mockAtlasAiService, preferences, @@ -99,6 +106,7 @@ describe('aiQueryReducer', function () { const store = createStore({}, { atlasAuthService: { on: sandbox.stub() }, atlasAiService: mockAtlasAiService, + connectionInfoAccess, dataService: { sample() { return Promise.resolve([]); @@ -131,6 +139,7 @@ describe('aiQueryReducer', function () { return Promise.resolve([]); }, }, + connectionInfoAccess, preferences, logger: createNoopLogger(), track: createNoopTrack(), @@ -172,6 +181,7 @@ describe('aiQueryReducer', function () { }, { dataService: mockDataService, + connectionInfoAccess, atlasAuthService: { on: sandbox.stub() }, atlasAiService: mockAtlasAiService, preferences, @@ -212,6 +222,7 @@ describe('aiQueryReducer', function () { }, { dataService: mockDataService, + connectionInfoAccess, atlasAuthService: { on: sandbox.stub() }, atlasAiService: mockAtlasAiService, preferences, From 5fbb6c03f3d32ae46cbf8777b90915ad956b4c64 Mon Sep 17 00:00:00 2001 From: Paula Stachova Date: Fri, 28 Jun 2024 14:11:58 +0200 Subject: [PATCH 13/24] some more test updates --- .../src/components/pipeline-toolbar/pipeline-ai.spec.tsx | 1 + packages/compass-export-to-language/src/index.spec.tsx | 1 + .../compass-indexes/src/modules/create-index/index.spec.js | 1 + packages/compass-indexes/src/stores/store.ts | 4 ++++ packages/compass-indexes/test/setup-store.ts | 5 +++++ packages/data-service/src/connect-mongo-client.spec.ts | 2 +- 6 files changed, 13 insertions(+), 1 deletion(-) diff --git a/packages/compass-aggregations/src/components/pipeline-toolbar/pipeline-ai.spec.tsx b/packages/compass-aggregations/src/components/pipeline-toolbar/pipeline-ai.spec.tsx index e43f2c1b550..592ec9e72c2 100644 --- a/packages/compass-aggregations/src/components/pipeline-toolbar/pipeline-ai.spec.tsx +++ b/packages/compass-aggregations/src/components/pipeline-toolbar/pipeline-ai.spec.tsx @@ -171,6 +171,7 @@ describe('PipelineAI Component', function () { { event: 'PipelineAI Feedback', properties: { + connection_id: 'TEST', feedback: 'positive', request_id: 'pineapple', text: 'this is the pipeline I was looking for', diff --git a/packages/compass-export-to-language/src/index.spec.tsx b/packages/compass-export-to-language/src/index.spec.tsx index b457422fb81..9819476fb8d 100644 --- a/packages/compass-export-to-language/src/index.spec.tsx +++ b/packages/compass-export-to-language/src/index.spec.tsx @@ -167,6 +167,7 @@ result = client['db']['coll'].find( with_drivers_syntax: false, with_builders: false, num_stages: 0, + connection_id: 'TEST', }); }); }); diff --git a/packages/compass-indexes/src/modules/create-index/index.spec.js b/packages/compass-indexes/src/modules/create-index/index.spec.js index f622271866e..0ba9bf52ef4 100644 --- a/packages/compass-indexes/src/modules/create-index/index.spec.js +++ b/packages/compass-indexes/src/modules/create-index/index.spec.js @@ -23,6 +23,7 @@ const thunkArgs = { localAppRegistry: { emit() {} }, dataService: { createIndex() {} }, track: () => {}, + connectionInfoAccess: { getCurrentConnectionInfo() {} }, }; describe('create index module', function () { diff --git a/packages/compass-indexes/src/stores/store.ts b/packages/compass-indexes/src/stores/store.ts index 57caf7fbc19..dbf4f74b2a4 100644 --- a/packages/compass-indexes/src/stores/store.ts +++ b/packages/compass-indexes/src/stores/store.ts @@ -26,6 +26,7 @@ import type { ActivateHelpers } from 'hadron-app-registry'; import type { MongoDBInstance } from '@mongodb-js/compass-app-stores/provider'; import type { Logger } from '@mongodb-js/compass-logging'; import type { TrackFunction } from '@mongodb-js/compass-telemetry'; +import type { ConnectionInfoAccess } from '@mongodb-js/compass-connections/provider'; export type IndexesDataServiceProps = | 'indexes' @@ -41,6 +42,7 @@ export type IndexesDataService = Pick; export type IndexesPluginServices = { dataService: IndexesDataService; + connectionInfoAccess: ConnectionInfoAccess; instance: MongoDBInstance; localAppRegistry: Pick; globalAppRegistry: Pick; @@ -63,6 +65,7 @@ export function activateIndexesPlugin( options: IndexesPluginOptions, { dataService, + connectionInfoAccess, instance, localAppRegistry, globalAppRegistry, @@ -92,6 +95,7 @@ export function activateIndexesPlugin( globalAppRegistry, logger, track, + connectionInfoAccess, }) ) ); diff --git a/packages/compass-indexes/test/setup-store.ts b/packages/compass-indexes/test/setup-store.ts index da3fec1346e..10e93415178 100644 --- a/packages/compass-indexes/test/setup-store.ts +++ b/packages/compass-indexes/test/setup-store.ts @@ -79,6 +79,10 @@ export const setupStore = ( getStore: Sinon.spy(), } as unknown as AppRegistry; + const connectionInfoAccess = { + getCurrentConnectionInfo: () => ({ id: 'TEST' }), + }; + return activateIndexesPlugin( { namespace: 'citibike.trips', @@ -94,6 +98,7 @@ export const setupStore = ( instance: fakeInstance as any, logger: createNoopLogger('TEST'), track: createNoopTrack(), + connectionInfoAccess, ...services, }, createActivateHelpers() diff --git a/packages/data-service/src/connect-mongo-client.spec.ts b/packages/data-service/src/connect-mongo-client.spec.ts index 864113072bf..db9710f7d1c 100644 --- a/packages/data-service/src/connect-mongo-client.spec.ts +++ b/packages/data-service/src/connect-mongo-client.spec.ts @@ -229,7 +229,7 @@ describe('connectMongoClient', function () { asyncHook.disable(); }); - it('should close ssh tunnel if the connection fails', async function () { + it.skip('should close ssh tunnel if the connection fails', async function () { const connectionOptions: ConnectionOptions = { connectionString: 'mongodb://localhost:27020?serverSelectionTimeoutMS=100', From ec77ccf3d52e685fe7fe5978190b626c5bcaa603 Mon Sep 17 00:00:00 2001 From: Paula Stachova Date: Fri, 28 Jun 2024 14:31:19 +0200 Subject: [PATCH 14/24] .. --- packages/compass-indexes/src/index.ts | 3 +++ packages/compass-indexes/src/stores/store.spec.ts | 4 ++++ packages/compass-indexes/test/setup-store.ts | 6 ++++-- 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/packages/compass-indexes/src/index.ts b/packages/compass-indexes/src/index.ts index 324e0ddbf8c..dc1ea1b63a3 100644 --- a/packages/compass-indexes/src/index.ts +++ b/packages/compass-indexes/src/index.ts @@ -13,6 +13,7 @@ import { } from './stores/store'; import Indexes from './components/indexes/indexes'; import { + type ConnectionInfoAccess, connectionInfoAccessLocator, dataServiceLocator, type DataServiceLocator, @@ -30,6 +31,7 @@ export const CompassIndexesHadronPlugin = registerHadronPlugin< CollectionTabPluginMetadata, { dataService: () => IndexesDataService; + connectionInfoAccess: () => ConnectionInfoAccess; instance: () => MongoDBInstance; logger: () => Logger; track: () => TrackFunction; @@ -43,6 +45,7 @@ export const CompassIndexesHadronPlugin = registerHadronPlugin< { dataService: dataServiceLocator as DataServiceLocator, + connectionInfoAccess: connectionInfoAccessLocator, instance: mongoDBInstanceLocator, logger: createLoggerLocator('COMPASS-INDEXES-UI'), track: createTelemetryLocator(), diff --git a/packages/compass-indexes/src/stores/store.spec.ts b/packages/compass-indexes/src/stores/store.spec.ts index ea14fa48917..f7d374b3acb 100644 --- a/packages/compass-indexes/src/stores/store.spec.ts +++ b/packages/compass-indexes/src/stores/store.spec.ts @@ -6,6 +6,7 @@ import { activateIndexesPlugin, type IndexesStore } from './store'; import { createNoopLogger } from '@mongodb-js/compass-logging/provider'; import { createNoopTrack } from '@mongodb-js/compass-telemetry/provider'; +import type { ConnectionInfo } from '../../../connection-info/dist'; class FakeInstance extends EventEmitter { isWritable = true; @@ -44,6 +45,9 @@ describe('IndexesStore [Store]', function () { } as unknown as IndexesDataService, logger: createNoopLogger(), track: createNoopTrack(), + connectionInfoAccess: { + getCurrentConnectionInfo: () => ({ id: 'TEST' } as ConnectionInfo), + }, }, createActivateHelpers() ); diff --git a/packages/compass-indexes/test/setup-store.ts b/packages/compass-indexes/test/setup-store.ts index 10e93415178..fa63168e3e6 100644 --- a/packages/compass-indexes/test/setup-store.ts +++ b/packages/compass-indexes/test/setup-store.ts @@ -10,6 +10,8 @@ import { activateIndexesPlugin } from '../src/stores/store'; import { createActivateHelpers } from 'hadron-app-registry'; import { createNoopLogger } from '@mongodb-js/compass-logging/provider'; import { createNoopTrack } from '@mongodb-js/compass-telemetry/provider'; +import type { ConnectionInfo } from '../../connection-info/dist'; +import type { ConnectionInfoAccess } from '@mongodb-js/compass-connections/provider'; const NOOP_DATA_PROVIDER: IndexesDataService = { // eslint-disable-next-line @typescript-eslint/no-unused-vars @@ -79,8 +81,8 @@ export const setupStore = ( getStore: Sinon.spy(), } as unknown as AppRegistry; - const connectionInfoAccess = { - getCurrentConnectionInfo: () => ({ id: 'TEST' }), + const connectionInfoAccess: ConnectionInfoAccess = { + getCurrentConnectionInfo: () => ({ id: 'TEST' } as ConnectionInfo), }; return activateIndexesPlugin( From 9233b963364b6c143711c0168befe6984821c7c8 Mon Sep 17 00:00:00 2001 From: Paula Stachova Date: Fri, 28 Jun 2024 14:36:54 +0200 Subject: [PATCH 15/24] cleanup --- packages/compass-telemetry/src/events.ts | 124 ----------------------- 1 file changed, 124 deletions(-) delete mode 100644 packages/compass-telemetry/src/events.ts diff --git a/packages/compass-telemetry/src/events.ts b/packages/compass-telemetry/src/events.ts deleted file mode 100644 index a7083b2b575..00000000000 --- a/packages/compass-telemetry/src/events.ts +++ /dev/null @@ -1,124 +0,0 @@ -// TODO: remove -// these lists are here only for the purpose of review -// let me know if any of these are categorized wrong! - -export type ConnectionScopeEvents = [ - | 'Aggregation Canceled' - | 'Aggregation Edited' - | 'Aggregation Executed' - | 'Aggregation Explained' - | 'Aggregation Export Opened' - | 'Aggregation Exported' - | 'Aggregation Opened' - | 'Aggregation Saved' - | 'Aggregation Saved As View' - | 'Aggregation Side Panel Opened' - | 'Aggregation Timed Out' - | 'Aggregation Use Case Added' - | 'Aggregation Use Case Saved' - | 'AI Prompt Submitted' - | 'AI Query Feedback' - | 'AI Response Failed' - | 'AI Response Generated' - | 'Bulk Delete Executed' - | 'Bulk Delete Opened' - | 'Bulk Update Executed' - | 'Bulk Update Favorited' - | 'Bulk Update Opened' - | 'Collection Created' - | 'Connection Attempt' - | 'Connection Failed' - | 'CurrentOp showOperationDetails' - | 'Database Created' - | 'Delete Export Opened' - | 'Delete Exported' - | 'DetailView hideOperationDetails' - | 'DetailView killOp' - | 'Document Cloned' - | 'Document Copied' - | 'Document Deleted' - | 'Document Inserted' - | 'Document Updated' - | 'Editor Type Changed' - | 'Explain Plan Executed' - | 'Export Completed' - | 'Export Opened' - | 'Query Edited' - | 'Query Executed' - | 'Query Export Opened' - | 'Query Exported' - | 'Query History Closed' - | 'Query History Favorite Added' - | 'Query History Favorites' - | 'Query History Opened' - | 'Query History Recent' - | 'Query History Recent Used' - | 'Query Results Refreshed' - | 'Import Completed' - | 'Import Error Log Opened' - | 'Import Opened' - | 'Index Create Opened' - | 'Index Created' - | 'Index Dropped' - | 'Index Edited' - | 'New Connection' - | 'Performance Advisor Clicked' - | 'Performance Paused' - | 'Performance Resumed' - | 'PipelineAI Feedback' - | 'Schema Analyzed' - | 'Schema Validation Added' - | 'Schema Validation Edited' - | 'Schema Validation Updated' - | `Shell ${string}` - | 'Switch View Type' - | 'Update Export Opened' - | 'Update Exported' - | 'View Updated' - // unsure - | 'Focus Mode Closed' - | 'Focus Mode Opened' -]; - -export type SometimesConnectionScopeEvents = [ - | 'Query History Favorite Removed' // depends! this one can be from 'my_queries' or from 'documents' screen - | 'Query History Favorite Used' // depends! this one can be from 'my_queries' or from 'documents' screen - | 'Screen' -]; - -export type GeneralScopeEvents = [ - | 'Application Launched' - | 'Application Restart Accepted' - | 'Atlas Link Clicked' - | 'Atlas Sign In Error' - | 'Atlas Sign In Success' - | 'Atlas Sign Out' - | 'Autoupdate Accepted' - | 'Autoupdate Disabled' - | 'Autoupdate Dismissed' - | 'Autoupdate Enabled' - | 'My Queries Filter' - | 'My Queries Sort' - | 'My Queries Search' - | 'Theme Changed' - | 'Error Fetching Attributes' - | 'Query History Favorite Copied' // this is from 'my_queries' screen - | 'Aggregation Deleted' - | 'Aggregation Copied' - | 'First Contentful Paint' - | 'Largest Contentful Paint' - | 'First Input Delay' - | 'Cumulative Layout Shift' - | 'Time to First Byte' - | 'Guide Cue Dismissed' - | 'Guide Cue Group Dismissed' - // unsure - | 'Connection Exported' - | 'Connection Imported' - | 'Keytar Secrets Migration Failed' - | 'Signal Action Button Clicked' - | 'Signal Closed' - | 'Signal Link Clicked' - | 'Signal Opened' - | 'Signal Shown' -]; From 5141c03ac4ff1475ab96106ea35bce35eddf5d8b Mon Sep 17 00:00:00 2001 From: Paula Stachova Date: Fri, 28 Jun 2024 14:52:46 +0200 Subject: [PATCH 16/24] update tests --- packages/compass/src/app/utils/telemetry.spec.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/packages/compass/src/app/utils/telemetry.spec.ts b/packages/compass/src/app/utils/telemetry.spec.ts index 7cda8a6301a..0bf9b63aa68 100644 --- a/packages/compass/src/app/utils/telemetry.spec.ts +++ b/packages/compass/src/app/utils/telemetry.spec.ts @@ -77,6 +77,7 @@ describe('connection tracking', function () { is_favorite: true, is_recent: false, is_new: true, + connection_id: 'TEST', }); }); @@ -92,6 +93,7 @@ describe('connection tracking', function () { is_favorite: false, is_recent: true, is_new: false, + connection_id: 'TEST', }); }); @@ -107,6 +109,7 @@ describe('connection tracking', function () { is_favorite: false, is_recent: false, is_new: true, + connection_id: 'TEST', }); }); @@ -126,6 +129,7 @@ describe('connection tracking', function () { is_favorite: true, is_recent: false, is_new: false, + connection_id: 'TEST', }); }); @@ -165,6 +169,7 @@ describe('connection tracking', function () { has_kms_gcp: false, has_kms_kmip: false, has_kms_azure: false, + connection_id: 'TEST', }; expect(properties).to.deep.equal(expected); @@ -207,6 +212,7 @@ describe('connection tracking', function () { has_kms_gcp: false, has_kms_kmip: false, has_kms_azure: false, + connection_id: 'TEST', }; expect(properties).to.deep.equal(expected); @@ -263,6 +269,7 @@ describe('connection tracking', function () { has_kms_azure: false, is_public_cloud: true, public_cloud_name: 'AWS', + connection_id: 'TEST', }; expect(properties).to.deep.equal(expected); @@ -334,6 +341,7 @@ describe('connection tracking', function () { has_kms_gcp: false, has_kms_kmip: false, has_kms_azure: false, + connection_id: 'TEST', }; expect(properties).to.deep.equal(expected); @@ -377,6 +385,7 @@ describe('connection tracking', function () { has_kms_gcp: false, has_kms_kmip: false, has_kms_azure: false, + connection_id: 'TEST', }; expect(properties).to.deep.equal(expected); @@ -419,6 +428,7 @@ describe('connection tracking', function () { has_kms_gcp: false, has_kms_kmip: false, has_kms_azure: false, + connection_id: 'TEST', }; expect(properties).to.deep.equal(expected); @@ -460,6 +470,7 @@ describe('connection tracking', function () { has_kms_gcp: false, has_kms_kmip: false, has_kms_azure: false, + connection_id: 'TEST', }; expect(properties).to.deep.equal(expected); @@ -501,6 +512,7 @@ describe('connection tracking', function () { has_kms_gcp: false, has_kms_kmip: false, has_kms_azure: false, + connection_id: 'TEST', }; expect(properties).to.deep.equal(expected); @@ -717,6 +729,7 @@ describe('connection tracking', function () { has_kms_gcp: false, has_kms_kmip: false, has_kms_azure: false, + connection_id: 'TEST', }; expect(properties).to.deep.equal(expected); @@ -771,6 +784,7 @@ describe('connection tracking', function () { has_kms_gcp: false, has_kms_kmip: false, has_kms_azure: false, + connection_id: 'TEST', }; expect(properties).to.deep.equal(expected); From 3220f3654fb2ccc949441c54d543890b8e029703 Mon Sep 17 00:00:00 2001 From: Paula Stachova Date: Fri, 28 Jun 2024 16:59:43 +0200 Subject: [PATCH 17/24] skip connection_id in deep equality checks e2e --- .../compass-crud/src/stores/crud-store.ts | 2 ++ .../tests/collection-bulk-delete.test.ts | 14 ++++++++++ .../tests/collection-bulk-update.test.ts | 14 ++++++++++ .../tests/collection-documents-tab.test.ts | 12 +++++++++ .../tests/collection-export.test.ts | 26 +++++++++++++++++++ .../tests/collection-import.test.ts | 2 ++ .../compass-telemetry/src/generic-track.ts | 5 ---- 7 files changed, 70 insertions(+), 5 deletions(-) diff --git a/packages/compass-crud/src/stores/crud-store.ts b/packages/compass-crud/src/stores/crud-store.ts index 9ad22db639e..ef43e68a82b 100644 --- a/packages/compass-crud/src/stores/crud-store.ts +++ b/packages/compass-crud/src/stores/crud-store.ts @@ -1747,6 +1747,7 @@ class CrudStoreImpl openBulkDeleteDialog() { this.track( 'Bulk Delete Opened', + {}, this.connectionInfoAccess.getCurrentConnectionInfo() ); @@ -1815,6 +1816,7 @@ class CrudStoreImpl async runBulkDelete() { this.track( 'Bulk Delete Executed', + {}, this.connectionInfoAccess.getCurrentConnectionInfo() ); diff --git a/packages/compass-e2e-tests/tests/collection-bulk-delete.test.ts b/packages/compass-e2e-tests/tests/collection-bulk-delete.test.ts index 9dce411f661..090c8b7b796 100644 --- a/packages/compass-e2e-tests/tests/collection-bulk-delete.test.ts +++ b/packages/compass-e2e-tests/tests/collection-bulk-delete.test.ts @@ -45,6 +45,10 @@ describe('Bulk Delete', function () { // Check the telemetry const openedEvent = await telemetryEntry('Bulk Delete Opened'); + + expect(openedEvent.connection_id).to.exist; + delete openedEvent.connection_id; // connection_id varies + expect(openedEvent).to.deep.equal({}); // Make sure the query is shown in the modal. @@ -75,6 +79,12 @@ describe('Bulk Delete', function () { // Check the telemetry const executedEvent = await telemetryEntry('Bulk Delete Executed'); + + // this id is always different, because the connection is not a saved one + // so we just check it exists for simplicity + expect(executedEvent.connection_id).to.exist; + delete executedEvent.connection_id; + expect(executedEvent).to.deep.equal({}); // The success toast is displayed @@ -153,6 +163,10 @@ describe('Bulk Delete', function () { // Check the telemetry const openedEvent = await telemetryEntry('Delete Export Opened'); + + expect(openedEvent.connection_id).to.exist; + delete openedEvent.connection_id; // connection_id varies + expect(openedEvent).to.deep.equal({}); const text = await browser.exportToLanguage('Python', { diff --git a/packages/compass-e2e-tests/tests/collection-bulk-update.test.ts b/packages/compass-e2e-tests/tests/collection-bulk-update.test.ts index e10211383cd..5b5a9b60c06 100644 --- a/packages/compass-e2e-tests/tests/collection-bulk-update.test.ts +++ b/packages/compass-e2e-tests/tests/collection-bulk-update.test.ts @@ -50,6 +50,10 @@ describe('Bulk Update', () => { // Check the telemetry const openedEvent = await telemetryEntry('Bulk Update Opened'); + + expect(openedEvent.connection_id).to.exist; + delete openedEvent.connection_id; // connection_id varies + expect(openedEvent).to.deep.equal({ isUpdatePreviewSupported: true, }); @@ -112,6 +116,10 @@ describe('Bulk Update', () => { // Check the telemetry const executedEvent = await telemetryEntry('Bulk Update Executed'); + + expect(openedEvent.connection_id).to.exist; + delete openedEvent.connection_id; // connection_id varies + expect(executedEvent).to.deep.equal({ isUpdatePreviewSupported: true, }); @@ -156,6 +164,12 @@ describe('Bulk Update', () => { // Check the telemetry const favoritedEvent = await telemetryEntry('Bulk Update Favorited'); + + // this id is always different, because the connection is not a saved one + // so we just check it exists for simplicity + expect(favoritedEvent.connection_id).to.exist; + delete favoritedEvent.connection_id; + expect(favoritedEvent).to.deep.equal({ isUpdatePreviewSupported: true, }); diff --git a/packages/compass-e2e-tests/tests/collection-documents-tab.test.ts b/packages/compass-e2e-tests/tests/collection-documents-tab.test.ts index e16385a5eb7..313c56edc81 100644 --- a/packages/compass-e2e-tests/tests/collection-documents-tab.test.ts +++ b/packages/compass-e2e-tests/tests/collection-documents-tab.test.ts @@ -155,6 +155,12 @@ describe('Collection documents tab', function () { // Check the telemetry const queryExecutedEvent = await telemetryEntry('Query Executed'); + + // this id is always different, because the connection is not a saved one + // so we just check it exists for simplicity + expect(queryExecutedEvent.connection_id).to.exist; + delete queryExecutedEvent.connection_id; + expect(queryExecutedEvent).to.deep.equal({ changed_maxtimems: false, collection_type: 'collection', @@ -190,6 +196,12 @@ describe('Collection documents tab', function () { // Check the telemetry const queryExecutedEvent = await telemetryEntry('Query Executed'); + + // this id is always different, because the connection is not a saved one + // so we just check it exists for simplicity + expect(queryExecutedEvent.connection_id).to.exist; + delete queryExecutedEvent.connection_id; + expect(queryExecutedEvent).to.deep.equal({ changed_maxtimems: false, collection_type: 'collection', diff --git a/packages/compass-e2e-tests/tests/collection-export.test.ts b/packages/compass-e2e-tests/tests/collection-export.test.ts index 2587bea41c1..4c2556f4b1c 100644 --- a/packages/compass-e2e-tests/tests/collection-export.test.ts +++ b/packages/compass-e2e-tests/tests/collection-export.test.ts @@ -136,6 +136,8 @@ describe('Collection export', function () { const exportCompletedEvent = await telemetryEntry('Export Completed'); delete exportCompletedEvent.duration; // Duration varies. + expect(exportCompletedEvent.connection_id).to.exist; + delete exportCompletedEvent.connection_id; // connection_id varies expect(exportCompletedEvent).to.deep.equal({ all_docs: false, has_projection: false, @@ -205,6 +207,8 @@ describe('Collection export', function () { const exportCompletedEvent = await telemetryEntry('Export Completed'); delete exportCompletedEvent.duration; // Duration varies. + expect(exportCompletedEvent.connection_id).to.exist; + delete exportCompletedEvent.connection_id; // connection_id varies expect(exportCompletedEvent).to.deep.equal({ all_docs: false, has_projection: false, @@ -272,6 +276,8 @@ describe('Collection export', function () { const exportCompletedEvent = await telemetryEntry('Export Completed'); delete exportCompletedEvent.duration; // Duration varies. + expect(exportCompletedEvent.connection_id).to.exist; + delete exportCompletedEvent.connection_id; // connection_id varies expect(exportCompletedEvent).to.deep.equal({ all_docs: false, has_projection: true, @@ -324,6 +330,8 @@ describe('Collection export', function () { const exportCompletedEvent = await telemetryEntry('Export Completed'); delete exportCompletedEvent.duration; // Duration varies. + expect(exportCompletedEvent.connection_id).to.exist; + delete exportCompletedEvent.connection_id; // connection_id varies expect(exportCompletedEvent).to.deep.equal({ all_docs: true, file_type: 'csv', @@ -396,6 +404,8 @@ describe('Collection export', function () { const exportCompletedEvent = await telemetryEntry('Export Completed'); delete exportCompletedEvent.duration; // Duration varies. + expect(exportCompletedEvent.connection_id).to.exist; + delete exportCompletedEvent.connection_id; // connection_id varies expect(exportCompletedEvent).to.deep.equal({ all_docs: false, file_type: 'json', @@ -463,6 +473,8 @@ describe('Collection export', function () { const exportCompletedEvent = await telemetryEntry('Export Completed'); delete exportCompletedEvent.duration; // Duration varies. + expect(exportCompletedEvent.connection_id).to.exist; + delete exportCompletedEvent.connection_id; // connection_id varies expect(exportCompletedEvent).to.deep.equal({ all_docs: false, file_type: 'json', @@ -515,6 +527,8 @@ describe('Collection export', function () { const exportCompletedEvent = await telemetryEntry('Export Completed'); delete exportCompletedEvent.duration; // Duration varies. + expect(exportCompletedEvent.connection_id).to.exist; + delete exportCompletedEvent.connection_id; // connection_id varies expect(exportCompletedEvent).to.deep.equal({ all_docs: true, file_type: 'json', @@ -569,6 +583,8 @@ describe('Collection export', function () { const exportCompletedEvent = await telemetryEntry('Export Completed'); delete exportCompletedEvent.duration; // Duration varies. + expect(exportCompletedEvent.connection_id).to.exist; + delete exportCompletedEvent.connection_id; // connection_id varies expect(exportCompletedEvent).to.deep.equal({ all_docs: true, file_type: 'json', @@ -658,6 +674,8 @@ describe('Collection export', function () { const exportCompletedEvent = await telemetryEntry('Export Completed'); delete exportCompletedEvent.duration; // Duration varies. + expect(exportCompletedEvent.connection_id).to.exist; + delete exportCompletedEvent.connection_id; // connection_id varies expect(exportCompletedEvent).to.deep.equal({ all_docs: false, file_type: 'csv', @@ -743,6 +761,8 @@ describe('Collection export', function () { const exportCompletedEvent = await telemetryEntry('Export Completed'); delete exportCompletedEvent.duration; // Duration varies. + expect(exportCompletedEvent.connection_id).to.exist; + delete exportCompletedEvent.connection_id; // connection_id varies expect(exportCompletedEvent).to.deep.equal({ all_docs: false, file_type: 'json', @@ -846,6 +866,8 @@ describe('Collection export', function () { const exportCompletedEvent = await telemetryEntry('Export Completed'); delete exportCompletedEvent.duration; // Duration varies. + expect(exportCompletedEvent.connection_id).to.exist; + delete exportCompletedEvent.connection_id; // connection_id varies expect(exportCompletedEvent).to.deep.equal({ all_docs: false, file_type: 'csv', @@ -957,6 +979,8 @@ describe('Collection export', function () { const exportCompletedEvent = await telemetryEntry('Export Completed'); delete exportCompletedEvent.duration; // Duration varies. + expect(exportCompletedEvent.connection_id).to.exist; + delete exportCompletedEvent.connection_id; // connection_id varies expect(exportCompletedEvent).to.deep.equal({ all_docs: false, file_type: 'csv', @@ -1058,6 +1082,8 @@ describe('Collection export', function () { const exportCompletedEvent = await telemetryEntry('Export Completed'); delete exportCompletedEvent.duration; // Duration varies. + expect(exportCompletedEvent.connection_id).to.exist; + delete exportCompletedEvent.connection_id; // connection_id varies expect(exportCompletedEvent).to.deep.equal({ all_docs: false, file_type: 'json', diff --git a/packages/compass-e2e-tests/tests/collection-import.test.ts b/packages/compass-e2e-tests/tests/collection-import.test.ts index 8c2908b8542..f70a3d34e2a 100644 --- a/packages/compass-e2e-tests/tests/collection-import.test.ts +++ b/packages/compass-e2e-tests/tests/collection-import.test.ts @@ -605,6 +605,8 @@ describe('Collection import', function () { const importCompletedEvent = await telemetryEntry('Import Completed'); delete importCompletedEvent.duration; // Duration varies. + expect(importCompletedEvent.connection_id).to.exist; + delete importCompletedEvent.connection_id; // connection_id varies expect(importCompletedEvent).to.deep.equal({ delimiter: ',', newline: '\n', diff --git a/packages/compass-telemetry/src/generic-track.ts b/packages/compass-telemetry/src/generic-track.ts index dd9a6805a88..28e003d5ea9 100644 --- a/packages/compass-telemetry/src/generic-track.ts +++ b/packages/compass-telemetry/src/generic-track.ts @@ -62,11 +62,6 @@ export const createTrack = ({ parameters.connection_id = connectionInfo.id; } - // console.log('TRACK', { - // event, - // connection_id: (parameters as { connection_id?: string }).connection_id, - // }); - sendTrack(event, parameters || {}); }; From c22ce90a83b39d33056f7f620f3e0a246b85033d Mon Sep 17 00:00:00 2001 From: Paula Stachova Date: Tue, 2 Jul 2024 13:41:16 +0200 Subject: [PATCH 18/24] update locators --- packages/compass-aggregations/src/index.ts | 6 +++--- .../src/components/connections-provider.tsx | 2 +- packages/compass-crud/src/index.ts | 4 ++-- packages/compass-explain-plan/src/index.ts | 4 ++-- packages/compass-import-export/src/index.ts | 6 +++--- packages/compass-indexes/src/index.ts | 8 ++++---- packages/compass-query-bar/src/index.tsx | 4 ++-- .../compass-saved-aggregations-queries/src/index.ts | 4 ++-- packages/compass-schema-validation/src/index.ts | 4 ++-- packages/compass-schema/src/index.ts | 4 ++-- packages/compass-shell/src/index.ts | 4 ++-- packages/compass-telemetry/src/provider.tsx | 10 ++++------ packages/compass-welcome/src/index.ts | 4 ++-- packages/databases-collections/src/index.ts | 6 +++--- 14 files changed, 34 insertions(+), 36 deletions(-) diff --git a/packages/compass-aggregations/src/index.ts b/packages/compass-aggregations/src/index.ts index 8644a7dfcfd..b2cd096f275 100644 --- a/packages/compass-aggregations/src/index.ts +++ b/packages/compass-aggregations/src/index.ts @@ -13,7 +13,7 @@ import { type DataServiceLocator, } from '@mongodb-js/compass-connections/provider'; import { createLoggerLocator } from '@mongodb-js/compass-logging/provider'; -import { createTelemetryLocator } from '@mongodb-js/compass-telemetry/provider'; +import { telemetryLocator } from '@mongodb-js/compass-telemetry/provider'; import type { OptionalDataServiceProps, RequiredDataServiceProps, @@ -44,7 +44,7 @@ export const CompassAggregationsHadronPlugin = registerHadronPlugin( instance: mongoDBInstanceLocator, preferences: preferencesLocator, logger: createLoggerLocator('COMPASS-AGGREGATIONS-UI'), - track: createTelemetryLocator(), + track: telemetryLocator, atlasAuthService: atlasAuthServiceLocator, atlasAiService: atlasAiServiceLocator, pipelineStorage: pipelineStorageLocator, @@ -70,7 +70,7 @@ export const CreateViewPlugin = registerHadronPlugin( connectionsManager: connectionsManagerLocator, connectionRepository: connectionRepositoryLocator, logger: createLoggerLocator('COMPASS-CREATE-VIEW-UI'), - track: createTelemetryLocator(), + track: telemetryLocator, workspaces: workspacesServiceLocator, } ); diff --git a/packages/compass-connections/src/components/connections-provider.tsx b/packages/compass-connections/src/components/connections-provider.tsx index 75fd659be6a..212eaf0d819 100644 --- a/packages/compass-connections/src/components/connections-provider.tsx +++ b/packages/compass-connections/src/components/connections-provider.tsx @@ -104,7 +104,7 @@ export { withConnectionRepository }; export const connectionRepositoryLocator = createServiceLocator( useConnectionRepository.bind(null), - 'createConnectionRepositoryLocator' + 'connectionRepositoryLocator' ); export type ConnectionRepository = ReturnType; diff --git a/packages/compass-crud/src/index.ts b/packages/compass-crud/src/index.ts index a69493b2fc4..e20f4778359 100644 --- a/packages/compass-crud/src/index.ts +++ b/packages/compass-crud/src/index.ts @@ -27,7 +27,7 @@ import { } from '@mongodb-js/my-queries-storage/provider'; import { fieldStoreServiceLocator } from '@mongodb-js/compass-field-store'; import { queryBarServiceLocator } from '@mongodb-js/compass-query-bar'; -import { createTelemetryLocator } from '@mongodb-js/compass-telemetry/provider'; +import { telemetryLocator } from '@mongodb-js/compass-telemetry/provider'; export const CompassDocumentsHadronPlugin = registerHadronPlugin( { @@ -43,7 +43,7 @@ export const CompassDocumentsHadronPlugin = registerHadronPlugin( instance: mongoDBInstanceLocator, preferences: preferencesLocator, logger: createLoggerLocator('COMPASS-CRUD-UI'), - track: createTelemetryLocator(), + track: telemetryLocator, favoriteQueryStorageAccess: favoriteQueryStorageAccessLocator, recentQueryStorageAccess: recentQueryStorageAccessLocator, fieldStoreService: fieldStoreServiceLocator, diff --git a/packages/compass-explain-plan/src/index.ts b/packages/compass-explain-plan/src/index.ts index 2879f3cbf07..bc74861baaa 100644 --- a/packages/compass-explain-plan/src/index.ts +++ b/packages/compass-explain-plan/src/index.ts @@ -7,7 +7,7 @@ import { type DataServiceLocator, } from '@mongodb-js/compass-connections/provider'; import { createLoggerLocator } from '@mongodb-js/compass-logging/provider'; -import { createTelemetryLocator } from '@mongodb-js/compass-telemetry/provider'; +import { telemetryLocator } from '@mongodb-js/compass-telemetry/provider'; import { preferencesLocator } from 'compass-preferences-model/provider'; const ExplainPlanModalPlugin = registerHadronPlugin( @@ -18,7 +18,7 @@ const ExplainPlanModalPlugin = registerHadronPlugin( }, { logger: createLoggerLocator('EXPLAIN-PLAN-MODAL-UI'), - track: createTelemetryLocator(), + track: telemetryLocator, connectionInfoAccess: connectionInfoAccessLocator, dataService: dataServiceLocator as DataServiceLocator< 'explainAggregate' | 'explainFind' | 'isCancelError' diff --git a/packages/compass-import-export/src/index.ts b/packages/compass-import-export/src/index.ts index 6370b4bb90a..8342aa7fdec 100644 --- a/packages/compass-import-export/src/index.ts +++ b/packages/compass-import-export/src/index.ts @@ -7,7 +7,7 @@ import { activatePlugin as activateExportPlugin } from './stores/export-store'; import { workspacesServiceLocator } from '@mongodb-js/compass-workspaces/provider'; import { preferencesLocator } from 'compass-preferences-model/provider'; import { createLoggerLocator } from '@mongodb-js/compass-logging/provider'; -import { createTelemetryLocator } from '@mongodb-js/compass-telemetry/provider'; +import { telemetryLocator } from '@mongodb-js/compass-telemetry/provider'; import { connectionRepositoryLocator } from '@mongodb-js/compass-connections/provider'; /** @@ -25,7 +25,7 @@ export const ImportPlugin = registerHadronPlugin( workspaces: workspacesServiceLocator, preferences: preferencesLocator, logger: createLoggerLocator('COMPASS-IMPORT-UI'), - track: createTelemetryLocator(), + track: telemetryLocator, } ); @@ -43,6 +43,6 @@ export const ExportPlugin = registerHadronPlugin( connectionRepository: connectionRepositoryLocator, preferences: preferencesLocator, logger: createLoggerLocator('COMPASS-EXPORT-UI'), - track: createTelemetryLocator(), + track: telemetryLocator, } ); diff --git a/packages/compass-indexes/src/index.ts b/packages/compass-indexes/src/index.ts index dc1ea1b63a3..7e83527fdf4 100644 --- a/packages/compass-indexes/src/index.ts +++ b/packages/compass-indexes/src/index.ts @@ -23,7 +23,7 @@ import { mongoDBInstanceLocator } from '@mongodb-js/compass-app-stores/provider' import type { Logger } from '@mongodb-js/compass-logging'; import { createLoggerLocator } from '@mongodb-js/compass-logging/provider'; import { - createTelemetryLocator, + telemetryLocator, type TrackFunction, } from '@mongodb-js/compass-telemetry/provider'; @@ -48,7 +48,7 @@ export const CompassIndexesHadronPlugin = registerHadronPlugin< connectionInfoAccess: connectionInfoAccessLocator, instance: mongoDBInstanceLocator, logger: createLoggerLocator('COMPASS-INDEXES-UI'), - track: createTelemetryLocator(), + track: telemetryLocator, } ); @@ -66,7 +66,7 @@ export const CreateIndexPlugin = registerHadronPlugin( { dataService: dataServiceLocator as DataServiceLocator<'createIndex'>, logger: createLoggerLocator('COMPASS-INDEXES-UI'), - track: createTelemetryLocator(), + track: telemetryLocator, connectionInfoAccess: connectionInfoAccessLocator, } ); @@ -80,7 +80,7 @@ export const DropIndexPlugin = registerHadronPlugin( { dataService: dataServiceLocator as DataServiceLocator<'dropIndex'>, logger: createLoggerLocator('COMPASS-INDEXES-UI'), - track: createTelemetryLocator(), + track: telemetryLocator, connectionInfoAccess: connectionInfoAccessLocator, } ); diff --git a/packages/compass-query-bar/src/index.tsx b/packages/compass-query-bar/src/index.tsx index 5caa176d90a..bf912de8321 100644 --- a/packages/compass-query-bar/src/index.tsx +++ b/packages/compass-query-bar/src/index.tsx @@ -26,7 +26,7 @@ import { favoriteQueryStorageAccessLocator, recentQueryStorageAccessLocator, } from '@mongodb-js/my-queries-storage/provider'; -import { createTelemetryLocator } from '@mongodb-js/compass-telemetry/provider'; +import { telemetryLocator } from '@mongodb-js/compass-telemetry/provider'; const QueryBarPlugin = registerHadronPlugin( { @@ -52,7 +52,7 @@ const QueryBarPlugin = registerHadronPlugin( instance: mongoDBInstanceLocator, preferences: preferencesLocator, logger: createLoggerLocator('COMPASS-QUERY-BAR-UI'), - track: createTelemetryLocator(), + track: telemetryLocator, connectionInfoAccess: connectionInfoAccessLocator, atlasAiService: atlasAiServiceLocator, atlasAuthService: atlasAuthServiceLocator, diff --git a/packages/compass-saved-aggregations-queries/src/index.ts b/packages/compass-saved-aggregations-queries/src/index.ts index bdcf6573577..c977c816dbd 100644 --- a/packages/compass-saved-aggregations-queries/src/index.ts +++ b/packages/compass-saved-aggregations-queries/src/index.ts @@ -2,7 +2,7 @@ import { registerHadronPlugin } from 'hadron-app-registry'; import { connectionsManagerLocator } from '@mongodb-js/compass-connections/provider'; import { mongoDBInstancesManagerLocator } from '@mongodb-js/compass-app-stores/provider'; import { createLoggerLocator } from '@mongodb-js/compass-logging/provider'; -import { createTelemetryLocator } from '@mongodb-js/compass-telemetry/provider'; +import { telemetryLocator } from '@mongodb-js/compass-telemetry/provider'; import { activatePlugin } from './stores'; import AggregationsQueriesList from './components/aggregations-queries-list'; import type { WorkspaceComponent } from '@mongodb-js/compass-workspaces'; @@ -18,7 +18,7 @@ const serviceLocators = { instancesManager: mongoDBInstancesManagerLocator, preferencesAccess: preferencesLocator, logger: createLoggerLocator('COMPASS-MY-QUERIES-UI'), - track: createTelemetryLocator(), + track: telemetryLocator, workspaces: workspacesServiceLocator, pipelineStorage: pipelineStorageLocator, favoriteQueryStorageAccess: favoriteQueryStorageAccessLocator, diff --git a/packages/compass-schema-validation/src/index.ts b/packages/compass-schema-validation/src/index.ts index 699568f1737..ec4da917a16 100644 --- a/packages/compass-schema-validation/src/index.ts +++ b/packages/compass-schema-validation/src/index.ts @@ -9,7 +9,7 @@ import { import { mongoDBInstanceLocator } from '@mongodb-js/compass-app-stores/provider'; import { preferencesLocator } from 'compass-preferences-model/provider'; import { createLoggerLocator } from '@mongodb-js/compass-logging/provider'; -import { createTelemetryLocator } from '@mongodb-js/compass-telemetry/provider'; +import { telemetryLocator } from '@mongodb-js/compass-telemetry/provider'; export const CompassSchemaValidationHadronPlugin = registerHadronPlugin( { @@ -25,7 +25,7 @@ export const CompassSchemaValidationHadronPlugin = registerHadronPlugin( instance: mongoDBInstanceLocator, preferences: preferencesLocator, logger: createLoggerLocator('COMPASS-SCHEMA-VALIDATION-UI'), - track: createTelemetryLocator(), + track: telemetryLocator, } ); export const CompassSchemaValidationPlugin = { diff --git a/packages/compass-schema/src/index.ts b/packages/compass-schema/src/index.ts index 61f58c67228..201098d8abd 100644 --- a/packages/compass-schema/src/index.ts +++ b/packages/compass-schema/src/index.ts @@ -8,7 +8,7 @@ import CompassSchema from './components/compass-schema'; import { registerHadronPlugin } from 'hadron-app-registry'; import { activateSchemaPlugin } from './stores/store'; import { createLoggerLocator } from '@mongodb-js/compass-logging/provider'; -import { createTelemetryLocator } from '@mongodb-js/compass-telemetry/provider'; +import { telemetryLocator } from '@mongodb-js/compass-telemetry/provider'; import { preferencesLocator } from 'compass-preferences-model/provider'; import { fieldStoreServiceLocator } from '@mongodb-js/compass-field-store'; import { queryBarServiceLocator } from '@mongodb-js/compass-query-bar'; @@ -24,7 +24,7 @@ export const CompassSchemaHadronPlugin = registerHadronPlugin( 'sample' | 'isCancelError' >, logger: createLoggerLocator('COMPASS-SCHEMA-UI'), - track: createTelemetryLocator(), + track: telemetryLocator, preferences: preferencesLocator, fieldStoreService: fieldStoreServiceLocator, queryBar: queryBarServiceLocator, diff --git a/packages/compass-shell/src/index.ts b/packages/compass-shell/src/index.ts index b185bf9835f..9bbdcbc388a 100644 --- a/packages/compass-shell/src/index.ts +++ b/packages/compass-shell/src/index.ts @@ -1,6 +1,6 @@ import type { Logger } from '@mongodb-js/compass-logging/provider'; import { createLoggerLocator } from '@mongodb-js/compass-logging/provider'; -import { createTelemetryLocator } from '@mongodb-js/compass-telemetry/provider'; +import { telemetryLocator } from '@mongodb-js/compass-telemetry/provider'; import { ShellPlugin, onActivated } from './plugin'; import { registerHadronPlugin } from 'hadron-app-registry'; import { @@ -33,7 +33,7 @@ export const CompassShellPlugin = registerHadronPlugin< }, { logger: createLoggerLocator('COMPASS-SHELL'), - track: createTelemetryLocator(), + track: telemetryLocator, dataService: dataServiceLocator, connectionInfoAccess: connectionInfoAccessLocator, preferences: preferencesLocator, diff --git a/packages/compass-telemetry/src/provider.tsx b/packages/compass-telemetry/src/provider.tsx index 5a119e6c0f0..56905338cb8 100644 --- a/packages/compass-telemetry/src/provider.tsx +++ b/packages/compass-telemetry/src/provider.tsx @@ -33,12 +33,10 @@ export const TelemetryProvider: React.FC<{ ); }; -export function createTelemetryLocator() { - return createServiceLocator( - useTelemetry.bind(null), - 'createTelemetryLocator' - ); -} +export const telemetryLocator = createServiceLocator( + useTelemetry.bind(null), + 'telemetryLocator' +); export function useTelemetry(): TrackFunction { const track = React.useContext(TelemetryContext); diff --git a/packages/compass-welcome/src/index.ts b/packages/compass-welcome/src/index.ts index 177ad6df9f0..0bbc98e3e57 100644 --- a/packages/compass-welcome/src/index.ts +++ b/packages/compass-welcome/src/index.ts @@ -4,11 +4,11 @@ import { workspacesServiceLocator } from '@mongodb-js/compass-workspaces/provide import type { WorkspaceComponent } from '@mongodb-js/compass-workspaces'; import { WelcomeModal, WelcomeTab } from './components'; import { activatePlugin } from './stores'; -import { createTelemetryLocator } from '@mongodb-js/compass-telemetry/provider'; +import { telemetryLocator } from '@mongodb-js/compass-telemetry/provider'; const serviceLocators = { logger: createLoggerLocator('COMPASS-MY-QUERIES-UI'), - track: createTelemetryLocator(), + track: telemetryLocator, workspaces: workspacesServiceLocator, }; diff --git a/packages/databases-collections/src/index.ts b/packages/databases-collections/src/index.ts index 76921c0149c..f6f10ec82a0 100644 --- a/packages/databases-collections/src/index.ts +++ b/packages/databases-collections/src/index.ts @@ -1,6 +1,6 @@ import { registerHadronPlugin } from 'hadron-app-registry'; import { createLoggerLocator } from '@mongodb-js/compass-logging/provider'; -import { createTelemetryLocator } from '@mongodb-js/compass-telemetry/provider'; +import { telemetryLocator } from '@mongodb-js/compass-telemetry/provider'; import { connectionsManagerLocator } from '@mongodb-js/compass-connections/provider'; import { mongoDBInstancesManagerLocator } from '@mongodb-js/compass-app-stores/provider'; import { CollectionsPlugin } from './collections-plugin'; @@ -39,7 +39,7 @@ export const CreateNamespacePlugin = registerHadronPlugin( }, { logger: createLoggerLocator('COMPASS-CREATE-NAMESPACE-UI'), - track: createTelemetryLocator(), + track: telemetryLocator, connectionsManager: connectionsManagerLocator, connectionRepository: connectionRepositoryLocator, instancesManager: mongoDBInstancesManagerLocator, @@ -55,7 +55,7 @@ export const DropNamespacePlugin = registerHadronPlugin( }, { logger: createLoggerLocator('COMPASS-DROP-NAMESPACE-UI'), - track: createTelemetryLocator(), + track: telemetryLocator, connectionRepository: connectionRepositoryLocator, connectionsManager: connectionsManagerLocator, } From c000d553715e6d8b6b2f1f8672f3422fed84a02b Mon Sep 17 00:00:00 2001 From: Paula Stachova Date: Wed, 3 Jul 2024 11:29:21 +0200 Subject: [PATCH 19/24] ref --- packages/compass-aggregations/src/index.ts | 4 ++-- .../src/stores/create-view.ts | 4 ++-- .../src/components/connections-provider.tsx | 23 +++++++++++++++---- packages/compass-connections/src/provider.ts | 3 ++- packages/compass-import-export/src/index.ts | 6 ++--- .../src/modules/import.ts | 14 ++++++----- .../src/stores/export-store.ts | 4 ++-- .../src/stores/import-store.ts | 4 ++-- packages/databases-collections/src/index.ts | 6 ++--- .../src/modules/create-namespace.spec.ts | 14 +++++++++-- .../src/stores/create-namespace.ts | 4 ++-- 11 files changed, 57 insertions(+), 29 deletions(-) diff --git a/packages/compass-aggregations/src/index.ts b/packages/compass-aggregations/src/index.ts index b2cd096f275..5a1820dcc51 100644 --- a/packages/compass-aggregations/src/index.ts +++ b/packages/compass-aggregations/src/index.ts @@ -27,7 +27,7 @@ import { preferencesLocator } from 'compass-preferences-model/provider'; import { atlasAuthServiceLocator } from '@mongodb-js/atlas-service/provider'; import { atlasAiServiceLocator } from '@mongodb-js/compass-generative-ai/provider'; import { pipelineStorageLocator } from '@mongodb-js/my-queries-storage/provider'; -import { connectionRepositoryLocator } from '@mongodb-js/compass-connections/provider'; +import { connectionRepositoryAccessLocator } from '@mongodb-js/compass-connections/provider'; export const CompassAggregationsHadronPlugin = registerHadronPlugin( { @@ -68,7 +68,7 @@ export const CreateViewPlugin = registerHadronPlugin( }, { connectionsManager: connectionsManagerLocator, - connectionRepository: connectionRepositoryLocator, + connectionRepository: connectionRepositoryAccessLocator, logger: createLoggerLocator('COMPASS-CREATE-VIEW-UI'), track: telemetryLocator, workspaces: workspacesServiceLocator, diff --git a/packages/compass-aggregations/src/stores/create-view.ts b/packages/compass-aggregations/src/stores/create-view.ts index 1e2be55519d..aff00f1979d 100644 --- a/packages/compass-aggregations/src/stores/create-view.ts +++ b/packages/compass-aggregations/src/stores/create-view.ts @@ -8,7 +8,7 @@ import type AppRegistry from 'hadron-app-registry'; import type { Logger } from '@mongodb-js/compass-logging/provider'; import type { WorkspacesService } from '@mongodb-js/compass-workspaces/provider'; import type { - ConnectionRepository, + ConnectionRepositoryAccess, ConnectionsManager, } from '@mongodb-js/compass-connections/provider'; import type { ActivateHelpers } from 'hadron-app-registry'; @@ -17,7 +17,7 @@ import type { TrackFunction } from '@mongodb-js/compass-telemetry'; type CreateViewServices = { globalAppRegistry: AppRegistry; connectionsManager: ConnectionsManager; - connectionRepository: ConnectionRepository; + connectionRepository: ConnectionRepositoryAccess; logger: Logger; track: TrackFunction; workspaces: WorkspacesService; diff --git a/packages/compass-connections/src/components/connections-provider.tsx b/packages/compass-connections/src/components/connections-provider.tsx index 212eaf0d819..f656593cb04 100644 --- a/packages/compass-connections/src/components/connections-provider.tsx +++ b/packages/compass-connections/src/components/connections-provider.tsx @@ -1,5 +1,5 @@ import React, { useContext, useEffect, useRef } from 'react'; -import { useConnectionsManagerContext } from '../provider'; +import { type ConnectionInfo, useConnectionsManagerContext } from '../provider'; import { useConnections as useConnectionsStore } from '../stores/connections-store'; import { useConnectionRepository as useConnectionsRepositoryState } from '../hooks/use-connection-repository'; import { createServiceLocator } from 'hadron-app-registry'; @@ -102,9 +102,24 @@ function withConnectionRepository< export { withConnectionRepository }; -export const connectionRepositoryLocator = createServiceLocator( - useConnectionRepository.bind(null), - 'connectionRepositoryLocator' +export type ConnectionRepositoryAccess = Pick< + ConnectionRepository, + 'getConnectionInfoById' +>; + +export const useConnectionRepositoryAccess = (): ConnectionRepositoryAccess => { + const repository = useConnectionRepository(); + const repositoryRef = useRef(repository); + repositoryRef.current = repository; + return { + getConnectionInfoById(id: ConnectionInfo['id']) { + return repositoryRef.current.getConnectionInfoById(id); + }, + }; +}; +export const connectionRepositoryAccessLocator = createServiceLocator( + useConnectionRepositoryAccess, + 'connectionRepositoryAccessLocator' ); export type ConnectionRepository = ReturnType; diff --git a/packages/compass-connections/src/provider.ts b/packages/compass-connections/src/provider.ts index 259809d3eb9..1dcbf347b62 100644 --- a/packages/compass-connections/src/provider.ts +++ b/packages/compass-connections/src/provider.ts @@ -91,7 +91,8 @@ export { useConnectionRepository, withConnectionRepository, areConnectionsEqual, - connectionRepositoryLocator, + connectionRepositoryAccessLocator, + type ConnectionRepositoryAccess, } from './components/connections-provider'; export * from './connection-info-provider'; diff --git a/packages/compass-import-export/src/index.ts b/packages/compass-import-export/src/index.ts index 8342aa7fdec..411aa09e62a 100644 --- a/packages/compass-import-export/src/index.ts +++ b/packages/compass-import-export/src/index.ts @@ -8,7 +8,7 @@ import { workspacesServiceLocator } from '@mongodb-js/compass-workspaces/provide import { preferencesLocator } from 'compass-preferences-model/provider'; import { createLoggerLocator } from '@mongodb-js/compass-logging/provider'; import { telemetryLocator } from '@mongodb-js/compass-telemetry/provider'; -import { connectionRepositoryLocator } from '@mongodb-js/compass-connections/provider'; +import { connectionRepositoryAccessLocator } from '@mongodb-js/compass-connections/provider'; /** * The import plugin. @@ -21,7 +21,7 @@ export const ImportPlugin = registerHadronPlugin( }, { connectionsManager: connectionsManagerLocator, - connectionRepository: connectionRepositoryLocator, + connectionRepository: connectionRepositoryAccessLocator, workspaces: workspacesServiceLocator, preferences: preferencesLocator, logger: createLoggerLocator('COMPASS-IMPORT-UI'), @@ -40,7 +40,7 @@ export const ExportPlugin = registerHadronPlugin( }, { connectionsManager: connectionsManagerLocator, - connectionRepository: connectionRepositoryLocator, + connectionRepository: connectionRepositoryAccessLocator, preferences: preferencesLocator, logger: createLoggerLocator('COMPASS-EXPORT-UI'), track: telemetryLocator, diff --git a/packages/compass-import-export/src/modules/import.ts b/packages/compass-import-export/src/modules/import.ts index 66ea5018b59..9dd131930cf 100644 --- a/packages/compass-import-export/src/modules/import.ts +++ b/packages/compass-import-export/src/modules/import.ts @@ -217,9 +217,6 @@ export const startImport = (): ImportThunkAction> => { }, } = getState(); - const connectionInfo = - connectionRepository.getConnectionInfoById(connectionId); - const ignoreBlanks = ignoreBlanks_ && fileType === FILE_TYPES.CSV; const fileSize = fileStats?.size || 0; const fields: Record = {}; @@ -369,7 +366,7 @@ export const startImport = (): ImportThunkAction> => { aborted: abortSignal.aborted, ignore_empty_strings: fileType === 'csv' ? ignoreBlanks : undefined, }, - connectionInfo + connectionRepository.getConnectionInfoById(connectionId) ); log.error(mongoLogId(1001000081), 'Import', 'Import failed', { @@ -389,6 +386,11 @@ export const startImport = (): ImportThunkAction> => { errorLogWriteStream?.close(); } + console.log( + '*** TRACK ***', + connectionRepository.getConnectionInfoById(connectionId) + ); + track( 'Import Completed', { @@ -403,7 +405,7 @@ export const startImport = (): ImportThunkAction> => { aborted: result.aborted, ignore_empty_strings: fileType === 'csv' ? ignoreBlanks : undefined, }, - connectionInfo + connectionRepository.getConnectionInfoById(connectionId) ); log.info(mongoLogId(1001000082), 'Import', 'Import completed', { @@ -420,7 +422,7 @@ export const startImport = (): ImportThunkAction> => { { errorCount: errors.length, }, - connectionInfo + connectionRepository.getConnectionInfoById(connectionId) ); void openFile(errorLogFilePath); } diff --git a/packages/compass-import-export/src/stores/export-store.ts b/packages/compass-import-export/src/stores/export-store.ts index b7422e15f53..3f1bf4237f8 100644 --- a/packages/compass-import-export/src/stores/export-store.ts +++ b/packages/compass-import-export/src/stores/export-store.ts @@ -8,7 +8,7 @@ import type { PreferencesAccess } from 'compass-preferences-model'; import type { Logger } from '@mongodb-js/compass-logging/provider'; import type { ActivateHelpers } from 'hadron-app-registry'; import type { - ConnectionRepository, + ConnectionRepositoryAccess, ConnectionsManager, } from '@mongodb-js/compass-connections/provider'; import type { TrackFunction } from '@mongodb-js/compass-telemetry'; @@ -29,7 +29,7 @@ export type RootExportState = ReturnType< export type ExportPluginServices = { globalAppRegistry: AppRegistry; connectionsManager: ConnectionsManager; - connectionRepository: ConnectionRepository; + connectionRepository: ConnectionRepositoryAccess; preferences: PreferencesAccess; logger: Logger; track: TrackFunction; diff --git a/packages/compass-import-export/src/stores/import-store.ts b/packages/compass-import-export/src/stores/import-store.ts index 31fef8f3a61..f19338163b5 100644 --- a/packages/compass-import-export/src/stores/import-store.ts +++ b/packages/compass-import-export/src/stores/import-store.ts @@ -7,7 +7,7 @@ import { cancelImport, importReducer, openImport } from '../modules/import'; import type { WorkspacesService } from '@mongodb-js/compass-workspaces/provider'; import type { Logger } from '@mongodb-js/compass-logging/provider'; import type { - ConnectionRepository, + ConnectionRepositoryAccess, ConnectionsManager, } from '@mongodb-js/compass-connections/provider'; import type { ActivateHelpers } from 'hadron-app-registry'; @@ -19,7 +19,7 @@ export type ImportPluginServices = { logger: Logger; track: TrackFunction; connectionsManager: ConnectionsManager; - connectionRepository: ConnectionRepository; + connectionRepository: ConnectionRepositoryAccess; }; export function configureStore(services: ImportPluginServices) { diff --git a/packages/databases-collections/src/index.ts b/packages/databases-collections/src/index.ts index f6f10ec82a0..7d4aaab7ba9 100644 --- a/packages/databases-collections/src/index.ts +++ b/packages/databases-collections/src/index.ts @@ -19,7 +19,7 @@ import { favoriteQueryStorageAccessLocator, pipelineStorageLocator, } from '@mongodb-js/my-queries-storage/provider'; -import { connectionRepositoryLocator } from '@mongodb-js/compass-connections/provider'; +import { connectionRepositoryAccessLocator } from '@mongodb-js/compass-connections/provider'; export const CollectionsWorkspaceTab: WorkspaceComponent<'Collections'> = { name: 'Collections' as const, @@ -41,7 +41,7 @@ export const CreateNamespacePlugin = registerHadronPlugin( logger: createLoggerLocator('COMPASS-CREATE-NAMESPACE-UI'), track: telemetryLocator, connectionsManager: connectionsManagerLocator, - connectionRepository: connectionRepositoryLocator, + connectionRepository: connectionRepositoryAccessLocator, instancesManager: mongoDBInstancesManagerLocator, workspaces: workspacesServiceLocator, } @@ -56,7 +56,7 @@ export const DropNamespacePlugin = registerHadronPlugin( { logger: createLoggerLocator('COMPASS-DROP-NAMESPACE-UI'), track: telemetryLocator, - connectionRepository: connectionRepositoryLocator, + connectionRepository: connectionRepositoryAccessLocator, connectionsManager: connectionsManagerLocator, } ); diff --git a/packages/databases-collections/src/modules/create-namespace.spec.ts b/packages/databases-collections/src/modules/create-namespace.spec.ts index d8e1ebb3bd5..163ef3fe032 100644 --- a/packages/databases-collections/src/modules/create-namespace.spec.ts +++ b/packages/databases-collections/src/modules/create-namespace.spec.ts @@ -32,7 +32,12 @@ describe('create collection module', function () { storeAction = action; }, () => INITIAL_STATE, - { track: createNoopTrack() } as any + { + track: createNoopTrack(), + connectionRepository: { + getConnectionInfoById: () => ({ id: 'TEST' }), + }, + } as any ); const state = reducer(undefined, storeAction); expect(state).to.deep.equal({ @@ -54,7 +59,12 @@ describe('create collection module', function () { storeAction = action; }, () => INITIAL_STATE, - { track: createNoopTrack() } as any + { + track: createNoopTrack(), + connectionRepository: { + getConnectionInfoById: () => ({ id: 'TEST' }), + }, + } as any ); const state = reducer(undefined, storeAction); expect(state).to.deep.equal({ diff --git a/packages/databases-collections/src/stores/create-namespace.ts b/packages/databases-collections/src/stores/create-namespace.ts index fc3fdca228b..1fbbece17b9 100644 --- a/packages/databases-collections/src/stores/create-namespace.ts +++ b/packages/databases-collections/src/stores/create-namespace.ts @@ -3,7 +3,7 @@ import { ConnectionsManagerEvents, type ConnectionsManager, type DataService, - type ConnectionRepository, + type ConnectionRepositoryAccess, } from '@mongodb-js/compass-connections/provider'; import type { MongoDBInstance } from 'mongodb-instance-model'; import type { Logger } from '@mongodb-js/compass-logging'; @@ -30,7 +30,7 @@ type NS = ReturnType; export type CreateNamespaceServices = { connectionsManager: ConnectionsManager; - connectionRepository: ConnectionRepository; + connectionRepository: ConnectionRepositoryAccess; instancesManager: MongoDBInstancesManager; globalAppRegistry: AppRegistry; logger: Logger; From d4f554e9e220132c826f12ed95ed4f481c335d8c Mon Sep 17 00:00:00 2001 From: Paula Stachova Date: Wed, 3 Jul 2024 13:59:12 +0200 Subject: [PATCH 20/24] cleanup --- .../tests/collection-bulk-update.test.ts | 8 +++----- .../tests/collection-documents-tab.test.ts | 8 ++------ packages/compass-import-export/src/modules/import.ts | 5 ----- 3 files changed, 5 insertions(+), 16 deletions(-) diff --git a/packages/compass-e2e-tests/tests/collection-bulk-update.test.ts b/packages/compass-e2e-tests/tests/collection-bulk-update.test.ts index 5b5a9b60c06..d2106638e79 100644 --- a/packages/compass-e2e-tests/tests/collection-bulk-update.test.ts +++ b/packages/compass-e2e-tests/tests/collection-bulk-update.test.ts @@ -117,8 +117,8 @@ describe('Bulk Update', () => { // Check the telemetry const executedEvent = await telemetryEntry('Bulk Update Executed'); - expect(openedEvent.connection_id).to.exist; - delete openedEvent.connection_id; // connection_id varies + expect(executedEvent.connection_id).to.exist; + delete executedEvent.connection_id; // connection_id varies expect(executedEvent).to.deep.equal({ isUpdatePreviewSupported: true, @@ -165,10 +165,8 @@ describe('Bulk Update', () => { // Check the telemetry const favoritedEvent = await telemetryEntry('Bulk Update Favorited'); - // this id is always different, because the connection is not a saved one - // so we just check it exists for simplicity expect(favoritedEvent.connection_id).to.exist; - delete favoritedEvent.connection_id; + delete favoritedEvent.connection_id; // connection_id varies expect(favoritedEvent).to.deep.equal({ isUpdatePreviewSupported: true, diff --git a/packages/compass-e2e-tests/tests/collection-documents-tab.test.ts b/packages/compass-e2e-tests/tests/collection-documents-tab.test.ts index 313c56edc81..d645f4ac801 100644 --- a/packages/compass-e2e-tests/tests/collection-documents-tab.test.ts +++ b/packages/compass-e2e-tests/tests/collection-documents-tab.test.ts @@ -156,10 +156,8 @@ describe('Collection documents tab', function () { // Check the telemetry const queryExecutedEvent = await telemetryEntry('Query Executed'); - // this id is always different, because the connection is not a saved one - // so we just check it exists for simplicity expect(queryExecutedEvent.connection_id).to.exist; - delete queryExecutedEvent.connection_id; + delete queryExecutedEvent.connection_id; // connection_id varies expect(queryExecutedEvent).to.deep.equal({ changed_maxtimems: false, @@ -197,10 +195,8 @@ describe('Collection documents tab', function () { // Check the telemetry const queryExecutedEvent = await telemetryEntry('Query Executed'); - // this id is always different, because the connection is not a saved one - // so we just check it exists for simplicity expect(queryExecutedEvent.connection_id).to.exist; - delete queryExecutedEvent.connection_id; + delete queryExecutedEvent.connection_id; // connection_id varies expect(queryExecutedEvent).to.deep.equal({ changed_maxtimems: false, diff --git a/packages/compass-import-export/src/modules/import.ts b/packages/compass-import-export/src/modules/import.ts index 9dd131930cf..b51b2de803f 100644 --- a/packages/compass-import-export/src/modules/import.ts +++ b/packages/compass-import-export/src/modules/import.ts @@ -386,11 +386,6 @@ export const startImport = (): ImportThunkAction> => { errorLogWriteStream?.close(); } - console.log( - '*** TRACK ***', - connectionRepository.getConnectionInfoById(connectionId) - ); - track( 'Import Completed', { From 22dda1d55057eff0a8aa4784970ee737a49242ef Mon Sep 17 00:00:00 2001 From: Paula Stachova Date: Wed, 3 Jul 2024 15:27:51 +0200 Subject: [PATCH 21/24] fix withConnectionRepository --- .../src/components/connections-provider.tsx | 4 ++-- .../src/components/detailview-component.tsx | 12 ++++++++++-- .../src/components/collections.tsx | 6 +----- 3 files changed, 13 insertions(+), 9 deletions(-) diff --git a/packages/compass-connections/src/components/connections-provider.tsx b/packages/compass-connections/src/components/connections-provider.tsx index f656593cb04..ffd3392d297 100644 --- a/packages/compass-connections/src/components/connections-provider.tsx +++ b/packages/compass-connections/src/components/connections-provider.tsx @@ -91,10 +91,10 @@ function withConnectionRepository< const WithConnectionRepository = ( props: Omit, 'connectionRepository'> & React.Attributes ) => { - const connectionInfoAccess = useConnectionRepository(); + const connectionRepository = useConnectionRepository(); return React.createElement(ReactComponent, { ...props, - connectionInfoAccess, + connectionRepository, }); }; return WithConnectionRepository; diff --git a/packages/compass-serverstats/src/components/detailview-component.tsx b/packages/compass-serverstats/src/components/detailview-component.tsx index ed7f0bee980..87a4b2e3f3e 100644 --- a/packages/compass-serverstats/src/components/detailview-component.tsx +++ b/packages/compass-serverstats/src/components/detailview-component.tsx @@ -47,12 +47,20 @@ export function DetailViewComponent() { }, []); const hideOperationDetails = useCallback(() => { - track('DetailView hideOperationDetails', {}, connectionInfoAccess.getCurrentConnectionInfo()); + track( + 'DetailView hideOperationDetails', + {}, + connectionInfoAccess.getCurrentConnectionInfo() + ); Actions.hideOperationDetails(); }, [track, connectionInfoAccess]); const onKillOp = useCallback(() => { - track('DetailView killOp', {}, connectionInfoAccess.getCurrentConnectionInfo()); + track( + 'DetailView killOp', + {}, + connectionInfoAccess.getCurrentConnectionInfo() + ); if (data?.opid !== undefined) Actions.killOp(data.opid); hideOperationDetails(); }, [data, track, hideOperationDetails, connectionInfoAccess]); diff --git a/packages/databases-collections/src/components/collections.tsx b/packages/databases-collections/src/components/collections.tsx index 0e9de1ca214..33229056b20 100644 --- a/packages/databases-collections/src/components/collections.tsx +++ b/packages/databases-collections/src/components/collections.tsx @@ -59,11 +59,7 @@ const Collections: React.FunctionComponent = ({ const { openCollectionWorkspace } = useOpenWorkspace(); useTrackOnChange((track: TrackFunction) => { - track( - 'Screen', - { name: 'collections' }, - connectionInfo - ); + track('Screen', { name: 'collections' }, connectionInfo); }, []); const onCollectionClick = useCallback( From e603203d17ca29e60746c1bfcdb65aefa4f958c0 Mon Sep 17 00:00:00 2001 From: Paula Stachova Date: Mon, 8 Jul 2024 14:54:57 +0200 Subject: [PATCH 22/24] fixes --- configs/eslint-config-compass/index.js | 3 +++ .../modules/pipeline-builder/pipeline-mode.ts | 13 ++++++++----- .../create-index-modal/create-index-modal.tsx | 2 +- .../base-search-index-modal.tsx | 2 +- .../components/query-history-button-popover.tsx | 2 +- .../src/components/query-history/index.tsx | 2 +- .../src/components/index.tsx | 17 ++++++++++------- .../src/connect-mongo-client.spec.ts | 2 +- .../src/components/collections.tsx | 9 ++++++--- .../src/components/databases.tsx | 9 ++++++--- 10 files changed, 38 insertions(+), 23 deletions(-) diff --git a/configs/eslint-config-compass/index.js b/configs/eslint-config-compass/index.js index 3ea4a6bb8ae..26365332baa 100644 --- a/configs/eslint-config-compass/index.js +++ b/configs/eslint-config-compass/index.js @@ -30,6 +30,9 @@ const tsOverrides = { const tsxRules = { ...common.tsxRules, ...extraTsRules, + "react-hooks/exhaustive-deps": ["warn", { + "additionalHooks": "useTrackOnChange" + }] }; const tsxOverrides = { diff --git a/packages/compass-aggregations/src/modules/pipeline-builder/pipeline-mode.ts b/packages/compass-aggregations/src/modules/pipeline-builder/pipeline-mode.ts index c45390b7265..c7d8f125ee6 100644 --- a/packages/compass-aggregations/src/modules/pipeline-builder/pipeline-mode.ts +++ b/packages/compass-aggregations/src/modules/pipeline-builder/pipeline-mode.ts @@ -95,11 +95,14 @@ export const changePipelineMode = ( pipelineBuilder ).length; - track('Editor Type Changed', { - num_stages, - editor_view_type: mapPipelineModeToEditorViewType(getState()), - connectionInfoAccess, - }); + track( + 'Editor Type Changed', + { + num_stages, + editor_view_type: mapPipelineModeToEditorViewType(getState()), + }, + connectionInfoAccess.getCurrentConnectionInfo() + ); dispatch(updatePipelinePreview()); }; diff --git a/packages/compass-indexes/src/components/create-index-modal/create-index-modal.tsx b/packages/compass-indexes/src/components/create-index-modal/create-index-modal.tsx index 265ba1ebce6..c8af3391597 100644 --- a/packages/compass-indexes/src/components/create-index-modal/create-index-modal.tsx +++ b/packages/compass-indexes/src/components/create-index-modal/create-index-modal.tsx @@ -69,7 +69,7 @@ function CreateIndexModal({ ); } }, - [isVisible], + [isVisible, connectionInfoAccess], undefined ); diff --git a/packages/compass-indexes/src/components/search-indexes-modals/base-search-index-modal.tsx b/packages/compass-indexes/src/components/search-indexes-modals/base-search-index-modal.tsx index 221d33860ed..c1f0eaf7c1f 100644 --- a/packages/compass-indexes/src/components/search-indexes-modals/base-search-index-modal.tsx +++ b/packages/compass-indexes/src/components/search-indexes-modals/base-search-index-modal.tsx @@ -205,7 +205,7 @@ export const BaseSearchIndexModal: React.FunctionComponent< } } }, - [isModalOpen, mode], + [isModalOpen, mode, connectionInfoAccess], undefined ); diff --git a/packages/compass-query-bar/src/components/query-history-button-popover.tsx b/packages/compass-query-bar/src/components/query-history-button-popover.tsx index 3c6295ca91f..fae6dbebbf6 100644 --- a/packages/compass-query-bar/src/components/query-history-button-popover.tsx +++ b/packages/compass-query-bar/src/components/query-history-button-popover.tsx @@ -54,7 +54,7 @@ const QueryHistoryButtonPopover = ({ track('Query History Closed', {}, connectionInfo); } }, - [isOpen], + [isOpen, connectionInfoAccess], undefined ); diff --git a/packages/compass-query-bar/src/components/query-history/index.tsx b/packages/compass-query-bar/src/components/query-history/index.tsx index 9a42cae2617..e817f9f1b93 100644 --- a/packages/compass-query-bar/src/components/query-history/index.tsx +++ b/packages/compass-query-bar/src/components/query-history/index.tsx @@ -52,7 +52,7 @@ const QueryHistory = ({ track('Query History Recent', {}, connectionInfo); } }, - [tab], + [tab, connectionInfoAccess], undefined ); diff --git a/packages/compass-serverstats/src/components/index.tsx b/packages/compass-serverstats/src/components/index.tsx index f56d928637f..a6757433c2c 100644 --- a/packages/compass-serverstats/src/components/index.tsx +++ b/packages/compass-serverstats/src/components/index.tsx @@ -121,13 +121,16 @@ function PerformanceComponent() { const eventDispatcher = useRef(realTimeDispatcher()); const connectionInfoAccess = useConnectionInfoAccess(); - useTrackOnChange((track: TrackFunction) => { - track( - 'Screen', - { name: 'performance' }, - connectionInfoAccess.getCurrentConnectionInfo() - ); - }, []); + useTrackOnChange( + (track: TrackFunction) => { + track( + 'Screen', + { name: 'performance' }, + connectionInfoAccess.getCurrentConnectionInfo() + ); + }, + [connectionInfoAccess] + ); useEffect(() => { return () => { diff --git a/packages/data-service/src/connect-mongo-client.spec.ts b/packages/data-service/src/connect-mongo-client.spec.ts index db9710f7d1c..864113072bf 100644 --- a/packages/data-service/src/connect-mongo-client.spec.ts +++ b/packages/data-service/src/connect-mongo-client.spec.ts @@ -229,7 +229,7 @@ describe('connectMongoClient', function () { asyncHook.disable(); }); - it.skip('should close ssh tunnel if the connection fails', async function () { + it('should close ssh tunnel if the connection fails', async function () { const connectionOptions: ConnectionOptions = { connectionString: 'mongodb://localhost:27020?serverSelectionTimeoutMS=100', diff --git a/packages/databases-collections/src/components/collections.tsx b/packages/databases-collections/src/components/collections.tsx index 33229056b20..7a6b202a33a 100644 --- a/packages/databases-collections/src/components/collections.tsx +++ b/packages/databases-collections/src/components/collections.tsx @@ -58,9 +58,12 @@ const Collections: React.FunctionComponent = ({ const { id: connectionId } = connectionInfo; const { openCollectionWorkspace } = useOpenWorkspace(); - useTrackOnChange((track: TrackFunction) => { - track('Screen', { name: 'collections' }, connectionInfo); - }, []); + useTrackOnChange( + (track: TrackFunction) => { + track('Screen', { name: 'collections' }, connectionInfo); + }, + [connectionInfo] + ); const onCollectionClick = useCallback( (ns: string) => { diff --git a/packages/databases-collections/src/components/databases.tsx b/packages/databases-collections/src/components/databases.tsx index 83f6b0ca585..e44226acf4f 100644 --- a/packages/databases-collections/src/components/databases.tsx +++ b/packages/databases-collections/src/components/databases.tsx @@ -112,9 +112,12 @@ const Databases: React.FunctionComponent = ({ _onCreateDatabaseClick(connectionId); }, [connectionId, _onCreateDatabaseClick]); - useTrackOnChange((track: TrackFunction) => { - track('Screen', { name: 'databases' }, connectionInfo); - }, []); + useTrackOnChange( + (track: TrackFunction) => { + track('Screen', { name: 'databases' }, connectionInfo); + }, + [connectionInfo] + ); const renderLoadSampleDataBanner = useCallback(() => { if ( From 09a4faa1268b73ec70f2c02bdca0dec0924e2dc0 Mon Sep 17 00:00:00 2001 From: Paula Stachova Date: Mon, 8 Jul 2024 16:06:22 +0200 Subject: [PATCH 23/24] reformat --- configs/eslint-config-compass/index.js | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/configs/eslint-config-compass/index.js b/configs/eslint-config-compass/index.js index 26365332baa..2e6adc138ed 100644 --- a/configs/eslint-config-compass/index.js +++ b/configs/eslint-config-compass/index.js @@ -30,9 +30,12 @@ const tsOverrides = { const tsxRules = { ...common.tsxRules, ...extraTsRules, - "react-hooks/exhaustive-deps": ["warn", { - "additionalHooks": "useTrackOnChange" - }] + 'react-hooks/exhaustive-deps': [ + 'warn', + { + additionalHooks: 'useTrackOnChange', + }, + ], }; const tsxOverrides = { From 95e0f961eb4fc5333f44ce667945e923c35ccfd5 Mon Sep 17 00:00:00 2001 From: Paula Stachova Date: Tue, 9 Jul 2024 12:03:35 +0200 Subject: [PATCH 24/24] .. --- .../src/components/collection-tab.tsx | 14 ++++++++++---- packages/compass/src/app/components/entrypoint.tsx | 6 ++++-- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/packages/compass-collection/src/components/collection-tab.tsx b/packages/compass-collection/src/components/collection-tab.tsx index 609698d38e0..5bcb7dd318f 100644 --- a/packages/compass-collection/src/components/collection-tab.tsx +++ b/packages/compass-collection/src/components/collection-tab.tsx @@ -22,6 +22,7 @@ import { } from './collection-tab-stats'; import type { CollectionSubtab } from '@mongodb-js/compass-workspaces'; import { useTelemetry } from '@mongodb-js/compass-telemetry/provider'; +import { useConnectionInfoAccess } from '@mongodb-js/compass-connections/provider'; function trackingIdForTabName(name: string) { return name.toLowerCase().replace(/ /g, '_'); @@ -119,6 +120,7 @@ const CollectionTabWithMetadata: React.FunctionComponent< stats, }) => { const track = useTelemetry(); + const connectionInfoAccess = useConnectionInfoAccess(); const { log, mongoLogId } = useLogger('COMPASS-COLLECTION-TAB-UI'); useEffect(() => { const activeSubTabName = currentTab @@ -126,11 +128,15 @@ const CollectionTabWithMetadata: React.FunctionComponent< : null; if (activeSubTabName) { - track('Screen', { - name: activeSubTabName, - }); + track( + 'Screen', + { + name: activeSubTabName, + }, + connectionInfoAccess.getCurrentConnectionInfo() + ); } - }, [currentTab, track]); + }, [currentTab, track, connectionInfoAccess]); const pluginTabs = useCollectionSubTabs(); const pluginModals = useCollectionScopedModals(); diff --git a/packages/compass/src/app/components/entrypoint.tsx b/packages/compass/src/app/components/entrypoint.tsx index 100977886e4..c263e42c6a9 100644 --- a/packages/compass/src/app/components/entrypoint.tsx +++ b/packages/compass/src/app/components/entrypoint.tsx @@ -25,8 +25,10 @@ import { LoggerProvider } from '@mongodb-js/compass-logging/provider'; import { TelemetryProvider } from '@mongodb-js/compass-telemetry/provider'; import { getAppName, getAppVersion } from '@mongodb-js/compass-utils'; import Home, { type HomeProps } from './home'; -import { createIpcSendTrack } from '@mongodb-js/compass-telemetry'; -import type { TelemetryServiceOptions } from '@mongodb-js/compass-telemetry/dist/generic-track'; +import { + type TelemetryServiceOptions, + createIpcSendTrack, +} from '@mongodb-js/compass-telemetry'; const WithPreferencesAndLoggerProviders: React.FC = ({ children }) => { const loggerProviderValue = useRef({