Skip to content

Commit 399b9b0

Browse files
committed
more cleanup, reformat and tests
1 parent 212dad8 commit 399b9b0

File tree

6 files changed

+62
-90
lines changed

6 files changed

+62
-90
lines changed

packages/compass-schema/src/components/compass-schema.tsx

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ import { useConnectionInfo } from '@mongodb-js/compass-connections/provider';
3535
import { getAtlasPerformanceAdvisorLink } from '../utils';
3636
import { useIsLastAppliedQueryOutdated } from '@mongodb-js/compass-query-bar';
3737
import { useTelemetry } from '@mongodb-js/compass-telemetry/provider';
38-
import type { RootState, SchemaThunkDispatch } from '../stores/store';
38+
import type { RootState } from '../stores/store';
3939
import { startAnalysis, stopAnalysis } from '../stores/reducer';
4040

4141
const rootStyles = css({
@@ -372,7 +372,7 @@ const Schema: React.FunctionComponent<{
372372
maxTimeMS?: number;
373373
schema: MongodbSchema | null;
374374
count?: number;
375-
resultId?: number;
375+
resultId?: string;
376376
onStartAnalysis: () => Promise<void>;
377377
onStopAnalysis: () => void;
378378
}> = ({
@@ -387,14 +387,6 @@ const Schema: React.FunctionComponent<{
387387
void onStartAnalysis();
388388
}, [onStartAnalysis]);
389389

390-
const onCancelClicked = useCallback(() => {
391-
onStopAnalysis();
392-
}, [onStopAnalysis]);
393-
394-
const onResetClicked = useCallback(() => {
395-
onStopAnalysis();
396-
}, [onStopAnalysis]);
397-
398390
const outdated = useIsLastAppliedQueryOutdated('schema');
399391

400392
const enablePerformanceAdvisorBanner = usePreference(
@@ -407,12 +399,12 @@ const Schema: React.FunctionComponent<{
407399
toolbar={
408400
<SchemaToolbar
409401
onAnalyzeSchemaClicked={onApplyClicked}
410-
onResetClicked={onResetClicked}
402+
onResetClicked={onStopAnalysis}
411403
analysisState={analysisState}
412404
errorMessage={errorMessage || ''}
413405
isOutdated={!!outdated}
414406
sampleSize={schema ? schema.count : 0}
415-
schemaResultId={String(resultId) || ''}
407+
schemaResultId={resultId || ''}
416408
/>
417409
}
418410
>
@@ -422,7 +414,7 @@ const Schema: React.FunctionComponent<{
422414
<InitialScreen onApplyClicked={onApplyClicked} />
423415
)}
424416
{analysisState === ANALYSIS_STATE_ANALYZING && (
425-
<AnalyzingScreen onCancelClicked={onCancelClicked} />
417+
<AnalyzingScreen onCancelClicked={onStopAnalysis} />
426418
)}
427419
{analysisState === ANALYSIS_STATE_COMPLETE && (
428420
<FieldList schema={schema} analysisState={analysisState} />

packages/compass-schema/src/components/field.spec.tsx

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ import {
1313
type SchemaType,
1414
} from 'mongodb-schema';
1515
import { BSON, Decimal128 } from 'bson';
16-
import { configureActions } from '../actions';
1716
import Field, { shouldShowUnboundArrayInsight } from './field';
1817
import QueryBarPlugin from '@mongodb-js/compass-query-bar';
1918
import {
@@ -44,7 +43,6 @@ function renderField(
4443
<MockQueryBarPlugin {...(queryBarProps as any)}>
4544
<Field
4645
enableMaps={false}
47-
actions={configureActions()}
4846
name="testFieldName"
4947
path={['test']}
5048
{...props}

packages/compass-schema/src/components/minichart/minichart.jsx

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,13 +34,10 @@ class MiniChart extends PureComponent {
3434
// but it is not noticable to the user.
3535
this.resizeListener();
3636
window.addEventListener('resize', this.resizeListener);
37-
// this.unsubscribeMiniChartResize =
38-
// this.props.actions.resizeMiniCharts.listen(this.resizeListener); // TODO: what was this doing?
3937
}
4038

4139
componentWillUnmount() {
4240
window.removeEventListener('resize', this.resizeListener);
43-
// this.unsubscribeMiniChartResize();
4441
}
4542

4643
/**

packages/compass-schema/src/stores/reducer.ts

Lines changed: 17 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,6 @@ import {
88
ANALYSIS_STATE_INITIAL,
99
ANALYSIS_STATE_TIMEOUT,
1010
} from '../constants/analysis-states';
11-
12-
import type { Query } from '@mongodb-js/compass-query-bar';
1311
import { addLayer, generateGeoQuery } from '../modules/geo';
1412
import {
1513
analyzeSchema,
@@ -21,6 +19,7 @@ import { openToast } from '@mongodb-js/compass-components';
2119
import type { Circle, Layer, LayerGroup, Polygon } from 'leaflet';
2220
import { mongoLogId } from '@mongodb-js/compass-logging/provider';
2321
import type { SchemaThunkAction } from './store';
22+
import { UUID } from 'bson';
2423

2524
const DEFAULT_SAMPLE_SIZE = 1000;
2625

@@ -37,7 +36,7 @@ export type SchemaState = {
3736
analysisState: AnalysisState;
3837
errorMessage: string;
3938
schema: Schema | null;
40-
resultId: number;
39+
resultId: string;
4140
};
4241

4342
export const enum SchemaActions {
@@ -61,10 +60,6 @@ export type AnalysisFailedAction = {
6160
error: Error;
6261
};
6362

64-
export type analysisCancelled = {
65-
type: SchemaActions.analysisCancelled;
66-
};
67-
6863
const reducer: Reducer<SchemaState, Action> = (
6964
state = getInitialState(),
7065
action
@@ -99,13 +94,6 @@ const reducer: Reducer<SchemaState, Action> = (
9994
};
10095
}
10196

102-
if (isAction<analysisCancelled>(action, SchemaActions.analysisCancelled)) {
103-
return {
104-
...state,
105-
analysisState: ANALYSIS_STATE_INITIAL,
106-
};
107-
}
108-
10997
return state;
11098
};
11199

@@ -124,8 +112,8 @@ function getErrorState(err: Error & { code?: number }) {
124112
return { analysisState, errorMessage };
125113
}
126114

127-
function resultId(): number {
128-
return Math.floor(Math.random() * 2 ** 53);
115+
function resultId(): string {
116+
return new UUID().toString();
129117
}
130118

131119
export const handleSchemaShare = (): SchemaThunkAction<void> => {
@@ -182,12 +170,6 @@ const getInitialState = (): SchemaState => ({
182170
resultId: resultId(),
183171
});
184172

185-
export const onSchemaSampled = (): SchemaThunkAction<void> => {
186-
return (dispatch, getState, { geoLayersRef }) => {
187-
geoLayersRef.current = {};
188-
};
189-
};
190-
191173
export const geoLayerAdded = (
192174
field: string,
193175
layer: Layer
@@ -228,28 +210,6 @@ export const geoLayersDeleted = (
228210
export const stopAnalysis = (): SchemaThunkAction<void> => {
229211
return (dispatch, getState, { abortControllerRef }) => {
230212
abortControllerRef.current?.abort();
231-
dispatch({ type: SchemaActions.analysisCancelled });
232-
};
233-
};
234-
235-
export const _trackSchemaAnalyzed = (
236-
analysisTimeMS: number,
237-
query: Query
238-
): SchemaThunkAction<void> => {
239-
return (dispatch, getState, { track, connectionInfoRef }) => {
240-
const { schema } = getState();
241-
// Use a function here to a) ensure that the calculations here
242-
// are only made when telemetry is enabled and b) that errors from
243-
// those calculations are caught and logged rather than displayed to
244-
// users as errors from the core schema analysis logic.
245-
const trackEvent = () => ({
246-
with_filter: Object.entries(query.filter ?? {}).length > 0,
247-
schema_width: schema?.fields?.length ?? 0,
248-
schema_depth: schema ? calculateSchemaDepth(schema) : 0,
249-
geo_data: schema ? schemaContainsGeoData(schema) : false,
250-
analysis_time_ms: analysisTimeMS,
251-
});
252-
track('Schema Analyzed', trackEvent, connectionInfoRef.current);
253213
};
254214
};
255215

@@ -269,6 +229,9 @@ export const startAnalysis = (): SchemaThunkAction<
269229
fieldStoreService,
270230
abortControllerRef,
271231
namespace,
232+
geoLayersRef,
233+
connectionInfoRef,
234+
track,
272235
}
273236
) => {
274237
const query = queryBar.getLastAppliedQuery('schema');
@@ -295,10 +258,6 @@ export const startAnalysis = (): SchemaThunkAction<
295258

296259
dispatch({ type: SchemaActions.analysisStarted });
297260

298-
abortSignal?.addEventListener('abort', () => {
299-
dispatch(stopAnalysis());
300-
});
301-
302261
const analysisStartTime = Date.now();
303262
const schema = await analyzeSchema(
304263
dataService,
@@ -316,9 +275,17 @@ export const startAnalysis = (): SchemaThunkAction<
316275

317276
dispatch({ type: SchemaActions.analysisFinished, schema });
318277

319-
_trackSchemaAnalyzed(analysisTime, query);
278+
// track schema analyzed
279+
const trackEvent = () => ({
280+
with_filter: Object.entries(query.filter ?? {}).length > 0,
281+
schema_width: schema?.fields?.length ?? 0,
282+
schema_depth: schema ? calculateSchemaDepth(schema) : 0,
283+
geo_data: schema ? schemaContainsGeoData(schema) : false,
284+
analysis_time_ms: analysisTime,
285+
});
286+
track('Schema Analyzed', trackEvent, connectionInfoRef.current);
320287

321-
dispatch(onSchemaSampled());
288+
geoLayersRef.current = {};
322289
} catch (err: any) {
323290
log.error(
324291
mongoLogId(1_001_000_188),

packages/compass-schema/src/stores/store.spec.ts

Lines changed: 39 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
import type { SchemaStore } from './store';
2-
import { activateSchemaPlugin } from './store';
1+
import { activateSchemaPlugin, type SchemaStore } from './store';
32
import AppRegistry, { createActivateHelpers } from 'hadron-app-registry';
43
import { expect } from 'chai';
54

@@ -9,6 +8,8 @@ import { createNoopLogger } from '@mongodb-js/compass-logging/provider';
98
import type { FieldStoreService } from '@mongodb-js/compass-field-store';
109
import { createNoopTrack } from '@mongodb-js/compass-telemetry/provider';
1110
import type { ConnectionInfoRef } from '@mongodb-js/compass-connections/provider';
11+
import { startAnalysis, stopAnalysis } from './reducer';
12+
import Sinon from 'sinon';
1213

1314
const dummyLogger = createNoopLogger('TEST');
1415
const dummyTrack = createNoopTrack();
@@ -28,15 +29,24 @@ describe('Schema Store', function () {
2829
describe('#configureStore', function () {
2930
let store: SchemaStore;
3031
let deactivate: () => void;
32+
let sandbox: Sinon.SinonSandbox;
3133
const localAppRegistry = new AppRegistry();
3234
const globalAppRegistry = new AppRegistry();
33-
const dataService = 'test';
3435
const namespace = 'db.coll';
3536
const connectionInfoRef = {
3637
current: {},
3738
} as ConnectionInfoRef;
39+
let sampleStub: Sinon.SinonStub;
40+
let isCancelErrorStub: Sinon.SinonStub;
3841

3942
beforeEach(async function () {
43+
sandbox = Sinon.createSandbox();
44+
sampleStub = sandbox.stub();
45+
isCancelErrorStub = sandbox.stub();
46+
const dataService = {
47+
sample: sampleStub,
48+
isCancelError: isCancelErrorStub,
49+
};
4050
const plugin = activateSchemaPlugin(
4151
{
4252
namespace: namespace,
@@ -60,34 +70,42 @@ describe('Schema Store', function () {
6070

6171
afterEach(function () {
6272
deactivate();
73+
sandbox.reset();
6374
});
6475

65-
it('sets the local app registry', function () {
66-
expect(store.localAppRegistry).to.equal(localAppRegistry);
67-
});
68-
69-
it('sets the global app registry', function () {
70-
expect(store.globalAppRegistry).to.equal(globalAppRegistry);
71-
});
72-
73-
it('sets the data provider', function () {
74-
expect(store.dataService).to.equal(dataService);
76+
it('defaults analysis state to initial', function () {
77+
expect(store.getState().analysisState).to.equal(ANALYSIS_STATE_INITIAL);
7578
});
7679

77-
it('sets the namespace', function () {
78-
expect(store.ns).to.equal(namespace);
80+
it('defaults the error to empty', function () {
81+
expect(store.getState().errorMessage).to.equal('');
7982
});
8083

81-
it('defaults analysis state to initial', function () {
82-
expect(store.state.analysisState).to.equal(ANALYSIS_STATE_INITIAL);
84+
it('defaults the schema to null', function () {
85+
expect(store.getState().schema).to.equal(null);
8386
});
8487

85-
it('defaults the error to empty', function () {
86-
expect(store.state.errorMessage).to.equal('');
88+
it('runs analysis', async function () {
89+
const oldResultId = store.getState().resultId;
90+
sampleStub.resolves([{ name: 'Hans' }, { name: 'Greta' }]);
91+
await store.dispatch(startAnalysis());
92+
expect(sampleStub).to.have.been.called;
93+
const { analysisState, errorMessage, schema, resultId } =
94+
store.getState();
95+
expect(analysisState).to.equal('complete');
96+
expect(!!errorMessage).to.be.false;
97+
expect(schema).not.to.be.null;
98+
expect(resultId).not.to.equal(oldResultId);
8799
});
88100

89-
it('defaults the schema to null', function () {
90-
expect(store.state.schema).to.equal(null);
101+
it('analysis can be aborted', async function () {
102+
const analysisPromise = store.dispatch(startAnalysis());
103+
expect(store.getState().analysisState).to.equal('analyzing');
104+
sampleStub.rejects(new Error('abort'));
105+
store.dispatch(stopAnalysis());
106+
isCancelErrorStub.returns(true);
107+
await analysisPromise;
108+
expect(store.getState().analysisState).to.equal('initial');
91109
});
92110
});
93111
});

packages/compass-schema/src/stores/store.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,4 +98,4 @@ export function configureStore(
9898
return store;
9999
}
100100

101-
export type AtlasServiceStore = ReturnType<typeof configureStore>;
101+
export type SchemaStore = ReturnType<typeof configureStore>;

0 commit comments

Comments
 (0)