@rsdk/db.knex 5.12.0-next.7 → 5.12.0-next.9
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 +3 -1
- package/dist/index.js.map +1 -1
- package/dist/providers/knex.config.d.ts +4 -3
- package/dist/providers/knex.config.js +23 -5
- package/dist/providers/knex.config.js.map +1 -1
- package/dist/providers/knex.factory.d.ts +2 -0
- package/dist/providers/knex.factory.js +77 -7
- package/dist/providers/knex.factory.js.map +1 -1
- package/package.json +2 -2
- package/src/index.ts +1 -0
- package/src/providers/knex.config.ts +21 -6
- package/src/providers/knex.factory.ts +98 -8
package/dist/index.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { TransactionRunner } from '@rsdk/db';
|
|
|
2
2
|
export { KnexPlugin } from './knex.plugin';
|
|
3
3
|
export { InjectKnex, KNEX_INJECTION_TOKEN } from './inject-knex.decorator';
|
|
4
4
|
export { IsolationLevel } from './types';
|
|
5
|
+
export { KnexPluginConfig } from './providers/knex.config';
|
|
5
6
|
export declare const Runner: TransactionRunner<import("./types").IsolationLevel, import("./internal/context").KnexContext>;
|
|
6
7
|
export declare const Transactional: (payload?: {
|
|
7
8
|
isolation?: import("./types").IsolationLevel;
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.Transactional = exports.Runner = exports.IsolationLevel = exports.KNEX_INJECTION_TOKEN = exports.InjectKnex = exports.KnexPlugin = void 0;
|
|
3
|
+
exports.Transactional = exports.Runner = exports.KnexPluginConfig = exports.IsolationLevel = exports.KNEX_INJECTION_TOKEN = exports.InjectKnex = exports.KnexPlugin = void 0;
|
|
4
4
|
const db_1 = require("@rsdk/db");
|
|
5
5
|
const strategy_1 = require("./internal/strategy");
|
|
6
6
|
var knex_plugin_1 = require("./knex.plugin");
|
|
@@ -10,6 +10,8 @@ Object.defineProperty(exports, "InjectKnex", { enumerable: true, get: function (
|
|
|
10
10
|
Object.defineProperty(exports, "KNEX_INJECTION_TOKEN", { enumerable: true, get: function () { return inject_knex_decorator_1.KNEX_INJECTION_TOKEN; } });
|
|
11
11
|
var types_1 = require("./types");
|
|
12
12
|
Object.defineProperty(exports, "IsolationLevel", { enumerable: true, get: function () { return types_1.IsolationLevel; } });
|
|
13
|
+
var knex_config_1 = require("./providers/knex.config");
|
|
14
|
+
Object.defineProperty(exports, "KnexPluginConfig", { enumerable: true, get: function () { return knex_config_1.KnexPluginConfig; } });
|
|
13
15
|
exports.Runner = new db_1.TransactionRunner(new strategy_1.KnexTransactionalStrategy());
|
|
14
16
|
exports.Transactional = exports.Runner.Transactional.bind(exports.Runner);
|
|
15
17
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,iCAA6C;AAE7C,kDAAgE;AAEhE,6CAA2C;AAAlC,yGAAA,UAAU,OAAA;AACnB,iEAA2E;AAAlE,mHAAA,UAAU,OAAA;AAAE,6HAAA,oBAAoB,OAAA;AACzC,iCAAyC;AAAhC,uGAAA,cAAc,OAAA;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,iCAA6C;AAE7C,kDAAgE;AAEhE,6CAA2C;AAAlC,yGAAA,UAAU,OAAA;AACnB,iEAA2E;AAAlE,mHAAA,UAAU,OAAA;AAAE,6HAAA,oBAAoB,OAAA;AACzC,iCAAyC;AAAhC,uGAAA,cAAc,OAAA;AACvB,uDAA2D;AAAlD,+GAAA,gBAAgB,OAAA;AAEZ,QAAA,MAAM,GAAG,IAAI,sBAAiB,CAAC,IAAI,oCAAyB,EAAE,CAAC,CAAC;AAChE,QAAA,aAAa,GAAG,cAAM,CAAC,aAAa,CAAC,IAAI,CAAC,cAAM,CAAC,CAAC"}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { Timespan } from '@rsdk/common';
|
|
2
2
|
import { Config } from '@rsdk/core';
|
|
3
|
-
import { SslModeEnum } from '@rsdk/db';
|
|
3
|
+
import { MultiHostUrl, SslModeEnum } from '@rsdk/db';
|
|
4
4
|
export declare class KnexPluginConfig extends Config {
|
|
5
|
-
url:
|
|
5
|
+
url: MultiHostUrl;
|
|
6
|
+
multiHostBootstrapFallback: boolean;
|
|
6
7
|
schema: string;
|
|
7
8
|
poolMin: number;
|
|
8
9
|
poolMax: number;
|
|
@@ -14,5 +15,5 @@ export declare class KnexPluginConfig extends Config {
|
|
|
14
15
|
sslMode: SslModeEnum;
|
|
15
16
|
tlsCa?: string | undefined;
|
|
16
17
|
tlsCert?: string | undefined;
|
|
17
|
-
|
|
18
|
+
tlsKey?: string | undefined;
|
|
18
19
|
}
|
|
@@ -15,6 +15,7 @@ const core_1 = require("@rsdk/core");
|
|
|
15
15
|
const db_1 = require("@rsdk/db");
|
|
16
16
|
let KnexPluginConfig = class KnexPluginConfig extends core_1.Config {
|
|
17
17
|
url;
|
|
18
|
+
multiHostBootstrapFallback;
|
|
18
19
|
schema;
|
|
19
20
|
poolMin;
|
|
20
21
|
poolMax;
|
|
@@ -26,15 +27,32 @@ let KnexPluginConfig = class KnexPluginConfig extends core_1.Config {
|
|
|
26
27
|
sslMode;
|
|
27
28
|
tlsCa;
|
|
28
29
|
tlsCert;
|
|
29
|
-
|
|
30
|
+
tlsKey;
|
|
30
31
|
};
|
|
31
32
|
exports.KnexPluginConfig = KnexPluginConfig;
|
|
32
33
|
__decorate([
|
|
33
|
-
(0, core_1.Property)('URL', new
|
|
34
|
-
description:
|
|
34
|
+
(0, core_1.Property)('URL', new db_1.MultiHostUrlParser(), {
|
|
35
|
+
description: (0, common_1.text) `
|
|
36
|
+
Database server url. Supports multi-host syntax for Postgres:
|
|
37
|
+
\`postgres://user:pass@host1:5432,host2:5432/db\`. Port is optional (driver default, e.g. 5432 for PostgreSQL).
|
|
38
|
+
With \`pg-native\` installed RSDK uses libpq runtime failover. Without \`pg-native\`
|
|
39
|
+
the app fails fast at startup unless DB_MULTIHOST_BOOTSTRAP_FALLBACK=true is set.
|
|
40
|
+
See docs/md/DATABASES.md for details.
|
|
41
|
+
`,
|
|
35
42
|
}),
|
|
36
|
-
__metadata("design:type",
|
|
43
|
+
__metadata("design:type", db_1.MultiHostUrl)
|
|
37
44
|
], KnexPluginConfig.prototype, "url", void 0);
|
|
45
|
+
__decorate([
|
|
46
|
+
(0, core_1.Property)('MULTIHOST_BOOTSTRAP_FALLBACK', new core_1.BoolParser(), {
|
|
47
|
+
defaultValue: false,
|
|
48
|
+
description: (0, common_1.text) `
|
|
49
|
+
Allows silent fallback to bootstrap-resolve when DB_URL has multiple
|
|
50
|
+
hosts but \`pg-native\` is not installed. When false (default) the app
|
|
51
|
+
fails fast at startup so that runtime failover is never quietly downgraded.
|
|
52
|
+
`,
|
|
53
|
+
}),
|
|
54
|
+
__metadata("design:type", Boolean)
|
|
55
|
+
], KnexPluginConfig.prototype, "multiHostBootstrapFallback", void 0);
|
|
38
56
|
__decorate([
|
|
39
57
|
(0, core_1.Property)('SCHEMA', new core_1.StringParser(), {
|
|
40
58
|
description: (0, common_1.text) `
|
|
@@ -135,7 +153,7 @@ __decorate([
|
|
|
135
153
|
description: 'Path to client key',
|
|
136
154
|
}),
|
|
137
155
|
__metadata("design:type", Object)
|
|
138
|
-
], KnexPluginConfig.prototype, "
|
|
156
|
+
], KnexPluginConfig.prototype, "tlsKey", void 0);
|
|
139
157
|
exports.KnexPluginConfig = KnexPluginConfig = __decorate([
|
|
140
158
|
(0, core_1.ConfigSection)({
|
|
141
159
|
name: 'knex database config',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"knex.config.js","sourceRoot":"","sources":["../../src/providers/knex.config.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,yC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C,UAAU,EAAE,IAAI,mBAAY,EAAE,EAAE;QACxC,YAAY,EAAE,SAAS;QACvB,WAAW,EAAE,4BAA4B;KAC1C,CAAC;;iDAC2B;AAM7B;IAJC,IAAA,eAAQ,EAAC,SAAS,EAAE,IAAI,mBAAY,EAAE,EAAE;QACvC,YAAY,EAAE,SAAS;QACvB,WAAW,EAAE,oBAAoB;KAClC,CAAC;;gDAC0B;2BA7GjB,gBAAgB;IAL5B,IAAA,oBAAa,EAAC;QACb,IAAI,EAAE,sBAAsB;QAC5B,IAAI,EAAE,CAAC,gBAAS,CAAC,cAAc,EAAE,gBAAS,CAAC,OAAO,CAAC;QACnD,MAAM,EAAE,IAAI;KACb,CAAC;GACW,gBAAgB,CA8G5B"}
|
|
@@ -10,4 +10,6 @@ export declare class KnexFactory implements OnApplicationShutdown {
|
|
|
10
10
|
constructor(appName: string, logger: ILogger, config: KnexPluginConfig);
|
|
11
11
|
create(driver: string): Promise<Knex>;
|
|
12
12
|
onApplicationShutdown(): Promise<void>;
|
|
13
|
+
private knexProbe;
|
|
14
|
+
private buildConnectionOptions;
|
|
13
15
|
}
|
|
@@ -34,15 +34,41 @@ let KnexFactory = class KnexFactory {
|
|
|
34
34
|
if (this.instance) {
|
|
35
35
|
return this.instance;
|
|
36
36
|
}
|
|
37
|
+
const ssl = (0, db_1.getSecureContextOptions)(this.config);
|
|
38
|
+
/**
|
|
39
|
+
* libpq-режим имеет смысл только для wire-совместимых с PostgreSQL
|
|
40
|
+
* клиентов knex. Knex принимает несколько алиасов для одного диалекта
|
|
41
|
+
* (`pg`, `postgres`, `postgresql` → `postgres`), поэтому проверяем все
|
|
42
|
+
* варианты. Для mysql/mssql/sqlite multi-host идёт через resolver.
|
|
43
|
+
* @see node_modules/knex/lib/constants.js (CLIENT_ALIASES)
|
|
44
|
+
*/
|
|
45
|
+
const isPostgresFamily = driver === 'pg' ||
|
|
46
|
+
driver === 'postgres' ||
|
|
47
|
+
driver === 'postgresql' ||
|
|
48
|
+
driver === 'pgnative';
|
|
49
|
+
/**
|
|
50
|
+
* Probe передаётся только если фолбэк явно разрешён через env.
|
|
51
|
+
* Иначе resolveDbConnection упадёт с MultiHostNativeRequired при
|
|
52
|
+
* отсутствии pg-native — runtime failover не будет тихо потерян.
|
|
53
|
+
*/
|
|
54
|
+
const resolved = await (0, db_1.resolveDbConnection)({
|
|
55
|
+
url: this.config.url,
|
|
56
|
+
logger: this.logger,
|
|
57
|
+
isPostgresFamily,
|
|
58
|
+
...(this.config.multiHostBootstrapFallback && {
|
|
59
|
+
bootstrapProbe: (candidate) => this.knexProbe(driver, candidate, ssl),
|
|
60
|
+
}),
|
|
61
|
+
});
|
|
37
62
|
this.instance = (0, knex_1.knex)({
|
|
38
|
-
|
|
63
|
+
/**
|
|
64
|
+
* При активации native пути переключаем dialect на встроенный в knex
|
|
65
|
+
* `pgnative` — он отличается от `pg` тем, что использует
|
|
66
|
+
* `require('pg').native` как driver factory и поддерживает
|
|
67
|
+
* `Client.cancel` через `PQcancel`.
|
|
68
|
+
*/
|
|
69
|
+
client: resolved.kind === 'native-libpq' ? 'pgnative' : driver,
|
|
39
70
|
log: new knex_logger_adapter_1.KnexLoggerAdapter(this.logger),
|
|
40
|
-
connection:
|
|
41
|
-
connectionString: this.config.url.toString(),
|
|
42
|
-
keepAlive: this.config.keepAlive,
|
|
43
|
-
keepAliveInitialDelay: this.config.keepAliveInitialDelay,
|
|
44
|
-
ssl: (0, db_1.getSecureContextOptions)(this.config),
|
|
45
|
-
},
|
|
71
|
+
connection: this.buildConnectionOptions(resolved, ssl),
|
|
46
72
|
...(this.config.schema && {
|
|
47
73
|
searchPath: [this.config.schema],
|
|
48
74
|
}),
|
|
@@ -90,6 +116,50 @@ let KnexFactory = class KnexFactory {
|
|
|
90
116
|
await this.instance.destroy();
|
|
91
117
|
}
|
|
92
118
|
}
|
|
119
|
+
async knexProbe(driver, candidate, ssl) {
|
|
120
|
+
const probe = (0, knex_1.knex)({
|
|
121
|
+
client: driver,
|
|
122
|
+
connection: {
|
|
123
|
+
connectionString: candidate.toString(),
|
|
124
|
+
ssl,
|
|
125
|
+
},
|
|
126
|
+
pool: { min: 0, max: 1 },
|
|
127
|
+
});
|
|
128
|
+
try {
|
|
129
|
+
await probe.raw('SELECT 1');
|
|
130
|
+
}
|
|
131
|
+
finally {
|
|
132
|
+
await probe.destroy().catch(() => {
|
|
133
|
+
/* swallow destroy errors */
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
buildConnectionOptions(resolved, ssl) {
|
|
138
|
+
if (resolved.kind === 'native-libpq') {
|
|
139
|
+
/**
|
|
140
|
+
* `pg-connection-string` падает на multi-host URI, поэтому отдаём
|
|
141
|
+
* строку через `nativeConnectionString` — pg.native использует её
|
|
142
|
+
* напрямую в libpq. SSL-options в native-режиме не применяются —
|
|
143
|
+
* они должны быть в самой URL (`sslmode=`/`sslrootcert=`).
|
|
144
|
+
*/
|
|
145
|
+
return {
|
|
146
|
+
host: resolved.firstHostEntry.host,
|
|
147
|
+
port: resolved.firstHostEntry.port,
|
|
148
|
+
...(resolved.username && { user: resolved.username }),
|
|
149
|
+
...(resolved.password && { password: resolved.password }),
|
|
150
|
+
...(resolved.database && { database: resolved.database }),
|
|
151
|
+
nativeConnectionString: resolved.multiHostUrl,
|
|
152
|
+
keepAlive: this.config.keepAlive,
|
|
153
|
+
keepAliveInitialDelay: this.config.keepAliveInitialDelay,
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
return {
|
|
157
|
+
connectionString: resolved.url.toString(),
|
|
158
|
+
keepAlive: this.config.keepAlive,
|
|
159
|
+
keepAliveInitialDelay: this.config.keepAliveInitialDelay,
|
|
160
|
+
ssl,
|
|
161
|
+
};
|
|
162
|
+
}
|
|
93
163
|
};
|
|
94
164
|
exports.KnexFactory = KnexFactory;
|
|
95
165
|
exports.KnexFactory = KnexFactory = __decorate([
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"knex.factory.js","sourceRoot":"","sources":["../../src/providers/knex.factory.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AACA,2CAA4C;AAC5C,qCAAmD;AACnD,
|
|
1
|
+
{"version":3,"file":"knex.factory.js","sourceRoot":"","sources":["../../src/providers/knex.factory.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AACA,2CAA4C;AAC5C,qCAAmD;AACnD,iCAIkB;AAGlB,+BAA4B;AAC5B,mDAAkD;AAElD,+CAAiD;AACjD,+DAA0D;AAKnD,IAAM,WAAW,GAAjB,MAAM,WAAW;IAIQ;IACgB;IAC3B;IALX,QAAQ,GAAgB,IAAI,CAAC;IAErC,YAC8B,OAAe,EACC,MAAe,EAC1C,MAAwB;QAFb,YAAO,GAAP,OAAO,CAAQ;QACC,WAAM,GAAN,MAAM,CAAS;QAC1C,WAAM,GAAN,MAAM,CAAkB;IACxC,CAAC;IAEG,KAAK,CAAC,MAAM,CAAC,MAAc;QAChC,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YAClB,OAAO,IAAI,CAAC,QAAQ,CAAC;QACvB,CAAC;QAED,MAAM,GAAG,GAAG,IAAA,4BAAuB,EAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAEjD;;;;;;WAMG;QACH,MAAM,gBAAgB,GACpB,MAAM,KAAK,IAAI;YACf,MAAM,KAAK,UAAU;YACrB,MAAM,KAAK,YAAY;YACvB,MAAM,KAAK,UAAU,CAAC;QAExB;;;;WAIG;QACH,MAAM,QAAQ,GAAG,MAAM,IAAA,wBAAmB,EAAC;YACzC,GAAG,EAAE,IAAI,CAAC,MAAM,CAAC,GAAG;YACpB,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,gBAAgB;YAChB,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,0BAA0B,IAAI;gBAC5C,cAAc,EAAE,CAAC,SAAc,EAAiB,EAAE,CAChD,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,SAAS,EAAE,GAAG,CAAC;aACzC,CAAC;SAC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EAAE,QAAQ,EAAE,QAAQ,CAAC,QAAQ,EAAE,CAAC;gBACzD,GAAG,CAAC,QAAQ,CAAC,QAAQ,IAAI,EAAE,QAAQ,EAAE,QAAQ,CAAC,QAAQ,EAAE,CAAC;gBACzD,sBAAsB,EAAE,QAAQ,CAAC,YAAY;gBAC7C,SAAS,EAAE,IAAI,CAAC,MAAM,CAAC,SAAS;gBAChC,qBAAqB,EAAE,IAAI,CAAC,MAAM,CAAC,qBAAqB;aAC9B,CAAC;QAC/B,CAAC;QACD,OAAO;YACL,gBAAgB,EAAE,QAAQ,CAAC,GAAG,CAAC,QAAQ,EAAE;YACzC,SAAS,EAAE,IAAI,CAAC,MAAM,CAAC,SAAS;YAChC,qBAAqB,EAAE,IAAI,CAAC,MAAM,CAAC,qBAAqB;YACxD,GAAG;SACuB,CAAC;IAC/B,CAAC;CACF,CAAA;AA/JY,kCAAW;sBAAX,WAAW;IADvB,IAAA,mBAAU,GAAE;IAKR,WAAA,IAAA,cAAO,GAAE,CAAA;IACT,WAAA,IAAA,mBAAY,EAAC,WAAW,CAAC,CAAA;qDACD,8BAAgB;GANhC,WAAW,CA+JvB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rsdk/db.knex",
|
|
3
|
-
"version": "5.12.0-next.
|
|
3
|
+
"version": "5.12.0-next.9",
|
|
4
4
|
"description": "Knex integration for platform",
|
|
5
5
|
"license": "Apache License 2.0",
|
|
6
6
|
"publishConfig": {
|
|
@@ -25,5 +25,5 @@
|
|
|
25
25
|
"reflect-metadata": "^0.1.12 || ^0.2.0",
|
|
26
26
|
"rxjs": "^7.1.0"
|
|
27
27
|
},
|
|
28
|
-
"gitHead": "
|
|
28
|
+
"gitHead": "43bfe38011bd365e92e35b8d159ab6e47a42c284"
|
|
29
29
|
}
|
package/src/index.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { KnexTransactionalStrategy } from './internal/strategy';
|
|
|
5
5
|
export { KnexPlugin } from './knex.plugin';
|
|
6
6
|
export { InjectKnex, KNEX_INJECTION_TOKEN } from './inject-knex.decorator';
|
|
7
7
|
export { IsolationLevel } from './types';
|
|
8
|
+
export { KnexPluginConfig } from './providers/knex.config';
|
|
8
9
|
|
|
9
10
|
export const Runner = new TransactionRunner(new KnexTransactionalStrategy());
|
|
10
11
|
export const Transactional = Runner.Transactional.bind(Runner);
|
|
@@ -9,9 +9,8 @@ import {
|
|
|
9
9
|
Property,
|
|
10
10
|
StringParser,
|
|
11
11
|
TimespanParser,
|
|
12
|
-
UrlParser,
|
|
13
12
|
} from '@rsdk/core';
|
|
14
|
-
import { SslModeEnum } from '@rsdk/db';
|
|
13
|
+
import { MultiHostUrl, MultiHostUrlParser, SslModeEnum } from '@rsdk/db';
|
|
15
14
|
|
|
16
15
|
@ConfigSection({
|
|
17
16
|
name: 'knex database config',
|
|
@@ -19,10 +18,26 @@ import { SslModeEnum } from '@rsdk/db';
|
|
|
19
18
|
prefix: 'DB',
|
|
20
19
|
})
|
|
21
20
|
export class KnexPluginConfig extends Config {
|
|
22
|
-
@Property('URL', new
|
|
23
|
-
description:
|
|
21
|
+
@Property('URL', new MultiHostUrlParser(), {
|
|
22
|
+
description: text`
|
|
23
|
+
Database server url. Supports multi-host syntax for Postgres:
|
|
24
|
+
\`postgres://user:pass@host1:5432,host2:5432/db\`. Port is optional (driver default, e.g. 5432 for PostgreSQL).
|
|
25
|
+
With \`pg-native\` installed RSDK uses libpq runtime failover. Without \`pg-native\`
|
|
26
|
+
the app fails fast at startup unless DB_MULTIHOST_BOOTSTRAP_FALLBACK=true is set.
|
|
27
|
+
See docs/md/DATABASES.md for details.
|
|
28
|
+
`,
|
|
29
|
+
})
|
|
30
|
+
url!: MultiHostUrl;
|
|
31
|
+
|
|
32
|
+
@Property('MULTIHOST_BOOTSTRAP_FALLBACK', new BoolParser(), {
|
|
33
|
+
defaultValue: false,
|
|
34
|
+
description: text`
|
|
35
|
+
Allows silent fallback to bootstrap-resolve when DB_URL has multiple
|
|
36
|
+
hosts but \`pg-native\` is not installed. When false (default) the app
|
|
37
|
+
fails fast at startup so that runtime failover is never quietly downgraded.
|
|
38
|
+
`,
|
|
24
39
|
})
|
|
25
|
-
|
|
40
|
+
multiHostBootstrapFallback!: boolean;
|
|
26
41
|
|
|
27
42
|
@Property('SCHEMA', new StringParser(), {
|
|
28
43
|
description: text`
|
|
@@ -111,5 +126,5 @@ export class KnexPluginConfig extends Config {
|
|
|
111
126
|
defaultValue: undefined,
|
|
112
127
|
description: 'Path to client key',
|
|
113
128
|
})
|
|
114
|
-
|
|
129
|
+
tlsKey?: string | undefined;
|
|
115
130
|
}
|
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
import type { OnApplicationShutdown } from '@nestjs/common';
|
|
2
2
|
import { Injectable } from '@nestjs/common';
|
|
3
3
|
import { AppName, InjectLogger } from '@rsdk/core';
|
|
4
|
-
import {
|
|
4
|
+
import {
|
|
5
|
+
getSecureContextOptions,
|
|
6
|
+
resolveDbConnection,
|
|
7
|
+
type ResolvedDbConnection,
|
|
8
|
+
} from '@rsdk/db';
|
|
5
9
|
import { ILogger } from '@rsdk/logging';
|
|
6
10
|
import type { Knex } from 'knex';
|
|
7
11
|
import { knex } from 'knex';
|
|
@@ -10,6 +14,8 @@ import { setTimeout } from 'node:timers/promises';
|
|
|
10
14
|
import { KnexPluginConfig } from './knex.config';
|
|
11
15
|
import { KnexLoggerAdapter } from './knex-logger.adapter';
|
|
12
16
|
|
|
17
|
+
type SslOption = ReturnType<typeof getSecureContextOptions>;
|
|
18
|
+
|
|
13
19
|
@Injectable()
|
|
14
20
|
export class KnexFactory implements OnApplicationShutdown {
|
|
15
21
|
private instance: Knex | null = null;
|
|
@@ -25,15 +31,46 @@ export class KnexFactory implements OnApplicationShutdown {
|
|
|
25
31
|
return this.instance;
|
|
26
32
|
}
|
|
27
33
|
|
|
34
|
+
const ssl = getSecureContextOptions(this.config);
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* libpq-режим имеет смысл только для wire-совместимых с PostgreSQL
|
|
38
|
+
* клиентов knex. Knex принимает несколько алиасов для одного диалекта
|
|
39
|
+
* (`pg`, `postgres`, `postgresql` → `postgres`), поэтому проверяем все
|
|
40
|
+
* варианты. Для mysql/mssql/sqlite multi-host идёт через resolver.
|
|
41
|
+
* @see node_modules/knex/lib/constants.js (CLIENT_ALIASES)
|
|
42
|
+
*/
|
|
43
|
+
const isPostgresFamily =
|
|
44
|
+
driver === 'pg' ||
|
|
45
|
+
driver === 'postgres' ||
|
|
46
|
+
driver === 'postgresql' ||
|
|
47
|
+
driver === 'pgnative';
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Probe передаётся только если фолбэк явно разрешён через env.
|
|
51
|
+
* Иначе resolveDbConnection упадёт с MultiHostNativeRequired при
|
|
52
|
+
* отсутствии pg-native — runtime failover не будет тихо потерян.
|
|
53
|
+
*/
|
|
54
|
+
const resolved = await resolveDbConnection({
|
|
55
|
+
url: this.config.url,
|
|
56
|
+
logger: this.logger,
|
|
57
|
+
isPostgresFamily,
|
|
58
|
+
...(this.config.multiHostBootstrapFallback && {
|
|
59
|
+
bootstrapProbe: (candidate: URL): Promise<void> =>
|
|
60
|
+
this.knexProbe(driver, candidate, ssl),
|
|
61
|
+
}),
|
|
62
|
+
});
|
|
63
|
+
|
|
28
64
|
this.instance = knex({
|
|
29
|
-
|
|
65
|
+
/**
|
|
66
|
+
* При активации native пути переключаем dialect на встроенный в knex
|
|
67
|
+
* `pgnative` — он отличается от `pg` тем, что использует
|
|
68
|
+
* `require('pg').native` как driver factory и поддерживает
|
|
69
|
+
* `Client.cancel` через `PQcancel`.
|
|
70
|
+
*/
|
|
71
|
+
client: resolved.kind === 'native-libpq' ? 'pgnative' : driver,
|
|
30
72
|
log: new KnexLoggerAdapter(this.logger),
|
|
31
|
-
connection:
|
|
32
|
-
connectionString: this.config.url.toString(),
|
|
33
|
-
keepAlive: this.config.keepAlive,
|
|
34
|
-
keepAliveInitialDelay: this.config.keepAliveInitialDelay,
|
|
35
|
-
ssl: getSecureContextOptions(this.config),
|
|
36
|
-
},
|
|
73
|
+
connection: this.buildConnectionOptions(resolved, ssl),
|
|
37
74
|
...(this.config.schema && {
|
|
38
75
|
searchPath: [this.config.schema],
|
|
39
76
|
}),
|
|
@@ -86,4 +123,57 @@ export class KnexFactory implements OnApplicationShutdown {
|
|
|
86
123
|
await this.instance.destroy();
|
|
87
124
|
}
|
|
88
125
|
}
|
|
126
|
+
|
|
127
|
+
private async knexProbe(
|
|
128
|
+
driver: string,
|
|
129
|
+
candidate: URL,
|
|
130
|
+
ssl: SslOption,
|
|
131
|
+
): Promise<void> {
|
|
132
|
+
const probe = knex({
|
|
133
|
+
client: driver,
|
|
134
|
+
connection: {
|
|
135
|
+
connectionString: candidate.toString(),
|
|
136
|
+
ssl,
|
|
137
|
+
},
|
|
138
|
+
pool: { min: 0, max: 1 },
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
try {
|
|
142
|
+
await probe.raw('SELECT 1');
|
|
143
|
+
} finally {
|
|
144
|
+
await probe.destroy().catch(() => {
|
|
145
|
+
/* swallow destroy errors */
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
private buildConnectionOptions(
|
|
151
|
+
resolved: ResolvedDbConnection,
|
|
152
|
+
ssl: SslOption,
|
|
153
|
+
): Knex.PgConnectionConfig {
|
|
154
|
+
if (resolved.kind === 'native-libpq') {
|
|
155
|
+
/**
|
|
156
|
+
* `pg-connection-string` падает на multi-host URI, поэтому отдаём
|
|
157
|
+
* строку через `nativeConnectionString` — pg.native использует её
|
|
158
|
+
* напрямую в libpq. SSL-options в native-режиме не применяются —
|
|
159
|
+
* они должны быть в самой URL (`sslmode=`/`sslrootcert=`).
|
|
160
|
+
*/
|
|
161
|
+
return {
|
|
162
|
+
host: resolved.firstHostEntry.host,
|
|
163
|
+
port: resolved.firstHostEntry.port,
|
|
164
|
+
...(resolved.username && { user: resolved.username }),
|
|
165
|
+
...(resolved.password && { password: resolved.password }),
|
|
166
|
+
...(resolved.database && { database: resolved.database }),
|
|
167
|
+
nativeConnectionString: resolved.multiHostUrl,
|
|
168
|
+
keepAlive: this.config.keepAlive,
|
|
169
|
+
keepAliveInitialDelay: this.config.keepAliveInitialDelay,
|
|
170
|
+
} as Knex.PgConnectionConfig;
|
|
171
|
+
}
|
|
172
|
+
return {
|
|
173
|
+
connectionString: resolved.url.toString(),
|
|
174
|
+
keepAlive: this.config.keepAlive,
|
|
175
|
+
keepAliveInitialDelay: this.config.keepAliveInitialDelay,
|
|
176
|
+
ssl,
|
|
177
|
+
} as Knex.PgConnectionConfig;
|
|
178
|
+
}
|
|
89
179
|
}
|