Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[MD] Refactor data source server side error handling #2661

Merged
merged 7 commits into from
Oct 27, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/core/server/http/router/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,7 @@ export class Router implements IRouter {
return e;
}

if (isDataSourceConfigError(e)) {
if (isDataSourceError(e)) {
return hapiResponseAdapter.handle(
opensearchDashboardsResponseFactory.badRequest({ body: e.message })
);
Expand All @@ -312,8 +312,8 @@ export class Router implements IRouter {
}
}

const isDataSourceConfigError = (error: any) => {
return error.constructor.name === 'DataSourceConfigError' && error.statusCode === 400;
const isDataSourceError = (error: any) => {
return error.constructor.name === 'DataSourceError' && error.statusCode === 400;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we use instanceofinstead of error.constructor.name ?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

importing DataSourceError from plugin module to here(core module) doesn't sound like a good practice. But anyway, I did some refactor to move data source error response logic from router.ts to resolve_index.ts(/internal/index-pattern-manage/resolve-index).

I checked the codebase, only the route handler defined resolve_index is missing error handling. All other internal/xxx/xxx API has err handling. E.g internal/search/, /internal/_msearch, /internal/index-pattern-manage/preview-script

```
catch (err) {
        return res.customError({
          statusCode: err.statusCode,
          body: {
            message: err.message,
            attributes: {
              error: err.body.error,
            },
          },
        });
```   

@zengyan-amazon could you review again

};

const convertOpenSearchUnauthorized = (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,11 @@
*/

import { first } from 'rxjs/operators';
import { SharedGlobalConfig, Logger } from 'opensearch-dashboards/server';
import { SearchResponse } from 'elasticsearch';
import { Observable } from 'rxjs';
import { ApiResponse } from '@opensearch-project/opensearch';
import { createDataSourceError } from '../../../../data_source/server';
import { SharedGlobalConfig, Logger } from '../../../../../core/server';
import { SearchUsage } from '../collectors/usage';
import { toSnakeCase } from './to_snake_case';
import {
Expand Down Expand Up @@ -86,8 +87,11 @@ export const opensearchSearchStrategyProvider = (
rawResponse,
...getTotalLoaded(rawResponse._shards),
};
} catch (e) {
} catch (e: any) {
zhongnansu marked this conversation as resolved.
Show resolved Hide resolved
if (usage) usage.trackError();
if (request.dataSourceId) {
throw createDataSourceError(e);
}
throw e;
}
},
Expand Down
10 changes: 5 additions & 5 deletions src/plugins/data_source/server/client/configure_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
} from '../../common/data_sources';
import { DataSourcePluginConfigType } from '../../config';
import { CryptographyServiceSetup } from '../cryptography_service';
import { DataSourceConfigError } from '../lib/error';
import { createDataSourceError, DataSourceError } from '../lib/error';
import { DataSourceClientParams } from '../types';
import { parseClientOptions } from './client_config';
import { OpenSearchClientPoolSetup } from './client_pool';
Expand All @@ -32,8 +32,8 @@ export const configureClient = async (
} catch (error: any) {
logger.error(`Failed to get data source client for dataSourceId: [${dataSourceId}]`);
logger.error(error);
// Re-throw as DataSourceConfigError
throw new DataSourceConfigError('Failed to get data source client: ', error);
// Re-throw as DataSourceError
throw createDataSourceError(error);
}
};

