Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Connection configuration provider - without changes to drivers #3497

Merged
merged 14 commits into from Oct 27, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
46 changes: 36 additions & 10 deletions lib/client.js
Expand Up @@ -55,7 +55,13 @@ function Client(config = {}) {
this.version = config.version;
}

this.connectionSettings = cloneDeep(config.connection || {});
if (config.connection && config.connection instanceof Function) {
this.connectionConfigProvider = config.connection;
this.connectionConfigExpirationChecker = () => true; // causes the provider to be called on first use
} else {
this.connectionSettings = cloneDeep(config.connection || {});
this.connectionConfigExpirationChecker = null;
}
if (this.driverName && config.connection) {
this.initializeDriver();
if (!config.pool || (config.pool && config.pool.max !== 0)) {
Expand Down Expand Up @@ -254,16 +260,36 @@ Object.assign(Client.prototype, {
// choose the smallest, positive timeout setting and set on poolConfig
poolConfig.acquireTimeoutMillis = Math.min(...timeouts);

return Object.assign(poolConfig, {
create: () => {
return this.acquireRawConnection().then(async (connection) => {
connection.__knexUid = uniqueId('__knexUid');
const updatePoolConnectionSettingsFromProvider = async () => {
if (!this.connectionConfigProvider) {
return; // static configuration, nothing to update
}
if (
!this.connectionConfigExpirationChecker ||
!this.connectionConfigExpirationChecker()
) {
return; // not expired, reuse existing connection
}
const providerResult = await this.connectionConfigProvider();
if (providerResult.expirationChecker) {
this.connectionConfigExpirationChecker =
providerResult.expirationChecker;
delete providerResult.expirationChecker; // MySQL2 driver warns on receiving extra properties
} else {
this.connectionConfigExpirationChecker = null;
}
this.connectionSettings = providerResult;
};

if (poolConfig.afterCreate) {
await promisify(poolConfig.afterCreate)(connection);
}
return connection;
});
return Object.assign(poolConfig, {
create: async () => {
await updatePoolConnectionSettingsFromProvider();
const connection = await this.acquireRawConnection();
connection.__knexUid = uniqueId('__knexUid');
if (poolConfig.afterCreate) {
await promisify(poolConfig.afterCreate)(connection);
}
return connection;
},

destroy: (connection) => {
Expand Down
71 changes: 71 additions & 0 deletions test/integration/connection-config-provider.js
@@ -0,0 +1,71 @@
/*global expect*/

'use strict';

const _ = require('lodash');
const makeKnex = require('../../knex');

module.exports = function(config) {
describe('Connection configuration provider', function() {
let configWorkingCopy;
let providerInvocationCount;
let connectionConfigWorkingCopy;

this.beforeEach(() => {
configWorkingCopy = _.cloneDeep(config);
configWorkingCopy.pool.min = 1;
configWorkingCopy.pool.max = 2;
providerInvocationCount = 0;
connectionConfigWorkingCopy = configWorkingCopy.connection;
});

it('is not used when configuration is static', async function() {
return runTwoConcurrentTransactions(0);
});

it('can return a promise for a config object, which is reused when not given given an expiry checker', async () => {
configWorkingCopy.connection = () => {
++providerInvocationCount;
return Promise.resolve(connectionConfigWorkingCopy);
};
return runTwoConcurrentTransactions(1);
});

it('can return a config object, which is reused when not given given an expiry checker', async () => {
configWorkingCopy.connection = () => {
++providerInvocationCount;
return connectionConfigWorkingCopy;
};
return runTwoConcurrentTransactions(1);
});

it('reuses the same resolved config when not yet expired', async () => {
configWorkingCopy.connection = () => {
++providerInvocationCount;
return Object.assign(connectionConfigWorkingCopy, {
expirationChecker: () => false,
});
};
return runTwoConcurrentTransactions(1);
});

it('replaces the resolved config when expired', async () => {
configWorkingCopy.connection = () => {
++providerInvocationCount;
return Object.assign(connectionConfigWorkingCopy, {
expirationChecker: () => true,
});
};
return runTwoConcurrentTransactions(2);
});

async function runTwoConcurrentTransactions(expectedInvocationCount) {
const knex = makeKnex(configWorkingCopy);
await knex.transaction(async (trx) => {
await knex.transaction(async (trx2) => {});
});
await knex.destroy();
expect(providerInvocationCount).equals(expectedInvocationCount);
}
});
};
1 change: 1 addition & 0 deletions test/integration/index.js
Expand Up @@ -6,6 +6,7 @@ const config = require('../knexfile');
const fs = require('fs');

Object.keys(config).forEach((dialectName) => {
require('./connection-config-provider')(config[dialectName]);
return require('./suite')(logger(knex(config[dialectName])));
});

Expand Down
34 changes: 23 additions & 11 deletions types/index.d.ts
Expand Up @@ -1609,17 +1609,7 @@ declare namespace Knex {
client?: string | typeof Client;
dialect?: string;
version?: string;
connection?:
| string
| ConnectionConfig
| MariaSqlConnectionConfig
| MySqlConnectionConfig
| MsSqlConnectionConfig
| OracleDbConnectionConfig
| PgConnectionConfig
| RedshiftConnectionConfig
| Sqlite3ConnectionConfig
| SocketConnectionConfig;
connection?: string | StaticConnectionConfig | ConnectionConfigProvider;
pool?: PoolConfig;
migrations?: MigratorConfig;
postProcessResponse?: (result: any, queryContext: any) => any;
Expand All @@ -1636,6 +1626,21 @@ declare namespace Knex {
log?: Logger;
}

type StaticConnectionConfig =
| ConnectionConfig
| MariaSqlConnectionConfig
| MySqlConnectionConfig
| MsSqlConnectionConfig
| OracleDbConnectionConfig
| PgConnectionConfig
| RedshiftConnectionConfig
| Sqlite3ConnectionConfig
| SocketConnectionConfig;

type ConnectionConfigProvider = SyncConnectionConfigProvider | AsyncConnectionConfigProvider;
type SyncConnectionConfigProvider = () => StaticConnectionConfig;
type AsyncConnectionConfigProvider = () => Promise<StaticConnectionConfig>;

interface ConnectionConfig {
host: string;
user: string;
Expand All @@ -1660,6 +1665,7 @@ declare namespace Knex {
requestTimeout?: number;
stream?: boolean;
parseJSON?: boolean;
expirationChecker?(): boolean;
options?: {
encrypt?: boolean;
instanceName?: string;
Expand Down Expand Up @@ -1707,6 +1713,7 @@ declare namespace Knex {
read_default_group?: string;
charset?: string;
streamHWM?: number;
expirationChecker?(): boolean;
}

interface MariaSslConfiguration {
Expand All @@ -1716,6 +1723,7 @@ declare namespace Knex {
capath?: string;
cipher?: string;
rejectUnauthorized?: boolean;
expirationChecker?(): boolean;
}

// Config object for mysql: https://github.com/mysqljs/mysql#connection-options
Expand Down Expand Up @@ -1743,6 +1751,7 @@ declare namespace Knex {
flags?: string;
ssl?: string | MariaSslConfiguration;
decimalNumbers?: boolean;
expirationChecker?(): boolean;
}

interface OracleDbConnectionConfig {
Expand All @@ -1755,6 +1764,7 @@ declare namespace Knex {
debug?: boolean;
requestTimeout?: number;
connectString?: string;
expirationChecker?(): boolean;
}

// Config object for pg: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/pg/index.d.ts
Expand All @@ -1778,6 +1788,7 @@ declare namespace Knex {
interface Sqlite3ConnectionConfig {
filename: string;
debug?: boolean;
expirationChecker?(): boolean;
}

interface SocketConnectionConfig {
Expand All @@ -1786,6 +1797,7 @@ declare namespace Knex {
password: string;
database: string;
debug?: boolean;
expirationChecker?(): boolean;
}

interface PoolConfig {
Expand Down