1
0

bootstrap.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. import { INestApplication, INestMicroservice } from '@nestjs/common';
  2. import { NestFactory } from '@nestjs/core';
  3. import { TcpClientOptions, Transport } from '@nestjs/microservices';
  4. import { getConnectionToken } from '@nestjs/typeorm';
  5. import { Type } from '@vendure/common/lib/shared-types';
  6. import cookieSession = require('cookie-session');
  7. import { Connection, ConnectionOptions, EntitySubscriberInterface } from 'typeorm';
  8. import { InternalServerError } from './common/error/errors';
  9. import { getConfig, setConfig } from './config/config-helpers';
  10. import { DefaultLogger } from './config/logger/default-logger';
  11. import { Logger } from './config/logger/vendure-logger';
  12. import { RuntimeVendureConfig, VendureConfig } from './config/vendure-config';
  13. import { Administrator } from './entity/administrator/administrator.entity';
  14. import { coreEntitiesMap } from './entity/entities';
  15. import { registerCustomEntityFields } from './entity/register-custom-entity-fields';
  16. import { setEntityIdStrategy } from './entity/set-entity-id-strategy';
  17. import { validateCustomFieldsConfig } from './entity/validate-custom-fields-config';
  18. import { getConfigurationFunction, getEntitiesFromPlugins } from './plugin/plugin-metadata';
  19. import { getProxyMiddlewareCliGreetings } from './plugin/plugin-utils';
  20. import { BeforeVendureBootstrap, BeforeVendureWorkerBootstrap } from './plugin/vendure-plugin';
  21. export type VendureBootstrapFunction = (config: VendureConfig) => Promise<INestApplication>;
  22. /**
  23. * @description
  24. * Bootstraps the Vendure server. This is the entry point to the application.
  25. *
  26. * @example
  27. * ```TypeScript
  28. * import { bootstrap } from '\@vendure/core';
  29. * import { config } from './vendure-config';
  30. *
  31. * bootstrap(config).catch(err => {
  32. * console.log(err);
  33. * });
  34. * ```
  35. * @docsCategory
  36. * */
  37. export async function bootstrap(userConfig: Partial<VendureConfig>): Promise<INestApplication> {
  38. const config = await preBootstrapConfig(userConfig);
  39. Logger.useLogger(config.logger);
  40. Logger.info(`Bootstrapping Vendure Server (pid: ${process.pid})...`);
  41. // The AppModule *must* be loaded only after the entities have been set in the
  42. // config, so that they are available when the AppModule decorator is evaluated.
  43. // tslint:disable-next-line:whitespace
  44. const appModule = await import('./app.module');
  45. const { hostname, port, cors } = config.apiOptions;
  46. DefaultLogger.hideNestBoostrapLogs();
  47. const app = await NestFactory.create(appModule.AppModule, {
  48. cors,
  49. logger: new Logger(),
  50. });
  51. DefaultLogger.restoreOriginalLogLevel();
  52. app.useLogger(new Logger());
  53. await runBeforeBootstrapHooks(config, app);
  54. if (config.authOptions.tokenMethod === 'cookie') {
  55. const { sessionSecret, cookieOptions } = config.authOptions;
  56. app.use(
  57. cookieSession({
  58. ...cookieOptions,
  59. // TODO: Remove once the deprecated sessionSecret field is removed
  60. ...(sessionSecret ? { secret: sessionSecret } : {}),
  61. }),
  62. );
  63. }
  64. await app.listen(port, hostname || '');
  65. app.enableShutdownHooks();
  66. if (config.workerOptions.runInMainProcess) {
  67. try {
  68. const worker = await bootstrapWorkerInternal(config);
  69. Logger.warn(`Worker is running in main process. This is not recommended for production.`);
  70. Logger.warn(`[VendureConfig.workerOptions.runInMainProcess = true]`);
  71. closeWorkerOnAppClose(app, worker);
  72. } catch (e) {
  73. Logger.error(`Could not start the worker process: ${e.message || e}`, 'Vendure Worker');
  74. }
  75. }
  76. logWelcomeMessage(config);
  77. return app;
  78. }
  79. /**
  80. * @description
  81. * Bootstraps the Vendure worker. Read more about the [Vendure Worker]({{< relref "vendure-worker" >}}) or see the worker-specific options
  82. * defined in {@link WorkerOptions}.
  83. *
  84. * @example
  85. * ```TypeScript
  86. * import { bootstrapWorker } from '\@vendure/core';
  87. * import { config } from './vendure-config';
  88. *
  89. * bootstrapWorker(config).catch(err => {
  90. * console.log(err);
  91. * });
  92. * ```
  93. * @docsCategory worker
  94. * */
  95. export async function bootstrapWorker(userConfig: Partial<VendureConfig>): Promise<INestMicroservice> {
  96. if (userConfig.workerOptions && userConfig.workerOptions.runInMainProcess === true) {
  97. Logger.useLogger(userConfig.logger || new DefaultLogger());
  98. const errorMessage = `Cannot bootstrap worker when "runInMainProcess" is set to true`;
  99. Logger.error(errorMessage, 'Vendure Worker');
  100. throw new Error(errorMessage);
  101. } else {
  102. try {
  103. const vendureConfig = await preBootstrapConfig(userConfig);
  104. return await bootstrapWorkerInternal(vendureConfig);
  105. } catch (e) {
  106. Logger.error(`Could not start the worker process: ${e.message}`, 'Vendure Worker');
  107. throw e;
  108. }
  109. }
  110. }
  111. async function bootstrapWorkerInternal(
  112. vendureConfig: Readonly<RuntimeVendureConfig>,
  113. ): Promise<INestMicroservice> {
  114. const config = disableSynchronize(vendureConfig);
  115. if (!config.workerOptions.runInMainProcess && (config.logger as any).setDefaultContext) {
  116. (config.logger as any).setDefaultContext('Vendure Worker');
  117. }
  118. Logger.useLogger(config.logger);
  119. Logger.info(`Bootstrapping Vendure Worker (pid: ${process.pid})...`);
  120. const workerModule = await import('./worker/worker.module');
  121. DefaultLogger.hideNestBoostrapLogs();
  122. const workerApp = await NestFactory.createMicroservice(workerModule.WorkerModule, {
  123. transport: config.workerOptions.transport,
  124. logger: new Logger(),
  125. options: config.workerOptions.options,
  126. });
  127. DefaultLogger.restoreOriginalLogLevel();
  128. workerApp.useLogger(new Logger());
  129. workerApp.enableShutdownHooks();
  130. await validateDbTablesForWorker(workerApp);
  131. await runBeforeWorkerBootstrapHooks(config, workerApp);
  132. // A work-around to correctly handle errors when attempting to start the
  133. // microservice server listening.
  134. // See https://github.com/nestjs/nest/issues/2777
  135. // TODO: Remove if & when the above issue is resolved.
  136. await new Promise((resolve, reject) => {
  137. const tcpServer = (workerApp as any).server.server;
  138. if (tcpServer) {
  139. tcpServer.on('error', (e: any) => {
  140. reject(e);
  141. });
  142. }
  143. workerApp.listenAsync().then(resolve);
  144. });
  145. workerWelcomeMessage(config);
  146. return workerApp;
  147. }
  148. /**
  149. * Setting the global config must be done prior to loading the AppModule.
  150. */
  151. export async function preBootstrapConfig(
  152. userConfig: Partial<VendureConfig>,
  153. ): Promise<Readonly<RuntimeVendureConfig>> {
  154. if (userConfig) {
  155. checkForDeprecatedOptions(userConfig);
  156. setConfig(userConfig);
  157. }
  158. const entities = await getAllEntities(userConfig);
  159. const { coreSubscribersMap } = await import('./entity/subscribers');
  160. setConfig({
  161. dbConnectionOptions: {
  162. entities,
  163. subscribers: Object.values(coreSubscribersMap) as Array<Type<EntitySubscriberInterface>>,
  164. },
  165. });
  166. let config = getConfig();
  167. setEntityIdStrategy(config.entityIdStrategy, entities);
  168. const customFieldValidationResult = validateCustomFieldsConfig(config.customFields, entities);
  169. if (!customFieldValidationResult.valid) {
  170. process.exitCode = 1;
  171. throw new Error(`CustomFields config error:\n- ` + customFieldValidationResult.errors.join('\n- '));
  172. }
  173. config = await runPluginConfigurations(config);
  174. registerCustomEntityFields(config);
  175. setExposedHeaders(config);
  176. return config;
  177. }
  178. /**
  179. * Initialize any configured plugins.
  180. */
  181. async function runPluginConfigurations(config: RuntimeVendureConfig): Promise<RuntimeVendureConfig> {
  182. for (const plugin of config.plugins) {
  183. const configFn = getConfigurationFunction(plugin);
  184. if (typeof configFn === 'function') {
  185. config = await configFn(config);
  186. }
  187. }
  188. return config;
  189. }
  190. /**
  191. * Returns an array of core entities and any additional entities defined in plugins.
  192. */
  193. export async function getAllEntities(userConfig: Partial<VendureConfig>): Promise<Array<Type<any>>> {
  194. const coreEntities = Object.values(coreEntitiesMap) as Array<Type<any>>;
  195. const pluginEntities = getEntitiesFromPlugins(userConfig.plugins);
  196. const allEntities: Array<Type<any>> = coreEntities;
  197. // Check to ensure that no plugins are defining entities with names
  198. // which conflict with existing entities.
  199. for (const pluginEntity of pluginEntities) {
  200. if (allEntities.find(e => e.name === pluginEntity.name)) {
  201. throw new InternalServerError(`error.entity-name-conflict`, { entityName: pluginEntity.name });
  202. } else {
  203. allEntities.push(pluginEntity);
  204. }
  205. }
  206. return allEntities;
  207. }
  208. /**
  209. * If the 'bearer' tokenMethod is being used, then we automatically expose the authTokenHeaderKey header
  210. * in the CORS options, making sure to preserve any user-configured exposedHeaders.
  211. */
  212. function setExposedHeaders(config: Readonly<RuntimeVendureConfig>) {
  213. if (config.authOptions.tokenMethod === 'bearer') {
  214. const authTokenHeaderKey = config.authOptions.authTokenHeaderKey;
  215. const corsOptions = config.apiOptions.cors;
  216. if (typeof corsOptions !== 'boolean') {
  217. const { exposedHeaders } = corsOptions;
  218. let exposedHeadersWithAuthKey: string[];
  219. if (!exposedHeaders) {
  220. exposedHeadersWithAuthKey = [authTokenHeaderKey];
  221. } else if (typeof exposedHeaders === 'string') {
  222. exposedHeadersWithAuthKey = exposedHeaders
  223. .split(',')
  224. .map(x => x.trim())
  225. .concat(authTokenHeaderKey);
  226. } else {
  227. exposedHeadersWithAuthKey = exposedHeaders.concat(authTokenHeaderKey);
  228. }
  229. corsOptions.exposedHeaders = exposedHeadersWithAuthKey;
  230. }
  231. }
  232. }
  233. export async function runBeforeBootstrapHooks(config: Readonly<RuntimeVendureConfig>, app: INestApplication) {
  234. function hasBeforeBootstrapHook(
  235. plugin: any,
  236. ): plugin is { beforeVendureBootstrap: BeforeVendureBootstrap } {
  237. return typeof plugin.beforeVendureBootstrap === 'function';
  238. }
  239. for (const plugin of config.plugins) {
  240. if (hasBeforeBootstrapHook(plugin)) {
  241. await plugin.beforeVendureBootstrap(app);
  242. }
  243. }
  244. }
  245. export async function runBeforeWorkerBootstrapHooks(
  246. config: Readonly<RuntimeVendureConfig>,
  247. worker: INestMicroservice,
  248. ) {
  249. function hasBeforeBootstrapHook(
  250. plugin: any,
  251. ): plugin is { beforeVendureWorkerBootstrap: BeforeVendureWorkerBootstrap } {
  252. return typeof plugin.beforeVendureWorkerBootstrap === 'function';
  253. }
  254. for (const plugin of config.plugins) {
  255. if (hasBeforeBootstrapHook(plugin)) {
  256. await plugin.beforeVendureWorkerBootstrap(worker);
  257. }
  258. }
  259. }
  260. /**
  261. * Monkey-patches the app's .close() method to also close the worker microservice
  262. * instance too.
  263. */
  264. function closeWorkerOnAppClose(app: INestApplication, worker: INestMicroservice) {
  265. // A Nest app is a nested Proxy. By getting the prototype we are
  266. // able to access and override the actual close() method.
  267. const appPrototype = Object.getPrototypeOf(app);
  268. const appClose = appPrototype.close.bind(app);
  269. appPrototype.close = async () => {
  270. return Promise.all([appClose(), worker.close()]);
  271. };
  272. }
  273. function workerWelcomeMessage(config: VendureConfig) {
  274. let transportString = '';
  275. let connectionString = '';
  276. const transport = (config.workerOptions && config.workerOptions.transport) || Transport.TCP;
  277. transportString = ` with ${Transport[transport]} transport`;
  278. const options = (config.workerOptions as TcpClientOptions).options;
  279. if (options) {
  280. const { host, port } = options;
  281. connectionString = ` at ${host || 'localhost'}:${port}`;
  282. }
  283. Logger.info(`Vendure Worker started${transportString}${connectionString}`);
  284. }
  285. function logWelcomeMessage(config: RuntimeVendureConfig) {
  286. let version: string;
  287. try {
  288. version = require('../package.json').version;
  289. } catch (e) {
  290. version = ' unknown';
  291. }
  292. const { port, shopApiPath, adminApiPath } = config.apiOptions;
  293. const apiCliGreetings: Array<[string, string]> = [];
  294. apiCliGreetings.push(['Shop API', `http://localhost:${port}/${shopApiPath}`]);
  295. apiCliGreetings.push(['Admin API', `http://localhost:${port}/${adminApiPath}`]);
  296. apiCliGreetings.push(...getProxyMiddlewareCliGreetings(config));
  297. const columnarGreetings = arrangeCliGreetingsInColumns(apiCliGreetings);
  298. const title = `Vendure server (v${version}) now running on port ${port}`;
  299. const maxLineLength = Math.max(title.length, ...columnarGreetings.map(l => l.length));
  300. const titlePadLength = title.length < maxLineLength ? Math.floor((maxLineLength - title.length) / 2) : 0;
  301. Logger.info(`=`.repeat(maxLineLength));
  302. Logger.info(title.padStart(title.length + titlePadLength));
  303. Logger.info('-'.repeat(maxLineLength).padStart(titlePadLength));
  304. columnarGreetings.forEach(line => Logger.info(line));
  305. Logger.info(`=`.repeat(maxLineLength));
  306. }
  307. function arrangeCliGreetingsInColumns(lines: Array<[string, string]>): string[] {
  308. const columnWidth = Math.max(...lines.map(l => l[0].length)) + 2;
  309. return lines.map(l => `${(l[0] + ':').padEnd(columnWidth)}${l[1]}`);
  310. }
  311. /**
  312. * Fix race condition when modifying DB
  313. * See: https://github.com/vendure-ecommerce/vendure/issues/152
  314. */
  315. function disableSynchronize(userConfig: Readonly<RuntimeVendureConfig>): Readonly<RuntimeVendureConfig> {
  316. const config = { ...userConfig };
  317. config.dbConnectionOptions = {
  318. ...userConfig.dbConnectionOptions,
  319. synchronize: false,
  320. } as ConnectionOptions;
  321. return config;
  322. }
  323. /**
  324. * Check that the Database tables exist. When running Vendure server & worker
  325. * concurrently for the first time, the worker will attempt to access the
  326. * DB tables before the server has populated them (assuming synchronize = true
  327. * in config). This method will use polling to check the existence of a known table
  328. * before allowing the rest of the worker bootstrap to continue.
  329. * @param worker
  330. */
  331. async function validateDbTablesForWorker(worker: INestMicroservice) {
  332. const connection: Connection = worker.get(getConnectionToken());
  333. await new Promise(async (resolve, reject) => {
  334. const checkForTables = async (): Promise<boolean> => {
  335. try {
  336. const adminCount = await connection.getRepository(Administrator).count();
  337. return 0 < adminCount;
  338. } catch (e) {
  339. return false;
  340. }
  341. };
  342. const pollIntervalMs = 5000;
  343. let attempts = 0;
  344. const maxAttempts = 10;
  345. let validTableStructure = false;
  346. Logger.verbose('Checking for expected DB table structure...');
  347. while (!validTableStructure && attempts < maxAttempts) {
  348. attempts++;
  349. validTableStructure = await checkForTables();
  350. if (validTableStructure) {
  351. Logger.verbose('Table structure verified');
  352. resolve();
  353. return;
  354. }
  355. Logger.verbose(
  356. `Table structure could not be verified, trying again after ${pollIntervalMs}ms (attempt ${attempts} of ${maxAttempts})`,
  357. );
  358. await new Promise(resolve1 => setTimeout(resolve1, pollIntervalMs));
  359. }
  360. reject(`Could not validate DB table structure. Aborting bootstrap.`);
  361. });
  362. }
  363. function checkForDeprecatedOptions(config: Partial<VendureConfig>) {
  364. const deprecatedApiOptions = [
  365. 'hostname',
  366. 'port',
  367. 'adminApiPath',
  368. 'shopApiPath',
  369. 'channelTokenKey',
  370. 'cors',
  371. 'middleware',
  372. 'apolloServerPlugins',
  373. ];
  374. const deprecatedOptionsUsed = deprecatedApiOptions.filter(option => config.hasOwnProperty(option));
  375. if (deprecatedOptionsUsed.length) {
  376. throw new Error(
  377. `The following VendureConfig options are deprecated: ${deprecatedOptionsUsed.join(', ')}\n` +
  378. `They have been moved to the "apiOptions" object. Please update your configuration.`,
  379. );
  380. }
  381. }