@rsdk/db 5.15.0-next.1 → 5.15.0-next.10

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.
Files changed (140) hide show
  1. package/dist/index.d.ts +1 -0
  2. package/dist/index.js +15 -0
  3. package/dist/index.js.map +1 -1
  4. package/dist/metrics/call-then.d.ts +30 -0
  5. package/dist/metrics/call-then.js +91 -0
  6. package/dist/metrics/call-then.js.map +1 -0
  7. package/dist/metrics/clock.d.ts +2 -0
  8. package/dist/metrics/clock.js +9 -0
  9. package/dist/metrics/clock.js.map +1 -0
  10. package/dist/metrics/db-client-metrics.d.ts +85 -0
  11. package/dist/metrics/db-client-metrics.js +164 -0
  12. package/dist/metrics/db-client-metrics.js.map +1 -0
  13. package/dist/metrics/db-metric.d.ts +41 -0
  14. package/dist/metrics/db-metric.js +99 -0
  15. package/dist/metrics/db-metric.js.map +1 -0
  16. package/dist/metrics/db-metrics.config.d.ts +7 -0
  17. package/dist/metrics/db-metrics.config.js +60 -0
  18. package/dist/metrics/db-metrics.config.js.map +1 -0
  19. package/dist/metrics/db-metrics.module-base.d.ts +61 -0
  20. package/dist/metrics/db-metrics.module-base.js +61 -0
  21. package/dist/metrics/db-metrics.module-base.js.map +1 -0
  22. package/dist/metrics/db-metrics.providers.d.ts +66 -0
  23. package/dist/metrics/db-metrics.providers.js +83 -0
  24. package/dist/metrics/db-metrics.providers.js.map +1 -0
  25. package/dist/metrics/detach-group.d.ts +19 -0
  26. package/dist/metrics/detach-group.js +31 -0
  27. package/dist/metrics/detach-group.js.map +1 -0
  28. package/dist/metrics/detach.d.ts +24 -0
  29. package/dist/metrics/detach.js +45 -0
  30. package/dist/metrics/detach.js.map +1 -0
  31. package/dist/metrics/entity-operations.recorder.d.ts +17 -0
  32. package/dist/metrics/entity-operations.recorder.js +28 -0
  33. package/dist/metrics/entity-operations.recorder.js.map +1 -0
  34. package/dist/metrics/events.d.ts +11 -0
  35. package/dist/metrics/events.js +20 -0
  36. package/dist/metrics/events.js.map +1 -0
  37. package/dist/metrics/guards.d.ts +12 -0
  38. package/dist/metrics/guards.js +19 -0
  39. package/dist/metrics/guards.js.map +1 -0
  40. package/dist/metrics/index.d.ts +1 -0
  41. package/dist/metrics/index.js +11 -0
  42. package/dist/metrics/index.js.map +1 -0
  43. package/dist/metrics/instrumentation/pg-pool.instrumentation.d.ts +48 -0
  44. package/dist/metrics/instrumentation/pg-pool.instrumentation.js +117 -0
  45. package/dist/metrics/instrumentation/pg-pool.instrumentation.js.map +1 -0
  46. package/dist/metrics/instrumentation/pool-adapters.d.ts +22 -0
  47. package/dist/metrics/instrumentation/pool-adapters.js +16 -0
  48. package/dist/metrics/instrumentation/pool-adapters.js.map +1 -0
  49. package/dist/metrics/instrumentation/pool-close.d.ts +10 -0
  50. package/dist/metrics/instrumentation/pool-close.js +43 -0
  51. package/dist/metrics/instrumentation/pool-close.js.map +1 -0
  52. package/dist/metrics/instrumentation/pool-scope.d.ts +13 -0
  53. package/dist/metrics/instrumentation/pool-scope.js +3 -0
  54. package/dist/metrics/instrumentation/pool-scope.js.map +1 -0
  55. package/dist/metrics/instrumentation/pool.adapter.d.ts +50 -0
  56. package/dist/metrics/instrumentation/pool.adapter.js +3 -0
  57. package/dist/metrics/instrumentation/pool.adapter.js.map +1 -0
  58. package/dist/metrics/instrumentation/pool.recorder.d.ts +74 -0
  59. package/dist/metrics/instrumentation/pool.recorder.js +125 -0
  60. package/dist/metrics/instrumentation/pool.recorder.js.map +1 -0
  61. package/dist/metrics/instrumentation/query-completion.d.ts +12 -0
  62. package/dist/metrics/instrumentation/query-completion.js +76 -0
  63. package/dist/metrics/instrumentation/query-completion.js.map +1 -0
  64. package/dist/metrics/instrumentation/query.instrumentation.d.ts +35 -0
  65. package/dist/metrics/instrumentation/query.instrumentation.js +85 -0
  66. package/dist/metrics/instrumentation/query.instrumentation.js.map +1 -0
  67. package/dist/metrics/instrumentation/tarn-pool.instrumentation.d.ts +44 -0
  68. package/dist/metrics/instrumentation/tarn-pool.instrumentation.js +95 -0
  69. package/dist/metrics/instrumentation/tarn-pool.instrumentation.js.map +1 -0
  70. package/dist/metrics/instrumentation/transaction-tracker.d.ts +32 -0
  71. package/dist/metrics/instrumentation/transaction-tracker.js +64 -0
  72. package/dist/metrics/instrumentation/transaction-tracker.js.map +1 -0
  73. package/dist/metrics/metric-types.d.ts +17 -0
  74. package/dist/metrics/metric-types.js +3 -0
  75. package/dist/metrics/metric-types.js.map +1 -0
  76. package/dist/metrics/metrics.d.ts +82 -0
  77. package/dist/metrics/metrics.js +269 -0
  78. package/dist/metrics/metrics.js.map +1 -0
  79. package/dist/metrics/plugin-kit.d.ts +12 -0
  80. package/dist/metrics/plugin-kit.js +42 -0
  81. package/dist/metrics/plugin-kit.js.map +1 -0
  82. package/dist/metrics/pool-names.d.ts +47 -0
  83. package/dist/metrics/pool-names.js +44 -0
  84. package/dist/metrics/pool-names.js.map +1 -0
  85. package/dist/metrics/pool-stats.registry.d.ts +25 -0
  86. package/dist/metrics/pool-stats.registry.js +32 -0
  87. package/dist/metrics/pool-stats.registry.js.map +1 -0
  88. package/dist/metrics/scrape-source.registry.d.ts +29 -0
  89. package/dist/metrics/scrape-source.registry.js +55 -0
  90. package/dist/metrics/scrape-source.registry.js.map +1 -0
  91. package/dist/metrics/sql.d.ts +34 -0
  92. package/dist/metrics/sql.js +132 -0
  93. package/dist/metrics/sql.js.map +1 -0
  94. package/package.json +2 -2
  95. package/src/index.ts +1 -0
  96. package/src/metrics/call-then.ts +134 -0
  97. package/src/metrics/clock.ts +5 -0
  98. package/src/metrics/db-client-metrics.spec.ts +1894 -0
  99. package/src/metrics/db-client-metrics.ts +206 -0
  100. package/src/metrics/db-metric.spec.ts +185 -0
  101. package/src/metrics/db-metric.ts +186 -0
  102. package/src/metrics/db-metrics.config.ts +46 -0
  103. package/src/metrics/db-metrics.module-base.spec.ts +91 -0
  104. package/src/metrics/db-metrics.module-base.ts +77 -0
  105. package/src/metrics/db-metrics.providers.spec.ts +182 -0
  106. package/src/metrics/db-metrics.providers.ts +134 -0
  107. package/src/metrics/detach-group.spec.ts +41 -0
  108. package/src/metrics/detach-group.ts +30 -0
  109. package/src/metrics/detach.spec.ts +61 -0
  110. package/src/metrics/detach.ts +57 -0
  111. package/src/metrics/entity-operations.recorder.ts +26 -0
  112. package/src/metrics/events.spec.ts +19 -0
  113. package/src/metrics/events.ts +28 -0
  114. package/src/metrics/guards.spec.ts +20 -0
  115. package/src/metrics/guards.ts +19 -0
  116. package/src/metrics/index.ts +6 -0
  117. package/src/metrics/instrumentation/pg-pool.instrumentation.ts +177 -0
  118. package/src/metrics/instrumentation/pool-adapters.ts +35 -0
  119. package/src/metrics/instrumentation/pool-close.ts +59 -0
  120. package/src/metrics/instrumentation/pool-guards.spec.ts +318 -0
  121. package/src/metrics/instrumentation/pool-scope.ts +14 -0
  122. package/src/metrics/instrumentation/pool.adapter.ts +67 -0
  123. package/src/metrics/instrumentation/pool.recorder.ts +167 -0
  124. package/src/metrics/instrumentation/query-completion.spec.ts +209 -0
  125. package/src/metrics/instrumentation/query-completion.ts +107 -0
  126. package/src/metrics/instrumentation/query.instrumentation.ts +136 -0
  127. package/src/metrics/instrumentation/tarn-pool.instrumentation.ts +138 -0
  128. package/src/metrics/instrumentation/transaction-tracker.ts +103 -0
  129. package/src/metrics/metric-types.ts +36 -0
  130. package/src/metrics/metrics.ts +233 -0
  131. package/src/metrics/plugin-kit.ts +39 -0
  132. package/src/metrics/pool-names.spec.ts +79 -0
  133. package/src/metrics/pool-names.ts +77 -0
  134. package/src/metrics/pool-stats.registry.spec.ts +81 -0
  135. package/src/metrics/pool-stats.registry.ts +54 -0
  136. package/src/metrics/public-api.spec.ts +104 -0
  137. package/src/metrics/scrape-source.registry.spec.ts +59 -0
  138. package/src/metrics/scrape-source.registry.ts +55 -0
  139. package/src/metrics/sql.spec.ts +110 -0
  140. package/src/metrics/sql.ts +172 -0
