fix: update mongodb connection options (#11310)

This commit is contained in:
Mohamed Akram 2025-03-30 15:32:20 -07:00 committed by GitHub
parent 03dbc7a697
commit 81bb9d53e8
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 289 additions and 346 deletions

View File

@ -3,7 +3,6 @@ import { ReadPreference } from "./typings"
/**
* MongoDB specific connection options.
* Synced with http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html
*/
export interface MongoConnectionOptions extends BaseDataSourceOptions {
/**
@ -46,11 +45,6 @@ export interface MongoConnectionOptions extends BaseDataSourceOptions {
*/
readonly database?: string
/**
* Specifies whether to force dispatch all operations to the specified host. Default: false
*/
readonly directConnection?: boolean
/**
* The driver object
* This defaults to require("mongodb")
@ -58,293 +52,255 @@ export interface MongoConnectionOptions extends BaseDataSourceOptions {
readonly driver?: any
/**
* Use ssl connection (needs to have a mongod server with ssl support). Default: false
* MongoClientOptions
* Synced with https://mongodb.github.io/node-mongodb-native/5.9/interfaces/MongoClientOptions.html
*/
readonly ssl?: boolean
/**
* Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher).
* Default: true
* The name of the application that created this MongoClient instance.
* MongoDB 3.4 and newer will print this value in the server log upon establishing each connection.
* It is also recorded in the slow query log and profile collections
*/
readonly sslValidate?: boolean
readonly appName?: string
/**
* Array of valid certificates either as Buffers or Strings
* (needs to have a mongod server with ssl support, 2.4 or higher).
*/
readonly sslCA?: string | Buffer
/**
* String or buffer containing the certificate we wish to present
* (needs to have a mongod server with ssl support, 2.4 or higher)
*/
readonly sslCert?: string | Buffer
/**
* String or buffer containing the certificate private key we wish to present
* (needs to have a mongod server with ssl support, 2.4 or higher)
*/
readonly sslKey?: string
/**
* String or buffer containing the certificate password
* (needs to have a mongod server with ssl support, 2.4 or higher)
*/
readonly sslPass?: string | Buffer
/**
* SSL Certificate revocation list binary buffer
* (needs to have a mongod server with ssl support, 2.4 or higher)
*/
readonly sslCRL?: string | Buffer
/**
* Reconnect on error. Default: true
*/
readonly autoReconnect?: boolean
/**
* TCP Socket NoDelay option. Default: true
*/
readonly noDelay?: boolean
/**
* The number of milliseconds to wait before initiating keepAlive on the TCP socket. Default: 30000
*/
readonly keepAlive?: number
/**
* TCP Connection timeout setting. Default: 30000
*/
readonly connectTimeoutMS?: number
/**
* Version of IP stack. Can be 4, 6.
* If undefined, will attempt to connect with IPv6, and will fall back to IPv4 on failure
*/
readonly family?: number
/**
* TCP Socket timeout setting. Default: 360000
*/
readonly socketTimeoutMS?: number
/**
* Server attempt to reconnect #times. Default 30
*/
readonly reconnectTries?: number
/**
* Server will wait #milliseconds between retries. Default 1000
*/
readonly reconnectInterval?: number
/**
* Control if high availability monitoring runs for Replicaset or Mongos proxies. Default true
*/
readonly ha?: boolean
/**
* The High availability period for replicaset inquiry. Default: 10000
*/
readonly haInterval?: number
/**
* The name of the replicaset to connect to
*/
readonly replicaSet?: string
/**
* Sets the range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms).
* Default: 15
*/
readonly acceptableLatencyMS?: number
/**
* Sets the range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms).
* Default: 15
*/
readonly secondaryAcceptableLatencyMS?: number
/**
* Sets if the driver should connect even if no primary is available. Default: false
*/
readonly connectWithNoPrimary?: boolean
/**
* If the database authentication is dependent on another databaseName.
*/
readonly authSource?: string
/**
* The write concern.
*/
readonly w?: string | number
/**
* The write concern timeout value.
*/
readonly wtimeout?: number
/**
* Specify a journal write concern. Default: false
*/
readonly j?: boolean
/**
* Force server to assign _id values instead of driver. Default: false
*/
readonly forceServerObjectId?: boolean
/**
* Serialize functions on any object. Default: false
*/
readonly serializeFunctions?: boolean
/**
* Specify if the BSON serializer should ignore undefined fields. Default: false
*/
readonly ignoreUndefined?: boolean
/**
* Return document results as raw BSON buffers. Default: false
*/
readonly raw?: boolean
/**
* Promotes Long values to number if they fit inside the 53 bits resolution. Default: true
*/
readonly promoteLongs?: boolean
/**
* Promotes Binary BSON values to native Node Buffers. Default: false
*/
readonly promoteBuffers?: boolean
/**
* Promotes BSON values to native types where possible, set to false to only receive wrapper types. Default: true
*/
readonly promoteValues?: boolean
/**
* Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. Default: false
*/
readonly domainsEnabled?: boolean
/**
* Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection,
* default is -1 which is unlimited.
*/
readonly bufferMaxEntries?: number
/**
* The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY,
* ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
*/
readonly readPreference?: ReadPreference | string
/**
* A primary key factory object for generation of custom _id keys.
*/
readonly pkFactory?: any
/**
* A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible.
*/
readonly promiseLibrary?: any
/**
* Specify a read concern for the collection. (only MongoDB 3.2 or higher supported).
*/
readonly readConcern?: any
/**
* Specify a maxStalenessSeconds value for secondary reads, minimum is 90 seconds
*/
readonly maxStalenessSeconds?: number
/**
* Specify the log level used by the driver logger (error/warn/info/debug).
*/
readonly loggerLevel?: "error" | "warn" | "info" | "debug"
// Do not overwrite BaseDataSourceOptions.logger
// readonly logger?: any;
/**
* Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function
* Default: true
*/
readonly checkServerIdentity?: boolean | Function
/**
* Validate MongoClient passed in options for correctness. Default: false
*/
readonly validateOptions?: boolean | any
/**
* The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections
*/
readonly appname?: string
/**
* Sets the authentication mechanism that MongoDB will use to authenticate the connection
* Specify the authentication mechanism that MongoDB will use to authenticate the connection.
*/
readonly authMechanism?: string
/**
* Type of compression to use: snappy or zlib
* Specify the database name associated with the users credentials.
*/
readonly compression?: any
readonly authSource?: string
/**
* Specify a file sync write concern. Default: false
*/
readonly fsync?: boolean
/**
* Read preference tags
*/
readonly readPreferenceTags?: any[]
/**
* The number of retries for a tailable cursor. Default: 5
*/
readonly numberOfRetries?: number
/**
* Enable auto reconnecting for single server instances. Default: true
*/
readonly auto_reconnect?: boolean
/**
* Enable command monitoring for this client. Default: false
*/
readonly monitorCommands?: boolean
/**
* If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections
*/
readonly minSize?: number
/**
* Determines whether or not to use the new url parser. Default: false
*/
readonly useNewUrlParser?: boolean
/**
* Determines whether or not to use the new Server Discovery and Monitoring engine. Default: false
* https://github.com/mongodb/node-mongodb-native/releases/tag/v3.2.1
*/
readonly useUnifiedTopology?: boolean
/**
* Automatic Client-Side Field Level Encryption configuration.
* Optionally enable in-use auto encryption
*/
readonly autoEncryption?: any
/**
* Enables or disables the ability to retry writes upon encountering transient network errors.
* Verifies the certificate `cert` is issued to `hostname`.
*/
readonly checkServerIdentity?: Function
/**
* An array or comma-delimited string of compressors to enable network
* compression for communication between this client and a mongod/mongos instance.
*/
readonly compressors?: string | string[]
/**
* The time in milliseconds to attempt a connection before timing out.
*/
readonly connectTimeoutMS?: number
/**
* Allow a driver to force a Single topology type with a connection string containing one host
*/
readonly directConnection?: boolean
/**
* IP family
*/
readonly family?: number
/**
* Force server to assign `_id` values instead of driver
*/
readonly forceServerObjectId?: boolean
/**
* serialize will not emit undefined fields
* note that the driver sets this to `false`
*/
readonly ignoreUndefined?: boolean
/**
* @deprecated TCP Connection keep alive enabled. Will not be able to turn off in the future.
*/
readonly keepAlive?: boolean
/**
* @deprecated The number of milliseconds to wait before initiating keepAlive on the TCP socket.
* Will not be configurable in the future.
*/
readonly keepAliveInitialDelay?: number
/**
* The size (in milliseconds) of the latency window for selecting among multiple suitable MongoDB instances.
*/
readonly localThresholdMS?: number
/**
* Specifies, in seconds, how stale a secondary can be before the client stops using it for read operations.
*/
readonly maxStalenessSeconds?: number
/**
* The minimum number of connections in the connection pool.
*/
readonly minPoolSize?: number
/**
* Enable command monitoring for this client
*/
readonly monitorCommands?: boolean
/**
* TCP Connection no delay
*/
readonly noDelay?: boolean
/**
* A primary key factory function for generation of custom `_id` keys
*/
readonly pkFactory?: any
/**
* when deserializing a Binary will return it as a node.js Buffer instance.
*/
readonly promoteBuffers?: boolean
/**
* when deserializing a Long will fit it into a Number if it's smaller than 53 bits.
*/
readonly promoteLongs?: boolean
/**
* when deserializing will promote BSON values to their Node.js closest equivalent types.
*/
readonly promoteValues?: boolean
/**
* Enabling the raw option will return a Node.js Buffer which is allocated using allocUnsafe API
*/
readonly raw?: boolean
/**
* Specify a read concern for the collection (only MongoDB 3.2 or higher supported)
*/
readonly readConcern?: any
/**
* Specifies the read preferences for this connection
*/
readonly readPreference?: ReadPreference | string
/**
* Specifies the tags document as a comma-separated list of colon-separated key-value pairs.
*/
readonly readPreferenceTags?: any[]
/**
* Specifies the name of the replica set, if the mongod is a member of a replica set.
*/
readonly replicaSet?: string
/**
* Enable retryable writes.
*/
readonly retryWrites?: boolean
/**
* serialize the javascript functions
*/
readonly serializeFunctions?: boolean
/**
* The time in milliseconds to attempt a send or receive on a socket before the attempt times out.
*/
readonly socketTimeoutMS?: number
/**
* @deprecated A boolean to enable or disables TLS/SSL for the connection.
* (The ssl option is equivalent to the tls option.)
*/
readonly ssl?: boolean
/**
* @deprecated SSL Root Certificate file path.
*
* Will be removed in the next major version. Please use tlsCAFile instead.
*/
readonly sslCA?: string
/**
* @deprecated SSL Certificate revocation list file path.
*
* Will be removed in the next major version.
*/
readonly sslCRL?: string
/**
* @deprecated SSL Certificate file path.
*
* Will be removed in the next major version. Please use tlsCertificateKeyFile instead.
*/
readonly sslCert?: string
/**
* @deprecated SSL Key file file path.
*
* Will be removed in the next major version. Please use tlsCertificateKeyFile instead.
*/
readonly sslKey?: string
/**
* @deprecated SSL Certificate pass phrase.
*
* Will be removed in the next major version. Please use tlsCertificateKeyFilePassword instead.
*/
readonly sslPass?: string
/**
* @deprecated Validate mongod server certificate against Certificate Authority
*
* Will be removed in the next major version. Please use tlsAllowInvalidCertificates instead.
*/
readonly sslValidate?: boolean
/**
* Enables or disables TLS/SSL for the connection.
*/
readonly tls?: boolean
/**
* Bypasses validation of the certificates presented by the mongod/mongos instance
*/
readonly tlsAllowInvalidCertificates?: boolean
/**
* Specifies the location of a local .pem file that contains the root certificate chain from the Certificate Authority.
*/
readonly tlsCAFile?: string
/**
* Specifies the location of a local .pem file that contains the client's TLS/SSL certificate and key.
*/
readonly tlsCertificateKeyFile?: string
/**
* Specifies the password to de-crypt the tlsCertificateKeyFile.
*/
readonly tlsCertificateKeyFilePassword?: string
/**
* @deprecated The write concern w value
*
* Please use the `writeConcern` option instead
*/
readonly w?: string | number
/**
* A MongoDB WriteConcern, which describes the level of acknowledgement
* requested from MongoDB for write operations.
*/
readonly writeConcern?: any
/**
* @deprecated The write concern timeout
*
* Please use the `writeConcern` option instead
*/
readonly wtimeoutMS?: number
}

View File

@ -145,85 +145,74 @@ export class MongoDriver implements Driver {
*/
maxAliasLength?: number
cteCapabilities: CteCapabilities = {
enabled: false,
}
// -------------------------------------------------------------------------
// Protected Properties
// -------------------------------------------------------------------------
/**
* Valid mongo connection options
* NOTE: Keep sync with MongoConnectionOptions
* Sync with http://mongodb.github.io/node-mongodb-native/3.5/api/MongoClient.html
* NOTE: Keep in sync with MongoConnectionOptions
*/
protected validOptionNames: string[] = [
"poolSize",
"appName",
"authMechanism",
"authSource",
"autoEncryption",
"checkServerIdentity",
"compressors",
"connectTimeoutMS",
"directConnection",
"family",
"forceServerObjectId",
"ignoreUndefined",
"keepAlive",
"keepAliveInitialDelay",
"localThresholdMS",
"maxStalenessSeconds",
"minPoolSize",
"monitorCommands",
"noDelay",
"pkFactory",
"promoteBuffers",
"promoteLongs",
"promoteValues",
"raw",
"readConcern",
"readPreference",
"readPreferenceTags",
"replicaSet",
"retryWrites",
"serializeFunctions",
"socketTimeoutMS",
"ssl",
"sslValidate",
"sslCA",
"sslCRL",
"sslCert",
"sslKey",
"sslPass",
"sslCRL",
"autoReconnect",
"noDelay",
"keepAlive",
"keepAliveInitialDelay",
"connectTimeoutMS",
"family",
"socketTimeoutMS",
"reconnectTries",
"reconnectInterval",
"ha",
"haInterval",
"replicaSet",
"secondaryAcceptableLatencyMS",
"acceptableLatencyMS",
"connectWithNoPrimary",
"authSource",
"sslValidate",
"tls",
"tlsAllowInvalidCertificates",
"tlsCAFile",
"tlsCertificateKeyFile",
"tlsCertificateKeyFilePassword",
"w",
"wtimeout",
"j",
"writeConcern",
"forceServerObjectId",
"serializeFunctions",
"ignoreUndefined",
"raw",
"bufferMaxEntries",
"readPreference",
"pkFactory",
"promiseLibrary",
"readConcern",
"maxStalenessSeconds",
"loggerLevel",
// Do not overwrite BaseDataSourceOptions.logger
// "logger",
"promoteValues",
"promoteBuffers",
"promoteLongs",
"domainsEnabled",
"checkServerIdentity",
"validateOptions",
"wtimeoutMS",
// Undocumented deprecated options
// todo: remove next major version
"appname",
// omit auth - we are building url from username and password
// "auth"
"authMechanism",
"compression",
"fsync",
"readPreferenceTags",
"numberOfRetries",
"auto_reconnect",
"minSize",
"monitorCommands",
"j",
"useNewUrlParser",
"useUnifiedTopology",
"autoEncryption",
"retryWrites",
"directConnection",
"wtimeout",
]
cteCapabilities: CteCapabilities = {
enabled: false,
}
// -------------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------------
@ -542,15 +531,11 @@ export class MongoDriver implements Driver {
options.hostReplicaSet ||
options.host + portUrlPart ||
"127.0.0.1" + portUrlPart
}/${options.database || ""}?replicaSet=${options.replicaSet}${
options.tls ? "&tls=true" : ""
}`
}/${options.database || ""}`
} else {
connectionString = `${schemaUrlPart}://${credentialsUrlPart}${
options.host || "127.0.0.1"
}${portUrlPart}/${options.database || ""}${
options.tls ? "?tls=true" : ""
}`
}${portUrlPart}/${options.database || ""}`
}
return connectionString
@ -562,16 +547,18 @@ export class MongoDriver implements Driver {
protected buildConnectionOptions(options: { [key: string]: any }): any {
const mongoOptions: any = {}
for (let index = 0; index < this.validOptionNames.length; index++) {
const optionName = this.validOptionNames[index]
if (options.extra && optionName in options.extra) {
mongoOptions[optionName] = options.extra[optionName]
} else if (optionName in options) {
for (const optionName of this.validOptionNames) {
if (optionName in options) {
mongoOptions[optionName] = options[optionName]
}
}
if ("poolSize" in options) {
mongoOptions["maxPoolSize"] = options["poolSize"]
}
Object.assign(mongoOptions, options.extra)
return mongoOptions
}
}