@lad-tech/nsc-toolkit 1.28.3 → 2.0.1

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/CHANGELOG.md ADDED
@@ -0,0 +1,6 @@
1
+ ## [2.0.1](https://github.com/lad-tech/nsc-toolkit/compare/v2.0.0...v2.0.1) (2025-07-07)
2
+
3
+
4
+ ### Bug Fixes
5
+
6
+ * Fix off method ([#151](https://github.com/lad-tech/nsc-toolkit/issues/151)) ([a6eafb4](https://github.com/lad-tech/nsc-toolkit/commit/a6eafb4679f2846496afde639b52dca86b2afc97))
package/README.md CHANGED
@@ -11,9 +11,6 @@
11
11
  - [Быстрый старт](#быстрый-старт)
12
12
  - [Переменные окружения](#переменные-окружения)
13
13
  - [Основные компоненты библиотеки](#основные-компоненты-библиотеки)
14
- - [Рекомендации](#рекомендации)
15
- - [Пример использования](#пример-использования)
16
- - [Описание каталога `examples`](#описание-каталога-examples)
17
14
  - [Сворачивание сервисов в монолитное приложение](#сворачивание-сервисов-в-монолитное-приложение)
18
15
  - [Инверсия зависимостей и DI-контейнер](#инверсия-зависимостей-и-di-контейнер)
19
16
 
@@ -275,11 +272,11 @@ npm i
275
272
 
276
273
  - `getListener` 一 метод получения объекта `EventEmitter` для подписки на события сервиса.
277
274
 
278
- 3. Класс `Container`. Реализует DI-контейнре. Сам класс не доступен для импорта, а доступен только его экземпляр, что позволяет реализовать шаблон Singlton. В микросервисном варианте контейнер один на сервис. В монолитном варианте использования контейнер один на все приложение. За счет использования объектов Symbol в качестве ключей для привязки зависимостей исключены коллизии при привязках зависимостей в разных частях приложения через один контейнер. Для привязки зависимости к ключу необходимо указать тип зависимости. Это нужно чтобы библиотека могла корректно создать экземпляр зависимости. Всего существуют 3 вида зависимостей:
275
+ 3. Класс `Container`. Реализует DI-контейнре. Сам класс не доступен для импорта, а доступен только его экземпляр, что позволяет реализовать шаблон Singleton. В микросервисном варианте контейнер один на сервис. В монолитном варианте использования контейнер один на все приложение. За счет использования объектов Symbol в качестве ключей для привязки зависимостей исключены коллизии при привязках зависимостей в разных частях приложения через один контейнер. Для привязки зависимости к ключу необходимо указать тип зависимости. Это нужно чтобы библиотека могла корректно создать экземпляр зависимости. Всего существуют 3 вида зависимостей:
279
276
 
280
277
  - `service` 一 сервис как зависимости.
281
278
  - `adapter` 一 класс с набором синхронных или асинхронных методов. Например репозиторий или фасад от стороннего API. Этот тип зависимости можно настроить с помощью необязательного объекта настроек. У опций адаптера могут быть следующие настройки:
282
- - `singlton` 一 Булевое значение. Если передать `true` то адаптер станет singlton'ом. Объект будет создан один раз и дальше будет всегда использоваться один экземпляр.
279
+ - `singleton` 一 Булевое значение. Если передать `true` то адаптер станет singleton'ом. Объект будет создан один раз и дальше будет всегда использоваться один экземпляр.
283
280
  - `init` 一 Булевое значение. Для того что бы использовать этот флаг адаптер должен реализовывать следующий интерфейс
284
281
  ```js
285
282
  {
@@ -287,7 +284,7 @@ npm i
287
284
  close: () => Promise<any>;
288
285
  }
289
286
  ```
290
- Если адаптер реализует требуемые методы и при передачи флага `init` при привязки адаптера адаптер можно будет инициализировать через контейнер использую метод контейнера `init`. Если к контейнеру было привязано несколько адаптеров, которые необходимо инициализировать, то после вызова метода контейнера `init` все адаптеры будут инициализированны последовательно. Метод инициализации вернет массив инициализированных экземпляров адаптеров. Каждый адаптер с настройкой `init` также становится singlton'ом.
287
+ Если адаптер реализует требуемые методы и при передачи флага `init` при привязки адаптера адаптер можно будет инициализировать через контейнер использую метод контейнера `init`. Если к контейнеру было привязано несколько адаптеров, которые необходимо инициализировать, то после вызова метода контейнера `init` все адаптеры будут инициализированны последовательно. Метод инициализации вернет массив инициализированных экземпляров адаптеров. Каждый адаптер с настройкой `init` также становится singleton'ом.
291
288
  - `constant`一 обычный объект. Например, объект с конфигурацией.
292
289
  - Альтернативный синтаксис привязки с учетом вышеизложенной информации
293
290
  ```js
@@ -296,7 +293,7 @@ npm i
296
293
  // константа
297
294
  container.symbol(key2).to.Constant({ obj: 'value' });
298
295
  // Синглтон
299
- container.symbol(key).to.Singlton(mySingleton);
296
+ container.symbol(key).to.Singleton(mySingleton);
300
297
  // Сервис с автоинициазлзацией
301
298
  container.symbol(key).to.Initializable(InitializableService);
302
299
  // Сервис
package/dist/Container.js CHANGED
@@ -5,7 +5,7 @@ const _1 = require(".");
5
5
  class Container {
6
6
  constructor() {
7
7
  this.container = new Map();
8
- this.singltons = new Map();
8
+ this.singletons = new Map();
9
9
  }
10
10
  buildDependency(key) {
11
11
  const deepDependency = this.get(key);
@@ -55,11 +55,11 @@ class Container {
55
55
  Adapter: (value, options) => {
56
56
  this.container.set(key, { type: _1.DependencyType.ADAPTER, value, options });
57
57
  },
58
- Singlton: (value) => {
59
- this.container.set(key, { type: _1.DependencyType.ADAPTER, value, options: { singlton: true } });
58
+ Singleton: (value) => {
59
+ this.container.set(key, { type: _1.DependencyType.ADAPTER, value, options: { singleton: true } });
60
60
  },
61
61
  Constant: (value) => {
62
- this.container.set(key, { type: _1.DependencyType.CONSTANT, value, options: { singlton: true } });
62
+ this.container.set(key, { type: _1.DependencyType.CONSTANT, value, options: { singleton: true } });
63
63
  },
64
64
  Initializable: (value) => {
65
65
  this.container.set(key, { type: _1.DependencyType.ADAPTER, value, options: { init: true } });
@@ -72,11 +72,11 @@ class Container {
72
72
  }
73
73
  async unbind(key) {
74
74
  this.container.delete(key);
75
- const instance = this.singltons.get(key);
75
+ const instance = this.singletons.get(key);
76
76
  if (instance === null || instance === void 0 ? void 0 : instance.init) {
77
77
  await instance.value.close();
78
78
  }
79
- this.singltons.delete(key);
79
+ this.singletons.delete(key);
80
80
  }
81
81
  get(key) {
82
82
  const dependency = this.container.get(key);
@@ -95,12 +95,12 @@ class Container {
95
95
  return dependency.value;
96
96
  }
97
97
  if (this.isAdapterDependency(dependency)) {
98
- if (this.singltons.has(key)) {
99
- return this.singltons.get(key).value;
98
+ if (this.singletons.has(key)) {
99
+ return this.singletons.get(key).value;
100
100
  }
101
101
  const adapter = new dependency.value(...constructor);
102
- if (((_a = dependency.options) === null || _a === void 0 ? void 0 : _a.singlton) || ((_b = dependency.options) === null || _b === void 0 ? void 0 : _b.init)) {
103
- this.singltons.set(key, { value: adapter, init: (_c = dependency.options) === null || _c === void 0 ? void 0 : _c.init });
102
+ if (((_a = dependency.options) === null || _a === void 0 ? void 0 : _a.singleton) || ((_b = dependency.options) === null || _b === void 0 ? void 0 : _b.init)) {
103
+ this.singletons.set(key, { value: adapter, init: (_c = dependency.options) === null || _c === void 0 ? void 0 : _c.init });
104
104
  }
105
105
  return adapter;
106
106
  }
@@ -110,11 +110,11 @@ class Container {
110
110
  var _a, _b;
111
111
  const initialized = [];
112
112
  for await (const [key, dependency] of this.container) {
113
- if (this.isAdapterDependency(dependency) && ((_a = dependency.options) === null || _a === void 0 ? void 0 : _a.init) && !this.singltons.has(key)) {
113
+ if (this.isAdapterDependency(dependency) && ((_a = dependency.options) === null || _a === void 0 ? void 0 : _a.init) && !this.singletons.has(key)) {
114
114
  const instance = this.getInstance(key);
115
115
  await (instance === null || instance === void 0 ? void 0 : instance.init());
116
116
  initialized.push(instance);
117
- this.singltons.set(key, { value: instance, init: (_b = dependency.options) === null || _b === void 0 ? void 0 : _b.init });
117
+ this.singletons.set(key, { value: instance, init: (_b = dependency.options) === null || _b === void 0 ? void 0 : _b.init });
118
118
  }
119
119
  }
120
120
  return initialized;
package/dist/Root.js CHANGED
@@ -43,7 +43,7 @@ class Root {
43
43
  getExpired(expired, ownTimeout) {
44
44
  try {
45
45
  if (!expired) {
46
- const timeout = ownTimeout || this.castToNumber(this.getSettingFromEnv('DEFAULT_REPONSE_TIMEOUT'));
46
+ const timeout = ownTimeout || this.castToNumber(this.getSettingFromEnv('DEFAULT_RESPONSE_TIMEOUT'));
47
47
  return Date.now() + timeout;
48
48
  }
49
49
  if (ownTimeout) {
package/dist/Service.js CHANGED
@@ -4,11 +4,11 @@ exports.Service = void 0;
4
4
  const Root_1 = require("./Root");
5
5
  const nats_1 = require("nats");
6
6
  const _1 = require(".");
7
- const sdk_trace_base_1 = require("@opentelemetry/sdk-trace-base");
7
+ const sdk_trace_node_1 = require("@opentelemetry/sdk-trace-node");
8
8
  const resources_1 = require("@opentelemetry/resources");
9
9
  const semantic_conventions_1 = require("@opentelemetry/semantic-conventions");
10
10
  const api_1 = require("@opentelemetry/api");
11
- const exporter_jaeger_1 = require("@opentelemetry/exporter-jaeger");
11
+ const exporter_trace_otlp_http_1 = require("@opentelemetry/exporter-trace-otlp-http");
12
12
  const node_stream_1 = require("node:stream");
13
13
  const promises_1 = require("node:stream/promises");
14
14
  const toolbelt_1 = require("@lad-tech/toolbelt");
@@ -99,21 +99,23 @@ class Service extends Root_1.Root {
99
99
  * Create global Tracer
100
100
  */
101
101
  createTracer() {
102
- const provider = new sdk_trace_base_1.BasicTracerProvider({
103
- resource: new resources_1.Resource({
104
- [semantic_conventions_1.SemanticResourceAttributes.SERVICE_NAME]: this.options.name,
102
+ const agentUrl = this.getSettingFromEnv('OTEL_AGENT', false);
103
+ const collectorOptions = {
104
+ url: agentUrl,
105
+ concurrencyLimit: 10,
106
+ };
107
+ const exporter = new exporter_trace_otlp_http_1.OTLPTraceExporter(collectorOptions);
108
+ const provider = new sdk_trace_node_1.NodeTracerProvider({
109
+ resource: (0, resources_1.resourceFromAttributes)({
110
+ [semantic_conventions_1.ATTR_SERVICE_NAME]: this.options.name,
105
111
  }),
112
+ spanProcessors: [
113
+ new sdk_trace_node_1.BatchSpanProcessor(exporter, {
114
+ maxQueueSize: 25,
115
+ scheduledDelayMillis: 10000,
116
+ }),
117
+ ],
106
118
  });
107
- let host;
108
- let port;
109
- const agentUrl = this.getSettingFromEnv('OTEL_AGENT', false);
110
- if (agentUrl) {
111
- const agent = agentUrl.split(':');
112
- host = agent[0];
113
- port = parseInt(agent[1]) || undefined;
114
- }
115
- const exporter = new exporter_jaeger_1.JaegerExporter({ host, port });
116
- provider.addSpanProcessor(new sdk_trace_base_1.SimpleSpanProcessor(exporter));
117
119
  provider.register();
118
120
  }
119
121
  finishSpan(span, error, tag) {
@@ -2,15 +2,15 @@ import { ClientService, DependencyType, InitializableService, Tag } from '.';
2
2
  type Constant = Record<string, any>;
3
3
  type Service<R extends Constant = Constant> = ClientService<R>;
4
4
  export type Adapter<R extends Constant = Constant> = new (...args: any[]) => R;
5
- export type Singlton = {
6
- singlton: true;
5
+ export type Singleton = {
6
+ singleton: true;
7
7
  tag?: Tag;
8
8
  };
9
9
  export type NeedInit = {
10
10
  init: true;
11
11
  tag?: Tag;
12
12
  };
13
- export type AdapterOptions = Singlton | NeedInit;
13
+ export type AdapterOptions = Singleton | NeedInit;
14
14
  type Dependency = Service | Adapter | Constant;
15
15
  type ContainerValue = {
16
16
  type: DependencyType;
@@ -19,14 +19,14 @@ type ContainerValue = {
19
19
  };
20
20
  declare class Container {
21
21
  private readonly container;
22
- private readonly singltons;
22
+ private readonly singletons;
23
23
  private buildDependency;
24
24
  private inject;
25
25
  private isServiceDependency;
26
26
  private isAdapterDependency;
27
27
  private isConstantDependency;
28
28
  bind<R extends Record<string, any>>(key: symbol, type: typeof DependencyType.SERVICE, value: ClientService<R>): void;
29
- bind<R extends Record<string, any>>(key: symbol, type: typeof DependencyType.ADAPTER, value: Adapter<R>, options?: Singlton): void;
29
+ bind<R extends Record<string, any>>(key: symbol, type: typeof DependencyType.ADAPTER, value: Adapter<R>, options?: Singleton): void;
30
30
  bind<R extends Record<string, any>>(key: symbol, type: typeof DependencyType.ADAPTER, value: Adapter<R & InitializableService>, options?: NeedInit): void;
31
31
  bind<R extends Record<string, any>>(key: symbol, type: typeof DependencyType.CONSTANT, value: R): void;
32
32
  symbol(key: symbol): {
@@ -34,7 +34,7 @@ declare class Container {
34
34
  Adapter: <R extends Record<string, any>>(value: Adapter<R> | Adapter<R & import("./interfaces").GracefulShutdownAdditionalService & {
35
35
  init: () => Promise<any>;
36
36
  }>, options?: AdapterOptions) => void;
37
- Singlton: <R_1 extends Record<string, any>>(value: Adapter<R_1>) => void;
37
+ Singleton: <R_1 extends Record<string, any>>(value: Adapter<R_1>) => void;
38
38
  Constant: <R_2 extends Record<string, any>>(value: R_2) => void;
39
39
  Initializable: <R_3 extends Record<string, any>>(value: Adapter<R_3 & import("./interfaces").GracefulShutdownAdditionalService & {
40
40
  init: () => Promise<any>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lad-tech/nsc-toolkit",
3
- "version": "1.28.3",
3
+ "version": "2.0.1",
4
4
  "description": "Toolkit for create microservices around NATS",
5
5
  "main": "dist/index.js",
6
6
  "types": "./dist/types/index.d.ts",
@@ -15,7 +15,7 @@
15
15
  "@commitlint/cli": "^17.2.0",
16
16
  "@commitlint/config-conventional": "^17.2.0",
17
17
  "@semantic-release/changelog": "^6.0.2",
18
- "@semantic-release/npm": "^9.0.1",
18
+ "@semantic-release/npm": "^12.0.2",
19
19
  "@types/jest": "^27.5.2",
20
20
  "@types/node": "^22.13.13",
21
21
  "eslint": "^7.32.0",
@@ -29,19 +29,19 @@
29
29
  "lefthook": "^1.2.0",
30
30
  "prettier": "^2.6.1",
31
31
  "prettier-eslint": "^13.0.0",
32
- "semantic-release": "^19.0.5",
32
+ "semantic-release": "^24.2.6",
33
33
  "ts-jest": "^29.1.0",
34
34
  "typescript": "^5.1.3"
35
35
  },
36
36
  "dependencies": {
37
37
  "@lad-tech/toolbelt": "^1.3.1",
38
- "@opentelemetry/api": "^1.1.0",
39
- "@opentelemetry/exporter-jaeger": "^1.3.1",
40
- "@opentelemetry/resources": "^1.3.1",
41
- "@opentelemetry/sdk-trace-base": "^1.3.1",
42
- "@opentelemetry/semantic-conventions": "^1.3.1",
38
+ "@opentelemetry/api": "^1.9.0",
39
+ "@opentelemetry/exporter-trace-otlp-http": "^0.202.0",
40
+ "@opentelemetry/resources": "^2.0.1",
41
+ "@opentelemetry/sdk-trace-node": "^2.0.1",
42
+ "@opentelemetry/semantic-conventions": "^1.34.0",
43
43
  "ajv": "^8.11.0",
44
- "nats": "^2.29.3",
44
+ "nats": "^2.15.0",
45
45
  "reflect-metadata": "^0.1.13"
46
46
  },
47
47
  "peerDependencies": {
@@ -1,77 +0,0 @@
1
- {
2
- // Use IntelliSense to learn about possible attributes.
3
- // Hover to view descriptions of existing attributes.
4
- // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5
- "version": "0.2.0",
6
- "configurations": [
7
- {
8
- "type": "node",
9
- "request": "launch",
10
- "name": "Launch NSC_Example_Gate_Micro",
11
- "skipFiles": ["<node_internals>/**"],
12
- "program": "${workspaceFolder}/examples/HttpGate/dist/examples/HttpGate/start.micro.js",
13
- "outFiles": ["${workspaceFolder}/examples/HttpGate/dist/**/*.js"],
14
- "preLaunchTask": "buildGateMicro",
15
- "outputCapture": "std",
16
- "env": {
17
- "NODE_PATH": "${workspaceFolder}/examples/HttpGate/dist",
18
- "LOG_LEVEL": "info",
19
- "NATS_HOST": "nats://localhost:4222",
20
- "DEFAULT_RESPONSE_TIMEOUT": "50000",
21
- "ENVIRONMENT": "local",
22
- "OTEL_AGENT": "http://localhost:4318/v1/traces"
23
- }
24
- },
25
- {
26
- "type": "node",
27
- "request": "launch",
28
- "name": "Launch NSC_Example_Gate_Mono",
29
- "skipFiles": ["<node_internals>/**"],
30
- "program": "${workspaceFolder}/examples/HttpGate/dist/examples/HttpGate/start.mono.js",
31
- "outFiles": ["${workspaceFolder}/examples/HttpGate/dist/**/*.js"],
32
- "preLaunchTask": "buildGateMono",
33
- "outputCapture": "std",
34
- "env": {
35
- "NODE_PATH": "${workspaceFolder}/examples/HttpGate/dist",
36
- "LOG_LEVEL": "info",
37
- "NATS_HOST": "nats://localhost:4222",
38
- "DEFAULT_RESPONSE_TIMEOUT": "50000",
39
- "ENVIRONMENT": "local"
40
- }
41
- },
42
- {
43
- "type": "node",
44
- "request": "launch",
45
- "name": "Launch NSC_Example_Logic",
46
- "skipFiles": ["<node_internals>/**"],
47
- "program": "${workspaceFolder}/examples/LogicService",
48
- "outFiles": ["${workspaceFolder}/examples/LogicService/dist/**/*.js"],
49
- "preLaunchTask": "buildLogic",
50
- "outputCapture": "std",
51
- "env": {
52
- "NODE_PATH": "${workspaceFolder}/examples/LogicService/dist",
53
- "LOG_LEVEL": "info",
54
- "NATS_HOST": "nats://localhost:4222",
55
- "ENVIRONMENT": "local",
56
- "OTEL_AGENT": "http://localhost:4318/v1/traces"
57
- }
58
- },
59
- {
60
- "type": "node",
61
- "request": "launch",
62
- "name": "Launch NSC_Example_Math",
63
- "skipFiles": ["<node_internals>/**"],
64
- "program": "${workspaceFolder}/examples/MathService",
65
- "outFiles": ["${workspaceFolder}/examples/MathService/dist/**/*.js"],
66
- "preLaunchTask": "buildMath",
67
- "outputCapture": "std",
68
- "env": {
69
- "NODE_PATH": "${workspaceFolder}/examples/MathService/dist",
70
- "LOG_LEVEL": "info",
71
- "NATS_HOST": "nats://localhost:4222",
72
- "ENVIRONMENT": "local",
73
- "OTEL_AGENT": "http://localhost:4318/v1/traces"
74
- }
75
- }
76
- ]
77
- }
@@ -1,25 +0,0 @@
1
- {
2
- "version": "2.0.0",
3
- "tasks": [
4
- {
5
- "label": "buildGateMicro",
6
- "type": "shell",
7
- "command": "cd ${workspaceFolder}/examples/HttpGate/ && npm run buildMicro",
8
- },
9
- {
10
- "label": "buildGateMono",
11
- "type": "shell",
12
- "command": "cd ${workspaceFolder}/examples/HttpGate/ && npm run buildMono",
13
- },
14
- {
15
- "label": "buildLogic",
16
- "type": "shell",
17
- "command": "cd ${workspaceFolder}/examples/LogicService/ && npm run build",
18
- },
19
- {
20
- "label": "buildMath",
21
- "type": "shell",
22
- "command": "cd ${workspaceFolder}/examples/MathService/ && npm run build",
23
- }
24
- ]
25
- }