Expand All @@ -59,8 +59,8 @@ export const getCredential = async (
const { decryptedText, encryptionContext } = await cryptography
.decodeAndDecrypt(password)
.catch((err: any) => {
// Re-throw as DataSourceConfigError
throw new DataSourceConfigError('Unable to decrypt "auth.credentials.password".', err);
// Re-throw as DataSourceError
throw createDataSourceError(err);
});

if (encryptionContext!.endpoint !== endpoint) {
Expand Down
2 changes: 2 additions & 0 deletions src/plugins/data_source/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,5 @@ export function plugin(initializerContext: PluginInitializerContext) {
}

export { DataSourcePluginSetup, DataSourcePluginStart } from './types';

export { DataSourceError, createDataSourceError } from './lib/error';
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import { CryptographyServiceSetup } from '../cryptography_service';
import { DataSourceClientParams, LegacyClientCallAPIParams } from '../types';
import { OpenSearchClientPoolSetup, getCredential, getDataSource } from '../client';
import { parseClientOptions } from './client_config';
import { DataSourceConfigError } from '../lib/error';
import { createDataSourceError, DataSourceError } from '../lib/error';

export const configureLegacyClient = async (
{ dataSourceId, savedObjects, cryptography }: DataSourceClientParams,
Expand All @@ -40,8 +40,8 @@ export const configureLegacyClient = async (
} catch (error: any) {
logger.error(`Failed to get data source client for dataSourceId: [${dataSourceId}]`);
logger.error(error);
// Re-throw as DataSourceConfigError
throw new DataSourceConfigError('Failed to get data source client: ', error);
// Re-throw as DataSourceError
throw createDataSourceError(error);
}
};

Expand Down Expand Up @@ -140,7 +140,6 @@ const callAPI = async (
if (!options.wrap401Errors || err.statusCode !== 401) {
throw err;
}

throw LegacyOpenSearchErrorHelpers.decorateNotAuthorizedError(err);
}
};
Expand Down
12 changes: 6 additions & 6 deletions src/plugins/data_source/server/lib/error.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,35 +4,35 @@
*/

import { SavedObjectsErrorHelpers } from '../../../../../src/core/server';
import { DataSourceConfigError } from './error';
import { DataSourceError } from './error';

describe('DataSourceConfigError', () => {
describe('DataSourceError', () => {
it('create from savedObject bad request error should be 400 error', () => {
const error = SavedObjectsErrorHelpers.createBadRequestError('test reason message');
expect(new DataSourceConfigError('test prefix: ', error)).toMatchObject({
expect(new DataSourceError('test prefix: ', error)).toMatchObject({
statusCode: 400,
message: 'test prefix: test reason message: Bad Request',
});
});

it('create from savedObject not found error should be 400 error', () => {
const error = SavedObjectsErrorHelpers.decorateNotAuthorizedError(new Error());
expect(new DataSourceConfigError('test prefix: ', error)).toHaveProperty('statusCode', 400);
expect(new DataSourceError('test prefix: ', error)).toHaveProperty('statusCode', 400);
});

it('create from savedObject service unavailable error should be a 500 error', () => {
const error = SavedObjectsErrorHelpers.decorateOpenSearchUnavailableError(
new Error('test reason message')
);
expect(new DataSourceConfigError('test prefix: ', error)).toMatchObject({
expect(new DataSourceError('test prefix: ', error)).toMatchObject({
statusCode: 500,
message: 'test prefix: test reason message',
});
});

it('create from non savedObject error should always be a 400 error', () => {
const error = new Error('test reason message');
expect(new DataSourceConfigError('test prefix: ', error)).toMatchObject({
expect(new DataSourceError('test prefix: ', error)).toMatchObject({
zhongnansu marked this conversation as resolved.
Show resolved Hide resolved
statusCode: 400,
message: 'test prefix: test reason message',
});
Expand Down
59 changes: 48 additions & 11 deletions src/plugins/data_source/server/lib/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,56 @@
* SPDX-License-Identifier: Apache-2.0
*/

import { ResponseError } from '@opensearch-project/opensearch/lib/errors';
import { errors } from 'elasticsearch';
import { SavedObjectsErrorHelpers } from '../../../../../src/core/server';
import { OsdError } from '../../../../../src/plugins/opensearch_dashboards_utils/common';

export class DataSourceConfigError extends OsdError {
import { OsdError } from '../../../opensearch_dashboards_utils/common';
export class DataSourceError extends OsdError {
// must have statusCode to avoid route handler in search.ts to return 500
statusCode: number;
constructor(messagePrefix: string, error: any) {
const messageContent = SavedObjectsErrorHelpers.isSavedObjectsClientError(error)
? error.output.payload.message
: error.message;
super(messagePrefix + messageContent);
// Cast all 5xx error returned by saveObjectClient to 500.
// Cast both savedObject client 4xx errors, and other errors to 400
this.statusCode = SavedObjectsErrorHelpers.isOpenSearchUnavailableError(error) ? 500 : 400;
constructor(error: any, message?: string, statusCode?: number) {
message = message ? message : error.message;
super('Data Source Error: ' + message);
if (statusCode) {
this.statusCode = statusCode;
} else if (error.statusCode) {
this.statusCode = error.statusCode;
} else {
this.statusCode = 400;
}
}
}

export const createDataSourceError = (error: any, message?: string) => {
// handle saved object client error, while retrieve data source meta info
if (SavedObjectsErrorHelpers.isSavedObjectsClientError(error)) {
const statusCode = SavedObjectsErrorHelpers.isOpenSearchUnavailableError(error)
? 500
: error.output.statusCode;
return new DataSourceError(error, error.output.payload.message, statusCode);
}

// cast OpenSearch client 500 response error to 400
// cast OpenSearch client 401 response error to 400, due to https://github.com/opensearch-project/OpenSearch-Dashboards/issues/2591
if (
(isResponseError(error) && error.statusCode === 500) ||
(isResponseError(error) && error.statusCode === 401)
) {
return new DataSourceError(error, JSON.stringify(error.meta.body), 400);
}

// cast legacy client 500, 401 response error to 400
if (
error instanceof errors.AuthenticationException ||
error instanceof errors.InternalServerError
) {
return new DataSourceError(error, error.message, 400);
}

// all other error that may or may not comes with statuscode
return new DataSourceError(error, message);
};

const isResponseError = (error: any): error is ResponseError => {
return Boolean(error.body && error.statusCode && error.headers);
};