@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.
- package/dist/index.d.ts +1 -0
- package/dist/index.js +15 -0
- package/dist/index.js.map +1 -1
- package/dist/metrics/call-then.d.ts +30 -0
- package/dist/metrics/call-then.js +91 -0
- package/dist/metrics/call-then.js.map +1 -0
- package/dist/metrics/clock.d.ts +2 -0
- package/dist/metrics/clock.js +9 -0
- package/dist/metrics/clock.js.map +1 -0
- package/dist/metrics/db-client-metrics.d.ts +85 -0
- package/dist/metrics/db-client-metrics.js +164 -0
- package/dist/metrics/db-client-metrics.js.map +1 -0
- package/dist/metrics/db-metric.d.ts +41 -0
- package/dist/metrics/db-metric.js +99 -0
- package/dist/metrics/db-metric.js.map +1 -0
- package/dist/metrics/db-metrics.config.d.ts +7 -0
- package/dist/metrics/db-metrics.config.js +60 -0
- package/dist/metrics/db-metrics.config.js.map +1 -0
- package/dist/metrics/db-metrics.module-base.d.ts +61 -0
- package/dist/metrics/db-metrics.module-base.js +61 -0
- package/dist/metrics/db-metrics.module-base.js.map +1 -0
- package/dist/metrics/db-metrics.providers.d.ts +66 -0
- package/dist/metrics/db-metrics.providers.js +83 -0
- package/dist/metrics/db-metrics.providers.js.map +1 -0
- package/dist/metrics/detach-group.d.ts +19 -0
- package/dist/metrics/detach-group.js +31 -0
- package/dist/metrics/detach-group.js.map +1 -0
- package/dist/metrics/detach.d.ts +24 -0
- package/dist/metrics/detach.js +45 -0
- package/dist/metrics/detach.js.map +1 -0
- package/dist/metrics/entity-operations.recorder.d.ts +17 -0
- package/dist/metrics/entity-operations.recorder.js +28 -0
- package/dist/metrics/entity-operations.recorder.js.map +1 -0
- package/dist/metrics/events.d.ts +11 -0
- package/dist/metrics/events.js +20 -0
- package/dist/metrics/events.js.map +1 -0
- package/dist/metrics/guards.d.ts +12 -0
- package/dist/metrics/guards.js +19 -0
- package/dist/metrics/guards.js.map +1 -0
- package/dist/metrics/index.d.ts +1 -0
- package/dist/metrics/index.js +11 -0
- package/dist/metrics/index.js.map +1 -0
- package/dist/metrics/instrumentation/pg-pool.instrumentation.d.ts +48 -0
- package/dist/metrics/instrumentation/pg-pool.instrumentation.js +117 -0
- package/dist/metrics/instrumentation/pg-pool.instrumentation.js.map +1 -0
- package/dist/metrics/instrumentation/pool-adapters.d.ts +22 -0
- package/dist/metrics/instrumentation/pool-adapters.js +16 -0
- package/dist/metrics/instrumentation/pool-adapters.js.map +1 -0
- package/dist/metrics/instrumentation/pool-close.d.ts +10 -0
- package/dist/metrics/instrumentation/pool-close.js +43 -0
- package/dist/metrics/instrumentation/pool-close.js.map +1 -0
- package/dist/metrics/instrumentation/pool-scope.d.ts +13 -0
- package/dist/metrics/instrumentation/pool-scope.js +3 -0
- package/dist/metrics/instrumentation/pool-scope.js.map +1 -0
- package/dist/metrics/instrumentation/pool.adapter.d.ts +50 -0
- package/dist/metrics/instrumentation/pool.adapter.js +3 -0
- package/dist/metrics/instrumentation/pool.adapter.js.map +1 -0
- package/dist/metrics/instrumentation/pool.recorder.d.ts +74 -0
- package/dist/metrics/instrumentation/pool.recorder.js +125 -0
- package/dist/metrics/instrumentation/pool.recorder.js.map +1 -0
- package/dist/metrics/instrumentation/query-completion.d.ts +12 -0
- package/dist/metrics/instrumentation/query-completion.js +76 -0
- package/dist/metrics/instrumentation/query-completion.js.map +1 -0
- package/dist/metrics/instrumentation/query.instrumentation.d.ts +35 -0
- package/dist/metrics/instrumentation/query.instrumentation.js +85 -0
- package/dist/metrics/instrumentation/query.instrumentation.js.map +1 -0
- package/dist/metrics/instrumentation/tarn-pool.instrumentation.d.ts +44 -0
- package/dist/metrics/instrumentation/tarn-pool.instrumentation.js +95 -0
- package/dist/metrics/instrumentation/tarn-pool.instrumentation.js.map +1 -0
- package/dist/metrics/instrumentation/transaction-tracker.d.ts +32 -0
- package/dist/metrics/instrumentation/transaction-tracker.js +64 -0
- package/dist/metrics/instrumentation/transaction-tracker.js.map +1 -0
- package/dist/metrics/metric-types.d.ts +17 -0
- package/dist/metrics/metric-types.js +3 -0
- package/dist/metrics/metric-types.js.map +1 -0
- package/dist/metrics/metrics.d.ts +82 -0
- package/dist/metrics/metrics.js +269 -0
- package/dist/metrics/metrics.js.map +1 -0
- package/dist/metrics/plugin-kit.d.ts +12 -0
- package/dist/metrics/plugin-kit.js +42 -0
- package/dist/metrics/plugin-kit.js.map +1 -0
- package/dist/metrics/pool-names.d.ts +47 -0
- package/dist/metrics/pool-names.js +44 -0
- package/dist/metrics/pool-names.js.map +1 -0
- package/dist/metrics/pool-stats.registry.d.ts +25 -0
- package/dist/metrics/pool-stats.registry.js +32 -0
- package/dist/metrics/pool-stats.registry.js.map +1 -0
- package/dist/metrics/scrape-source.registry.d.ts +29 -0
- package/dist/metrics/scrape-source.registry.js +55 -0
- package/dist/metrics/scrape-source.registry.js.map +1 -0
- package/dist/metrics/sql.d.ts +34 -0
- package/dist/metrics/sql.js +132 -0
- package/dist/metrics/sql.js.map +1 -0
- package/package.json +2 -2
- package/src/index.ts +1 -0
- package/src/metrics/call-then.ts +134 -0
- package/src/metrics/clock.ts +5 -0
- package/src/metrics/db-client-metrics.spec.ts +1894 -0
- package/src/metrics/db-client-metrics.ts +206 -0
- package/src/metrics/db-metric.spec.ts +185 -0
- package/src/metrics/db-metric.ts +186 -0
- package/src/metrics/db-metrics.config.ts +46 -0
- package/src/metrics/db-metrics.module-base.spec.ts +91 -0
- package/src/metrics/db-metrics.module-base.ts +77 -0
- package/src/metrics/db-metrics.providers.spec.ts +182 -0
- package/src/metrics/db-metrics.providers.ts +134 -0
- package/src/metrics/detach-group.spec.ts +41 -0
- package/src/metrics/detach-group.ts +30 -0
- package/src/metrics/detach.spec.ts +61 -0
- package/src/metrics/detach.ts +57 -0
- package/src/metrics/entity-operations.recorder.ts +26 -0
- package/src/metrics/events.spec.ts +19 -0
- package/src/metrics/events.ts +28 -0
- package/src/metrics/guards.spec.ts +20 -0
- package/src/metrics/guards.ts +19 -0
- package/src/metrics/index.ts +6 -0
- package/src/metrics/instrumentation/pg-pool.instrumentation.ts +177 -0
- package/src/metrics/instrumentation/pool-adapters.ts +35 -0
- package/src/metrics/instrumentation/pool-close.ts +59 -0
- package/src/metrics/instrumentation/pool-guards.spec.ts +318 -0
- package/src/metrics/instrumentation/pool-scope.ts +14 -0
- package/src/metrics/instrumentation/pool.adapter.ts +67 -0
- package/src/metrics/instrumentation/pool.recorder.ts +167 -0
- package/src/metrics/instrumentation/query-completion.spec.ts +209 -0
- package/src/metrics/instrumentation/query-completion.ts +107 -0
- package/src/metrics/instrumentation/query.instrumentation.ts +136 -0
- package/src/metrics/instrumentation/tarn-pool.instrumentation.ts +138 -0
- package/src/metrics/instrumentation/transaction-tracker.ts +103 -0
- package/src/metrics/metric-types.ts +36 -0
- package/src/metrics/metrics.ts +233 -0
- package/src/metrics/plugin-kit.ts +39 -0
- package/src/metrics/pool-names.spec.ts +79 -0
- package/src/metrics/pool-names.ts +77 -0
- package/src/metrics/pool-stats.registry.spec.ts +81 -0
- package/src/metrics/pool-stats.registry.ts +54 -0
- package/src/metrics/public-api.spec.ts +104 -0
- package/src/metrics/scrape-source.registry.spec.ts +59 -0
- package/src/metrics/scrape-source.registry.ts +55 -0
- package/src/metrics/sql.spec.ts +110 -0
- package/src/metrics/sql.ts +172 -0
|
@@ -0,0 +1,1894 @@
|
|
|
1
|
+
/* eslint-disable unicorn/prefer-event-target -- pg и tarn построены на EventEmitter */
|
|
2
|
+
import { Timespan } from '@rsdk/common';
|
|
3
|
+
import type { Histogram } from '@rsdk/core';
|
|
4
|
+
import { register } from '@rsdk/core';
|
|
5
|
+
import { errorMonitor, EventEmitter } from 'node:events';
|
|
6
|
+
// eslint-disable-next-line import/no-extraneous-dependencies -- tarn приходит с knex в корневой node_modules, зависимостью @rsdk/db он не становится
|
|
7
|
+
import { Pool as TarnPool } from 'tarn';
|
|
8
|
+
|
|
9
|
+
import type { PgPoolLike } from './instrumentation/pg-pool.instrumentation';
|
|
10
|
+
import type { QueryableClient } from './instrumentation/query.instrumentation';
|
|
11
|
+
import type { TarnPoolLike } from './instrumentation/tarn-pool.instrumentation';
|
|
12
|
+
import { DbClientMetrics } from './db-client-metrics';
|
|
13
|
+
import type { DbMetricsConfig } from './db-metrics.config';
|
|
14
|
+
import type { Detach } from './detach';
|
|
15
|
+
import { EntityOperationsRecorder } from './entity-operations.recorder';
|
|
16
|
+
import { PoolStatsRegistry } from './pool-stats.registry';
|
|
17
|
+
|
|
18
|
+
const APP = 'svc';
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Ресурс пула в тестах: метка `pool` у него `svc__typeorm`
|
|
22
|
+
*/
|
|
23
|
+
const POOL = 'typeorm';
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Значение метки `pool` для ресурса: `<APP_NAME>__<ресурс>`. Имя
|
|
27
|
+
* приложения `DbClientMetrics` получает в `create`, тест передаёт только
|
|
28
|
+
* ресурс
|
|
29
|
+
*/
|
|
30
|
+
const poolName = (resource: string): string => `${APP}__${resource}`;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Конфиг метрик: `DbClientMetrics` читает из него только порог медленного запроса
|
|
34
|
+
*/
|
|
35
|
+
const config = (slowQueryThresholdMs: number): DbMetricsConfig =>
|
|
36
|
+
({
|
|
37
|
+
slowQueryThreshold: new Timespan(slowQueryThresholdMs, 'ms'),
|
|
38
|
+
}) as DbMetricsConfig;
|
|
39
|
+
|
|
40
|
+
const value = async (
|
|
41
|
+
name: string,
|
|
42
|
+
labels: Record<string, string> = {},
|
|
43
|
+
suffix = '',
|
|
44
|
+
): Promise<number | undefined> => {
|
|
45
|
+
const metric = register.getSingleMetric(name);
|
|
46
|
+
if (!metric) {
|
|
47
|
+
return undefined;
|
|
48
|
+
}
|
|
49
|
+
const { values } = await metric.get();
|
|
50
|
+
|
|
51
|
+
return values.find(
|
|
52
|
+
(x) =>
|
|
53
|
+
((x as { metricName?: string }).metricName ?? name) ===
|
|
54
|
+
`${name}${suffix}` &&
|
|
55
|
+
Object.entries(labels).every(
|
|
56
|
+
([key, expected]) => String(x.labels[key]) === expected,
|
|
57
|
+
),
|
|
58
|
+
)?.value;
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
const histogramCount = (
|
|
62
|
+
name: string,
|
|
63
|
+
labels: Record<string, string> = {},
|
|
64
|
+
): Promise<number | undefined> => value(name, labels, '_count');
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Submittable-объект по контракту `pg`: клиент вызывает `submit`, об ошибке
|
|
68
|
+
* запроса сообщает через `handleError`, а объект — потребителю событиями.
|
|
69
|
+
* Как QueryStream: ошибку эмитит всегда, текст лежит в `cursor.text`
|
|
70
|
+
*/
|
|
71
|
+
class FakeSubmittable extends EventEmitter {
|
|
72
|
+
submitted = false;
|
|
73
|
+
readonly cursor: { text: string };
|
|
74
|
+
|
|
75
|
+
constructor(text: string) {
|
|
76
|
+
super();
|
|
77
|
+
this.cursor = { text };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
submit(): void {
|
|
81
|
+
this.submitted = true;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
handleError(error: unknown): void {
|
|
85
|
+
this.emit('error', error);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Как pg-cursor: эмитит `error`, только если на него подписаны,
|
|
91
|
+
* и после ошибки не эмитит `end`
|
|
92
|
+
*/
|
|
93
|
+
class FakeCursor extends FakeSubmittable {
|
|
94
|
+
override handleError(error: unknown): void {
|
|
95
|
+
if (this.listenerCount('error') > 0) {
|
|
96
|
+
this.emit('error', error);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const abortError = (): Error =>
|
|
102
|
+
Object.assign(new Error('The operation was aborted'), {
|
|
103
|
+
name: 'AbortError',
|
|
104
|
+
code: 'ABORT_ERR',
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
class FakeClient extends EventEmitter implements QueryableClient {
|
|
108
|
+
/**
|
|
109
|
+
* Как у `pg.Client`: `true` после подключения
|
|
110
|
+
*/
|
|
111
|
+
_connected = true;
|
|
112
|
+
responses: Record<string, unknown> = {};
|
|
113
|
+
errors: Record<string, unknown> = {};
|
|
114
|
+
|
|
115
|
+
query(sql: string | { text: string } | FakeSubmittable, ...rest: any[]): any {
|
|
116
|
+
if (sql instanceof FakeSubmittable) {
|
|
117
|
+
sql.submit();
|
|
118
|
+
return sql;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const text = typeof sql === 'string' ? sql : sql.text;
|
|
122
|
+
const callback = rest.find((x) => typeof x === 'function');
|
|
123
|
+
const error = this.errors[text];
|
|
124
|
+
const response = this.responses[text] ?? { command: text.split(' ')[0] };
|
|
125
|
+
|
|
126
|
+
if (callback) {
|
|
127
|
+
setImmediate(() => callback(error, error ? undefined : response));
|
|
128
|
+
return undefined;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
return error ? Promise.reject(error) : Promise.resolve(response);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
class FakePgPool extends EventEmitter implements PgPoolLike {
|
|
136
|
+
totalCount = 0;
|
|
137
|
+
idleCount = 0;
|
|
138
|
+
waitingCount = 0;
|
|
139
|
+
options = { max: 10 };
|
|
140
|
+
_clients: QueryableClient[] = [];
|
|
141
|
+
nextError: Error | undefined;
|
|
142
|
+
endError: Error | undefined;
|
|
143
|
+
ending = false;
|
|
144
|
+
|
|
145
|
+
connect(callback?: (...args: any[]) => void): any {
|
|
146
|
+
const error = this.nextError;
|
|
147
|
+
const client = new FakeClient();
|
|
148
|
+
if (!error) {
|
|
149
|
+
this._clients.push(client);
|
|
150
|
+
this.emit('connect', client);
|
|
151
|
+
this.emit('acquire', client);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
if (callback) {
|
|
155
|
+
setImmediate(() => callback(error, client));
|
|
156
|
+
return undefined;
|
|
157
|
+
}
|
|
158
|
+
return error ? Promise.reject(error) : Promise.resolve(client);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Как `pg-pool`: закрывает все соединения, о каждом сообщает `remove`,
|
|
163
|
+
* затем завершает callback или promise
|
|
164
|
+
*/
|
|
165
|
+
end(callback?: (error?: Error) => void): any {
|
|
166
|
+
if (this.ending) {
|
|
167
|
+
const twice = new Error('Called end on pool more than once');
|
|
168
|
+
|
|
169
|
+
return callback ? callback(twice) : Promise.reject(twice);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
this.ending = true;
|
|
173
|
+
|
|
174
|
+
const error = this.endError;
|
|
175
|
+
const done = new Promise<void>((resolve) => setImmediate(resolve)).then(
|
|
176
|
+
() => {
|
|
177
|
+
for (const client of this._clients.splice(0)) {
|
|
178
|
+
this.emit('remove', client);
|
|
179
|
+
}
|
|
180
|
+
},
|
|
181
|
+
);
|
|
182
|
+
|
|
183
|
+
if (callback) {
|
|
184
|
+
void done.then(() => callback(error));
|
|
185
|
+
return undefined;
|
|
186
|
+
}
|
|
187
|
+
return done.then(() => {
|
|
188
|
+
if (error) {
|
|
189
|
+
throw error;
|
|
190
|
+
}
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
class FakeTarnPool extends EventEmitter implements TarnPoolLike {
|
|
196
|
+
max = 7;
|
|
197
|
+
used: { resource: FakeClient }[] = [];
|
|
198
|
+
free: { resource: FakeClient }[] = [];
|
|
199
|
+
pending = 0;
|
|
200
|
+
|
|
201
|
+
numUsed(): number {
|
|
202
|
+
return this.used.length;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
numFree(): number {
|
|
206
|
+
return this.free.length;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
numPendingAcquires(): number {
|
|
210
|
+
return this.pending;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Как tarn: закрывает все соединения, о каждом сообщает `destroySuccess`
|
|
215
|
+
*/
|
|
216
|
+
async destroy(): Promise<void> {
|
|
217
|
+
await new Promise(setImmediate);
|
|
218
|
+
for (const { resource } of [
|
|
219
|
+
...this.free.splice(0),
|
|
220
|
+
...this.used.splice(0),
|
|
221
|
+
]) {
|
|
222
|
+
this.emit('destroySuccess', 0, resource);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Ошибка запроса так, как её доставляет `pg`: через `handleError`
|
|
229
|
+
*/
|
|
230
|
+
const failWith = (query: FakeSubmittable, error: unknown) => (): void =>
|
|
231
|
+
query.handleError(error);
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Что бросил `emit('error')` без обработчиков: саму ошибку или, если она
|
|
235
|
+
* не из этого realm (как в jest), обёртку ERR_UNHANDLED_ERROR с ней в `context`
|
|
236
|
+
*/
|
|
237
|
+
const thrownBy = (fn: () => void): unknown => {
|
|
238
|
+
try {
|
|
239
|
+
fn();
|
|
240
|
+
} catch (error) {
|
|
241
|
+
return (error as { context?: unknown }).context ?? error;
|
|
242
|
+
}
|
|
243
|
+
return undefined;
|
|
244
|
+
};
|
|
245
|
+
|
|
246
|
+
const counter = async (
|
|
247
|
+
name: string,
|
|
248
|
+
labels: Record<string, string>,
|
|
249
|
+
): Promise<number> => (await value(name, labels)) ?? 0;
|
|
250
|
+
|
|
251
|
+
const snapshot = async (
|
|
252
|
+
pool: string,
|
|
253
|
+
): Promise<{ closed: number; rollback: number }> => ({
|
|
254
|
+
closed: await counter('db_pool_connections_closed_total', { pool }),
|
|
255
|
+
rollback: await counter('db_transactions_total', { result: 'rollback' }),
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Ряды gauge с этим пулом: после detach их быть не должно
|
|
260
|
+
*/
|
|
261
|
+
const gaugeRows = async (name: string, pool: string): Promise<number> => {
|
|
262
|
+
const { values } = await register.getSingleMetric(name)!.get();
|
|
263
|
+
|
|
264
|
+
return values.filter((x) => x.labels.pool === pool).length;
|
|
265
|
+
};
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* Ряды пула во всех gauge с label `pool`: после итога их быть не должно
|
|
269
|
+
*/
|
|
270
|
+
const rowsOf = async (pool: string): Promise<number> =>
|
|
271
|
+
(await gaugeRows('db_transactions_active', pool)) +
|
|
272
|
+
(await gaugeRows('db_client_queries_active', pool)) +
|
|
273
|
+
(await gaugeRows('db_pool_connections_max', pool));
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* Пулы, которые сейчас отдают состояние для `db_pool_connections*`
|
|
277
|
+
*/
|
|
278
|
+
const registeredPools = (): string[] =>
|
|
279
|
+
PoolStatsRegistry.snapshots().map(({ pool }) => pool);
|
|
280
|
+
|
|
281
|
+
const results = async (): Promise<{ commit: number; rollback: number }> => ({
|
|
282
|
+
commit: await counter('db_transactions_total', { result: 'commit' }),
|
|
283
|
+
rollback: await counter('db_transactions_total', { result: 'rollback' }),
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
const poolErrors = (pool: string): Promise<number> =>
|
|
287
|
+
counter('db_pool_errors_total', { pool });
|
|
288
|
+
|
|
289
|
+
const createdTotal = (pool: string): Promise<number> =>
|
|
290
|
+
counter('db_pool_connections_created_total', { pool });
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Как `pg.Client` при обрыве: `error` дважды подряд
|
|
294
|
+
*/
|
|
295
|
+
const terminate = (connection: EventEmitter): void => {
|
|
296
|
+
connection.emit('error', new Error('terminating connection'));
|
|
297
|
+
connection.emit('error', new Error('Connection terminated unexpectedly'));
|
|
298
|
+
};
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* Соединение knex: knex слушает у него `error`
|
|
302
|
+
*/
|
|
303
|
+
const knexConnection = (): FakeClient => {
|
|
304
|
+
const connection = new FakeClient();
|
|
305
|
+
|
|
306
|
+
connection.on('error', () => {});
|
|
307
|
+
return connection;
|
|
308
|
+
};
|
|
309
|
+
|
|
310
|
+
const negativeValues = async (name: string): Promise<number[]> => {
|
|
311
|
+
const { values } = await register.getSingleMetric(name)!.get();
|
|
312
|
+
|
|
313
|
+
return values.map((x) => x.value).filter((x) => x < 0);
|
|
314
|
+
};
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* Detach пула, который должен был пройти проверку адаптера
|
|
318
|
+
*/
|
|
319
|
+
const instrumented = (detachPool: Detach | undefined): Detach => {
|
|
320
|
+
if (!detachPool) {
|
|
321
|
+
throw new Error('the pool did not pass the adapter check');
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
return detachPool;
|
|
325
|
+
};
|
|
326
|
+
|
|
327
|
+
describe('DbClientMetrics', () => {
|
|
328
|
+
let metrics: DbClientMetrics;
|
|
329
|
+
const detach: (() => void)[] = [];
|
|
330
|
+
|
|
331
|
+
const logger = { warn: jest.fn() };
|
|
332
|
+
|
|
333
|
+
beforeEach(() => {
|
|
334
|
+
register.resetMetrics();
|
|
335
|
+
logger.warn.mockClear();
|
|
336
|
+
metrics = DbClientMetrics.create(config(50), APP);
|
|
337
|
+
});
|
|
338
|
+
|
|
339
|
+
const instrumentPg = (pool: unknown, name: string): Detach =>
|
|
340
|
+
instrumented(
|
|
341
|
+
metrics.instrumentPool('pg', pool, name, logger, {
|
|
342
|
+
instrumentQueries: true,
|
|
343
|
+
}),
|
|
344
|
+
);
|
|
345
|
+
|
|
346
|
+
const instrumentTarn = (
|
|
347
|
+
pool: unknown,
|
|
348
|
+
name: string,
|
|
349
|
+
options: { instrumentQueries: boolean },
|
|
350
|
+
): Detach =>
|
|
351
|
+
instrumented(metrics.instrumentPool('tarn', pool, name, logger, options));
|
|
352
|
+
|
|
353
|
+
afterEach(() => {
|
|
354
|
+
for (const fn of detach.splice(0)) fn();
|
|
355
|
+
});
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* Соединение, открытое пулом до подключения метрик: инструментирование
|
|
359
|
+
* пула оборачивает и его
|
|
360
|
+
*/
|
|
361
|
+
const instrumentClient = (client: QueryableClient, name = POOL): void => {
|
|
362
|
+
const pool = new FakePgPool();
|
|
363
|
+
|
|
364
|
+
pool._clients.push(Object.assign(client, { _connected: true }));
|
|
365
|
+
detach.push(instrumentPg(pool, name));
|
|
366
|
+
};
|
|
367
|
+
|
|
368
|
+
describe('pg-pool', () => {
|
|
369
|
+
let pool: FakePgPool;
|
|
370
|
+
|
|
371
|
+
beforeEach(() => {
|
|
372
|
+
pool = new FakePgPool();
|
|
373
|
+
detach.push(instrumentPg(pool, POOL));
|
|
374
|
+
});
|
|
375
|
+
|
|
376
|
+
it('reports pool state on scrape', async () => {
|
|
377
|
+
// Как в pg-pool: `totalCount` — длина `_clients`, все клиенты подключены
|
|
378
|
+
pool._clients.push(...Array.from({ length: 5 }, () => new FakeClient()));
|
|
379
|
+
Object.assign(pool, { totalCount: 5, idleCount: 2, waitingCount: 3 });
|
|
380
|
+
|
|
381
|
+
expect(await value('db_pool_connections', { state: 'total' })).toBe(5);
|
|
382
|
+
expect(await value('db_pool_connections', { state: 'idle' })).toBe(2);
|
|
383
|
+
expect(await value('db_pool_connections', { state: 'active' })).toBe(3);
|
|
384
|
+
expect(await value('db_pool_connections', { state: 'waiting' })).toBe(3);
|
|
385
|
+
expect(
|
|
386
|
+
await value('db_pool_connections_max', { pool: poolName(POOL) }),
|
|
387
|
+
).toBe(10);
|
|
388
|
+
});
|
|
389
|
+
|
|
390
|
+
it('removes the pool from gauges after detach', async () => {
|
|
391
|
+
for (const fn of detach.splice(0)) fn();
|
|
392
|
+
|
|
393
|
+
expect(await value('db_pool_connections', { pool: poolName(POOL) })).toBe(
|
|
394
|
+
undefined,
|
|
395
|
+
);
|
|
396
|
+
});
|
|
397
|
+
|
|
398
|
+
it('measures connection acquire, creation, usage and close', async () => {
|
|
399
|
+
const client = await pool.connect();
|
|
400
|
+
|
|
401
|
+
pool.emit('release', undefined, client);
|
|
402
|
+
pool.emit('remove', client);
|
|
403
|
+
|
|
404
|
+
expect(
|
|
405
|
+
await histogramCount('db_pool_acquire_duration_seconds', {
|
|
406
|
+
pool: poolName(POOL),
|
|
407
|
+
}),
|
|
408
|
+
).toBe(1);
|
|
409
|
+
expect(
|
|
410
|
+
await value('db_pool_connections_created_total', {
|
|
411
|
+
pool: poolName(POOL),
|
|
412
|
+
}),
|
|
413
|
+
).toBe(1);
|
|
414
|
+
expect(
|
|
415
|
+
await histogramCount('db_pool_connection_usage_seconds', {
|
|
416
|
+
pool: poolName(POOL),
|
|
417
|
+
}),
|
|
418
|
+
).toBe(1);
|
|
419
|
+
expect(
|
|
420
|
+
await value('db_pool_connections_closed_total', {
|
|
421
|
+
pool: poolName(POOL),
|
|
422
|
+
}),
|
|
423
|
+
).toBe(1);
|
|
424
|
+
});
|
|
425
|
+
|
|
426
|
+
it('measures the callback form of connect too', async () => {
|
|
427
|
+
await new Promise((resolve) => pool.connect(resolve));
|
|
428
|
+
|
|
429
|
+
expect(
|
|
430
|
+
await histogramCount('db_pool_acquire_duration_seconds', {
|
|
431
|
+
pool: poolName(POOL),
|
|
432
|
+
}),
|
|
433
|
+
).toBe(1);
|
|
434
|
+
});
|
|
435
|
+
|
|
436
|
+
it.each([
|
|
437
|
+
['waiting in the queue', 'timeout exceeded when trying to connect'],
|
|
438
|
+
[
|
|
439
|
+
'opening a new connection',
|
|
440
|
+
'Connection terminated due to connection timeout',
|
|
441
|
+
],
|
|
442
|
+
])('counts connection acquire timeouts: %s', async (_case, message) => {
|
|
443
|
+
pool.nextError = new Error(message);
|
|
444
|
+
|
|
445
|
+
await expect(pool.connect()).rejects.toThrow(message);
|
|
446
|
+
expect(
|
|
447
|
+
await value('db_pool_acquire_timeouts_total', { pool: poolName(POOL) }),
|
|
448
|
+
).toBe(1);
|
|
449
|
+
});
|
|
450
|
+
|
|
451
|
+
it('does not count another connect error as a timeout', async () => {
|
|
452
|
+
pool.nextError = new Error('connect ECONNREFUSED 127.0.0.1:5432');
|
|
453
|
+
|
|
454
|
+
await expect(pool.connect()).rejects.toThrow();
|
|
455
|
+
expect(
|
|
456
|
+
(await value('db_pool_acquire_timeouts_total', {
|
|
457
|
+
pool: poolName(POOL),
|
|
458
|
+
})) ?? 0,
|
|
459
|
+
).toBe(0);
|
|
460
|
+
});
|
|
461
|
+
|
|
462
|
+
it('instruments connections opened before metrics were attached', async () => {
|
|
463
|
+
const lateMetricsPool = new FakePgPool();
|
|
464
|
+
const existing = new FakeClient();
|
|
465
|
+
|
|
466
|
+
lateMetricsPool._clients.push(existing);
|
|
467
|
+
detach.push(instrumentPg(lateMetricsPool, 'late'));
|
|
468
|
+
|
|
469
|
+
await existing.query('SELECT 1');
|
|
470
|
+
|
|
471
|
+
expect(
|
|
472
|
+
await histogramCount('db_client_operation_duration_seconds', {
|
|
473
|
+
operation: 'SELECT',
|
|
474
|
+
}),
|
|
475
|
+
).toBe(1);
|
|
476
|
+
expect(
|
|
477
|
+
await value('db_pool_connections_created_total', {
|
|
478
|
+
pool: poolName('late'),
|
|
479
|
+
}),
|
|
480
|
+
).toBe(1);
|
|
481
|
+
});
|
|
482
|
+
|
|
483
|
+
it('restores the original connect on detach', () => {
|
|
484
|
+
for (const fn of detach.splice(0)) fn();
|
|
485
|
+
|
|
486
|
+
expect(Object.hasOwn(pool, 'connect')).toBe(false);
|
|
487
|
+
});
|
|
488
|
+
});
|
|
489
|
+
|
|
490
|
+
describe('queries', () => {
|
|
491
|
+
let client: FakeClient;
|
|
492
|
+
|
|
493
|
+
beforeEach(() => {
|
|
494
|
+
client = new FakeClient();
|
|
495
|
+
instrumentClient(client);
|
|
496
|
+
});
|
|
497
|
+
|
|
498
|
+
it('measures duration by operation and status', async () => {
|
|
499
|
+
await client.query('SELECT 1');
|
|
500
|
+
await client.query({ text: 'INSERT INTO cat VALUES (1)' });
|
|
501
|
+
|
|
502
|
+
expect(
|
|
503
|
+
await histogramCount('db_client_operation_duration_seconds', {
|
|
504
|
+
operation: 'SELECT',
|
|
505
|
+
status: 'ok',
|
|
506
|
+
}),
|
|
507
|
+
).toBe(1);
|
|
508
|
+
expect(
|
|
509
|
+
await histogramCount('db_client_operation_duration_seconds', {
|
|
510
|
+
operation: 'INSERT',
|
|
511
|
+
status: 'ok',
|
|
512
|
+
}),
|
|
513
|
+
).toBe(1);
|
|
514
|
+
});
|
|
515
|
+
|
|
516
|
+
it('counts errors by SQLSTATE', async () => {
|
|
517
|
+
client.errors['INSERT INTO cat'] = Object.assign(new Error('dup'), {
|
|
518
|
+
code: '23505',
|
|
519
|
+
});
|
|
520
|
+
|
|
521
|
+
await expect(client.query('INSERT INTO cat')).rejects.toThrow('dup');
|
|
522
|
+
expect(
|
|
523
|
+
await value('db_client_query_errors_total', { code: '23505' }),
|
|
524
|
+
).toBe(1);
|
|
525
|
+
expect(
|
|
526
|
+
await histogramCount('db_client_operation_duration_seconds', {
|
|
527
|
+
operation: 'INSERT',
|
|
528
|
+
status: 'error',
|
|
529
|
+
}),
|
|
530
|
+
).toBe(1);
|
|
531
|
+
});
|
|
532
|
+
|
|
533
|
+
it('counts active queries', async () => {
|
|
534
|
+
let resolve!: (value: unknown) => void;
|
|
535
|
+
const pending = new Promise((r) => (resolve = r));
|
|
536
|
+
const slowClient = { query: (): Promise<unknown> => pending };
|
|
537
|
+
|
|
538
|
+
instrumentClient(slowClient, 'slow');
|
|
539
|
+
|
|
540
|
+
const query = slowClient.query();
|
|
541
|
+
|
|
542
|
+
expect(
|
|
543
|
+
await value('db_client_queries_active', { pool: poolName('slow') }),
|
|
544
|
+
).toBe(1);
|
|
545
|
+
|
|
546
|
+
resolve({});
|
|
547
|
+
await query;
|
|
548
|
+
await new Promise(setImmediate);
|
|
549
|
+
expect(
|
|
550
|
+
await value('db_client_queries_active', { pool: poolName('slow') }),
|
|
551
|
+
).toBe(0);
|
|
552
|
+
});
|
|
553
|
+
|
|
554
|
+
it('counts slow queries', async () => {
|
|
555
|
+
const slowClient = {
|
|
556
|
+
query: (): Promise<unknown> =>
|
|
557
|
+
new Promise((resolve) => setTimeout(resolve, 60)),
|
|
558
|
+
};
|
|
559
|
+
|
|
560
|
+
instrumentClient(slowClient);
|
|
561
|
+
|
|
562
|
+
await slowClient.query();
|
|
563
|
+
await new Promise(setImmediate);
|
|
564
|
+
|
|
565
|
+
expect(
|
|
566
|
+
await value('db_client_slow_queries_total', { operation: 'OTHER' }),
|
|
567
|
+
).toBe(1);
|
|
568
|
+
});
|
|
569
|
+
|
|
570
|
+
it('measures the callback form of query too', async () => {
|
|
571
|
+
await new Promise((resolve) =>
|
|
572
|
+
client.query({ text: 'SELECT 1' }, resolve),
|
|
573
|
+
);
|
|
574
|
+
|
|
575
|
+
expect(
|
|
576
|
+
await histogramCount('db_client_operation_duration_seconds', {
|
|
577
|
+
operation: 'SELECT',
|
|
578
|
+
}),
|
|
579
|
+
).toBe(1);
|
|
580
|
+
});
|
|
581
|
+
|
|
582
|
+
it('does not wrap a client twice', async () => {
|
|
583
|
+
instrumentClient(client);
|
|
584
|
+
await client.query('SELECT 1');
|
|
585
|
+
|
|
586
|
+
expect(
|
|
587
|
+
await histogramCount('db_client_operation_duration_seconds', {
|
|
588
|
+
operation: 'SELECT',
|
|
589
|
+
}),
|
|
590
|
+
).toBe(1);
|
|
591
|
+
});
|
|
592
|
+
});
|
|
593
|
+
|
|
594
|
+
describe('transactions', () => {
|
|
595
|
+
let client: FakeClient;
|
|
596
|
+
|
|
597
|
+
beforeEach(() => {
|
|
598
|
+
client = new FakeClient();
|
|
599
|
+
instrumentClient(client);
|
|
600
|
+
});
|
|
601
|
+
|
|
602
|
+
it('commit', async () => {
|
|
603
|
+
await client.query('START TRANSACTION');
|
|
604
|
+
expect(
|
|
605
|
+
await value('db_transactions_active', { pool: poolName(POOL) }),
|
|
606
|
+
).toBe(1);
|
|
607
|
+
|
|
608
|
+
await client.query('SAVEPOINT typeorm_1');
|
|
609
|
+
await client.query('ROLLBACK TO SAVEPOINT typeorm_1');
|
|
610
|
+
await client.query('COMMIT');
|
|
611
|
+
|
|
612
|
+
expect(
|
|
613
|
+
await value('db_transactions_active', { pool: poolName(POOL) }),
|
|
614
|
+
).toBe(0);
|
|
615
|
+
expect(await value('db_transactions_total', { result: 'commit' })).toBe(
|
|
616
|
+
1,
|
|
617
|
+
);
|
|
618
|
+
expect(
|
|
619
|
+
await histogramCount('db_transaction_duration_seconds', {
|
|
620
|
+
result: 'commit',
|
|
621
|
+
}),
|
|
622
|
+
).toBe(1);
|
|
623
|
+
});
|
|
624
|
+
|
|
625
|
+
it('rollback', async () => {
|
|
626
|
+
await client.query('BEGIN;');
|
|
627
|
+
await client.query('ROLLBACK');
|
|
628
|
+
|
|
629
|
+
expect(await value('db_transactions_total', { result: 'rollback' })).toBe(
|
|
630
|
+
1,
|
|
631
|
+
);
|
|
632
|
+
});
|
|
633
|
+
|
|
634
|
+
it('counts COMMIT of an aborted transaction as a rollback', async () => {
|
|
635
|
+
client.responses.COMMIT = { command: 'ROLLBACK' };
|
|
636
|
+
|
|
637
|
+
await client.query('BEGIN');
|
|
638
|
+
await client.query('COMMIT');
|
|
639
|
+
|
|
640
|
+
expect(await value('db_transactions_total', { result: 'rollback' })).toBe(
|
|
641
|
+
1,
|
|
642
|
+
);
|
|
643
|
+
});
|
|
644
|
+
|
|
645
|
+
it('counts a failed COMMIT as a rollback', async () => {
|
|
646
|
+
client.errors.COMMIT = Object.assign(new Error('serialization'), {
|
|
647
|
+
code: '40001',
|
|
648
|
+
});
|
|
649
|
+
|
|
650
|
+
await client.query('BEGIN');
|
|
651
|
+
await expect(client.query('COMMIT')).rejects.toThrow();
|
|
652
|
+
|
|
653
|
+
expect(await value('db_transactions_total', { result: 'rollback' })).toBe(
|
|
654
|
+
1,
|
|
655
|
+
);
|
|
656
|
+
});
|
|
657
|
+
|
|
658
|
+
it('counts closing a connection with an open transaction as a rollback', async () => {
|
|
659
|
+
const pool = new FakePgPool();
|
|
660
|
+
|
|
661
|
+
detach.push(instrumentPg(pool, 'tx-close'));
|
|
662
|
+
const pooled = await pool.connect();
|
|
663
|
+
|
|
664
|
+
await pooled.query('BEGIN');
|
|
665
|
+
pool.emit('remove', pooled);
|
|
666
|
+
|
|
667
|
+
expect(
|
|
668
|
+
await value('db_transactions_active', { pool: poolName('tx-close') }),
|
|
669
|
+
).toBe(0);
|
|
670
|
+
expect(await value('db_transactions_total', { result: 'rollback' })).toBe(
|
|
671
|
+
1,
|
|
672
|
+
);
|
|
673
|
+
});
|
|
674
|
+
});
|
|
675
|
+
|
|
676
|
+
describe('tarn', () => {
|
|
677
|
+
let pool: FakeTarnPool;
|
|
678
|
+
|
|
679
|
+
beforeEach(() => {
|
|
680
|
+
pool = new FakeTarnPool();
|
|
681
|
+
detach.push(
|
|
682
|
+
instrumentTarn(pool, 'mikro-orm', { instrumentQueries: true }),
|
|
683
|
+
);
|
|
684
|
+
});
|
|
685
|
+
|
|
686
|
+
it('reports pool state on scrape', async () => {
|
|
687
|
+
pool.used.push({ resource: new FakeClient() });
|
|
688
|
+
pool.free.push(
|
|
689
|
+
{ resource: new FakeClient() },
|
|
690
|
+
{ resource: new FakeClient() },
|
|
691
|
+
);
|
|
692
|
+
pool.pending = 4;
|
|
693
|
+
|
|
694
|
+
const labels = { pool: poolName('mikro-orm') };
|
|
695
|
+
|
|
696
|
+
expect(
|
|
697
|
+
await value('db_pool_connections', { ...labels, state: 'total' }),
|
|
698
|
+
).toBe(3);
|
|
699
|
+
expect(
|
|
700
|
+
await value('db_pool_connections', { ...labels, state: 'idle' }),
|
|
701
|
+
).toBe(2);
|
|
702
|
+
expect(
|
|
703
|
+
await value('db_pool_connections', { ...labels, state: 'active' }),
|
|
704
|
+
).toBe(1);
|
|
705
|
+
expect(
|
|
706
|
+
await value('db_pool_connections', { ...labels, state: 'waiting' }),
|
|
707
|
+
).toBe(4);
|
|
708
|
+
expect(await value('db_pool_connections_max', labels)).toBe(7);
|
|
709
|
+
});
|
|
710
|
+
|
|
711
|
+
it('measures the connection lifecycle', async () => {
|
|
712
|
+
const resource = new FakeClient();
|
|
713
|
+
const labels = { pool: poolName('mikro-orm') };
|
|
714
|
+
|
|
715
|
+
pool.emit('createSuccess', 1, resource);
|
|
716
|
+
pool.emit('acquireRequest', 2);
|
|
717
|
+
pool.emit('acquireSuccess', 2, resource);
|
|
718
|
+
await resource.query('SELECT 1');
|
|
719
|
+
pool.emit('release', resource);
|
|
720
|
+
|
|
721
|
+
// knex слушает error у своих соединений
|
|
722
|
+
resource.on('error', () => {});
|
|
723
|
+
resource.emit('error', new Error('terminated'));
|
|
724
|
+
pool.emit('destroySuccess', 3, resource);
|
|
725
|
+
|
|
726
|
+
expect(await value('db_pool_connections_created_total', labels)).toBe(1);
|
|
727
|
+
expect(
|
|
728
|
+
await histogramCount('db_pool_acquire_duration_seconds', labels),
|
|
729
|
+
).toBe(1);
|
|
730
|
+
expect(
|
|
731
|
+
await histogramCount('db_pool_connection_usage_seconds', labels),
|
|
732
|
+
).toBe(1);
|
|
733
|
+
expect(await value('db_pool_errors_total', labels)).toBe(1);
|
|
734
|
+
expect(await value('db_pool_connections_closed_total', labels)).toBe(1);
|
|
735
|
+
expect(
|
|
736
|
+
await histogramCount('db_client_operation_duration_seconds', {
|
|
737
|
+
operation: 'SELECT',
|
|
738
|
+
}),
|
|
739
|
+
).toBe(1);
|
|
740
|
+
});
|
|
741
|
+
|
|
742
|
+
it('counts a connection whose destroyer failed as closed', async () => {
|
|
743
|
+
const resource = new FakeClient();
|
|
744
|
+
const labels = { pool: poolName('mikro-orm') };
|
|
745
|
+
|
|
746
|
+
pool.emit('createSuccess', 1, resource);
|
|
747
|
+
await resource.query('BEGIN');
|
|
748
|
+
pool.emit('destroyFail', 2, resource, new Error('destroy timeout'));
|
|
749
|
+
|
|
750
|
+
expect(await value('db_pool_connections_closed_total', labels)).toBe(1);
|
|
751
|
+
expect(await value('db_transactions_active', labels)).toBe(0);
|
|
752
|
+
expect(await value('db_transactions_total', { result: 'rollback' })).toBe(
|
|
753
|
+
1,
|
|
754
|
+
);
|
|
755
|
+
});
|
|
756
|
+
|
|
757
|
+
it('counts connection acquire timeouts of a real tarn', async () => {
|
|
758
|
+
// У TimeoutError из tarn `name === 'Error'`: узнать его можно только по классу
|
|
759
|
+
let created = 0;
|
|
760
|
+
const tarn = new TarnPool({
|
|
761
|
+
create: (
|
|
762
|
+
callback: (error: Error | null, resource: object) => void,
|
|
763
|
+
): void => callback(null, { id: ++created }),
|
|
764
|
+
destroy: (): void => {},
|
|
765
|
+
min: 0,
|
|
766
|
+
max: 1,
|
|
767
|
+
acquireTimeoutMillis: 50,
|
|
768
|
+
});
|
|
769
|
+
|
|
770
|
+
detach.push(instrumentTarn(tarn, 'tarn', { instrumentQueries: false }));
|
|
771
|
+
|
|
772
|
+
const held = await tarn.acquire().promise;
|
|
773
|
+
|
|
774
|
+
try {
|
|
775
|
+
await expect(tarn.acquire().promise).rejects.toThrow();
|
|
776
|
+
expect(
|
|
777
|
+
await value('db_pool_acquire_timeouts_total', {
|
|
778
|
+
pool: poolName('tarn'),
|
|
779
|
+
}),
|
|
780
|
+
).toBe(1);
|
|
781
|
+
} finally {
|
|
782
|
+
tarn.release(held);
|
|
783
|
+
await tarn.destroy();
|
|
784
|
+
}
|
|
785
|
+
});
|
|
786
|
+
|
|
787
|
+
it('leaves connection query untouched without instrumentQueries', () => {
|
|
788
|
+
const resource = new FakeClient();
|
|
789
|
+
const original = resource.query;
|
|
790
|
+
const otherPool = new FakeTarnPool();
|
|
791
|
+
|
|
792
|
+
detach.push(
|
|
793
|
+
instrumentTarn(otherPool, 'mysql', { instrumentQueries: false }),
|
|
794
|
+
);
|
|
795
|
+
|
|
796
|
+
otherPool.emit('createSuccess', 1, resource);
|
|
797
|
+
|
|
798
|
+
expect(resource.query).toBe(original);
|
|
799
|
+
});
|
|
800
|
+
});
|
|
801
|
+
|
|
802
|
+
describe('submittable queries (QueryStream, Cursor)', () => {
|
|
803
|
+
let client: FakeClient;
|
|
804
|
+
|
|
805
|
+
beforeEach(() => {
|
|
806
|
+
client = new FakeClient();
|
|
807
|
+
instrumentClient(client);
|
|
808
|
+
});
|
|
809
|
+
|
|
810
|
+
it('classifies by the text from cursor.text', async () => {
|
|
811
|
+
const stream = client.query(new FakeSubmittable('SELECT * FROM cat'));
|
|
812
|
+
|
|
813
|
+
stream.emit('end');
|
|
814
|
+
|
|
815
|
+
expect(
|
|
816
|
+
await histogramCount('db_client_operation_duration_seconds', {
|
|
817
|
+
operation: 'SELECT',
|
|
818
|
+
status: 'ok',
|
|
819
|
+
}),
|
|
820
|
+
).toBe(1);
|
|
821
|
+
});
|
|
822
|
+
|
|
823
|
+
it('surfaces an unhandled error the same way as without metrics', async () => {
|
|
824
|
+
const error = new Error('relation does not exist');
|
|
825
|
+
const plain = new FakeSubmittable('SELECT * FROM missing');
|
|
826
|
+
const instrumented = client.query(
|
|
827
|
+
new FakeSubmittable('SELECT * FROM missing'),
|
|
828
|
+
);
|
|
829
|
+
|
|
830
|
+
expect(thrownBy(failWith(plain, error))).toBe(error);
|
|
831
|
+
expect(thrownBy(failWith(instrumented, error))).toBe(error);
|
|
832
|
+
expect(
|
|
833
|
+
await histogramCount('db_client_operation_duration_seconds', {
|
|
834
|
+
operation: 'SELECT',
|
|
835
|
+
status: 'error',
|
|
836
|
+
}),
|
|
837
|
+
).toBe(1);
|
|
838
|
+
});
|
|
839
|
+
|
|
840
|
+
it('surfaces an unhandled stream error the same way as without metrics', () => {
|
|
841
|
+
// Так QueryStream сообщает об ошибке: destroy(error) и emit('error')
|
|
842
|
+
const error = new Error('stream failed');
|
|
843
|
+
const plain = new FakeSubmittable('SELECT 1');
|
|
844
|
+
const instrumented = client.query(new FakeSubmittable('SELECT 1'));
|
|
845
|
+
|
|
846
|
+
expect(thrownBy(() => plain.emit('error', error))).toBe(error);
|
|
847
|
+
expect(thrownBy(() => instrumented.emit('error', error))).toBe(error);
|
|
848
|
+
});
|
|
849
|
+
|
|
850
|
+
it('delivers an error to its handler and does not throw', () => {
|
|
851
|
+
const error = new Error('relation does not exist');
|
|
852
|
+
const received: unknown[] = [];
|
|
853
|
+
const stream = client.query(new FakeSubmittable('SELECT 1'));
|
|
854
|
+
|
|
855
|
+
stream.on('error', (e: unknown) => received.push(e));
|
|
856
|
+
|
|
857
|
+
expect(failWith(stream, error)).not.toThrow();
|
|
858
|
+
expect(received).toEqual([error]);
|
|
859
|
+
});
|
|
860
|
+
|
|
861
|
+
it('Cursor without a handler does not surface the error but counts it', async () => {
|
|
862
|
+
const error = Object.assign(new Error('missing'), { code: '42P01' });
|
|
863
|
+
const plain = new FakeCursor('SELECT * FROM missing');
|
|
864
|
+
const cursor = client.query(new FakeCursor('SELECT * FROM missing'));
|
|
865
|
+
|
|
866
|
+
expect(failWith(plain, error)).not.toThrow();
|
|
867
|
+
expect(failWith(cursor, error)).not.toThrow();
|
|
868
|
+
expect(
|
|
869
|
+
await value('db_client_query_errors_total', { code: '42P01' }),
|
|
870
|
+
).toBe(1);
|
|
871
|
+
expect(
|
|
872
|
+
await value('db_client_queries_active', { pool: poolName(POOL) }),
|
|
873
|
+
).toBe(0);
|
|
874
|
+
});
|
|
875
|
+
|
|
876
|
+
it('early close by the consumer is not a query error', async () => {
|
|
877
|
+
const errorsBefore =
|
|
878
|
+
(await value('db_client_query_errors_total', { code: 'unknown' })) ?? 0;
|
|
879
|
+
const stream = client.query(new FakeSubmittable('SELECT g FROM gen'));
|
|
880
|
+
|
|
881
|
+
// Так делает for await: свой обработчик error, затем AbortError
|
|
882
|
+
stream.on('error', () => {});
|
|
883
|
+
stream.emit('error', abortError());
|
|
884
|
+
stream.emit('close');
|
|
885
|
+
|
|
886
|
+
expect(
|
|
887
|
+
await histogramCount('db_client_operation_duration_seconds', {
|
|
888
|
+
operation: 'SELECT',
|
|
889
|
+
status: 'ok',
|
|
890
|
+
}),
|
|
891
|
+
).toBe(1);
|
|
892
|
+
expect(
|
|
893
|
+
await histogramCount('db_client_operation_duration_seconds', {
|
|
894
|
+
operation: 'SELECT',
|
|
895
|
+
status: 'error',
|
|
896
|
+
}),
|
|
897
|
+
).toBe(undefined);
|
|
898
|
+
expect(
|
|
899
|
+
(await value('db_client_query_errors_total', { code: 'unknown' })) ?? 0,
|
|
900
|
+
).toBe(errorsBefore);
|
|
901
|
+
expect(
|
|
902
|
+
await value('db_client_queries_active', { pool: poolName(POOL) }),
|
|
903
|
+
).toBe(0);
|
|
904
|
+
});
|
|
905
|
+
|
|
906
|
+
it('does not count an early close as a transaction rollback', async () => {
|
|
907
|
+
await client.query('BEGIN');
|
|
908
|
+
const stream = client.query(new FakeSubmittable('COMMIT'));
|
|
909
|
+
|
|
910
|
+
stream.on('error', () => {});
|
|
911
|
+
stream.emit('error', abortError());
|
|
912
|
+
|
|
913
|
+
expect(await value('db_transactions_total', { result: 'rollback' })).toBe(
|
|
914
|
+
undefined,
|
|
915
|
+
);
|
|
916
|
+
});
|
|
917
|
+
|
|
918
|
+
it('destroy() without an error completes the query', async () => {
|
|
919
|
+
const stream = client.query(new FakeSubmittable('SELECT 1'));
|
|
920
|
+
|
|
921
|
+
expect(
|
|
922
|
+
await value('db_client_queries_active', { pool: poolName(POOL) }),
|
|
923
|
+
).toBe(1);
|
|
924
|
+
stream.emit('close');
|
|
925
|
+
expect(
|
|
926
|
+
await value('db_client_queries_active', { pool: poolName(POOL) }),
|
|
927
|
+
).toBe(0);
|
|
928
|
+
});
|
|
929
|
+
|
|
930
|
+
it('removes its listeners and the handleError wrapper after completion', () => {
|
|
931
|
+
const stream = client.query(new FakeSubmittable('SELECT 1'));
|
|
932
|
+
|
|
933
|
+
stream.emit('end');
|
|
934
|
+
|
|
935
|
+
expect(stream.listenerCount('end')).toBe(0);
|
|
936
|
+
expect(stream.listenerCount('close')).toBe(0);
|
|
937
|
+
expect(Object.hasOwn(stream, 'handleError')).toBe(false);
|
|
938
|
+
});
|
|
939
|
+
});
|
|
940
|
+
|
|
941
|
+
describe('detach finalizes the pool', () => {
|
|
942
|
+
describe('pg-pool', () => {
|
|
943
|
+
let pool: FakePgPool;
|
|
944
|
+
let detachPool: () => void;
|
|
945
|
+
|
|
946
|
+
beforeEach(() => {
|
|
947
|
+
pool = new FakePgPool();
|
|
948
|
+
detachPool = instrumentPg(pool, 'pg-detach');
|
|
949
|
+
detach.push(detachPool);
|
|
950
|
+
});
|
|
951
|
+
|
|
952
|
+
it('counts an open transaction as rollback and connections as closed', async () => {
|
|
953
|
+
const preexisting = new FakeClient();
|
|
954
|
+
const otherPool = new FakePgPool();
|
|
955
|
+
|
|
956
|
+
otherPool._clients.push(preexisting);
|
|
957
|
+
const detachOther = instrumentPg(otherPool, 'pg-detach-2');
|
|
958
|
+
const inTransaction = await otherPool.connect();
|
|
959
|
+
const before = await snapshot(poolName('pg-detach-2'));
|
|
960
|
+
|
|
961
|
+
await inTransaction.query('BEGIN');
|
|
962
|
+
expect(
|
|
963
|
+
await gaugeRows('db_transactions_active', poolName('pg-detach-2')),
|
|
964
|
+
).toBe(1);
|
|
965
|
+
|
|
966
|
+
detachOther();
|
|
967
|
+
|
|
968
|
+
const after = await snapshot(poolName('pg-detach-2'));
|
|
969
|
+
|
|
970
|
+
expect(after.rollback - before.rollback).toBe(1);
|
|
971
|
+
|
|
972
|
+
// соединение, открытое до метрик, и соединение, созданное при них
|
|
973
|
+
expect(after.closed - before.closed).toBe(2);
|
|
974
|
+
expect(
|
|
975
|
+
await gaugeRows('db_transactions_active', poolName('pg-detach-2')),
|
|
976
|
+
).toBe(0);
|
|
977
|
+
expect(
|
|
978
|
+
await gaugeRows('db_client_queries_active', poolName('pg-detach-2')),
|
|
979
|
+
).toBe(0);
|
|
980
|
+
});
|
|
981
|
+
|
|
982
|
+
it('does not count a pool closed before detach twice', async () => {
|
|
983
|
+
const client = await pool.connect();
|
|
984
|
+
|
|
985
|
+
await client.query('BEGIN');
|
|
986
|
+
pool.emit('remove', client);
|
|
987
|
+
|
|
988
|
+
const before = await snapshot(poolName('pg-detach'));
|
|
989
|
+
|
|
990
|
+
detachPool();
|
|
991
|
+
detachPool();
|
|
992
|
+
|
|
993
|
+
expect(await snapshot(poolName('pg-detach'))).toEqual(before);
|
|
994
|
+
});
|
|
995
|
+
|
|
996
|
+
it('does not recreate a series for a query finished after detach', async () => {
|
|
997
|
+
let resolve!: (value: unknown) => void;
|
|
998
|
+
const slowClient = {
|
|
999
|
+
query: (_sql?: string): Promise<unknown> =>
|
|
1000
|
+
new Promise((r) => (resolve = r)),
|
|
1001
|
+
};
|
|
1002
|
+
const slowPool = new FakePgPool();
|
|
1003
|
+
|
|
1004
|
+
slowPool._clients.push(Object.assign(slowClient, { _connected: true }));
|
|
1005
|
+
const detachSlow = instrumentPg(slowPool, 'pg-detach-3');
|
|
1006
|
+
|
|
1007
|
+
const query = slowClient.query('SELECT 1');
|
|
1008
|
+
|
|
1009
|
+
expect(
|
|
1010
|
+
await gaugeRows('db_client_queries_active', poolName('pg-detach-3')),
|
|
1011
|
+
).toBe(1);
|
|
1012
|
+
|
|
1013
|
+
detachSlow();
|
|
1014
|
+
resolve({});
|
|
1015
|
+
await query;
|
|
1016
|
+
await new Promise(setImmediate);
|
|
1017
|
+
|
|
1018
|
+
expect(
|
|
1019
|
+
await gaugeRows('db_client_queries_active', poolName('pg-detach-3')),
|
|
1020
|
+
).toBe(0);
|
|
1021
|
+
|
|
1022
|
+
// Клиент остаётся обёрнутым: новые запросы и транзакции ряды не создают
|
|
1023
|
+
const begin = slowClient.query('BEGIN');
|
|
1024
|
+
|
|
1025
|
+
resolve({});
|
|
1026
|
+
await begin;
|
|
1027
|
+
await new Promise(setImmediate);
|
|
1028
|
+
|
|
1029
|
+
expect(
|
|
1030
|
+
await gaugeRows('db_client_queries_active', poolName('pg-detach-3')),
|
|
1031
|
+
).toBe(0);
|
|
1032
|
+
expect(
|
|
1033
|
+
await gaugeRows('db_transactions_active', poolName('pg-detach-3')),
|
|
1034
|
+
).toBe(0);
|
|
1035
|
+
});
|
|
1036
|
+
});
|
|
1037
|
+
|
|
1038
|
+
describe('tarn', () => {
|
|
1039
|
+
let pool: FakeTarnPool;
|
|
1040
|
+
let detachPool: () => void;
|
|
1041
|
+
|
|
1042
|
+
beforeEach(() => {
|
|
1043
|
+
pool = new FakeTarnPool();
|
|
1044
|
+
detachPool = instrumentTarn(pool, 'tarn-detach', {
|
|
1045
|
+
instrumentQueries: true,
|
|
1046
|
+
});
|
|
1047
|
+
detach.push(detachPool);
|
|
1048
|
+
});
|
|
1049
|
+
|
|
1050
|
+
it('counts an open transaction as rollback and connections as closed', async () => {
|
|
1051
|
+
const preexisting = new FakeClient();
|
|
1052
|
+
const otherPool = new FakeTarnPool();
|
|
1053
|
+
|
|
1054
|
+
otherPool.free.push({ resource: preexisting });
|
|
1055
|
+
const detachOther = instrumentTarn(otherPool, 'tarn-detach-2', {
|
|
1056
|
+
instrumentQueries: true,
|
|
1057
|
+
});
|
|
1058
|
+
const created = new FakeClient();
|
|
1059
|
+
|
|
1060
|
+
otherPool.emit('createSuccess', 1, created);
|
|
1061
|
+
const before = await snapshot(poolName('tarn-detach-2'));
|
|
1062
|
+
|
|
1063
|
+
await created.query('BEGIN;');
|
|
1064
|
+
expect(
|
|
1065
|
+
await gaugeRows('db_transactions_active', poolName('tarn-detach-2')),
|
|
1066
|
+
).toBe(1);
|
|
1067
|
+
|
|
1068
|
+
detachOther();
|
|
1069
|
+
|
|
1070
|
+
const after = await snapshot(poolName('tarn-detach-2'));
|
|
1071
|
+
|
|
1072
|
+
expect(after.rollback - before.rollback).toBe(1);
|
|
1073
|
+
expect(after.closed - before.closed).toBe(2);
|
|
1074
|
+
expect(
|
|
1075
|
+
await gaugeRows('db_transactions_active', poolName('tarn-detach-2')),
|
|
1076
|
+
).toBe(0);
|
|
1077
|
+
});
|
|
1078
|
+
|
|
1079
|
+
it('does not count a pool closed before detach twice', async () => {
|
|
1080
|
+
const resource = new FakeClient();
|
|
1081
|
+
|
|
1082
|
+
pool.emit('createSuccess', 1, resource);
|
|
1083
|
+
await resource.query('BEGIN;');
|
|
1084
|
+
pool.emit('destroySuccess', 2, resource);
|
|
1085
|
+
|
|
1086
|
+
const before = await snapshot(poolName('tarn-detach'));
|
|
1087
|
+
|
|
1088
|
+
detachPool();
|
|
1089
|
+
detachPool();
|
|
1090
|
+
|
|
1091
|
+
expect(await snapshot(poolName('tarn-detach'))).toEqual(before);
|
|
1092
|
+
});
|
|
1093
|
+
|
|
1094
|
+
it('does not recreate a series for a query finished after detach', async () => {
|
|
1095
|
+
const resource = new FakeClient();
|
|
1096
|
+
|
|
1097
|
+
pool.emit('createSuccess', 1, resource);
|
|
1098
|
+
const query = new Promise((resolve) =>
|
|
1099
|
+
resource.query('SELECT 1', resolve),
|
|
1100
|
+
);
|
|
1101
|
+
|
|
1102
|
+
expect(
|
|
1103
|
+
await gaugeRows('db_client_queries_active', poolName('tarn-detach')),
|
|
1104
|
+
).toBe(1);
|
|
1105
|
+
detachPool();
|
|
1106
|
+
await query;
|
|
1107
|
+
|
|
1108
|
+
expect(
|
|
1109
|
+
await gaugeRows('db_client_queries_active', poolName('tarn-detach')),
|
|
1110
|
+
).toBe(0);
|
|
1111
|
+
});
|
|
1112
|
+
});
|
|
1113
|
+
});
|
|
1114
|
+
|
|
1115
|
+
describe('connection errors', () => {
|
|
1116
|
+
describe('pg-pool', () => {
|
|
1117
|
+
let pool: FakePgPool;
|
|
1118
|
+
let detachPool: () => void;
|
|
1119
|
+
|
|
1120
|
+
beforeEach(() => {
|
|
1121
|
+
pool = new FakePgPool();
|
|
1122
|
+
});
|
|
1123
|
+
|
|
1124
|
+
const attach = (): void => {
|
|
1125
|
+
detachPool = instrumentPg(pool, 'pg-errors');
|
|
1126
|
+
detach.push(detachPool);
|
|
1127
|
+
};
|
|
1128
|
+
|
|
1129
|
+
it('counts a dropped idle connection once', async () => {
|
|
1130
|
+
attach();
|
|
1131
|
+
const client = (await pool.connect()) as FakeClient;
|
|
1132
|
+
|
|
1133
|
+
// Как pg-pool: idleListener убирает соединение и эмитит error пула
|
|
1134
|
+
pool.on('error', () => {});
|
|
1135
|
+
client.on('error', () => {
|
|
1136
|
+
pool._clients = pool._clients.filter((c) => c !== client);
|
|
1137
|
+
pool.emit('remove', client);
|
|
1138
|
+
pool.emit('error', new Error('terminated'), client);
|
|
1139
|
+
});
|
|
1140
|
+
terminate(client);
|
|
1141
|
+
|
|
1142
|
+
expect(await poolErrors(poolName('pg-errors'))).toBe(1);
|
|
1143
|
+
});
|
|
1144
|
+
|
|
1145
|
+
it('counts a dropped checked-out connection', async () => {
|
|
1146
|
+
attach();
|
|
1147
|
+
const client = (await pool.connect()) as FakeClient;
|
|
1148
|
+
|
|
1149
|
+
// Выданное соединение слушает его владелец, пул про ошибку не знает
|
|
1150
|
+
client.on('error', () => {});
|
|
1151
|
+
terminate(client);
|
|
1152
|
+
|
|
1153
|
+
expect(await poolErrors(poolName('pg-errors'))).toBe(1);
|
|
1154
|
+
});
|
|
1155
|
+
|
|
1156
|
+
it('counts a dropped connection opened before metrics were attached', async () => {
|
|
1157
|
+
const existing = new FakeClient();
|
|
1158
|
+
|
|
1159
|
+
existing.on('error', () => {});
|
|
1160
|
+
pool._clients.push(existing);
|
|
1161
|
+
attach();
|
|
1162
|
+
terminate(existing);
|
|
1163
|
+
|
|
1164
|
+
expect(await poolErrors(poolName('pg-errors'))).toBe(1);
|
|
1165
|
+
});
|
|
1166
|
+
|
|
1167
|
+
it('stops counting errors and leaves no listeners after finalization', async () => {
|
|
1168
|
+
const existing = new FakeClient();
|
|
1169
|
+
|
|
1170
|
+
existing.on('error', () => {});
|
|
1171
|
+
pool._clients.push(existing);
|
|
1172
|
+
attach();
|
|
1173
|
+
const created = (await pool.connect()) as FakeClient;
|
|
1174
|
+
|
|
1175
|
+
created.on('error', () => {});
|
|
1176
|
+
detachPool();
|
|
1177
|
+
terminate(existing);
|
|
1178
|
+
terminate(created);
|
|
1179
|
+
|
|
1180
|
+
expect(await poolErrors(poolName('pg-errors'))).toBe(0);
|
|
1181
|
+
expect(existing.listenerCount(errorMonitor)).toBe(0);
|
|
1182
|
+
expect(created.listenerCount(errorMonitor)).toBe(0);
|
|
1183
|
+
});
|
|
1184
|
+
|
|
1185
|
+
it('throws an unhandled error the same way as without metrics', async () => {
|
|
1186
|
+
const error = new Error('terminated');
|
|
1187
|
+
const plain = new FakeClient();
|
|
1188
|
+
|
|
1189
|
+
attach();
|
|
1190
|
+
const instrumented = (await pool.connect()) as FakeClient;
|
|
1191
|
+
|
|
1192
|
+
expect(thrownBy(() => plain.emit('error', error))).toBe(error);
|
|
1193
|
+
expect(thrownBy(() => instrumented.emit('error', error))).toBe(error);
|
|
1194
|
+
expect(await poolErrors(poolName('pg-errors'))).toBe(1);
|
|
1195
|
+
});
|
|
1196
|
+
|
|
1197
|
+
it('does not add an error handler to the pool', () => {
|
|
1198
|
+
attach();
|
|
1199
|
+
|
|
1200
|
+
expect(pool.listenerCount('error')).toBe(0);
|
|
1201
|
+
});
|
|
1202
|
+
});
|
|
1203
|
+
|
|
1204
|
+
describe('tarn', () => {
|
|
1205
|
+
let pool: FakeTarnPool;
|
|
1206
|
+
let detachPool: () => void;
|
|
1207
|
+
|
|
1208
|
+
beforeEach(() => {
|
|
1209
|
+
pool = new FakeTarnPool();
|
|
1210
|
+
});
|
|
1211
|
+
|
|
1212
|
+
const attach = (): void => {
|
|
1213
|
+
detachPool = instrumentTarn(pool, 'tarn-errors', {
|
|
1214
|
+
instrumentQueries: true,
|
|
1215
|
+
});
|
|
1216
|
+
detach.push(detachPool);
|
|
1217
|
+
};
|
|
1218
|
+
|
|
1219
|
+
it('counts a dropped connection once', async () => {
|
|
1220
|
+
attach();
|
|
1221
|
+
const connection = knexConnection();
|
|
1222
|
+
|
|
1223
|
+
pool.emit('createSuccess', 1, connection);
|
|
1224
|
+
terminate(connection);
|
|
1225
|
+
|
|
1226
|
+
expect(await poolErrors(poolName('tarn-errors'))).toBe(1);
|
|
1227
|
+
});
|
|
1228
|
+
|
|
1229
|
+
it('counts dropped connections opened before metrics were attached', async () => {
|
|
1230
|
+
const free = knexConnection();
|
|
1231
|
+
const used = knexConnection();
|
|
1232
|
+
|
|
1233
|
+
pool.free.push({ resource: free });
|
|
1234
|
+
pool.used.push({ resource: used });
|
|
1235
|
+
attach();
|
|
1236
|
+
terminate(free);
|
|
1237
|
+
terminate(used);
|
|
1238
|
+
|
|
1239
|
+
expect(await poolErrors(poolName('tarn-errors'))).toBe(2);
|
|
1240
|
+
});
|
|
1241
|
+
|
|
1242
|
+
it('counts a dropped checked-out connection', async () => {
|
|
1243
|
+
attach();
|
|
1244
|
+
const connection = knexConnection();
|
|
1245
|
+
|
|
1246
|
+
pool.emit('createSuccess', 1, connection);
|
|
1247
|
+
pool.emit('acquireRequest', 2);
|
|
1248
|
+
pool.emit('acquireSuccess', 2, connection);
|
|
1249
|
+
terminate(connection);
|
|
1250
|
+
|
|
1251
|
+
expect(await poolErrors(poolName('tarn-errors'))).toBe(1);
|
|
1252
|
+
});
|
|
1253
|
+
|
|
1254
|
+
it('stops counting errors and leaves no listeners after finalization', async () => {
|
|
1255
|
+
const existing = knexConnection();
|
|
1256
|
+
const created = knexConnection();
|
|
1257
|
+
|
|
1258
|
+
pool.free.push({ resource: existing });
|
|
1259
|
+
attach();
|
|
1260
|
+
pool.emit('createSuccess', 1, created);
|
|
1261
|
+
detachPool();
|
|
1262
|
+
terminate(existing);
|
|
1263
|
+
terminate(created);
|
|
1264
|
+
|
|
1265
|
+
expect(await poolErrors(poolName('tarn-errors'))).toBe(0);
|
|
1266
|
+
expect(existing.listenerCount(errorMonitor)).toBe(0);
|
|
1267
|
+
expect(created.listenerCount(errorMonitor)).toBe(0);
|
|
1268
|
+
});
|
|
1269
|
+
|
|
1270
|
+
it('throws an unhandled error the same way as without metrics', async () => {
|
|
1271
|
+
const error = new Error('terminated');
|
|
1272
|
+
const plain = new FakeClient();
|
|
1273
|
+
const instrumented = new FakeClient();
|
|
1274
|
+
|
|
1275
|
+
attach();
|
|
1276
|
+
pool.emit('createSuccess', 1, instrumented);
|
|
1277
|
+
|
|
1278
|
+
expect(thrownBy(() => plain.emit('error', error))).toBe(error);
|
|
1279
|
+
expect(thrownBy(() => instrumented.emit('error', error))).toBe(error);
|
|
1280
|
+
expect(await poolErrors(poolName('tarn-errors'))).toBe(1);
|
|
1281
|
+
});
|
|
1282
|
+
});
|
|
1283
|
+
});
|
|
1284
|
+
|
|
1285
|
+
describe('pool finalization on close', () => {
|
|
1286
|
+
describe('pg-pool', () => {
|
|
1287
|
+
let pool: FakePgPool;
|
|
1288
|
+
let detachPool: () => void;
|
|
1289
|
+
|
|
1290
|
+
beforeEach(() => {
|
|
1291
|
+
pool = new FakePgPool();
|
|
1292
|
+
detachPool = instrumentPg(pool, 'pg-end');
|
|
1293
|
+
detach.push(detachPool);
|
|
1294
|
+
});
|
|
1295
|
+
|
|
1296
|
+
it('counts a transaction committed before end as commit, not rollback', async () => {
|
|
1297
|
+
const client = (await pool.connect()) as FakeClient;
|
|
1298
|
+
const before = await results();
|
|
1299
|
+
|
|
1300
|
+
await client.query('BEGIN');
|
|
1301
|
+
await client.query('COMMIT');
|
|
1302
|
+
await pool.end();
|
|
1303
|
+
|
|
1304
|
+
const after = await results();
|
|
1305
|
+
|
|
1306
|
+
expect(after.commit - before.commit).toBe(1);
|
|
1307
|
+
expect(after.rollback - before.rollback).toBe(0);
|
|
1308
|
+
expect(await rowsOf(poolName('pg-end'))).toBe(0);
|
|
1309
|
+
});
|
|
1310
|
+
|
|
1311
|
+
it('finalizes on the callback form of end too', async () => {
|
|
1312
|
+
const client = (await pool.connect()) as FakeClient;
|
|
1313
|
+
|
|
1314
|
+
await client.query('BEGIN');
|
|
1315
|
+
expect(
|
|
1316
|
+
await gaugeRows('db_transactions_active', poolName('pg-end')),
|
|
1317
|
+
).toBe(1);
|
|
1318
|
+
|
|
1319
|
+
await new Promise<void>((resolve) => pool.end(() => resolve()));
|
|
1320
|
+
|
|
1321
|
+
expect(await rowsOf(poolName('pg-end'))).toBe(0);
|
|
1322
|
+
expect(Object.hasOwn(pool, 'end')).toBe(false);
|
|
1323
|
+
});
|
|
1324
|
+
|
|
1325
|
+
it('counts a transaction on a connection closed by end as rollback', async () => {
|
|
1326
|
+
const client = (await pool.connect()) as FakeClient;
|
|
1327
|
+
const before = await snapshot(poolName('pg-end'));
|
|
1328
|
+
|
|
1329
|
+
await client.query('BEGIN');
|
|
1330
|
+
await pool.end();
|
|
1331
|
+
|
|
1332
|
+
const after = await snapshot(poolName('pg-end'));
|
|
1333
|
+
|
|
1334
|
+
expect(after.rollback - before.rollback).toBe(1);
|
|
1335
|
+
expect(after.closed - before.closed).toBe(1);
|
|
1336
|
+
});
|
|
1337
|
+
|
|
1338
|
+
it('does not finalize until end finishes', async () => {
|
|
1339
|
+
const client = (await pool.connect()) as FakeClient;
|
|
1340
|
+
|
|
1341
|
+
await client.query('BEGIN');
|
|
1342
|
+
const ending = pool.end();
|
|
1343
|
+
|
|
1344
|
+
expect(
|
|
1345
|
+
await gaugeRows('db_transactions_active', poolName('pg-end')),
|
|
1346
|
+
).toBe(1);
|
|
1347
|
+
await ending;
|
|
1348
|
+
expect(await rowsOf(poolName('pg-end'))).toBe(0);
|
|
1349
|
+
});
|
|
1350
|
+
|
|
1351
|
+
it('finalizes when end fails too', async () => {
|
|
1352
|
+
pool.endError = new Error('end failed');
|
|
1353
|
+
await pool.connect();
|
|
1354
|
+
|
|
1355
|
+
await expect(pool.end()).rejects.toThrow('end failed');
|
|
1356
|
+
expect(await rowsOf(poolName('pg-end'))).toBe(0);
|
|
1357
|
+
});
|
|
1358
|
+
|
|
1359
|
+
it('second end does not finalize before the first one', async () => {
|
|
1360
|
+
const client = (await pool.connect()) as FakeClient;
|
|
1361
|
+
const second = jest.fn();
|
|
1362
|
+
|
|
1363
|
+
await client.query('BEGIN');
|
|
1364
|
+
const ending = pool.end();
|
|
1365
|
+
|
|
1366
|
+
pool.end(second);
|
|
1367
|
+
|
|
1368
|
+
expect(second).toHaveBeenCalledWith(expect.any(Error));
|
|
1369
|
+
expect(
|
|
1370
|
+
await gaugeRows('db_transactions_active', poolName('pg-end')),
|
|
1371
|
+
).toBe(1);
|
|
1372
|
+
|
|
1373
|
+
await ending;
|
|
1374
|
+
expect(await rowsOf(poolName('pg-end'))).toBe(0);
|
|
1375
|
+
});
|
|
1376
|
+
|
|
1377
|
+
it('detach before pool close finalizes at once, a later end adds nothing', async () => {
|
|
1378
|
+
const client = (await pool.connect()) as FakeClient;
|
|
1379
|
+
|
|
1380
|
+
await client.query('BEGIN');
|
|
1381
|
+
detachPool();
|
|
1382
|
+
|
|
1383
|
+
const before = await snapshot(poolName('pg-end'));
|
|
1384
|
+
|
|
1385
|
+
expect(before.closed).toBe(1);
|
|
1386
|
+
expect(await rowsOf(poolName('pg-end'))).toBe(0);
|
|
1387
|
+
expect(Object.hasOwn(pool, 'end')).toBe(false);
|
|
1388
|
+
|
|
1389
|
+
await pool.end();
|
|
1390
|
+
expect(await snapshot(poolName('pg-end'))).toEqual(before);
|
|
1391
|
+
});
|
|
1392
|
+
|
|
1393
|
+
it('keeps series of a pool that lost its connections without end', async () => {
|
|
1394
|
+
const client = (await pool.connect()) as FakeClient;
|
|
1395
|
+
|
|
1396
|
+
await client.query('BEGIN');
|
|
1397
|
+
await client.query('COMMIT');
|
|
1398
|
+
pool._clients = [];
|
|
1399
|
+
pool.emit('remove', client);
|
|
1400
|
+
|
|
1401
|
+
expect(
|
|
1402
|
+
await gaugeRows('db_transactions_active', poolName('pg-end')),
|
|
1403
|
+
).toBe(1);
|
|
1404
|
+
expect(
|
|
1405
|
+
await gaugeRows('db_pool_connections_max', poolName('pg-end')),
|
|
1406
|
+
).toBe(1);
|
|
1407
|
+
});
|
|
1408
|
+
});
|
|
1409
|
+
|
|
1410
|
+
describe('tarn', () => {
|
|
1411
|
+
let pool: FakeTarnPool;
|
|
1412
|
+
let detachPool: () => void;
|
|
1413
|
+
|
|
1414
|
+
beforeEach(() => {
|
|
1415
|
+
pool = new FakeTarnPool();
|
|
1416
|
+
detachPool = instrumentTarn(pool, 'tarn-destroy', {
|
|
1417
|
+
instrumentQueries: true,
|
|
1418
|
+
});
|
|
1419
|
+
detach.push(detachPool);
|
|
1420
|
+
});
|
|
1421
|
+
|
|
1422
|
+
const create = (): FakeClient => {
|
|
1423
|
+
const resource = new FakeClient();
|
|
1424
|
+
|
|
1425
|
+
pool.free.push({ resource });
|
|
1426
|
+
pool.emit('createSuccess', 1, resource);
|
|
1427
|
+
return resource;
|
|
1428
|
+
};
|
|
1429
|
+
|
|
1430
|
+
it('counts a transaction committed before destroy as commit, not rollback', async () => {
|
|
1431
|
+
const resource = create();
|
|
1432
|
+
const before = await results();
|
|
1433
|
+
|
|
1434
|
+
await resource.query('BEGIN;');
|
|
1435
|
+
await resource.query('COMMIT');
|
|
1436
|
+
await pool.destroy();
|
|
1437
|
+
|
|
1438
|
+
const after = await results();
|
|
1439
|
+
|
|
1440
|
+
expect(after.commit - before.commit).toBe(1);
|
|
1441
|
+
expect(after.rollback - before.rollback).toBe(0);
|
|
1442
|
+
expect(await rowsOf(poolName('tarn-destroy'))).toBe(0);
|
|
1443
|
+
expect(Object.hasOwn(pool, 'destroy')).toBe(false);
|
|
1444
|
+
});
|
|
1445
|
+
|
|
1446
|
+
it('counts a transaction on a connection closed by destroy as rollback', async () => {
|
|
1447
|
+
const resource = create();
|
|
1448
|
+
const before = await snapshot(poolName('tarn-destroy'));
|
|
1449
|
+
|
|
1450
|
+
await resource.query('BEGIN;');
|
|
1451
|
+
await pool.destroy();
|
|
1452
|
+
|
|
1453
|
+
const after = await snapshot(poolName('tarn-destroy'));
|
|
1454
|
+
|
|
1455
|
+
expect(after.rollback - before.rollback).toBe(1);
|
|
1456
|
+
expect(after.closed - before.closed).toBe(1);
|
|
1457
|
+
});
|
|
1458
|
+
|
|
1459
|
+
it('detach before pool close finalizes at once, a later destroy adds nothing', async () => {
|
|
1460
|
+
const resource = create();
|
|
1461
|
+
|
|
1462
|
+
await resource.query('BEGIN;');
|
|
1463
|
+
detachPool();
|
|
1464
|
+
|
|
1465
|
+
const before = await snapshot(poolName('tarn-destroy'));
|
|
1466
|
+
|
|
1467
|
+
expect(before.closed).toBe(1);
|
|
1468
|
+
expect(await rowsOf(poolName('tarn-destroy'))).toBe(0);
|
|
1469
|
+
|
|
1470
|
+
await pool.destroy();
|
|
1471
|
+
expect(await snapshot(poolName('tarn-destroy'))).toEqual(before);
|
|
1472
|
+
});
|
|
1473
|
+
|
|
1474
|
+
it('keeps series of a pool that lost its connections without destroy', async () => {
|
|
1475
|
+
const resource = create();
|
|
1476
|
+
|
|
1477
|
+
await resource.query('BEGIN;');
|
|
1478
|
+
pool.free = [];
|
|
1479
|
+
pool.emit('destroySuccess', 2, resource);
|
|
1480
|
+
await resource.query('BEGIN;');
|
|
1481
|
+
|
|
1482
|
+
expect(
|
|
1483
|
+
await gaugeRows('db_transactions_active', poolName('tarn-destroy')),
|
|
1484
|
+
).toBe(1);
|
|
1485
|
+
expect(
|
|
1486
|
+
await gaugeRows('db_pool_connections_max', poolName('tarn-destroy')),
|
|
1487
|
+
).toBe(1);
|
|
1488
|
+
});
|
|
1489
|
+
|
|
1490
|
+
it('finalizes a real tarn after destroy', async () => {
|
|
1491
|
+
const tarn = new TarnPool({
|
|
1492
|
+
create: (
|
|
1493
|
+
callback: (error: Error | null, resource: object) => void,
|
|
1494
|
+
): void => callback(null, new FakeClient()),
|
|
1495
|
+
destroy: (): void => {},
|
|
1496
|
+
min: 0,
|
|
1497
|
+
max: 1,
|
|
1498
|
+
});
|
|
1499
|
+
|
|
1500
|
+
detach.push(instrumentTarn(tarn, 'real', { instrumentQueries: true }));
|
|
1501
|
+
|
|
1502
|
+
const resource = (await tarn.acquire().promise) as FakeClient;
|
|
1503
|
+
const before = await snapshot(poolName('real'));
|
|
1504
|
+
|
|
1505
|
+
await resource.query('BEGIN');
|
|
1506
|
+
tarn.release(resource);
|
|
1507
|
+
await tarn.destroy();
|
|
1508
|
+
|
|
1509
|
+
const after = await snapshot(poolName('real'));
|
|
1510
|
+
|
|
1511
|
+
expect(after.closed - before.closed).toBe(1);
|
|
1512
|
+
expect(after.rollback - before.rollback).toBe(1);
|
|
1513
|
+
expect(await rowsOf(poolName('real'))).toBe(0);
|
|
1514
|
+
});
|
|
1515
|
+
});
|
|
1516
|
+
});
|
|
1517
|
+
|
|
1518
|
+
describe('connection that is still connecting', () => {
|
|
1519
|
+
it('is counted once when it connects', async () => {
|
|
1520
|
+
const pool = new FakePgPool();
|
|
1521
|
+
const connecting = new FakeClient();
|
|
1522
|
+
|
|
1523
|
+
connecting._connected = false;
|
|
1524
|
+
pool._clients.push(connecting);
|
|
1525
|
+
detach.push(instrumentPg(pool, 'connecting'));
|
|
1526
|
+
|
|
1527
|
+
expect(await createdTotal(poolName('connecting'))).toBe(0);
|
|
1528
|
+
|
|
1529
|
+
connecting._connected = true;
|
|
1530
|
+
pool.emit('connect', connecting);
|
|
1531
|
+
pool.emit('connect', connecting);
|
|
1532
|
+
|
|
1533
|
+
expect(await createdTotal(poolName('connecting'))).toBe(1);
|
|
1534
|
+
});
|
|
1535
|
+
|
|
1536
|
+
it('is counted neither as created nor as closed if it fails to connect', async () => {
|
|
1537
|
+
const pool = new FakePgPool();
|
|
1538
|
+
const connecting = new FakeClient();
|
|
1539
|
+
|
|
1540
|
+
connecting._connected = false;
|
|
1541
|
+
pool._clients.push(connecting);
|
|
1542
|
+
|
|
1543
|
+
const detachPool = instrumentPg(pool, 'never-connected');
|
|
1544
|
+
|
|
1545
|
+
detach.push(detachPool);
|
|
1546
|
+
|
|
1547
|
+
// Подключение не удалось: pg-pool убирает клиента без события remove
|
|
1548
|
+
pool._clients = [];
|
|
1549
|
+
detachPool();
|
|
1550
|
+
|
|
1551
|
+
expect(await createdTotal(poolName('never-connected'))).toBe(0);
|
|
1552
|
+
expect(
|
|
1553
|
+
await counter('db_pool_connections_closed_total', {
|
|
1554
|
+
pool: poolName('never-connected'),
|
|
1555
|
+
}),
|
|
1556
|
+
).toBe(0);
|
|
1557
|
+
});
|
|
1558
|
+
});
|
|
1559
|
+
|
|
1560
|
+
describe('same pool names', () => {
|
|
1561
|
+
it('gives the second pool a suffix and keeps pool series apart', async () => {
|
|
1562
|
+
const first = new FakePgPool();
|
|
1563
|
+
const second = new FakePgPool();
|
|
1564
|
+
|
|
1565
|
+
first.options.max = 10;
|
|
1566
|
+
second.options.max = 5;
|
|
1567
|
+
|
|
1568
|
+
const detachFirst = instrumentPg(first, 'typeorm');
|
|
1569
|
+
const detachSecond = instrumentPg(second, 'typeorm');
|
|
1570
|
+
|
|
1571
|
+
detach.push(detachFirst, detachSecond);
|
|
1572
|
+
|
|
1573
|
+
expect(
|
|
1574
|
+
await value('db_pool_connections_max', { pool: 'svc__typeorm' }),
|
|
1575
|
+
).toBe(10);
|
|
1576
|
+
expect(
|
|
1577
|
+
await value('db_pool_connections_max', { pool: 'svc__typeorm#2' }),
|
|
1578
|
+
).toBe(5);
|
|
1579
|
+
|
|
1580
|
+
// У второго пула открыта транзакция и идёт запрос, первый закрывается
|
|
1581
|
+
let resolve!: (value: unknown) => void;
|
|
1582
|
+
const client = (await second.connect()) as FakeClient;
|
|
1583
|
+
|
|
1584
|
+
await client.query('BEGIN');
|
|
1585
|
+
const original = client.query.bind(client);
|
|
1586
|
+
const slowClient = Object.assign(new FakeClient(), {
|
|
1587
|
+
query: (): Promise<unknown> => new Promise((r) => (resolve = r)),
|
|
1588
|
+
});
|
|
1589
|
+
|
|
1590
|
+
second._clients.push(slowClient);
|
|
1591
|
+
second.emit('connect', slowClient);
|
|
1592
|
+
const slow = slowClient.query();
|
|
1593
|
+
|
|
1594
|
+
await first.end();
|
|
1595
|
+
|
|
1596
|
+
expect(
|
|
1597
|
+
await value('db_transactions_active', { pool: 'svc__typeorm#2' }),
|
|
1598
|
+
).toBe(1);
|
|
1599
|
+
expect(
|
|
1600
|
+
await value('db_client_queries_active', { pool: 'svc__typeorm#2' }),
|
|
1601
|
+
).toBe(1);
|
|
1602
|
+
|
|
1603
|
+
resolve({});
|
|
1604
|
+
await slow;
|
|
1605
|
+
await original('COMMIT');
|
|
1606
|
+
await new Promise(setImmediate);
|
|
1607
|
+
|
|
1608
|
+
expect(await negativeValues('db_transactions_active')).toEqual([]);
|
|
1609
|
+
expect(await negativeValues('db_client_queries_active')).toEqual([]);
|
|
1610
|
+
expect(
|
|
1611
|
+
await value('db_transactions_active', { pool: 'svc__typeorm#2' }),
|
|
1612
|
+
).toBe(0);
|
|
1613
|
+
expect(
|
|
1614
|
+
await value('db_client_queries_active', { pool: 'svc__typeorm#2' }),
|
|
1615
|
+
).toBe(0);
|
|
1616
|
+
});
|
|
1617
|
+
|
|
1618
|
+
it('frees the name of a closed pool', async () => {
|
|
1619
|
+
const first = new FakePgPool();
|
|
1620
|
+
|
|
1621
|
+
instrumentPg(first, 'reused');
|
|
1622
|
+
await first.end();
|
|
1623
|
+
|
|
1624
|
+
const next = new FakePgPool();
|
|
1625
|
+
|
|
1626
|
+
detach.push(instrumentPg(next, 'reused'));
|
|
1627
|
+
|
|
1628
|
+
expect(
|
|
1629
|
+
await value('db_pool_connections_max', { pool: poolName('reused') }),
|
|
1630
|
+
).toBe(10);
|
|
1631
|
+
expect(
|
|
1632
|
+
await gaugeRows('db_pool_connections_max', `${poolName('reused')}#2`),
|
|
1633
|
+
).toBe(0);
|
|
1634
|
+
});
|
|
1635
|
+
});
|
|
1636
|
+
|
|
1637
|
+
describe('pool lifecycle', () => {
|
|
1638
|
+
/**
|
|
1639
|
+
* Фейковый пул каждого вида и метод, которым он закрывается
|
|
1640
|
+
*/
|
|
1641
|
+
const POOLS = {
|
|
1642
|
+
pg: { create: (): EventEmitter => new FakePgPool(), close: 'end' },
|
|
1643
|
+
tarn: {
|
|
1644
|
+
create: (): EventEmitter => new FakeTarnPool(),
|
|
1645
|
+
close: 'destroy',
|
|
1646
|
+
},
|
|
1647
|
+
} as const;
|
|
1648
|
+
|
|
1649
|
+
const instrumentKind = (
|
|
1650
|
+
kind: keyof typeof POOLS,
|
|
1651
|
+
pool: unknown,
|
|
1652
|
+
name: string,
|
|
1653
|
+
): Detach | undefined =>
|
|
1654
|
+
metrics.instrumentPool(kind, pool, name, logger, {
|
|
1655
|
+
instrumentQueries: true,
|
|
1656
|
+
});
|
|
1657
|
+
|
|
1658
|
+
const close = async (
|
|
1659
|
+
kind: keyof typeof POOLS,
|
|
1660
|
+
pool: EventEmitter,
|
|
1661
|
+
): Promise<void> => {
|
|
1662
|
+
await (pool as unknown as Record<string, () => Promise<void>>)[
|
|
1663
|
+
POOLS[kind].close
|
|
1664
|
+
]!();
|
|
1665
|
+
};
|
|
1666
|
+
|
|
1667
|
+
it.each(['pg', 'tarn'] as const)(
|
|
1668
|
+
'%s: closing the pool frees its name and gauge source, a later detach does nothing',
|
|
1669
|
+
async (kind) => {
|
|
1670
|
+
const pool = POOLS[kind].create();
|
|
1671
|
+
const detachClosed = instrumented(
|
|
1672
|
+
instrumentKind(kind, pool, 'lifecycle'),
|
|
1673
|
+
);
|
|
1674
|
+
|
|
1675
|
+
expect(registeredPools()).toContain(poolName('lifecycle'));
|
|
1676
|
+
|
|
1677
|
+
await close(kind, pool);
|
|
1678
|
+
|
|
1679
|
+
expect(registeredPools()).not.toContain(poolName('lifecycle'));
|
|
1680
|
+
expect(pool.eventNames()).toEqual([]);
|
|
1681
|
+
|
|
1682
|
+
const next = POOLS[kind].create();
|
|
1683
|
+
|
|
1684
|
+
detach.push(instrumented(instrumentKind(kind, next, 'lifecycle')));
|
|
1685
|
+
detachClosed();
|
|
1686
|
+
|
|
1687
|
+
// Detach закрытого пула не освободил имя и не снял источник нового
|
|
1688
|
+
expect(registeredPools()).toContain(poolName('lifecycle'));
|
|
1689
|
+
detach.push(
|
|
1690
|
+
instrumented(instrumentKind(kind, POOLS[kind].create(), 'lifecycle')),
|
|
1691
|
+
);
|
|
1692
|
+
expect(registeredPools()).toContain(`${poolName('lifecycle')}#2`);
|
|
1693
|
+
},
|
|
1694
|
+
);
|
|
1695
|
+
|
|
1696
|
+
it.each(['pg', 'tarn'] as const)(
|
|
1697
|
+
'%s: an error after the name is claimed undoes everything and is rethrown',
|
|
1698
|
+
async (kind) => {
|
|
1699
|
+
const pool = POOLS[kind].create();
|
|
1700
|
+
const closeMethod = POOLS[kind].close;
|
|
1701
|
+
const original = (pool as unknown as Record<string, unknown>)[
|
|
1702
|
+
closeMethod
|
|
1703
|
+
];
|
|
1704
|
+
const error = new Error('close method is unavailable');
|
|
1705
|
+
let armed = false;
|
|
1706
|
+
|
|
1707
|
+
// Метод закрытия перестаёт читаться, когда адаптер уже подписался на
|
|
1708
|
+
// события пула: так исключение бросает последний шаг подключения,
|
|
1709
|
+
// обёртка метода закрытия, а не проверка адаптера
|
|
1710
|
+
pool.once('newListener', () => {
|
|
1711
|
+
armed = true;
|
|
1712
|
+
});
|
|
1713
|
+
Object.defineProperty(pool, closeMethod, {
|
|
1714
|
+
configurable: true,
|
|
1715
|
+
get: () => {
|
|
1716
|
+
if (armed) {
|
|
1717
|
+
throw error;
|
|
1718
|
+
}
|
|
1719
|
+
return original;
|
|
1720
|
+
},
|
|
1721
|
+
});
|
|
1722
|
+
|
|
1723
|
+
expect(() => instrumentKind(kind, pool, 'failing')).toThrow(error);
|
|
1724
|
+
expect(registeredPools()).not.toContain(poolName('failing'));
|
|
1725
|
+
expect(pool.eventNames()).toEqual([]);
|
|
1726
|
+
expect(Object.hasOwn(pool, 'connect')).toBe(false);
|
|
1727
|
+
expect(await rowsOf(poolName('failing'))).toBe(0);
|
|
1728
|
+
|
|
1729
|
+
detach.push(
|
|
1730
|
+
instrumented(instrumentKind(kind, POOLS[kind].create(), 'failing')),
|
|
1731
|
+
);
|
|
1732
|
+
expect(registeredPools()).toContain(poolName('failing'));
|
|
1733
|
+
expect(registeredPools()).not.toContain(`${poolName('failing')}#2`);
|
|
1734
|
+
},
|
|
1735
|
+
);
|
|
1736
|
+
});
|
|
1737
|
+
|
|
1738
|
+
describe('instrumentPool', () => {
|
|
1739
|
+
it.each([
|
|
1740
|
+
['pg', (): object => new FakeTarnPool()],
|
|
1741
|
+
['tarn', (): object => new FakePgPool()],
|
|
1742
|
+
] as const)(
|
|
1743
|
+
'skips a pool that is not a %s pool with a warning and keeps the name free',
|
|
1744
|
+
async (kind, wrongPool) => {
|
|
1745
|
+
expect(
|
|
1746
|
+
metrics.instrumentPool(kind, wrongPool(), 'wrong', logger, {
|
|
1747
|
+
instrumentQueries: true,
|
|
1748
|
+
}),
|
|
1749
|
+
).toBeUndefined();
|
|
1750
|
+
expect(logger.warn).toHaveBeenCalledWith(
|
|
1751
|
+
`Pool metrics are disabled for pool svc__wrong: expected a ${kind} pool`,
|
|
1752
|
+
);
|
|
1753
|
+
|
|
1754
|
+
detach.push(instrumentPg(new FakePgPool(), 'wrong'));
|
|
1755
|
+
|
|
1756
|
+
expect(
|
|
1757
|
+
await value('db_pool_connections_max', { pool: poolName('wrong') }),
|
|
1758
|
+
).toBe(10);
|
|
1759
|
+
expect(
|
|
1760
|
+
await gaugeRows('db_pool_connections_max', `${poolName('wrong')}#2`),
|
|
1761
|
+
).toBe(0);
|
|
1762
|
+
},
|
|
1763
|
+
);
|
|
1764
|
+
|
|
1765
|
+
it('wraps tarn connection query with instrumentQueries: true', () => {
|
|
1766
|
+
const pool = new FakeTarnPool();
|
|
1767
|
+
const resource = new FakeClient();
|
|
1768
|
+
const original = resource.query;
|
|
1769
|
+
|
|
1770
|
+
detach.push(
|
|
1771
|
+
instrumented(
|
|
1772
|
+
metrics.instrumentPool('tarn', pool, 'tarn', logger, {
|
|
1773
|
+
instrumentQueries: true,
|
|
1774
|
+
}),
|
|
1775
|
+
),
|
|
1776
|
+
);
|
|
1777
|
+
pool.emit('createSuccess', 1, resource);
|
|
1778
|
+
|
|
1779
|
+
expect(resource.query).not.toBe(original);
|
|
1780
|
+
});
|
|
1781
|
+
|
|
1782
|
+
it('leaves pg connection query untouched with instrumentQueries: false', () => {
|
|
1783
|
+
const pool = new FakePgPool();
|
|
1784
|
+
const client = new FakeClient();
|
|
1785
|
+
const original = client.query;
|
|
1786
|
+
|
|
1787
|
+
detach.push(
|
|
1788
|
+
instrumented(
|
|
1789
|
+
metrics.instrumentPool('pg', pool, 'pg', logger, {
|
|
1790
|
+
instrumentQueries: false,
|
|
1791
|
+
}),
|
|
1792
|
+
),
|
|
1793
|
+
);
|
|
1794
|
+
pool.emit('connect', client);
|
|
1795
|
+
|
|
1796
|
+
expect(client.query).toBe(original);
|
|
1797
|
+
});
|
|
1798
|
+
|
|
1799
|
+
it('builds the pool label from the app name given to create and the resource', async () => {
|
|
1800
|
+
const other = DbClientMetrics.create(config(50), 'other');
|
|
1801
|
+
|
|
1802
|
+
detach.push(
|
|
1803
|
+
instrumented(
|
|
1804
|
+
other.instrumentPool('pg', new FakePgPool(), POOL, logger, {
|
|
1805
|
+
instrumentQueries: true,
|
|
1806
|
+
}),
|
|
1807
|
+
),
|
|
1808
|
+
instrumented(
|
|
1809
|
+
other.instrumentPool('pg', new FakePgPool(), POOL, logger, {
|
|
1810
|
+
instrumentQueries: true,
|
|
1811
|
+
}),
|
|
1812
|
+
),
|
|
1813
|
+
);
|
|
1814
|
+
|
|
1815
|
+
expect(registeredPools()).toEqual(
|
|
1816
|
+
expect.arrayContaining(['other__typeorm', 'other__typeorm#2']),
|
|
1817
|
+
);
|
|
1818
|
+
expect(
|
|
1819
|
+
await value('db_pool_connections_max', { pool: 'other__typeorm' }),
|
|
1820
|
+
).toBe(10);
|
|
1821
|
+
});
|
|
1822
|
+
|
|
1823
|
+
it('leaves no own properties of the instrumentation on the client', () => {
|
|
1824
|
+
const client = new FakeClient();
|
|
1825
|
+
const symbols = Object.getOwnPropertySymbols(client);
|
|
1826
|
+
const names = Object.getOwnPropertyNames(client);
|
|
1827
|
+
|
|
1828
|
+
instrumentClient(client);
|
|
1829
|
+
|
|
1830
|
+
expect(Object.getOwnPropertySymbols(client)).toEqual(symbols);
|
|
1831
|
+
expect(Object.getOwnPropertyNames(client)).toEqual(
|
|
1832
|
+
names.includes('query') ? names : [...names, 'query'],
|
|
1833
|
+
);
|
|
1834
|
+
});
|
|
1835
|
+
});
|
|
1836
|
+
|
|
1837
|
+
describe('pool.connect when recording fails', () => {
|
|
1838
|
+
let pool: FakePgPool;
|
|
1839
|
+
|
|
1840
|
+
beforeEach(() => {
|
|
1841
|
+
pool = new FakePgPool();
|
|
1842
|
+
detach.push(instrumentPg(pool, 'broken-recording'));
|
|
1843
|
+
const acquireDuration = register.getSingleMetric(
|
|
1844
|
+
'db_pool_acquire_duration_seconds',
|
|
1845
|
+
) as Histogram<'pool'>;
|
|
1846
|
+
|
|
1847
|
+
jest.spyOn(acquireDuration, 'observe').mockImplementation(() => {
|
|
1848
|
+
throw new Error('recording failed');
|
|
1849
|
+
});
|
|
1850
|
+
});
|
|
1851
|
+
|
|
1852
|
+
afterEach(() => {
|
|
1853
|
+
jest.restoreAllMocks();
|
|
1854
|
+
});
|
|
1855
|
+
|
|
1856
|
+
it('resolves the promise with the same client', async () => {
|
|
1857
|
+
const client = await pool.connect();
|
|
1858
|
+
|
|
1859
|
+
expect(client).toBeInstanceOf(FakeClient);
|
|
1860
|
+
});
|
|
1861
|
+
|
|
1862
|
+
it('rejects the promise with the same error', async () => {
|
|
1863
|
+
const error = new Error('connect failed');
|
|
1864
|
+
|
|
1865
|
+
pool.nextError = error;
|
|
1866
|
+
|
|
1867
|
+
await expect(pool.connect()).rejects.toBe(error);
|
|
1868
|
+
});
|
|
1869
|
+
|
|
1870
|
+
it('calls the callback with the same arguments', async () => {
|
|
1871
|
+
const outcome = await new Promise<unknown[]>((resolve) => {
|
|
1872
|
+
pool.connect((...args: unknown[]) => resolve(args));
|
|
1873
|
+
});
|
|
1874
|
+
|
|
1875
|
+
expect(outcome[0]).toBeUndefined();
|
|
1876
|
+
expect(outcome[1]).toBeInstanceOf(FakeClient);
|
|
1877
|
+
});
|
|
1878
|
+
});
|
|
1879
|
+
|
|
1880
|
+
it('records entity operations', async () => {
|
|
1881
|
+
EntityOperationsRecorder.create().record('Cat', 'insert');
|
|
1882
|
+
|
|
1883
|
+
expect(
|
|
1884
|
+
await value('orm_entity_operations_total', {
|
|
1885
|
+
entity: 'Cat',
|
|
1886
|
+
op: 'insert',
|
|
1887
|
+
}),
|
|
1888
|
+
).toBe(1);
|
|
1889
|
+
});
|
|
1890
|
+
|
|
1891
|
+
it('metrics are shared per process: a second instance does not fail on registration', () => {
|
|
1892
|
+
expect(() => DbClientMetrics.create(config(1), APP)).not.toThrow();
|
|
1893
|
+
});
|
|
1894
|
+
});
|