@tramvai/module-server 2.7.1 → 2.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,10 @@
1
1
  export declare const sharedProviders: {
2
- provide: import("@tinkoff/dippy/lib/createToken/createToken").BaseTokenInterface<string>;
2
+ provide: import("@tinkoff/dippy").BaseTokenInterface<string>;
3
3
  useFactory: ({ appInfo }: {
4
4
  appInfo: any;
5
5
  }) => string;
6
6
  deps: {
7
- appInfo: import("@tinkoff/dippy/lib/createToken/createToken").BaseTokenInterface<{
7
+ appInfo: import("@tinkoff/dippy").BaseTokenInterface<{
8
8
  [key: string]: string;
9
9
  appName: string;
10
10
  }>;
@@ -1,8 +1,8 @@
1
1
  /// <reference types="node" />
2
- import type { LOGGER_TOKEN } from '@tramvai/tokens-common';
2
+ import type { EXECUTION_CONTEXT_MANAGER_TOKEN, LOGGER_TOKEN } from '@tramvai/tokens-common';
3
3
  import type { COMMAND_LINE_RUNNER_TOKEN } from '@tramvai/core';
4
4
  import type { WEB_APP_TOKEN, WEB_APP_BEFORE_INIT_TOKEN, WEB_APP_INIT_TOKEN, WEB_APP_AFTER_INIT_TOKEN, WEB_APP_LIMITER_TOKEN, SERVER_TOKEN } from '@tramvai/tokens-server';
5
- import type { WEB_FASTIFY_APP_TOKEN, WEB_FASTIFY_APP_AFTER_INIT_TOKEN, WEB_FASTIFY_APP_BEFORE_INIT_TOKEN, WEB_FASTIFY_APP_INIT_TOKEN, WEB_FASTIFY_APP_LIMITER_TOKEN, WEB_FASTIFY_APP_BEFORE_ERROR_TOKEN, WEB_FASTIFY_APP_AFTER_ERROR_TOKEN, WEB_FASTIFY_APP_PROCESS_ERROR_TOKEN } from '@tramvai/tokens-server-private';
5
+ import type { WEB_FASTIFY_APP_TOKEN, WEB_FASTIFY_APP_AFTER_INIT_TOKEN, WEB_FASTIFY_APP_BEFORE_INIT_TOKEN, WEB_FASTIFY_APP_INIT_TOKEN, WEB_FASTIFY_APP_LIMITER_TOKEN, WEB_FASTIFY_APP_BEFORE_ERROR_TOKEN, WEB_FASTIFY_APP_AFTER_ERROR_TOKEN, WEB_FASTIFY_APP_PROCESS_ERROR_TOKEN, WEB_FASTIFY_APP_METRICS_TOKEN } from '@tramvai/tokens-server-private';
6
6
  import type { ExtractDependencyType } from '@tinkoff/dippy';
7
7
  export declare const webAppFactory: ({ server }: {
8
8
  server: typeof SERVER_TOKEN;
@@ -10,12 +10,14 @@ export declare const webAppFactory: ({ server }: {
10
10
  export declare const webAppExpressFactory: ({ webApp }: {
11
11
  webApp: typeof WEB_FASTIFY_APP_TOKEN;
12
12
  }) => import("express-serve-static-core").Express;
13
- export declare const webAppInitCommand: ({ app, expressApp, logger, commandLineRunner, beforeInit, limiterRequest, init, afterInit, expressBeforeInit, expressInit, expressAfterInit, expressLimiterRequest, beforeError, processError, afterError, }: {
13
+ export declare const webAppInitCommand: ({ app, expressApp, logger, commandLineRunner, executionContextManager, beforeInit, requestMetrics, limiterRequest, init, afterInit, expressBeforeInit, expressInit, expressAfterInit, expressLimiterRequest, beforeError, processError, afterError, }: {
14
14
  app: ExtractDependencyType<typeof WEB_FASTIFY_APP_TOKEN>;
15
15
  expressApp: ExtractDependencyType<typeof WEB_APP_TOKEN>;
16
16
  logger: ExtractDependencyType<typeof LOGGER_TOKEN>;
17
17
  commandLineRunner: ExtractDependencyType<typeof COMMAND_LINE_RUNNER_TOKEN>;
18
+ executionContextManager: ExtractDependencyType<typeof EXECUTION_CONTEXT_MANAGER_TOKEN>;
18
19
  beforeInit: ExtractDependencyType<typeof WEB_FASTIFY_APP_BEFORE_INIT_TOKEN>;
20
+ requestMetrics: ExtractDependencyType<typeof WEB_FASTIFY_APP_METRICS_TOKEN>;
19
21
  limiterRequest: ExtractDependencyType<typeof WEB_FASTIFY_APP_LIMITER_TOKEN>;
20
22
  init: ExtractDependencyType<typeof WEB_FASTIFY_APP_INIT_TOKEN>;
21
23
  afterInit: ExtractDependencyType<typeof WEB_FASTIFY_APP_AFTER_INIT_TOKEN>;
package/lib/server.es.js CHANGED
@@ -1,10 +1,11 @@
1
1
  import { __decorate } from 'tslib';
2
2
  import { setDefaultResultOrder } from 'dns';
3
- import { Scope, APP_INFO_TOKEN, Module, provide, DI_TOKEN, COMMAND_LINE_RUNNER_TOKEN, commandLineListTokens, createToken } from '@tramvai/core';
3
+ import EventEmitter$1, { EventEmitter } from 'events';
4
+ import { Scope, APP_INFO_TOKEN, Module, provide as provide$1, DI_TOKEN, COMMAND_LINE_RUNNER_TOKEN, commandLineListTokens, createToken } from '@tramvai/core';
4
5
  import { SERVER_MODULE_PAPI_PUBLIC_ROUTE, SERVER_MODULE_PAPI_PUBLIC_URL, SERVER_MODULE_PAPI_PRIVATE_URL, WEB_APP_BEFORE_INIT_TOKEN, WEB_APP_TOKEN, SERVER_MODULE_PAPI_PRIVATE_ROUTE, SERVER_MODULE_STATICS_OPTIONS, SERVER_TOKEN, READINESS_PROBE_TOKEN, LIVENESS_PROBE_TOKEN, UTILITY_SERVER_PATHS, PROXY_CONFIG_TOKEN, DEPENDENCIES_VERSION_FILTER_TOKEN, UTILITY_SERVER_PORT_TOKEN, WEB_APP_INIT_TOKEN, WEB_APP_AFTER_INIT_TOKEN, WEB_APP_LIMITER_TOKEN } from '@tramvai/tokens-server';
5
6
  export * from '@tramvai/tokens-server';
6
- import { WEB_FASTIFY_APP_BEFORE_INIT_TOKEN, UTILITY_WEB_FASTIFY_APP_TOKEN, UTILITY_SERVER_TOKEN, SERVER_FACTORY_TOKEN, WEB_FASTIFY_APP_TOKEN, WEB_FASTIFY_APP_FACTORY_TOKEN, WEB_FASTIFY_APP_INIT_TOKEN, WEB_FASTIFY_APP_AFTER_INIT_TOKEN, WEB_FASTIFY_APP_LIMITER_TOKEN, WEB_FASTIFY_APP_BEFORE_ERROR_TOKEN, WEB_FASTIFY_APP_PROCESS_ERROR_TOKEN, WEB_FASTIFY_APP_AFTER_ERROR_TOKEN } from '@tramvai/tokens-server-private';
7
- import { REQUEST, RESPONSE, FASTIFY_REQUEST, FASTIFY_RESPONSE, RESPONSE_MANAGER_TOKEN, LOGGER_TOKEN, ENV_MANAGER_TOKEN, ENV_USED_TOKEN } from '@tramvai/tokens-common';
7
+ import { WEB_FASTIFY_APP_BEFORE_INIT_TOKEN, UTILITY_WEB_FASTIFY_APP_TOKEN, UTILITY_SERVER_TOKEN, SERVER_FACTORY_TOKEN, WEB_FASTIFY_APP_TOKEN, WEB_FASTIFY_APP_FACTORY_TOKEN, WEB_FASTIFY_APP_INIT_TOKEN, WEB_FASTIFY_APP_AFTER_INIT_TOKEN, WEB_FASTIFY_APP_METRICS_TOKEN, WEB_FASTIFY_APP_LIMITER_TOKEN, WEB_FASTIFY_APP_BEFORE_ERROR_TOKEN, WEB_FASTIFY_APP_PROCESS_ERROR_TOKEN, WEB_FASTIFY_APP_AFTER_ERROR_TOKEN } from '@tramvai/tokens-server-private';
8
+ import { ROOT_EXECUTION_CONTEXT_TOKEN, REQUEST, RESPONSE, FASTIFY_REQUEST, FASTIFY_RESPONSE, RESPONSE_MANAGER_TOKEN, LOGGER_TOKEN, ENV_MANAGER_TOKEN, ENV_USED_TOKEN, EXECUTION_CONTEXT_MANAGER_TOKEN } from '@tramvai/tokens-common';
8
9
  import { MetricsModule } from '@tramvai/module-metrics';
9
10
  import { CacheWarmupModule } from '@tramvai/module-cache-warmup';
10
11
  import http from 'http';
@@ -12,6 +13,7 @@ import fastify from 'fastify';
12
13
  import express from 'express';
13
14
  import { fastifyCookie } from '@fastify/cookie';
14
15
  import fastifyFormBody from '@fastify/formbody';
16
+ import { provide, createChildContainer } from '@tinkoff/dippy';
15
17
  import fp from 'fastify-plugin';
16
18
  import symbols from 'fastify/lib/symbols';
17
19
  import isNil from '@tinkoff/utils/is/nil';
@@ -23,13 +25,11 @@ import filterObj from '@tinkoff/utils/object/filter';
23
25
  import flatten from '@tinkoff/utils/array/flatten';
24
26
  import toArray from '@tinkoff/utils/array/toArray';
25
27
  import { create, middlewares, getPapiParameters, createPapiMethod } from '@tramvai/papi';
26
- import { createChildContainer } from '@tinkoff/dippy';
27
28
  import eachObj from '@tinkoff/utils/object/each';
28
29
  import { resolve } from 'path';
29
30
  import FastifyStatic from '@fastify/static';
30
31
  import { createTerminus } from '@tinkoff/terminus';
31
32
  import { parse } from '@tinkoff/url';
32
- import { EventEmitter } from 'events';
33
33
  import monkeypatch from '@tinkoff/monkeypatch';
34
34
  import https from 'https';
35
35
  import isArray from '@tinkoff/utils/is/array';
@@ -201,7 +201,7 @@ const webAppExpressFactory = ({ webApp }) => {
201
201
  app.disable('x-powered-by');
202
202
  return app;
203
203
  };
204
- const webAppInitCommand = ({ app, expressApp, logger, commandLineRunner, beforeInit, limiterRequest, init, afterInit, expressBeforeInit, expressInit, expressAfterInit, expressLimiterRequest, beforeError, processError, afterError, }) => {
204
+ const webAppInitCommand = ({ app, expressApp, logger, commandLineRunner, executionContextManager, beforeInit, requestMetrics, limiterRequest, init, afterInit, expressBeforeInit, expressInit, expressAfterInit, expressLimiterRequest, beforeError, processError, afterError, }) => {
205
205
  const log = logger('server:webapp');
206
206
  const runHandlers = (instance, handlers, expressHandlers) => {
207
207
  return Promise.all([
@@ -220,6 +220,7 @@ const webAppInitCommand = ({ app, expressApp, logger, commandLineRunner, beforeI
220
220
  await runHandlers(instance, beforeInit, expressBeforeInit);
221
221
  });
222
222
  await app.register(async (instance) => {
223
+ await runHandlers(instance, requestMetrics, []);
223
224
  await runHandlers(instance, limiterRequest, expressLimiterRequest);
224
225
  await app.register(fastifyCookie);
225
226
  await app.register(fastifyFormBody, { bodyLimit: 2097152 }); // 2mb
@@ -235,45 +236,51 @@ const webAppInitCommand = ({ app, expressApp, logger, commandLineRunner, beforeI
235
236
  message: 'Клиент зашел на страницу',
236
237
  url: request.url,
237
238
  });
238
- const di = await commandLineRunner.run('server', 'customer', [
239
- {
240
- provide: REQUEST,
241
- scope: Scope.REQUEST,
242
- useValue: request.raw,
243
- },
244
- {
245
- provide: RESPONSE,
246
- scope: Scope.REQUEST,
247
- useValue: reply.raw,
248
- },
249
- // TODO: перевести использование на новые
250
- // TODO: добавить для papi
251
- {
252
- provide: FASTIFY_REQUEST,
253
- scope: Scope.REQUEST,
254
- useValue: request,
255
- },
256
- {
257
- provide: FASTIFY_RESPONSE,
258
- scope: Scope.REQUEST,
259
- useValue: reply,
260
- },
261
- ]);
262
- const responseManager = di.get(RESPONSE_MANAGER_TOKEN);
263
- if (reply.sent) {
264
- log.debug({
265
- event: 'response-ended',
266
- message: 'Response was already ended.',
267
- url: request.url,
268
- });
269
- }
270
- else {
271
- reply
272
- .header('content-type', 'text/html')
273
- .headers(responseManager.getHeaders())
274
- .status(responseManager.getStatus())
275
- .send(responseManager.getBody());
276
- }
239
+ await executionContextManager.withContext(null, 'root', async (rootExecutionContext) => {
240
+ const di = await commandLineRunner.run('server', 'customer', [
241
+ provide({
242
+ provide: ROOT_EXECUTION_CONTEXT_TOKEN,
243
+ useValue: rootExecutionContext,
244
+ }),
245
+ {
246
+ provide: REQUEST,
247
+ scope: Scope.REQUEST,
248
+ useValue: request.raw,
249
+ },
250
+ {
251
+ provide: RESPONSE,
252
+ scope: Scope.REQUEST,
253
+ useValue: reply.raw,
254
+ },
255
+ // TODO: перевести использование на новые
256
+ // TODO: добавить для papi
257
+ {
258
+ provide: FASTIFY_REQUEST,
259
+ scope: Scope.REQUEST,
260
+ useValue: request,
261
+ },
262
+ {
263
+ provide: FASTIFY_RESPONSE,
264
+ scope: Scope.REQUEST,
265
+ useValue: reply,
266
+ },
267
+ ]);
268
+ const responseManager = di.get(RESPONSE_MANAGER_TOKEN);
269
+ if (reply.sent) {
270
+ log.debug({
271
+ event: 'response-ended',
272
+ message: 'Response was already ended.',
273
+ url: request.url,
274
+ });
275
+ }
276
+ else {
277
+ reply
278
+ .header('content-type', 'text/html')
279
+ .headers(responseManager.getHeaders())
280
+ .status(responseManager.getStatus())
281
+ .send(responseManager.getBody());
282
+ }
283
+ });
277
284
  }
278
285
  catch (err) {
279
286
  if (err.di) {
@@ -439,7 +446,7 @@ ServerPapiModule = __decorate([
439
446
  providers: [
440
447
  fileApiProvider,
441
448
  ...sharedProviders,
442
- provide({
449
+ provide$1({
443
450
  provide: WEB_APP_BEFORE_INIT_TOKEN,
444
451
  useFactory: ({ di, app, logger, privateRoutes, publicRoutes, publicBaseUrl, privateBaseUrl, }) => () => {
445
452
  if (process.env.NODE_ENV === 'development') {
@@ -509,7 +516,7 @@ ServerPapiModule = __decorate([
509
516
  multi: true,
510
517
  }),
511
518
  // необходимо для утилит. Подумать как можно убрать в будующем. Если убрать не будет ломающим изменением
512
- provide({
519
+ provide$1({
513
520
  provide: SERVER_MODULE_PAPI_PUBLIC_ROUTE,
514
521
  multi: true,
515
522
  useValue: createPapiMethod({
@@ -543,7 +550,7 @@ let ServerStaticsModule = class ServerStaticsModule {
543
550
  ServerStaticsModule = __decorate([
544
551
  Module({
545
552
  providers: [
546
- provide({
553
+ provide$1({
547
554
  provide: WEB_FASTIFY_APP_BEFORE_INIT_TOKEN,
548
555
  useFactory: ({ options }) => {
549
556
  const path = (options === null || options === void 0 ? void 0 : options.path) || 'public';
@@ -587,7 +594,7 @@ let ServerGracefulShutdownModule = class ServerGracefulShutdownModule {
587
594
  ServerGracefulShutdownModule = __decorate([
588
595
  Module({
589
596
  providers: [
590
- provide({
597
+ provide$1({
591
598
  provide: WEB_FASTIFY_APP_BEFORE_INIT_TOKEN,
592
599
  multi: true,
593
600
  useFactory: ({ app, server, logger, commandLineRunner, livenessProbe, readinessProbe }) => {
@@ -893,12 +900,12 @@ let UtilityServerModule = class UtilityServerModule {
893
900
  UtilityServerModule = __decorate([
894
901
  Module({
895
902
  providers: [
896
- provide({
903
+ provide$1({
897
904
  provide: ENV_USED_TOKEN,
898
905
  multi: true,
899
906
  useValue: [{ key: 'UTILITY_SERVER_PORT', optional: true }],
900
907
  }),
901
- provide({
908
+ provide$1({
902
909
  provide: UTILITY_SERVER_PORT_TOKEN,
903
910
  scope: Scope.SINGLETON,
904
911
  useFactory: ({ envManager }) => {
@@ -908,7 +915,7 @@ UtilityServerModule = __decorate([
908
915
  envManager: ENV_MANAGER_TOKEN,
909
916
  },
910
917
  }),
911
- provide({
918
+ provide$1({
912
919
  provide: IS_CUSTOM_SERVER_TOKEN,
913
920
  scope: Scope.SINGLETON,
914
921
  useFactory: ({ port, envManager }) => {
@@ -919,7 +926,7 @@ UtilityServerModule = __decorate([
919
926
  port: UTILITY_SERVER_PORT_TOKEN,
920
927
  },
921
928
  }),
922
- provide({
929
+ provide$1({
923
930
  provide: UTILITY_SERVER_TOKEN,
924
931
  scope: Scope.SINGLETON,
925
932
  useFactory: ({ isCustomServer, serverFactory, server }) => {
@@ -931,7 +938,7 @@ UtilityServerModule = __decorate([
931
938
  serverFactory: SERVER_FACTORY_TOKEN,
932
939
  },
933
940
  }),
934
- provide({
941
+ provide$1({
935
942
  provide: UTILITY_WEB_FASTIFY_APP_TOKEN,
936
943
  scope: Scope.SINGLETON,
937
944
  useFactory: ({ isCustomServer, app, appFactory, server }) => {
@@ -944,7 +951,7 @@ UtilityServerModule = __decorate([
944
951
  server: UTILITY_SERVER_TOKEN,
945
952
  },
946
953
  }),
947
- provide({
954
+ provide$1({
948
955
  provide: commandLineListTokens.listen,
949
956
  multi: true,
950
957
  scope: Scope.SINGLETON,
@@ -984,7 +991,7 @@ let KeepAliveModule = class KeepAliveModule {
984
991
  KeepAliveModule = __decorate([
985
992
  Module({
986
993
  providers: [
987
- provide({
994
+ provide$1({
988
995
  provide: ENV_USED_TOKEN,
989
996
  useValue: [
990
997
  {
@@ -1003,7 +1010,7 @@ KeepAliveModule = __decorate([
1003
1010
  },
1004
1011
  ],
1005
1012
  }),
1006
- provide({
1013
+ provide$1({
1007
1014
  provide: commandLineListTokens.init,
1008
1015
  useFactory: ({ server, envManager, }) => () => {
1009
1016
  const externalKeepAliveTimeout = envManager.get('NODE_KEEPALIVE_TIMEOUT');
@@ -1022,6 +1029,9 @@ KeepAliveModule = __decorate([
1022
1029
  if (typeof setDefaultResultOrder === 'function') {
1023
1030
  setDefaultResultOrder('ipv4first');
1024
1031
  }
1032
+ // tramvai add a lot of "abort" event listeners to AbortSignal, but we can't configure only AbortSignal max listeners,
1033
+ // because AbortSignal is not instance of EventEmitter - https://github.com/southpolesteve/node-abort-controller/blob/master/index.js
1034
+ EventEmitter$1.defaultMaxListeners = 50;
1025
1035
  let ServerModule = class ServerModule {
1026
1036
  };
1027
1037
  ServerModule = __decorate([
@@ -1039,12 +1049,12 @@ ServerModule = __decorate([
1039
1049
  process.env.NODE_ENV !== 'production' && DebugHttpRequestsModule,
1040
1050
  ].filter(Boolean),
1041
1051
  providers: [
1042
- provide({
1052
+ provide$1({
1043
1053
  provide: SERVER_FACTORY_TOKEN,
1044
1054
  scope: Scope.SINGLETON,
1045
1055
  useValue: serverFactory,
1046
1056
  }),
1047
- provide({
1057
+ provide$1({
1048
1058
  provide: SERVER_TOKEN,
1049
1059
  scope: Scope.SINGLETON,
1050
1060
  useFactory: ({ factory }) => factory(),
@@ -1052,12 +1062,12 @@ ServerModule = __decorate([
1052
1062
  factory: SERVER_FACTORY_TOKEN,
1053
1063
  },
1054
1064
  }),
1055
- provide({
1065
+ provide$1({
1056
1066
  provide: WEB_FASTIFY_APP_FACTORY_TOKEN,
1057
1067
  scope: Scope.SINGLETON,
1058
1068
  useValue: webAppFactory,
1059
1069
  }),
1060
- provide({
1070
+ provide$1({
1061
1071
  provide: WEB_FASTIFY_APP_TOKEN,
1062
1072
  useFactory: ({ factory, server }) => factory({ server }),
1063
1073
  scope: Scope.SINGLETON,
@@ -1066,7 +1076,7 @@ ServerModule = __decorate([
1066
1076
  factory: WEB_FASTIFY_APP_FACTORY_TOKEN,
1067
1077
  },
1068
1078
  }),
1069
- provide({
1079
+ provide$1({
1070
1080
  // BACKWARD: provide the express app as before
1071
1081
  provide: WEB_APP_TOKEN,
1072
1082
  scope: Scope.SINGLETON,
@@ -1084,9 +1094,11 @@ ServerModule = __decorate([
1084
1094
  expressApp: WEB_APP_TOKEN,
1085
1095
  logger: LOGGER_TOKEN,
1086
1096
  commandLineRunner: COMMAND_LINE_RUNNER_TOKEN,
1097
+ executionContextManager: EXECUTION_CONTEXT_MANAGER_TOKEN,
1087
1098
  beforeInit: { token: WEB_FASTIFY_APP_BEFORE_INIT_TOKEN, optional: true },
1088
1099
  init: { token: WEB_FASTIFY_APP_INIT_TOKEN, optional: true },
1089
1100
  afterInit: { token: WEB_FASTIFY_APP_AFTER_INIT_TOKEN, optional: true },
1101
+ requestMetrics: { token: WEB_FASTIFY_APP_METRICS_TOKEN, optional: true },
1090
1102
  limiterRequest: { token: WEB_FASTIFY_APP_LIMITER_TOKEN, optional: true },
1091
1103
  expressBeforeInit: { token: WEB_APP_BEFORE_INIT_TOKEN, optional: true },
1092
1104
  expressInit: { token: WEB_APP_INIT_TOKEN, optional: true },
package/lib/server.js CHANGED
@@ -4,6 +4,7 @@ Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var tslib = require('tslib');
6
6
  var dns = require('dns');
7
+ var EventEmitter = require('events');
7
8
  var core = require('@tramvai/core');
8
9
  var tokensServer = require('@tramvai/tokens-server');
9
10
  var tokensServerPrivate = require('@tramvai/tokens-server-private');
@@ -15,6 +16,7 @@ var fastify = require('fastify');
15
16
  var express = require('express');
16
17
  var cookie = require('@fastify/cookie');
17
18
  var fastifyFormBody = require('@fastify/formbody');
19
+ var dippy = require('@tinkoff/dippy');
18
20
  var fp = require('fastify-plugin');
19
21
  var symbols = require('fastify/lib/symbols');
20
22
  var isNil = require('@tinkoff/utils/is/nil');
@@ -26,13 +28,11 @@ var filterObj = require('@tinkoff/utils/object/filter');
26
28
  var flatten = require('@tinkoff/utils/array/flatten');
27
29
  var toArray = require('@tinkoff/utils/array/toArray');
28
30
  var papi = require('@tramvai/papi');
29
- var dippy = require('@tinkoff/dippy');
30
31
  var eachObj = require('@tinkoff/utils/object/each');
31
32
  var path = require('path');
32
33
  var FastifyStatic = require('@fastify/static');
33
34
  var terminus = require('@tinkoff/terminus');
34
35
  var url = require('@tinkoff/url');
35
- var events = require('events');
36
36
  var monkeypatch = require('@tinkoff/monkeypatch');
37
37
  var https = require('https');
38
38
  var isArray = require('@tinkoff/utils/is/array');
@@ -42,6 +42,7 @@ var moduleCommon = require('@tramvai/module-common');
42
42
 
43
43
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
44
44
 
45
+ var EventEmitter__default = /*#__PURE__*/_interopDefaultLegacy(EventEmitter);
45
46
  var http__default = /*#__PURE__*/_interopDefaultLegacy(http);
46
47
  var fastify__default = /*#__PURE__*/_interopDefaultLegacy(fastify);
47
48
  var express__default = /*#__PURE__*/_interopDefaultLegacy(express);
@@ -226,7 +227,7 @@ const webAppExpressFactory = ({ webApp }) => {
226
227
  app.disable('x-powered-by');
227
228
  return app;
228
229
  };
229
- const webAppInitCommand = ({ app, expressApp, logger, commandLineRunner, beforeInit, limiterRequest, init, afterInit, expressBeforeInit, expressInit, expressAfterInit, expressLimiterRequest, beforeError, processError, afterError, }) => {
230
+ const webAppInitCommand = ({ app, expressApp, logger, commandLineRunner, executionContextManager, beforeInit, requestMetrics, limiterRequest, init, afterInit, expressBeforeInit, expressInit, expressAfterInit, expressLimiterRequest, beforeError, processError, afterError, }) => {
230
231
  const log = logger('server:webapp');
231
232
  const runHandlers = (instance, handlers, expressHandlers) => {
232
233
  return Promise.all([
@@ -245,6 +246,7 @@ const webAppInitCommand = ({ app, expressApp, logger, commandLineRunner, beforeI
245
246
  await runHandlers(instance, beforeInit, expressBeforeInit);
246
247
  });
247
248
  await app.register(async (instance) => {
249
+ await runHandlers(instance, requestMetrics, []);
248
250
  await runHandlers(instance, limiterRequest, expressLimiterRequest);
249
251
  await app.register(cookie.fastifyCookie);
250
252
  await app.register(fastifyFormBody__default["default"], { bodyLimit: 2097152 }); // 2mb
@@ -260,45 +262,51 @@ const webAppInitCommand = ({ app, expressApp, logger, commandLineRunner, beforeI
260
262
  message: 'Клиент зашел на страницу',
261
263
  url: request.url,
262
264
  });
263
- const di = await commandLineRunner.run('server', 'customer', [
264
- {
265
- provide: tokensCommon.REQUEST,
266
- scope: core.Scope.REQUEST,
267
- useValue: request.raw,
268
- },
269
- {
270
- provide: tokensCommon.RESPONSE,
271
- scope: core.Scope.REQUEST,
272
- useValue: reply.raw,
273
- },
274
- // TODO: перевести использование на новые
275
- // TODO: добавить для papi
276
- {
277
- provide: tokensCommon.FASTIFY_REQUEST,
278
- scope: core.Scope.REQUEST,
279
- useValue: request,
280
- },
281
- {
282
- provide: tokensCommon.FASTIFY_RESPONSE,
283
- scope: core.Scope.REQUEST,
284
- useValue: reply,
285
- },
286
- ]);
287
- const responseManager = di.get(tokensCommon.RESPONSE_MANAGER_TOKEN);
288
- if (reply.sent) {
289
- log.debug({
290
- event: 'response-ended',
291
- message: 'Response was already ended.',
292
- url: request.url,
293
- });
294
- }
295
- else {
296
- reply
297
- .header('content-type', 'text/html')
298
- .headers(responseManager.getHeaders())
299
- .status(responseManager.getStatus())
300
- .send(responseManager.getBody());
301
- }
265
+ await executionContextManager.withContext(null, 'root', async (rootExecutionContext) => {
266
+ const di = await commandLineRunner.run('server', 'customer', [
267
+ dippy.provide({
268
+ provide: tokensCommon.ROOT_EXECUTION_CONTEXT_TOKEN,
269
+ useValue: rootExecutionContext,
270
+ }),
271
+ {
272
+ provide: tokensCommon.REQUEST,
273
+ scope: core.Scope.REQUEST,
274
+ useValue: request.raw,
275
+ },
276
+ {
277
+ provide: tokensCommon.RESPONSE,
278
+ scope: core.Scope.REQUEST,
279
+ useValue: reply.raw,
280
+ },
281
+ // TODO: перевести использование на новые
282
+ // TODO: добавить для papi
283
+ {
284
+ provide: tokensCommon.FASTIFY_REQUEST,
285
+ scope: core.Scope.REQUEST,
286
+ useValue: request,
287
+ },
288
+ {
289
+ provide: tokensCommon.FASTIFY_RESPONSE,
290
+ scope: core.Scope.REQUEST,
291
+ useValue: reply,
292
+ },
293
+ ]);
294
+ const responseManager = di.get(tokensCommon.RESPONSE_MANAGER_TOKEN);
295
+ if (reply.sent) {
296
+ log.debug({
297
+ event: 'response-ended',
298
+ message: 'Response was already ended.',
299
+ url: request.url,
300
+ });
301
+ }
302
+ else {
303
+ reply
304
+ .header('content-type', 'text/html')
305
+ .headers(responseManager.getHeaders())
306
+ .status(responseManager.getStatus())
307
+ .send(responseManager.getBody());
308
+ }
309
+ });
302
310
  }
303
311
  catch (err) {
304
312
  if (err.di) {
@@ -738,7 +746,7 @@ DebugHttpRequestsModule = tslib.__decorate([
738
746
  .on('response', (response) => {
739
747
  // Workaround for res._dump in Node.JS http client
740
748
  // https://github.com/nodejs/node/blob/20285ad17755187ece16b8a5effeaa87f5407da2/lib/_http_client.js#L421-L427
741
- if (!wasHandled && events.EventEmitter.listenerCount(response.req, 'response') === 0) {
749
+ if (!wasHandled && EventEmitter.EventEmitter.listenerCount(response.req, 'response') === 0) {
742
750
  response.resume();
743
751
  }
744
752
  log.debug(`${response.statusCode}
@@ -1047,6 +1055,9 @@ KeepAliveModule = tslib.__decorate([
1047
1055
  if (typeof dns.setDefaultResultOrder === 'function') {
1048
1056
  dns.setDefaultResultOrder('ipv4first');
1049
1057
  }
1058
+ // tramvai add a lot of "abort" event listeners to AbortSignal, but we can't configure only AbortSignal max listeners,
1059
+ // because AbortSignal is not instance of EventEmitter - https://github.com/southpolesteve/node-abort-controller/blob/master/index.js
1060
+ EventEmitter__default["default"].defaultMaxListeners = 50;
1050
1061
  exports.ServerModule = class ServerModule {
1051
1062
  };
1052
1063
  exports.ServerModule = tslib.__decorate([
@@ -1109,9 +1120,11 @@ exports.ServerModule = tslib.__decorate([
1109
1120
  expressApp: tokensServer.WEB_APP_TOKEN,
1110
1121
  logger: tokensCommon.LOGGER_TOKEN,
1111
1122
  commandLineRunner: core.COMMAND_LINE_RUNNER_TOKEN,
1123
+ executionContextManager: tokensCommon.EXECUTION_CONTEXT_MANAGER_TOKEN,
1112
1124
  beforeInit: { token: tokensServerPrivate.WEB_FASTIFY_APP_BEFORE_INIT_TOKEN, optional: true },
1113
1125
  init: { token: tokensServerPrivate.WEB_FASTIFY_APP_INIT_TOKEN, optional: true },
1114
1126
  afterInit: { token: tokensServerPrivate.WEB_FASTIFY_APP_AFTER_INIT_TOKEN, optional: true },
1127
+ requestMetrics: { token: tokensServerPrivate.WEB_FASTIFY_APP_METRICS_TOKEN, optional: true },
1115
1128
  limiterRequest: { token: tokensServerPrivate.WEB_FASTIFY_APP_LIMITER_TOKEN, optional: true },
1116
1129
  expressBeforeInit: { token: tokensServer.WEB_APP_BEFORE_INIT_TOKEN, optional: true },
1117
1130
  expressInit: { token: tokensServer.WEB_APP_INIT_TOKEN, optional: true },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tramvai/module-server",
3
- "version": "2.7.1",
3
+ "version": "2.20.0",
4
4
  "description": "",
5
5
  "browser": "lib/browser.js",
6
6
  "main": "lib/server.js",
@@ -22,15 +22,15 @@
22
22
  "build-for-publish": "true"
23
23
  },
24
24
  "dependencies": {
25
- "@tinkoff/errors": "0.2.22",
26
- "@tinkoff/monkeypatch": "1.3.5",
27
- "@tinkoff/terminus": "0.0.5",
28
- "@tinkoff/url": "0.7.39",
29
- "@tramvai/module-cache-warmup": "2.7.1",
30
- "@tramvai/module-metrics": "2.7.1",
31
- "@tramvai/papi": "2.7.1",
32
- "@tramvai/tokens-server": "2.7.1",
33
- "@tramvai/tokens-server-private": "2.7.1",
25
+ "@tinkoff/errors": "0.3.2",
26
+ "@tinkoff/monkeypatch": "2.0.2",
27
+ "@tinkoff/terminus": "0.1.2",
28
+ "@tinkoff/url": "0.8.2",
29
+ "@tramvai/module-cache-warmup": "2.20.0",
30
+ "@tramvai/module-metrics": "2.20.0",
31
+ "@tramvai/papi": "2.20.0",
32
+ "@tramvai/tokens-server": "2.20.0",
33
+ "@tramvai/tokens-server-private": "2.20.0",
34
34
  "compression": "^1.7.4",
35
35
  "express": "^4.17.1",
36
36
  "fastify": "^3.29.0",
@@ -41,13 +41,13 @@
41
41
  "http-proxy-middleware": "^2.0.2"
42
42
  },
43
43
  "peerDependencies": {
44
- "@tinkoff/dippy": "0.7.44",
44
+ "@tinkoff/dippy": "0.8.2",
45
45
  "@tinkoff/utils": "^2.1.2",
46
- "@tramvai/cli": "2.7.1",
47
- "@tramvai/core": "2.7.1",
48
- "@tramvai/module-common": "2.7.1",
49
- "@tramvai/module-environment": "2.7.1",
50
- "@tramvai/tokens-common": "2.7.1",
46
+ "@tramvai/cli": "2.20.0",
47
+ "@tramvai/core": "2.20.0",
48
+ "@tramvai/module-common": "2.20.0",
49
+ "@tramvai/module-environment": "2.20.0",
50
+ "@tramvai/tokens-common": "2.20.0",
51
51
  "tslib": "^2.0.3"
52
52
  },
53
53
  "devDependencies": {