Fix all suggestions | working tests

Signed-off-by: David Lilienfeld <davidlilienfeld4@gmail.com>
This commit is contained in:
David Lilienfeld
2025-03-02 22:52:59 -05:00
parent 00d989fd7a
commit bb305509fd
16 changed files with 52 additions and 128 deletions
@@ -30,14 +30,12 @@ yarn --cwd packages/backend add @backstage/plugin-catalog-backend-module-bitbuck
```ts
// optional if you want HTTP endpojnts to receive external events
// backend.add(import('@backstage/plugin-events-backend/alpha'));
// backend.add(import('@backstage/plugin-events-backend'));
// optional if you want to use AWS SQS instead of HTTP endpoints to receive external events
// backend.add(import('@backstage/plugin-events-backend-module-aws-sqs/alpha'));
// backend.add(import('@backstage/plugin-events-backend-module-aws-sqs'));
backend.add(import('@backstage/plugin-events-backend-module-bitbucket-server'));
backend.add(
import('@backstage/plugin-events-backend-module-bitbucket-server/alpha'),
);
backend.add(
import('@backstage/plugin-catalog-backend-module-bitbucket-server/alpha'),
import('@backstage/plugin-catalog-backend-module-bitbucket-server'),
);
```
@@ -59,7 +59,6 @@
"@backstage/plugin-catalog-common": "workspace:^",
"@backstage/plugin-catalog-node": "workspace:^",
"@backstage/plugin-events-node": "workspace:^",
"node-fetch": "^2.7.0",
"p-throttle": "^4.1.1",
"uuid": "^11.0.0"
},
@@ -67,7 +66,6 @@
"@backstage/backend-test-utils": "workspace:^",
"@backstage/cli": "workspace:^",
"@backstage/plugin-events-backend-test-utils": "workspace:^",
"@types/node-fetch": "^2.5.12",
"luxon": "^3.0.0",
"msw": "^1.0.0"
},
@@ -3,11 +3,5 @@
> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).
```ts
import { BackendFeature } from '@backstage/backend-plugin-api';
// @alpha (undocumented)
const _feature: BackendFeature;
export default _feature;
// (No @packageDocumentation comment for this package)
```
@@ -6,7 +6,7 @@
import { AuthService } from '@backstage/backend-plugin-api';
import { BackendFeature } from '@backstage/backend-plugin-api';
import { BitbucketServerIntegrationConfig } from '@backstage/integration';
import { CatalogApi } from '@backstage/catalog-client';
import { CatalogService } from '@backstage/plugin-catalog-node';
import { Config } from '@backstage/config';
import { Entity } from '@backstage/catalog-model';
import { EntityProvider } from '@backstage/plugin-catalog-node';
@@ -77,7 +77,7 @@ export class BitbucketServerEntityProvider implements EntityProvider {
parser?: BitbucketServerLocationParser;
schedule?: SchedulerServiceTaskRunner;
scheduler?: SchedulerService;
catalogApi?: CatalogApi;
catalogApi?: CatalogService;
auth?: AuthService;
},
): BitbucketServerEntityProvider[];
@@ -14,8 +14,4 @@
* limitations under the License.
*/
import { default as feature } from './module';
/** @alpha */
const _feature = feature;
export default _feature;
import {} from './module';
@@ -197,6 +197,7 @@ export type BitbucketServerPagedResponse<T> = {
values: T[];
nextPageStart: number;
};
/**
* @public
*/
@@ -18,10 +18,8 @@ import {
coreServices,
createBackendModule,
} from '@backstage/backend-plugin-api';
import {
catalogProcessingExtensionPoint,
catalogServiceRef,
} from '@backstage/plugin-catalog-node/alpha';
import { catalogServiceRef } from '@backstage/plugin-catalog-node';
import { catalogProcessingExtensionPoint } from '@backstage/plugin-catalog-node/alpha';
import { eventsServiceRef } from '@backstage/plugin-events-node';
import { BitbucketServerEntityProvider } from '../providers/BitbucketServerEntityProvider';
@@ -18,7 +18,7 @@ import {
SchedulerService,
SchedulerServiceTaskRunner,
SchedulerServiceTaskInvocationDefinition,
AuthService,
BackstageCredentials,
} from '@backstage/backend-plugin-api';
import {
mockServices,
@@ -26,6 +26,7 @@ import {
} from '@backstage/backend-test-utils';
import { ConfigReader } from '@backstage/config';
import {
CatalogService,
DeferredEntity,
EntityProviderConnection,
locationSpecToLocationEntity,
@@ -39,8 +40,8 @@ import {
import { BitbucketServerPagedResponse } from '../lib';
import { Entity, LocationEntity } from '@backstage/catalog-model';
import { BitbucketServerEvents } from '../lib/index';
import { CatalogApi } from '@backstage/catalog-client';
import { DefaultEventsService } from '@backstage/plugin-events-node';
import { catalogServiceMock } from '@backstage/plugin-catalog-node/testUtils';
class PersistingTaskRunner implements SchedulerServiceTaskRunner {
private tasks: SchedulerServiceTaskInvocationDefinition[] = [];
@@ -163,11 +164,6 @@ function setupRepositoryReqHandler(defaultBranch: string) {
);
}
// const authService = {
// getPluginRequestToken: async ({onBehalfOf, targetPluginId}) => {
// return { token: 'fake-token' };
// },
// } as any as AuthService;
const repoPushEvent: BitbucketServerEvents.RefsChangedEvent = {
eventKey: 'repo:refs_changed',
date: '2017-09-19T09:45:32+1000',
@@ -771,9 +767,7 @@ describe('BitbucketServerEntityProvider', () => {
setupRepositoryReqHandler('master');
authService.getPluginRequestToken.mockResolvedValue({
token: 'fake-token',
});
// authService.getOwnServiceCredentials();
const config = new ConfigReader({
integrations: {
@@ -797,13 +791,14 @@ describe('BitbucketServerEntityProvider', () => {
},
});
const catalogApi = {
const catalogApi = catalogServiceMock.mock({
getEntities: async (
request: { filter: Record<string, string> },
options: { token: string },
credentials: { credentials: BackstageCredentials },
): Promise<{ items: Entity[] }> => {
if (
options.token !== 'fake-token' ||
credentials.credentials !==
(await authService.getOwnServiceCredentials()) ||
request.filter.kind !== 'Location' ||
request.filter[`metadata.annotations.${host}/repo-url`] !==
`${test1RepoUrl}/kept-module:${targetPath}`
@@ -814,14 +809,14 @@ describe('BitbucketServerEntityProvider', () => {
items: [keptModule],
};
},
};
});
const provider = BitbucketServerEntityProvider.fromConfig(config, {
catalogApi: catalogApi as any as CatalogApi,
catalogApi: catalogApi,
logger,
schedule,
events,
auth: authService as any as AuthService,
auth: authService,
})[0];
await provider.connect(entityProviderConnection);
@@ -869,13 +864,14 @@ describe('BitbucketServerEntityProvider', () => {
},
});
const catalogApi = {
const catalogApi = catalogServiceMock.mock({
getEntities: async (
request: { filter: Record<string, string> },
options: { token: string },
credentials: { credentials: BackstageCredentials },
): Promise<{ items: Entity[] }> => {
if (
options.token !== 'fake-token' ||
credentials.credentials !==
(await authService.getOwnServiceCredentials()) ||
request.filter.kind !== 'Location' ||
request.filter[`metadata.annotations.${host}/repo-url`] !==
`${test1RepoUrl}/kept-module:${targetPath}`
@@ -886,13 +882,14 @@ describe('BitbucketServerEntityProvider', () => {
items: [keptModule],
};
},
};
});
const provider = BitbucketServerEntityProvider.fromConfig(config, {
catalogApi: catalogApi as any as CatalogApi,
catalogApi: catalogApi,
logger,
schedule,
events,
auth: authService as any as AuthService,
auth: authService,
})[0];
await provider.connect(entityProviderConnection);
@@ -940,22 +937,13 @@ describe('BitbucketServerEntityProvider', () => {
},
});
const catalogApi = {
getEntities: async (
_request: { filter: Record<string, string> },
_options: { token: string },
): Promise<{ items: Entity[] }> => {
return {
items: [],
};
},
};
const catalogApi = catalogServiceMock({ entities: [] });
const provider = BitbucketServerEntityProvider.fromConfig(config, {
catalogApi: catalogApi as any as CatalogApi,
catalogApi: catalogApi,
logger,
schedule,
events,
auth: authService as any as AuthService,
auth: authService,
})[0];
await provider.connect(entityProviderConnection);
@@ -1010,22 +998,13 @@ describe('BitbucketServerEntityProvider', () => {
},
});
const catalogApi = {
getEntities: async (
_request: { filter: Record<string, string> },
_options: { token: string },
): Promise<{ items: Entity[] }> => {
return {
items: [],
};
},
};
const catalogApi = catalogServiceMock({ entities: [] });
const provider = BitbucketServerEntityProvider.fromConfig(config, {
catalogApi: catalogApi as any as CatalogApi,
catalogApi: catalogApi as any as CatalogService,
logger,
schedule,
events,
auth: authService as any as AuthService,
auth: authService,
})[0];
await provider.connect(entityProviderConnection);
@@ -25,6 +25,7 @@ import {
EntityProvider,
EntityProviderConnection,
DeferredEntity,
CatalogService,
} from '@backstage/plugin-catalog-node';
import * as uuid from 'uuid';
import { BitbucketServerClient, paginated } from '../lib';
@@ -38,13 +39,13 @@ import {
} from './BitbucketServerLocationParser';
import {
AuthService,
BackstageCredentials,
LoggerService,
SchedulerService,
SchedulerServiceTaskRunner,
} from '@backstage/backend-plugin-api';
import { BitbucketServerEvents } from '../lib';
import { EventsService } from '@backstage/plugin-events-node';
import { CatalogApi } from '@backstage/catalog-client';
const TOPIC_REPO_REFS_CHANGED = 'bitbucketServer.repo:refs_changed';
@@ -63,7 +64,7 @@ export class BitbucketServerEntityProvider implements EntityProvider {
private readonly logger: LoggerService;
private readonly scheduleFn: () => Promise<void>;
private connection?: EntityProviderConnection;
private readonly catalogApi?: CatalogApi;
private readonly catalogApi?: CatalogService;
private readonly events?: EventsService;
private readonly auth?: AuthService;
private eventConfigErrorThrown = false;
@@ -78,7 +79,7 @@ export class BitbucketServerEntityProvider implements EntityProvider {
parser?: BitbucketServerLocationParser;
schedule?: SchedulerServiceTaskRunner;
scheduler?: SchedulerService;
catalogApi?: CatalogApi;
catalogApi?: CatalogService;
auth?: AuthService;
},
): BitbucketServerEntityProvider[] {
@@ -127,7 +128,7 @@ export class BitbucketServerEntityProvider implements EntityProvider {
logger: LoggerService,
taskRunner: SchedulerServiceTaskRunner,
parser?: BitbucketServerLocationParser,
catalogApi?: CatalogApi,
catalogApi?: CatalogService,
events?: EventsService,
auth?: AuthService,
) {
@@ -294,19 +295,14 @@ export class BitbucketServerEntityProvider implements EntityProvider {
* @returns Boolean
*/
private canHandleEvents(): boolean {
if (
this.catalogApi !== undefined &&
this.catalogApi !== null &&
this.auth !== undefined &&
this.auth !== null
) {
if (this.catalogApi && this.auth) {
return true;
}
if (!this.eventConfigErrorThrown) {
this.eventConfigErrorThrown = true;
throw new Error(
`${this.getProviderName()} not well configured to handle repo:push. Missing CatalogApi and/or TokenManager.`,
`${this.getProviderName()} not well configured to handle repo:push. Missing CatalogApi and/or AuthService.`,
);
}
@@ -387,11 +383,10 @@ export class BitbucketServerEntityProvider implements EntityProvider {
this.logger.error('Failed to create location entity.');
return;
}
const { token } = await this.auth!.getPluginRequestToken({
onBehalfOf: await this.auth!.getOwnServiceCredentials(),
targetPluginId: 'catalog', // e.g. 'catalog'
});
const existing = await this.findExistingLocations(catalogRepoUrl, token);
const existing = await this.findExistingLocations(
catalogRepoUrl,
await this.auth!.getOwnServiceCredentials(),
);
const stillExisting: LocationEntity[] = [];
const removed: DeferredEntity[] = [];
existing.forEach(item => {
@@ -486,13 +481,13 @@ export class BitbucketServerEntityProvider implements EntityProvider {
private async findExistingLocations(
catalogRepoUrl: string,
token: string,
credentials: BackstageCredentials,
): Promise<LocationEntity[]> {
const filter: Record<string, string> = {};
filter.kind = 'Location';
filter[`metadata.annotations.${this.targetAnnotation}`] = catalogRepoUrl;
return this.catalogApi!.getEntities({ filter }, { token }).then(
return this.catalogApi!.getEntities({ filter }, { credentials }).then(
result => result.items,
) as Promise<LocationEntity[]>;
}
@@ -32,17 +32,5 @@ yarn add --cwd packages/backend @backstage/plugin-events-backend-module-bitbucke
```ts
// packages/backend/src/index.ts
backend.add(
import('@backstage/plugin-events-backend-module-bitbucket-server/alpha'),
);
```
### Legacy Backend System
```ts
// packages/backend/src/plugins/events.ts
const eventRouter = new BitbucketCloudEventRouter({
events: env.events,
});
await eventRouter.subscribe();
backend.add(import('@backstage/plugin-events-backend-module-bitbucket-server'));
```
@@ -1,6 +1,6 @@
{
"name": "@backstage/plugin-events-backend-module-bitbucket-server",
"version": "0.1.0",
"version": "0.0.0",
"backstage": {
"role": "backend-plugin-module",
"pluginId": "events",
@@ -3,12 +3,5 @@
> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).
```ts
import { BackendFeature } from '@backstage/backend-plugin-api';
// @public
const eventsModuleBitbucketServerEventRouter: BackendFeature;
export default eventsModuleBitbucketServerEventRouter;
export { eventsModuleBitbucketServerEventRouter };
// (No @packageDocumentation comment for this package)
```
@@ -4,18 +4,6 @@
```ts
import { BackendFeature } from '@backstage/backend-plugin-api';
import { EventParams } from '@backstage/plugin-events-node';
import { EventsService } from '@backstage/plugin-events-node';
import { SubTopicEventRouter } from '@backstage/plugin-events-node';
// @public
export class BitbucketServerEventRouter extends SubTopicEventRouter {
constructor(options: { events: EventsService });
// (undocumented)
protected determineSubTopic(params: EventParams): string | undefined;
// (undocumented)
protected getSubscriberId(): string;
}
// @public
const eventsModuleBitbucketServerEventRouter: BackendFeature;
@@ -14,5 +14,4 @@
* limitations under the License.
*/
export { eventsModuleBitbucketServerEventRouter } from './service/eventsModuleBitbucketServerEventRouter';
export { eventsModuleBitbucketServerEventRouter as default } from './service/eventsModuleBitbucketServerEventRouter';
import {} from './service/eventsModuleBitbucketServerEventRouter';
@@ -21,6 +21,5 @@
* @packageDocumentation
*/
export { BitbucketServerEventRouter } from './router/BitbucketServerEventRouter';
export { eventsModuleBitbucketServerEventRouter } from './service/eventsModuleBitbucketServerEventRouter';
export { eventsModuleBitbucketServerEventRouter as default } from './service/eventsModuleBitbucketServerEventRouter';
+1 -3
View File
@@ -5749,10 +5749,8 @@ __metadata:
"@backstage/plugin-catalog-node": "workspace:^"
"@backstage/plugin-events-backend-test-utils": "workspace:^"
"@backstage/plugin-events-node": "workspace:^"
"@types/node-fetch": ^2.5.12
luxon: ^3.0.0
msw: ^1.0.0
node-fetch: ^2.7.0
p-throttle: ^4.1.1
uuid: ^11.0.0
languageName: unknown
@@ -20110,7 +20108,7 @@ __metadata:
languageName: node
linkType: hard
"@types/node-fetch@npm:^2.5.12, @types/node-fetch@npm:^2.6.4, @types/node-fetch@npm:^2.6.9":
"@types/node-fetch@npm:^2.6.4, @types/node-fetch@npm:^2.6.9":
version: 2.6.12
resolution: "@types/node-fetch@npm:2.6.12"
dependencies: