Merge pull request #23346 from drodil/migrate_local_dev

chore: migrate to new backend in local development
This commit is contained in:
Patrik Oldsberg
2024-04-14 13:49:28 +02:00
committed by GitHub
20 changed files with 295 additions and 342 deletions
-32
View File
@@ -1,32 +0,0 @@
/*
* Copyright 2023 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { getRootLogger } from '@backstage/backend-common';
import yn from 'yn';
import { startStandaloneServer } from './service/standaloneServer';
const port = process.env.PLUGIN_PORT ? Number(process.env.PLUGIN_PORT) : 7007;
const enableCors = yn(process.env.PLUGIN_CORS, { default: false });
const logger = getRootLogger();
startStandaloneServer({ port, enableCors, logger }).catch(err => {
logger.error(err);
process.exit(1);
});
process.on('SIGINT', () => {
logger.info('CTRL+C pressed; exiting.');
process.exit(0);
});
@@ -458,7 +458,7 @@ export async function createRouter(
if (!recipients || !title) {
logger.error(`Invalid notification request received`);
throw new InputError();
throw new InputError(`Invalid notification request received`);
}
const origin = credentials.principal.subject;
@@ -484,8 +484,10 @@ export async function createRouter(
try {
users = await getUsersForEntityRef(entityRef);
} catch (e) {
throw new InputError();
logger.error(`Failed to resolve notification receivers: ${e}`);
throw new InputError('Failed to resolve notification receivers', e);
}
const userNotifications = await sendUserNotifications(
baseNotification,
users,
@@ -1,150 +0,0 @@
/*
* Copyright 2023 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
createLegacyAuthAdapters,
createServiceBuilder,
HostDiscovery,
loadBackendConfig,
PluginDatabaseManager,
ServerTokenManager,
} from '@backstage/backend-common';
import { Server } from 'http';
import { Logger } from 'winston';
import { createRouter } from './router';
import Knex from 'knex';
import { IdentityApi } from '@backstage/plugin-auth-node';
import { Request } from 'express';
import {
CatalogApi,
CatalogRequestOptions,
GetEntitiesByRefsRequest,
} from '@backstage/catalog-client';
import { DefaultSignalsService } from '@backstage/plugin-signals-node';
import {
EventParams,
EventsService,
EventsServiceSubscribeOptions,
} from '@backstage/plugin-events-node';
import {
AuthService,
HttpAuthService,
UserInfoService,
} from '@backstage/backend-plugin-api';
export interface ServerOptions {
port: number;
enableCors: boolean;
logger: Logger;
}
export async function startStandaloneServer(
options: ServerOptions,
): Promise<Server> {
const logger = options.logger.child({ service: 'notifications-backend' });
logger.debug('Starting application server...');
const config = await loadBackendConfig({ logger, argv: process.argv });
const db = Knex(config.get('backend.database'));
const tokenManager = ServerTokenManager.fromConfig(config, {
logger,
});
const discovery = HostDiscovery.fromConfig(config);
const dbMock: PluginDatabaseManager = {
async getClient() {
return db;
},
};
const catalogApi = {
async getEntitiesByRefs(
_request: GetEntitiesByRefsRequest,
__options?: CatalogRequestOptions,
) {
return {
items: [
{
apiVersion: 'backstage.io/v1alpha1',
kind: 'User',
metadata: { name: 'user', namespace: 'default' },
spec: {},
},
],
};
},
} as Partial<CatalogApi> as CatalogApi;
const identityMock: IdentityApi = {
async getIdentity({ request }: { request: Request<unknown> }) {
const token = request.headers.authorization?.split(' ')[1];
return {
identity: {
type: 'user',
ownershipEntityRefs: [],
userEntityRef: 'user:default/guest',
},
token: token || 'no-token',
};
},
};
const mockSubscribers: EventsServiceSubscribeOptions[] = [];
const events: EventsService = {
async publish(params: EventParams): Promise<void> {
mockSubscribers.forEach(sub => sub.onEvent(params));
},
async subscribe(subscription: EventsServiceSubscribeOptions) {
mockSubscribers.push(subscription);
},
};
const signalService = DefaultSignalsService.create({ events });
// TODO: Move to use services instead this hack
const { auth, httpAuth, userInfo } = createLegacyAuthAdapters<
any,
{ auth: AuthService; httpAuth: HttpAuthService; userInfo: UserInfoService }
>({
identity: identityMock,
tokenManager,
discovery,
});
const router = await createRouter({
logger,
database: dbMock,
catalog: catalogApi,
discovery,
signals: signalService,
auth,
httpAuth,
userInfo,
});
let service = createServiceBuilder(module)
.setPort(options.port)
.addRouter('/notifications', router);
if (options.enableCors) {
service = service.enableCors({ origin: 'http://localhost:3000' });
}
return await service.start().catch(err => {
logger.error(err);
process.exit(1);
});
}
module.hot?.accept();