Skip to content

Commit

Permalink
ui: split txn and stmt fingerprints requests and storage
Browse files Browse the repository at this point in the history
Previously, both the stmt and txns fingerprints
pages were using the same api response from the
/statements. This was because we need the stmts
response to build txns pages. Howevever having to
fetch both types of stats can slow down the request.
Now that we can specify the fetch_mode as part of
the request, we can split the 2 into their own api
calls and redux fields.

Epic: none
Part of: cockroachdb#97875

Release note: None
  • Loading branch information
xinhaoz committed May 15, 2023
1 parent a3c4857 commit bdfb915
Show file tree
Hide file tree
Showing 21 changed files with 362 additions and 54 deletions.
25 changes: 24 additions & 1 deletion pkg/ui/workspaces/cluster-ui/src/api/statementsApi.ts
Expand Up @@ -24,6 +24,11 @@ export type StatementDetailsResponseWithKey = {
key: string;
};

export type SqlStatsResponse = cockroach.server.serverpb.StatementsResponse;

const FetchStatsMode =
cockroach.server.serverpb.CombinedStatementsStatsRequest.StatsType;

export type ErrorWithKey = {
err: Error;
key: string;
Expand All @@ -35,13 +40,31 @@ export const getCombinedStatements = (
const queryStr = propsToQueryString({
start: req.start.toInt(),
end: req.end.toInt(),
"fetch_mode.stats_type": FetchStatsMode.StmtStatsOnly,
});
return fetchData(
cockroach.server.serverpb.StatementsResponse,
`${STATEMENTS_PATH}?${queryStr}`,
null,
null,
"30M",
"10M",
);
};

export const getFlushedTxnStatsApi = (
req: StatementsRequest,
): Promise<SqlStatsResponse> => {
const queryStr = propsToQueryString({
start: req.start.toInt(),
end: req.end.toInt(),
"fetch_mode.stats_type": FetchStatsMode.TxnStatsOnly,
});
return fetchData(
cockroach.server.serverpb.StatementsResponse,
`${STATEMENTS_PATH}?${queryStr}`,
null,
null,
"10M",
);
};

Expand Down
Expand Up @@ -10,11 +10,14 @@

import { AnyAction } from "redux";
import { all, call, takeEvery, takeLatest, put } from "redux-saga/effects";
import { actions, LocalStorageKeys } from "./localStorage.reducer";
import {
actions,
LocalStorageKeys,
TypedPayload,
} from "./localStorage.reducer";
import { actions as sqlStatsActions } from "src/store/sqlStats";
import { PayloadAction } from "@reduxjs/toolkit";
import { TypedPayload } from "./localStorage.reducer";
import { TimeScale } from "../../timeScaleDropdown";
import { TimeScale } from "src/timeScaleDropdown";

export function* updateLocalStorageItemSaga(action: AnyAction) {
const { key, value } = action.payload;
Expand All @@ -28,12 +31,11 @@ export function* updateLocalStorageItemSaga(action: AnyAction) {
export function* updateTimeScale(
action: PayloadAction<TypedPayload<TimeScale>>,
) {
yield all([put(sqlStatsActions.invalidated())]);
const { value } = action.payload;
yield put(sqlStatsActions.invalidated());
yield call(
{ context: localStorage, fn: localStorage.setItem },
LocalStorageKeys.GLOBAL_TIME_SCALE,
JSON.stringify(value),
JSON.stringify(action.payload?.value),
);
}

Expand Down
4 changes: 2 additions & 2 deletions pkg/ui/workspaces/cluster-ui/src/store/reducers.spec.ts
Expand Up @@ -25,8 +25,8 @@ describe("rootReducer", () => {

assert.deepEqual(initState, resetState);
assert.notDeepEqual(
resetState.sqlStats.lastError,
changedState.sqlStats.lastError,
resetState.statements.lastError,
changedState.statements.lastError,
);
});
});
7 changes: 5 additions & 2 deletions pkg/ui/workspaces/cluster-ui/src/store/reducers.ts
Expand Up @@ -29,6 +29,7 @@ import {
SQLDetailsStatsReducerState,
reducer as sqlDetailsStats,
} from "./statementDetails";
import { reducer as txnStats, TxnStatsState } from "./transactionStats";

export type AdminUiState = {
statementDiagnostics: StatementDiagnosticsState;
Expand All @@ -38,7 +39,8 @@ export type AdminUiState = {
sessions: SessionsState;
terminateQuery: TerminateQueryState;
uiConfig: UIConfigState;
sqlStats: SQLStatsState;
statements: SQLStatsState;
transactions: TxnStatsState;
sqlDetailsStats: SQLDetailsStatsReducerState;
};

Expand All @@ -54,7 +56,8 @@ export const reducers = combineReducers<AdminUiState>({
sessions,
terminateQuery,
uiConfig,
sqlStats,
statements: sqlStats,
transactions: txnStats,
sqlDetailsStats,
});

Expand Down
2 changes: 2 additions & 0 deletions pkg/ui/workspaces/cluster-ui/src/store/sagas.ts
Expand Up @@ -21,6 +21,7 @@ import { notifificationsSaga } from "./notifications";
import { sqlStatsSaga } from "./sqlStats";
import { sqlDetailsStatsSaga } from "./statementDetails";
import { uiConfigSaga } from "./uiConfig";
import { txnStatsSaga } from "./transactionStats";

export function* sagas(cacheInvalidationPeriod?: number): SagaIterator {
yield all([
Expand All @@ -34,5 +35,6 @@ export function* sagas(cacheInvalidationPeriod?: number): SagaIterator {
fork(sqlStatsSaga),
fork(sqlDetailsStatsSaga),
fork(uiConfigSaga, cacheInvalidationPeriod),
fork(txnStatsSaga),
]);
}
Expand Up @@ -37,6 +37,8 @@ export type UpdateTimeScalePayload = {
ts: TimeScale;
};

// This is actually statements only, despite the SQLStatsState name.
// We can rename this in the future. Leaving it now to reduce backport surface area.
const sqlStatsSlice = createSlice({
name: `${DOMAIN_NAME}/sqlstats`,
initialState,
Expand Down
Expand Up @@ -20,6 +20,7 @@ import {
actions as sqlStatsActions,
UpdateTimeScalePayload,
} from "./sqlStats.reducer";
import { actions as txnStatsActions } from "../transactionStats";
import { actions as sqlDetailsStatsActions } from "../statementDetails/statementDetails.reducer";

export function* refreshSQLStatsSaga(action: PayloadAction<StatementsRequest>) {
Expand Down Expand Up @@ -54,6 +55,7 @@ export function* resetSQLStatsSaga() {
yield all([
put(sqlDetailsStatsActions.invalidateAll()),
put(sqlStatsActions.invalidated()),
put(txnStatsActions.invalidated()),
]);
} catch (e) {
yield put(sqlStatsActions.failed(e));
Expand Down
Expand Up @@ -18,5 +18,5 @@ const adminUISelector = createSelector(

export const sqlStatsSelector = createSelector(
adminUISelector,
adminUiState => adminUiState?.sqlStats,
adminUiState => adminUiState?.statements,
);
12 changes: 12 additions & 0 deletions pkg/ui/workspaces/cluster-ui/src/store/transactionStats/index.ts
@@ -0,0 +1,12 @@
// Copyright 2023 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.

export * from "./txnStats.reducer";
export * from "./txnStats.sagas";
@@ -0,0 +1,66 @@
// Copyright 2023 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.

import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { DOMAIN_NAME } from "../utils";
import { StatementsRequest } from "src/api/statementsApi";
import { TimeScale } from "../../timeScaleDropdown";
import moment from "moment";
import { StatementsResponse } from "../sqlStats";

export type TxnStatsState = {
// Note that we request transactions from the
// statements api, hence the StatementsResponse type here.
data: StatementsResponse;
inFlight: boolean;
lastError: Error;
valid: boolean;
lastUpdated: moment.Moment | null;
};

const initialState: TxnStatsState = {
data: null,
inFlight: false,
lastError: null,
valid: false,
lastUpdated: null,
};

const txnStatsSlice = createSlice({
name: `${DOMAIN_NAME}/txnStats`,
initialState,
reducers: {
received: (state, action: PayloadAction<StatementsResponse>) => {
state.inFlight = false;
state.data = action.payload;
state.valid = true;
state.lastError = null;
state.lastUpdated = moment.utc();
},
failed: (state, action: PayloadAction<Error>) => {
state.inFlight = false;
state.valid = false;
state.lastError = action.payload;
state.lastUpdated = moment.utc();
},
invalidated: state => {
state.inFlight = false;
state.valid = false;
},
refresh: (state, _: PayloadAction<StatementsRequest>) => {
state.inFlight = true;
},
request: (state, _: PayloadAction<StatementsRequest>) => {
state.inFlight = true;
},
},
});

export const { reducer, actions } = txnStatsSlice;
@@ -0,0 +1,100 @@
// Copyright 2023 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.

import { expectSaga } from "redux-saga-test-plan";
import {
EffectProviders,
StaticProvider,
throwError,
} from "redux-saga-test-plan/providers";
import * as matchers from "redux-saga-test-plan/matchers";
import { cockroach } from "@cockroachlabs/crdb-protobuf-client";

import { getFlushedTxnStatsApi } from "src/api/statementsApi";
import { refreshTxnStatsSaga, requestTxnStatsSaga } from "./txnStats.sagas";
import { actions, reducer, TxnStatsState } from "./txnStats.reducer";
import Long from "long";
import moment from "moment";

const lastUpdated = moment();

describe("txnStats sagas", () => {
let spy: jest.SpyInstance;
beforeAll(() => {
spy = jest.spyOn(moment, "utc").mockImplementation(() => lastUpdated);
});

afterAll(() => {
spy.mockRestore();
});

const payload = new cockroach.server.serverpb.CombinedStatementsStatsRequest({
start: Long.fromNumber(1596816675),
end: Long.fromNumber(1596820675),
});

const txnStatsResponse = new cockroach.server.serverpb.StatementsResponse({
transactions: [
{
stats_data: { transaction_fingerprint_id: new Long(1) },
},
{
stats_data: { transaction_fingerprint_id: new Long(2) },
},
],
last_reset: null,
});

const txnStatsAPIProvider: (EffectProviders | StaticProvider)[] = [
[matchers.call.fn(getFlushedTxnStatsApi), txnStatsResponse],
];

describe("refreshTxnStatsSaga", () => {
it("dispatches request txnStats action", () => {
return expectSaga(refreshTxnStatsSaga, actions.request(payload))
.provide(txnStatsAPIProvider)
.put(actions.request(payload))
.run();
});
});

describe("requestTxnStatsSaga", () => {
it("successfully requests statements list", () => {
return expectSaga(requestTxnStatsSaga, actions.request(payload))
.provide(txnStatsAPIProvider)
.put(actions.received(txnStatsResponse))
.withReducer(reducer)
.hasFinalState<TxnStatsState>({
inFlight: false,
data: txnStatsResponse,
lastError: null,
valid: true,
lastUpdated,
})
.run();
});

it("returns error on failed request", () => {
const error = new Error("Failed request");
return expectSaga(requestTxnStatsSaga, actions.request(payload))
.provide([[matchers.call.fn(getFlushedTxnStatsApi), throwError(error)]])
.put(actions.failed(error))
.withReducer(reducer)
.hasFinalState<TxnStatsState>({
inFlight: false,
data: null,
lastError: error,
valid: false,
lastUpdated,
})
.run();
});
});
});
@@ -0,0 +1,41 @@
// Copyright 2023 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.

import { PayloadAction } from "@reduxjs/toolkit";
import { all, call, put, takeLatest } from "redux-saga/effects";
import {
getFlushedTxnStatsApi,
StatementsRequest,
} from "src/api/statementsApi";
import { actions as txnStatsActions } from "./txnStats.reducer";

export function* refreshTxnStatsSaga(
action: PayloadAction<StatementsRequest>,
): any {
yield put(txnStatsActions.request(action.payload));
}

export function* requestTxnStatsSaga(
action: PayloadAction<StatementsRequest>,
): any {
try {
const result = yield call(getFlushedTxnStatsApi, action.payload);
yield put(txnStatsActions.received(result));
} catch (e) {
yield put(txnStatsActions.failed(e));
}
}

export function* txnStatsSaga(): any {
yield all([
takeLatest(txnStatsActions.refresh, refreshTxnStatsSaga),
takeLatest(txnStatsActions.request, requestTxnStatsSaga),
]);
}

0 comments on commit bdfb915

Please sign in to comment.