@@ -0,0 +1,36 @@
1
+ import type { Counter, Gauge, Histogram } from '@rsdk/core';
2
+
3
+ /*
4
+ * Компоненты получают не метрику prom-client целиком, а только те методы,
5
+ * которые сами вызывают: так их можно собрать с любыми метриками и
6
+ * проверить без реестра
7
+ */
8
+
9
+ /**
10
+ * Counter, в который компонент только пишет
11
+ */
12
+ export type CounterLike<T extends string = string> = Pick<Counter<T>, 'inc'>;
13
+
14
+ /**
15
+ * Gauge, который компонент увеличивает и уменьшает по ходу работы
16
+ */
17
+ export type ActiveGaugeLike<T extends string = string> = Pick<
18
+ Gauge<T>,
19
+ 'inc' | 'dec'
20
+ >;
21
+
22
+ /**
23
+ * Gauge, из которого компонент только удаляет свои ряды
24
+ */
25
+ export type RemovableGaugeLike<T extends string = string> = Pick<
26
+ Gauge<T>,
27
+ 'remove'
28
+ >;
29
+
30
+ /**
31
+ * Histogram, в который компонент только пишет
32
+ */
33
+ export type HistogramLike<T extends string = string> = Pick<
34
+ Histogram<T>,
35
+ 'observe'
36
+ >;
@@ -0,0 +1,233 @@
1
+ import type { AnyMetric } from '@rsdk/core';
2
+ import { Counter, Gauge, Histogram } from '@rsdk/core';
3
+
4
+ import { DbMetric, resolveDbMetric } from './db-metric';
5
+ import { PoolStatsRegistry } from './pool-stats.registry';
6
+
7
+ /**
8
+ * Границы `db_client_operation_duration_seconds`. Плагины берут их через
9
+ * `plugin-kit` для своих длительностей, которые должны сравниваться
10
+ * с длительностью запроса.
11
+ *
12
+ * Все массивы границ здесь неизменяемые, а prom-client получает их копию
13
+ * от `resolveDbMetric`: метрики с одной константой не делят один массив
14
+ */
15
+ export const QUERY_BUCKETS: readonly number[] = [
16
+ 0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10,
17
+ ];
18
+ const ACQUIRE_BUCKETS: readonly number[] = [
19
+ 0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5,
20
+ ];
21
+ const USAGE_BUCKETS: readonly number[] = [
22
+ 0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30,
23
+ ];
24
+ const TRANSACTION_BUCKETS: readonly number[] = [
25
+ 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60,
26
+ ];
27
+
28
+ @DbMetric('histogram', {
29
+ name: 'db_client_operation_duration_seconds',
30
+ help: 'Duration of database queries',
31
+ description: 'Длительность запроса к БД без ожидания соединения из пула',
32
+ labelNames: ['operation', 'status'],
33
+ buckets: QUERY_BUCKETS,
34
+ })
35
+ export class DbClientOperationDuration extends Histogram<
36
+ 'operation' | 'status'
37
+ > {}
38
+
39
+ @DbMetric('gauge', {
40
+ name: 'db_client_queries_active',
41
+ help: 'Number of database queries in flight',
42
+ description: 'Выполняющиеся запросы. Рост означает зависания или блокировки',
43
+ labelNames: ['pool'],
44
+ })
45
+ export class DbClientQueriesActive extends Gauge<'pool'> {}
46
+
47
+ @DbMetric('counter', {
48
+ name: 'db_client_slow_queries_total',
49
+ help: 'Number of database queries slower than the threshold',
50
+ description: 'Запросы дольше порога DB_METRICS_SLOW_QUERY_THRESHOLD',
51
+ labelNames: ['operation'],
52
+ })
53
+ export class DbClientSlowQueries extends Counter<'operation'> {}
54
+
55
+ @DbMetric('counter', {
56
+ name: 'db_client_query_errors_total',
57
+ help: 'Number of failed database queries by SQLSTATE',
58
+ description: 'Ошибки запросов, code — SQLSTATE или unknown',
59
+ labelNames: ['code'],
60
+ })
61
+ export class DbClientQueryErrors extends Counter<'code'> {}
62
+
63
+ @DbMetric('gauge', {
64
+ name: 'db_pool_connections',
65
+ help: 'Number of pool connections by state',
66
+ description: 'Соединения пула по состояниям total / idle / active / waiting',
67
+ labelNames: ['pool', 'state'],
68
+ collect(this: Gauge<'pool' | 'state'>): void {
69
+ this.reset();
70
+ for (const { pool, stats } of PoolStatsRegistry.snapshots()) {
71
+ const { total, idle, active, waiting } = stats;
72
+
73
+ this.set({ pool, state: 'total' }, total);
74
+ this.set({ pool, state: 'idle' }, idle);
75
+ this.set({ pool, state: 'active' }, active);
76
+ this.set({ pool, state: 'waiting' }, waiting);
77
+ }
78
+ },
79
+ })
80
+ export class DbPoolConnections extends Gauge<'pool' | 'state'> {}
81
+
82
+ @DbMetric('gauge', {
83
+ name: 'db_pool_connections_max',
84
+ help: 'Maximum size of the connection pool',
85
+ description: 'Лимит пула. Для алерта active / max > 0.9',
86
+ labelNames: ['pool'],
87
+ collect(this: Gauge<'pool'>): void {
88
+ this.reset();
89
+ for (const { pool, stats } of PoolStatsRegistry.snapshots()) {
90
+ this.set({ pool }, stats.max);
91
+ }
92
+ },
93
+ })
94
+ export class DbPoolConnectionsMax extends Gauge<'pool'> {}
95
+
96
+ @DbMetric('counter', {
97
+ name: 'db_pool_connections_created_total',
98
+ help: 'Number of connections opened by the pool',
99
+ description:
100
+ 'Открытые пулом соединения. Частый рост означает, что соединения часто пересоздаются',
101
+ labelNames: ['pool'],
102
+ })
103
+ export class DbPoolConnectionsCreated extends Counter<'pool'> {}
104
+
105
+ @DbMetric('counter', {
106
+ name: 'db_pool_connections_closed_total',
107
+ help: 'Number of connections removed from the pool',
108
+ description: 'Закрытые пулом соединения',
109
+ labelNames: ['pool'],
110
+ })
111
+ export class DbPoolConnectionsClosed extends Counter<'pool'> {}
112
+
113
+ @DbMetric('histogram', {
114
+ name: 'db_pool_acquire_duration_seconds',
115
+ help: 'Time spent waiting for a pool connection',
116
+ description: 'Ожидание свободного соединения, главный признак нехватки пула',
117
+ labelNames: ['pool'],
118
+ buckets: ACQUIRE_BUCKETS,
119
+ })
120
+ export class DbPoolAcquireDuration extends Histogram<'pool'> {}
121
+
122
+ @DbMetric('counter', {
123
+ name: 'db_pool_acquire_timeouts_total',
124
+ help: 'Number of pool connection acquire timeouts',
125
+ description: 'Таймауты получения соединения из пула',
126
+ labelNames: ['pool'],
127
+ })
128
+ export class DbPoolAcquireTimeouts extends Counter<'pool'> {}
129
+
130
+ @DbMetric('histogram', {
131
+ name: 'db_pool_connection_usage_seconds',
132
+ help: 'Time a connection is held between acquire and release',
133
+ description:
134
+ 'Время удержания соединения между acquire и release. Показывает долгие транзакции',
135
+ labelNames: ['pool'],
136
+ buckets: USAGE_BUCKETS,
137
+ })
138
+ export class DbPoolConnectionUsage extends Histogram<'pool'> {}
139
+
140
+ @DbMetric('counter', {
141
+ name: 'db_pool_errors_total',
142
+ help: 'Number of errors emitted by pool connections',
143
+ description: 'Ошибки соединений пула: обрыв, рестарт БД',
144
+ labelNames: ['pool'],
145
+ })
146
+ export class DbPoolErrors extends Counter<'pool'> {}
147
+
148
+ @DbMetric('counter', {
149
+ name: 'db_transactions_total',
150
+ help: 'Number of finished transactions',
151
+ description: 'Завершённые транзакции, result — commit или rollback',
152
+ labelNames: ['result'],
153
+ })
154
+ export class DbTransactions extends Counter<'result'> {}
155
+
156
+ @DbMetric('histogram', {
157
+ name: 'db_transaction_duration_seconds',
158
+ help: 'Duration of transactions from BEGIN to COMMIT or ROLLBACK',
159
+ description: 'Длительность транзакции от BEGIN до COMMIT или ROLLBACK',
160
+ labelNames: ['result'],
161
+ buckets: TRANSACTION_BUCKETS,
162
+ })
163
+ export class DbTransactionDuration extends Histogram<'result'> {}
164
+
165
+ @DbMetric('gauge', {
166
+ name: 'db_transactions_active',
167
+ help: 'Number of open transactions',
168
+ description: 'Открытые транзакции, помогает находить утечки',
169
+ labelNames: ['pool'],
170
+ })
171
+ export class DbTransactionsActive extends Gauge<'pool'> {}
172
+
173
+ @DbMetric('counter', {
174
+ name: 'orm_entity_operations_total',
175
+ help: 'Number of ORM entity operations',
176
+ description:
177
+ 'Операции ORM над сущностями. Включается DB_METRICS_ORM_ENTITY_OPERATIONS_TOTAL_ENABLED',
178
+ labelNames: ['entity', 'op'],
179
+ })
180
+ export class OrmEntityOperations extends Counter<'entity' | 'op'> {}
181
+
182
+ /**
183
+ * Метрики пула, запросов и транзакций, общие для всех ORM: ключ — под каким
184
+ * именем метрику получает `DbClientMetrics`. Набор записан только здесь: по
185
+ * этой таблице объявляются провайдеры (а через них autodoc) и создаются
186
+ * метрики в `DbClientMetrics.create`
187
+ */
188
+ const CLIENT_METRICS = {
189
+ duration: DbClientOperationDuration,
190
+ queriesActive: DbClientQueriesActive,
191
+ slow: DbClientSlowQueries,
192
+ errors: DbClientQueryErrors,
193
+ connections: DbPoolConnections,
194
+ connectionsMax: DbPoolConnectionsMax,
195
+ created: DbPoolConnectionsCreated,
196
+ closed: DbPoolConnectionsClosed,
197
+ acquireDuration: DbPoolAcquireDuration,
198
+ acquireTimeouts: DbPoolAcquireTimeouts,
199
+ usage: DbPoolConnectionUsage,
200
+ poolErrors: DbPoolErrors,
201
+ transactions: DbTransactions,
202
+ transactionDuration: DbTransactionDuration,
203
+ transactionsActive: DbTransactionsActive,
204
+ } as const;
205
+
206
+ type ClientMetricKey = keyof typeof CLIENT_METRICS;
207
+
208
+ /**
209
+ * Экземпляры метрик из {@link CLIENT_METRICS} под теми же ключами
210
+ */
211
+ export type ClientMetrics = {
212
+ readonly [K in ClientMetricKey]: InstanceType<(typeof CLIENT_METRICS)[K]>;
213
+ };
214
+
215
+ /**
216
+ * Классы метрик из {@link CLIENT_METRICS}: по ним объявляются провайдеры
217
+ */
218
+ export const DB_CLIENT_METRICS = Object.values(CLIENT_METRICS);
219
+
220
+ /**
221
+ * Регистрирует (или берёт уже зарегистрированные) все метрики из
222
+ * {@link CLIENT_METRICS}
223
+ */
224
+ export const resolveClientMetrics = (): ClientMetrics => {
225
+ const resolved: Partial<Record<ClientMetricKey, AnyMetric>> = {};
226
+
227
+ for (const key of Object.keys(CLIENT_METRICS) as ClientMetricKey[]) {
228
+ resolved[key] = resolveDbMetric<AnyMetric>(CLIENT_METRICS[key]);
229
+ }
230
+
231
+ // Каждый ключ таблицы заполнен в цикле выше
232
+ return resolved as ClientMetrics;
233
+ };
@@ -0,0 +1,39 @@
1
+ /*
2
+ * Внутренний API для ORM-плагинов rsdk (`@rsdk/db.typeorm`,
3
+ * `@rsdk/db.mikro-orm`): инструментирование пулов, объявление и провайдеры
4
+ * метрик, база модуля метрик, запись операций над сущностями и общие
5
+ * утилиты. Плагины импортируют его как `@rsdk/db/dist/metrics/plugin-kit`.
6
+ *
7
+ * В корень `@rsdk/db` этот модуль не входит и публичным API не считается:
8
+ * его состав и сигнатуры могут меняться без major-версии. Каждый тип в
9
+ * сигнатурах экспортов отсюда экспортирован здесь же, из корня `@rsdk/db`
10
+ * (`DbMetricsConfig`) или взят из сторонних пакетов. Значения здесь только
11
+ * те, которые импортирует исходный код хотя бы одного плагина; типы — те,
12
+ * которые импортирует плагин или которые нужны сигнатурам экспортов.
13
+ * Метрику плагин получает только через провайдеры
14
+ * {@link dbMetricsModuleProviders}: они проверяют `DB_METRICS_ENABLED`, и
15
+ * фабрики в обход них здесь нет. Поэтому `DbClientMetrics` и
16
+ * `EntityOperationsRecorder` экспортированы только как типы, а внедряет их
17
+ * плагин по токенам `DB_CLIENT_METRICS_TOKEN` и
18
+ * `ENTITY_OPERATIONS_RECORDER_TOKEN`: значение класса открыло бы его
19
+ * статический `create`. Состав закреплён в `public-api.spec.ts`
20
+ */
21
+ export { now, secondsSince } from './clock';
22
+ export type { DbClientMetrics, DbPoolKind } from './db-client-metrics';
23
+ export { DbMetric } from './db-metric';
24
+ export { DbMetricsModuleBase } from './db-metrics.module-base';
25
+ export {
26
+ DB_CLIENT_METRICS_TOKEN,
27
+ dbMetricsModuleProviders,
28
+ ENTITY_OPERATIONS_RECORDER_TOKEN,
29
+ } from './db-metrics.providers';
30
+ export type { DbMetricProvider } from './db-metrics.providers';
31
+ export type {
32
+ EntityOperation,
33
+ EntityOperationsRecorder,
34
+ } from './entity-operations.recorder';
35
+ export { once, replaceMethod } from './detach';
36
+ export type { Detach } from './detach';
37
+ export type { CounterLike, HistogramLike } from './metric-types';
38
+ export { QUERY_BUCKETS } from './metrics';
39
+ export { ScrapeSourceRegistry } from './scrape-source.registry';
@@ -0,0 +1,79 @@
1
+ import type { ClaimedPoolName } from './pool-names';
2
+ import { poolLabelValue, PoolNames } from './pool-names';
3
+
4
+ describe('poolLabelValue', () => {
5
+ it('joins the application name and the resource with a double underscore', () => {
6
+ expect(poolLabelValue({ appName: 'app', resource: 'typeorm' })).toBe(
7
+ 'app__typeorm',
8
+ );
9
+ expect(poolLabelValue({ appName: 'app', resource: 'typeorm:slave0' })).toBe(
10
+ 'app__typeorm:slave0',
11
+ );
12
+ });
13
+ });
14
+
15
+ describe('PoolNames', () => {
16
+ const claimed: ClaimedPoolName[] = [];
17
+
18
+ /**
19
+ * Имя ресурса `x` у приложения `app` даёт значение `app__x`
20
+ */
21
+ const claim = (resource: string): ClaimedPoolName => {
22
+ const result = PoolNames.claim({ appName: 'app', resource });
23
+
24
+ claimed.push(result);
25
+ return result;
26
+ };
27
+
28
+ afterEach(() => {
29
+ for (const { release } of claimed.splice(0)) release();
30
+ });
31
+
32
+ it('returns a free name as is', () => {
33
+ expect(claim('typeorm').name).toBe('app__typeorm');
34
+ });
35
+
36
+ it('adds a suffix to a repeated label', () => {
37
+ expect(claim('typeorm').name).toBe('app__typeorm');
38
+ expect(claim('typeorm').name).toBe('app__typeorm#2');
39
+ });
40
+
41
+ it('gives a taken name the first free suffix', () => {
42
+ expect(claim('x').name).toBe('app__x');
43
+ expect(claim('x').name).toBe('app__x#2');
44
+ expect(claim('x').name).toBe('app__x#3');
45
+ });
46
+
47
+ it('reuses a released name', () => {
48
+ const first = claim('x');
49
+ const second = claim('x');
50
+
51
+ first.release();
52
+
53
+ expect(claim('x').name).toBe('app__x');
54
+ expect(second.name).toBe('app__x#2');
55
+ expect(claim('x').name).toBe('app__x#3');
56
+ });
57
+
58
+ it('reuses a released suffix', () => {
59
+ claim('x');
60
+ const second = claim('x');
61
+
62
+ claim('x');
63
+ second.release();
64
+
65
+ expect(claim('x').name).toBe('app__x#2');
66
+ });
67
+
68
+ it('second release does not free a name claimed after the first one', () => {
69
+ const first = claim('x');
70
+
71
+ first.release();
72
+ const next = claim('x');
73
+
74
+ first.release();
75
+
76
+ expect(next.name).toBe('app__x');
77
+ expect(claim('x').name).toBe('app__x#2');
78
+ });
79
+ });
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Откуда пул: приложение и ресурс внутри него. Из них собирается значение
3
+ * label `pool` — `<appName>__<resource>`, см. {@link poolLabelValue}.
4
+ * Тип внутренний: имя приложения `DbClientMetrics` получает из DI, плагин
5
+ * передаёт только ресурс
6
+ */
7
+ export interface PoolLabel {
8
+ /**
9
+ * `APP_NAME` приложения, которому принадлежит пул
10
+ */
11
+ readonly appName: string;
12
+
13
+ /**
14
+ * Ресурс внутри приложения: `typeorm`, `typeorm:slave0`, `mikro-orm`
15
+ */
16
+ readonly resource: string;
17
+ }
18
+
19
+ /**
20
+ * Значение label `pool` для пула: `<appName>__<resource>`. Формат
21
+ * задаётся только здесь
22
+ */
23
+ export const poolLabelValue = ({ appName, resource }: PoolLabel): string =>
24
+ `${appName}__${resource}`;
25
+
26
+ export interface ClaimedPoolName {
27
+ /**
28
+ * Значение label `pool`: {@link poolLabelValue} или, если оно занято,
29
+ * оно же с суффиксом `#2`, `#3`, …
30
+ */
31
+ readonly name: string;
32
+
33
+ /**
34
+ * Освобождает имя. Повторный вызов ничего не делает
35
+ */
36
+ release(): void;
37
+ }
38
+
39
+ /**
40
+ * Имена пулов, которые сейчас подключены к метрикам, на весь процесс.
41
+ * Метрики общие на процесс, и два пула с одной меткой `pool` писали бы в
42
+ * одни ряды gauge: итог по одному пулу удалял бы ряды другого, а его
43
+ * `dec` потом уводил бы их в минус. Так бывает, когда в одном процессе
44
+ * запущены приложения с одинаковым `APP_NAME`
45
+ */
46
+ export class PoolNames {
47
+ private static readonly taken = new Set<string>();
48
+
49
+ /**
50
+ * Собирает имя из `label` и занимает первое свободное из `name`,
51
+ * `${name}#2`, `${name}#3`, …
52
+ */
53
+ static claim(label: PoolLabel): ClaimedPoolName {
54
+ const name = poolLabelValue(label);
55
+ let claimed = name;
56
+
57
+ for (let index = 2; PoolNames.taken.has(claimed); index++) {
58
+ claimed = `${name}#${index}`;
59
+ }
60
+
61
+ PoolNames.taken.add(claimed);
62
+
63
+ let released = false;
64
+
65
+ return {
66
+ name: claimed,
67
+ release: (): void => {
68
+ if (released) {
69
+ return;
70
+ }
71
+
72
+ released = true;
73
+ PoolNames.taken.delete(claimed);
74
+ },
75
+ };
76
+ }
77
+ }
@@ -0,0 +1,81 @@
1
+ import { register } from '@rsdk/core';
2
+
3
+ import { resolveDbMetric } from './db-metric';
4
+ import { DbPoolConnections, DbPoolConnectionsMax } from './metrics';
5
+ import type { PoolStats } from './pool-stats.registry';
6
+ import { PoolStatsRegistry } from './pool-stats.registry';
7
+
8
+ const STATS: PoolStats = { total: 3, idle: 1, active: 2, waiting: 0, max: 10 };
9
+
10
+ describe('PoolStatsRegistry', () => {
11
+ const detach: (() => void)[] = [];
12
+
13
+ beforeAll(() => {
14
+ resolveDbMetric(DbPoolConnections);
15
+ resolveDbMetric(DbPoolConnectionsMax);
16
+ });
17
+
18
+ afterEach(() => {
19
+ for (const remove of detach.splice(0)) {
20
+ remove();
21
+ }
22
+ });
23
+
24
+ it('skips a source that throws and returns the rest', () => {
25
+ detach.push(
26
+ PoolStatsRegistry.add({
27
+ pool: 'broken',
28
+ stats: () => {
29
+ throw new Error('pool is gone');
30
+ },
31
+ }),
32
+ PoolStatsRegistry.add({ pool: 'alive', stats: () => STATS }),
33
+ );
34
+
35
+ expect(PoolStatsRegistry.snapshots()).toEqual([
36
+ { pool: 'alive', stats: STATS },
37
+ ]);
38
+ });
39
+
40
+ it('skips a source that returns non-numbers', () => {
41
+ detach.push(
42
+ PoolStatsRegistry.add({
43
+ pool: 'invalid',
44
+ stats: () => ({ ...STATS, max: undefined as unknown as number }),
45
+ }),
46
+ PoolStatsRegistry.add({ pool: 'alive', stats: () => STATS }),
47
+ );
48
+
49
+ expect(PoolStatsRegistry.snapshots()).toEqual([
50
+ { pool: 'alive', stats: STATS },
51
+ ]);
52
+ });
53
+
54
+ it('does not fail scrape when one pool throws', async () => {
55
+ detach.push(
56
+ PoolStatsRegistry.add({
57
+ pool: 'broken',
58
+ stats: () => {
59
+ throw new Error('pool is gone');
60
+ },
61
+ }),
62
+ PoolStatsRegistry.add({ pool: 'alive', stats: () => STATS }),
63
+ );
64
+
65
+ const text = await register.metrics();
66
+
67
+ expect(text).toContain(
68
+ 'db_pool_connections{pool="alive",state="active"} 2',
69
+ );
70
+ expect(text).toContain('db_pool_connections_max{pool="alive"} 10');
71
+ expect(text).not.toContain('pool="broken"');
72
+ });
73
+
74
+ it('does not return a source after detach', () => {
75
+ const remove = PoolStatsRegistry.add({ pool: 'alive', stats: () => STATS });
76
+
77
+ remove();
78
+
79
+ expect(PoolStatsRegistry.snapshots()).toEqual([]);
80
+ });
81
+ });
@@ -0,0 +1,54 @@
1
+ import type { Detach } from './detach';
2
+ import { isObject } from './guards';
3
+ import { ScrapeSourceRegistry } from './scrape-source.registry';
4
+
5
+ export interface PoolStats {
6
+ total: number;
7
+ idle: number;
8
+ active: number;
9
+ waiting: number;
10
+ max: number;
11
+ }
12
+
13
+ export interface PoolStatsSource {
14
+ pool: string;
15
+ stats: () => PoolStats;
16
+ }
17
+
18
+ export interface PoolStatsSnapshot {
19
+ pool: string;
20
+ stats: PoolStats;
21
+ }
22
+
23
+ const STAT_KEYS: readonly (keyof PoolStats)[] = [
24
+ 'total',
25
+ 'idle',
26
+ 'active',
27
+ 'waiting',
28
+ 'max',
29
+ ];
30
+
31
+ const isValidStats = (stats: unknown): stats is PoolStats =>
32
+ isObject(stats) && STAT_KEYS.every((key) => typeof stats[key] === 'number');
33
+
34
+ const isValidSnapshot = (value: unknown): value is PoolStatsSnapshot =>
35
+ isObject(value) &&
36
+ typeof value.pool === 'string' &&
37
+ isValidStats(value.stats);
38
+
39
+ const registry = new ScrapeSourceRegistry(isValidSnapshot);
40
+
41
+ /**
42
+ * Пулы, состояние которых gauge `db_pool_connections*` читают при scrape.
43
+ * Пул, который бросил исключение или вернул не числа, пропускается:
44
+ * см. {@link ScrapeSourceRegistry}
45
+ */
46
+ export class PoolStatsRegistry {
47
+ static add({ pool, stats }: PoolStatsSource): Detach {
48
+ return registry.add(() => ({ pool, stats: stats() }));
49
+ }
50
+
51
+ static snapshots(): PoolStatsSnapshot[] {
52
+ return registry.snapshots();
53
+ }
54
+ }