import type { DeferredRegistrationScopeCompletionFunction, DeferredRegistrationScopeOptions } from "../plugins/Plugin.ts"; import type { Runtime } from "../runtime/Runtime.ts"; import type { ModuleRegistrationError, ModuleRegistry, RegisterModulesOptions } from "./ModuleRegistry.ts"; import type { ModuleRegisterFunction } from "./registerModule.ts"; export type ModuleRegistrationStatusListener = () => void; export interface ModuleDefinition { definition: ModuleRegisterFunction | Record; registryId: string; } export class ModuleManager { private readonly runtime: Runtime; private readonly moduleRegistries: ModuleRegistry[]; private readonly listenerRefs = new Map(); #hasRegistrationStarted = false; constructor(runtime: Runtime, moduleRegistries: ModuleRegistry[]) { this.runtime = runtime; this.moduleRegistries = moduleRegistries; } addModuleRegistry(moduleRegistry: ModuleRegistry) { // A registry added afterwards is never started by "registerModules", the modules would never be registered. if (this.#hasRegistrationStarted) { throw new Error("[squide] Cannot add a module registry once the modules registration has started. Are you adding a registry from a deferred registration function or after the application bootstrapped? Add the registry from a plugin constructor."); } this.moduleRegistries.push(moduleRegistry); // A listener registered before this registry was added would otherwise never be notified of its status // changes, and "getAreModulesRegistered" requires every registry, therefore that listener would never fire. // Plugins subscribe from their constructor, which can execute before another plugin adds its own registry. this.listenerRefs.forEach(onChange => { moduleRegistry.registerStatusChangedListener(onChange); }); } async registerModules(definitions: ModuleDefinition[], options?: RegisterModulesOptions) { const errors: ModuleRegistrationError[] = []; // { // local: [ // { registryId: "local", definition: () => ... }, // { registryId: "local", definition: () => ... } // ], // remote: [ // { registryId: "remote", definition: {...} }, // { registryId: "remote", definition: {...} } // ] // } const definitionsByRegistryId = Object.groupBy(definitions, x => x.registryId); // A registry without modules settles synchronously, before the next registry leaves "none". Without this flag, // "getAreModulesRegistered" would report true in between, and a listener subscribed before the bootstrapping, // from a plugin constructor for example, would be notified before the other registries have started. this.#hasRegistrationStarted = true; // It's important to always to though all the registered registries even if there's no module definitions. // Using Promise.all rather than Promise.allSettled to throw any errors that occurs. await Promise.all( this.moduleRegistries.map(async x => { const registryDefinitions = definitionsByRegistryId[x.id]; const modules = registryDefinitions ? registryDefinitions.map(y => y.definition) : []; const registrationErrors = await x.registerModules(this.runtime, modules, options); errors.push(...registrationErrors); }) ); return errors; } async #withDeferredRegistrationScope(options: DeferredRegistrationScopeOptions, run: () => Promise) { this.runtime.startDeferredRegistrationScope({ transactional: options.transactional }); const completionFunctions: DeferredRegistrationScopeCompletionFunction[] = []; try { // The plugins are notified before the modules so they can reset their registry first. A faulty plugin is // isolated rather than failing the run: aborting would leave the modules unregistered, and therefore never // ready, which keeps the application on its bootstrapping fallback forever. for (const plugin of this.runtime.plugins) { try { const completionFunction = plugin.onDeferredRegistrationScopeStarted?.({ ...options }); if (typeof completionFunction === "function") { completionFunctions.push(completionFunction); } } catch (error: unknown) { this.runtime.logger .withText(`[squide] An error occured while starting the deferred registration scope of the "${plugin.name}" plugin.`) .withError(error as Error) .error(); } } // The runtime listeners are the non plugin surface of the very same hook, so they are notified in // the same place, under the same guarantees. Plugins first: a plugin registry is framework adjacent // and an application listener may want to read what a plugin just reset. completionFunctions.push(...this.runtime._notifyDeferredRegistrationScopeStarted(options)); return await run(); } finally { // A completion error is logged rather than rethrown. Rethrowing would abort the caller before it notifies // the app router store, and the navigation items committed just below would never be rendered. for (const completionFunction of completionFunctions) { try { completionFunction(); } catch (error: unknown) { // Deliberately not saying "plugin": this array holds the completion functions of both the // plugins and the runtime listeners, and naming one would send a reader hunting through the // plugin list for a plugin that may not be there. this.runtime.logger .withText("[squide] An error occured while completing a deferred registration scope.") .withError(error as Error) .error(); } } // Must always be completed, otherwise every subsequent run throws for the lifetime of the runtime. this.runtime.completeDeferredRegistrationScope(); } } async registerDeferredRegistrations(data?: TData) { return this.#withDeferredRegistrationScope({ operation: "register", transactional: false }, async () => { const errors: ModuleRegistrationError[] = []; // Using Promise.all rather than Promise.allSettled to throw any errors that occurs. await Promise.all( this.moduleRegistries.map(async x => { const registrationErrors = await x.registerDeferredRegistrations(this.runtime, data); errors.push(...registrationErrors); }) ); return errors; }); } async updateDeferredRegistrations(data?: TData) { return this.#withDeferredRegistrationScope({ operation: "update", transactional: true }, async () => { const errors: ModuleRegistrationError[] = []; // IMPORTANT: Currently cannot make this a concurrent operation because it cause errors // with the Honeycomb telemetry due to "active spans". for (const x of this.moduleRegistries) { const registrationErrors = await x.updateDeferredRegistrations(this.runtime, data); errors.push(...registrationErrors); } return errors; }); } getAreModulesRegistered() { if (this.moduleRegistries.length === 0) { return true; } if (this.moduleRegistries.every(x => x.registrationStatus === "none")) { return false; } // The registration status could be "registering-deferred-registration" if all the modules of an application are registered and it's registering the deferred registrations (which is considered as being already registered). // The registration status could be at "ready" if there's no deferred registrations. return this.moduleRegistries.every(x => { const status = x.registrationStatus; // Once the registration has started, a registry still at "none" hasn't been started yet. if (status === "none") { return !this.#hasRegistrationStarted; } return status === "modules-registered" || status === "registering-deferred-registration" || status === "ready"; }); } getAreModulesReady() { if (this.moduleRegistries.length === 0) { return true; } if (this.moduleRegistries.every(x => x.registrationStatus === "none")) { return false; } return this.moduleRegistries.every(x => { const status = x.registrationStatus; // Once the registration has started, a registry still at "none" hasn't been started yet. if (status === "none") { return !this.#hasRegistrationStarted; } return status === "ready"; }); } registerModulesRegisteredListener(callback: ModuleRegistrationStatusListener) { const onChange: ModuleRegistrationStatusListener = () => { if (this.getAreModulesRegistered()) { this.removeModulesRegisteredListener(callback); callback(); } }; this.moduleRegistries.forEach(x => { x.registerStatusChangedListener(onChange); }); this.listenerRefs.set(callback, onChange); } registerModulesReadyListener(callback: ModuleRegistrationStatusListener) { const onChange: ModuleRegistrationStatusListener = () => { if (this.getAreModulesReady()) { this.removeModulesRegisteredListener(callback); callback(); } }; this.moduleRegistries.forEach(x => { x.registerStatusChangedListener(onChange); }); this.listenerRefs.set(callback, onChange); } #removeRegistrationStatusListener(callback: ModuleRegistrationStatusListener) { const onChange = this.listenerRefs.get(callback); if (onChange) { this.moduleRegistries.forEach(x => { x.removeStatusChangedListener(onChange); }); this.listenerRefs.delete(callback); } } removeModulesRegisteredListener(callback: ModuleRegistrationStatusListener) { this.#removeRegistrationStatusListener(callback); } removeModulesReadyListener(callback: ModuleRegistrationStatusListener) { this.#removeRegistrationStatusListener(callback); } get listenersCount() { return this.listenerRefs.size; } setAsReady() { this.moduleRegistries.forEach(x => { x.setAsReady(); }); } }