@tramvai/module-server 1.39.1 → 1.44.5

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.
package/README.md CHANGED
@@ -1,16 +1,16 @@
1
1
  # Module Server
2
2
 
3
- Один из основных модулей Tramvai который реализует обработку HTTP запросов клиентов. В этом модули изолирована вся логика работы с ответами клиентам.
3
+ Core `tramvai` module, responsible for processing the users requests.
4
4
 
5
- ## Подключение
5
+ ## Installation
6
6
 
7
- Необходимо установить `@tramvai/module-server` с помощью npm
7
+ You need to install `@tramvai/module-server`
8
8
 
9
9
  ```bash
10
10
  npm i --save @tramvai/module-server
11
11
  ```
12
12
 
13
- И подключить в проекте
13
+ And connect to the project
14
14
 
15
15
  ```tsx
16
16
  import { createApp } from '@tramvai/core';
@@ -24,28 +24,28 @@ createApp({
24
24
 
25
25
  ## Explanation
26
26
 
27
- ### Обработка запросов пользователей
27
+ ### Processing the users requests
28
28
 
29
- Основной функционал модуля заключается в том, что-бы обработать запрос пользователя, запустить commandLine у tramvai приложения и забрать данные страницы с RESPONSE_MANAGER_TOKEN
29
+ `ServerModule` creates [express.js](https://expressjs.com/) application, handles user requests, runs [commandLineRunner](concepts/command-line-runner.md), and sends responses to users with data, headers and status from `RESPONSE_MANAGER_TOKEN` token.
30
30
 
31
- ### Проксирование запросов
31
+ ### Request proxying
32
32
 
33
- В server модуле доступна функциональность, которая позволяет настроить проксирование урлов в приложение используя библиотеку [http-proxy-middleware](https://github.com/chimurai/http-proxy-middleware). Эта фича работает как в дев режиме, так и на проде
33
+ `ServerModule` allows you to configure the proxying of urls to the application using the library [http-proxy-middleware](https://github.com/chimurai/http-proxy-middleware)
34
34
 
35
- Для включения проксирования необходимо в корне проекта создать файл `proxy.conf.js` или `proxy.conf.json` который будет экспортировать объект-маппинг запросов, либо можно использовать токен PROXY_CONFIG_TOKEN.
35
+ To enable proxying, create a file `proxy.conf.js` or `proxy.conf.json` in the root of the project to export the request mapping object, or you can use the `PROXY_CONFIG_TOKEN` token.
36
36
 
37
- #### Формат прокси-файла
37
+ #### Proxy config format
38
38
 
39
- ##### Объект ключ-значение
39
+ ##### Key-value object
40
40
 
41
41
  ```javascript
42
42
  const testStand = 'https://example.org';
43
43
 
