Skip to content

Commit

Permalink
chore: remove own backstage/backend-common dependency (#153)
Browse files Browse the repository at this point in the history
  • Loading branch information
Kirdock authored Nov 7, 2024
1 parent 79fa4ea commit 01889f8
Show file tree
Hide file tree
Showing 11 changed files with 48 additions and 124 deletions.
1 change: 0 additions & 1 deletion packages/backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
"build-image": "docker build ../.. -f Dockerfile --tag backstage"
},
"dependencies": {
"@backstage/backend-common": "^0.23.2",
"@backstage/backend-defaults": "^0.4.0",
"@backstage/backend-plugin-api": "^0.7.0",
"@backstage/backend-tasks": "^0.5.23",
Expand Down
3 changes: 1 addition & 2 deletions plugins/dql-backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,13 @@
"postpack": "backstage-cli package postpack"
},
"dependencies": {
"@backstage/backend-common": "^0.23.0",
"@backstage/config": "^1.2.0",
"@dynatrace/backstage-plugin-dql-common": "^0.1.0",
"@types/express": "*",
"express": "^4.17.1",
"express-promise-router": "^4.1.0",
"node-fetch": "^2.6.7",
"https-proxy-agent": "7.0.5",
"node-fetch": "^2.6.7",
"winston": "^3.2.1",
"yn": "^4.0.0",
"zod": "^3.22.4"
Expand Down
32 changes: 0 additions & 32 deletions plugins/dql-backend/src/run.ts

This file was deleted.

5 changes: 4 additions & 1 deletion plugins/dql-backend/src/service/dynatraceApi.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
PollQueryResponse,
TokenResponse,
} from './dynatraceApi';
import { createLogger } from 'winston';

jest.mock('../utils', () => ({ dtFetch: jest.fn() }));

