backend-app-api: add support for discoverying additional service factories

Co-authored-by: Fredrik Adelöw <freben@gmail.com>
Co-authored-by: Johan Haals <johan.haals@gmail.com>
Co-authored-by: Philipp Hugenroth <philipph@spotify.com>
Co-authored-by: Camila Belo <camilaibs@gmail.com>
Signed-off-by: Patrik Oldsberg <poldsberg@gmail.com>
This commit is contained in:
Patrik Oldsberg
2023-09-06 13:30:34 +02:00
parent 19c2e46fc5
commit 154632d875
5 changed files with 75 additions and 46 deletions
+5
View File
@@ -0,0 +1,5 @@
---
'@backstage/backend-app-api': patch
---
Add support for discovering additional service factories during startup.
@@ -23,7 +23,7 @@ import {
} from '@backstage/backend-plugin-api';
import { BackendLifecycleImpl } from '../services/implementations/rootLifecycle/rootLifecycleServiceFactory';
import { BackendPluginLifecycleImpl } from '../services/implementations/lifecycle/lifecycleServiceFactory';
import { EnumerableServiceHolder, ServiceOrExtensionPoint } from './types';
import { ServiceOrExtensionPoint } from './types';
// Direct internal import to avoid duplication
// eslint-disable-next-line @backstage/no-forbidden-package-imports
import { InternalBackendFeature } from '@backstage/backend-plugin-api/src/wiring/types';
@@ -45,12 +45,10 @@ export class BackendInitializer {
#startPromise?: Promise<void>;
#features = new Array<InternalBackendFeature>();
#extensionPoints = new Map<string, { impl: unknown; pluginId: string }>();
#serviceHolder: EnumerableServiceHolder | undefined;
#providedServiceFactories = new Array<ServiceFactory>();
#defaultApiFactories: ServiceFactory[];
#serviceRegistry: ServiceRegistry;
constructor(defaultApiFactories: ServiceFactory[]) {
this.#defaultApiFactories = defaultApiFactories;
this.#serviceRegistry = ServiceRegistry.create([...defaultApiFactories]);
}
async #getInitDeps(
@@ -70,7 +68,7 @@ export class BackendInitializer {
}
result.set(name, ep.impl);
} else {
const impl = await this.#serviceHolder!.get(
const impl = await this.#serviceRegistry.get(
ref as ServiceRef<unknown>,
pluginId,
);
@@ -107,21 +105,7 @@ export class BackendInitializer {
}
if (isServiceFactory(feature)) {
if (feature.service.id === coreServices.pluginMetadata.id) {
throw new Error(
`The ${coreServices.pluginMetadata.id} service cannot be overridden`,
);
}
if (
this.#providedServiceFactories.find(
sf => sf.service.id === feature.service.id,
)
) {
throw new Error(
`Duplicate service implementations provided for ${feature.service.id}`,
);
}
this.#providedServiceFactories.push(feature);
this.#serviceRegistry.add(feature);
} else if (isInternalBackendFeature(feature)) {
if (feature.version !== 'v1') {
throw new Error(
@@ -164,12 +148,9 @@ export class BackendInitializer {
}
async #doStart(): Promise<void> {
this.#serviceHolder = ServiceRegistry.create([
...this.#defaultApiFactories,
...this.#providedServiceFactories,
]);
this.#serviceRegistry.checkForCircularDeps();
const featureDiscovery = await this.#serviceHolder.get(
const featureDiscovery = await this.#serviceRegistry.get(
featureDiscoveryServiceRef,
'root',
);
@@ -179,12 +160,13 @@ export class BackendInitializer {
for (const feature of features) {
this.#addFeature(feature);
}
this.#serviceRegistry.checkForCircularDeps();
}
// Initialize all root scoped services
for (const ref of this.#serviceHolder.getServiceRefs()) {
for (const ref of this.#serviceRegistry.getServiceRefs()) {
if (ref.scope === 'root') {
await this.#serviceHolder.get(ref, 'root');
await this.#serviceRegistry.get(ref, 'root');
}
}
@@ -313,7 +295,7 @@ export class BackendInitializer {
// Once the backend is started, any uncaught errors or unhandled rejections are caught
// and logged, in order to avoid crashing the entire backend on local failures.
if (process.env.NODE_ENV !== 'test') {
const rootLogger = await this.#serviceHolder.get(
const rootLogger = await this.#serviceRegistry.get(
coreServices.rootLogger,
'root',
);
@@ -347,7 +329,7 @@ export class BackendInitializer {
// Bit of a hacky way to grab the lifecycle services, potentially find a nicer way to do this
async #getRootLifecycleImpl(): Promise<BackendLifecycleImpl> {
const lifecycleService = await this.#serviceHolder!.get(
const lifecycleService = await this.#serviceRegistry.get(
coreServices.rootLifecycle,
'root',
);
@@ -360,7 +342,7 @@ export class BackendInitializer {
async #getPluginLifecycleImpl(
pluginId: string,
): Promise<BackendPluginLifecycleImpl> {
const lifecycleService = await this.#serviceHolder!.get(
const lifecycleService = await this.#serviceRegistry.get(
coreServices.lifecycle,
pluginId,
);
@@ -188,6 +188,32 @@ describe('ServiceRegistry', () => {
});
});
it('should use added service factories for each ref', async () => {
const registry = ServiceRegistry.create([sf2()]);
registry.add(sf2b());
await expect(registry.get(ref2, 'catalog')).resolves.toEqual({
x: 22,
});
});
it('should not allow factories to be added after instantiation', async () => {
const registry = ServiceRegistry.create([sf2()]);
await expect(registry.get(ref2, 'catalog')).resolves.toEqual({
x: 2,
});
expect(() => registry.add(sf2b())).toThrow(
'Unable to set service factory with id 2, service has already been instantiated',
);
});
it('should not allow the same factory to be added twice', async () => {
const registry = ServiceRegistry.create([sf2()]);
registry.add(sf2b());
expect(() => registry.add(sf2b())).toThrow(
'Duplicate service implementations provided for 2',
);
});
it('should use the defaultFactory from the ref if not provided to the registry', async () => {
const registry = ServiceRegistry.create([]);
await expect(registry.get(refDefault1, 'catalog')).resolves.toEqual({
@@ -21,7 +21,6 @@ import {
createServiceFactory,
} from '@backstage/backend-plugin-api';
import { ConflictError, stringifyError } from '@backstage/errors';
import { EnumerableServiceHolder } from './types';
// Direct internal import to avoid duplication
// eslint-disable-next-line @backstage/no-forbidden-package-imports
import { InternalServiceFactory } from '@backstage/backend-plugin-api/src/services/system/types';
@@ -57,10 +56,10 @@ const pluginMetadataServiceFactory = createServiceFactory(
}),
);
export class ServiceRegistry implements EnumerableServiceHolder {
export class ServiceRegistry {
static create(factories: Array<ServiceFactory>): ServiceRegistry {
const registry = new ServiceRegistry(factories);
registry.#checkForCircularDeps();
registry.checkForCircularDeps();
return registry;
}
@@ -80,6 +79,8 @@ export class ServiceRegistry implements EnumerableServiceHolder {
InternalServiceFactory,
Promise<unknown>
>();
readonly #addedFactoryIds = new Set<string>();
readonly #instantiatedFactories = new Set<string>();
private constructor(factories: Array<ServiceFactory>) {
this.#providedFactories = new Map(
@@ -153,7 +154,7 @@ export class ServiceRegistry implements EnumerableServiceHolder {
}
}
#checkForCircularDeps(): void {
checkForCircularDeps(): void {
const graph = DependencyGraph.fromIterable(
Array.from(this.#providedFactories).map(
([serviceId, serviceFactory]) => ({
@@ -174,11 +175,37 @@ export class ServiceRegistry implements EnumerableServiceHolder {
}
}
add(factory: ServiceFactory) {
const factoryId = factory.service.id;
if (factoryId === coreServices.pluginMetadata.id) {
throw new Error(
`The ${coreServices.pluginMetadata.id} service cannot be overridden`,
);
}
if (this.#addedFactoryIds.has(factoryId)) {
throw new Error(
`Duplicate service implementations provided for ${factoryId}`,
);
}
if (this.#instantiatedFactories.has(factoryId)) {
throw new Error(
`Unable to set service factory with id ${factoryId}, service has already been instantiated`,
);
}
this.#addedFactoryIds.add(factoryId);
this.#providedFactories.set(factoryId, toInternalServiceFactory(factory));
}
getServiceRefs(): ServiceRef<unknown>[] {
return Array.from(this.#providedFactories.values()).map(f => f.service);
}
get<T>(ref: ServiceRef<T>, pluginId: string): Promise<T> | undefined {
this.#instantiatedFactories.add(ref.id);
return this.#resolveFactory(ref, pluginId)?.then(factory => {
if (factory.service.scope === 'root') {
let existing = this.#rootServiceImplementations.get(factory);
@@ -37,17 +37,6 @@ export interface CreateSpecializedBackendOptions {
defaultServiceFactories: ServiceFactoryOrFunction[];
}
export interface ServiceHolder {
get<T>(api: ServiceRef<T>, pluginId: string): Promise<T> | undefined;
}
/**
* @internal
*/
export interface EnumerableServiceHolder extends ServiceHolder {
getServiceRefs(): ServiceRef<unknown>[];
}
/**
* @public
*/