44
44
  module.exports = {
45
- // ключ - path pattern для express который будет передан в app.use
46
- // значение может быть строкой, для того чтобы проксировать все урлы начинающиеся с /login/
45
+ // The key is the path pattern for the `express` to be passed to `app.use`
46
+ // value can be a string, in order to proxy all urls starting with `/login/`
47
47
  '/login/': testStand,
48
- // или может быть объектом конфига для [http-proxy](https://github.com/chimurai/http-proxy-middleware#http-proxy-options)
48
+ // or can be a config object for [http-proxy](https://github.com/chimurai/http-proxy-middleware#http-proxy-options)
49
49
  '/test/': {
50
50
  target: testStand,
51
51
  auth: true,
@@ -55,19 +55,19 @@ module.exports = {
55
55
  };
56
56
  ```
57
57
 
58
- ##### Объект со свойствами context и target
58
+ ##### Object with context and target properties
59
59
 
60
60
  ```javascript
61
61
  module.exports = {
62
- // context - аналогичен опции для [http-proxy-middleware](https://github.com/chimurai/http-proxy-middleware#context-matching)
62
+ // context - is similar to the option for [http-proxy-middleware](https://github.com/chimurai/http-proxy-middleware#context-matching)
63
63
  context: ['/login/', '/registration/', '/auth/papi/'],
64
64
  target: 'https://example.org',
65
- // разные дополнительные опции
65
+ // other `http-proxy-middleware` options
66
66
  changeOrigin: true,
67
67
  };
68
68
  ```
69
69
 
70
- ##### Массив со свойствами context и target
70
+ ##### Array with context and target properties
71
71
 
72
72
  ```json
73
73
  [
@@ -78,7 +78,7 @@ module.exports = {
78
78
  ]
79
79
  ```
80
80
 
81
- ##### Используя провайдеры с помощью токена PROXY_CONFIG_TOKEN
81
+ ##### Implementation of the PROXY_CONFIG_TOKEN token
82
82
 
83
83
  ```tsx
84
84
  import { Scope, provide } from '@tramvai/core';
@@ -97,30 +97,30 @@ import { PROXY_CONFIG_TOKEN } from '@tramvai/tokens-server';
97
97
  ];
98
98
  ```
99
99
 
100
- ### Раздача статических файлов
100
+ ### Serving static files
101
101
 
102
- В module-server встроен статический сервер, который позволяет раздавать статичные файлы пользователям.
102
+ The `ServerModule` has a built-in static server that allows you to distribute static files to users.
103
103
 
104
- Для раздачи файлов, необходимо в корне проекта создать директорию `public` в который поместить необходимые файлы. После этого все файлы будут доступны для запроса браузерами
104
+ To serve files, you need to create a directory `public` in the root of the project in which to place the necessary files.
105
+ After that, all files will be available for request by browsers.
105
106
 
106
- примеру, мы хотим раздать sw.js файл из корня проекта:_ для этого создаем папку `public` в которой закидываем файл `sw.js`. Теперь на стороне клиента, мы сможем запросить данные с урла http://localhost:3000/sw.js. Так-же скорее всего нужны будут доработки на стороне CD, для того что бы скопировать папаку public на стенды.
107
-
108
- Эта функция доступна так-же и на продакшене. Для этого необходимо в докер контейнер скопировать папку `public`
107
+ _For example, we want to distribute sw.js file from the project's root:_ for this we create a folder `public` in which we put the file `sw.js`. Now on the client side, we will be able to request data from the url http://localhost:3000/sw.js. Also, we will most likely need some modifications on the CI/CD side to copy the public folder to the stands.
109
108
 
109
+ This function is also available in production. For this purpose, copy the folder `public` into the docker container
110
110
  ### PAPI
111
111
 
112
- Papi - API роуты для `tramvai` приложения. Подробная информация доступна в разделе [Papi](features/papi/introduction.md)
112
+ Papi - API routes for the `tramvai` application. More information is available in [Papi](features/papi/introduction.md)
113
113
 
114
- ### Эмуляция проблем с сетью/бэкендами в приложении
114
+ ### Emulation of network/backends problems in the application
115
115
 
116
- (функционал доступен только в dev режиме)
116
+ (functionality is only available in dev mode)
117
117
 
118
- На сервере есть возможность увеличить время ответа всех запросов.
118
+ The server has the ability to increase the response time of all requests.
119
119
 
120
- Для этого необходимо:
120
+ To do this you must:
121
121
 
122
- - стартануть приложение
123
- - отправить post-запрос на `/private/papi/debug-http-request` с указанием задержки для запроса:
122
+ - start the application
123
+ - send a POST request to `/private/papi/debug-http-request` with a delay for the request:
124
124
 
125
125
  ```shell script
126
126
  curl --location --request POST 'http://localhost:3000/tincoin/private/papi/debug-http-request' \
@@ -128,52 +128,54 @@ curl --location --request POST 'http://localhost:3000/tincoin/private/papi/debug
128
128
  --data-urlencode 'delay=2000'
129
129
  ```
130
130
 
131
- - проверить работу приложения. Внимание! после каждого перезапуска сервера настройки сбрасываются, поэтому после каждой пересборки надо обращаться к papi снова.
132
- - отключить таймаут можно обратившись к тому же papi методом delete
131
+ - check if the application works. Note: after each restart of the server the settings are reset, so after each rebuild it is necessary to access papi again.
132
+ - you can disable the timeout by accessing the same papi using the DELETE method
133
133
 
134
134
  ```shell script
135
135
  curl --location --request DELETE 'http://localhost:3000/tincoin/private/papi/debug-http-request'
136
136
  ```
137
137
 
138
- ### Логгирование запросов отправленных на сервере
138
+ ### Logging requests sent to the server
139
139
 
140
- В дев режиме все запросы отправленные через стандартные библиотеки `http` и `https` для nodejs логгируются под специальным ключом `node-debug.request`. Это позволяет увидеть все запросы которые были отправлены на сервере, даже если для запросов не было определено логгирование явно.
140
+ In dev mode, all requests sent through the standard `http` and `https` libraries for nodejs are logged under a special `server:node-debug:request` key. This allows you to see all requests that have been sent to the server, even if no logging has been defined for the requests explicitly.
141
141
 
142
- Чтобы включить такие логи, достаточно добавить в переменную окружения `DEBUG_ENABLE` ключ `node-debug.request`
142
+ To enable such logging, simply add the `server:node-debug:request` key to the `LOG_ENABLE` environment variable
143
143
 
144
144
  ### Health checks
145
145
 
146
- - _`/healthz`_ - после старта приложения всегда отдает ответ `OK`
147
- - _`/readyz`_ - после старта приложения всегда отдает `OK`
146
+ - _`/healthz`_ - always replies `OK` after starting the application
147
+ - _`/readyz`_ - always replies `OK` after starting the application
148
148
 
149
- ### Метрики
149
+ Metrics
150
150
 
151
- В модуль сервера автоматически подключен модуль метрик. Подробную информацию по метрикам, можете почитать [в документации метрик](references/modules/metrics.md)
151
+ The metrics module is automatically connected into the server module.
152
+ For more information on metrics, you can read [in the metrics documentation](references/modules/metrics.md)
152
153
 
153
- ### Прогрев кэшей приложения
154
+ ### Warming application caches
154
155
 
155
- В модуль сервера автоматически подключен модуль прогрева кэшей. Подробную информацию по прогреву кэшей, можете почитать [в документации cache-warmup](references/modules/cache-warmup.md)
156
+ The cache-warmup module is automatically plugged into the server module.
157
+ Detailed information on cache warmup can be found [in cache-warmup documentation](references/modules/cache-warmup.md)
156
158
 
157
- ### Специальные заголовки
159
+ ### Custom headers
158
160
 
159
- #### Информация о сборке и деплое
161
+ #### Building and Deployment Information
160
162
 
161
- В модуле проставляются особые заголовки, которые помогают определить точную информацию о версии собранного приложения, коммите, ветке и т.п.:
163
+ There are special headers in the module, which help to determine the exact information about the version of the built application, commit, branch, etc:
162
164
 
163
- - _x-app-id_ - имя приложения указанного в `createApp`. Указывается в коде приложения.
164
- - _x-host_ - hostname сервера на котором запущено текущее приложение. Вычисляется в рантайме.
165
- - _x-app-version_ - версия запущенного приложения. Передаётся через переменную окружения `APP_VERSION` (внутри tinkoff проставляется в рамках стандартных пайплайнов gitlab ci).
166
- - _x-deploy-branch_ - ветка с которой был собран текущий образ приложения. Передаётся через переменную окружения `DEPLOY_BRANCH` (внутри tinkoff проставляется с помощью unic).
167
- - _x-deploy-commit_ - sha коммита с которого был собран текущий образ приложения. Передаётся через переменную окружения `DEPLOY_COMMIT` (внутри tinkoff проставляется с помощью unic).
168
- - _x-deploy-version_ - номер ревизии деплоя в k8s. Передаётся через переменную окружения `DEPLOY_VERSION` (внутри tinkoff проставляется с помощью unic).
169
- - _x-deploy-repository_ - ссылка на репозиторий приложения. Передаётся через переменную окружения `DEPLOY_REPOSITORY` (внутри tinkoff проставляется с помощью unic).
165
+ - _x-app-id_ - The name of the application specified in `createApp`. Specified in the application code.
166
+ - _x-host_ - Hostname of the server where the current application is running. Computed in runtime.
167
+ - _x-app-version_ - version of the running application. Transmitted through the environment variable `APP_VERSION`.
168
+ - _x-deploy-branch_ - branch from which the current application image was built. Passed through environment variable `DEPLOY_BRANCH`.
169
+ - _x-deploy-commit_ - sha commit from which current application image was built. Passed through environment variable `DEPLOY_COMMIT`.
170
+ - _x-deploy-version_ - deploy revision number in k8s. Passed through environment variable `DEPLOY_VERSION`.
171
+ - _x-deploy-repository_ - application repository link. Passed through environment variable `DEPLOY_REPOSITORY`.
170
172
 
171
- Для всех заголовков выше, которые передаются через переменные окружения, чтобы они были доступны, необходимо чтобы внешняя инфраструктура передавала их при сборке и деплое образа приложения (внутри tinkoff это делается автоматически).
173
+ For all of the headers above which are passed via environment variables to be available, you need the external infrastructure to pass them when building and deprovisioning the application image (inside tinkoff this is done automatically).
172
174
 
173
- ## Отладка
175
+ ## Debugging
174
176
 
175
- Модуль использует логгеры с идентификаторами: `server`, `server:static`, `server:webapp`, `server:node-debug:request`
177
+ Module uses loggers with identifiers: `server`, `server:static`, `server:webapp`, `server:node-debug:request`
176
178
 
177
- ## Экспортируемые токены
179
+ ## Exportable tokens
178
180
 
179
- [ссылка](references/tokens/server-tokens.md)
181
+ [Link](references/tokens/server-tokens.md)
package/lib/server.es.js CHANGED
@@ -93,7 +93,7 @@ const webAppInitCommand = ({ app, logger, commandLineRunner, beforeInit, init, a
93
93
  return async function webAppInit() {
94
94
  await runHandlers(beforeInit);
95
95
  app.use(bodyParser.urlencoded({
96
- limit: '500kb',
96
+ limit: '2mb',
97
97
  extended: false,
98
98
  }), cookieParser());
99
99
  await runHandlers(init);
package/lib/server.js CHANGED
@@ -115,7 +115,7 @@ const webAppInitCommand = ({ app, logger, commandLineRunner, beforeInit, init, a
115
115
  return async function webAppInit() {
116
116
  await runHandlers(beforeInit);
117
117
  app.use(bodyParser__default["default"].urlencoded({
118
- limit: '500kb',
118
+ limit: '2mb',
119
119
  extended: false,
120
120
  }), cookieParser__default["default"]());
121
121
  await runHandlers(init);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tramvai/module-server",
3
- "version": "1.39.1",
3
+ "version": "1.44.5",
4
4
  "description": "",
5
5
  "browser": "lib/browser.js",
6
6
  "main": "lib/server.js",
@@ -23,10 +23,10 @@
23
23
  "@tinkoff/express-terminus": "0.1.12",
24
24
  "@tinkoff/monkeypatch": "1.3.3",
25
25
  "@tinkoff/url": "0.7.37",
26
- "@tramvai/module-cache-warmup": "1.39.1",
27
- "@tramvai/module-metrics": "1.39.1",
28
- "@tramvai/papi": "1.39.1",
29
- "@tramvai/tokens-server": "1.39.1",
26
+ "@tramvai/module-cache-warmup": "1.44.5",
27
+ "@tramvai/module-metrics": "1.44.5",
28
+ "@tramvai/papi": "1.44.5",
29
+ "@tramvai/tokens-server": "1.44.5",
30
30
  "body-parser": "^1.19.0",
31
31
  "compression": "^1.7.4",
32
32
  "cookie-parser": "^1.4.3",
@@ -36,11 +36,11 @@
36
36
  },
37
37
  "peerDependencies": {
38
38
  "@tinkoff/utils": "^2.1.2",
39
- "@tramvai/cli": "1.39.1",
40
- "@tramvai/core": "1.39.1",
41
- "@tramvai/module-common": "1.39.1",
42
- "@tramvai/module-environment": "1.39.1",
43
- "@tramvai/tokens-common": "1.39.1",
39
+ "@tramvai/cli": "1.44.5",
40
+ "@tramvai/core": "1.44.5",
41
+ "@tramvai/module-common": "1.44.5",
42
+ "@tramvai/module-environment": "1.44.5",
43
+ "@tramvai/tokens-common": "1.44.5",
44
44
  "@tinkoff/dippy": "0.7.35",
45
45
  "tslib": "^2.0.3"
46
46
  },