Expand Down Expand Up @@ -58,10 +59,12 @@ describe('dynatraceApi', () => {
name: 'myEnv',
accountUrn: 'urn',
};
const dynatraceApi = new DynatraceApi(defaultApiConfig, 'identifier');
const logger = createLogger();
const dynatraceApi = new DynatraceApi(defaultApiConfig, 'identifier', logger);
const trailingSlashApi = new DynatraceApi(
{ ...defaultApiConfig, url: 'https://example.com/' },
'identifier',
logger,
);

const mockTokenResult = (result: MockResult<TokenResponse>) =>
Expand Down
22 changes: 17 additions & 5 deletions plugins/dql-backend/src/service/dynatraceApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
* limitations under the License.
*/
import { dtFetch } from '../utils';
import { getRootLogger } from '@backstage/backend-common';
import { LoggerService } from '@backstage/backend-plugin-api';
import { TabularData } from '@dynatrace/backstage-plugin-dql-common';

export type DynatraceEnvironmentConfig = {
Expand Down Expand Up @@ -59,7 +59,6 @@ export type PollQueryResponse<RecordType> = {
};
};

const logger = getRootLogger().child({ plugin: 'dql-backend' });
const DEFAULT_TOKEN_URL = 'https://sso.dynatrace.com/sso/oauth2/token';

const executeQuery = async (
Expand All @@ -84,6 +83,7 @@ const executeQuery = async (
const pollQuery = async <T>(
{ url, accessToken, identifier }: DynatraceAccessInfo,
requestToken: string,
logger: LoggerService,
): Promise<PollQueryResponse<T>> => {
const fullUrl = new URL('platform/storage/query/v1/query:poll', url);
fullUrl.searchParams.set('request-token', requestToken);
Expand All @@ -105,20 +105,23 @@ const pollQuery = async <T>(
const waitForQueryResult = async <RecordType>(
accessInfo: DynatraceAccessInfo,
requestToken: string,
logger: LoggerService,
): Promise<RecordType[]> => {
let pollQueryRes: PollQueryResponse<RecordType> = await pollQuery(
accessInfo,
requestToken,
logger,
);
while (pollQueryRes.state !== 'SUCCEEDED') {
pollQueryRes = await pollQuery(accessInfo, requestToken);
pollQueryRes = await pollQuery(accessInfo, requestToken, logger);
}
return pollQueryRes.result.records;
};

const getAccessToken = async (
config: DynatraceEnvironmentConfig,
identifier: string,
logger: LoggerService,
): Promise<TokenResponse> => {
const body = new URLSearchParams({
grant_type: 'client_credentials',
Expand Down Expand Up @@ -152,6 +155,7 @@ export class DynatraceApi {
constructor(
private readonly config: DynatraceEnvironmentConfig,
private identifier: string,
private logger: LoggerService,
) {}

get environmentName() {
Expand All @@ -163,14 +167,22 @@ export class DynatraceApi {
}

async executeDqlQuery(query: string): Promise<TabularData> {
const tokenResponse = await getAccessToken(this.config, this.identifier);
const tokenResponse = await getAccessToken(
this.config,
this.identifier,
this.logger,
);
const environment: DynatraceAccessInfo = {
url: this.config.url,
accessToken: tokenResponse.access_token,
identifier: this.identifier,
};

const execQueryRes = await executeQuery(environment, query);
return await waitForQueryResult(environment, execQueryRes.requestToken);
return await waitForQueryResult(
environment,
execQueryRes.requestToken,
this.logger,
);
}
}
4 changes: 2 additions & 2 deletions plugins/dql-backend/src/service/router.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,16 @@
* limitations under the License.
*/
import { RouterOptions, createRouter } from './router';
import { getVoidLogger } from '@backstage/backend-common';
import { MockConfigApi } from '@backstage/test-utils';
import express from 'express';
import { createLogger } from 'winston';

describe('createRouter', () => {
let app: express.Express;

beforeAll(async () => {
const router = await createRouter({
logger: getVoidLogger(),
logger: createLogger(),
discovery: {
async getBaseUrl(): Promise<string> {
return '';
Expand Down
23 changes: 7 additions & 16 deletions plugins/dql-backend/src/service/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,8 @@
import { parseCustomQueries, parseEnvironments } from '../utils/configParser';
import { getEntityFromRequest, validateQueries } from '../utils/routeUtils';
import { QueryExecutor } from './queryExecutor';
import {
createLegacyAuthAdapters,
errorHandler,
} from '@backstage/backend-common';
import { PluginEndpointDiscovery } from '@backstage/backend-common';
import { MiddlewareFactory } from '@backstage/backend-defaults/rootHttpRouter';
import { DiscoveryService } from '@backstage/backend-plugin-api';
import { LoggerService, AuthService } from '@backstage/backend-plugin-api';
import { CatalogClient } from '@backstage/catalog-client';
import { Config } from '@backstage/config';
Expand All @@ -31,22 +28,16 @@ import Router from 'express-promise-router';
export interface RouterOptions {
logger: LoggerService;
config: Config;
discovery: PluginEndpointDiscovery;
auth?: AuthService;
discovery: DiscoveryService;
auth: AuthService;
}

export const createRouter = async (
options: RouterOptions,
): Promise<express.Router> => {
// In order to make the new auth services available to the plugin
// implementation in a backwards compatible way, we use the
// createLegacyAuthAdapters helper from @backstage/backend-common.
// Ref: https://backstage.io/docs/tutorials/auth-service-migration/#making-the-new-auth-services-available-in-createrouter
const { auth } = createLegacyAuthAdapters(options);
const { config, discovery, logger, auth } = options;

const { config, discovery } = options;

const apis = parseEnvironments(config);
const apis = parseEnvironments(config, logger);
const customQueries = parseCustomQueries(config);
const queryExecutor = new QueryExecutor(apis, customQueries);
const catalogClient = new CatalogClient({ discoveryApi: discovery });
Expand Down Expand Up @@ -86,6 +77,6 @@ export const createRouter = async (
res.json(deployments);
});

router.use(errorHandler());
router.use(MiddlewareFactory.create({ logger, config }).error());
return router;
};
59 changes: 0 additions & 59 deletions plugins/dql-backend/src/service/standaloneServer.ts

This file was deleted.

9 changes: 6 additions & 3 deletions plugins/dql-backend/src/utils/configParser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*/
import { parseCustomQueries, parseEnvironments } from './configParser';
import { MockConfigApi } from '@backstage/test-utils';
import { createLogger } from 'winston';

const TEST_ENVIRONMENT = {
name: 'test',
Expand All @@ -25,13 +26,15 @@ const TEST_ENVIRONMENT = {
accountUrn: 'test',
};

const logger = createLogger();

describe('config-parser', () => {
describe('parseEnvironments', () => {
it('should return a list of DynatraceApis with the corresponding config', () => {
const config = new MockConfigApi({
dynatrace: { environments: [TEST_ENVIRONMENT] },
});
const result = parseEnvironments(config);
const result = parseEnvironments(config, logger);

expect(result).toHaveLength(1);
const api = result[0];
Expand All @@ -46,7 +49,7 @@ describe('config-parser', () => {
environments: [{ ...TEST_ENVIRONMENT, url: 'https://example' }],
},
});
const result = parseEnvironments(config);
const result = parseEnvironments(config, logger);
const api = result[0];
expect(Reflect.get(api, 'identifier')).toEqual(btoa('unknown'));
});
Expand All @@ -55,7 +58,7 @@ describe('config-parser', () => {
const config = new MockConfigApi({
dynatrace: { environments: [{ ...TEST_ENVIRONMENT, url: '' }] },
});
const result = parseEnvironments(config);
const result = parseEnvironments(config, logger);
const api = result[0];
expect(Reflect.get(api, 'identifier')).toEqual(btoa('unknown'));
});
Expand Down
12 changes: 10 additions & 2 deletions plugins/dql-backend/src/utils/configParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
* limitations under the License.
*/
import { DynatraceApi, DynatraceEnvironmentConfig } from '../service';
import { LoggerService } from '@backstage/backend-plugin-api';
import { Config } from '@backstage/config';

const defaultId = 'unknown';
Expand All @@ -35,13 +36,20 @@ const getIdentifier = (configArray: Config[]) => {
);
};

export const parseEnvironments = (config: Config): DynatraceApi[] => {
export const parseEnvironments = (
config: Config,
logger: LoggerService,
): DynatraceApi[] => {
const configArray = config.getConfigArray('dynatrace.environments');

const identifier = getIdentifier(configArray);
return configArray.map(
envConfig =>
new DynatraceApi(envConfig.get<DynatraceEnvironmentConfig>(), identifier),
new DynatraceApi(
envConfig.get<DynatraceEnvironmentConfig>(),
identifier,
logger,
),
);
};

Expand Down
2 changes: 1 addition & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2665,7 +2665,7 @@
winston "^3.2.1"
winston-transport "^4.5.0"

"@backstage/backend-common@^0.23.0", "@backstage/backend-common@^0.23.2", "@backstage/backend-common@^0.23.3":
"@backstage/backend-common@^0.23.3":
version "0.23.3"
resolved "https://registry.yarnpkg.com/@backstage/backend-common/-/backend-common-0.23.3.tgz#bba71a3f932a88481ab8e09f4406fc551fb47aec"
integrity sha512-/OZRnxlNokdMfoQEfDRrjIuojPi6UL80smHuNpcvP/93fXkrYiMwISulDQPxCfm1Rm9JW8mnRORGFihKIALNpQ==
Expand Down

0 comments on commit 01889f8

Please sign in to comment.