@backstage/backend-defaults
Version:
Backend defaults used by Backstage backend apps
106 lines (102 loc) • 2.98 kB
JavaScript
;
var backendPluginApi = require('@backstage/backend-plugin-api');
class BackendLifecycleImpl {
constructor(logger) {
this.logger = logger;
}
#hasStarted = false;
#startupTasks = [];
addStartupHook(hook, options) {
if (this.#hasStarted) {
throw new Error("Attempted to add startup hook after startup");
}
this.#startupTasks.push({ hook, options });
}
async startup() {
if (this.#hasStarted) {
return;
}
this.#hasStarted = true;
this.logger.debug(`Running ${this.#startupTasks.length} startup tasks...`);
await Promise.all(
this.#startupTasks.map(async ({ hook, options }) => {
const logger = options?.logger ?? this.logger;
try {
await hook();
logger.debug(`Startup hook succeeded`);
} catch (error) {
logger.error(`Startup hook failed, ${error}`);
}
})
);
}
#hasBeforeShutdown = false;
#beforeShutdownTasks = [];
addBeforeShutdownHook(hook) {
if (this.#hasBeforeShutdown) {
throw new Error(
"Attempt to add before shutdown hook after shutdown has started"
);
}
this.#beforeShutdownTasks.push({ hook });
}
async beforeShutdown() {
if (this.#hasBeforeShutdown) {
return;
}
this.#hasBeforeShutdown = true;
this.logger.debug(
`Running ${this.#beforeShutdownTasks.length} before shutdown tasks...`
);
await Promise.all(
this.#beforeShutdownTasks.map(async ({ hook }) => {
try {
await hook();
this.logger.debug(`Before shutdown hook succeeded`);
} catch (error) {
this.logger.error(`Before shutdown hook failed, ${error}`);
}
})
);
}
#hasShutdown = false;
#shutdownTasks = [];
addShutdownHook(hook, options) {
if (this.#hasShutdown) {
throw new Error("Attempted to add shutdown hook after shutdown");
}
this.#shutdownTasks.push({ hook, options });
}
async shutdown() {
if (this.#hasShutdown) {
return;
}
this.#hasShutdown = true;
this.logger.debug(
`Running ${this.#shutdownTasks.length} shutdown tasks...`
);
await Promise.all(
this.#shutdownTasks.map(async ({ hook, options }) => {
const logger = options?.logger ?? this.logger;
try {
await hook();
logger.debug(`Shutdown hook succeeded`);
} catch (error) {
logger.error(`Shutdown hook failed, ${error}`);
}
})
);
}
}
const rootLifecycleServiceFactory = backendPluginApi.createServiceFactory({
service: backendPluginApi.coreServices.rootLifecycle,
deps: {
logger: backendPluginApi.coreServices.rootLogger
},
async factory({ logger }) {
return new BackendLifecycleImpl(logger);
}
});
exports.BackendLifecycleImpl = BackendLifecycleImpl;
exports.rootLifecycleServiceFactory = rootLifecycleServiceFactory;
//# sourceMappingURL=rootLifecycleServiceFactory.cjs.js.map