Initial commit
This commit is contained in:
2788
node_modules/mongodb/HISTORY.md
generated
vendored
Normal file
2788
node_modules/mongodb/HISTORY.md
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
201
node_modules/mongodb/LICENSE.md
generated
vendored
Normal file
201
node_modules/mongodb/LICENSE.md
generated
vendored
Normal file
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "{}"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright {yyyy} {name of copyright owner}
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
499
node_modules/mongodb/README.md
generated
vendored
Normal file
499
node_modules/mongodb/README.md
generated
vendored
Normal file
@@ -0,0 +1,499 @@
|
||||
[](https://nodei.co/npm/mongodb/) [](https://nodei.co/npm/mongodb/)
|
||||
|
||||
[](http://travis-ci.org/mongodb/node-mongodb-native)
|
||||
[](https://coveralls.io/github/mongodb/node-mongodb-native?branch=2.1)
|
||||
[](https://gitter.im/mongodb/node-mongodb-native?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
|
||||
|
||||
# Description
|
||||
|
||||
The official [MongoDB](https://www.mongodb.com/) driver for Node.js. Provides a high-level API on top of [mongodb-core](https://www.npmjs.com/package/mongodb-core) that is meant for end users.
|
||||
|
||||
**NOTE: v3.x was recently released with breaking API changes. You can find a list of changes [here](CHANGES_3.0.0.md).**
|
||||
|
||||
## MongoDB Node.JS Driver
|
||||
|
||||
| what | where |
|
||||
|---------------|------------------------------------------------|
|
||||
| documentation | http://mongodb.github.io/node-mongodb-native |
|
||||
| api-doc | http://mongodb.github.io/node-mongodb-native/3.1/api |
|
||||
| source | https://github.com/mongodb/node-mongodb-native |
|
||||
| mongodb | http://www.mongodb.org |
|
||||
|
||||
### Bugs / Feature Requests
|
||||
|
||||
Think you’ve found a bug? Want to see a new feature in `node-mongodb-native`? Please open a
|
||||
case in our issue management tool, JIRA:
|
||||
|
||||
- Create an account and login [jira.mongodb.org](https://jira.mongodb.org).
|
||||
- Navigate to the NODE project [jira.mongodb.org/browse/NODE](https://jira.mongodb.org/browse/NODE).
|
||||
- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it.
|
||||
|
||||
Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the
|
||||
Core Server (i.e. SERVER) project are **public**.
|
||||
|
||||
### Support / Feedback
|
||||
|
||||
For issues with, questions about, or feedback for the Node.js driver, please look into our [support channels](https://docs.mongodb.com/manual/support). Please do not email any of the driver developers directly with issues or questions - you're more likely to get an answer on the [MongoDB Community Forums](https://community.mongodb.com/tags/c/drivers-odms-connectors/7/node-js-driver).
|
||||
|
||||
### Change Log
|
||||
|
||||
Change history can be found in [`HISTORY.md`](HISTORY.md).
|
||||
|
||||
### Compatibility
|
||||
|
||||
For version compatibility matrices, please refer to the following links:
|
||||
|
||||
* [MongoDB](https://docs.mongodb.com/ecosystem/drivers/driver-compatibility-reference/#reference-compatibility-mongodb-node)
|
||||
* [NodeJS](https://docs.mongodb.com/ecosystem/drivers/driver-compatibility-reference/#reference-compatibility-language-node)
|
||||
|
||||
# Installation
|
||||
|
||||
The recommended way to get started using the Node.js 3.0 driver is by using the `npm` (Node Package Manager) to install the dependency in your project.
|
||||
|
||||
## MongoDB Driver
|
||||
|
||||
Given that you have created your own project using `npm init` we install the MongoDB driver and its dependencies by executing the following `npm` command.
|
||||
|
||||
```bash
|
||||
npm install mongodb --save
|
||||
```
|
||||
|
||||
This will download the MongoDB driver and add a dependency entry in your `package.json` file.
|
||||
|
||||
You can also use the [Yarn](https://yarnpkg.com/en) package manager.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
The MongoDB driver depends on several other packages. These are:
|
||||
|
||||
* [mongodb-core](https://github.com/mongodb-js/mongodb-core)
|
||||
* [bson](https://github.com/mongodb/js-bson)
|
||||
* [kerberos](https://github.com/mongodb-js/kerberos)
|
||||
* [node-gyp](https://github.com/nodejs/node-gyp)
|
||||
|
||||
The `kerberos` package is a C++ extension that requires a build environment to be installed on your system. You must be able to build Node.js itself in order to compile and install the `kerberos` module. Furthermore, the `kerberos` module requires the MIT Kerberos package to correctly compile on UNIX operating systems. Consult your UNIX operation system package manager for what libraries to install.
|
||||
|
||||
**Windows already contains the SSPI API used for Kerberos authentication. However, you will need to install a full compiler tool chain using Visual Studio C++ to correctly install the Kerberos extension.**
|
||||
|
||||
### Diagnosing on UNIX
|
||||
|
||||
If you don’t have the build-essentials, this module won’t build. In the case of Linux, you will need gcc, g++, Node.js with all the headers and Python. The easiest way to figure out what’s missing is by trying to build the Kerberos project. You can do this by performing the following steps.
|
||||
|
||||
```bash
|
||||
git clone https://github.com/mongodb-js/kerberos
|
||||
cd kerberos
|
||||
npm install
|
||||
```
|
||||
|
||||
If all the steps complete, you have the right toolchain installed. If you get the error "node-gyp not found," you need to install `node-gyp` globally:
|
||||
|
||||
```bash
|
||||
npm install -g node-gyp
|
||||
```
|
||||
|
||||
If it correctly compiles and runs the tests you are golden. We can now try to install the `mongod` driver by performing the following command.
|
||||
|
||||
```bash
|
||||
cd yourproject
|
||||
npm install mongodb --save
|
||||
```
|
||||
|
||||
If it still fails the next step is to examine the npm log. Rerun the command but in this case in verbose mode.
|
||||
|
||||
```bash
|
||||
npm --loglevel verbose install mongodb
|
||||
```
|
||||
|
||||
This will print out all the steps npm is performing while trying to install the module.
|
||||
|
||||
### Diagnosing on Windows
|
||||
|
||||
A compiler tool chain known to work for compiling `kerberos` on Windows is the following.
|
||||
|
||||
* Visual Studio C++ 2010 (do not use higher versions)
|
||||
* Windows 7 64bit SDK
|
||||
* Python 2.7 or higher
|
||||
|
||||
Open the Visual Studio command prompt. Ensure `node.exe` is in your path and install `node-gyp`.
|
||||
|
||||
```bash
|
||||
npm install -g node-gyp
|
||||
```
|
||||
|
||||
Next, you will have to build the project manually to test it. Clone the repo, install dependencies and rebuild:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/christkv/kerberos.git
|
||||
cd kerberos
|
||||
npm install
|
||||
node-gyp rebuild
|
||||
```
|
||||
|
||||
This should rebuild the driver successfully if you have everything set up correctly.
|
||||
|
||||
### Other possible issues
|
||||
|
||||
Your Python installation might be hosed making gyp break. Test your deployment environment first by trying to build Node.js itself on the server in question, as this should unearth any issues with broken packages (and there are a lot of broken packages out there).
|
||||
|
||||
Another tip is to ensure your user has write permission to wherever the Node.js modules are being installed.
|
||||
|
||||
## Quick Start
|
||||
|
||||
This guide will show you how to set up a simple application using Node.js and MongoDB. Its scope is only how to set up the driver and perform the simple CRUD operations. For more in-depth coverage, see the [tutorials](docs/reference/content/tutorials/main.md).
|
||||
|
||||
### Create the `package.json` file
|
||||
|
||||
First, create a directory where your application will live.
|
||||
|
||||
```bash
|
||||
mkdir myproject
|
||||
cd myproject
|
||||
```
|
||||
|
||||
Enter the following command and answer the questions to create the initial structure for your new project:
|
||||
|
||||
```bash
|
||||
npm init
|
||||
```
|
||||
|
||||
Next, install the driver dependency.
|
||||
|
||||
```bash
|
||||
npm install mongodb --save
|
||||
```
|
||||
|
||||
You should see **NPM** download a lot of files. Once it's done you'll find all the downloaded packages under the **node_modules** directory.
|
||||
|
||||
### Start a MongoDB Server
|
||||
|
||||
For complete MongoDB installation instructions, see [the manual](https://docs.mongodb.org/manual/installation/).
|
||||
|
||||
1. Download the right MongoDB version from [MongoDB](https://www.mongodb.org/downloads)
|
||||
2. Create a database directory (in this case under **/data**).
|
||||
3. Install and start a ``mongod`` process.
|
||||
|
||||
```bash
|
||||
mongod --dbpath=/data
|
||||
```
|
||||
|
||||
You should see the **mongod** process start up and print some status information.
|
||||
|
||||
### Connect to MongoDB
|
||||
|
||||
Create a new **app.js** file and add the following code to try out some basic CRUD
|
||||
operations using the MongoDB driver.
|
||||
|
||||
Add code to connect to the server and the database **myproject**:
|
||||
|
||||
```js
|
||||
const MongoClient = require('mongodb').MongoClient;
|
||||
const assert = require('assert');
|
||||
|
||||
// Connection URL
|
||||
const url = 'mongodb://localhost:27017';
|
||||
|
||||
// Database Name
|
||||
const dbName = 'myproject';
|
||||
|
||||
// Use connect method to connect to the server
|
||||
MongoClient.connect(url, function(err, client) {
|
||||
assert.equal(null, err);
|
||||
console.log("Connected successfully to server");
|
||||
|
||||
const db = client.db(dbName);
|
||||
|
||||
client.close();
|
||||
});
|
||||
```
|
||||
|
||||
Run your app from the command line with:
|
||||
|
||||
```bash
|
||||
node app.js
|
||||
```
|
||||
|
||||
The application should print **Connected successfully to server** to the console.
|
||||
|
||||
### Insert a Document
|
||||
|
||||
Add to **app.js** the following function which uses the **insertMany**
|
||||
method to add three documents to the **documents** collection.
|
||||
|
||||
```js
|
||||
const insertDocuments = function(db, callback) {
|
||||
// Get the documents collection
|
||||
const collection = db.collection('documents');
|
||||
// Insert some documents
|
||||
collection.insertMany([
|
||||
{a : 1}, {a : 2}, {a : 3}
|
||||
], function(err, result) {
|
||||
assert.equal(err, null);
|
||||
assert.equal(3, result.result.n);
|
||||
assert.equal(3, result.ops.length);
|
||||
console.log("Inserted 3 documents into the collection");
|
||||
callback(result);
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
The **insert** command returns an object with the following fields:
|
||||
|
||||
* **result** Contains the result document from MongoDB
|
||||
* **ops** Contains the documents inserted with added **_id** fields
|
||||
* **connection** Contains the connection used to perform the insert
|
||||
|
||||
Add the following code to call the **insertDocuments** function:
|
||||
|
||||
```js
|
||||
const MongoClient = require('mongodb').MongoClient;
|
||||
const assert = require('assert');
|
||||
|
||||
// Connection URL
|
||||
const url = 'mongodb://localhost:27017';
|
||||
|
||||
// Database Name
|
||||
const dbName = 'myproject';
|
||||
|
||||
// Use connect method to connect to the server
|
||||
MongoClient.connect(url, function(err, client) {
|
||||
assert.equal(null, err);
|
||||
console.log("Connected successfully to server");
|
||||
|
||||
const db = client.db(dbName);
|
||||
|
||||
insertDocuments(db, function() {
|
||||
client.close();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
Run the updated **app.js** file:
|
||||
|
||||
```bash
|
||||
node app.js
|
||||
```
|
||||
|
||||
The operation returns the following output:
|
||||
|
||||
```bash
|
||||
Connected successfully to server
|
||||
Inserted 3 documents into the collection
|
||||
```
|
||||
|
||||
### Find All Documents
|
||||
|
||||
Add a query that returns all the documents.
|
||||
|
||||
```js
|
||||
const findDocuments = function(db, callback) {
|
||||
// Get the documents collection
|
||||
const collection = db.collection('documents');
|
||||
// Find some documents
|
||||
collection.find({}).toArray(function(err, docs) {
|
||||
assert.equal(err, null);
|
||||
console.log("Found the following records");
|
||||
console.log(docs)
|
||||
callback(docs);
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
This query returns all the documents in the **documents** collection. Add the **findDocument** method to the **MongoClient.connect** callback:
|
||||
|
||||
```js
|
||||
const MongoClient = require('mongodb').MongoClient;
|
||||
const assert = require('assert');
|
||||
|
||||
// Connection URL
|
||||
const url = 'mongodb://localhost:27017';
|
||||
|
||||
// Database Name
|
||||
const dbName = 'myproject';
|
||||
|
||||
// Use connect method to connect to the server
|
||||
MongoClient.connect(url, function(err, client) {
|
||||
assert.equal(null, err);
|
||||
console.log("Connected correctly to server");
|
||||
|
||||
const db = client.db(dbName);
|
||||
|
||||
insertDocuments(db, function() {
|
||||
findDocuments(db, function() {
|
||||
client.close();
|
||||
});
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### Find Documents with a Query Filter
|
||||
|
||||
Add a query filter to find only documents which meet the query criteria.
|
||||
|
||||
```js
|
||||
const findDocuments = function(db, callback) {
|
||||
// Get the documents collection
|
||||
const collection = db.collection('documents');
|
||||
// Find some documents
|
||||
collection.find({'a': 3}).toArray(function(err, docs) {
|
||||
assert.equal(err, null);
|
||||
console.log("Found the following records");
|
||||
console.log(docs);
|
||||
callback(docs);
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
Only the documents which match ``'a' : 3`` should be returned.
|
||||
|
||||
### Update a document
|
||||
|
||||
The following operation updates a document in the **documents** collection.
|
||||
|
||||
```js
|
||||
const updateDocument = function(db, callback) {
|
||||
// Get the documents collection
|
||||
const collection = db.collection('documents');
|
||||
// Update document where a is 2, set b equal to 1
|
||||
collection.updateOne({ a : 2 }
|
||||
, { $set: { b : 1 } }, function(err, result) {
|
||||
assert.equal(err, null);
|
||||
assert.equal(1, result.result.n);
|
||||
console.log("Updated the document with the field a equal to 2");
|
||||
callback(result);
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
The method updates the first document where the field **a** is equal to **2** by adding a new field **b** to the document set to **1**. Next, update the callback function from **MongoClient.connect** to include the update method.
|
||||
|
||||
```js
|
||||
const MongoClient = require('mongodb').MongoClient;
|
||||
const assert = require('assert');
|
||||
|
||||
// Connection URL
|
||||
const url = 'mongodb://localhost:27017';
|
||||
|
||||
// Database Name
|
||||
const dbName = 'myproject';
|
||||
|
||||
// Use connect method to connect to the server
|
||||
MongoClient.connect(url, function(err, client) {
|
||||
assert.equal(null, err);
|
||||
console.log("Connected successfully to server");
|
||||
|
||||
const db = client.db(dbName);
|
||||
|
||||
insertDocuments(db, function() {
|
||||
updateDocument(db, function() {
|
||||
client.close();
|
||||
});
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### Remove a document
|
||||
|
||||
Remove the document where the field **a** is equal to **3**.
|
||||
|
||||
```js
|
||||
const removeDocument = function(db, callback) {
|
||||
// Get the documents collection
|
||||
const collection = db.collection('documents');
|
||||
// Delete document where a is 3
|
||||
collection.deleteOne({ a : 3 }, function(err, result) {
|
||||
assert.equal(err, null);
|
||||
assert.equal(1, result.result.n);
|
||||
console.log("Removed the document with the field a equal to 3");
|
||||
callback(result);
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
Add the new method to the **MongoClient.connect** callback function.
|
||||
|
||||
```js
|
||||
const MongoClient = require('mongodb').MongoClient;
|
||||
const assert = require('assert');
|
||||
|
||||
// Connection URL
|
||||
const url = 'mongodb://localhost:27017';
|
||||
|
||||
// Database Name
|
||||
const dbName = 'myproject';
|
||||
|
||||
// Use connect method to connect to the server
|
||||
MongoClient.connect(url, function(err, client) {
|
||||
assert.equal(null, err);
|
||||
console.log("Connected successfully to server");
|
||||
|
||||
const db = client.db(dbName);
|
||||
|
||||
insertDocuments(db, function() {
|
||||
updateDocument(db, function() {
|
||||
removeDocument(db, function() {
|
||||
client.close();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### Index a Collection
|
||||
|
||||
[Indexes](https://docs.mongodb.org/manual/indexes/) can improve your application's
|
||||
performance. The following function creates an index on the **a** field in the
|
||||
**documents** collection.
|
||||
|
||||
```js
|
||||
const indexCollection = function(db, callback) {
|
||||
db.collection('documents').createIndex(
|
||||
{ "a": 1 },
|
||||
null,
|
||||
function(err, results) {
|
||||
console.log(results);
|
||||
callback();
|
||||
}
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
Add the ``indexCollection`` method to your app:
|
||||
|
||||
```js
|
||||
const MongoClient = require('mongodb').MongoClient;
|
||||
const assert = require('assert');
|
||||
|
||||
// Connection URL
|
||||
const url = 'mongodb://localhost:27017';
|
||||
|
||||
const dbName = 'myproject';
|
||||
|
||||
// Use connect method to connect to the server
|
||||
MongoClient.connect(url, function(err, client) {
|
||||
assert.equal(null, err);
|
||||
console.log("Connected successfully to server");
|
||||
|
||||
const db = client.db(dbName);
|
||||
|
||||
insertDocuments(db, function() {
|
||||
indexCollection(db, function() {
|
||||
client.close();
|
||||
});
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
For more detailed information, see the [tutorials](docs/reference/content/tutorials/main.md).
|
||||
|
||||
## Next Steps
|
||||
|
||||
* [MongoDB Documentation](http://mongodb.org)
|
||||
* [Read about Schemas](http://learnmongodbthehardway.com)
|
||||
* [Star us on GitHub](https://github.com/mongodb/node-mongodb-native)
|
||||
|
||||
## License
|
||||
|
||||
[Apache 2.0](LICENSE.md)
|
||||
|
||||
© 2009-2012 Christian Amor Kvalheim
|
||||
© 2012-present MongoDB [Contributors](CONTRIBUTORS.md)
|
||||
73
node_modules/mongodb/index.js
generated
vendored
Normal file
73
node_modules/mongodb/index.js
generated
vendored
Normal file
@@ -0,0 +1,73 @@
|
||||
'use strict';
|
||||
|
||||
// Core module
|
||||
const core = require('./lib/core');
|
||||
const Instrumentation = require('./lib/apm');
|
||||
|
||||
// Set up the connect function
|
||||
const connect = require('./lib/mongo_client').connect;
|
||||
|
||||
// Expose error class
|
||||
connect.MongoError = core.MongoError;
|
||||
connect.MongoNetworkError = core.MongoNetworkError;
|
||||
connect.MongoTimeoutError = core.MongoTimeoutError;
|
||||
connect.MongoServerSelectionError = core.MongoServerSelectionError;
|
||||
connect.MongoParseError = core.MongoParseError;
|
||||
connect.MongoWriteConcernError = core.MongoWriteConcernError;
|
||||
connect.MongoBulkWriteError = require('./lib/bulk/common').BulkWriteError;
|
||||
connect.BulkWriteError = connect.MongoBulkWriteError;
|
||||
|
||||
// Actual driver classes exported
|
||||
connect.Admin = require('./lib/admin');
|
||||
connect.MongoClient = require('./lib/mongo_client');
|
||||
connect.Db = require('./lib/db');
|
||||
connect.Collection = require('./lib/collection');
|
||||
connect.Server = require('./lib/topologies/server');
|
||||
connect.ReplSet = require('./lib/topologies/replset');
|
||||
connect.Mongos = require('./lib/topologies/mongos');
|
||||
connect.ReadPreference = core.ReadPreference;
|
||||
connect.GridStore = require('./lib/gridfs/grid_store');
|
||||
connect.Chunk = require('./lib/gridfs/chunk');
|
||||
connect.Logger = core.Logger;
|
||||
connect.AggregationCursor = require('./lib/aggregation_cursor');
|
||||
connect.CommandCursor = require('./lib/command_cursor');
|
||||
connect.Cursor = require('./lib/cursor');
|
||||
connect.GridFSBucket = require('./lib/gridfs-stream');
|
||||
// Exported to be used in tests not to be used anywhere else
|
||||
connect.CoreServer = core.Server;
|
||||
connect.CoreConnection = core.Connection;
|
||||
|
||||
// BSON types exported
|
||||
connect.Binary = core.BSON.Binary;
|
||||
connect.Code = core.BSON.Code;
|
||||
connect.Map = core.BSON.Map;
|
||||
connect.DBRef = core.BSON.DBRef;
|
||||
connect.Double = core.BSON.Double;
|
||||
connect.Int32 = core.BSON.Int32;
|
||||
connect.Long = core.BSON.Long;
|
||||
connect.MinKey = core.BSON.MinKey;
|
||||
connect.MaxKey = core.BSON.MaxKey;
|
||||
connect.ObjectID = core.BSON.ObjectID;
|
||||
connect.ObjectId = core.BSON.ObjectID;
|
||||
connect.Symbol = core.BSON.Symbol;
|
||||
connect.Timestamp = core.BSON.Timestamp;
|
||||
connect.BSONRegExp = core.BSON.BSONRegExp;
|
||||
connect.Decimal128 = core.BSON.Decimal128;
|
||||
|
||||
// Add connect method
|
||||
connect.connect = connect;
|
||||
|
||||
// Set up the instrumentation method
|
||||
connect.instrument = function(options, callback) {
|
||||
if (typeof options === 'function') {
|
||||
callback = options;
|
||||
options = {};
|
||||
}
|
||||
|
||||
const instrumentation = new Instrumentation();
|
||||
instrumentation.instrument(connect.MongoClient, callback);
|
||||
return instrumentation;
|
||||
};
|
||||
|
||||
// Set our exports to be the connect function
|
||||
module.exports = connect;
|
||||
294
node_modules/mongodb/lib/admin.js
generated
vendored
Normal file
294
node_modules/mongodb/lib/admin.js
generated
vendored
Normal file
@@ -0,0 +1,294 @@
|
||||
'use strict';
|
||||
|
||||
const applyWriteConcern = require('./utils').applyWriteConcern;
|
||||
|
||||
const AddUserOperation = require('./operations/add_user');
|
||||
const ExecuteDbAdminCommandOperation = require('./operations/execute_db_admin_command');
|
||||
const RemoveUserOperation = require('./operations/remove_user');
|
||||
const ValidateCollectionOperation = require('./operations/validate_collection');
|
||||
const ListDatabasesOperation = require('./operations/list_databases');
|
||||
|
||||
const executeOperation = require('./operations/execute_operation');
|
||||
|
||||
/**
|
||||
* @fileOverview The **Admin** class is an internal class that allows convenient access to
|
||||
* the admin functionality and commands for MongoDB.
|
||||
*
|
||||
* **ADMIN Cannot directly be instantiated**
|
||||
* @example
|
||||
* const MongoClient = require('mongodb').MongoClient;
|
||||
* const test = require('assert');
|
||||
* // Connection url
|
||||
* const url = 'mongodb://localhost:27017';
|
||||
* // Database Name
|
||||
* const dbName = 'test';
|
||||
*
|
||||
* // Connect using MongoClient
|
||||
* MongoClient.connect(url, function(err, client) {
|
||||
* // Use the admin database for the operation
|
||||
* const adminDb = client.db(dbName).admin();
|
||||
*
|
||||
* // List all the available databases
|
||||
* adminDb.listDatabases(function(err, dbs) {
|
||||
* test.equal(null, err);
|
||||
* test.ok(dbs.databases.length > 0);
|
||||
* client.close();
|
||||
* });
|
||||
* });
|
||||
*/
|
||||
|
||||
/**
|
||||
* Create a new Admin instance (INTERNAL TYPE, do not instantiate directly)
|
||||
* @class
|
||||
* @return {Admin} a collection instance.
|
||||
*/
|
||||
function Admin(db, topology, promiseLibrary) {
|
||||
if (!(this instanceof Admin)) return new Admin(db, topology);
|
||||
|
||||
// Internal state
|
||||
this.s = {
|
||||
db: db,
|
||||
topology: topology,
|
||||
promiseLibrary: promiseLibrary
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The callback format for results
|
||||
* @callback Admin~resultCallback
|
||||
* @param {MongoError} error An error instance representing the error during the execution.
|
||||
* @param {object} result The result object if the command was executed successfully.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Execute a command
|
||||
* @method
|
||||
* @param {object} command The command hash
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
|
||||
* @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query.
|
||||
* @param {Admin~resultCallback} [callback] The command result callback
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
Admin.prototype.command = function(command, options, callback) {
|
||||
const args = Array.prototype.slice.call(arguments, 1);
|
||||
callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
|
||||
options = args.length ? args.shift() : {};
|
||||
|
||||
const commandOperation = new ExecuteDbAdminCommandOperation(this.s.db, command, options);
|
||||
|
||||
return executeOperation(this.s.db.s.topology, commandOperation, callback);
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieve the server information for the current
|
||||
* instance of the db client
|
||||
*
|
||||
* @param {Object} [options] optional parameters for this operation
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @param {Admin~resultCallback} [callback] The command result callback
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
Admin.prototype.buildInfo = function(options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options || {};
|
||||
|
||||
const cmd = { buildinfo: 1 };
|
||||
|
||||
const buildInfoOperation = new ExecuteDbAdminCommandOperation(this.s.db, cmd, options);
|
||||
|
||||
return executeOperation(this.s.db.s.topology, buildInfoOperation, callback);
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieve the server information for the current
|
||||
* instance of the db client
|
||||
*
|
||||
* @param {Object} [options] optional parameters for this operation
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @param {Admin~resultCallback} [callback] The command result callback
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
Admin.prototype.serverInfo = function(options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options || {};
|
||||
|
||||
const cmd = { buildinfo: 1 };
|
||||
|
||||
const serverInfoOperation = new ExecuteDbAdminCommandOperation(this.s.db, cmd, options);
|
||||
|
||||
return executeOperation(this.s.db.s.topology, serverInfoOperation, callback);
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieve this db's server status.
|
||||
*
|
||||
* @param {Object} [options] optional parameters for this operation
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @param {Admin~resultCallback} [callback] The command result callback
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
Admin.prototype.serverStatus = function(options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options || {};
|
||||
|
||||
const serverStatusOperation = new ExecuteDbAdminCommandOperation(
|
||||
this.s.db,
|
||||
{ serverStatus: 1 },
|
||||
options
|
||||
);
|
||||
|
||||
return executeOperation(this.s.db.s.topology, serverStatusOperation, callback);
|
||||
};
|
||||
|
||||
/**
|
||||
* Ping the MongoDB server and retrieve results
|
||||
*
|
||||
* @param {Object} [options] optional parameters for this operation
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @param {Admin~resultCallback} [callback] The command result callback
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
Admin.prototype.ping = function(options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options || {};
|
||||
|
||||
const cmd = { ping: 1 };
|
||||
|
||||
const pingOperation = new ExecuteDbAdminCommandOperation(this.s.db, cmd, options);
|
||||
|
||||
return executeOperation(this.s.db.s.topology, pingOperation, callback);
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a user to the database.
|
||||
* @method
|
||||
* @param {string} username The username.
|
||||
* @param {string} password The password.
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {(number|string)} [options.w] The write concern.
|
||||
* @param {number} [options.wtimeout] The write concern timeout.
|
||||
* @param {boolean} [options.j=false] Specify a journal write concern.
|
||||
* @param {boolean} [options.fsync=false] Specify a file sync write concern.
|
||||
* @param {object} [options.customData] Custom data associated with the user (only Mongodb 2.6 or higher)
|
||||
* @param {object[]} [options.roles] Roles associated with the created user (only Mongodb 2.6 or higher)
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @param {Admin~resultCallback} [callback] The command result callback
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
Admin.prototype.addUser = function(username, password, options, callback) {
|
||||
const args = Array.prototype.slice.call(arguments, 2);
|
||||
callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
|
||||
|
||||
// Special case where there is no password ($external users)
|
||||
if (typeof username === 'string' && password != null && typeof password === 'object') {
|
||||
options = password;
|
||||
password = null;
|
||||
}
|
||||
|
||||
options = args.length ? args.shift() : {};
|
||||
options = Object.assign({}, options);
|
||||
// Get the options
|
||||
options = applyWriteConcern(options, { db: this.s.db });
|
||||
// Set the db name to admin
|
||||
options.dbName = 'admin';
|
||||
|
||||
const addUserOperation = new AddUserOperation(this.s.db, username, password, options);
|
||||
|
||||
return executeOperation(this.s.db.s.topology, addUserOperation, callback);
|
||||
};
|
||||
|
||||
/**
|
||||
* Remove a user from a database
|
||||
* @method
|
||||
* @param {string} username The username.
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {(number|string)} [options.w] The write concern.
|
||||
* @param {number} [options.wtimeout] The write concern timeout.
|
||||
* @param {boolean} [options.j=false] Specify a journal write concern.
|
||||
* @param {boolean} [options.fsync=false] Specify a file sync write concern.
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @param {Admin~resultCallback} [callback] The command result callback
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
Admin.prototype.removeUser = function(username, options, callback) {
|
||||
const args = Array.prototype.slice.call(arguments, 1);
|
||||
callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
|
||||
|
||||
options = args.length ? args.shift() : {};
|
||||
options = Object.assign({}, options);
|
||||
// Get the options
|
||||
options = applyWriteConcern(options, { db: this.s.db });
|
||||
// Set the db name
|
||||
options.dbName = 'admin';
|
||||
|
||||
const removeUserOperation = new RemoveUserOperation(this.s.db, username, options);
|
||||
|
||||
return executeOperation(this.s.db.s.topology, removeUserOperation, callback);
|
||||
};
|
||||
|
||||
/**
|
||||
* Validate an existing collection
|
||||
*
|
||||
* @param {string} collectionName The name of the collection to validate.
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {boolean} [options.background] Validates a collection in the background, without interrupting read or write traffic (only in MongoDB 4.4+)
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @param {Admin~resultCallback} [callback] The command result callback.
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
Admin.prototype.validateCollection = function(collectionName, options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options || {};
|
||||
|
||||
const validateCollectionOperation = new ValidateCollectionOperation(
|
||||
this,
|
||||
collectionName,
|
||||
options
|
||||
);
|
||||
|
||||
return executeOperation(this.s.db.s.topology, validateCollectionOperation, callback);
|
||||
};
|
||||
|
||||
/**
|
||||
* List the available databases
|
||||
*
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {boolean} [options.nameOnly=false] Whether the command should return only db names, or names and size info.
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @param {Admin~resultCallback} [callback] The command result callback.
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
Admin.prototype.listDatabases = function(options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options || {};
|
||||
|
||||
return executeOperation(
|
||||
this.s.db.s.topology,
|
||||
new ListDatabasesOperation(this.s.db, options),
|
||||
callback
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Get ReplicaSet status
|
||||
*
|
||||
* @param {Object} [options] optional parameters for this operation
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @param {Admin~resultCallback} [callback] The command result callback.
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
Admin.prototype.replSetGetStatus = function(options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options || {};
|
||||
|
||||
const replSetGetStatusOperation = new ExecuteDbAdminCommandOperation(
|
||||
this.s.db,
|
||||
{ replSetGetStatus: 1 },
|
||||
options
|
||||
);
|
||||
|
||||
return executeOperation(this.s.db.s.topology, replSetGetStatusOperation, callback);
|
||||
};
|
||||
|
||||
module.exports = Admin;
|
||||
370
node_modules/mongodb/lib/aggregation_cursor.js
generated
vendored
Normal file
370
node_modules/mongodb/lib/aggregation_cursor.js
generated
vendored
Normal file
@@ -0,0 +1,370 @@
|
||||
'use strict';
|
||||
|
||||
const MongoError = require('./core').MongoError;
|
||||
const Cursor = require('./cursor');
|
||||
const CursorState = require('./core/cursor').CursorState;
|
||||
const deprecate = require('util').deprecate;
|
||||
|
||||
/**
|
||||
* @fileOverview The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB
|
||||
* allowing for iteration over the results returned from the underlying query. It supports
|
||||
* one by one document iteration, conversion to an array or can be iterated as a Node 4.X
|
||||
* or higher stream
|
||||
*
|
||||
* **AGGREGATIONCURSOR Cannot directly be instantiated**
|
||||
* @example
|
||||
* const MongoClient = require('mongodb').MongoClient;
|
||||
* const test = require('assert');
|
||||
* // Connection url
|
||||
* const url = 'mongodb://localhost:27017';
|
||||
* // Database Name
|
||||
* const dbName = 'test';
|
||||
* // Connect using MongoClient
|
||||
* MongoClient.connect(url, function(err, client) {
|
||||
* // Create a collection we want to drop later
|
||||
* const col = client.db(dbName).collection('createIndexExample1');
|
||||
* // Insert a bunch of documents
|
||||
* col.insert([{a:1, b:1}
|
||||
* , {a:2, b:2}, {a:3, b:3}
|
||||
* , {a:4, b:4}], {w:1}, function(err, result) {
|
||||
* test.equal(null, err);
|
||||
* // Show that duplicate records got dropped
|
||||
* col.aggregation({}, {cursor: {}}).toArray(function(err, items) {
|
||||
* test.equal(null, err);
|
||||
* test.equal(4, items.length);
|
||||
* client.close();
|
||||
* });
|
||||
* });
|
||||
* });
|
||||
*/
|
||||
|
||||
/**
|
||||
* Namespace provided by the browser.
|
||||
* @external Readable
|
||||
*/
|
||||
|
||||
/**
|
||||
* Creates a new Aggregation Cursor instance (INTERNAL TYPE, do not instantiate directly)
|
||||
* @class AggregationCursor
|
||||
* @extends external:Readable
|
||||
* @fires AggregationCursor#data
|
||||
* @fires AggregationCursor#end
|
||||
* @fires AggregationCursor#close
|
||||
* @fires AggregationCursor#readable
|
||||
* @return {AggregationCursor} an AggregationCursor instance.
|
||||
*/
|
||||
class AggregationCursor extends Cursor {
|
||||
constructor(topology, operation, options) {
|
||||
super(topology, operation, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the batch size for the cursor.
|
||||
* @method
|
||||
* @param {number} value The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.
|
||||
* @throws {MongoError}
|
||||
* @return {AggregationCursor}
|
||||
*/
|
||||
batchSize(value) {
|
||||
if (this.s.state === CursorState.CLOSED || this.isDead()) {
|
||||
throw MongoError.create({ message: 'Cursor is closed', driver: true });
|
||||
}
|
||||
|
||||
if (typeof value !== 'number') {
|
||||
throw MongoError.create({ message: 'batchSize requires an integer', driver: true });
|
||||
}
|
||||
|
||||
this.operation.options.batchSize = value;
|
||||
this.setCursorBatchSize(value);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a geoNear stage to the aggregation pipeline
|
||||
* @method
|
||||
* @param {object} document The geoNear stage document.
|
||||
* @return {AggregationCursor}
|
||||
*/
|
||||
geoNear(document) {
|
||||
this.operation.addToPipeline({ $geoNear: document });
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a group stage to the aggregation pipeline
|
||||
* @method
|
||||
* @param {object} document The group stage document.
|
||||
* @return {AggregationCursor}
|
||||
*/
|
||||
group(document) {
|
||||
this.operation.addToPipeline({ $group: document });
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a limit stage to the aggregation pipeline
|
||||
* @method
|
||||
* @param {number} value The state limit value.
|
||||
* @return {AggregationCursor}
|
||||
*/
|
||||
limit(value) {
|
||||
this.operation.addToPipeline({ $limit: value });
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a match stage to the aggregation pipeline
|
||||
* @method
|
||||
* @param {object} document The match stage document.
|
||||
* @return {AggregationCursor}
|
||||
*/
|
||||
match(document) {
|
||||
this.operation.addToPipeline({ $match: document });
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a maxTimeMS stage to the aggregation pipeline
|
||||
* @method
|
||||
* @param {number} value The state maxTimeMS value.
|
||||
* @return {AggregationCursor}
|
||||
*/
|
||||
maxTimeMS(value) {
|
||||
this.operation.options.maxTimeMS = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a out stage to the aggregation pipeline
|
||||
* @method
|
||||
* @param {number} destination The destination name.
|
||||
* @return {AggregationCursor}
|
||||
*/
|
||||
out(destination) {
|
||||
this.operation.addToPipeline({ $out: destination });
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a project stage to the aggregation pipeline
|
||||
* @method
|
||||
* @param {object} document The project stage document.
|
||||
* @return {AggregationCursor}
|
||||
*/
|
||||
project(document) {
|
||||
this.operation.addToPipeline({ $project: document });
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a lookup stage to the aggregation pipeline
|
||||
* @method
|
||||
* @param {object} document The lookup stage document.
|
||||
* @return {AggregationCursor}
|
||||
*/
|
||||
lookup(document) {
|
||||
this.operation.addToPipeline({ $lookup: document });
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a redact stage to the aggregation pipeline
|
||||
* @method
|
||||
* @param {object} document The redact stage document.
|
||||
* @return {AggregationCursor}
|
||||
*/
|
||||
redact(document) {
|
||||
this.operation.addToPipeline({ $redact: document });
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a skip stage to the aggregation pipeline
|
||||
* @method
|
||||
* @param {number} value The state skip value.
|
||||
* @return {AggregationCursor}
|
||||
*/
|
||||
skip(value) {
|
||||
this.operation.addToPipeline({ $skip: value });
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a sort stage to the aggregation pipeline
|
||||
* @method
|
||||
* @param {object} document The sort stage document.
|
||||
* @return {AggregationCursor}
|
||||
*/
|
||||
sort(document) {
|
||||
this.operation.addToPipeline({ $sort: document });
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a unwind stage to the aggregation pipeline
|
||||
* @method
|
||||
* @param {number} field The unwind field name.
|
||||
* @return {AggregationCursor}
|
||||
*/
|
||||
unwind(field) {
|
||||
this.operation.addToPipeline({ $unwind: field });
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the cursor logger
|
||||
* @method
|
||||
* @return {Logger} return the cursor logger
|
||||
* @ignore
|
||||
*/
|
||||
getLogger() {
|
||||
return this.logger;
|
||||
}
|
||||
}
|
||||
|
||||
// aliases
|
||||
AggregationCursor.prototype.get = AggregationCursor.prototype.toArray;
|
||||
|
||||
// deprecated methods
|
||||
deprecate(
|
||||
AggregationCursor.prototype.geoNear,
|
||||
'The `$geoNear` stage is deprecated in MongoDB 4.0, and removed in version 4.2.'
|
||||
);
|
||||
|
||||
/**
|
||||
* AggregationCursor stream data event, fired for each document in the cursor.
|
||||
*
|
||||
* @event AggregationCursor#data
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* AggregationCursor stream end event
|
||||
*
|
||||
* @event AggregationCursor#end
|
||||
* @type {null}
|
||||
*/
|
||||
|
||||
/**
|
||||
* AggregationCursor stream close event
|
||||
*
|
||||
* @event AggregationCursor#close
|
||||
* @type {null}
|
||||
*/
|
||||
|
||||
/**
|
||||
* AggregationCursor stream readable event
|
||||
*
|
||||
* @event AggregationCursor#readable
|
||||
* @type {null}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Get the next available document from the cursor, returns null if no more documents are available.
|
||||
* @function AggregationCursor.prototype.next
|
||||
* @param {AggregationCursor~resultCallback} [callback] The result callback.
|
||||
* @throws {MongoError}
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
|
||||
/**
|
||||
* Check if there is any document still available in the cursor
|
||||
* @function AggregationCursor.prototype.hasNext
|
||||
* @param {AggregationCursor~resultCallback} [callback] The result callback.
|
||||
* @throws {MongoError}
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
|
||||
/**
|
||||
* The callback format for results
|
||||
* @callback AggregationCursor~toArrayResultCallback
|
||||
* @param {MongoError} error An error instance representing the error during the execution.
|
||||
* @param {object[]} documents All the documents the satisfy the cursor.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Returns an array of documents. The caller is responsible for making sure that there
|
||||
* is enough memory to store the results. Note that the array only contain partial
|
||||
* results when this cursor had been previously accessed. In that case,
|
||||
* cursor.rewind() can be used to reset the cursor.
|
||||
* @method AggregationCursor.prototype.toArray
|
||||
* @param {AggregationCursor~toArrayResultCallback} [callback] The result callback.
|
||||
* @throws {MongoError}
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
|
||||
/**
|
||||
* The callback format for results
|
||||
* @callback AggregationCursor~resultCallback
|
||||
* @param {MongoError} error An error instance representing the error during the execution.
|
||||
* @param {(object|null)} result The result object if the command was executed successfully.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Iterates over all the documents for this cursor. As with **{cursor.toArray}**,
|
||||
* not all of the elements will be iterated if this cursor had been previously accessed.
|
||||
* In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike
|
||||
* **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements
|
||||
* at any given time if batch size is specified. Otherwise, the caller is responsible
|
||||
* for making sure that the entire result can fit the memory.
|
||||
* @method AggregationCursor.prototype.each
|
||||
* @deprecated
|
||||
* @param {AggregationCursor~resultCallback} callback The result callback.
|
||||
* @throws {MongoError}
|
||||
* @return {null}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Close the cursor, sending a AggregationCursor command and emitting close.
|
||||
* @method AggregationCursor.prototype.close
|
||||
* @param {AggregationCursor~resultCallback} [callback] The result callback.
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
|
||||
/**
|
||||
* Is the cursor closed
|
||||
* @method AggregationCursor.prototype.isClosed
|
||||
* @return {boolean}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Execute the explain for the cursor
|
||||
* @method AggregationCursor.prototype.explain
|
||||
* @param {AggregationCursor~resultCallback} [callback] The result callback.
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
|
||||
/**
|
||||
* Clone the cursor
|
||||
* @function AggregationCursor.prototype.clone
|
||||
* @return {AggregationCursor}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Resets the cursor
|
||||
* @function AggregationCursor.prototype.rewind
|
||||
* @return {AggregationCursor}
|
||||
*/
|
||||
|
||||
/**
|
||||
* The callback format for the forEach iterator method
|
||||
* @callback AggregationCursor~iteratorCallback
|
||||
* @param {Object} doc An emitted document for the iterator
|
||||
*/
|
||||
|
||||
/**
|
||||
* The callback error format for the forEach iterator method
|
||||
* @callback AggregationCursor~endCallback
|
||||
* @param {MongoError} error An error instance representing the error during the execution.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Iterates over all the documents for this cursor using the iterator, callback pattern.
|
||||
* @method AggregationCursor.prototype.forEach
|
||||
* @param {AggregationCursor~iteratorCallback} iterator The iteration callback.
|
||||
* @param {AggregationCursor~endCallback} callback The end callback.
|
||||
* @throws {MongoError}
|
||||
* @return {null}
|
||||
*/
|
||||
|
||||
module.exports = AggregationCursor;
|
||||
31
node_modules/mongodb/lib/apm.js
generated
vendored
Normal file
31
node_modules/mongodb/lib/apm.js
generated
vendored
Normal file
@@ -0,0 +1,31 @@
|
||||
'use strict';
|
||||
const EventEmitter = require('events').EventEmitter;
|
||||
|
||||
class Instrumentation extends EventEmitter {
|
||||
constructor() {
|
||||
super();
|
||||
}
|
||||
|
||||
instrument(MongoClient, callback) {
|
||||
// store a reference to the original functions
|
||||
this.$MongoClient = MongoClient;
|
||||
const $prototypeConnect = (this.$prototypeConnect = MongoClient.prototype.connect);
|
||||
|
||||
const instrumentation = this;
|
||||
MongoClient.prototype.connect = function(callback) {
|
||||
this.s.options.monitorCommands = true;
|
||||
this.on('commandStarted', event => instrumentation.emit('started', event));
|
||||
this.on('commandSucceeded', event => instrumentation.emit('succeeded', event));
|
||||
this.on('commandFailed', event => instrumentation.emit('failed', event));
|
||||
return $prototypeConnect.call(this, callback);
|
||||
};
|
||||
|
||||
if (typeof callback === 'function') callback(null, this);
|
||||
}
|
||||
|
||||
uninstrument() {
|
||||
this.$MongoClient.prototype.connect = this.$prototypeConnect;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Instrumentation;
|
||||
5
node_modules/mongodb/lib/async/.eslintrc
generated
vendored
Normal file
5
node_modules/mongodb/lib/async/.eslintrc
generated
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"parserOptions": {
|
||||
"ecmaVersion": 2018
|
||||
}
|
||||
}
|
||||
33
node_modules/mongodb/lib/async/async_iterator.js
generated
vendored
Normal file
33
node_modules/mongodb/lib/async/async_iterator.js
generated
vendored
Normal file
@@ -0,0 +1,33 @@
|
||||
'use strict';
|
||||
|
||||
// async function* asyncIterator() {
|
||||
// while (true) {
|
||||
// const value = await this.next();
|
||||
// if (!value) {
|
||||
// await this.close();
|
||||
// return;
|
||||
// }
|
||||
|
||||
// yield value;
|
||||
// }
|
||||
// }
|
||||
|
||||
// TODO: change this to the async generator function above
|
||||
function asyncIterator() {
|
||||
const cursor = this;
|
||||
|
||||
return {
|
||||
next: function() {
|
||||
return Promise.resolve()
|
||||
.then(() => cursor.next())
|
||||
.then(value => {
|
||||
if (!value) {
|
||||
return cursor.close().then(() => ({ value, done: true }));
|
||||
}
|
||||
return { value, done: false };
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
exports.asyncIterator = asyncIterator;
|
||||
1297
node_modules/mongodb/lib/bulk/common.js
generated
vendored
Normal file
1297
node_modules/mongodb/lib/bulk/common.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
110
node_modules/mongodb/lib/bulk/ordered.js
generated
vendored
Normal file
110
node_modules/mongodb/lib/bulk/ordered.js
generated
vendored
Normal file
@@ -0,0 +1,110 @@
|
||||
'use strict';
|
||||
|
||||
const common = require('./common');
|
||||
const BulkOperationBase = common.BulkOperationBase;
|
||||
const Batch = common.Batch;
|
||||
const bson = common.bson;
|
||||
const utils = require('../utils');
|
||||
const toError = utils.toError;
|
||||
|
||||
/**
|
||||
* Add to internal list of Operations
|
||||
*
|
||||
* @ignore
|
||||
* @param {OrderedBulkOperation} bulkOperation
|
||||
* @param {number} docType number indicating the document type
|
||||
* @param {object} document
|
||||
* @return {OrderedBulkOperation}
|
||||
*/
|
||||
function addToOperationsList(bulkOperation, docType, document) {
|
||||
// Get the bsonSize
|
||||
const bsonSize = bson.calculateObjectSize(document, {
|
||||
checkKeys: false,
|
||||
|
||||
// Since we don't know what the user selected for BSON options here,
|
||||
// err on the safe side, and check the size with ignoreUndefined: false.
|
||||
ignoreUndefined: false
|
||||
});
|
||||
|
||||
// Throw error if the doc is bigger than the max BSON size
|
||||
if (bsonSize >= bulkOperation.s.maxBsonObjectSize)
|
||||
throw toError('document is larger than the maximum size ' + bulkOperation.s.maxBsonObjectSize);
|
||||
|
||||
// Create a new batch object if we don't have a current one
|
||||
if (bulkOperation.s.currentBatch == null)
|
||||
bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex);
|
||||
|
||||
const maxKeySize = bulkOperation.s.maxKeySize;
|
||||
|
||||
// Check if we need to create a new batch
|
||||
if (
|
||||
// New batch if we exceed the max batch op size
|
||||
bulkOperation.s.currentBatchSize + 1 >= bulkOperation.s.maxWriteBatchSize ||
|
||||
// New batch if we exceed the maxBatchSizeBytes. Only matters if batch already has a doc,
|
||||
// since we can't sent an empty batch
|
||||
(bulkOperation.s.currentBatchSize > 0 &&
|
||||
bulkOperation.s.currentBatchSizeBytes + maxKeySize + bsonSize >=
|
||||
bulkOperation.s.maxBatchSizeBytes) ||
|
||||
// New batch if the new op does not have the same op type as the current batch
|
||||
bulkOperation.s.currentBatch.batchType !== docType
|
||||
) {
|
||||
// Save the batch to the execution stack
|
||||
bulkOperation.s.batches.push(bulkOperation.s.currentBatch);
|
||||
|
||||
// Create a new batch
|
||||
bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex);
|
||||
|
||||
// Reset the current size trackers
|
||||
bulkOperation.s.currentBatchSize = 0;
|
||||
bulkOperation.s.currentBatchSizeBytes = 0;
|
||||
}
|
||||
|
||||
if (docType === common.INSERT) {
|
||||
bulkOperation.s.bulkResult.insertedIds.push({
|
||||
index: bulkOperation.s.currentIndex,
|
||||
_id: document._id
|
||||
});
|
||||
}
|
||||
|
||||
// We have an array of documents
|
||||
if (Array.isArray(document)) {
|
||||
throw toError('operation passed in cannot be an Array');
|
||||
}
|
||||
|
||||
bulkOperation.s.currentBatch.originalIndexes.push(bulkOperation.s.currentIndex);
|
||||
bulkOperation.s.currentBatch.operations.push(document);
|
||||
bulkOperation.s.currentBatchSize += 1;
|
||||
bulkOperation.s.currentBatchSizeBytes += maxKeySize + bsonSize;
|
||||
bulkOperation.s.currentIndex += 1;
|
||||
|
||||
// Return bulkOperation
|
||||
return bulkOperation;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new OrderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly)
|
||||
* @class
|
||||
* @extends BulkOperationBase
|
||||
* @property {number} length Get the number of operations in the bulk.
|
||||
* @return {OrderedBulkOperation} a OrderedBulkOperation instance.
|
||||
*/
|
||||
class OrderedBulkOperation extends BulkOperationBase {
|
||||
constructor(topology, collection, options) {
|
||||
options = options || {};
|
||||
options = Object.assign(options, { addToOperationsList });
|
||||
|
||||
super(topology, collection, options, true);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an unordered batch object
|
||||
* @ignore
|
||||
*/
|
||||
function initializeOrderedBulkOp(topology, collection, options) {
|
||||
return new OrderedBulkOperation(topology, collection, options);
|
||||
}
|
||||
|
||||
initializeOrderedBulkOp.OrderedBulkOperation = OrderedBulkOperation;
|
||||
module.exports = initializeOrderedBulkOp;
|
||||
module.exports.Bulk = OrderedBulkOperation;
|
||||
131
node_modules/mongodb/lib/bulk/unordered.js
generated
vendored
Normal file
131
node_modules/mongodb/lib/bulk/unordered.js
generated
vendored
Normal file
@@ -0,0 +1,131 @@
|
||||
'use strict';
|
||||
|
||||
const common = require('./common');
|
||||
const BulkOperationBase = common.BulkOperationBase;
|
||||
const Batch = common.Batch;
|
||||
const bson = common.bson;
|
||||
const utils = require('../utils');
|
||||
const toError = utils.toError;
|
||||
|
||||
/**
|
||||
* Add to internal list of Operations
|
||||
*
|
||||
* @ignore
|
||||
* @param {UnorderedBulkOperation} bulkOperation
|
||||
* @param {number} docType number indicating the document type
|
||||
* @param {object} document
|
||||
* @return {UnorderedBulkOperation}
|
||||
*/
|
||||
function addToOperationsList(bulkOperation, docType, document) {
|
||||
// Get the bsonSize
|
||||
const bsonSize = bson.calculateObjectSize(document, {
|
||||
checkKeys: false,
|
||||
|
||||
// Since we don't know what the user selected for BSON options here,
|
||||
// err on the safe side, and check the size with ignoreUndefined: false.
|
||||
ignoreUndefined: false
|
||||
});
|
||||
// Throw error if the doc is bigger than the max BSON size
|
||||
if (bsonSize >= bulkOperation.s.maxBsonObjectSize)
|
||||
throw toError('document is larger than the maximum size ' + bulkOperation.s.maxBsonObjectSize);
|
||||
// Holds the current batch
|
||||
bulkOperation.s.currentBatch = null;
|
||||
// Get the right type of batch
|
||||
if (docType === common.INSERT) {
|
||||
bulkOperation.s.currentBatch = bulkOperation.s.currentInsertBatch;
|
||||
} else if (docType === common.UPDATE) {
|
||||
bulkOperation.s.currentBatch = bulkOperation.s.currentUpdateBatch;
|
||||
} else if (docType === common.REMOVE) {
|
||||
bulkOperation.s.currentBatch = bulkOperation.s.currentRemoveBatch;
|
||||
}
|
||||
|
||||
const maxKeySize = bulkOperation.s.maxKeySize;
|
||||
|
||||
// Create a new batch object if we don't have a current one
|
||||
if (bulkOperation.s.currentBatch == null)
|
||||
bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex);
|
||||
|
||||
// Check if we need to create a new batch
|
||||
if (
|
||||
// New batch if we exceed the max batch op size
|
||||
bulkOperation.s.currentBatch.size + 1 >= bulkOperation.s.maxWriteBatchSize ||
|
||||
// New batch if we exceed the maxBatchSizeBytes. Only matters if batch already has a doc,
|
||||
// since we can't sent an empty batch
|
||||
(bulkOperation.s.currentBatch.size > 0 &&
|
||||
bulkOperation.s.currentBatch.sizeBytes + maxKeySize + bsonSize >=
|
||||
bulkOperation.s.maxBatchSizeBytes) ||
|
||||
// New batch if the new op does not have the same op type as the current batch
|
||||
bulkOperation.s.currentBatch.batchType !== docType
|
||||
) {
|
||||
// Save the batch to the execution stack
|
||||
bulkOperation.s.batches.push(bulkOperation.s.currentBatch);
|
||||
|
||||
// Create a new batch
|
||||
bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex);
|
||||
}
|
||||
|
||||
// We have an array of documents
|
||||
if (Array.isArray(document)) {
|
||||
throw toError('operation passed in cannot be an Array');
|
||||
}
|
||||
|
||||
bulkOperation.s.currentBatch.operations.push(document);
|
||||
bulkOperation.s.currentBatch.originalIndexes.push(bulkOperation.s.currentIndex);
|
||||
bulkOperation.s.currentIndex = bulkOperation.s.currentIndex + 1;
|
||||
|
||||
// Save back the current Batch to the right type
|
||||
if (docType === common.INSERT) {
|
||||
bulkOperation.s.currentInsertBatch = bulkOperation.s.currentBatch;
|
||||
bulkOperation.s.bulkResult.insertedIds.push({
|
||||
index: bulkOperation.s.bulkResult.insertedIds.length,
|
||||
_id: document._id
|
||||
});
|
||||
} else if (docType === common.UPDATE) {
|
||||
bulkOperation.s.currentUpdateBatch = bulkOperation.s.currentBatch;
|
||||
} else if (docType === common.REMOVE) {
|
||||
bulkOperation.s.currentRemoveBatch = bulkOperation.s.currentBatch;
|
||||
}
|
||||
|
||||
// Update current batch size
|
||||
bulkOperation.s.currentBatch.size += 1;
|
||||
bulkOperation.s.currentBatch.sizeBytes += maxKeySize + bsonSize;
|
||||
|
||||
// Return bulkOperation
|
||||
return bulkOperation;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new UnorderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly)
|
||||
* @class
|
||||
* @extends BulkOperationBase
|
||||
* @property {number} length Get the number of operations in the bulk.
|
||||
* @return {UnorderedBulkOperation} a UnorderedBulkOperation instance.
|
||||
*/
|
||||
class UnorderedBulkOperation extends BulkOperationBase {
|
||||
constructor(topology, collection, options) {
|
||||
options = options || {};
|
||||
options = Object.assign(options, { addToOperationsList });
|
||||
|
||||
super(topology, collection, options, false);
|
||||
}
|
||||
|
||||
handleWriteError(callback, writeResult) {
|
||||
if (this.s.batches.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return super.handleWriteError(callback, writeResult);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an unordered batch object
|
||||
* @ignore
|
||||
*/
|
||||
function initializeUnorderedBulkOp(topology, collection, options) {
|
||||
return new UnorderedBulkOperation(topology, collection, options);
|
||||
}
|
||||
|
||||
initializeUnorderedBulkOp.UnorderedBulkOperation = UnorderedBulkOperation;
|
||||
module.exports = initializeUnorderedBulkOp;
|
||||
module.exports.Bulk = UnorderedBulkOperation;
|
||||
623
node_modules/mongodb/lib/change_stream.js
generated
vendored
Normal file
623
node_modules/mongodb/lib/change_stream.js
generated
vendored
Normal file
@@ -0,0 +1,623 @@
|
||||
'use strict';
|
||||
|
||||
const Denque = require('denque');
|
||||
const EventEmitter = require('events');
|
||||
const isResumableError = require('./error').isResumableError;
|
||||
const MongoError = require('./core').MongoError;
|
||||
const Cursor = require('./cursor');
|
||||
const relayEvents = require('./core/utils').relayEvents;
|
||||
const maxWireVersion = require('./core/utils').maxWireVersion;
|
||||
const maybePromise = require('./utils').maybePromise;
|
||||
const now = require('./utils').now;
|
||||
const calculateDurationInMs = require('./utils').calculateDurationInMs;
|
||||
const AggregateOperation = require('./operations/aggregate');
|
||||
|
||||
const kResumeQueue = Symbol('resumeQueue');
|
||||
|
||||
const CHANGE_STREAM_OPTIONS = ['resumeAfter', 'startAfter', 'startAtOperationTime', 'fullDocument'];
|
||||
const CURSOR_OPTIONS = ['batchSize', 'maxAwaitTimeMS', 'collation', 'readPreference'].concat(
|
||||
CHANGE_STREAM_OPTIONS
|
||||
);
|
||||
|
||||
const CHANGE_DOMAIN_TYPES = {
|
||||
COLLECTION: Symbol('Collection'),
|
||||
DATABASE: Symbol('Database'),
|
||||
CLUSTER: Symbol('Cluster')
|
||||
};
|
||||
|
||||
/**
|
||||
* @typedef ResumeToken
|
||||
* @description Represents the logical starting point for a new or resuming {@link ChangeStream} on the server.
|
||||
* @see https://docs.mongodb.com/master/changeStreams/#change-stream-resume-token
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef OperationTime
|
||||
* @description Represents a specific point in time on a server. Can be retrieved by using {@link Db#command}
|
||||
* @see https://docs.mongodb.com/manual/reference/method/db.runCommand/#response
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef ChangeStreamOptions
|
||||
* @description Options that can be passed to a ChangeStream. Note that startAfter, resumeAfter, and startAtOperationTime are all mutually exclusive, and the server will error if more than one is specified.
|
||||
* @property {string} [fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred.
|
||||
* @property {number} [maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query.
|
||||
* @property {ResumeToken} [resumeAfter] Allows you to start a changeStream after a specified event. See {@link https://docs.mongodb.com/master/changeStreams/#resumeafter-for-change-streams|ChangeStream documentation}.
|
||||
* @property {ResumeToken} [startAfter] Similar to resumeAfter, but will allow you to start after an invalidated event. See {@link https://docs.mongodb.com/master/changeStreams/#startafter-for-change-streams|ChangeStream documentation}.
|
||||
* @property {OperationTime} [startAtOperationTime] Will start the changeStream after the specified operationTime.
|
||||
* @property {number} [batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.
|
||||
* @property {object} [collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.
|
||||
* @property {ReadPreference} [readPreference] The read preference. Defaults to the read preference of the database or collection. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Creates a new Change Stream instance. Normally created using {@link Collection#watch|Collection.watch()}.
|
||||
* @class ChangeStream
|
||||
* @since 3.0.0
|
||||
* @param {(MongoClient|Db|Collection)} parent The parent object that created this change stream
|
||||
* @param {Array} pipeline An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents
|
||||
* @param {ChangeStreamOptions} [options] Optional settings
|
||||
* @fires ChangeStream#close
|
||||
* @fires ChangeStream#change
|
||||
* @fires ChangeStream#end
|
||||
* @fires ChangeStream#error
|
||||
* @fires ChangeStream#resumeTokenChanged
|
||||
* @return {ChangeStream} a ChangeStream instance.
|
||||
*/
|
||||
class ChangeStream extends EventEmitter {
|
||||
constructor(parent, pipeline, options) {
|
||||
super();
|
||||
const Collection = require('./collection');
|
||||
const Db = require('./db');
|
||||
const MongoClient = require('./mongo_client');
|
||||
|
||||
this.pipeline = pipeline || [];
|
||||
this.options = options || {};
|
||||
|
||||
this.parent = parent;
|
||||
this.namespace = parent.s.namespace;
|
||||
if (parent instanceof Collection) {
|
||||
this.type = CHANGE_DOMAIN_TYPES.COLLECTION;
|
||||
this.topology = parent.s.db.serverConfig;
|
||||
} else if (parent instanceof Db) {
|
||||
this.type = CHANGE_DOMAIN_TYPES.DATABASE;
|
||||
this.topology = parent.serverConfig;
|
||||
} else if (parent instanceof MongoClient) {
|
||||
this.type = CHANGE_DOMAIN_TYPES.CLUSTER;
|
||||
this.topology = parent.topology;
|
||||
} else {
|
||||
throw new TypeError(
|
||||
'parent provided to ChangeStream constructor is not an instance of Collection, Db, or MongoClient'
|
||||
);
|
||||
}
|
||||
|
||||
this.promiseLibrary = parent.s.promiseLibrary;
|
||||
if (!this.options.readPreference && parent.s.readPreference) {
|
||||
this.options.readPreference = parent.s.readPreference;
|
||||
}
|
||||
|
||||
this[kResumeQueue] = new Denque();
|
||||
|
||||
// Create contained Change Stream cursor
|
||||
this.cursor = createChangeStreamCursor(this, options);
|
||||
|
||||
this.closed = false;
|
||||
|
||||
// Listen for any `change` listeners being added to ChangeStream
|
||||
this.on('newListener', eventName => {
|
||||
if (eventName === 'change' && this.cursor && this.listenerCount('change') === 0) {
|
||||
this.cursor.on('data', change => processNewChange(this, change));
|
||||
}
|
||||
});
|
||||
|
||||
// Listen for all `change` listeners being removed from ChangeStream
|
||||
this.on('removeListener', eventName => {
|
||||
if (eventName === 'change' && this.listenerCount('change') === 0 && this.cursor) {
|
||||
this.cursor.removeAllListeners('data');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @property {ResumeToken} resumeToken
|
||||
* The cached resume token that will be used to resume
|
||||
* after the most recently returned change.
|
||||
*/
|
||||
get resumeToken() {
|
||||
return this.cursor.resumeToken;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if there is any document still available in the Change Stream
|
||||
* @function ChangeStream.prototype.hasNext
|
||||
* @param {ChangeStream~resultCallback} [callback] The result callback.
|
||||
* @throws {MongoError}
|
||||
* @returns {Promise|void} returns Promise if no callback passed
|
||||
*/
|
||||
hasNext(callback) {
|
||||
return maybePromise(this.parent, callback, cb => {
|
||||
getCursor(this, (err, cursor) => {
|
||||
if (err) return cb(err); // failed to resume, raise an error
|
||||
cursor.hasNext(cb);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the next available document from the Change Stream, returns null if no more documents are available.
|
||||
* @function ChangeStream.prototype.next
|
||||
* @param {ChangeStream~resultCallback} [callback] The result callback.
|
||||
* @throws {MongoError}
|
||||
* @returns {Promise|void} returns Promise if no callback passed
|
||||
*/
|
||||
next(callback) {
|
||||
return maybePromise(this.parent, callback, cb => {
|
||||
getCursor(this, (err, cursor) => {
|
||||
if (err) return cb(err); // failed to resume, raise an error
|
||||
cursor.next((error, change) => {
|
||||
if (error) {
|
||||
this[kResumeQueue].push(() => this.next(cb));
|
||||
processError(this, error, cb);
|
||||
return;
|
||||
}
|
||||
processNewChange(this, change, cb);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Is the change stream closed
|
||||
* @method ChangeStream.prototype.isClosed
|
||||
* @return {boolean}
|
||||
*/
|
||||
isClosed() {
|
||||
return this.closed || (this.cursor && this.cursor.isClosed());
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the Change Stream
|
||||
* @method ChangeStream.prototype.close
|
||||
* @param {ChangeStream~resultCallback} [callback] The result callback.
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
close(callback) {
|
||||
return maybePromise(this.parent, callback, cb => {
|
||||
if (this.closed) return cb();
|
||||
|
||||
// flag the change stream as explicitly closed
|
||||
this.closed = true;
|
||||
|
||||
if (!this.cursor) return cb();
|
||||
|
||||
// Tidy up the existing cursor
|
||||
const cursor = this.cursor;
|
||||
|
||||
return cursor.close(err => {
|
||||
['data', 'close', 'end', 'error'].forEach(event => cursor.removeAllListeners(event));
|
||||
this.cursor = undefined;
|
||||
|
||||
return cb(err);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream.
|
||||
* @method
|
||||
* @param {Writable} destination The destination for writing data
|
||||
* @param {object} [options] {@link https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options|Pipe options}
|
||||
* @return {null}
|
||||
*/
|
||||
pipe(destination, options) {
|
||||
if (!this.pipeDestinations) {
|
||||
this.pipeDestinations = [];
|
||||
}
|
||||
this.pipeDestinations.push(destination);
|
||||
return this.cursor.pipe(destination, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* This method will remove the hooks set up for a previous pipe() call.
|
||||
* @param {Writable} [destination] The destination for writing data
|
||||
* @return {null}
|
||||
*/
|
||||
unpipe(destination) {
|
||||
if (this.pipeDestinations && this.pipeDestinations.indexOf(destination) > -1) {
|
||||
this.pipeDestinations.splice(this.pipeDestinations.indexOf(destination), 1);
|
||||
}
|
||||
return this.cursor.unpipe(destination);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a modified Readable stream including a possible transform method.
|
||||
* @method
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {function} [options.transform] A transformation method applied to each document emitted by the stream.
|
||||
* @return {Cursor}
|
||||
*/
|
||||
stream(options) {
|
||||
this.streamOptions = options;
|
||||
return this.cursor.stream(options);
|
||||
}
|
||||
|
||||
/**
|
||||
* This method will cause a stream in flowing mode to stop emitting data events. Any data that becomes available will remain in the internal buffer.
|
||||
* @return {null}
|
||||
*/
|
||||
pause() {
|
||||
return this.cursor.pause();
|
||||
}
|
||||
|
||||
/**
|
||||
* This method will cause the readable stream to resume emitting data events.
|
||||
* @return {null}
|
||||
*/
|
||||
resume() {
|
||||
return this.cursor.resume();
|
||||
}
|
||||
}
|
||||
|
||||
class ChangeStreamCursor extends Cursor {
|
||||
constructor(topology, operation, options) {
|
||||
super(topology, operation, options);
|
||||
|
||||
options = options || {};
|
||||
this._resumeToken = null;
|
||||
this.startAtOperationTime = options.startAtOperationTime;
|
||||
|
||||
if (options.startAfter) {
|
||||
this.resumeToken = options.startAfter;
|
||||
} else if (options.resumeAfter) {
|
||||
this.resumeToken = options.resumeAfter;
|
||||
}
|
||||
}
|
||||
|
||||
set resumeToken(token) {
|
||||
this._resumeToken = token;
|
||||
this.emit('resumeTokenChanged', token);
|
||||
}
|
||||
|
||||
get resumeToken() {
|
||||
return this._resumeToken;
|
||||
}
|
||||
|
||||
get resumeOptions() {
|
||||
const result = {};
|
||||
for (const optionName of CURSOR_OPTIONS) {
|
||||
if (this.options[optionName]) result[optionName] = this.options[optionName];
|
||||
}
|
||||
|
||||
if (this.resumeToken || this.startAtOperationTime) {
|
||||
['resumeAfter', 'startAfter', 'startAtOperationTime'].forEach(key => delete result[key]);
|
||||
|
||||
if (this.resumeToken) {
|
||||
const resumeKey =
|
||||
this.options.startAfter && !this.hasReceived ? 'startAfter' : 'resumeAfter';
|
||||
result[resumeKey] = this.resumeToken;
|
||||
} else if (this.startAtOperationTime && maxWireVersion(this.server) >= 7) {
|
||||
result.startAtOperationTime = this.startAtOperationTime;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
cacheResumeToken(resumeToken) {
|
||||
if (this.bufferedCount() === 0 && this.cursorState.postBatchResumeToken) {
|
||||
this.resumeToken = this.cursorState.postBatchResumeToken;
|
||||
} else {
|
||||
this.resumeToken = resumeToken;
|
||||
}
|
||||
this.hasReceived = true;
|
||||
}
|
||||
|
||||
_processBatch(batchName, response) {
|
||||
const cursor = response.cursor;
|
||||
if (cursor.postBatchResumeToken) {
|
||||
this.cursorState.postBatchResumeToken = cursor.postBatchResumeToken;
|
||||
|
||||
if (cursor[batchName].length === 0) {
|
||||
this.resumeToken = cursor.postBatchResumeToken;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_initializeCursor(callback) {
|
||||
super._initializeCursor((err, result) => {
|
||||
if (err || result == null) {
|
||||
callback(err, result);
|
||||
return;
|
||||
}
|
||||
|
||||
const response = result.documents[0];
|
||||
|
||||
if (
|
||||
this.startAtOperationTime == null &&
|
||||
this.resumeAfter == null &&
|
||||
this.startAfter == null &&
|
||||
maxWireVersion(this.server) >= 7
|
||||
) {
|
||||
this.startAtOperationTime = response.operationTime;
|
||||
}
|
||||
|
||||
this._processBatch('firstBatch', response);
|
||||
|
||||
this.emit('init', result);
|
||||
this.emit('response');
|
||||
callback(err, result);
|
||||
});
|
||||
}
|
||||
|
||||
_getMore(callback) {
|
||||
super._getMore((err, response) => {
|
||||
if (err) {
|
||||
callback(err);
|
||||
return;
|
||||
}
|
||||
|
||||
this._processBatch('nextBatch', response);
|
||||
|
||||
this.emit('more', response);
|
||||
this.emit('response');
|
||||
callback(err, response);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @event ChangeStreamCursor#response
|
||||
* internal event DO NOT USE
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
// Create a new change stream cursor based on self's configuration
|
||||
function createChangeStreamCursor(self, options) {
|
||||
const changeStreamStageOptions = { fullDocument: options.fullDocument || 'default' };
|
||||
applyKnownOptions(changeStreamStageOptions, options, CHANGE_STREAM_OPTIONS);
|
||||
if (self.type === CHANGE_DOMAIN_TYPES.CLUSTER) {
|
||||
changeStreamStageOptions.allChangesForCluster = true;
|
||||
}
|
||||
|
||||
const pipeline = [{ $changeStream: changeStreamStageOptions }].concat(self.pipeline);
|
||||
const cursorOptions = applyKnownOptions({}, options, CURSOR_OPTIONS);
|
||||
|
||||
const changeStreamCursor = new ChangeStreamCursor(
|
||||
self.topology,
|
||||
new AggregateOperation(self.parent, pipeline, options),
|
||||
cursorOptions
|
||||
);
|
||||
|
||||
relayEvents(changeStreamCursor, self, ['resumeTokenChanged', 'end', 'close']);
|
||||
|
||||
/**
|
||||
* Fired for each new matching change in the specified namespace. Attaching a `change`
|
||||
* event listener to a Change Stream will switch the stream into flowing mode. Data will
|
||||
* then be passed as soon as it is available.
|
||||
*
|
||||
* @event ChangeStream#change
|
||||
* @type {object}
|
||||
*/
|
||||
if (self.listenerCount('change') > 0) {
|
||||
changeStreamCursor.on('data', function(change) {
|
||||
processNewChange(self, change);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Change stream close event
|
||||
*
|
||||
* @event ChangeStream#close
|
||||
* @type {null}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Change stream end event
|
||||
*
|
||||
* @event ChangeStream#end
|
||||
* @type {null}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Emitted each time the change stream stores a new resume token.
|
||||
*
|
||||
* @event ChangeStream#resumeTokenChanged
|
||||
* @type {ResumeToken}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Fired when the stream encounters an error.
|
||||
*
|
||||
* @event ChangeStream#error
|
||||
* @type {Error}
|
||||
*/
|
||||
changeStreamCursor.on('error', function(error) {
|
||||
processError(self, error);
|
||||
});
|
||||
|
||||
if (self.pipeDestinations) {
|
||||
const cursorStream = changeStreamCursor.stream(self.streamOptions);
|
||||
for (let pipeDestination in self.pipeDestinations) {
|
||||
cursorStream.pipe(pipeDestination);
|
||||
}
|
||||
}
|
||||
|
||||
return changeStreamCursor;
|
||||
}
|
||||
|
||||
function applyKnownOptions(target, source, optionNames) {
|
||||
optionNames.forEach(name => {
|
||||
if (source[name]) {
|
||||
target[name] = source[name];
|
||||
}
|
||||
});
|
||||
|
||||
return target;
|
||||
}
|
||||
|
||||
// This method performs a basic server selection loop, satisfying the requirements of
|
||||
// ChangeStream resumability until the new SDAM layer can be used.
|
||||
const SELECTION_TIMEOUT = 30000;
|
||||
function waitForTopologyConnected(topology, options, callback) {
|
||||
setTimeout(() => {
|
||||
if (options && options.start == null) {
|
||||
options.start = now();
|
||||
}
|
||||
|
||||
const start = options.start || now();
|
||||
const timeout = options.timeout || SELECTION_TIMEOUT;
|
||||
const readPreference = options.readPreference;
|
||||
if (topology.isConnected({ readPreference })) {
|
||||
return callback();
|
||||
}
|
||||
|
||||
if (calculateDurationInMs(start) > timeout) {
|
||||
return callback(new MongoError('Timed out waiting for connection'));
|
||||
}
|
||||
|
||||
waitForTopologyConnected(topology, options, callback);
|
||||
}, 500); // this is an arbitrary wait time to allow SDAM to transition
|
||||
}
|
||||
|
||||
function processNewChange(changeStream, change, callback) {
|
||||
const cursor = changeStream.cursor;
|
||||
|
||||
// a null change means the cursor has been notified, implicitly closing the change stream
|
||||
if (change == null) {
|
||||
changeStream.closed = true;
|
||||
}
|
||||
|
||||
if (changeStream.closed) {
|
||||
if (callback) callback(new MongoError('ChangeStream is closed'));
|
||||
return;
|
||||
}
|
||||
|
||||
if (change && !change._id) {
|
||||
const noResumeTokenError = new Error(
|
||||
'A change stream document has been received that lacks a resume token (_id).'
|
||||
);
|
||||
|
||||
if (!callback) return changeStream.emit('error', noResumeTokenError);
|
||||
return callback(noResumeTokenError);
|
||||
}
|
||||
|
||||
// cache the resume token
|
||||
cursor.cacheResumeToken(change._id);
|
||||
|
||||
// wipe the startAtOperationTime if there was one so that there won't be a conflict
|
||||
// between resumeToken and startAtOperationTime if we need to reconnect the cursor
|
||||
changeStream.options.startAtOperationTime = undefined;
|
||||
|
||||
// Return the change
|
||||
if (!callback) return changeStream.emit('change', change);
|
||||
return callback(undefined, change);
|
||||
}
|
||||
|
||||
function processError(changeStream, error, callback) {
|
||||
const topology = changeStream.topology;
|
||||
const cursor = changeStream.cursor;
|
||||
|
||||
// If the change stream has been closed explictly, do not process error.
|
||||
if (changeStream.closed) {
|
||||
if (callback) callback(new MongoError('ChangeStream is closed'));
|
||||
return;
|
||||
}
|
||||
|
||||
// if the resume succeeds, continue with the new cursor
|
||||
function resumeWithCursor(newCursor) {
|
||||
changeStream.cursor = newCursor;
|
||||
processResumeQueue(changeStream);
|
||||
}
|
||||
|
||||
// otherwise, raise an error and close the change stream
|
||||
function unresumableError(err) {
|
||||
if (!callback) {
|
||||
changeStream.emit('error', err);
|
||||
changeStream.emit('close');
|
||||
}
|
||||
processResumeQueue(changeStream, err);
|
||||
changeStream.closed = true;
|
||||
}
|
||||
|
||||
if (cursor && isResumableError(error, maxWireVersion(cursor.server))) {
|
||||
changeStream.cursor = undefined;
|
||||
|
||||
// stop listening to all events from old cursor
|
||||
['data', 'close', 'end', 'error'].forEach(event => cursor.removeAllListeners(event));
|
||||
|
||||
// close internal cursor, ignore errors
|
||||
cursor.close();
|
||||
|
||||
waitForTopologyConnected(topology, { readPreference: cursor.options.readPreference }, err => {
|
||||
// if the topology can't reconnect, close the stream
|
||||
if (err) return unresumableError(err);
|
||||
|
||||
// create a new cursor, preserving the old cursor's options
|
||||
const newCursor = createChangeStreamCursor(changeStream, cursor.resumeOptions);
|
||||
|
||||
// attempt to continue in emitter mode
|
||||
if (!callback) return resumeWithCursor(newCursor);
|
||||
|
||||
// attempt to continue in iterator mode
|
||||
newCursor.hasNext(err => {
|
||||
// if there's an error immediately after resuming, close the stream
|
||||
if (err) return unresumableError(err);
|
||||
resumeWithCursor(newCursor);
|
||||
});
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!callback) return changeStream.emit('error', error);
|
||||
return callback(error);
|
||||
}
|
||||
|
||||
/**
|
||||
* Safely provides a cursor across resume attempts
|
||||
*
|
||||
* @param {ChangeStream} changeStream the parent ChangeStream
|
||||
* @param {function} callback gets the cursor or error
|
||||
* @param {ChangeStreamCursor} [oldCursor] when resuming from an error, carry over options from previous cursor
|
||||
*/
|
||||
function getCursor(changeStream, callback) {
|
||||
if (changeStream.isClosed()) {
|
||||
callback(new MongoError('ChangeStream is closed.'));
|
||||
return;
|
||||
}
|
||||
|
||||
// if a cursor exists and it is open, return it
|
||||
if (changeStream.cursor) {
|
||||
callback(undefined, changeStream.cursor);
|
||||
return;
|
||||
}
|
||||
|
||||
// no cursor, queue callback until topology reconnects
|
||||
changeStream[kResumeQueue].push(callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Drain the resume queue when a new has become available
|
||||
*
|
||||
* @param {ChangeStream} changeStream the parent ChangeStream
|
||||
* @param {ChangeStreamCursor?} changeStream.cursor the new cursor
|
||||
* @param {Error} [err] error getting a new cursor
|
||||
*/
|
||||
function processResumeQueue(changeStream, err) {
|
||||
while (changeStream[kResumeQueue].length) {
|
||||
const request = changeStream[kResumeQueue].pop();
|
||||
if (changeStream.isClosed() && !err) {
|
||||
request(new MongoError('Change Stream is not open.'));
|
||||
return;
|
||||
}
|
||||
request(err, changeStream.cursor);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The callback format for results
|
||||
* @callback ChangeStream~resultCallback
|
||||
* @param {MongoError} error An error instance representing the error during the execution.
|
||||
* @param {(object|null)} result The result object if the command was executed successfully.
|
||||
*/
|
||||
|
||||
module.exports = ChangeStream;
|
||||
384
node_modules/mongodb/lib/cmap/connection.js
generated
vendored
Normal file
384
node_modules/mongodb/lib/cmap/connection.js
generated
vendored
Normal file
@@ -0,0 +1,384 @@
|
||||
'use strict';
|
||||
|
||||
const EventEmitter = require('events');
|
||||
const MessageStream = require('./message_stream');
|
||||
const MongoError = require('../core/error').MongoError;
|
||||
const MongoNetworkError = require('../core/error').MongoNetworkError;
|
||||
const MongoNetworkTimeoutError = require('../core/error').MongoNetworkTimeoutError;
|
||||
const MongoWriteConcernError = require('../core/error').MongoWriteConcernError;
|
||||
const CommandResult = require('../core/connection/command_result');
|
||||
const StreamDescription = require('./stream_description').StreamDescription;
|
||||
const wp = require('../core/wireprotocol');
|
||||
const apm = require('../core/connection/apm');
|
||||
const updateSessionFromResponse = require('../core/sessions').updateSessionFromResponse;
|
||||
const uuidV4 = require('../core/utils').uuidV4;
|
||||
const now = require('../utils').now;
|
||||
const calculateDurationInMs = require('../utils').calculateDurationInMs;
|
||||
|
||||
const kStream = Symbol('stream');
|
||||
const kQueue = Symbol('queue');
|
||||
const kMessageStream = Symbol('messageStream');
|
||||
const kGeneration = Symbol('generation');
|
||||
const kLastUseTime = Symbol('lastUseTime');
|
||||
const kClusterTime = Symbol('clusterTime');
|
||||
const kDescription = Symbol('description');
|
||||
const kIsMaster = Symbol('ismaster');
|
||||
const kAutoEncrypter = Symbol('autoEncrypter');
|
||||
|
||||
class Connection extends EventEmitter {
|
||||
constructor(stream, options) {
|
||||
super(options);
|
||||
|
||||
this.id = options.id;
|
||||
this.address = streamIdentifier(stream);
|
||||
this.bson = options.bson;
|
||||
this.socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000;
|
||||
this.host = options.host || 'localhost';
|
||||
this.port = options.port || 27017;
|
||||
this.monitorCommands =
|
||||
typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false;
|
||||
this.closed = false;
|
||||
this.destroyed = false;
|
||||
|
||||
this[kDescription] = new StreamDescription(this.address, options);
|
||||
this[kGeneration] = options.generation;
|
||||
this[kLastUseTime] = now();
|
||||
|
||||
// retain a reference to an `AutoEncrypter` if present
|
||||
if (options.autoEncrypter) {
|
||||
this[kAutoEncrypter] = options.autoEncrypter;
|
||||
}
|
||||
|
||||
// setup parser stream and message handling
|
||||
this[kQueue] = new Map();
|
||||
this[kMessageStream] = new MessageStream(options);
|
||||
this[kMessageStream].on('message', messageHandler(this));
|
||||
this[kStream] = stream;
|
||||
stream.on('error', () => {
|
||||
/* ignore errors, listen to `close` instead */
|
||||
});
|
||||
|
||||
stream.on('close', () => {
|
||||
if (this.closed) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.closed = true;
|
||||
this[kQueue].forEach(op =>
|
||||
op.cb(new MongoNetworkError(`connection ${this.id} to ${this.address} closed`))
|
||||
);
|
||||
this[kQueue].clear();
|
||||
|
||||
this.emit('close');
|
||||
});
|
||||
|
||||
stream.on('timeout', () => {
|
||||
if (this.closed) {
|
||||
return;
|
||||
}
|
||||
|
||||
stream.destroy();
|
||||
this.closed = true;
|
||||
this[kQueue].forEach(op =>
|
||||
op.cb(
|
||||
new MongoNetworkTimeoutError(`connection ${this.id} to ${this.address} timed out`, {
|
||||
beforeHandshake: this[kIsMaster] == null
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
this[kQueue].clear();
|
||||
this.emit('close');
|
||||
});
|
||||
|
||||
// hook the message stream up to the passed in stream
|
||||
stream.pipe(this[kMessageStream]);
|
||||
this[kMessageStream].pipe(stream);
|
||||
}
|
||||
|
||||
get description() {
|
||||
return this[kDescription];
|
||||
}
|
||||
|
||||
get ismaster() {
|
||||
return this[kIsMaster];
|
||||
}
|
||||
|
||||
// the `connect` method stores the result of the handshake ismaster on the connection
|
||||
set ismaster(response) {
|
||||
this[kDescription].receiveResponse(response);
|
||||
|
||||
// TODO: remove this, and only use the `StreamDescription` in the future
|
||||
this[kIsMaster] = response;
|
||||
}
|
||||
|
||||
get generation() {
|
||||
return this[kGeneration] || 0;
|
||||
}
|
||||
|
||||
get idleTime() {
|
||||
return calculateDurationInMs(this[kLastUseTime]);
|
||||
}
|
||||
|
||||
get clusterTime() {
|
||||
return this[kClusterTime];
|
||||
}
|
||||
|
||||
get stream() {
|
||||
return this[kStream];
|
||||
}
|
||||
|
||||
markAvailable() {
|
||||
this[kLastUseTime] = now();
|
||||
}
|
||||
|
||||
destroy(options, callback) {
|
||||
if (typeof options === 'function') {
|
||||
callback = options;
|
||||
options = {};
|
||||
}
|
||||
|
||||
options = Object.assign({ force: false }, options);
|
||||
if (this[kStream] == null || this.destroyed) {
|
||||
this.destroyed = true;
|
||||
if (typeof callback === 'function') {
|
||||
callback();
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (options.force) {
|
||||
this[kStream].destroy();
|
||||
this.destroyed = true;
|
||||
if (typeof callback === 'function') {
|
||||
callback();
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
this[kStream].end(err => {
|
||||
this.destroyed = true;
|
||||
if (typeof callback === 'function') {
|
||||
callback(err);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Wire protocol methods
|
||||
command(ns, cmd, options, callback) {
|
||||
wp.command(makeServerTrampoline(this), ns, cmd, options, callback);
|
||||
}
|
||||
|
||||
query(ns, cmd, cursorState, options, callback) {
|
||||
wp.query(makeServerTrampoline(this), ns, cmd, cursorState, options, callback);
|
||||
}
|
||||
|
||||
getMore(ns, cursorState, batchSize, options, callback) {
|
||||
wp.getMore(makeServerTrampoline(this), ns, cursorState, batchSize, options, callback);
|
||||
}
|
||||
|
||||
killCursors(ns, cursorState, callback) {
|
||||
wp.killCursors(makeServerTrampoline(this), ns, cursorState, callback);
|
||||
}
|
||||
|
||||
insert(ns, ops, options, callback) {
|
||||
wp.insert(makeServerTrampoline(this), ns, ops, options, callback);
|
||||
}
|
||||
|
||||
update(ns, ops, options, callback) {
|
||||
wp.update(makeServerTrampoline(this), ns, ops, options, callback);
|
||||
}
|
||||
|
||||
remove(ns, ops, options, callback) {
|
||||
wp.remove(makeServerTrampoline(this), ns, ops, options, callback);
|
||||
}
|
||||
}
|
||||
|
||||
/// This lets us emulate a legacy `Server` instance so we can work with the existing wire
|
||||
/// protocol methods. Eventually, the operation executor will return a `Connection` to execute
|
||||
/// against.
|
||||
function makeServerTrampoline(connection) {
|
||||
const server = {
|
||||
description: connection.description,
|
||||
clusterTime: connection[kClusterTime],
|
||||
s: {
|
||||
bson: connection.bson,
|
||||
pool: { write: write.bind(connection), isConnected: () => true }
|
||||
}
|
||||
};
|
||||
|
||||
if (connection[kAutoEncrypter]) {
|
||||
server.autoEncrypter = connection[kAutoEncrypter];
|
||||
}
|
||||
|
||||
return server;
|
||||
}
|
||||
|
||||
function messageHandler(conn) {
|
||||
return function messageHandler(message) {
|
||||
// always emit the message, in case we are streaming
|
||||
conn.emit('message', message);
|
||||
if (!conn[kQueue].has(message.responseTo)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const operationDescription = conn[kQueue].get(message.responseTo);
|
||||
const callback = operationDescription.cb;
|
||||
|
||||
// SERVER-45775: For exhaust responses we should be able to use the same requestId to
|
||||
// track response, however the server currently synthetically produces remote requests
|
||||
// making the `responseTo` change on each response
|
||||
conn[kQueue].delete(message.responseTo);
|
||||
if (message.moreToCome) {
|
||||
// requeue the callback for next synthetic request
|
||||
conn[kQueue].set(message.requestId, operationDescription);
|
||||
} else if (operationDescription.socketTimeoutOverride) {
|
||||
conn[kStream].setTimeout(conn.socketTimeout);
|
||||
}
|
||||
|
||||
try {
|
||||
// Pass in the entire description because it has BSON parsing options
|
||||
message.parse(operationDescription);
|
||||
} catch (err) {
|
||||
callback(new MongoError(err));
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.documents[0]) {
|
||||
const document = message.documents[0];
|
||||
const session = operationDescription.session;
|
||||
if (session) {
|
||||
updateSessionFromResponse(session, document);
|
||||
}
|
||||
|
||||
if (document.$clusterTime) {
|
||||
conn[kClusterTime] = document.$clusterTime;
|
||||
conn.emit('clusterTimeReceived', document.$clusterTime);
|
||||
}
|
||||
|
||||
if (operationDescription.command) {
|
||||
if (document.writeConcernError) {
|
||||
callback(new MongoWriteConcernError(document.writeConcernError, document));
|
||||
return;
|
||||
}
|
||||
|
||||
if (document.ok === 0 || document.$err || document.errmsg || document.code) {
|
||||
callback(new MongoError(document));
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// NODE-2382: reenable in our glorious non-leaky abstraction future
|
||||
// callback(null, operationDescription.fullResult ? message : message.documents[0]);
|
||||
|
||||
callback(
|
||||
undefined,
|
||||
new CommandResult(
|
||||
operationDescription.fullResult ? message : message.documents[0],
|
||||
conn,
|
||||
message
|
||||
)
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
function streamIdentifier(stream) {
|
||||
if (typeof stream.address === 'function') {
|
||||
return `${stream.remoteAddress}:${stream.remotePort}`;
|
||||
}
|
||||
|
||||
return uuidV4().toString('hex');
|
||||
}
|
||||
|
||||
// Not meant to be called directly, the wire protocol methods call this assuming it is a `Pool` instance
|
||||
function write(command, options, callback) {
|
||||
if (typeof options === 'function') {
|
||||
callback = options;
|
||||
}
|
||||
|
||||
options = options || {};
|
||||
const operationDescription = {
|
||||
requestId: command.requestId,
|
||||
cb: callback,
|
||||
session: options.session,
|
||||
fullResult: typeof options.fullResult === 'boolean' ? options.fullResult : false,
|
||||
noResponse: typeof options.noResponse === 'boolean' ? options.noResponse : false,
|
||||
documentsReturnedIn: options.documentsReturnedIn,
|
||||
command: !!options.command,
|
||||
|
||||
// for BSON parsing
|
||||
promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true,
|
||||
promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true,
|
||||
promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false,
|
||||
raw: typeof options.raw === 'boolean' ? options.raw : false
|
||||
};
|
||||
|
||||
if (this[kDescription] && this[kDescription].compressor) {
|
||||
operationDescription.agreedCompressor = this[kDescription].compressor;
|
||||
|
||||
if (this[kDescription].zlibCompressionLevel) {
|
||||
operationDescription.zlibCompressionLevel = this[kDescription].zlibCompressionLevel;
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof options.socketTimeout === 'number') {
|
||||
operationDescription.socketTimeoutOverride = true;
|
||||
this[kStream].setTimeout(options.socketTimeout);
|
||||
}
|
||||
|
||||
// if command monitoring is enabled we need to modify the callback here
|
||||
if (this.monitorCommands) {
|
||||
this.emit('commandStarted', new apm.CommandStartedEvent(this, command));
|
||||
|
||||
operationDescription.started = now();
|
||||
operationDescription.cb = (err, reply) => {
|
||||
if (err) {
|
||||
this.emit(
|
||||
'commandFailed',
|
||||
new apm.CommandFailedEvent(this, command, err, operationDescription.started)
|
||||
);
|
||||
} else {
|
||||
if (reply && reply.result && (reply.result.ok === 0 || reply.result.$err)) {
|
||||
this.emit(
|
||||
'commandFailed',
|
||||
new apm.CommandFailedEvent(this, command, reply.result, operationDescription.started)
|
||||
);
|
||||
} else {
|
||||
this.emit(
|
||||
'commandSucceeded',
|
||||
new apm.CommandSucceededEvent(this, command, reply, operationDescription.started)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof callback === 'function') {
|
||||
callback(err, reply);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
if (!operationDescription.noResponse) {
|
||||
this[kQueue].set(operationDescription.requestId, operationDescription);
|
||||
}
|
||||
|
||||
try {
|
||||
this[kMessageStream].writeCommand(command, operationDescription);
|
||||
} catch (e) {
|
||||
if (!operationDescription.noResponse) {
|
||||
this[kQueue].delete(operationDescription.requestId);
|
||||
operationDescription.cb(e);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (operationDescription.noResponse) {
|
||||
operationDescription.cb();
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
Connection
|
||||
};
|
||||
595
node_modules/mongodb/lib/cmap/connection_pool.js
generated
vendored
Normal file
595
node_modules/mongodb/lib/cmap/connection_pool.js
generated
vendored
Normal file
@@ -0,0 +1,595 @@
|
||||
'use strict';
|
||||
|
||||
const Denque = require('denque');
|
||||
const EventEmitter = require('events').EventEmitter;
|
||||
const Logger = require('../core/connection/logger');
|
||||
const makeCounter = require('../utils').makeCounter;
|
||||
const MongoError = require('../core/error').MongoError;
|
||||
const Connection = require('./connection').Connection;
|
||||
const eachAsync = require('../core/utils').eachAsync;
|
||||
const connect = require('../core/connection/connect');
|
||||
const relayEvents = require('../core/utils').relayEvents;
|
||||
|
||||
const errors = require('./errors');
|
||||
const PoolClosedError = errors.PoolClosedError;
|
||||
const WaitQueueTimeoutError = errors.WaitQueueTimeoutError;
|
||||
|
||||
const events = require('./events');
|
||||
const ConnectionPoolCreatedEvent = events.ConnectionPoolCreatedEvent;
|
||||
const ConnectionPoolClosedEvent = events.ConnectionPoolClosedEvent;
|
||||
const ConnectionCreatedEvent = events.ConnectionCreatedEvent;
|
||||
const ConnectionReadyEvent = events.ConnectionReadyEvent;
|
||||
const ConnectionClosedEvent = events.ConnectionClosedEvent;
|
||||
const ConnectionCheckOutStartedEvent = events.ConnectionCheckOutStartedEvent;
|
||||
const ConnectionCheckOutFailedEvent = events.ConnectionCheckOutFailedEvent;
|
||||
const ConnectionCheckedOutEvent = events.ConnectionCheckedOutEvent;
|
||||
const ConnectionCheckedInEvent = events.ConnectionCheckedInEvent;
|
||||
const ConnectionPoolClearedEvent = events.ConnectionPoolClearedEvent;
|
||||
|
||||
const kLogger = Symbol('logger');
|
||||
const kConnections = Symbol('connections');
|
||||
const kPermits = Symbol('permits');
|
||||
const kMinPoolSizeTimer = Symbol('minPoolSizeTimer');
|
||||
const kGeneration = Symbol('generation');
|
||||
const kConnectionCounter = Symbol('connectionCounter');
|
||||
const kCancellationToken = Symbol('cancellationToken');
|
||||
const kWaitQueue = Symbol('waitQueue');
|
||||
const kCancelled = Symbol('cancelled');
|
||||
|
||||
const VALID_POOL_OPTIONS = new Set([
|
||||
// `connect` options
|
||||
'ssl',
|
||||
'bson',
|
||||
'connectionType',
|
||||
'monitorCommands',
|
||||
'socketTimeout',
|
||||
'credentials',
|
||||
'compression',
|
||||
|
||||
// node Net options
|
||||
'host',
|
||||
'port',
|
||||
'localAddress',
|
||||
'localPort',
|
||||
'family',
|
||||
'hints',
|
||||
'lookup',
|
||||
'path',
|
||||
|
||||
// node TLS options
|
||||
'ca',
|
||||
'cert',
|
||||
'sigalgs',
|
||||
'ciphers',
|
||||
'clientCertEngine',
|
||||
'crl',
|
||||
'dhparam',
|
||||
'ecdhCurve',
|
||||
'honorCipherOrder',
|
||||
'key',
|
||||
'privateKeyEngine',
|
||||
'privateKeyIdentifier',
|
||||
'maxVersion',
|
||||
'minVersion',
|
||||
'passphrase',
|
||||
'pfx',
|
||||
'secureOptions',
|
||||
'secureProtocol',
|
||||
'sessionIdContext',
|
||||
'allowHalfOpen',
|
||||
'rejectUnauthorized',
|
||||
'pskCallback',
|
||||
'ALPNProtocols',
|
||||
'servername',
|
||||
'checkServerIdentity',
|
||||
'session',
|
||||
'minDHSize',
|
||||
'secureContext',
|
||||
|
||||
// spec options
|
||||
'maxPoolSize',
|
||||
'minPoolSize',
|
||||
'maxIdleTimeMS',
|
||||
'waitQueueTimeoutMS'
|
||||
]);
|
||||
|
||||
function resolveOptions(options, defaults) {
|
||||
const newOptions = Array.from(VALID_POOL_OPTIONS).reduce((obj, key) => {
|
||||
if (options.hasOwnProperty(key)) {
|
||||
obj[key] = options[key];
|
||||
}
|
||||
|
||||
return obj;
|
||||
}, {});
|
||||
|
||||
return Object.freeze(Object.assign({}, defaults, newOptions));
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration options for drivers wrapping the node driver.
|
||||
*
|
||||
* @typedef {Object} ConnectionPoolOptions
|
||||
* @property
|
||||
* @property {string} [host] The host to connect to
|
||||
* @property {number} [port] The port to connect to
|
||||
* @property {bson} [bson] The BSON instance to use for new connections
|
||||
* @property {number} [maxPoolSize=100] The maximum number of connections that may be associated with a pool at a given time. This includes in use and available connections.
|
||||
* @property {number} [minPoolSize=0] The minimum number of connections that MUST exist at any moment in a single connection pool.
|
||||
* @property {number} [maxIdleTimeMS] The maximum amount of time a connection should remain idle in the connection pool before being marked idle.
|
||||
* @property {number} [waitQueueTimeoutMS=0] The maximum amount of time operation execution should wait for a connection to become available. The default is 0 which means there is no limit.
|
||||
*/
|
||||
|
||||
/**
|
||||
* A pool of connections which dynamically resizes, and emit events related to pool activity
|
||||
*
|
||||
* @property {number} generation An integer representing the SDAM generation of the pool
|
||||
* @property {number} totalConnectionCount An integer expressing how many total connections (active + in use) the pool currently has
|
||||
* @property {number} availableConnectionCount An integer expressing how many connections are currently available in the pool.
|
||||
* @property {string} address The address of the endpoint the pool is connected to
|
||||
*
|
||||
* @emits ConnectionPool#connectionPoolCreated
|
||||
* @emits ConnectionPool#connectionPoolClosed
|
||||
* @emits ConnectionPool#connectionCreated
|
||||
* @emits ConnectionPool#connectionReady
|
||||
* @emits ConnectionPool#connectionClosed
|
||||
* @emits ConnectionPool#connectionCheckOutStarted
|
||||
* @emits ConnectionPool#connectionCheckOutFailed
|
||||
* @emits ConnectionPool#connectionCheckedOut
|
||||
* @emits ConnectionPool#connectionCheckedIn
|
||||
* @emits ConnectionPool#connectionPoolCleared
|
||||
*/
|
||||
class ConnectionPool extends EventEmitter {
|
||||
/**
|
||||
* Create a new Connection Pool
|
||||
*
|
||||
* @param {ConnectionPoolOptions} options
|
||||
*/
|
||||
constructor(options) {
|
||||
super();
|
||||
options = options || {};
|
||||
|
||||
this.closed = false;
|
||||
this.options = resolveOptions(options, {
|
||||
connectionType: Connection,
|
||||
maxPoolSize: typeof options.maxPoolSize === 'number' ? options.maxPoolSize : 100,
|
||||
minPoolSize: typeof options.minPoolSize === 'number' ? options.minPoolSize : 0,
|
||||
maxIdleTimeMS: typeof options.maxIdleTimeMS === 'number' ? options.maxIdleTimeMS : 0,
|
||||
waitQueueTimeoutMS:
|
||||
typeof options.waitQueueTimeoutMS === 'number' ? options.waitQueueTimeoutMS : 0,
|
||||
autoEncrypter: options.autoEncrypter,
|
||||
metadata: options.metadata
|
||||
});
|
||||
|
||||
if (options.minSize > options.maxSize) {
|
||||
throw new TypeError(
|
||||
'Connection pool minimum size must not be greater than maxiumum pool size'
|
||||
);
|
||||
}
|
||||
|
||||
this[kLogger] = Logger('ConnectionPool', options);
|
||||
this[kConnections] = new Denque();
|
||||
this[kPermits] = this.options.maxPoolSize;
|
||||
this[kMinPoolSizeTimer] = undefined;
|
||||
this[kGeneration] = 0;
|
||||
this[kConnectionCounter] = makeCounter(1);
|
||||
this[kCancellationToken] = new EventEmitter();
|
||||
this[kCancellationToken].setMaxListeners(Infinity);
|
||||
this[kWaitQueue] = new Denque();
|
||||
|
||||
process.nextTick(() => {
|
||||
this.emit('connectionPoolCreated', new ConnectionPoolCreatedEvent(this));
|
||||
ensureMinPoolSize(this);
|
||||
});
|
||||
}
|
||||
|
||||
get address() {
|
||||
return `${this.options.host}:${this.options.port}`;
|
||||
}
|
||||
|
||||
get generation() {
|
||||
return this[kGeneration];
|
||||
}
|
||||
|
||||
get totalConnectionCount() {
|
||||
return this[kConnections].length + (this.options.maxPoolSize - this[kPermits]);
|
||||
}
|
||||
|
||||
get availableConnectionCount() {
|
||||
return this[kConnections].length;
|
||||
}
|
||||
|
||||
get waitQueueSize() {
|
||||
return this[kWaitQueue].length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check a connection out of this pool. The connection will continue to be tracked, but no reference to it
|
||||
* will be held by the pool. This means that if a connection is checked out it MUST be checked back in or
|
||||
* explicitly destroyed by the new owner.
|
||||
*
|
||||
* @param {ConnectionPool~checkOutCallback} callback
|
||||
*/
|
||||
checkOut(callback) {
|
||||
this.emit('connectionCheckOutStarted', new ConnectionCheckOutStartedEvent(this));
|
||||
|
||||
if (this.closed) {
|
||||
this.emit('connectionCheckOutFailed', new ConnectionCheckOutFailedEvent(this, 'poolClosed'));
|
||||
callback(new PoolClosedError(this));
|
||||
return;
|
||||
}
|
||||
|
||||
const waitQueueMember = { callback };
|
||||
|
||||
const pool = this;
|
||||
const waitQueueTimeoutMS = this.options.waitQueueTimeoutMS;
|
||||
if (waitQueueTimeoutMS) {
|
||||
waitQueueMember.timer = setTimeout(() => {
|
||||
waitQueueMember[kCancelled] = true;
|
||||
waitQueueMember.timer = undefined;
|
||||
|
||||
pool.emit('connectionCheckOutFailed', new ConnectionCheckOutFailedEvent(pool, 'timeout'));
|
||||
waitQueueMember.callback(new WaitQueueTimeoutError(pool));
|
||||
}, waitQueueTimeoutMS);
|
||||
}
|
||||
|
||||
this[kWaitQueue].push(waitQueueMember);
|
||||
setImmediate(() => processWaitQueue(this));
|
||||
}
|
||||
|
||||
/**
|
||||
* Check a connection into the pool.
|
||||
*
|
||||
* @param {Connection} connection The connection to check in
|
||||
*/
|
||||
checkIn(connection) {
|
||||
const poolClosed = this.closed;
|
||||
const stale = connectionIsStale(this, connection);
|
||||
const willDestroy = !!(poolClosed || stale || connection.closed);
|
||||
|
||||
if (!willDestroy) {
|
||||
connection.markAvailable();
|
||||
this[kConnections].push(connection);
|
||||
}
|
||||
|
||||
this.emit('connectionCheckedIn', new ConnectionCheckedInEvent(this, connection));
|
||||
|
||||
if (willDestroy) {
|
||||
const reason = connection.closed ? 'error' : poolClosed ? 'poolClosed' : 'stale';
|
||||
destroyConnection(this, connection, reason);
|
||||
}
|
||||
|
||||
setImmediate(() => processWaitQueue(this));
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear the pool
|
||||
*
|
||||
* Pool reset is handled by incrementing the pool's generation count. Any existing connection of a
|
||||
* previous generation will eventually be pruned during subsequent checkouts.
|
||||
*/
|
||||
clear() {
|
||||
this[kGeneration] += 1;
|
||||
this.emit('connectionPoolCleared', new ConnectionPoolClearedEvent(this));
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the pool
|
||||
*
|
||||
* @param {object} [options] Optional settings
|
||||
* @param {boolean} [options.force] Force close connections
|
||||
* @param {Function} callback
|
||||
*/
|
||||
close(options, callback) {
|
||||
if (typeof options === 'function') {
|
||||
callback = options;
|
||||
}
|
||||
|
||||
options = Object.assign({ force: false }, options);
|
||||
if (this.closed) {
|
||||
return callback();
|
||||
}
|
||||
|
||||
// immediately cancel any in-flight connections
|
||||
this[kCancellationToken].emit('cancel');
|
||||
|
||||
// drain the wait queue
|
||||
while (this.waitQueueSize) {
|
||||
const waitQueueMember = this[kWaitQueue].pop();
|
||||
clearTimeout(waitQueueMember.timer);
|
||||
if (!waitQueueMember[kCancelled]) {
|
||||
waitQueueMember.callback(new MongoError('connection pool closed'));
|
||||
}
|
||||
}
|
||||
|
||||
// clear the min pool size timer
|
||||
if (this[kMinPoolSizeTimer]) {
|
||||
clearTimeout(this[kMinPoolSizeTimer]);
|
||||
}
|
||||
|
||||
// end the connection counter
|
||||
if (typeof this[kConnectionCounter].return === 'function') {
|
||||
this[kConnectionCounter].return();
|
||||
}
|
||||
|
||||
// mark the pool as closed immediately
|
||||
this.closed = true;
|
||||
|
||||
eachAsync(
|
||||
this[kConnections].toArray(),
|
||||
(conn, cb) => {
|
||||
this.emit('connectionClosed', new ConnectionClosedEvent(this, conn, 'poolClosed'));
|
||||
conn.destroy(options, cb);
|
||||
},
|
||||
err => {
|
||||
this[kConnections].clear();
|
||||
this.emit('connectionPoolClosed', new ConnectionPoolClosedEvent(this));
|
||||
callback(err);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a lambda with an implicitly checked out connection, checking that connection back in when the lambda
|
||||
* has completed by calling back.
|
||||
*
|
||||
* NOTE: please note the required signature of `fn`
|
||||
*
|
||||
* @param {ConnectionPool~withConnectionCallback} fn A function which operates on a managed connection
|
||||
* @param {Function} callback The original callback
|
||||
* @return {Promise}
|
||||
*/
|
||||
withConnection(fn, callback) {
|
||||
this.checkOut((err, conn) => {
|
||||
// don't callback with `err` here, we might want to act upon it inside `fn`
|
||||
|
||||
fn(err, conn, (fnErr, result) => {
|
||||
if (typeof callback === 'function') {
|
||||
if (fnErr) {
|
||||
callback(fnErr);
|
||||
} else {
|
||||
callback(undefined, result);
|
||||
}
|
||||
}
|
||||
|
||||
if (conn) {
|
||||
this.checkIn(conn);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function ensureMinPoolSize(pool) {
|
||||
if (pool.closed || pool.options.minPoolSize === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const minPoolSize = pool.options.minPoolSize;
|
||||
for (let i = pool.totalConnectionCount; i < minPoolSize; ++i) {
|
||||
createConnection(pool);
|
||||
}
|
||||
|
||||
pool[kMinPoolSizeTimer] = setTimeout(() => ensureMinPoolSize(pool), 10);
|
||||
}
|
||||
|
||||
function connectionIsStale(pool, connection) {
|
||||
return connection.generation !== pool[kGeneration];
|
||||
}
|
||||
|
||||
function connectionIsIdle(pool, connection) {
|
||||
return !!(pool.options.maxIdleTimeMS && connection.idleTime > pool.options.maxIdleTimeMS);
|
||||
}
|
||||
|
||||
function createConnection(pool, callback) {
|
||||
const connectOptions = Object.assign(
|
||||
{
|
||||
id: pool[kConnectionCounter].next().value,
|
||||
generation: pool[kGeneration]
|
||||
},
|
||||
pool.options
|
||||
);
|
||||
|
||||
pool[kPermits]--;
|
||||
connect(connectOptions, pool[kCancellationToken], (err, connection) => {
|
||||
if (err) {
|
||||
pool[kPermits]++;
|
||||
pool[kLogger].debug(`connection attempt failed with error [${JSON.stringify(err)}]`);
|
||||
if (typeof callback === 'function') {
|
||||
callback(err);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// The pool might have closed since we started trying to create a connection
|
||||
if (pool.closed) {
|
||||
connection.destroy({ force: true });
|
||||
return;
|
||||
}
|
||||
|
||||
// forward all events from the connection to the pool
|
||||
relayEvents(connection, pool, [
|
||||
'commandStarted',
|
||||
'commandFailed',
|
||||
'commandSucceeded',
|
||||
'clusterTimeReceived'
|
||||
]);
|
||||
|
||||
pool.emit('connectionCreated', new ConnectionCreatedEvent(pool, connection));
|
||||
|
||||
connection.markAvailable();
|
||||
pool.emit('connectionReady', new ConnectionReadyEvent(pool, connection));
|
||||
|
||||
// if a callback has been provided, check out the connection immediately
|
||||
if (typeof callback === 'function') {
|
||||
callback(undefined, connection);
|
||||
return;
|
||||
}
|
||||
|
||||
// otherwise add it to the pool for later acquisition, and try to process the wait queue
|
||||
pool[kConnections].push(connection);
|
||||
setImmediate(() => processWaitQueue(pool));
|
||||
});
|
||||
}
|
||||
|
||||
function destroyConnection(pool, connection, reason) {
|
||||
pool.emit('connectionClosed', new ConnectionClosedEvent(pool, connection, reason));
|
||||
|
||||
// allow more connections to be created
|
||||
pool[kPermits]++;
|
||||
|
||||
// destroy the connection
|
||||
setImmediate(() => connection.destroy());
|
||||
}
|
||||
|
||||
function processWaitQueue(pool) {
|
||||
if (pool.closed) {
|
||||
return;
|
||||
}
|
||||
|
||||
while (pool.waitQueueSize) {
|
||||
const waitQueueMember = pool[kWaitQueue].peekFront();
|
||||
if (waitQueueMember[kCancelled]) {
|
||||
pool[kWaitQueue].shift();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!pool.availableConnectionCount) {
|
||||
break;
|
||||
}
|
||||
|
||||
const connection = pool[kConnections].shift();
|
||||
const isStale = connectionIsStale(pool, connection);
|
||||
const isIdle = connectionIsIdle(pool, connection);
|
||||
if (!isStale && !isIdle && !connection.closed) {
|
||||
pool.emit('connectionCheckedOut', new ConnectionCheckedOutEvent(pool, connection));
|
||||
clearTimeout(waitQueueMember.timer);
|
||||
pool[kWaitQueue].shift();
|
||||
waitQueueMember.callback(undefined, connection);
|
||||
return;
|
||||
}
|
||||
|
||||
const reason = connection.closed ? 'error' : isStale ? 'stale' : 'idle';
|
||||
destroyConnection(pool, connection, reason);
|
||||
}
|
||||
|
||||
const maxPoolSize = pool.options.maxPoolSize;
|
||||
if (pool.waitQueueSize && (maxPoolSize <= 0 || pool.totalConnectionCount < maxPoolSize)) {
|
||||
createConnection(pool, (err, connection) => {
|
||||
const waitQueueMember = pool[kWaitQueue].shift();
|
||||
if (waitQueueMember == null) {
|
||||
if (err == null) {
|
||||
pool[kConnections].push(connection);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (waitQueueMember[kCancelled]) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (err) {
|
||||
pool.emit('connectionCheckOutFailed', new ConnectionCheckOutFailedEvent(pool, err));
|
||||
} else {
|
||||
pool.emit('connectionCheckedOut', new ConnectionCheckedOutEvent(pool, connection));
|
||||
}
|
||||
|
||||
clearTimeout(waitQueueMember.timer);
|
||||
waitQueueMember.callback(err, connection);
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A callback provided to `withConnection`
|
||||
*
|
||||
* @callback ConnectionPool~withConnectionCallback
|
||||
* @param {MongoError} error An error instance representing the error during the execution.
|
||||
* @param {Connection} connection The managed connection which was checked out of the pool.
|
||||
* @param {Function} callback A function to call back after connection management is complete
|
||||
*/
|
||||
|
||||
/**
|
||||
* A callback provided to `checkOut`
|
||||
*
|
||||
* @callback ConnectionPool~checkOutCallback
|
||||
* @param {MongoError} error An error instance representing the error during checkout
|
||||
* @param {Connection} connection A connection from the pool
|
||||
*/
|
||||
|
||||
/**
|
||||
* Emitted once when the connection pool is created
|
||||
*
|
||||
* @event ConnectionPool#connectionPoolCreated
|
||||
* @type {PoolCreatedEvent}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Emitted once when the connection pool is closed
|
||||
*
|
||||
* @event ConnectionPool#connectionPoolClosed
|
||||
* @type {PoolClosedEvent}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Emitted each time a connection is created
|
||||
*
|
||||
* @event ConnectionPool#connectionCreated
|
||||
* @type {ConnectionCreatedEvent}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Emitted when a connection becomes established, and is ready to use
|
||||
*
|
||||
* @event ConnectionPool#connectionReady
|
||||
* @type {ConnectionReadyEvent}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Emitted when a connection is closed
|
||||
*
|
||||
* @event ConnectionPool#connectionClosed
|
||||
* @type {ConnectionClosedEvent}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Emitted when an attempt to check out a connection begins
|
||||
*
|
||||
* @event ConnectionPool#connectionCheckOutStarted
|
||||
* @type {ConnectionCheckOutStartedEvent}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Emitted when an attempt to check out a connection fails
|
||||
*
|
||||
* @event ConnectionPool#connectionCheckOutFailed
|
||||
* @type {ConnectionCheckOutFailedEvent}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Emitted each time a connection is successfully checked out of the connection pool
|
||||
*
|
||||
* @event ConnectionPool#connectionCheckedOut
|
||||
* @type {ConnectionCheckedOutEvent}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Emitted each time a connection is successfully checked into the connection pool
|
||||
*
|
||||
* @event ConnectionPool#connectionCheckedIn
|
||||
* @type {ConnectionCheckedInEvent}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Emitted each time the connection pool is cleared and it's generation incremented
|
||||
*
|
||||
* @event ConnectionPool#connectionPoolCleared
|
||||
* @type {PoolClearedEvent}
|
||||
*/
|
||||
|
||||
module.exports = {
|
||||
ConnectionPool
|
||||
};
|
||||
35
node_modules/mongodb/lib/cmap/errors.js
generated
vendored
Normal file
35
node_modules/mongodb/lib/cmap/errors.js
generated
vendored
Normal file
@@ -0,0 +1,35 @@
|
||||
'use strict';
|
||||
const MongoError = require('../core/error').MongoError;
|
||||
|
||||
/**
|
||||
* An error indicating a connection pool is closed
|
||||
*
|
||||
* @property {string} address The address of the connection pool
|
||||
* @extends MongoError
|
||||
*/
|
||||
class PoolClosedError extends MongoError {
|
||||
constructor(pool) {
|
||||
super('Attempted to check out a connection from closed connection pool');
|
||||
this.name = 'MongoPoolClosedError';
|
||||
this.address = pool.address;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An error thrown when a request to check out a connection times out
|
||||
*
|
||||
* @property {string} address The address of the connection pool
|
||||
* @extends MongoError
|
||||
*/
|
||||
class WaitQueueTimeoutError extends MongoError {
|
||||
constructor(pool) {
|
||||
super('Timed out while checking out a connection from connection pool');
|
||||
this.name = 'MongoWaitQueueTimeoutError';
|
||||
this.address = pool.address;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
PoolClosedError,
|
||||
WaitQueueTimeoutError
|
||||
};
|
||||
154
node_modules/mongodb/lib/cmap/events.js
generated
vendored
Normal file
154
node_modules/mongodb/lib/cmap/events.js
generated
vendored
Normal file
@@ -0,0 +1,154 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* The base class for all monitoring events published from the connection pool
|
||||
*
|
||||
* @property {number} time A timestamp when the event was created
|
||||
* @property {string} address The address (host/port pair) of the pool
|
||||
*/
|
||||
class ConnectionPoolMonitoringEvent {
|
||||
constructor(pool) {
|
||||
this.time = new Date();
|
||||
this.address = pool.address;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An event published when a connection pool is created
|
||||
*
|
||||
* @property {Object} options The options used to create this connection pool
|
||||
*/
|
||||
class ConnectionPoolCreatedEvent extends ConnectionPoolMonitoringEvent {
|
||||
constructor(pool) {
|
||||
super(pool);
|
||||
this.options = pool.options;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An event published when a connection pool is closed
|
||||
*/
|
||||
class ConnectionPoolClosedEvent extends ConnectionPoolMonitoringEvent {
|
||||
constructor(pool) {
|
||||
super(pool);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An event published when a connection pool creates a new connection
|
||||
*
|
||||
* @property {number} connectionId A monotonically increasing, per-pool id for the newly created connection
|
||||
*/
|
||||
class ConnectionCreatedEvent extends ConnectionPoolMonitoringEvent {
|
||||
constructor(pool, connection) {
|
||||
super(pool);
|
||||
this.connectionId = connection.id;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An event published when a connection is ready for use
|
||||
*
|
||||
* @property {number} connectionId The id of the connection
|
||||
*/
|
||||
class ConnectionReadyEvent extends ConnectionPoolMonitoringEvent {
|
||||
constructor(pool, connection) {
|
||||
super(pool);
|
||||
this.connectionId = connection.id;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An event published when a connection is closed
|
||||
*
|
||||
* @property {number} connectionId The id of the connection
|
||||
* @property {string} reason The reason the connection was closed
|
||||
*/
|
||||
class ConnectionClosedEvent extends ConnectionPoolMonitoringEvent {
|
||||
constructor(pool, connection, reason) {
|
||||
super(pool);
|
||||
this.connectionId = connection.id;
|
||||
this.reason = reason || 'unknown';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An event published when a request to check a connection out begins
|
||||
*/
|
||||
class ConnectionCheckOutStartedEvent extends ConnectionPoolMonitoringEvent {
|
||||
constructor(pool) {
|
||||
super(pool);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An event published when a request to check a connection out fails
|
||||
*
|
||||
* @property {string} reason The reason the attempt to check out failed
|
||||
*/
|
||||
class ConnectionCheckOutFailedEvent extends ConnectionPoolMonitoringEvent {
|
||||
constructor(pool, reason) {
|
||||
super(pool);
|
||||
this.reason = reason;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An event published when a connection is checked out of the connection pool
|
||||
*
|
||||
* @property {number} connectionId The id of the connection
|
||||
*/
|
||||
class ConnectionCheckedOutEvent extends ConnectionPoolMonitoringEvent {
|
||||
constructor(pool, connection) {
|
||||
super(pool);
|
||||
this.connectionId = connection.id;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An event published when a connection is checked into the connection pool
|
||||
*
|
||||
* @property {number} connectionId The id of the connection
|
||||
*/
|
||||
class ConnectionCheckedInEvent extends ConnectionPoolMonitoringEvent {
|
||||
constructor(pool, connection) {
|
||||
super(pool);
|
||||
this.connectionId = connection.id;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An event published when a connection pool is cleared
|
||||
*/
|
||||
class ConnectionPoolClearedEvent extends ConnectionPoolMonitoringEvent {
|
||||
constructor(pool) {
|
||||
super(pool);
|
||||
}
|
||||
}
|
||||
|
||||
const CMAP_EVENT_NAMES = [
|
||||
'connectionPoolCreated',
|
||||
'connectionPoolClosed',
|
||||
'connectionCreated',
|
||||
'connectionReady',
|
||||
'connectionClosed',
|
||||
'connectionCheckOutStarted',
|
||||
'connectionCheckOutFailed',
|
||||
'connectionCheckedOut',
|
||||
'connectionCheckedIn',
|
||||
'connectionPoolCleared'
|
||||
];
|
||||
|
||||
module.exports = {
|
||||
CMAP_EVENT_NAMES,
|
||||
ConnectionPoolCreatedEvent,
|
||||
ConnectionPoolClosedEvent,
|
||||
ConnectionCreatedEvent,
|
||||
ConnectionReadyEvent,
|
||||
ConnectionClosedEvent,
|
||||
ConnectionCheckOutStartedEvent,
|
||||
ConnectionCheckOutFailedEvent,
|
||||
ConnectionCheckedOutEvent,
|
||||
ConnectionCheckedInEvent,
|
||||
ConnectionPoolClearedEvent
|
||||
};
|
||||
196
node_modules/mongodb/lib/cmap/message_stream.js
generated
vendored
Normal file
196
node_modules/mongodb/lib/cmap/message_stream.js
generated
vendored
Normal file
@@ -0,0 +1,196 @@
|
||||
'use strict';
|
||||
|
||||
const Duplex = require('stream').Duplex;
|
||||
const BufferList = require('bl');
|
||||
const MongoParseError = require('../core/error').MongoParseError;
|
||||
const decompress = require('../core/wireprotocol/compression').decompress;
|
||||
const Response = require('../core/connection/commands').Response;
|
||||
const BinMsg = require('../core/connection/msg').BinMsg;
|
||||
const MongoError = require('../core/error').MongoError;
|
||||
const OP_COMPRESSED = require('../core/wireprotocol/shared').opcodes.OP_COMPRESSED;
|
||||
const OP_MSG = require('../core/wireprotocol/shared').opcodes.OP_MSG;
|
||||
const MESSAGE_HEADER_SIZE = require('../core/wireprotocol/shared').MESSAGE_HEADER_SIZE;
|
||||
const COMPRESSION_DETAILS_SIZE = require('../core/wireprotocol/shared').COMPRESSION_DETAILS_SIZE;
|
||||
const opcodes = require('../core/wireprotocol/shared').opcodes;
|
||||
const compress = require('../core/wireprotocol/compression').compress;
|
||||
const compressorIDs = require('../core/wireprotocol/compression').compressorIDs;
|
||||
const uncompressibleCommands = require('../core/wireprotocol/compression').uncompressibleCommands;
|
||||
const Msg = require('../core/connection/msg').Msg;
|
||||
|
||||
const kDefaultMaxBsonMessageSize = 1024 * 1024 * 16 * 4;
|
||||
const kBuffer = Symbol('buffer');
|
||||
|
||||
/**
|
||||
* A duplex stream that is capable of reading and writing raw wire protocol messages, with
|
||||
* support for optional compression
|
||||
*/
|
||||
class MessageStream extends Duplex {
|
||||
constructor(options) {
|
||||
options = options || {};
|
||||
super(options);
|
||||
|
||||
this.bson = options.bson;
|
||||
this.maxBsonMessageSize = options.maxBsonMessageSize || kDefaultMaxBsonMessageSize;
|
||||
|
||||
this[kBuffer] = new BufferList();
|
||||
}
|
||||
|
||||
_write(chunk, _, callback) {
|
||||
const buffer = this[kBuffer];
|
||||
buffer.append(chunk);
|
||||
|
||||
processIncomingData(this, callback);
|
||||
}
|
||||
|
||||
_read(/* size */) {
|
||||
// NOTE: This implementation is empty because we explicitly push data to be read
|
||||
// when `writeMessage` is called.
|
||||
return;
|
||||
}
|
||||
|
||||
writeCommand(command, operationDescription) {
|
||||
// TODO: agreed compressor should live in `StreamDescription`
|
||||
const shouldCompress = operationDescription && !!operationDescription.agreedCompressor;
|
||||
if (!shouldCompress || !canCompress(command)) {
|
||||
const data = command.toBin();
|
||||
this.push(Array.isArray(data) ? Buffer.concat(data) : data);
|
||||
return;
|
||||
}
|
||||
|
||||
// otherwise, compress the message
|
||||
const concatenatedOriginalCommandBuffer = Buffer.concat(command.toBin());
|
||||
const messageToBeCompressed = concatenatedOriginalCommandBuffer.slice(MESSAGE_HEADER_SIZE);
|
||||
|
||||
// Extract information needed for OP_COMPRESSED from the uncompressed message
|
||||
const originalCommandOpCode = concatenatedOriginalCommandBuffer.readInt32LE(12);
|
||||
|
||||
// Compress the message body
|
||||
compress({ options: operationDescription }, messageToBeCompressed, (err, compressedMessage) => {
|
||||
if (err) {
|
||||
operationDescription.cb(err, null);
|
||||
return;
|
||||
}
|
||||
|
||||
// Create the msgHeader of OP_COMPRESSED
|
||||
const msgHeader = Buffer.alloc(MESSAGE_HEADER_SIZE);
|
||||
msgHeader.writeInt32LE(
|
||||
MESSAGE_HEADER_SIZE + COMPRESSION_DETAILS_SIZE + compressedMessage.length,
|
||||
0
|
||||
); // messageLength
|
||||
msgHeader.writeInt32LE(command.requestId, 4); // requestID
|
||||
msgHeader.writeInt32LE(0, 8); // responseTo (zero)
|
||||
msgHeader.writeInt32LE(opcodes.OP_COMPRESSED, 12); // opCode
|
||||
|
||||
// Create the compression details of OP_COMPRESSED
|
||||
const compressionDetails = Buffer.alloc(COMPRESSION_DETAILS_SIZE);
|
||||
compressionDetails.writeInt32LE(originalCommandOpCode, 0); // originalOpcode
|
||||
compressionDetails.writeInt32LE(messageToBeCompressed.length, 4); // Size of the uncompressed compressedMessage, excluding the MsgHeader
|
||||
compressionDetails.writeUInt8(compressorIDs[operationDescription.agreedCompressor], 8); // compressorID
|
||||
|
||||
this.push(Buffer.concat([msgHeader, compressionDetails, compressedMessage]));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Return whether a command contains an uncompressible command term
|
||||
// Will return true if command contains no uncompressible command terms
|
||||
function canCompress(command) {
|
||||
const commandDoc = command instanceof Msg ? command.command : command.query;
|
||||
const commandName = Object.keys(commandDoc)[0];
|
||||
return !uncompressibleCommands.has(commandName);
|
||||
}
|
||||
|
||||
function processIncomingData(stream, callback) {
|
||||
const buffer = stream[kBuffer];
|
||||
if (buffer.length < 4) {
|
||||
callback();
|
||||
return;
|
||||
}
|
||||
|
||||
const sizeOfMessage = buffer.readInt32LE(0);
|
||||
if (sizeOfMessage < 0) {
|
||||
callback(new MongoParseError(`Invalid message size: ${sizeOfMessage}`));
|
||||
return;
|
||||
}
|
||||
|
||||
if (sizeOfMessage > stream.maxBsonMessageSize) {
|
||||
callback(
|
||||
new MongoParseError(
|
||||
`Invalid message size: ${sizeOfMessage}, max allowed: ${stream.maxBsonMessageSize}`
|
||||
)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (sizeOfMessage > buffer.length) {
|
||||
callback();
|
||||
return;
|
||||
}
|
||||
|
||||
const message = buffer.slice(0, sizeOfMessage);
|
||||
buffer.consume(sizeOfMessage);
|
||||
|
||||
const messageHeader = {
|
||||
length: message.readInt32LE(0),
|
||||
requestId: message.readInt32LE(4),
|
||||
responseTo: message.readInt32LE(8),
|
||||
opCode: message.readInt32LE(12)
|
||||
};
|
||||
|
||||
let ResponseType = messageHeader.opCode === OP_MSG ? BinMsg : Response;
|
||||
const responseOptions = stream.responseOptions;
|
||||
if (messageHeader.opCode !== OP_COMPRESSED) {
|
||||
const messageBody = message.slice(MESSAGE_HEADER_SIZE);
|
||||
stream.emit(
|
||||
'message',
|
||||
new ResponseType(stream.bson, message, messageHeader, messageBody, responseOptions)
|
||||
);
|
||||
|
||||
if (buffer.length >= 4) {
|
||||
processIncomingData(stream, callback);
|
||||
} else {
|
||||
callback();
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
messageHeader.fromCompressed = true;
|
||||
messageHeader.opCode = message.readInt32LE(MESSAGE_HEADER_SIZE);
|
||||
messageHeader.length = message.readInt32LE(MESSAGE_HEADER_SIZE + 4);
|
||||
const compressorID = message[MESSAGE_HEADER_SIZE + 8];
|
||||
const compressedBuffer = message.slice(MESSAGE_HEADER_SIZE + 9);
|
||||
|
||||
// recalculate based on wrapped opcode
|
||||
ResponseType = messageHeader.opCode === OP_MSG ? BinMsg : Response;
|
||||
|
||||
decompress(compressorID, compressedBuffer, (err, messageBody) => {
|
||||
if (err) {
|
||||
callback(err);
|
||||
return;
|
||||
}
|
||||
|
||||
if (messageBody.length !== messageHeader.length) {
|
||||
callback(
|
||||
new MongoError(
|
||||
'Decompressing a compressed message from the server failed. The message is corrupt.'
|
||||
)
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
stream.emit(
|
||||
'message',
|
||||
new ResponseType(stream.bson, message, messageHeader, messageBody, responseOptions)
|
||||
);
|
||||
|
||||
if (buffer.length >= 4) {
|
||||
processIncomingData(stream, callback);
|
||||
} else {
|
||||
callback();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = MessageStream;
|
||||
45
node_modules/mongodb/lib/cmap/stream_description.js
generated
vendored
Normal file
45
node_modules/mongodb/lib/cmap/stream_description.js
generated
vendored
Normal file
@@ -0,0 +1,45 @@
|
||||
'use strict';
|
||||
const parseServerType = require('../core/sdam/server_description').parseServerType;
|
||||
|
||||
const RESPONSE_FIELDS = [
|
||||
'minWireVersion',
|
||||
'maxWireVersion',
|
||||
'maxBsonObjectSize',
|
||||
'maxMessageSizeBytes',
|
||||
'maxWriteBatchSize',
|
||||
'__nodejs_mock_server__'
|
||||
];
|
||||
|
||||
class StreamDescription {
|
||||
constructor(address, options) {
|
||||
this.address = address;
|
||||
this.type = parseServerType(null);
|
||||
this.minWireVersion = undefined;
|
||||
this.maxWireVersion = undefined;
|
||||
this.maxBsonObjectSize = 16777216;
|
||||
this.maxMessageSizeBytes = 48000000;
|
||||
this.maxWriteBatchSize = 100000;
|
||||
this.compressors =
|
||||
options && options.compression && Array.isArray(options.compression.compressors)
|
||||
? options.compression.compressors
|
||||
: [];
|
||||
}
|
||||
|
||||
receiveResponse(response) {
|
||||
this.type = parseServerType(response);
|
||||
|
||||
RESPONSE_FIELDS.forEach(field => {
|
||||
if (typeof response[field] !== 'undefined') {
|
||||
this[field] = response[field];
|
||||
}
|
||||
});
|
||||
|
||||
if (response.compression) {
|
||||
this.compressor = this.compressors.filter(c => response.compression.indexOf(c) !== -1)[0];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
StreamDescription
|
||||
};
|
||||
2178
node_modules/mongodb/lib/collection.js
generated
vendored
Normal file
2178
node_modules/mongodb/lib/collection.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
269
node_modules/mongodb/lib/command_cursor.js
generated
vendored
Normal file
269
node_modules/mongodb/lib/command_cursor.js
generated
vendored
Normal file
@@ -0,0 +1,269 @@
|
||||
'use strict';
|
||||
|
||||
const ReadPreference = require('./core').ReadPreference;
|
||||
const MongoError = require('./core').MongoError;
|
||||
const Cursor = require('./cursor');
|
||||
const CursorState = require('./core/cursor').CursorState;
|
||||
|
||||
/**
|
||||
* @fileOverview The **CommandCursor** class is an internal class that embodies a
|
||||
* generalized cursor based on a MongoDB command allowing for iteration over the
|
||||
* results returned. It supports one by one document iteration, conversion to an
|
||||
* array or can be iterated as a Node 0.10.X or higher stream
|
||||
*
|
||||
* **CommandCursor Cannot directly be instantiated**
|
||||
* @example
|
||||
* const MongoClient = require('mongodb').MongoClient;
|
||||
* const test = require('assert');
|
||||
* // Connection url
|
||||
* const url = 'mongodb://localhost:27017';
|
||||
* // Database Name
|
||||
* const dbName = 'test';
|
||||
* // Connect using MongoClient
|
||||
* MongoClient.connect(url, function(err, client) {
|
||||
* // Create a collection we want to drop later
|
||||
* const col = client.db(dbName).collection('listCollectionsExample1');
|
||||
* // Insert a bunch of documents
|
||||
* col.insert([{a:1, b:1}
|
||||
* , {a:2, b:2}, {a:3, b:3}
|
||||
* , {a:4, b:4}], {w:1}, function(err, result) {
|
||||
* test.equal(null, err);
|
||||
* // List the database collections available
|
||||
* db.listCollections().toArray(function(err, items) {
|
||||
* test.equal(null, err);
|
||||
* client.close();
|
||||
* });
|
||||
* });
|
||||
* });
|
||||
*/
|
||||
|
||||
/**
|
||||
* Namespace provided by the browser.
|
||||
* @external Readable
|
||||
*/
|
||||
|
||||
/**
|
||||
* Creates a new Command Cursor instance (INTERNAL TYPE, do not instantiate directly)
|
||||
* @class CommandCursor
|
||||
* @extends external:Readable
|
||||
* @fires CommandCursor#data
|
||||
* @fires CommandCursor#end
|
||||
* @fires CommandCursor#close
|
||||
* @fires CommandCursor#readable
|
||||
* @return {CommandCursor} an CommandCursor instance.
|
||||
*/
|
||||
class CommandCursor extends Cursor {
|
||||
constructor(topology, ns, cmd, options) {
|
||||
super(topology, ns, cmd, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the ReadPreference for the cursor.
|
||||
* @method
|
||||
* @param {(string|ReadPreference)} readPreference The new read preference for the cursor.
|
||||
* @throws {MongoError}
|
||||
* @return {Cursor}
|
||||
*/
|
||||
setReadPreference(readPreference) {
|
||||
if (this.s.state === CursorState.CLOSED || this.isDead()) {
|
||||
throw MongoError.create({ message: 'Cursor is closed', driver: true });
|
||||
}
|
||||
|
||||
if (this.s.state !== CursorState.INIT) {
|
||||
throw MongoError.create({
|
||||
message: 'cannot change cursor readPreference after cursor has been accessed',
|
||||
driver: true
|
||||
});
|
||||
}
|
||||
|
||||
if (readPreference instanceof ReadPreference) {
|
||||
this.options.readPreference = readPreference;
|
||||
} else if (typeof readPreference === 'string') {
|
||||
this.options.readPreference = new ReadPreference(readPreference);
|
||||
} else {
|
||||
throw new TypeError('Invalid read preference: ' + readPreference);
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the batch size for the cursor.
|
||||
* @method
|
||||
* @param {number} value The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/|find command documentation}.
|
||||
* @throws {MongoError}
|
||||
* @return {CommandCursor}
|
||||
*/
|
||||
batchSize(value) {
|
||||
if (this.s.state === CursorState.CLOSED || this.isDead()) {
|
||||
throw MongoError.create({ message: 'Cursor is closed', driver: true });
|
||||
}
|
||||
|
||||
if (typeof value !== 'number') {
|
||||
throw MongoError.create({ message: 'batchSize requires an integer', driver: true });
|
||||
}
|
||||
|
||||
if (this.cmd.cursor) {
|
||||
this.cmd.cursor.batchSize = value;
|
||||
}
|
||||
|
||||
this.setCursorBatchSize(value);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a maxTimeMS stage to the aggregation pipeline
|
||||
* @method
|
||||
* @param {number} value The state maxTimeMS value.
|
||||
* @return {CommandCursor}
|
||||
*/
|
||||
maxTimeMS(value) {
|
||||
if (this.topology.lastIsMaster().minWireVersion > 2) {
|
||||
this.cmd.maxTimeMS = value;
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the cursor logger
|
||||
* @method
|
||||
* @return {Logger} return the cursor logger
|
||||
* @ignore
|
||||
*/
|
||||
getLogger() {
|
||||
return this.logger;
|
||||
}
|
||||
}
|
||||
|
||||
// aliases
|
||||
CommandCursor.prototype.get = CommandCursor.prototype.toArray;
|
||||
|
||||
/**
|
||||
* CommandCursor stream data event, fired for each document in the cursor.
|
||||
*
|
||||
* @event CommandCursor#data
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* CommandCursor stream end event
|
||||
*
|
||||
* @event CommandCursor#end
|
||||
* @type {null}
|
||||
*/
|
||||
|
||||
/**
|
||||
* CommandCursor stream close event
|
||||
*
|
||||
* @event CommandCursor#close
|
||||
* @type {null}
|
||||
*/
|
||||
|
||||
/**
|
||||
* CommandCursor stream readable event
|
||||
*
|
||||
* @event CommandCursor#readable
|
||||
* @type {null}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Get the next available document from the cursor, returns null if no more documents are available.
|
||||
* @function CommandCursor.prototype.next
|
||||
* @param {CommandCursor~resultCallback} [callback] The result callback.
|
||||
* @throws {MongoError}
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
|
||||
/**
|
||||
* Check if there is any document still available in the cursor
|
||||
* @function CommandCursor.prototype.hasNext
|
||||
* @param {CommandCursor~resultCallback} [callback] The result callback.
|
||||
* @throws {MongoError}
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
|
||||
/**
|
||||
* The callback format for results
|
||||
* @callback CommandCursor~toArrayResultCallback
|
||||
* @param {MongoError} error An error instance representing the error during the execution.
|
||||
* @param {object[]} documents All the documents the satisfy the cursor.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Returns an array of documents. The caller is responsible for making sure that there
|
||||
* is enough memory to store the results. Note that the array only contain partial
|
||||
* results when this cursor had been previously accessed.
|
||||
* @method CommandCursor.prototype.toArray
|
||||
* @param {CommandCursor~toArrayResultCallback} [callback] The result callback.
|
||||
* @throws {MongoError}
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
|
||||
/**
|
||||
* The callback format for results
|
||||
* @callback CommandCursor~resultCallback
|
||||
* @param {MongoError} error An error instance representing the error during the execution.
|
||||
* @param {(object|null)} result The result object if the command was executed successfully.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Iterates over all the documents for this cursor. As with **{cursor.toArray}**,
|
||||
* not all of the elements will be iterated if this cursor had been previously accessed.
|
||||
* In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike
|
||||
* **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements
|
||||
* at any given time if batch size is specified. Otherwise, the caller is responsible
|
||||
* for making sure that the entire result can fit the memory.
|
||||
* @method CommandCursor.prototype.each
|
||||
* @param {CommandCursor~resultCallback} callback The result callback.
|
||||
* @throws {MongoError}
|
||||
* @return {null}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Close the cursor, sending a KillCursor command and emitting close.
|
||||
* @method CommandCursor.prototype.close
|
||||
* @param {CommandCursor~resultCallback} [callback] The result callback.
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
|
||||
/**
|
||||
* Is the cursor closed
|
||||
* @method CommandCursor.prototype.isClosed
|
||||
* @return {boolean}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Clone the cursor
|
||||
* @function CommandCursor.prototype.clone
|
||||
* @return {CommandCursor}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Resets the cursor
|
||||
* @function CommandCursor.prototype.rewind
|
||||
* @return {CommandCursor}
|
||||
*/
|
||||
|
||||
/**
|
||||
* The callback format for the forEach iterator method
|
||||
* @callback CommandCursor~iteratorCallback
|
||||
* @param {Object} doc An emitted document for the iterator
|
||||
*/
|
||||
|
||||
/**
|
||||
* The callback error format for the forEach iterator method
|
||||
* @callback CommandCursor~endCallback
|
||||
* @param {MongoError} error An error instance representing the error during the execution.
|
||||
*/
|
||||
|
||||
/*
|
||||
* Iterates over all the documents for this cursor using the iterator, callback pattern.
|
||||
* @method CommandCursor.prototype.forEach
|
||||
* @param {CommandCursor~iteratorCallback} iterator The iteration callback.
|
||||
* @param {CommandCursor~endCallback} callback The end callback.
|
||||
* @throws {MongoError}
|
||||
* @return {null}
|
||||
*/
|
||||
|
||||
module.exports = CommandCursor;
|
||||
10
node_modules/mongodb/lib/constants.js
generated
vendored
Normal file
10
node_modules/mongodb/lib/constants.js
generated
vendored
Normal file
@@ -0,0 +1,10 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = {
|
||||
SYSTEM_NAMESPACE_COLLECTION: 'system.namespaces',
|
||||
SYSTEM_INDEX_COLLECTION: 'system.indexes',
|
||||
SYSTEM_PROFILE_COLLECTION: 'system.profile',
|
||||
SYSTEM_USER_COLLECTION: 'system.users',
|
||||
SYSTEM_COMMAND_COLLECTION: '$cmd',
|
||||
SYSTEM_JS_COLLECTION: 'system.js'
|
||||
};
|
||||
55
node_modules/mongodb/lib/core/auth/auth_provider.js
generated
vendored
Normal file
55
node_modules/mongodb/lib/core/auth/auth_provider.js
generated
vendored
Normal file
@@ -0,0 +1,55 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Context used during authentication
|
||||
*
|
||||
* @property {Connection} connection The connection to authenticate
|
||||
* @property {MongoCredentials} credentials The credentials to use for authentication
|
||||
* @property {object} options The options passed to the `connect` method
|
||||
* @property {object?} response The response of the initial handshake
|
||||
* @property {Buffer?} nonce A random nonce generated for use in an authentication conversation
|
||||
*/
|
||||
class AuthContext {
|
||||
constructor(connection, credentials, options) {
|
||||
this.connection = connection;
|
||||
this.credentials = credentials;
|
||||
this.options = options;
|
||||
}
|
||||
}
|
||||
|
||||
class AuthProvider {
|
||||
constructor(bson) {
|
||||
this.bson = bson;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare the handshake document before the initial handshake.
|
||||
*
|
||||
* @param {object} handshakeDoc The document used for the initial handshake on a connection
|
||||
* @param {AuthContext} authContext Context for authentication flow
|
||||
* @param {function} callback
|
||||
*/
|
||||
prepare(handshakeDoc, context, callback) {
|
||||
callback(undefined, handshakeDoc);
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticate
|
||||
*
|
||||
* @param {AuthContext} context A shared context for authentication flow
|
||||
* @param {authResultCallback} callback The callback to return the result from the authentication
|
||||
*/
|
||||
auth(context, callback) {
|
||||
callback(new TypeError('`auth` method must be overridden by subclass'));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This is a result from an authentication provider
|
||||
*
|
||||
* @callback authResultCallback
|
||||
* @param {error} error An error object. Set to null if no error present
|
||||
* @param {boolean} result The result of the authentication process
|
||||
*/
|
||||
|
||||
module.exports = { AuthContext, AuthProvider };
|
||||
29
node_modules/mongodb/lib/core/auth/defaultAuthProviders.js
generated
vendored
Normal file
29
node_modules/mongodb/lib/core/auth/defaultAuthProviders.js
generated
vendored
Normal file
@@ -0,0 +1,29 @@
|
||||
'use strict';
|
||||
|
||||
const MongoCR = require('./mongocr');
|
||||
const X509 = require('./x509');
|
||||
const Plain = require('./plain');
|
||||
const GSSAPI = require('./gssapi');
|
||||
const ScramSHA1 = require('./scram').ScramSHA1;
|
||||
const ScramSHA256 = require('./scram').ScramSHA256;
|
||||
const MongoDBAWS = require('./mongodb_aws');
|
||||
|
||||
/**
|
||||
* Returns the default authentication providers.
|
||||
*
|
||||
* @param {BSON} bson Bson definition
|
||||
* @returns {Object} a mapping of auth names to auth types
|
||||
*/
|
||||
function defaultAuthProviders(bson) {
|
||||
return {
|
||||
'mongodb-aws': new MongoDBAWS(bson),
|
||||
mongocr: new MongoCR(bson),
|
||||
x509: new X509(bson),
|
||||
plain: new Plain(bson),
|
||||
gssapi: new GSSAPI(bson),
|
||||
'scram-sha-1': new ScramSHA1(bson),
|
||||
'scram-sha-256': new ScramSHA256(bson)
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { defaultAuthProviders };
|
||||
151
node_modules/mongodb/lib/core/auth/gssapi.js
generated
vendored
Normal file
151
node_modules/mongodb/lib/core/auth/gssapi.js
generated
vendored
Normal file
@@ -0,0 +1,151 @@
|
||||
'use strict';
|
||||
const dns = require('dns');
|
||||
|
||||
const AuthProvider = require('./auth_provider').AuthProvider;
|
||||
const retrieveKerberos = require('../utils').retrieveKerberos;
|
||||
const MongoError = require('../error').MongoError;
|
||||
|
||||
const kGssapiClient = Symbol('GSSAPI_CLIENT');
|
||||
let kerberos;
|
||||
|
||||
class GSSAPI extends AuthProvider {
|
||||
prepare(handshakeDoc, authContext, callback) {
|
||||
const host = authContext.options.host;
|
||||
const port = authContext.options.port;
|
||||
const credentials = authContext.credentials;
|
||||
if (!host || !port || !credentials) {
|
||||
return callback(
|
||||
new MongoError(
|
||||
`Connection must specify: ${host ? 'host' : ''}, ${port ? 'port' : ''}, ${
|
||||
credentials ? 'host' : 'credentials'
|
||||
}.`
|
||||
)
|
||||
);
|
||||
}
|
||||
if (kerberos == null) {
|
||||
try {
|
||||
kerberos = retrieveKerberos();
|
||||
} catch (e) {
|
||||
return callback(e);
|
||||
}
|
||||
}
|
||||
const username = credentials.username;
|
||||
const password = credentials.password;
|
||||
const mechanismProperties = credentials.mechanismProperties;
|
||||
const serviceName =
|
||||
mechanismProperties['gssapiservicename'] ||
|
||||
mechanismProperties['gssapiServiceName'] ||
|
||||
'mongodb';
|
||||
performGssapiCanonicalizeHostName(host, mechanismProperties, (err, host) => {
|
||||
if (err) return callback(err);
|
||||
const initOptions = {};
|
||||
if (password != null) {
|
||||
Object.assign(initOptions, { user: username, password: password });
|
||||
}
|
||||
kerberos.initializeClient(
|
||||
`${serviceName}${process.platform === 'win32' ? '/' : '@'}${host}`,
|
||||
initOptions,
|
||||
(err, client) => {
|
||||
if (err) return callback(new MongoError(err));
|
||||
if (client == null) return callback();
|
||||
this[kGssapiClient] = client;
|
||||
callback(undefined, handshakeDoc);
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
auth(authContext, callback) {
|
||||
const connection = authContext.connection;
|
||||
const credentials = authContext.credentials;
|
||||
if (credentials == null) return callback(new MongoError('credentials required'));
|
||||
const username = credentials.username;
|
||||
const client = this[kGssapiClient];
|
||||
if (client == null) return callback(new MongoError('gssapi client missing'));
|
||||
function externalCommand(command, cb) {
|
||||
return connection.command('$external.$cmd', command, cb);
|
||||
}
|
||||
client.step('', (err, payload) => {
|
||||
if (err) return callback(err);
|
||||
externalCommand(saslStart(payload), (err, response) => {
|
||||
const result = response.result;
|
||||
if (err) return callback(err);
|
||||
negotiate(client, 10, result.payload, (err, payload) => {
|
||||
if (err) return callback(err);
|
||||
externalCommand(saslContinue(payload, result.conversationId), (err, response) => {
|
||||
const result = response.result;
|
||||
if (err) return callback(err);
|
||||
finalize(client, username, result.payload, (err, payload) => {
|
||||
if (err) return callback(err);
|
||||
externalCommand(
|
||||
{
|
||||
saslContinue: 1,
|
||||
conversationId: result.conversationId,
|
||||
payload
|
||||
},
|
||||
(err, result) => {
|
||||
if (err) return callback(err);
|
||||
callback(undefined, result);
|
||||
}
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
module.exports = GSSAPI;
|
||||
|
||||
function saslStart(payload) {
|
||||
return {
|
||||
saslStart: 1,
|
||||
mechanism: 'GSSAPI',
|
||||
payload,
|
||||
autoAuthorize: 1
|
||||
};
|
||||
}
|
||||
function saslContinue(payload, conversationId) {
|
||||
return {
|
||||
saslContinue: 1,
|
||||
conversationId,
|
||||
payload
|
||||
};
|
||||
}
|
||||
function negotiate(client, retries, payload, callback) {
|
||||
client.step(payload, (err, response) => {
|
||||
// Retries exhausted, raise error
|
||||
if (err && retries === 0) return callback(err);
|
||||
// Adjust number of retries and call step again
|
||||
if (err) return negotiate(client, retries - 1, payload, callback);
|
||||
// Return the payload
|
||||
callback(undefined, response || '');
|
||||
});
|
||||
}
|
||||
function finalize(client, user, payload, callback) {
|
||||
// GSS Client Unwrap
|
||||
client.unwrap(payload, (err, response) => {
|
||||
if (err) return callback(err);
|
||||
// Wrap the response
|
||||
client.wrap(response || '', { user }, (err, wrapped) => {
|
||||
if (err) return callback(err);
|
||||
// Return the payload
|
||||
callback(undefined, wrapped);
|
||||
});
|
||||
});
|
||||
}
|
||||
function performGssapiCanonicalizeHostName(host, mechanismProperties, callback) {
|
||||
const canonicalizeHostName =
|
||||
typeof mechanismProperties.gssapiCanonicalizeHostName === 'boolean'
|
||||
? mechanismProperties.gssapiCanonicalizeHostName
|
||||
: false;
|
||||
if (!canonicalizeHostName) return callback(undefined, host);
|
||||
// Attempt to resolve the host name
|
||||
dns.resolveCname(host, (err, r) => {
|
||||
if (err) return callback(err);
|
||||
// Get the first resolve host id
|
||||
if (Array.isArray(r) && r.length > 0) {
|
||||
return callback(undefined, r[0]);
|
||||
}
|
||||
callback(undefined, host);
|
||||
});
|
||||
}
|
||||
107
node_modules/mongodb/lib/core/auth/mongo_credentials.js
generated
vendored
Normal file
107
node_modules/mongodb/lib/core/auth/mongo_credentials.js
generated
vendored
Normal file
@@ -0,0 +1,107 @@
|
||||
'use strict';
|
||||
|
||||
// Resolves the default auth mechanism according to
|
||||
// https://github.com/mongodb/specifications/blob/master/source/auth/auth.rst
|
||||
function getDefaultAuthMechanism(ismaster) {
|
||||
if (ismaster) {
|
||||
// If ismaster contains saslSupportedMechs, use scram-sha-256
|
||||
// if it is available, else scram-sha-1
|
||||
if (Array.isArray(ismaster.saslSupportedMechs)) {
|
||||
return ismaster.saslSupportedMechs.indexOf('SCRAM-SHA-256') >= 0
|
||||
? 'scram-sha-256'
|
||||
: 'scram-sha-1';
|
||||
}
|
||||
|
||||
// Fallback to legacy selection method. If wire version >= 3, use scram-sha-1
|
||||
if (ismaster.maxWireVersion >= 3) {
|
||||
return 'scram-sha-1';
|
||||
}
|
||||
}
|
||||
|
||||
// Default for wireprotocol < 3
|
||||
return 'mongocr';
|
||||
}
|
||||
|
||||
/**
|
||||
* A representation of the credentials used by MongoDB
|
||||
* @class
|
||||
* @property {string} mechanism The method used to authenticate
|
||||
* @property {string} [username] The username used for authentication
|
||||
* @property {string} [password] The password used for authentication
|
||||
* @property {string} [source] The database that the user should authenticate against
|
||||
* @property {object} [mechanismProperties] Special properties used by some types of auth mechanisms
|
||||
*/
|
||||
class MongoCredentials {
|
||||
/**
|
||||
* Creates a new MongoCredentials object
|
||||
* @param {object} [options]
|
||||
* @param {string} [options.username] The username used for authentication
|
||||
* @param {string} [options.password] The password used for authentication
|
||||
* @param {string} [options.source] The database that the user should authenticate against
|
||||
* @param {string} [options.mechanism] The method used to authenticate
|
||||
* @param {object} [options.mechanismProperties] Special properties used by some types of auth mechanisms
|
||||
*/
|
||||
constructor(options) {
|
||||
options = options || {};
|
||||
this.username = options.username;
|
||||
this.password = options.password;
|
||||
this.source = options.source || options.db;
|
||||
this.mechanism = options.mechanism || 'default';
|
||||
this.mechanismProperties = options.mechanismProperties || {};
|
||||
|
||||
if (this.mechanism.match(/MONGODB-AWS/i)) {
|
||||
if (this.username == null && process.env.AWS_ACCESS_KEY_ID) {
|
||||
this.username = process.env.AWS_ACCESS_KEY_ID;
|
||||
}
|
||||
|
||||
if (this.password == null && process.env.AWS_SECRET_ACCESS_KEY) {
|
||||
this.password = process.env.AWS_SECRET_ACCESS_KEY;
|
||||
}
|
||||
|
||||
if (this.mechanismProperties.AWS_SESSION_TOKEN == null && process.env.AWS_SESSION_TOKEN) {
|
||||
this.mechanismProperties.AWS_SESSION_TOKEN = process.env.AWS_SESSION_TOKEN;
|
||||
}
|
||||
}
|
||||
|
||||
Object.freeze(this.mechanismProperties);
|
||||
Object.freeze(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if two MongoCredentials objects are equivalent
|
||||
* @param {MongoCredentials} other another MongoCredentials object
|
||||
* @returns {boolean} true if the two objects are equal.
|
||||
*/
|
||||
equals(other) {
|
||||
return (
|
||||
this.mechanism === other.mechanism &&
|
||||
this.username === other.username &&
|
||||
this.password === other.password &&
|
||||
this.source === other.source
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* If the authentication mechanism is set to "default", resolves the authMechanism
|
||||
* based on the server version and server supported sasl mechanisms.
|
||||
*
|
||||
* @param {Object} [ismaster] An ismaster response from the server
|
||||
* @returns {MongoCredentials}
|
||||
*/
|
||||
resolveAuthMechanism(ismaster) {
|
||||
// If the mechanism is not "default", then it does not need to be resolved
|
||||
if (this.mechanism.match(/DEFAULT/i)) {
|
||||
return new MongoCredentials({
|
||||
username: this.username,
|
||||
password: this.password,
|
||||
source: this.source,
|
||||
mechanism: getDefaultAuthMechanism(ismaster),
|
||||
mechanismProperties: this.mechanismProperties
|
||||
});
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { MongoCredentials };
|
||||
45
node_modules/mongodb/lib/core/auth/mongocr.js
generated
vendored
Normal file
45
node_modules/mongodb/lib/core/auth/mongocr.js
generated
vendored
Normal file
@@ -0,0 +1,45 @@
|
||||
'use strict';
|
||||
|
||||
const crypto = require('crypto');
|
||||
const AuthProvider = require('./auth_provider').AuthProvider;
|
||||
|
||||
class MongoCR extends AuthProvider {
|
||||
auth(authContext, callback) {
|
||||
const connection = authContext.connection;
|
||||
const credentials = authContext.credentials;
|
||||
const username = credentials.username;
|
||||
const password = credentials.password;
|
||||
const source = credentials.source;
|
||||
|
||||
connection.command(`${source}.$cmd`, { getnonce: 1 }, (err, result) => {
|
||||
let nonce = null;
|
||||
let key = null;
|
||||
|
||||
// Get nonce
|
||||
if (err == null) {
|
||||
const r = result.result;
|
||||
nonce = r.nonce;
|
||||
// Use node md5 generator
|
||||
let md5 = crypto.createHash('md5');
|
||||
// Generate keys used for authentication
|
||||
md5.update(username + ':mongo:' + password, 'utf8');
|
||||
const hash_password = md5.digest('hex');
|
||||
// Final key
|
||||
md5 = crypto.createHash('md5');
|
||||
md5.update(nonce + username + hash_password, 'utf8');
|
||||
key = md5.digest('hex');
|
||||
}
|
||||
|
||||
const authenticateCommand = {
|
||||
authenticate: 1,
|
||||
user: username,
|
||||
nonce,
|
||||
key
|
||||
};
|
||||
|
||||
connection.command(`${source}.$cmd`, authenticateCommand, callback);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = MongoCR;
|
||||
256
node_modules/mongodb/lib/core/auth/mongodb_aws.js
generated
vendored
Normal file
256
node_modules/mongodb/lib/core/auth/mongodb_aws.js
generated
vendored
Normal file
@@ -0,0 +1,256 @@
|
||||
'use strict';
|
||||
const AuthProvider = require('./auth_provider').AuthProvider;
|
||||
const MongoCredentials = require('./mongo_credentials').MongoCredentials;
|
||||
const MongoError = require('../error').MongoError;
|
||||
const crypto = require('crypto');
|
||||
const http = require('http');
|
||||
const maxWireVersion = require('../utils').maxWireVersion;
|
||||
const url = require('url');
|
||||
|
||||
let aws4;
|
||||
try {
|
||||
aws4 = require('aws4');
|
||||
} catch (e) {
|
||||
// don't do anything;
|
||||
}
|
||||
|
||||
const ASCII_N = 110;
|
||||
const AWS_RELATIVE_URI = 'http://169.254.170.2';
|
||||
const AWS_EC2_URI = 'http://169.254.169.254';
|
||||
const AWS_EC2_PATH = '/latest/meta-data/iam/security-credentials';
|
||||
|
||||
class MongoDBAWS extends AuthProvider {
|
||||
auth(authContext, callback) {
|
||||
const connection = authContext.connection;
|
||||
const credentials = authContext.credentials;
|
||||
|
||||
if (maxWireVersion(connection) < 9) {
|
||||
callback(new MongoError('MONGODB-AWS authentication requires MongoDB version 4.4 or later'));
|
||||
return;
|
||||
}
|
||||
|
||||
if (aws4 == null) {
|
||||
callback(
|
||||
new MongoError(
|
||||
'MONGODB-AWS authentication requires the `aws4` module, please install it as a dependency of your project'
|
||||
)
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (credentials.username == null) {
|
||||
makeTempCredentials(credentials, (err, tempCredentials) => {
|
||||
if (err) return callback(err);
|
||||
|
||||
authContext.credentials = tempCredentials;
|
||||
this.auth(authContext, callback);
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const username = credentials.username;
|
||||
const password = credentials.password;
|
||||
const db = credentials.source;
|
||||
const token = credentials.mechanismProperties.AWS_SESSION_TOKEN;
|
||||
const bson = this.bson;
|
||||
|
||||
crypto.randomBytes(32, (err, nonce) => {
|
||||
if (err) {
|
||||
callback(err);
|
||||
return;
|
||||
}
|
||||
|
||||
const saslStart = {
|
||||
saslStart: 1,
|
||||
mechanism: 'MONGODB-AWS',
|
||||
payload: bson.serialize({ r: nonce, p: ASCII_N })
|
||||
};
|
||||
|
||||
connection.command(`${db}.$cmd`, saslStart, (err, result) => {
|
||||
if (err) return callback(err);
|
||||
|
||||
const res = result.result;
|
||||
const serverResponse = bson.deserialize(res.payload.buffer);
|
||||
const host = serverResponse.h;
|
||||
const serverNonce = serverResponse.s.buffer;
|
||||
if (serverNonce.length !== 64) {
|
||||
callback(
|
||||
new MongoError(`Invalid server nonce length ${serverNonce.length}, expected 64`)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (serverNonce.compare(nonce, 0, nonce.length, 0, nonce.length) !== 0) {
|
||||
callback(new MongoError('Server nonce does not begin with client nonce'));
|
||||
return;
|
||||
}
|
||||
|
||||
if (host.length < 1 || host.length > 255 || host.indexOf('..') !== -1) {
|
||||
callback(new MongoError(`Server returned an invalid host: "${host}"`));
|
||||
return;
|
||||
}
|
||||
|
||||
const body = 'Action=GetCallerIdentity&Version=2011-06-15';
|
||||
const options = aws4.sign(
|
||||
{
|
||||
method: 'POST',
|
||||
host,
|
||||
region: deriveRegion(serverResponse.h),
|
||||
service: 'sts',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'Content-Length': body.length,
|
||||
'X-MongoDB-Server-Nonce': serverNonce.toString('base64'),
|
||||
'X-MongoDB-GS2-CB-Flag': 'n'
|
||||
},
|
||||
path: '/',
|
||||
body
|
||||
},
|
||||
{
|
||||
accessKeyId: username,
|
||||
secretAccessKey: password,
|
||||
token
|
||||
}
|
||||
);
|
||||
|
||||
const authorization = options.headers.Authorization;
|
||||
const date = options.headers['X-Amz-Date'];
|
||||
const payload = { a: authorization, d: date };
|
||||
if (token) {
|
||||
payload.t = token;
|
||||
}
|
||||
|
||||
const saslContinue = {
|
||||
saslContinue: 1,
|
||||
conversationId: 1,
|
||||
payload: bson.serialize(payload)
|
||||
};
|
||||
|
||||
connection.command(`${db}.$cmd`, saslContinue, err => {
|
||||
if (err) return callback(err);
|
||||
callback();
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function makeTempCredentials(credentials, callback) {
|
||||
function done(creds) {
|
||||
if (creds.AccessKeyId == null || creds.SecretAccessKey == null || creds.Token == null) {
|
||||
callback(new MongoError('Could not obtain temporary MONGODB-AWS credentials'));
|
||||
return;
|
||||
}
|
||||
|
||||
callback(
|
||||
undefined,
|
||||
new MongoCredentials({
|
||||
username: creds.AccessKeyId,
|
||||
password: creds.SecretAccessKey,
|
||||
source: credentials.source,
|
||||
mechanism: 'MONGODB-AWS',
|
||||
mechanismProperties: {
|
||||
AWS_SESSION_TOKEN: creds.Token
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
// If the environment variable AWS_CONTAINER_CREDENTIALS_RELATIVE_URI
|
||||
// is set then drivers MUST assume that it was set by an AWS ECS agent
|
||||
if (process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI) {
|
||||
request(
|
||||
`${AWS_RELATIVE_URI}${process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI}`,
|
||||
(err, res) => {
|
||||
if (err) return callback(err);
|
||||
done(res);
|
||||
}
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Otherwise assume we are on an EC2 instance
|
||||
|
||||
// get a token
|
||||
|
||||
request(
|
||||
`${AWS_EC2_URI}/latest/api/token`,
|
||||
{ method: 'PUT', json: false, headers: { 'X-aws-ec2-metadata-token-ttl-seconds': 30 } },
|
||||
(err, token) => {
|
||||
if (err) return callback(err);
|
||||
|
||||
// get role name
|
||||
request(
|
||||
`${AWS_EC2_URI}/${AWS_EC2_PATH}`,
|
||||
{ json: false, headers: { 'X-aws-ec2-metadata-token': token } },
|
||||
(err, roleName) => {
|
||||
if (err) return callback(err);
|
||||
|
||||
// get temp credentials
|
||||
request(
|
||||
`${AWS_EC2_URI}/${AWS_EC2_PATH}/${roleName}`,
|
||||
{ headers: { 'X-aws-ec2-metadata-token': token } },
|
||||
(err, creds) => {
|
||||
if (err) return callback(err);
|
||||
done(creds);
|
||||
}
|
||||
);
|
||||
}
|
||||
);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
function deriveRegion(host) {
|
||||
const parts = host.split('.');
|
||||
if (parts.length === 1 || parts[1] === 'amazonaws') {
|
||||
return 'us-east-1';
|
||||
}
|
||||
|
||||
return parts[1];
|
||||
}
|
||||
|
||||
function request(uri, options, callback) {
|
||||
if (typeof options === 'function') {
|
||||
callback = options;
|
||||
options = {};
|
||||
}
|
||||
|
||||
options = Object.assign(
|
||||
{
|
||||
method: 'GET',
|
||||
timeout: 10000,
|
||||
json: true
|
||||
},
|
||||
url.parse(uri),
|
||||
options
|
||||
);
|
||||
|
||||
const req = http.request(options, res => {
|
||||
res.setEncoding('utf8');
|
||||
|
||||
let data = '';
|
||||
res.on('data', d => (data += d));
|
||||
res.on('end', () => {
|
||||
if (options.json === false) {
|
||||
callback(undefined, data);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(data);
|
||||
callback(undefined, parsed);
|
||||
} catch (err) {
|
||||
callback(new MongoError(`Invalid JSON response: "${data}"`));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
req.on('error', err => callback(err));
|
||||
req.end();
|
||||
}
|
||||
|
||||
module.exports = MongoDBAWS;
|
||||
28
node_modules/mongodb/lib/core/auth/plain.js
generated
vendored
Normal file
28
node_modules/mongodb/lib/core/auth/plain.js
generated
vendored
Normal file
@@ -0,0 +1,28 @@
|
||||
'use strict';
|
||||
const retrieveBSON = require('../connection/utils').retrieveBSON;
|
||||
const AuthProvider = require('./auth_provider').AuthProvider;
|
||||
|
||||
// TODO: can we get the Binary type from this.bson instead?
|
||||
const BSON = retrieveBSON();
|
||||
const Binary = BSON.Binary;
|
||||
|
||||
class Plain extends AuthProvider {
|
||||
auth(authContext, callback) {
|
||||
const connection = authContext.connection;
|
||||
const credentials = authContext.credentials;
|
||||
const username = credentials.username;
|
||||
const password = credentials.password;
|
||||
|
||||
const payload = new Binary(`\x00${username}\x00${password}`);
|
||||
const command = {
|
||||
saslStart: 1,
|
||||
mechanism: 'PLAIN',
|
||||
payload: payload,
|
||||
autoAuthorize: 1
|
||||
};
|
||||
|
||||
connection.command('$external.$cmd', command, callback);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Plain;
|
||||
346
node_modules/mongodb/lib/core/auth/scram.js
generated
vendored
Normal file
346
node_modules/mongodb/lib/core/auth/scram.js
generated
vendored
Normal file
@@ -0,0 +1,346 @@
|
||||
'use strict';
|
||||
const crypto = require('crypto');
|
||||
const Buffer = require('safe-buffer').Buffer;
|
||||
const retrieveBSON = require('../connection/utils').retrieveBSON;
|
||||
const MongoError = require('../error').MongoError;
|
||||
const AuthProvider = require('./auth_provider').AuthProvider;
|
||||
|
||||
const BSON = retrieveBSON();
|
||||
const Binary = BSON.Binary;
|
||||
|
||||
let saslprep;
|
||||
try {
|
||||
saslprep = require('saslprep');
|
||||
} catch (e) {
|
||||
// don't do anything;
|
||||
}
|
||||
|
||||
class ScramSHA extends AuthProvider {
|
||||
constructor(bson, cryptoMethod) {
|
||||
super(bson);
|
||||
this.cryptoMethod = cryptoMethod || 'sha1';
|
||||
}
|
||||
|
||||
prepare(handshakeDoc, authContext, callback) {
|
||||
const cryptoMethod = this.cryptoMethod;
|
||||
if (cryptoMethod === 'sha256' && saslprep == null) {
|
||||
console.warn('Warning: no saslprep library specified. Passwords will not be sanitized');
|
||||
}
|
||||
|
||||
crypto.randomBytes(24, (err, nonce) => {
|
||||
if (err) {
|
||||
return callback(err);
|
||||
}
|
||||
|
||||
// store the nonce for later use
|
||||
Object.assign(authContext, { nonce });
|
||||
|
||||
const credentials = authContext.credentials;
|
||||
const request = Object.assign({}, handshakeDoc, {
|
||||
speculativeAuthenticate: Object.assign(makeFirstMessage(cryptoMethod, credentials, nonce), {
|
||||
db: credentials.source
|
||||
})
|
||||
});
|
||||
|
||||
callback(undefined, request);
|
||||
});
|
||||
}
|
||||
|
||||
auth(authContext, callback) {
|
||||
const response = authContext.response;
|
||||
if (response && response.speculativeAuthenticate) {
|
||||
continueScramConversation(
|
||||
this.cryptoMethod,
|
||||
response.speculativeAuthenticate,
|
||||
authContext,
|
||||
callback
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
executeScram(this.cryptoMethod, authContext, callback);
|
||||
}
|
||||
}
|
||||
|
||||
function cleanUsername(username) {
|
||||
return username.replace('=', '=3D').replace(',', '=2C');
|
||||
}
|
||||
|
||||
function clientFirstMessageBare(username, nonce) {
|
||||
// NOTE: This is done b/c Javascript uses UTF-16, but the server is hashing in UTF-8.
|
||||
// Since the username is not sasl-prep-d, we need to do this here.
|
||||
return Buffer.concat([
|
||||
Buffer.from('n=', 'utf8'),
|
||||
Buffer.from(username, 'utf8'),
|
||||
Buffer.from(',r=', 'utf8'),
|
||||
Buffer.from(nonce.toString('base64'), 'utf8')
|
||||
]);
|
||||
}
|
||||
|
||||
function makeFirstMessage(cryptoMethod, credentials, nonce) {
|
||||
const username = cleanUsername(credentials.username);
|
||||
const mechanism = cryptoMethod === 'sha1' ? 'SCRAM-SHA-1' : 'SCRAM-SHA-256';
|
||||
|
||||
// NOTE: This is done b/c Javascript uses UTF-16, but the server is hashing in UTF-8.
|
||||
// Since the username is not sasl-prep-d, we need to do this here.
|
||||
return {
|
||||
saslStart: 1,
|
||||
mechanism,
|
||||
payload: new Binary(
|
||||
Buffer.concat([Buffer.from('n,,', 'utf8'), clientFirstMessageBare(username, nonce)])
|
||||
),
|
||||
autoAuthorize: 1,
|
||||
options: { skipEmptyExchange: true }
|
||||
};
|
||||
}
|
||||
|
||||
function executeScram(cryptoMethod, authContext, callback) {
|
||||
const connection = authContext.connection;
|
||||
const credentials = authContext.credentials;
|
||||
const nonce = authContext.nonce;
|
||||
const db = credentials.source;
|
||||
|
||||
const saslStartCmd = makeFirstMessage(cryptoMethod, credentials, nonce);
|
||||
connection.command(`${db}.$cmd`, saslStartCmd, (_err, result) => {
|
||||
const err = resolveError(_err, result);
|
||||
if (err) {
|
||||
return callback(err);
|
||||
}
|
||||
|
||||
continueScramConversation(cryptoMethod, result.result, authContext, callback);
|
||||
});
|
||||
}
|
||||
|
||||
function continueScramConversation(cryptoMethod, response, authContext, callback) {
|
||||
const connection = authContext.connection;
|
||||
const credentials = authContext.credentials;
|
||||
const nonce = authContext.nonce;
|
||||
|
||||
const db = credentials.source;
|
||||
const username = cleanUsername(credentials.username);
|
||||
const password = credentials.password;
|
||||
|
||||
let processedPassword;
|
||||
if (cryptoMethod === 'sha256') {
|
||||
processedPassword = saslprep ? saslprep(password) : password;
|
||||
} else {
|
||||
try {
|
||||
processedPassword = passwordDigest(username, password);
|
||||
} catch (e) {
|
||||
return callback(e);
|
||||
}
|
||||
}
|
||||
|
||||
const payload = Buffer.isBuffer(response.payload)
|
||||
? new Binary(response.payload)
|
||||
: response.payload;
|
||||
const dict = parsePayload(payload.value());
|
||||
|
||||
const iterations = parseInt(dict.i, 10);
|
||||
if (iterations && iterations < 4096) {
|
||||
callback(new MongoError(`Server returned an invalid iteration count ${iterations}`), false);
|
||||
return;
|
||||
}
|
||||
|
||||
const salt = dict.s;
|
||||
const rnonce = dict.r;
|
||||
if (rnonce.startsWith('nonce')) {
|
||||
callback(new MongoError(`Server returned an invalid nonce: ${rnonce}`), false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Set up start of proof
|
||||
const withoutProof = `c=biws,r=${rnonce}`;
|
||||
const saltedPassword = HI(
|
||||
processedPassword,
|
||||
Buffer.from(salt, 'base64'),
|
||||
iterations,
|
||||
cryptoMethod
|
||||
);
|
||||
|
||||
const clientKey = HMAC(cryptoMethod, saltedPassword, 'Client Key');
|
||||
const serverKey = HMAC(cryptoMethod, saltedPassword, 'Server Key');
|
||||
const storedKey = H(cryptoMethod, clientKey);
|
||||
const authMessage = [
|
||||
clientFirstMessageBare(username, nonce),
|
||||
payload.value().toString('base64'),
|
||||
withoutProof
|
||||
].join(',');
|
||||
|
||||
const clientSignature = HMAC(cryptoMethod, storedKey, authMessage);
|
||||
const clientProof = `p=${xor(clientKey, clientSignature)}`;
|
||||
const clientFinal = [withoutProof, clientProof].join(',');
|
||||
|
||||
const serverSignature = HMAC(cryptoMethod, serverKey, authMessage);
|
||||
const saslContinueCmd = {
|
||||
saslContinue: 1,
|
||||
conversationId: response.conversationId,
|
||||
payload: new Binary(Buffer.from(clientFinal))
|
||||
};
|
||||
|
||||
connection.command(`${db}.$cmd`, saslContinueCmd, (_err, result) => {
|
||||
const err = resolveError(_err, result);
|
||||
if (err) {
|
||||
return callback(err);
|
||||
}
|
||||
|
||||
const r = result.result;
|
||||
const parsedResponse = parsePayload(r.payload.value());
|
||||
if (!compareDigest(Buffer.from(parsedResponse.v, 'base64'), serverSignature)) {
|
||||
callback(new MongoError('Server returned an invalid signature'));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!r || r.done !== false) {
|
||||
return callback(err, r);
|
||||
}
|
||||
|
||||
const retrySaslContinueCmd = {
|
||||
saslContinue: 1,
|
||||
conversationId: r.conversationId,
|
||||
payload: Buffer.alloc(0)
|
||||
};
|
||||
|
||||
connection.command(`${db}.$cmd`, retrySaslContinueCmd, callback);
|
||||
});
|
||||
}
|
||||
|
||||
function parsePayload(payload) {
|
||||
const dict = {};
|
||||
const parts = payload.split(',');
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
const valueParts = parts[i].split('=');
|
||||
dict[valueParts[0]] = valueParts[1];
|
||||
}
|
||||
|
||||
return dict;
|
||||
}
|
||||
|
||||
function passwordDigest(username, password) {
|
||||
if (typeof username !== 'string') {
|
||||
throw new MongoError('username must be a string');
|
||||
}
|
||||
|
||||
if (typeof password !== 'string') {
|
||||
throw new MongoError('password must be a string');
|
||||
}
|
||||
|
||||
if (password.length === 0) {
|
||||
throw new MongoError('password cannot be empty');
|
||||
}
|
||||
|
||||
const md5 = crypto.createHash('md5');
|
||||
md5.update(`${username}:mongo:${password}`, 'utf8');
|
||||
return md5.digest('hex');
|
||||
}
|
||||
|
||||
// XOR two buffers
|
||||
function xor(a, b) {
|
||||
if (!Buffer.isBuffer(a)) {
|
||||
a = Buffer.from(a);
|
||||
}
|
||||
|
||||
if (!Buffer.isBuffer(b)) {
|
||||
b = Buffer.from(b);
|
||||
}
|
||||
|
||||
const length = Math.max(a.length, b.length);
|
||||
const res = [];
|
||||
|
||||
for (let i = 0; i < length; i += 1) {
|
||||
res.push(a[i] ^ b[i]);
|
||||
}
|
||||
|
||||
return Buffer.from(res).toString('base64');
|
||||
}
|
||||
|
||||
function H(method, text) {
|
||||
return crypto
|
||||
.createHash(method)
|
||||
.update(text)
|
||||
.digest();
|
||||
}
|
||||
|
||||
function HMAC(method, key, text) {
|
||||
return crypto
|
||||
.createHmac(method, key)
|
||||
.update(text)
|
||||
.digest();
|
||||
}
|
||||
|
||||
let _hiCache = {};
|
||||
let _hiCacheCount = 0;
|
||||
function _hiCachePurge() {
|
||||
_hiCache = {};
|
||||
_hiCacheCount = 0;
|
||||
}
|
||||
|
||||
const hiLengthMap = {
|
||||
sha256: 32,
|
||||
sha1: 20
|
||||
};
|
||||
|
||||
function HI(data, salt, iterations, cryptoMethod) {
|
||||
// omit the work if already generated
|
||||
const key = [data, salt.toString('base64'), iterations].join('_');
|
||||
if (_hiCache[key] !== undefined) {
|
||||
return _hiCache[key];
|
||||
}
|
||||
|
||||
// generate the salt
|
||||
const saltedData = crypto.pbkdf2Sync(
|
||||
data,
|
||||
salt,
|
||||
iterations,
|
||||
hiLengthMap[cryptoMethod],
|
||||
cryptoMethod
|
||||
);
|
||||
|
||||
// cache a copy to speed up the next lookup, but prevent unbounded cache growth
|
||||
if (_hiCacheCount >= 200) {
|
||||
_hiCachePurge();
|
||||
}
|
||||
|
||||
_hiCache[key] = saltedData;
|
||||
_hiCacheCount += 1;
|
||||
return saltedData;
|
||||
}
|
||||
|
||||
function compareDigest(lhs, rhs) {
|
||||
if (lhs.length !== rhs.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (typeof crypto.timingSafeEqual === 'function') {
|
||||
return crypto.timingSafeEqual(lhs, rhs);
|
||||
}
|
||||
|
||||
let result = 0;
|
||||
for (let i = 0; i < lhs.length; i++) {
|
||||
result |= lhs[i] ^ rhs[i];
|
||||
}
|
||||
|
||||
return result === 0;
|
||||
}
|
||||
|
||||
function resolveError(err, result) {
|
||||
if (err) return err;
|
||||
|
||||
const r = result.result;
|
||||
if (r.$err || r.errmsg) return new MongoError(r);
|
||||
}
|
||||
|
||||
class ScramSHA1 extends ScramSHA {
|
||||
constructor(bson) {
|
||||
super(bson, 'sha1');
|
||||
}
|
||||
}
|
||||
|
||||
class ScramSHA256 extends ScramSHA {
|
||||
constructor(bson) {
|
||||
super(bson, 'sha256');
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { ScramSHA1, ScramSHA256 };
|
||||
35
node_modules/mongodb/lib/core/auth/x509.js
generated
vendored
Normal file
35
node_modules/mongodb/lib/core/auth/x509.js
generated
vendored
Normal file
@@ -0,0 +1,35 @@
|
||||
'use strict';
|
||||
const AuthProvider = require('./auth_provider').AuthProvider;
|
||||
|
||||
class X509 extends AuthProvider {
|
||||
prepare(handshakeDoc, authContext, callback) {
|
||||
const credentials = authContext.credentials;
|
||||
Object.assign(handshakeDoc, {
|
||||
speculativeAuthenticate: x509AuthenticateCommand(credentials)
|
||||
});
|
||||
|
||||
callback(undefined, handshakeDoc);
|
||||
}
|
||||
|
||||
auth(authContext, callback) {
|
||||
const connection = authContext.connection;
|
||||
const credentials = authContext.credentials;
|
||||
const response = authContext.response;
|
||||
if (response.speculativeAuthenticate) {
|
||||
return callback();
|
||||
}
|
||||
|
||||
connection.command('$external.$cmd', x509AuthenticateCommand(credentials), callback);
|
||||
}
|
||||
}
|
||||
|
||||
function x509AuthenticateCommand(credentials) {
|
||||
const command = { authenticate: 1, mechanism: 'MONGODB-X509' };
|
||||
if (credentials.username) {
|
||||
Object.apply(command, { user: credentials.username });
|
||||
}
|
||||
|
||||
return command;
|
||||
}
|
||||
|
||||
module.exports = X509;
|
||||
251
node_modules/mongodb/lib/core/connection/apm.js
generated
vendored
Normal file
251
node_modules/mongodb/lib/core/connection/apm.js
generated
vendored
Normal file
@@ -0,0 +1,251 @@
|
||||
'use strict';
|
||||
const Msg = require('../connection/msg').Msg;
|
||||
const KillCursor = require('../connection/commands').KillCursor;
|
||||
const GetMore = require('../connection/commands').GetMore;
|
||||
const calculateDurationInMs = require('../../utils').calculateDurationInMs;
|
||||
|
||||
/** Commands that we want to redact because of the sensitive nature of their contents */
|
||||
const SENSITIVE_COMMANDS = new Set([
|
||||
'authenticate',
|
||||
'saslStart',
|
||||
'saslContinue',
|
||||
'getnonce',
|
||||
'createUser',
|
||||
'updateUser',
|
||||
'copydbgetnonce',
|
||||
'copydbsaslstart',
|
||||
'copydb'
|
||||
]);
|
||||
|
||||
// helper methods
|
||||
const extractCommandName = commandDoc => Object.keys(commandDoc)[0];
|
||||
const namespace = command => command.ns;
|
||||
const databaseName = command => command.ns.split('.')[0];
|
||||
const collectionName = command => command.ns.split('.')[1];
|
||||
const generateConnectionId = pool =>
|
||||
pool.options ? `${pool.options.host}:${pool.options.port}` : pool.address;
|
||||
const maybeRedact = (commandName, result) => (SENSITIVE_COMMANDS.has(commandName) ? {} : result);
|
||||
const isLegacyPool = pool => pool.s && pool.queue;
|
||||
|
||||
const LEGACY_FIND_QUERY_MAP = {
|
||||
$query: 'filter',
|
||||
$orderby: 'sort',
|
||||
$hint: 'hint',
|
||||
$comment: 'comment',
|
||||
$maxScan: 'maxScan',
|
||||
$max: 'max',
|
||||
$min: 'min',
|
||||
$returnKey: 'returnKey',
|
||||
$showDiskLoc: 'showRecordId',
|
||||
$maxTimeMS: 'maxTimeMS',
|
||||
$snapshot: 'snapshot'
|
||||
};
|
||||
|
||||
const LEGACY_FIND_OPTIONS_MAP = {
|
||||
numberToSkip: 'skip',
|
||||
numberToReturn: 'batchSize',
|
||||
returnFieldsSelector: 'projection'
|
||||
};
|
||||
|
||||
const OP_QUERY_KEYS = [
|
||||
'tailable',
|
||||
'oplogReplay',
|
||||
'noCursorTimeout',
|
||||
'awaitData',
|
||||
'partial',
|
||||
'exhaust'
|
||||
];
|
||||
|
||||
/**
|
||||
* Extract the actual command from the query, possibly upconverting if it's a legacy
|
||||
* format
|
||||
*
|
||||
* @param {Object} command the command
|
||||
*/
|
||||
const extractCommand = command => {
|
||||
if (command instanceof GetMore) {
|
||||
return {
|
||||
getMore: command.cursorId,
|
||||
collection: collectionName(command),
|
||||
batchSize: command.numberToReturn
|
||||
};
|
||||
}
|
||||
|
||||
if (command instanceof KillCursor) {
|
||||
return {
|
||||
killCursors: collectionName(command),
|
||||
cursors: command.cursorIds
|
||||
};
|
||||
}
|
||||
|
||||
if (command instanceof Msg) {
|
||||
return command.command;
|
||||
}
|
||||
|
||||
if (command.query && command.query.$query) {
|
||||
let result;
|
||||
if (command.ns === 'admin.$cmd') {
|
||||
// upconvert legacy command
|
||||
result = Object.assign({}, command.query.$query);
|
||||
} else {
|
||||
// upconvert legacy find command
|
||||
result = { find: collectionName(command) };
|
||||
Object.keys(LEGACY_FIND_QUERY_MAP).forEach(key => {
|
||||
if (typeof command.query[key] !== 'undefined')
|
||||
result[LEGACY_FIND_QUERY_MAP[key]] = command.query[key];
|
||||
});
|
||||
}
|
||||
|
||||
Object.keys(LEGACY_FIND_OPTIONS_MAP).forEach(key => {
|
||||
if (typeof command[key] !== 'undefined') result[LEGACY_FIND_OPTIONS_MAP[key]] = command[key];
|
||||
});
|
||||
|
||||
OP_QUERY_KEYS.forEach(key => {
|
||||
if (command[key]) result[key] = command[key];
|
||||
});
|
||||
|
||||
if (typeof command.pre32Limit !== 'undefined') {
|
||||
result.limit = command.pre32Limit;
|
||||
}
|
||||
|
||||
if (command.query.$explain) {
|
||||
return { explain: result };
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
return command.query ? command.query : command;
|
||||
};
|
||||
|
||||
const extractReply = (command, reply) => {
|
||||
if (command instanceof GetMore) {
|
||||
return {
|
||||
ok: 1,
|
||||
cursor: {
|
||||
id: reply.message.cursorId,
|
||||
ns: namespace(command),
|
||||
nextBatch: reply.message.documents
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
if (command instanceof KillCursor) {
|
||||
return {
|
||||
ok: 1,
|
||||
cursorsUnknown: command.cursorIds
|
||||
};
|
||||
}
|
||||
|
||||
// is this a legacy find command?
|
||||
if (command.query && typeof command.query.$query !== 'undefined') {
|
||||
return {
|
||||
ok: 1,
|
||||
cursor: {
|
||||
id: reply.message.cursorId,
|
||||
ns: namespace(command),
|
||||
firstBatch: reply.message.documents
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return reply && reply.result ? reply.result : reply;
|
||||
};
|
||||
|
||||
const extractConnectionDetails = pool => {
|
||||
if (isLegacyPool(pool)) {
|
||||
return {
|
||||
connectionId: generateConnectionId(pool)
|
||||
};
|
||||
}
|
||||
|
||||
// APM in the modern pool is done at the `Connection` level, so we rename it here for
|
||||
// readability.
|
||||
const connection = pool;
|
||||
return {
|
||||
address: connection.address,
|
||||
connectionId: connection.id
|
||||
};
|
||||
};
|
||||
|
||||
/** An event indicating the start of a given command */
|
||||
class CommandStartedEvent {
|
||||
/**
|
||||
* Create a started event
|
||||
*
|
||||
* @param {Pool} pool the pool that originated the command
|
||||
* @param {Object} command the command
|
||||
*/
|
||||
constructor(pool, command) {
|
||||
const cmd = extractCommand(command);
|
||||
const commandName = extractCommandName(cmd);
|
||||
const connectionDetails = extractConnectionDetails(pool);
|
||||
|
||||
// NOTE: remove in major revision, this is not spec behavior
|
||||
if (SENSITIVE_COMMANDS.has(commandName)) {
|
||||
this.commandObj = {};
|
||||
this.commandObj[commandName] = true;
|
||||
}
|
||||
|
||||
Object.assign(this, connectionDetails, {
|
||||
requestId: command.requestId,
|
||||
databaseName: databaseName(command),
|
||||
commandName,
|
||||
command: cmd
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** An event indicating the success of a given command */
|
||||
class CommandSucceededEvent {
|
||||
/**
|
||||
* Create a succeeded event
|
||||
*
|
||||
* @param {Pool} pool the pool that originated the command
|
||||
* @param {Object} command the command
|
||||
* @param {Object} reply the reply for this command from the server
|
||||
* @param {Array} started a high resolution tuple timestamp of when the command was first sent, to calculate duration
|
||||
*/
|
||||
constructor(pool, command, reply, started) {
|
||||
const cmd = extractCommand(command);
|
||||
const commandName = extractCommandName(cmd);
|
||||
const connectionDetails = extractConnectionDetails(pool);
|
||||
|
||||
Object.assign(this, connectionDetails, {
|
||||
requestId: command.requestId,
|
||||
commandName,
|
||||
duration: calculateDurationInMs(started),
|
||||
reply: maybeRedact(commandName, extractReply(command, reply))
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** An event indicating the failure of a given command */
|
||||
class CommandFailedEvent {
|
||||
/**
|
||||
* Create a failure event
|
||||
*
|
||||
* @param {Pool} pool the pool that originated the command
|
||||
* @param {Object} command the command
|
||||
* @param {MongoError|Object} error the generated error or a server error response
|
||||
* @param {Array} started a high resolution tuple timestamp of when the command was first sent, to calculate duration
|
||||
*/
|
||||
constructor(pool, command, error, started) {
|
||||
const cmd = extractCommand(command);
|
||||
const commandName = extractCommandName(cmd);
|
||||
const connectionDetails = extractConnectionDetails(pool);
|
||||
|
||||
Object.assign(this, connectionDetails, {
|
||||
requestId: command.requestId,
|
||||
commandName,
|
||||
duration: calculateDurationInMs(started),
|
||||
failure: maybeRedact(commandName, error)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
CommandStartedEvent,
|
||||
CommandSucceededEvent,
|
||||
CommandFailedEvent
|
||||
};
|
||||
36
node_modules/mongodb/lib/core/connection/command_result.js
generated
vendored
Normal file
36
node_modules/mongodb/lib/core/connection/command_result.js
generated
vendored
Normal file
@@ -0,0 +1,36 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Creates a new CommandResult instance
|
||||
* @class
|
||||
* @param {object} result CommandResult object
|
||||
* @param {Connection} connection A connection instance associated with this result
|
||||
* @return {CommandResult} A cursor instance
|
||||
*/
|
||||
var CommandResult = function(result, connection, message) {
|
||||
this.result = result;
|
||||
this.connection = connection;
|
||||
this.message = message;
|
||||
};
|
||||
|
||||
/**
|
||||
* Convert CommandResult to JSON
|
||||
* @method
|
||||
* @return {object}
|
||||
*/
|
||||
CommandResult.prototype.toJSON = function() {
|
||||
let result = Object.assign({}, this, this.result);
|
||||
delete result.message;
|
||||
return result;
|
||||
};
|
||||
|
||||
/**
|
||||
* Convert CommandResult to String representation
|
||||
* @method
|
||||
* @return {string}
|
||||
*/
|
||||
CommandResult.prototype.toString = function() {
|
||||
return JSON.stringify(this.toJSON());
|
||||
};
|
||||
|
||||
module.exports = CommandResult;
|
||||
507
node_modules/mongodb/lib/core/connection/commands.js
generated
vendored
Normal file
507
node_modules/mongodb/lib/core/connection/commands.js
generated
vendored
Normal file
@@ -0,0 +1,507 @@
|
||||
'use strict';
|
||||
|
||||
var retrieveBSON = require('./utils').retrieveBSON;
|
||||
var BSON = retrieveBSON();
|
||||
var Long = BSON.Long;
|
||||
const Buffer = require('safe-buffer').Buffer;
|
||||
|
||||
// Incrementing request id
|
||||
var _requestId = 0;
|
||||
|
||||
// Wire command operation ids
|
||||
var opcodes = require('../wireprotocol/shared').opcodes;
|
||||
|
||||
// Query flags
|
||||
var OPTS_TAILABLE_CURSOR = 2;
|
||||
var OPTS_SLAVE = 4;
|
||||
var OPTS_OPLOG_REPLAY = 8;
|
||||
var OPTS_NO_CURSOR_TIMEOUT = 16;
|
||||
var OPTS_AWAIT_DATA = 32;
|
||||
var OPTS_EXHAUST = 64;
|
||||
var OPTS_PARTIAL = 128;
|
||||
|
||||
// Response flags
|
||||
var CURSOR_NOT_FOUND = 1;
|
||||
var QUERY_FAILURE = 2;
|
||||
var SHARD_CONFIG_STALE = 4;
|
||||
var AWAIT_CAPABLE = 8;
|
||||
|
||||
/**************************************************************
|
||||
* QUERY
|
||||
**************************************************************/
|
||||
var Query = function(bson, ns, query, options) {
|
||||
var self = this;
|
||||
// Basic options needed to be passed in
|
||||
if (ns == null) throw new Error('ns must be specified for query');
|
||||
if (query == null) throw new Error('query must be specified for query');
|
||||
|
||||
// Validate that we are not passing 0x00 in the collection name
|
||||
if (ns.indexOf('\x00') !== -1) {
|
||||
throw new Error('namespace cannot contain a null character');
|
||||
}
|
||||
|
||||
// Basic options
|
||||
this.bson = bson;
|
||||
this.ns = ns;
|
||||
this.query = query;
|
||||
|
||||
// Additional options
|
||||
this.numberToSkip = options.numberToSkip || 0;
|
||||
this.numberToReturn = options.numberToReturn || 0;
|
||||
this.returnFieldSelector = options.returnFieldSelector || null;
|
||||
this.requestId = Query.getRequestId();
|
||||
|
||||
// special case for pre-3.2 find commands, delete ASAP
|
||||
this.pre32Limit = options.pre32Limit;
|
||||
|
||||
// Serialization option
|
||||
this.serializeFunctions =
|
||||
typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
|
||||
this.ignoreUndefined =
|
||||
typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false;
|
||||
this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16;
|
||||
this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : true;
|
||||
this.batchSize = self.numberToReturn;
|
||||
|
||||
// Flags
|
||||
this.tailable = false;
|
||||
this.slaveOk = typeof options.slaveOk === 'boolean' ? options.slaveOk : false;
|
||||
this.oplogReplay = false;
|
||||
this.noCursorTimeout = false;
|
||||
this.awaitData = false;
|
||||
this.exhaust = false;
|
||||
this.partial = false;
|
||||
};
|
||||
|
||||
//
|
||||
// Assign a new request Id
|
||||
Query.prototype.incRequestId = function() {
|
||||
this.requestId = _requestId++;
|
||||
};
|
||||
|
||||
//
|
||||
// Assign a new request Id
|
||||
Query.nextRequestId = function() {
|
||||
return _requestId + 1;
|
||||
};
|
||||
|
||||
//
|
||||
// Uses a single allocated buffer for the process, avoiding multiple memory allocations
|
||||
Query.prototype.toBin = function() {
|
||||
var self = this;
|
||||
var buffers = [];
|
||||
var projection = null;
|
||||
|
||||
// Set up the flags
|
||||
var flags = 0;
|
||||
if (this.tailable) {
|
||||
flags |= OPTS_TAILABLE_CURSOR;
|
||||
}
|
||||
|
||||
if (this.slaveOk) {
|
||||
flags |= OPTS_SLAVE;
|
||||
}
|
||||
|
||||
if (this.oplogReplay) {
|
||||
flags |= OPTS_OPLOG_REPLAY;
|
||||
}
|
||||
|
||||
if (this.noCursorTimeout) {
|
||||
flags |= OPTS_NO_CURSOR_TIMEOUT;
|
||||
}
|
||||
|
||||
if (this.awaitData) {
|
||||
flags |= OPTS_AWAIT_DATA;
|
||||
}
|
||||
|
||||
if (this.exhaust) {
|
||||
flags |= OPTS_EXHAUST;
|
||||
}
|
||||
|
||||
if (this.partial) {
|
||||
flags |= OPTS_PARTIAL;
|
||||
}
|
||||
|
||||
// If batchSize is different to self.numberToReturn
|
||||
if (self.batchSize !== self.numberToReturn) self.numberToReturn = self.batchSize;
|
||||
|
||||
// Allocate write protocol header buffer
|
||||
var header = Buffer.alloc(
|
||||
4 * 4 + // Header
|
||||
4 + // Flags
|
||||
Buffer.byteLength(self.ns) +
|
||||
1 + // namespace
|
||||
4 + // numberToSkip
|
||||
4 // numberToReturn
|
||||
);
|
||||
|
||||
// Add header to buffers
|
||||
buffers.push(header);
|
||||
|
||||
// Serialize the query
|
||||
var query = self.bson.serialize(this.query, {
|
||||
checkKeys: this.checkKeys,
|
||||
serializeFunctions: this.serializeFunctions,
|
||||
ignoreUndefined: this.ignoreUndefined
|
||||
});
|
||||
|
||||
// Add query document
|
||||
buffers.push(query);
|
||||
|
||||
if (self.returnFieldSelector && Object.keys(self.returnFieldSelector).length > 0) {
|
||||
// Serialize the projection document
|
||||
projection = self.bson.serialize(this.returnFieldSelector, {
|
||||
checkKeys: this.checkKeys,
|
||||
serializeFunctions: this.serializeFunctions,
|
||||
ignoreUndefined: this.ignoreUndefined
|
||||
});
|
||||
// Add projection document
|
||||
buffers.push(projection);
|
||||
}
|
||||
|
||||
// Total message size
|
||||
var totalLength = header.length + query.length + (projection ? projection.length : 0);
|
||||
|
||||
// Set up the index
|
||||
var index = 4;
|
||||
|
||||
// Write total document length
|
||||
header[3] = (totalLength >> 24) & 0xff;
|
||||
header[2] = (totalLength >> 16) & 0xff;
|
||||
header[1] = (totalLength >> 8) & 0xff;
|
||||
header[0] = totalLength & 0xff;
|
||||
|
||||
// Write header information requestId
|
||||
header[index + 3] = (this.requestId >> 24) & 0xff;
|
||||
header[index + 2] = (this.requestId >> 16) & 0xff;
|
||||
header[index + 1] = (this.requestId >> 8) & 0xff;
|
||||
header[index] = this.requestId & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// Write header information responseTo
|
||||
header[index + 3] = (0 >> 24) & 0xff;
|
||||
header[index + 2] = (0 >> 16) & 0xff;
|
||||
header[index + 1] = (0 >> 8) & 0xff;
|
||||
header[index] = 0 & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// Write header information OP_QUERY
|
||||
header[index + 3] = (opcodes.OP_QUERY >> 24) & 0xff;
|
||||
header[index + 2] = (opcodes.OP_QUERY >> 16) & 0xff;
|
||||
header[index + 1] = (opcodes.OP_QUERY >> 8) & 0xff;
|
||||
header[index] = opcodes.OP_QUERY & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// Write header information flags
|
||||
header[index + 3] = (flags >> 24) & 0xff;
|
||||
header[index + 2] = (flags >> 16) & 0xff;
|
||||
header[index + 1] = (flags >> 8) & 0xff;
|
||||
header[index] = flags & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// Write collection name
|
||||
index = index + header.write(this.ns, index, 'utf8') + 1;
|
||||
header[index - 1] = 0;
|
||||
|
||||
// Write header information flags numberToSkip
|
||||
header[index + 3] = (this.numberToSkip >> 24) & 0xff;
|
||||
header[index + 2] = (this.numberToSkip >> 16) & 0xff;
|
||||
header[index + 1] = (this.numberToSkip >> 8) & 0xff;
|
||||
header[index] = this.numberToSkip & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// Write header information flags numberToReturn
|
||||
header[index + 3] = (this.numberToReturn >> 24) & 0xff;
|
||||
header[index + 2] = (this.numberToReturn >> 16) & 0xff;
|
||||
header[index + 1] = (this.numberToReturn >> 8) & 0xff;
|
||||
header[index] = this.numberToReturn & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// Return the buffers
|
||||
return buffers;
|
||||
};
|
||||
|
||||
Query.getRequestId = function() {
|
||||
return ++_requestId;
|
||||
};
|
||||
|
||||
/**************************************************************
|
||||
* GETMORE
|
||||
**************************************************************/
|
||||
var GetMore = function(bson, ns, cursorId, opts) {
|
||||
opts = opts || {};
|
||||
this.numberToReturn = opts.numberToReturn || 0;
|
||||
this.requestId = _requestId++;
|
||||
this.bson = bson;
|
||||
this.ns = ns;
|
||||
this.cursorId = cursorId;
|
||||
};
|
||||
|
||||
//
|
||||
// Uses a single allocated buffer for the process, avoiding multiple memory allocations
|
||||
GetMore.prototype.toBin = function() {
|
||||
var length = 4 + Buffer.byteLength(this.ns) + 1 + 4 + 8 + 4 * 4;
|
||||
// Create command buffer
|
||||
var index = 0;
|
||||
// Allocate buffer
|
||||
var _buffer = Buffer.alloc(length);
|
||||
|
||||
// Write header information
|
||||
// index = write32bit(index, _buffer, length);
|
||||
_buffer[index + 3] = (length >> 24) & 0xff;
|
||||
_buffer[index + 2] = (length >> 16) & 0xff;
|
||||
_buffer[index + 1] = (length >> 8) & 0xff;
|
||||
_buffer[index] = length & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// index = write32bit(index, _buffer, requestId);
|
||||
_buffer[index + 3] = (this.requestId >> 24) & 0xff;
|
||||
_buffer[index + 2] = (this.requestId >> 16) & 0xff;
|
||||
_buffer[index + 1] = (this.requestId >> 8) & 0xff;
|
||||
_buffer[index] = this.requestId & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// index = write32bit(index, _buffer, 0);
|
||||
_buffer[index + 3] = (0 >> 24) & 0xff;
|
||||
_buffer[index + 2] = (0 >> 16) & 0xff;
|
||||
_buffer[index + 1] = (0 >> 8) & 0xff;
|
||||
_buffer[index] = 0 & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// index = write32bit(index, _buffer, OP_GETMORE);
|
||||
_buffer[index + 3] = (opcodes.OP_GETMORE >> 24) & 0xff;
|
||||
_buffer[index + 2] = (opcodes.OP_GETMORE >> 16) & 0xff;
|
||||
_buffer[index + 1] = (opcodes.OP_GETMORE >> 8) & 0xff;
|
||||
_buffer[index] = opcodes.OP_GETMORE & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// index = write32bit(index, _buffer, 0);
|
||||
_buffer[index + 3] = (0 >> 24) & 0xff;
|
||||
_buffer[index + 2] = (0 >> 16) & 0xff;
|
||||
_buffer[index + 1] = (0 >> 8) & 0xff;
|
||||
_buffer[index] = 0 & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// Write collection name
|
||||
index = index + _buffer.write(this.ns, index, 'utf8') + 1;
|
||||
_buffer[index - 1] = 0;
|
||||
|
||||
// Write batch size
|
||||
// index = write32bit(index, _buffer, numberToReturn);
|
||||
_buffer[index + 3] = (this.numberToReturn >> 24) & 0xff;
|
||||
_buffer[index + 2] = (this.numberToReturn >> 16) & 0xff;
|
||||
_buffer[index + 1] = (this.numberToReturn >> 8) & 0xff;
|
||||
_buffer[index] = this.numberToReturn & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// Write cursor id
|
||||
// index = write32bit(index, _buffer, cursorId.getLowBits());
|
||||
_buffer[index + 3] = (this.cursorId.getLowBits() >> 24) & 0xff;
|
||||
_buffer[index + 2] = (this.cursorId.getLowBits() >> 16) & 0xff;
|
||||
_buffer[index + 1] = (this.cursorId.getLowBits() >> 8) & 0xff;
|
||||
_buffer[index] = this.cursorId.getLowBits() & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// index = write32bit(index, _buffer, cursorId.getHighBits());
|
||||
_buffer[index + 3] = (this.cursorId.getHighBits() >> 24) & 0xff;
|
||||
_buffer[index + 2] = (this.cursorId.getHighBits() >> 16) & 0xff;
|
||||
_buffer[index + 1] = (this.cursorId.getHighBits() >> 8) & 0xff;
|
||||
_buffer[index] = this.cursorId.getHighBits() & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// Return buffer
|
||||
return _buffer;
|
||||
};
|
||||
|
||||
/**************************************************************
|
||||
* KILLCURSOR
|
||||
**************************************************************/
|
||||
var KillCursor = function(bson, ns, cursorIds) {
|
||||
this.ns = ns;
|
||||
this.requestId = _requestId++;
|
||||
this.cursorIds = cursorIds;
|
||||
};
|
||||
|
||||
//
|
||||
// Uses a single allocated buffer for the process, avoiding multiple memory allocations
|
||||
KillCursor.prototype.toBin = function() {
|
||||
var length = 4 + 4 + 4 * 4 + this.cursorIds.length * 8;
|
||||
|
||||
// Create command buffer
|
||||
var index = 0;
|
||||
var _buffer = Buffer.alloc(length);
|
||||
|
||||
// Write header information
|
||||
// index = write32bit(index, _buffer, length);
|
||||
_buffer[index + 3] = (length >> 24) & 0xff;
|
||||
_buffer[index + 2] = (length >> 16) & 0xff;
|
||||
_buffer[index + 1] = (length >> 8) & 0xff;
|
||||
_buffer[index] = length & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// index = write32bit(index, _buffer, requestId);
|
||||
_buffer[index + 3] = (this.requestId >> 24) & 0xff;
|
||||
_buffer[index + 2] = (this.requestId >> 16) & 0xff;
|
||||
_buffer[index + 1] = (this.requestId >> 8) & 0xff;
|
||||
_buffer[index] = this.requestId & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// index = write32bit(index, _buffer, 0);
|
||||
_buffer[index + 3] = (0 >> 24) & 0xff;
|
||||
_buffer[index + 2] = (0 >> 16) & 0xff;
|
||||
_buffer[index + 1] = (0 >> 8) & 0xff;
|
||||
_buffer[index] = 0 & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// index = write32bit(index, _buffer, OP_KILL_CURSORS);
|
||||
_buffer[index + 3] = (opcodes.OP_KILL_CURSORS >> 24) & 0xff;
|
||||
_buffer[index + 2] = (opcodes.OP_KILL_CURSORS >> 16) & 0xff;
|
||||
_buffer[index + 1] = (opcodes.OP_KILL_CURSORS >> 8) & 0xff;
|
||||
_buffer[index] = opcodes.OP_KILL_CURSORS & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// index = write32bit(index, _buffer, 0);
|
||||
_buffer[index + 3] = (0 >> 24) & 0xff;
|
||||
_buffer[index + 2] = (0 >> 16) & 0xff;
|
||||
_buffer[index + 1] = (0 >> 8) & 0xff;
|
||||
_buffer[index] = 0 & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// Write batch size
|
||||
// index = write32bit(index, _buffer, this.cursorIds.length);
|
||||
_buffer[index + 3] = (this.cursorIds.length >> 24) & 0xff;
|
||||
_buffer[index + 2] = (this.cursorIds.length >> 16) & 0xff;
|
||||
_buffer[index + 1] = (this.cursorIds.length >> 8) & 0xff;
|
||||
_buffer[index] = this.cursorIds.length & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// Write all the cursor ids into the array
|
||||
for (var i = 0; i < this.cursorIds.length; i++) {
|
||||
// Write cursor id
|
||||
// index = write32bit(index, _buffer, cursorIds[i].getLowBits());
|
||||
_buffer[index + 3] = (this.cursorIds[i].getLowBits() >> 24) & 0xff;
|
||||
_buffer[index + 2] = (this.cursorIds[i].getLowBits() >> 16) & 0xff;
|
||||
_buffer[index + 1] = (this.cursorIds[i].getLowBits() >> 8) & 0xff;
|
||||
_buffer[index] = this.cursorIds[i].getLowBits() & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// index = write32bit(index, _buffer, cursorIds[i].getHighBits());
|
||||
_buffer[index + 3] = (this.cursorIds[i].getHighBits() >> 24) & 0xff;
|
||||
_buffer[index + 2] = (this.cursorIds[i].getHighBits() >> 16) & 0xff;
|
||||
_buffer[index + 1] = (this.cursorIds[i].getHighBits() >> 8) & 0xff;
|
||||
_buffer[index] = this.cursorIds[i].getHighBits() & 0xff;
|
||||
index = index + 4;
|
||||
}
|
||||
|
||||
// Return buffer
|
||||
return _buffer;
|
||||
};
|
||||
|
||||
var Response = function(bson, message, msgHeader, msgBody, opts) {
|
||||
opts = opts || { promoteLongs: true, promoteValues: true, promoteBuffers: false };
|
||||
this.parsed = false;
|
||||
this.raw = message;
|
||||
this.data = msgBody;
|
||||
this.bson = bson;
|
||||
this.opts = opts;
|
||||
|
||||
// Read the message header
|
||||
this.length = msgHeader.length;
|
||||
this.requestId = msgHeader.requestId;
|
||||
this.responseTo = msgHeader.responseTo;
|
||||
this.opCode = msgHeader.opCode;
|
||||
this.fromCompressed = msgHeader.fromCompressed;
|
||||
|
||||
// Read the message body
|
||||
this.responseFlags = msgBody.readInt32LE(0);
|
||||
this.cursorId = new Long(msgBody.readInt32LE(4), msgBody.readInt32LE(8));
|
||||
this.startingFrom = msgBody.readInt32LE(12);
|
||||
this.numberReturned = msgBody.readInt32LE(16);
|
||||
|
||||
// Preallocate document array
|
||||
this.documents = new Array(this.numberReturned);
|
||||
|
||||
// Flag values
|
||||
this.cursorNotFound = (this.responseFlags & CURSOR_NOT_FOUND) !== 0;
|
||||
this.queryFailure = (this.responseFlags & QUERY_FAILURE) !== 0;
|
||||
this.shardConfigStale = (this.responseFlags & SHARD_CONFIG_STALE) !== 0;
|
||||
this.awaitCapable = (this.responseFlags & AWAIT_CAPABLE) !== 0;
|
||||
this.promoteLongs = typeof opts.promoteLongs === 'boolean' ? opts.promoteLongs : true;
|
||||
this.promoteValues = typeof opts.promoteValues === 'boolean' ? opts.promoteValues : true;
|
||||
this.promoteBuffers = typeof opts.promoteBuffers === 'boolean' ? opts.promoteBuffers : false;
|
||||
};
|
||||
|
||||
Response.prototype.isParsed = function() {
|
||||
return this.parsed;
|
||||
};
|
||||
|
||||
Response.prototype.parse = function(options) {
|
||||
// Don't parse again if not needed
|
||||
if (this.parsed) return;
|
||||
options = options || {};
|
||||
|
||||
// Allow the return of raw documents instead of parsing
|
||||
var raw = options.raw || false;
|
||||
var documentsReturnedIn = options.documentsReturnedIn || null;
|
||||
var promoteLongs =
|
||||
typeof options.promoteLongs === 'boolean' ? options.promoteLongs : this.opts.promoteLongs;
|
||||
var promoteValues =
|
||||
typeof options.promoteValues === 'boolean' ? options.promoteValues : this.opts.promoteValues;
|
||||
var promoteBuffers =
|
||||
typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : this.opts.promoteBuffers;
|
||||
var bsonSize, _options;
|
||||
|
||||
// Set up the options
|
||||
_options = {
|
||||
promoteLongs: promoteLongs,
|
||||
promoteValues: promoteValues,
|
||||
promoteBuffers: promoteBuffers
|
||||
};
|
||||
|
||||
// Position within OP_REPLY at which documents start
|
||||
// (See https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#wire-op-reply)
|
||||
this.index = 20;
|
||||
|
||||
//
|
||||
// Parse Body
|
||||
//
|
||||
for (var i = 0; i < this.numberReturned; i++) {
|
||||
bsonSize =
|
||||
this.data[this.index] |
|
||||
(this.data[this.index + 1] << 8) |
|
||||
(this.data[this.index + 2] << 16) |
|
||||
(this.data[this.index + 3] << 24);
|
||||
|
||||
// If we have raw results specified slice the return document
|
||||
if (raw) {
|
||||
this.documents[i] = this.data.slice(this.index, this.index + bsonSize);
|
||||
} else {
|
||||
this.documents[i] = this.bson.deserialize(
|
||||
this.data.slice(this.index, this.index + bsonSize),
|
||||
_options
|
||||
);
|
||||
}
|
||||
|
||||
// Adjust the index
|
||||
this.index = this.index + bsonSize;
|
||||
}
|
||||
|
||||
if (this.documents.length === 1 && documentsReturnedIn != null && raw) {
|
||||
const fieldsAsRaw = {};
|
||||
fieldsAsRaw[documentsReturnedIn] = true;
|
||||
_options.fieldsAsRaw = fieldsAsRaw;
|
||||
|
||||
const doc = this.bson.deserialize(this.documents[0], _options);
|
||||
this.documents = [doc];
|
||||
}
|
||||
|
||||
// Set parsed
|
||||
this.parsed = true;
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
Query: Query,
|
||||
GetMore: GetMore,
|
||||
Response: Response,
|
||||
KillCursor: KillCursor
|
||||
};
|
||||
352
node_modules/mongodb/lib/core/connection/connect.js
generated
vendored
Normal file
352
node_modules/mongodb/lib/core/connection/connect.js
generated
vendored
Normal file
@@ -0,0 +1,352 @@
|
||||
'use strict';
|
||||
const net = require('net');
|
||||
const tls = require('tls');
|
||||
const Connection = require('./connection');
|
||||
const MongoError = require('../error').MongoError;
|
||||
const MongoNetworkError = require('../error').MongoNetworkError;
|
||||
const MongoNetworkTimeoutError = require('../error').MongoNetworkTimeoutError;
|
||||
const defaultAuthProviders = require('../auth/defaultAuthProviders').defaultAuthProviders;
|
||||
const AuthContext = require('../auth/auth_provider').AuthContext;
|
||||
const WIRE_CONSTANTS = require('../wireprotocol/constants');
|
||||
const makeClientMetadata = require('../utils').makeClientMetadata;
|
||||
const MAX_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_WIRE_VERSION;
|
||||
const MAX_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_SERVER_VERSION;
|
||||
const MIN_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_WIRE_VERSION;
|
||||
const MIN_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_SERVER_VERSION;
|
||||
let AUTH_PROVIDERS;
|
||||
|
||||
function connect(options, cancellationToken, callback) {
|
||||
if (typeof cancellationToken === 'function') {
|
||||
callback = cancellationToken;
|
||||
cancellationToken = undefined;
|
||||
}
|
||||
|
||||
const ConnectionType = options && options.connectionType ? options.connectionType : Connection;
|
||||
if (AUTH_PROVIDERS == null) {
|
||||
AUTH_PROVIDERS = defaultAuthProviders(options.bson);
|
||||
}
|
||||
|
||||
const family = options.family !== void 0 ? options.family : 0;
|
||||
makeConnection(family, options, cancellationToken, (err, socket) => {
|
||||
if (err) {
|
||||
callback(err, socket); // in the error case, `socket` is the originating error event name
|
||||
return;
|
||||
}
|
||||
|
||||
performInitialHandshake(new ConnectionType(socket, options), options, callback);
|
||||
});
|
||||
}
|
||||
|
||||
function isModernConnectionType(conn) {
|
||||
return !(conn instanceof Connection);
|
||||
}
|
||||
|
||||
function checkSupportedServer(ismaster, options) {
|
||||
const serverVersionHighEnough =
|
||||
ismaster &&
|
||||
typeof ismaster.maxWireVersion === 'number' &&
|
||||
ismaster.maxWireVersion >= MIN_SUPPORTED_WIRE_VERSION;
|
||||
const serverVersionLowEnough =
|
||||
ismaster &&
|
||||
typeof ismaster.minWireVersion === 'number' &&
|
||||
ismaster.minWireVersion <= MAX_SUPPORTED_WIRE_VERSION;
|
||||
|
||||
if (serverVersionHighEnough) {
|
||||
if (serverVersionLowEnough) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const message = `Server at ${options.host}:${options.port} reports minimum wire version ${ismaster.minWireVersion}, but this version of the Node.js Driver requires at most ${MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${MAX_SUPPORTED_SERVER_VERSION})`;
|
||||
return new MongoError(message);
|
||||
}
|
||||
|
||||
const message = `Server at ${options.host}:${
|
||||
options.port
|
||||
} reports maximum wire version ${ismaster.maxWireVersion ||
|
||||
0}, but this version of the Node.js Driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION})`;
|
||||
return new MongoError(message);
|
||||
}
|
||||
|
||||
function performInitialHandshake(conn, options, _callback) {
|
||||
const callback = function(err, ret) {
|
||||
if (err && conn) {
|
||||
conn.destroy();
|
||||
}
|
||||
_callback(err, ret);
|
||||
};
|
||||
|
||||
const credentials = options.credentials;
|
||||
if (credentials) {
|
||||
if (!credentials.mechanism.match(/DEFAULT/i) && !AUTH_PROVIDERS[credentials.mechanism]) {
|
||||
callback(new MongoError(`authMechanism '${credentials.mechanism}' not supported`));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const authContext = new AuthContext(conn, credentials, options);
|
||||
prepareHandshakeDocument(authContext, (err, handshakeDoc) => {
|
||||
if (err) {
|
||||
return callback(err);
|
||||
}
|
||||
|
||||
const handshakeOptions = Object.assign({}, options);
|
||||
if (options.connectTimeoutMS || options.connectionTimeout) {
|
||||
// The handshake technically is a monitoring check, so its socket timeout should be connectTimeoutMS
|
||||
handshakeOptions.socketTimeout = options.connectTimeoutMS || options.connectionTimeout;
|
||||
}
|
||||
|
||||
const start = new Date().getTime();
|
||||
conn.command('admin.$cmd', handshakeDoc, handshakeOptions, (err, result) => {
|
||||
if (err) {
|
||||
callback(err);
|
||||
return;
|
||||
}
|
||||
|
||||
const response = result.result;
|
||||
if (response.ok === 0) {
|
||||
callback(new MongoError(response));
|
||||
return;
|
||||
}
|
||||
|
||||
const supportedServerErr = checkSupportedServer(response, options);
|
||||
if (supportedServerErr) {
|
||||
callback(supportedServerErr);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isModernConnectionType(conn)) {
|
||||
// resolve compression
|
||||
if (response.compression) {
|
||||
const agreedCompressors = handshakeDoc.compression.filter(
|
||||
compressor => response.compression.indexOf(compressor) !== -1
|
||||
);
|
||||
|
||||
if (agreedCompressors.length) {
|
||||
conn.agreedCompressor = agreedCompressors[0];
|
||||
}
|
||||
|
||||
if (options.compression && options.compression.zlibCompressionLevel) {
|
||||
conn.zlibCompressionLevel = options.compression.zlibCompressionLevel;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// NOTE: This is metadata attached to the connection while porting away from
|
||||
// handshake being done in the `Server` class. Likely, it should be
|
||||
// relocated, or at very least restructured.
|
||||
conn.ismaster = response;
|
||||
conn.lastIsMasterMS = new Date().getTime() - start;
|
||||
|
||||
if (!response.arbiterOnly && credentials) {
|
||||
// store the response on auth context
|
||||
Object.assign(authContext, { response });
|
||||
|
||||
const resolvedCredentials = credentials.resolveAuthMechanism(response);
|
||||
const authProvider = AUTH_PROVIDERS[resolvedCredentials.mechanism];
|
||||
authProvider.auth(authContext, err => {
|
||||
if (err) return callback(err);
|
||||
callback(undefined, conn);
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
callback(undefined, conn);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function prepareHandshakeDocument(authContext, callback) {
|
||||
const options = authContext.options;
|
||||
const compressors =
|
||||
options.compression && options.compression.compressors ? options.compression.compressors : [];
|
||||
|
||||
const handshakeDoc = {
|
||||
ismaster: true,
|
||||
client: options.metadata || makeClientMetadata(options),
|
||||
compression: compressors
|
||||
};
|
||||
|
||||
const credentials = authContext.credentials;
|
||||
if (credentials) {
|
||||
if (credentials.mechanism.match(/DEFAULT/i) && credentials.username) {
|
||||
Object.assign(handshakeDoc, {
|
||||
saslSupportedMechs: `${credentials.source}.${credentials.username}`
|
||||
});
|
||||
|
||||
AUTH_PROVIDERS['scram-sha-256'].prepare(handshakeDoc, authContext, callback);
|
||||
return;
|
||||
}
|
||||
|
||||
const authProvider = AUTH_PROVIDERS[credentials.mechanism];
|
||||
authProvider.prepare(handshakeDoc, authContext, callback);
|
||||
return;
|
||||
}
|
||||
|
||||
callback(undefined, handshakeDoc);
|
||||
}
|
||||
|
||||
const LEGAL_SSL_SOCKET_OPTIONS = [
|
||||
'pfx',
|
||||
'key',
|
||||
'passphrase',
|
||||
'cert',
|
||||
'ca',
|
||||
'ciphers',
|
||||
'NPNProtocols',
|
||||
'ALPNProtocols',
|
||||
'servername',
|
||||
'ecdhCurve',
|
||||
'secureProtocol',
|
||||
'secureContext',
|
||||
'session',
|
||||
'minDHSize',
|
||||
'crl',
|
||||
'rejectUnauthorized'
|
||||
];
|
||||
|
||||
function parseConnectOptions(family, options) {
|
||||
const host = typeof options.host === 'string' ? options.host : 'localhost';
|
||||
if (host.indexOf('/') !== -1) {
|
||||
return { path: host };
|
||||
}
|
||||
|
||||
const result = {
|
||||
family,
|
||||
host,
|
||||
port: typeof options.port === 'number' ? options.port : 27017,
|
||||
rejectUnauthorized: false
|
||||
};
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function parseSslOptions(family, options) {
|
||||
const result = parseConnectOptions(family, options);
|
||||
|
||||
// Merge in valid SSL options
|
||||
for (const name in options) {
|
||||
if (options[name] != null && LEGAL_SSL_SOCKET_OPTIONS.indexOf(name) !== -1) {
|
||||
result[name] = options[name];
|
||||
}
|
||||
}
|
||||
|
||||
// Override checkServerIdentity behavior
|
||||
if (options.checkServerIdentity === false) {
|
||||
// Skip the identiy check by retuning undefined as per node documents
|
||||
// https://nodejs.org/api/tls.html#tls_tls_connect_options_callback
|
||||
result.checkServerIdentity = function() {
|
||||
return undefined;
|
||||
};
|
||||
} else if (typeof options.checkServerIdentity === 'function') {
|
||||
result.checkServerIdentity = options.checkServerIdentity;
|
||||
}
|
||||
|
||||
// Set default sni servername to be the same as host
|
||||
if (result.servername == null) {
|
||||
result.servername = result.host;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
const SOCKET_ERROR_EVENTS = new Set(['error', 'close', 'timeout', 'parseError']);
|
||||
function makeConnection(family, options, cancellationToken, _callback) {
|
||||
const useSsl = typeof options.ssl === 'boolean' ? options.ssl : false;
|
||||
const keepAlive = typeof options.keepAlive === 'boolean' ? options.keepAlive : true;
|
||||
let keepAliveInitialDelay =
|
||||
typeof options.keepAliveInitialDelay === 'number' ? options.keepAliveInitialDelay : 120000;
|
||||
const noDelay = typeof options.noDelay === 'boolean' ? options.noDelay : true;
|
||||
const connectionTimeout =
|
||||
typeof options.connectionTimeout === 'number'
|
||||
? options.connectionTimeout
|
||||
: typeof options.connectTimeoutMS === 'number'
|
||||
? options.connectTimeoutMS
|
||||
: 30000;
|
||||
const socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000;
|
||||
const rejectUnauthorized =
|
||||
typeof options.rejectUnauthorized === 'boolean' ? options.rejectUnauthorized : true;
|
||||
|
||||
if (keepAliveInitialDelay > socketTimeout) {
|
||||
keepAliveInitialDelay = Math.round(socketTimeout / 2);
|
||||
}
|
||||
|
||||
let socket;
|
||||
const callback = function(err, ret) {
|
||||
if (err && socket) {
|
||||
socket.destroy();
|
||||
}
|
||||
|
||||
_callback(err, ret);
|
||||
};
|
||||
|
||||
try {
|
||||
if (useSsl) {
|
||||
socket = tls.connect(parseSslOptions(family, options));
|
||||
if (typeof socket.disableRenegotiation === 'function') {
|
||||
socket.disableRenegotiation();
|
||||
}
|
||||
} else {
|
||||
socket = net.createConnection(parseConnectOptions(family, options));
|
||||
}
|
||||
} catch (err) {
|
||||
return callback(err);
|
||||
}
|
||||
|
||||
socket.setKeepAlive(keepAlive, keepAliveInitialDelay);
|
||||
socket.setTimeout(connectionTimeout);
|
||||
socket.setNoDelay(noDelay);
|
||||
|
||||
const connectEvent = useSsl ? 'secureConnect' : 'connect';
|
||||
let cancellationHandler;
|
||||
function errorHandler(eventName) {
|
||||
return err => {
|
||||
SOCKET_ERROR_EVENTS.forEach(event => socket.removeAllListeners(event));
|
||||
if (cancellationHandler) {
|
||||
cancellationToken.removeListener('cancel', cancellationHandler);
|
||||
}
|
||||
|
||||
socket.removeListener(connectEvent, connectHandler);
|
||||
callback(connectionFailureError(eventName, err));
|
||||
};
|
||||
}
|
||||
|
||||
function connectHandler() {
|
||||
SOCKET_ERROR_EVENTS.forEach(event => socket.removeAllListeners(event));
|
||||
if (cancellationHandler) {
|
||||
cancellationToken.removeListener('cancel', cancellationHandler);
|
||||
}
|
||||
|
||||
if (socket.authorizationError && rejectUnauthorized) {
|
||||
return callback(socket.authorizationError);
|
||||
}
|
||||
|
||||
socket.setTimeout(socketTimeout);
|
||||
callback(null, socket);
|
||||
}
|
||||
|
||||
SOCKET_ERROR_EVENTS.forEach(event => socket.once(event, errorHandler(event)));
|
||||
if (cancellationToken) {
|
||||
cancellationHandler = errorHandler('cancel');
|
||||
cancellationToken.once('cancel', cancellationHandler);
|
||||
}
|
||||
|
||||
socket.once(connectEvent, connectHandler);
|
||||
}
|
||||
|
||||
function connectionFailureError(type, err) {
|
||||
switch (type) {
|
||||
case 'error':
|
||||
return new MongoNetworkError(err);
|
||||
case 'timeout':
|
||||
return new MongoNetworkTimeoutError(`connection timed out`);
|
||||
case 'close':
|
||||
return new MongoNetworkError(`connection closed`);
|
||||
case 'cancel':
|
||||
return new MongoNetworkError(`connection establishment was cancelled`);
|
||||
default:
|
||||
return new MongoNetworkError(`unknown network error`);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = connect;
|
||||
712
node_modules/mongodb/lib/core/connection/connection.js
generated
vendored
Normal file
712
node_modules/mongodb/lib/core/connection/connection.js
generated
vendored
Normal file
@@ -0,0 +1,712 @@
|
||||
'use strict';
|
||||
|
||||
const EventEmitter = require('events').EventEmitter;
|
||||
const crypto = require('crypto');
|
||||
const debugOptions = require('./utils').debugOptions;
|
||||
const parseHeader = require('../wireprotocol/shared').parseHeader;
|
||||
const decompress = require('../wireprotocol/compression').decompress;
|
||||
const Response = require('./commands').Response;
|
||||
const BinMsg = require('./msg').BinMsg;
|
||||
const MongoNetworkError = require('../error').MongoNetworkError;
|
||||
const MongoNetworkTimeoutError = require('../error').MongoNetworkTimeoutError;
|
||||
const MongoError = require('../error').MongoError;
|
||||
const Logger = require('./logger');
|
||||
const OP_COMPRESSED = require('../wireprotocol/shared').opcodes.OP_COMPRESSED;
|
||||
const OP_MSG = require('../wireprotocol/shared').opcodes.OP_MSG;
|
||||
const MESSAGE_HEADER_SIZE = require('../wireprotocol/shared').MESSAGE_HEADER_SIZE;
|
||||
const Buffer = require('safe-buffer').Buffer;
|
||||
const Query = require('./commands').Query;
|
||||
const CommandResult = require('./command_result');
|
||||
|
||||
let _id = 0;
|
||||
|
||||
const DEFAULT_MAX_BSON_MESSAGE_SIZE = 1024 * 1024 * 16 * 4;
|
||||
const DEBUG_FIELDS = [
|
||||
'host',
|
||||
'port',
|
||||
'size',
|
||||
'keepAlive',
|
||||
'keepAliveInitialDelay',
|
||||
'noDelay',
|
||||
'connectionTimeout',
|
||||
'socketTimeout',
|
||||
'ssl',
|
||||
'ca',
|
||||
'crl',
|
||||
'cert',
|
||||
'rejectUnauthorized',
|
||||
'promoteLongs',
|
||||
'promoteValues',
|
||||
'promoteBuffers',
|
||||
'checkServerIdentity'
|
||||
];
|
||||
|
||||
let connectionAccountingSpy = undefined;
|
||||
let connectionAccounting = false;
|
||||
let connections = {};
|
||||
|
||||
/**
|
||||
* A class representing a single connection to a MongoDB server
|
||||
*
|
||||
* @fires Connection#connect
|
||||
* @fires Connection#close
|
||||
* @fires Connection#error
|
||||
* @fires Connection#timeout
|
||||
* @fires Connection#parseError
|
||||
* @fires Connection#message
|
||||
*/
|
||||
class Connection extends EventEmitter {
|
||||
/**
|
||||
* Creates a new Connection instance
|
||||
*
|
||||
* **NOTE**: Internal class, do not instantiate directly
|
||||
*
|
||||
* @param {Socket} socket The socket this connection wraps
|
||||
* @param {Object} options Various settings
|
||||
* @param {object} options.bson An implementation of bson serialize and deserialize
|
||||
* @param {string} [options.host='localhost'] The host the socket is connected to
|
||||
* @param {number} [options.port=27017] The port used for the socket connection
|
||||
* @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled
|
||||
* @param {number} [options.keepAliveInitialDelay=120000] Initial delay before TCP keep alive enabled
|
||||
* @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting
|
||||
* @param {number} [options.socketTimeout=360000] TCP Socket timeout setting
|
||||
* @param {boolean} [options.promoteLongs] Convert Long values from the db into Numbers if they fit into 53 bits
|
||||
* @param {boolean} [options.promoteValues] Promotes BSON values to native types where possible, set to false to only receive wrapper types.
|
||||
* @param {boolean} [options.promoteBuffers] Promotes Binary BSON values to native Node Buffers.
|
||||
* @param {number} [options.maxBsonMessageSize=0x4000000] Largest possible size of a BSON message (for legacy purposes)
|
||||
*/
|
||||
constructor(socket, options) {
|
||||
super();
|
||||
|
||||
options = options || {};
|
||||
if (!options.bson) {
|
||||
throw new TypeError('must pass in valid bson parser');
|
||||
}
|
||||
|
||||
this.id = _id++;
|
||||
this.options = options;
|
||||
this.logger = Logger('Connection', options);
|
||||
this.bson = options.bson;
|
||||
this.tag = options.tag;
|
||||
this.maxBsonMessageSize = options.maxBsonMessageSize || DEFAULT_MAX_BSON_MESSAGE_SIZE;
|
||||
|
||||
this.port = options.port || 27017;
|
||||
this.host = options.host || 'localhost';
|
||||
this.socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000;
|
||||
|
||||
// These values are inspected directly in tests, but maybe not necessary to keep around
|
||||
this.keepAlive = typeof options.keepAlive === 'boolean' ? options.keepAlive : true;
|
||||
this.keepAliveInitialDelay =
|
||||
typeof options.keepAliveInitialDelay === 'number' ? options.keepAliveInitialDelay : 120000;
|
||||
this.connectionTimeout =
|
||||
typeof options.connectionTimeout === 'number' ? options.connectionTimeout : 30000;
|
||||
if (this.keepAliveInitialDelay > this.socketTimeout) {
|
||||
this.keepAliveInitialDelay = Math.round(this.socketTimeout / 2);
|
||||
}
|
||||
|
||||
// Debug information
|
||||
if (this.logger.isDebug()) {
|
||||
this.logger.debug(
|
||||
`creating connection ${this.id} with options [${JSON.stringify(
|
||||
debugOptions(DEBUG_FIELDS, options)
|
||||
)}]`
|
||||
);
|
||||
}
|
||||
|
||||
// Response options
|
||||
this.responseOptions = {
|
||||
promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true,
|
||||
promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true,
|
||||
promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false
|
||||
};
|
||||
|
||||
// Flushing
|
||||
this.flushing = false;
|
||||
this.queue = [];
|
||||
|
||||
// Internal state
|
||||
this.writeStream = null;
|
||||
this.destroyed = false;
|
||||
this.timedOut = false;
|
||||
|
||||
// Create hash method
|
||||
const hash = crypto.createHash('sha1');
|
||||
hash.update(this.address);
|
||||
this.hashedName = hash.digest('hex');
|
||||
|
||||
// All operations in flight on the connection
|
||||
this.workItems = [];
|
||||
|
||||
// setup socket
|
||||
this.socket = socket;
|
||||
this.socket.once('error', errorHandler(this));
|
||||
this.socket.once('timeout', timeoutHandler(this));
|
||||
this.socket.once('close', closeHandler(this));
|
||||
this.socket.on('data', dataHandler(this));
|
||||
|
||||
if (connectionAccounting) {
|
||||
addConnection(this.id, this);
|
||||
}
|
||||
}
|
||||
|
||||
setSocketTimeout(value) {
|
||||
if (this.socket) {
|
||||
this.socket.setTimeout(value);
|
||||
}
|
||||
}
|
||||
|
||||
resetSocketTimeout() {
|
||||
if (this.socket) {
|
||||
this.socket.setTimeout(this.socketTimeout);
|
||||
}
|
||||
}
|
||||
|
||||
static enableConnectionAccounting(spy) {
|
||||
if (spy) {
|
||||
connectionAccountingSpy = spy;
|
||||
}
|
||||
|
||||
connectionAccounting = true;
|
||||
connections = {};
|
||||
}
|
||||
|
||||
static disableConnectionAccounting() {
|
||||
connectionAccounting = false;
|
||||
connectionAccountingSpy = undefined;
|
||||
}
|
||||
|
||||
static connections() {
|
||||
return connections;
|
||||
}
|
||||
|
||||
get address() {
|
||||
return `${this.host}:${this.port}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unref this connection
|
||||
* @method
|
||||
* @return {boolean}
|
||||
*/
|
||||
unref() {
|
||||
if (this.socket == null) {
|
||||
this.once('connect', () => this.socket.unref());
|
||||
return;
|
||||
}
|
||||
|
||||
this.socket.unref();
|
||||
}
|
||||
|
||||
/**
|
||||
* Flush all work Items on this connection
|
||||
*
|
||||
* @param {*} err The error to propagate to the flushed work items
|
||||
*/
|
||||
flush(err) {
|
||||
while (this.workItems.length > 0) {
|
||||
const workItem = this.workItems.shift();
|
||||
if (workItem.cb) {
|
||||
workItem.cb(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroy connection
|
||||
* @method
|
||||
*/
|
||||
destroy(options, callback) {
|
||||
if (typeof options === 'function') {
|
||||
callback = options;
|
||||
options = {};
|
||||
}
|
||||
|
||||
options = Object.assign({ force: false }, options);
|
||||
|
||||
if (connectionAccounting) {
|
||||
deleteConnection(this.id);
|
||||
}
|
||||
|
||||
if (this.socket == null) {
|
||||
this.destroyed = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (options.force || this.timedOut) {
|
||||
this.socket.destroy();
|
||||
this.destroyed = true;
|
||||
if (typeof callback === 'function') callback(null, null);
|
||||
return;
|
||||
}
|
||||
|
||||
this.socket.end(err => {
|
||||
this.destroyed = true;
|
||||
if (typeof callback === 'function') callback(err, null);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Write to connection
|
||||
* @method
|
||||
* @param {Command} command Command to write out need to implement toBin and toBinUnified
|
||||
*/
|
||||
write(buffer) {
|
||||
// Debug Log
|
||||
if (this.logger.isDebug()) {
|
||||
if (!Array.isArray(buffer)) {
|
||||
this.logger.debug(`writing buffer [${buffer.toString('hex')}] to ${this.address}`);
|
||||
} else {
|
||||
for (let i = 0; i < buffer.length; i++)
|
||||
this.logger.debug(`writing buffer [${buffer[i].toString('hex')}] to ${this.address}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Double check that the connection is not destroyed
|
||||
if (this.socket.destroyed === false) {
|
||||
// Write out the command
|
||||
if (!Array.isArray(buffer)) {
|
||||
this.socket.write(buffer, 'binary');
|
||||
return true;
|
||||
}
|
||||
|
||||
// Iterate over all buffers and write them in order to the socket
|
||||
for (let i = 0; i < buffer.length; i++) {
|
||||
this.socket.write(buffer[i], 'binary');
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Connection is destroyed return write failed
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return id of connection as a string
|
||||
* @method
|
||||
* @return {string}
|
||||
*/
|
||||
toString() {
|
||||
return '' + this.id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return json object of connection
|
||||
* @method
|
||||
* @return {object}
|
||||
*/
|
||||
toJSON() {
|
||||
return { id: this.id, host: this.host, port: this.port };
|
||||
}
|
||||
|
||||
/**
|
||||
* Is the connection connected
|
||||
* @method
|
||||
* @return {boolean}
|
||||
*/
|
||||
isConnected() {
|
||||
if (this.destroyed) return false;
|
||||
return !this.socket.destroyed && this.socket.writable;
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
command(ns, command, options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
|
||||
const conn = this;
|
||||
const socketTimeout =
|
||||
typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000;
|
||||
const bson = conn.options.bson;
|
||||
const query = new Query(bson, ns, command, {
|
||||
numberToSkip: 0,
|
||||
numberToReturn: 1
|
||||
});
|
||||
|
||||
const noop = () => {};
|
||||
function _callback(err, result) {
|
||||
callback(err, result);
|
||||
callback = noop;
|
||||
}
|
||||
|
||||
function errorHandler(err) {
|
||||
conn.resetSocketTimeout();
|
||||
CONNECTION_ERROR_EVENTS.forEach(eventName => conn.removeListener(eventName, errorHandler));
|
||||
conn.removeListener('message', messageHandler);
|
||||
|
||||
if (err == null) {
|
||||
err = new MongoError(`runCommand failed for connection to '${conn.address}'`);
|
||||
}
|
||||
|
||||
// ignore all future errors
|
||||
conn.on('error', noop);
|
||||
_callback(err);
|
||||
}
|
||||
|
||||
function messageHandler(msg) {
|
||||
if (msg.responseTo !== query.requestId) {
|
||||
return;
|
||||
}
|
||||
|
||||
conn.resetSocketTimeout();
|
||||
CONNECTION_ERROR_EVENTS.forEach(eventName => conn.removeListener(eventName, errorHandler));
|
||||
conn.removeListener('message', messageHandler);
|
||||
|
||||
msg.parse({ promoteValues: true });
|
||||
|
||||
const response = msg.documents[0];
|
||||
if (response.ok === 0 || response.$err || response.errmsg || response.code) {
|
||||
_callback(new MongoError(response));
|
||||
return;
|
||||
}
|
||||
|
||||
_callback(undefined, new CommandResult(response, this, msg));
|
||||
}
|
||||
|
||||
conn.setSocketTimeout(socketTimeout);
|
||||
CONNECTION_ERROR_EVENTS.forEach(eventName => conn.once(eventName, errorHandler));
|
||||
conn.on('message', messageHandler);
|
||||
conn.write(query.toBin());
|
||||
}
|
||||
}
|
||||
|
||||
const CONNECTION_ERROR_EVENTS = ['error', 'close', 'timeout', 'parseError'];
|
||||
|
||||
function deleteConnection(id) {
|
||||
// console.log("=== deleted connection " + id + " :: " + (connections[id] ? connections[id].port : ''))
|
||||
delete connections[id];
|
||||
|
||||
if (connectionAccountingSpy) {
|
||||
connectionAccountingSpy.deleteConnection(id);
|
||||
}
|
||||
}
|
||||
|
||||
function addConnection(id, connection) {
|
||||
// console.log("=== added connection " + id + " :: " + connection.port)
|
||||
connections[id] = connection;
|
||||
|
||||
if (connectionAccountingSpy) {
|
||||
connectionAccountingSpy.addConnection(id, connection);
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// Connection handlers
|
||||
function errorHandler(conn) {
|
||||
return function(err) {
|
||||
if (connectionAccounting) deleteConnection(conn.id);
|
||||
// Debug information
|
||||
if (conn.logger.isDebug()) {
|
||||
conn.logger.debug(
|
||||
`connection ${conn.id} for [${conn.address}] errored out with [${JSON.stringify(err)}]`
|
||||
);
|
||||
}
|
||||
|
||||
conn.emit('error', new MongoNetworkError(err), conn);
|
||||
};
|
||||
}
|
||||
|
||||
function timeoutHandler(conn) {
|
||||
return function() {
|
||||
if (connectionAccounting) deleteConnection(conn.id);
|
||||
|
||||
if (conn.logger.isDebug()) {
|
||||
conn.logger.debug(`connection ${conn.id} for [${conn.address}] timed out`);
|
||||
}
|
||||
|
||||
conn.timedOut = true;
|
||||
conn.emit(
|
||||
'timeout',
|
||||
new MongoNetworkTimeoutError(`connection ${conn.id} to ${conn.address} timed out`, {
|
||||
beforeHandshake: conn.ismaster == null
|
||||
}),
|
||||
conn
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
function closeHandler(conn) {
|
||||
return function(hadError) {
|
||||
if (connectionAccounting) deleteConnection(conn.id);
|
||||
|
||||
if (conn.logger.isDebug()) {
|
||||
conn.logger.debug(`connection ${conn.id} with for [${conn.address}] closed`);
|
||||
}
|
||||
|
||||
if (!hadError) {
|
||||
conn.emit(
|
||||
'close',
|
||||
new MongoNetworkError(`connection ${conn.id} to ${conn.address} closed`),
|
||||
conn
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Handle a message once it is received
|
||||
function processMessage(conn, message) {
|
||||
const msgHeader = parseHeader(message);
|
||||
if (msgHeader.opCode !== OP_COMPRESSED) {
|
||||
const ResponseConstructor = msgHeader.opCode === OP_MSG ? BinMsg : Response;
|
||||
conn.emit(
|
||||
'message',
|
||||
new ResponseConstructor(
|
||||
conn.bson,
|
||||
message,
|
||||
msgHeader,
|
||||
message.slice(MESSAGE_HEADER_SIZE),
|
||||
conn.responseOptions
|
||||
),
|
||||
conn
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
msgHeader.fromCompressed = true;
|
||||
let index = MESSAGE_HEADER_SIZE;
|
||||
msgHeader.opCode = message.readInt32LE(index);
|
||||
index += 4;
|
||||
msgHeader.length = message.readInt32LE(index);
|
||||
index += 4;
|
||||
const compressorID = message[index];
|
||||
index++;
|
||||
|
||||
decompress(compressorID, message.slice(index), (err, decompressedMsgBody) => {
|
||||
if (err) {
|
||||
conn.emit('error', err);
|
||||
return;
|
||||
}
|
||||
|
||||
if (decompressedMsgBody.length !== msgHeader.length) {
|
||||
conn.emit(
|
||||
'error',
|
||||
new MongoError(
|
||||
'Decompressing a compressed message from the server failed. The message is corrupt.'
|
||||
)
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const ResponseConstructor = msgHeader.opCode === OP_MSG ? BinMsg : Response;
|
||||
conn.emit(
|
||||
'message',
|
||||
new ResponseConstructor(
|
||||
conn.bson,
|
||||
message,
|
||||
msgHeader,
|
||||
decompressedMsgBody,
|
||||
conn.responseOptions
|
||||
),
|
||||
conn
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function dataHandler(conn) {
|
||||
return function(data) {
|
||||
// Parse until we are done with the data
|
||||
while (data.length > 0) {
|
||||
// If we still have bytes to read on the current message
|
||||
if (conn.bytesRead > 0 && conn.sizeOfMessage > 0) {
|
||||
// Calculate the amount of remaining bytes
|
||||
const remainingBytesToRead = conn.sizeOfMessage - conn.bytesRead;
|
||||
// Check if the current chunk contains the rest of the message
|
||||
if (remainingBytesToRead > data.length) {
|
||||
// Copy the new data into the exiting buffer (should have been allocated when we know the message size)
|
||||
data.copy(conn.buffer, conn.bytesRead);
|
||||
// Adjust the number of bytes read so it point to the correct index in the buffer
|
||||
conn.bytesRead = conn.bytesRead + data.length;
|
||||
|
||||
// Reset state of buffer
|
||||
data = Buffer.alloc(0);
|
||||
} else {
|
||||
// Copy the missing part of the data into our current buffer
|
||||
data.copy(conn.buffer, conn.bytesRead, 0, remainingBytesToRead);
|
||||
// Slice the overflow into a new buffer that we will then re-parse
|
||||
data = data.slice(remainingBytesToRead);
|
||||
|
||||
// Emit current complete message
|
||||
const emitBuffer = conn.buffer;
|
||||
// Reset state of buffer
|
||||
conn.buffer = null;
|
||||
conn.sizeOfMessage = 0;
|
||||
conn.bytesRead = 0;
|
||||
conn.stubBuffer = null;
|
||||
|
||||
processMessage(conn, emitBuffer);
|
||||
}
|
||||
} else {
|
||||
// Stub buffer is kept in case we don't get enough bytes to determine the
|
||||
// size of the message (< 4 bytes)
|
||||
if (conn.stubBuffer != null && conn.stubBuffer.length > 0) {
|
||||
// If we have enough bytes to determine the message size let's do it
|
||||
if (conn.stubBuffer.length + data.length > 4) {
|
||||
// Prepad the data
|
||||
const newData = Buffer.alloc(conn.stubBuffer.length + data.length);
|
||||
conn.stubBuffer.copy(newData, 0);
|
||||
data.copy(newData, conn.stubBuffer.length);
|
||||
// Reassign for parsing
|
||||
data = newData;
|
||||
|
||||
// Reset state of buffer
|
||||
conn.buffer = null;
|
||||
conn.sizeOfMessage = 0;
|
||||
conn.bytesRead = 0;
|
||||
conn.stubBuffer = null;
|
||||
} else {
|
||||
// Add the the bytes to the stub buffer
|
||||
const newStubBuffer = Buffer.alloc(conn.stubBuffer.length + data.length);
|
||||
// Copy existing stub buffer
|
||||
conn.stubBuffer.copy(newStubBuffer, 0);
|
||||
// Copy missing part of the data
|
||||
data.copy(newStubBuffer, conn.stubBuffer.length);
|
||||
// Exit parsing loop
|
||||
data = Buffer.alloc(0);
|
||||
}
|
||||
} else {
|
||||
if (data.length > 4) {
|
||||
// Retrieve the message size
|
||||
const sizeOfMessage = data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
|
||||
// If we have a negative sizeOfMessage emit error and return
|
||||
if (sizeOfMessage < 0 || sizeOfMessage > conn.maxBsonMessageSize) {
|
||||
const errorObject = {
|
||||
err: 'socketHandler',
|
||||
trace: '',
|
||||
bin: conn.buffer,
|
||||
parseState: {
|
||||
sizeOfMessage: sizeOfMessage,
|
||||
bytesRead: conn.bytesRead,
|
||||
stubBuffer: conn.stubBuffer
|
||||
}
|
||||
};
|
||||
// We got a parse Error fire it off then keep going
|
||||
conn.emit('parseError', errorObject, conn);
|
||||
return;
|
||||
}
|
||||
|
||||
// Ensure that the size of message is larger than 0 and less than the max allowed
|
||||
if (
|
||||
sizeOfMessage > 4 &&
|
||||
sizeOfMessage < conn.maxBsonMessageSize &&
|
||||
sizeOfMessage > data.length
|
||||
) {
|
||||
conn.buffer = Buffer.alloc(sizeOfMessage);
|
||||
// Copy all the data into the buffer
|
||||
data.copy(conn.buffer, 0);
|
||||
// Update bytes read
|
||||
conn.bytesRead = data.length;
|
||||
// Update sizeOfMessage
|
||||
conn.sizeOfMessage = sizeOfMessage;
|
||||
// Ensure stub buffer is null
|
||||
conn.stubBuffer = null;
|
||||
// Exit parsing loop
|
||||
data = Buffer.alloc(0);
|
||||
} else if (
|
||||
sizeOfMessage > 4 &&
|
||||
sizeOfMessage < conn.maxBsonMessageSize &&
|
||||
sizeOfMessage === data.length
|
||||
) {
|
||||
const emitBuffer = data;
|
||||
// Reset state of buffer
|
||||
conn.buffer = null;
|
||||
conn.sizeOfMessage = 0;
|
||||
conn.bytesRead = 0;
|
||||
conn.stubBuffer = null;
|
||||
// Exit parsing loop
|
||||
data = Buffer.alloc(0);
|
||||
// Emit the message
|
||||
processMessage(conn, emitBuffer);
|
||||
} else if (sizeOfMessage <= 4 || sizeOfMessage > conn.maxBsonMessageSize) {
|
||||
const errorObject = {
|
||||
err: 'socketHandler',
|
||||
trace: null,
|
||||
bin: data,
|
||||
parseState: {
|
||||
sizeOfMessage: sizeOfMessage,
|
||||
bytesRead: 0,
|
||||
buffer: null,
|
||||
stubBuffer: null
|
||||
}
|
||||
};
|
||||
// We got a parse Error fire it off then keep going
|
||||
conn.emit('parseError', errorObject, conn);
|
||||
|
||||
// Clear out the state of the parser
|
||||
conn.buffer = null;
|
||||
conn.sizeOfMessage = 0;
|
||||
conn.bytesRead = 0;
|
||||
conn.stubBuffer = null;
|
||||
// Exit parsing loop
|
||||
data = Buffer.alloc(0);
|
||||
} else {
|
||||
const emitBuffer = data.slice(0, sizeOfMessage);
|
||||
// Reset state of buffer
|
||||
conn.buffer = null;
|
||||
conn.sizeOfMessage = 0;
|
||||
conn.bytesRead = 0;
|
||||
conn.stubBuffer = null;
|
||||
// Copy rest of message
|
||||
data = data.slice(sizeOfMessage);
|
||||
// Emit the message
|
||||
processMessage(conn, emitBuffer);
|
||||
}
|
||||
} else {
|
||||
// Create a buffer that contains the space for the non-complete message
|
||||
conn.stubBuffer = Buffer.alloc(data.length);
|
||||
// Copy the data to the stub buffer
|
||||
data.copy(conn.stubBuffer, 0);
|
||||
// Exit parsing loop
|
||||
data = Buffer.alloc(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A server connect event, used to verify that the connection is up and running
|
||||
*
|
||||
* @event Connection#connect
|
||||
* @type {Connection}
|
||||
*/
|
||||
|
||||
/**
|
||||
* The server connection closed, all pool connections closed
|
||||
*
|
||||
* @event Connection#close
|
||||
* @type {Connection}
|
||||
*/
|
||||
|
||||
/**
|
||||
* The server connection caused an error, all pool connections closed
|
||||
*
|
||||
* @event Connection#error
|
||||
* @type {Connection}
|
||||
*/
|
||||
|
||||
/**
|
||||
* The server connection timed out, all pool connections closed
|
||||
*
|
||||
* @event Connection#timeout
|
||||
* @type {Connection}
|
||||
*/
|
||||
|
||||
/**
|
||||
* The driver experienced an invalid message, all pool connections closed
|
||||
*
|
||||
* @event Connection#parseError
|
||||
* @type {Connection}
|
||||
*/
|
||||
|
||||
/**
|
||||
* An event emitted each time the connection receives a parsed message from the wire
|
||||
*
|
||||
* @event Connection#message
|
||||
* @type {Connection}
|
||||
*/
|
||||
|
||||
module.exports = Connection;
|
||||
251
node_modules/mongodb/lib/core/connection/logger.js
generated
vendored
Normal file
251
node_modules/mongodb/lib/core/connection/logger.js
generated
vendored
Normal file
@@ -0,0 +1,251 @@
|
||||
'use strict';
|
||||
|
||||
var f = require('util').format,
|
||||
MongoError = require('../error').MongoError;
|
||||
|
||||
// Filters for classes
|
||||
var classFilters = {};
|
||||
var filteredClasses = {};
|
||||
var level = null;
|
||||
// Save the process id
|
||||
var pid = process.pid;
|
||||
// current logger
|
||||
var currentLogger = null;
|
||||
|
||||
/**
|
||||
* @callback Logger~loggerCallback
|
||||
* @param {string} msg message being logged
|
||||
* @param {object} state an object containing more metadata about the logging message
|
||||
*/
|
||||
|
||||
/**
|
||||
* Creates a new Logger instance
|
||||
* @class
|
||||
* @param {string} className The Class name associated with the logging instance
|
||||
* @param {object} [options=null] Optional settings.
|
||||
* @param {Logger~loggerCallback} [options.logger=null] Custom logger function;
|
||||
* @param {string} [options.loggerLevel=error] Override default global log level.
|
||||
*/
|
||||
var Logger = function(className, options) {
|
||||
if (!(this instanceof Logger)) return new Logger(className, options);
|
||||
options = options || {};
|
||||
|
||||
// Current reference
|
||||
this.className = className;
|
||||
|
||||
// Current logger
|
||||
if (options.logger) {
|
||||
currentLogger = options.logger;
|
||||
} else if (currentLogger == null) {
|
||||
currentLogger = console.log;
|
||||
}
|
||||
|
||||
// Set level of logging, default is error
|
||||
if (options.loggerLevel) {
|
||||
level = options.loggerLevel || 'error';
|
||||
}
|
||||
|
||||
// Add all class names
|
||||
if (filteredClasses[this.className] == null) classFilters[this.className] = true;
|
||||
};
|
||||
|
||||
/**
|
||||
* Log a message at the debug level
|
||||
* @method
|
||||
* @param {string} message The message to log
|
||||
* @param {object} object additional meta data to log
|
||||
* @return {null}
|
||||
*/
|
||||
Logger.prototype.debug = function(message, object) {
|
||||
if (
|
||||
this.isDebug() &&
|
||||
((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) ||
|
||||
(Object.keys(filteredClasses).length === 0 && classFilters[this.className]))
|
||||
) {
|
||||
var dateTime = new Date().getTime();
|
||||
var msg = f('[%s-%s:%s] %s %s', 'DEBUG', this.className, pid, dateTime, message);
|
||||
var state = {
|
||||
type: 'debug',
|
||||
message: message,
|
||||
className: this.className,
|
||||
pid: pid,
|
||||
date: dateTime
|
||||
};
|
||||
if (object) state.meta = object;
|
||||
currentLogger(msg, state);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Log a message at the warn level
|
||||
* @method
|
||||
* @param {string} message The message to log
|
||||
* @param {object} object additional meta data to log
|
||||
* @return {null}
|
||||
*/
|
||||
(Logger.prototype.warn = function(message, object) {
|
||||
if (
|
||||
this.isWarn() &&
|
||||
((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) ||
|
||||
(Object.keys(filteredClasses).length === 0 && classFilters[this.className]))
|
||||
) {
|
||||
var dateTime = new Date().getTime();
|
||||
var msg = f('[%s-%s:%s] %s %s', 'WARN', this.className, pid, dateTime, message);
|
||||
var state = {
|
||||
type: 'warn',
|
||||
message: message,
|
||||
className: this.className,
|
||||
pid: pid,
|
||||
date: dateTime
|
||||
};
|
||||
if (object) state.meta = object;
|
||||
currentLogger(msg, state);
|
||||
}
|
||||
}),
|
||||
/**
|
||||
* Log a message at the info level
|
||||
* @method
|
||||
* @param {string} message The message to log
|
||||
* @param {object} object additional meta data to log
|
||||
* @return {null}
|
||||
*/
|
||||
(Logger.prototype.info = function(message, object) {
|
||||
if (
|
||||
this.isInfo() &&
|
||||
((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) ||
|
||||
(Object.keys(filteredClasses).length === 0 && classFilters[this.className]))
|
||||
) {
|
||||
var dateTime = new Date().getTime();
|
||||
var msg = f('[%s-%s:%s] %s %s', 'INFO', this.className, pid, dateTime, message);
|
||||
var state = {
|
||||
type: 'info',
|
||||
message: message,
|
||||
className: this.className,
|
||||
pid: pid,
|
||||
date: dateTime
|
||||
};
|
||||
if (object) state.meta = object;
|
||||
currentLogger(msg, state);
|
||||
}
|
||||
}),
|
||||
/**
|
||||
* Log a message at the error level
|
||||
* @method
|
||||
* @param {string} message The message to log
|
||||
* @param {object} object additional meta data to log
|
||||
* @return {null}
|
||||
*/
|
||||
(Logger.prototype.error = function(message, object) {
|
||||
if (
|
||||
this.isError() &&
|
||||
((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) ||
|
||||
(Object.keys(filteredClasses).length === 0 && classFilters[this.className]))
|
||||
) {
|
||||
var dateTime = new Date().getTime();
|
||||
var msg = f('[%s-%s:%s] %s %s', 'ERROR', this.className, pid, dateTime, message);
|
||||
var state = {
|
||||
type: 'error',
|
||||
message: message,
|
||||
className: this.className,
|
||||
pid: pid,
|
||||
date: dateTime
|
||||
};
|
||||
if (object) state.meta = object;
|
||||
currentLogger(msg, state);
|
||||
}
|
||||
}),
|
||||
/**
|
||||
* Is the logger set at info level
|
||||
* @method
|
||||
* @return {boolean}
|
||||
*/
|
||||
(Logger.prototype.isInfo = function() {
|
||||
return level === 'info' || level === 'debug';
|
||||
}),
|
||||
/**
|
||||
* Is the logger set at error level
|
||||
* @method
|
||||
* @return {boolean}
|
||||
*/
|
||||
(Logger.prototype.isError = function() {
|
||||
return level === 'error' || level === 'info' || level === 'debug';
|
||||
}),
|
||||
/**
|
||||
* Is the logger set at error level
|
||||
* @method
|
||||
* @return {boolean}
|
||||
*/
|
||||
(Logger.prototype.isWarn = function() {
|
||||
return level === 'error' || level === 'warn' || level === 'info' || level === 'debug';
|
||||
}),
|
||||
/**
|
||||
* Is the logger set at debug level
|
||||
* @method
|
||||
* @return {boolean}
|
||||
*/
|
||||
(Logger.prototype.isDebug = function() {
|
||||
return level === 'debug';
|
||||
});
|
||||
|
||||
/**
|
||||
* Resets the logger to default settings, error and no filtered classes
|
||||
* @method
|
||||
* @return {null}
|
||||
*/
|
||||
Logger.reset = function() {
|
||||
level = 'error';
|
||||
filteredClasses = {};
|
||||
};
|
||||
|
||||
/**
|
||||
* Get the current logger function
|
||||
* @method
|
||||
* @return {Logger~loggerCallback}
|
||||
*/
|
||||
Logger.currentLogger = function() {
|
||||
return currentLogger;
|
||||
};
|
||||
|
||||
/**
|
||||
* Set the current logger function
|
||||
* @method
|
||||
* @param {Logger~loggerCallback} logger Logger function.
|
||||
* @return {null}
|
||||
*/
|
||||
Logger.setCurrentLogger = function(logger) {
|
||||
if (typeof logger !== 'function') throw new MongoError('current logger must be a function');
|
||||
currentLogger = logger;
|
||||
};
|
||||
|
||||
/**
|
||||
* Set what classes to log.
|
||||
* @method
|
||||
* @param {string} type The type of filter (currently only class)
|
||||
* @param {string[]} values The filters to apply
|
||||
* @return {null}
|
||||
*/
|
||||
Logger.filter = function(type, values) {
|
||||
if (type === 'class' && Array.isArray(values)) {
|
||||
filteredClasses = {};
|
||||
|
||||
values.forEach(function(x) {
|
||||
filteredClasses[x] = true;
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Set the current log level
|
||||
* @method
|
||||
* @param {string} level Set current log level (debug, info, error)
|
||||
* @return {null}
|
||||
*/
|
||||
Logger.setLevel = function(_level) {
|
||||
if (_level !== 'info' && _level !== 'error' && _level !== 'debug' && _level !== 'warn') {
|
||||
throw new Error(f('%s is an illegal logging level', _level));
|
||||
}
|
||||
|
||||
level = _level;
|
||||
};
|
||||
|
||||
module.exports = Logger;
|
||||
222
node_modules/mongodb/lib/core/connection/msg.js
generated
vendored
Normal file
222
node_modules/mongodb/lib/core/connection/msg.js
generated
vendored
Normal file
@@ -0,0 +1,222 @@
|
||||
'use strict';
|
||||
|
||||
// Implementation of OP_MSG spec:
|
||||
// https://github.com/mongodb/specifications/blob/master/source/message/OP_MSG.rst
|
||||
//
|
||||
// struct Section {
|
||||
// uint8 payloadType;
|
||||
// union payload {
|
||||
// document document; // payloadType == 0
|
||||
// struct sequence { // payloadType == 1
|
||||
// int32 size;
|
||||
// cstring identifier;
|
||||
// document* documents;
|
||||
// };
|
||||
// };
|
||||
// };
|
||||
|
||||
// struct OP_MSG {
|
||||
// struct MsgHeader {
|
||||
// int32 messageLength;
|
||||
// int32 requestID;
|
||||
// int32 responseTo;
|
||||
// int32 opCode = 2013;
|
||||
// };
|
||||
// uint32 flagBits;
|
||||
// Section+ sections;
|
||||
// [uint32 checksum;]
|
||||
// };
|
||||
|
||||
const Buffer = require('safe-buffer').Buffer;
|
||||
const opcodes = require('../wireprotocol/shared').opcodes;
|
||||
const databaseNamespace = require('../wireprotocol/shared').databaseNamespace;
|
||||
const ReadPreference = require('../topologies/read_preference');
|
||||
|
||||
// Incrementing request id
|
||||
let _requestId = 0;
|
||||
|
||||
// Msg Flags
|
||||
const OPTS_CHECKSUM_PRESENT = 1;
|
||||
const OPTS_MORE_TO_COME = 2;
|
||||
const OPTS_EXHAUST_ALLOWED = 1 << 16;
|
||||
|
||||
class Msg {
|
||||
constructor(bson, ns, command, options) {
|
||||
// Basic options needed to be passed in
|
||||
if (command == null) throw new Error('query must be specified for query');
|
||||
|
||||
// Basic options
|
||||
this.bson = bson;
|
||||
this.ns = ns;
|
||||
this.command = command;
|
||||
this.command.$db = databaseNamespace(ns);
|
||||
|
||||
if (options.readPreference && options.readPreference.mode !== ReadPreference.PRIMARY) {
|
||||
this.command.$readPreference = options.readPreference.toJSON();
|
||||
}
|
||||
|
||||
// Ensure empty options
|
||||
this.options = options || {};
|
||||
|
||||
// Additional options
|
||||
this.requestId = options.requestId ? options.requestId : Msg.getRequestId();
|
||||
|
||||
// Serialization option
|
||||
this.serializeFunctions =
|
||||
typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
|
||||
this.ignoreUndefined =
|
||||
typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false;
|
||||
this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
|
||||
this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16;
|
||||
|
||||
// flags
|
||||
this.checksumPresent = false;
|
||||
this.moreToCome = options.moreToCome || false;
|
||||
this.exhaustAllowed =
|
||||
typeof options.exhaustAllowed === 'boolean' ? options.exhaustAllowed : false;
|
||||
}
|
||||
|
||||
toBin() {
|
||||
const buffers = [];
|
||||
let flags = 0;
|
||||
|
||||
if (this.checksumPresent) {
|
||||
flags |= OPTS_CHECKSUM_PRESENT;
|
||||
}
|
||||
|
||||
if (this.moreToCome) {
|
||||
flags |= OPTS_MORE_TO_COME;
|
||||
}
|
||||
|
||||
if (this.exhaustAllowed) {
|
||||
flags |= OPTS_EXHAUST_ALLOWED;
|
||||
}
|
||||
|
||||
const header = Buffer.alloc(
|
||||
4 * 4 + // Header
|
||||
4 // Flags
|
||||
);
|
||||
|
||||
buffers.push(header);
|
||||
|
||||
let totalLength = header.length;
|
||||
const command = this.command;
|
||||
totalLength += this.makeDocumentSegment(buffers, command);
|
||||
|
||||
header.writeInt32LE(totalLength, 0); // messageLength
|
||||
header.writeInt32LE(this.requestId, 4); // requestID
|
||||
header.writeInt32LE(0, 8); // responseTo
|
||||
header.writeInt32LE(opcodes.OP_MSG, 12); // opCode
|
||||
header.writeUInt32LE(flags, 16); // flags
|
||||
return buffers;
|
||||
}
|
||||
|
||||
makeDocumentSegment(buffers, document) {
|
||||
const payloadTypeBuffer = Buffer.alloc(1);
|
||||
payloadTypeBuffer[0] = 0;
|
||||
|
||||
const documentBuffer = this.serializeBson(document);
|
||||
buffers.push(payloadTypeBuffer);
|
||||
buffers.push(documentBuffer);
|
||||
|
||||
return payloadTypeBuffer.length + documentBuffer.length;
|
||||
}
|
||||
|
||||
serializeBson(document) {
|
||||
return this.bson.serialize(document, {
|
||||
checkKeys: this.checkKeys,
|
||||
serializeFunctions: this.serializeFunctions,
|
||||
ignoreUndefined: this.ignoreUndefined
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Msg.getRequestId = function() {
|
||||
_requestId = (_requestId + 1) & 0x7fffffff;
|
||||
return _requestId;
|
||||
};
|
||||
|
||||
class BinMsg {
|
||||
constructor(bson, message, msgHeader, msgBody, opts) {
|
||||
opts = opts || { promoteLongs: true, promoteValues: true, promoteBuffers: false };
|
||||
this.parsed = false;
|
||||
this.raw = message;
|
||||
this.data = msgBody;
|
||||
this.bson = bson;
|
||||
this.opts = opts;
|
||||
|
||||
// Read the message header
|
||||
this.length = msgHeader.length;
|
||||
this.requestId = msgHeader.requestId;
|
||||
this.responseTo = msgHeader.responseTo;
|
||||
this.opCode = msgHeader.opCode;
|
||||
this.fromCompressed = msgHeader.fromCompressed;
|
||||
|
||||
// Read response flags
|
||||
this.responseFlags = msgBody.readInt32LE(0);
|
||||
this.checksumPresent = (this.responseFlags & OPTS_CHECKSUM_PRESENT) !== 0;
|
||||
this.moreToCome = (this.responseFlags & OPTS_MORE_TO_COME) !== 0;
|
||||
this.exhaustAllowed = (this.responseFlags & OPTS_EXHAUST_ALLOWED) !== 0;
|
||||
this.promoteLongs = typeof opts.promoteLongs === 'boolean' ? opts.promoteLongs : true;
|
||||
this.promoteValues = typeof opts.promoteValues === 'boolean' ? opts.promoteValues : true;
|
||||
this.promoteBuffers = typeof opts.promoteBuffers === 'boolean' ? opts.promoteBuffers : false;
|
||||
|
||||
this.documents = [];
|
||||
}
|
||||
|
||||
isParsed() {
|
||||
return this.parsed;
|
||||
}
|
||||
|
||||
parse(options) {
|
||||
// Don't parse again if not needed
|
||||
if (this.parsed) return;
|
||||
options = options || {};
|
||||
|
||||
this.index = 4;
|
||||
// Allow the return of raw documents instead of parsing
|
||||
const raw = options.raw || false;
|
||||
const documentsReturnedIn = options.documentsReturnedIn || null;
|
||||
const promoteLongs =
|
||||
typeof options.promoteLongs === 'boolean' ? options.promoteLongs : this.opts.promoteLongs;
|
||||
const promoteValues =
|
||||
typeof options.promoteValues === 'boolean' ? options.promoteValues : this.opts.promoteValues;
|
||||
const promoteBuffers =
|
||||
typeof options.promoteBuffers === 'boolean'
|
||||
? options.promoteBuffers
|
||||
: this.opts.promoteBuffers;
|
||||
|
||||
// Set up the options
|
||||
const _options = {
|
||||
promoteLongs: promoteLongs,
|
||||
promoteValues: promoteValues,
|
||||
promoteBuffers: promoteBuffers
|
||||
};
|
||||
|
||||
while (this.index < this.data.length) {
|
||||
const payloadType = this.data.readUInt8(this.index++);
|
||||
if (payloadType === 1) {
|
||||
console.error('TYPE 1');
|
||||
} else if (payloadType === 0) {
|
||||
const bsonSize = this.data.readUInt32LE(this.index);
|
||||
const bin = this.data.slice(this.index, this.index + bsonSize);
|
||||
this.documents.push(raw ? bin : this.bson.deserialize(bin, _options));
|
||||
|
||||
this.index += bsonSize;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.documents.length === 1 && documentsReturnedIn != null && raw) {
|
||||
const fieldsAsRaw = {};
|
||||
fieldsAsRaw[documentsReturnedIn] = true;
|
||||
_options.fieldsAsRaw = fieldsAsRaw;
|
||||
|
||||
const doc = this.bson.deserialize(this.documents[0], _options);
|
||||
this.documents = [doc];
|
||||
}
|
||||
|
||||
this.parsed = true;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { Msg, BinMsg };
|
||||
1281
node_modules/mongodb/lib/core/connection/pool.js
generated
vendored
Normal file
1281
node_modules/mongodb/lib/core/connection/pool.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
57
node_modules/mongodb/lib/core/connection/utils.js
generated
vendored
Normal file
57
node_modules/mongodb/lib/core/connection/utils.js
generated
vendored
Normal file
@@ -0,0 +1,57 @@
|
||||
'use strict';
|
||||
|
||||
const require_optional = require('require_optional');
|
||||
|
||||
function debugOptions(debugFields, options) {
|
||||
var finaloptions = {};
|
||||
debugFields.forEach(function(n) {
|
||||
finaloptions[n] = options[n];
|
||||
});
|
||||
|
||||
return finaloptions;
|
||||
}
|
||||
|
||||
function retrieveBSON() {
|
||||
var BSON = require('bson');
|
||||
BSON.native = false;
|
||||
|
||||
try {
|
||||
var optionalBSON = require_optional('bson-ext');
|
||||
if (optionalBSON) {
|
||||
optionalBSON.native = true;
|
||||
return optionalBSON;
|
||||
}
|
||||
} catch (err) {} // eslint-disable-line
|
||||
|
||||
return BSON;
|
||||
}
|
||||
|
||||
// Throw an error if an attempt to use Snappy is made when Snappy is not installed
|
||||
function noSnappyWarning() {
|
||||
throw new Error(
|
||||
'Attempted to use Snappy compression, but Snappy is not installed. Install or disable Snappy compression and try again.'
|
||||
);
|
||||
}
|
||||
|
||||
// Facilitate loading Snappy optionally
|
||||
function retrieveSnappy() {
|
||||
var snappy = null;
|
||||
try {
|
||||
snappy = require_optional('snappy');
|
||||
} catch (error) {} // eslint-disable-line
|
||||
if (!snappy) {
|
||||
snappy = {
|
||||
compress: noSnappyWarning,
|
||||
uncompress: noSnappyWarning,
|
||||
compressSync: noSnappyWarning,
|
||||
uncompressSync: noSnappyWarning
|
||||
};
|
||||
}
|
||||
return snappy;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
debugOptions,
|
||||
retrieveBSON,
|
||||
retrieveSnappy
|
||||
};
|
||||
871
node_modules/mongodb/lib/core/cursor.js
generated
vendored
Normal file
871
node_modules/mongodb/lib/core/cursor.js
generated
vendored
Normal file
@@ -0,0 +1,871 @@
|
||||
'use strict';
|
||||
|
||||
const Logger = require('./connection/logger');
|
||||
const retrieveBSON = require('./connection/utils').retrieveBSON;
|
||||
const MongoError = require('./error').MongoError;
|
||||
const MongoNetworkError = require('./error').MongoNetworkError;
|
||||
const collationNotSupported = require('./utils').collationNotSupported;
|
||||
const ReadPreference = require('./topologies/read_preference');
|
||||
const isUnifiedTopology = require('./utils').isUnifiedTopology;
|
||||
const executeOperation = require('../operations/execute_operation');
|
||||
const Readable = require('stream').Readable;
|
||||
const SUPPORTS = require('../utils').SUPPORTS;
|
||||
const MongoDBNamespace = require('../utils').MongoDBNamespace;
|
||||
const OperationBase = require('../operations/operation').OperationBase;
|
||||
|
||||
const BSON = retrieveBSON();
|
||||
const Long = BSON.Long;
|
||||
|
||||
// Possible states for a cursor
|
||||
const CursorState = {
|
||||
INIT: 0,
|
||||
OPEN: 1,
|
||||
CLOSED: 2,
|
||||
GET_MORE: 3
|
||||
};
|
||||
|
||||
//
|
||||
// Handle callback (including any exceptions thrown)
|
||||
function handleCallback(callback, err, result) {
|
||||
try {
|
||||
callback(err, result);
|
||||
} catch (err) {
|
||||
process.nextTick(function() {
|
||||
throw err;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This is a cursor results callback
|
||||
*
|
||||
* @callback resultCallback
|
||||
* @param {error} error An error object. Set to null if no error present
|
||||
* @param {object} document
|
||||
*/
|
||||
|
||||
/**
|
||||
* @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB
|
||||
* allowing for iteration over the results returned from the underlying query.
|
||||
*
|
||||
* **CURSORS Cannot directly be instantiated**
|
||||
*/
|
||||
|
||||
/**
|
||||
* The core cursor class. All cursors in the driver build off of this one.
|
||||
*
|
||||
* @property {number} cursorBatchSize The current cursorBatchSize for the cursor
|
||||
* @property {number} cursorLimit The current cursorLimit for the cursor
|
||||
* @property {number} cursorSkip The current cursorSkip for the cursor
|
||||
*/
|
||||
class CoreCursor extends Readable {
|
||||
/**
|
||||
* Create a new core `Cursor` instance.
|
||||
* **NOTE** Not to be instantiated directly
|
||||
*
|
||||
* @param {object} topology The server topology instance.
|
||||
* @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)
|
||||
* @param {{object}|Long} cmd The selector (can be a command or a cursorId)
|
||||
* @param {object} [options=null] Optional settings.
|
||||
* @param {object} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/| find command documentation} and {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.
|
||||
* @param {array} [options.documents=[]] Initial documents list for cursor
|
||||
* @param {object} [options.transforms=null] Transform methods for the cursor results
|
||||
* @param {function} [options.transforms.query] Transform the value returned from the initial query
|
||||
* @param {function} [options.transforms.doc] Transform each document returned from Cursor.prototype._next
|
||||
*/
|
||||
constructor(topology, ns, cmd, options) {
|
||||
super({ objectMode: true });
|
||||
options = options || {};
|
||||
|
||||
if (ns instanceof OperationBase) {
|
||||
this.operation = ns;
|
||||
ns = this.operation.ns.toString();
|
||||
options = this.operation.options;
|
||||
cmd = this.operation.cmd ? this.operation.cmd : {};
|
||||
}
|
||||
|
||||
// Cursor pool
|
||||
this.pool = null;
|
||||
// Cursor server
|
||||
this.server = null;
|
||||
|
||||
// Do we have a not connected handler
|
||||
this.disconnectHandler = options.disconnectHandler;
|
||||
|
||||
// Set local values
|
||||
this.bson = topology.s.bson;
|
||||
this.ns = ns;
|
||||
this.namespace = MongoDBNamespace.fromString(ns);
|
||||
this.cmd = cmd;
|
||||
this.options = options;
|
||||
this.topology = topology;
|
||||
|
||||
// All internal state
|
||||
this.cursorState = {
|
||||
cursorId: null,
|
||||
cmd,
|
||||
documents: options.documents || [],
|
||||
cursorIndex: 0,
|
||||
dead: false,
|
||||
killed: false,
|
||||
init: false,
|
||||
notified: false,
|
||||
limit: options.limit || cmd.limit || 0,
|
||||
skip: options.skip || cmd.skip || 0,
|
||||
batchSize: options.batchSize || cmd.batchSize || 1000,
|
||||
currentLimit: 0,
|
||||
// Result field name if not a cursor (contains the array of results)
|
||||
transforms: options.transforms,
|
||||
raw: options.raw || (cmd && cmd.raw)
|
||||
};
|
||||
|
||||
if (typeof options.session === 'object') {
|
||||
this.cursorState.session = options.session;
|
||||
}
|
||||
|
||||
// Add promoteLong to cursor state
|
||||
const topologyOptions = topology.s.options;
|
||||
if (typeof topologyOptions.promoteLongs === 'boolean') {
|
||||
this.cursorState.promoteLongs = topologyOptions.promoteLongs;
|
||||
} else if (typeof options.promoteLongs === 'boolean') {
|
||||
this.cursorState.promoteLongs = options.promoteLongs;
|
||||
}
|
||||
|
||||
// Add promoteValues to cursor state
|
||||
if (typeof topologyOptions.promoteValues === 'boolean') {
|
||||
this.cursorState.promoteValues = topologyOptions.promoteValues;
|
||||
} else if (typeof options.promoteValues === 'boolean') {
|
||||
this.cursorState.promoteValues = options.promoteValues;
|
||||
}
|
||||
|
||||
// Add promoteBuffers to cursor state
|
||||
if (typeof topologyOptions.promoteBuffers === 'boolean') {
|
||||
this.cursorState.promoteBuffers = topologyOptions.promoteBuffers;
|
||||
} else if (typeof options.promoteBuffers === 'boolean') {
|
||||
this.cursorState.promoteBuffers = options.promoteBuffers;
|
||||
}
|
||||
|
||||
if (topologyOptions.reconnect) {
|
||||
this.cursorState.reconnect = topologyOptions.reconnect;
|
||||
}
|
||||
|
||||
// Logger
|
||||
this.logger = Logger('Cursor', topologyOptions);
|
||||
|
||||
//
|
||||
// Did we pass in a cursor id
|
||||
if (typeof cmd === 'number') {
|
||||
this.cursorState.cursorId = Long.fromNumber(cmd);
|
||||
this.cursorState.lastCursorId = this.cursorState.cursorId;
|
||||
} else if (cmd instanceof Long) {
|
||||
this.cursorState.cursorId = cmd;
|
||||
this.cursorState.lastCursorId = cmd;
|
||||
}
|
||||
|
||||
// TODO: remove as part of NODE-2104
|
||||
if (this.operation) {
|
||||
this.operation.cursorState = this.cursorState;
|
||||
}
|
||||
}
|
||||
|
||||
setCursorBatchSize(value) {
|
||||
this.cursorState.batchSize = value;
|
||||
}
|
||||
|
||||
cursorBatchSize() {
|
||||
return this.cursorState.batchSize;
|
||||
}
|
||||
|
||||
setCursorLimit(value) {
|
||||
this.cursorState.limit = value;
|
||||
}
|
||||
|
||||
cursorLimit() {
|
||||
return this.cursorState.limit;
|
||||
}
|
||||
|
||||
setCursorSkip(value) {
|
||||
this.cursorState.skip = value;
|
||||
}
|
||||
|
||||
cursorSkip() {
|
||||
return this.cursorState.skip;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the next document from the cursor
|
||||
* @method
|
||||
* @param {resultCallback} callback A callback function
|
||||
*/
|
||||
_next(callback) {
|
||||
nextFunction(this, callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clone the cursor
|
||||
* @method
|
||||
* @return {Cursor}
|
||||
*/
|
||||
clone() {
|
||||
return this.topology.cursor(this.ns, this.cmd, this.options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the cursor is dead
|
||||
* @method
|
||||
* @return {boolean} A boolean signifying if the cursor is dead or not
|
||||
*/
|
||||
isDead() {
|
||||
return this.cursorState.dead === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the cursor was killed by the application
|
||||
* @method
|
||||
* @return {boolean} A boolean signifying if the cursor was killed by the application
|
||||
*/
|
||||
isKilled() {
|
||||
return this.cursorState.killed === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the cursor notified it's caller about it's death
|
||||
* @method
|
||||
* @return {boolean} A boolean signifying if the cursor notified the callback
|
||||
*/
|
||||
isNotified() {
|
||||
return this.cursorState.notified === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns current buffered documents length
|
||||
* @method
|
||||
* @return {number} The number of items in the buffered documents
|
||||
*/
|
||||
bufferedCount() {
|
||||
return this.cursorState.documents.length - this.cursorState.cursorIndex;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns current buffered documents
|
||||
* @method
|
||||
* @return {Array} An array of buffered documents
|
||||
*/
|
||||
readBufferedDocuments(number) {
|
||||
const unreadDocumentsLength = this.cursorState.documents.length - this.cursorState.cursorIndex;
|
||||
const length = number < unreadDocumentsLength ? number : unreadDocumentsLength;
|
||||
let elements = this.cursorState.documents.slice(
|
||||
this.cursorState.cursorIndex,
|
||||
this.cursorState.cursorIndex + length
|
||||
);
|
||||
|
||||
// Transform the doc with passed in transformation method if provided
|
||||
if (this.cursorState.transforms && typeof this.cursorState.transforms.doc === 'function') {
|
||||
// Transform all the elements
|
||||
for (let i = 0; i < elements.length; i++) {
|
||||
elements[i] = this.cursorState.transforms.doc(elements[i]);
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure we do not return any more documents than the limit imposed
|
||||
// Just return the number of elements up to the limit
|
||||
if (
|
||||
this.cursorState.limit > 0 &&
|
||||
this.cursorState.currentLimit + elements.length > this.cursorState.limit
|
||||
) {
|
||||
elements = elements.slice(0, this.cursorState.limit - this.cursorState.currentLimit);
|
||||
this.kill();
|
||||
}
|
||||
|
||||
// Adjust current limit
|
||||
this.cursorState.currentLimit = this.cursorState.currentLimit + elements.length;
|
||||
this.cursorState.cursorIndex = this.cursorState.cursorIndex + elements.length;
|
||||
|
||||
// Return elements
|
||||
return elements;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets local state for this cursor instance, and issues a `killCursors` command to the server
|
||||
*
|
||||
* @param {resultCallback} callback A callback function
|
||||
*/
|
||||
kill(callback) {
|
||||
// Set cursor to dead
|
||||
this.cursorState.dead = true;
|
||||
this.cursorState.killed = true;
|
||||
// Remove documents
|
||||
this.cursorState.documents = [];
|
||||
|
||||
// If no cursor id just return
|
||||
if (
|
||||
this.cursorState.cursorId == null ||
|
||||
this.cursorState.cursorId.isZero() ||
|
||||
this.cursorState.init === false
|
||||
) {
|
||||
if (callback) callback(null, null);
|
||||
return;
|
||||
}
|
||||
|
||||
this.server.killCursors(this.ns, this.cursorState, callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets the cursor
|
||||
*/
|
||||
rewind() {
|
||||
if (this.cursorState.init) {
|
||||
if (!this.cursorState.dead) {
|
||||
this.kill();
|
||||
}
|
||||
|
||||
this.cursorState.currentLimit = 0;
|
||||
this.cursorState.init = false;
|
||||
this.cursorState.dead = false;
|
||||
this.cursorState.killed = false;
|
||||
this.cursorState.notified = false;
|
||||
this.cursorState.documents = [];
|
||||
this.cursorState.cursorId = null;
|
||||
this.cursorState.cursorIndex = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Internal methods
|
||||
_read() {
|
||||
if ((this.s && this.s.state === CursorState.CLOSED) || this.isDead()) {
|
||||
return this.push(null);
|
||||
}
|
||||
|
||||
// Get the next item
|
||||
this._next((err, result) => {
|
||||
if (err) {
|
||||
if (this.listeners('error') && this.listeners('error').length > 0) {
|
||||
this.emit('error', err);
|
||||
}
|
||||
if (!this.isDead()) this.close();
|
||||
|
||||
// Emit end event
|
||||
this.emit('end');
|
||||
return this.emit('finish');
|
||||
}
|
||||
|
||||
// If we provided a transformation method
|
||||
if (
|
||||
this.cursorState.streamOptions &&
|
||||
typeof this.cursorState.streamOptions.transform === 'function' &&
|
||||
result != null
|
||||
) {
|
||||
return this.push(this.cursorState.streamOptions.transform(result));
|
||||
}
|
||||
|
||||
// Return the result
|
||||
this.push(result);
|
||||
|
||||
if (result === null && this.isDead()) {
|
||||
this.once('end', () => {
|
||||
this.close();
|
||||
this.emit('finish');
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
_endSession(options, callback) {
|
||||
if (typeof options === 'function') {
|
||||
callback = options;
|
||||
options = {};
|
||||
}
|
||||
options = options || {};
|
||||
|
||||
const session = this.cursorState.session;
|
||||
|
||||
if (session && (options.force || session.owner === this)) {
|
||||
this.cursorState.session = undefined;
|
||||
|
||||
if (this.operation) {
|
||||
this.operation.clearSession();
|
||||
}
|
||||
|
||||
session.endSession(callback);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (callback) {
|
||||
callback();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
_getMore(callback) {
|
||||
if (this.logger.isDebug()) {
|
||||
this.logger.debug(`schedule getMore call for query [${JSON.stringify(this.query)}]`);
|
||||
}
|
||||
|
||||
// Set the current batchSize
|
||||
let batchSize = this.cursorState.batchSize;
|
||||
if (
|
||||
this.cursorState.limit > 0 &&
|
||||
this.cursorState.currentLimit + batchSize > this.cursorState.limit
|
||||
) {
|
||||
batchSize = this.cursorState.limit - this.cursorState.currentLimit;
|
||||
}
|
||||
|
||||
const cursorState = this.cursorState;
|
||||
this.server.getMore(this.ns, cursorState, batchSize, this.options, (err, result, conn) => {
|
||||
// NOTE: `getMore` modifies `cursorState`, would be very ideal not to do so in the future
|
||||
if (err || (cursorState.cursorId && cursorState.cursorId.isZero())) {
|
||||
this._endSession();
|
||||
}
|
||||
|
||||
callback(err, result, conn);
|
||||
});
|
||||
}
|
||||
|
||||
_initializeCursor(callback) {
|
||||
const cursor = this;
|
||||
|
||||
// NOTE: this goes away once cursors use `executeOperation`
|
||||
if (isUnifiedTopology(cursor.topology) && cursor.topology.shouldCheckForSessionSupport()) {
|
||||
cursor.topology.selectServer(ReadPreference.primaryPreferred, err => {
|
||||
if (err) {
|
||||
callback(err);
|
||||
return;
|
||||
}
|
||||
|
||||
this._initializeCursor(callback);
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
function done(err, result) {
|
||||
const cursorState = cursor.cursorState;
|
||||
if (err || (cursorState.cursorId && cursorState.cursorId.isZero())) {
|
||||
cursor._endSession();
|
||||
}
|
||||
|
||||
if (
|
||||
cursorState.documents.length === 0 &&
|
||||
cursorState.cursorId &&
|
||||
cursorState.cursorId.isZero() &&
|
||||
!cursor.cmd.tailable &&
|
||||
!cursor.cmd.awaitData
|
||||
) {
|
||||
return setCursorNotified(cursor, callback);
|
||||
}
|
||||
|
||||
callback(err, result);
|
||||
}
|
||||
|
||||
const queryCallback = (err, r) => {
|
||||
if (err) {
|
||||
return done(err);
|
||||
}
|
||||
|
||||
const result = r.message;
|
||||
|
||||
if (Array.isArray(result.documents) && result.documents.length === 1) {
|
||||
const document = result.documents[0];
|
||||
|
||||
if (result.queryFailure) {
|
||||
return done(new MongoError(document), null);
|
||||
}
|
||||
|
||||
// Check if we have a command cursor
|
||||
if (!cursor.cmd.find || (cursor.cmd.find && cursor.cmd.virtual === false)) {
|
||||
// We have an error document, return the error
|
||||
if (document.$err || document.errmsg) {
|
||||
return done(new MongoError(document), null);
|
||||
}
|
||||
|
||||
// We have a cursor document
|
||||
if (document.cursor != null && typeof document.cursor !== 'string') {
|
||||
const id = document.cursor.id;
|
||||
// If we have a namespace change set the new namespace for getmores
|
||||
if (document.cursor.ns) {
|
||||
cursor.ns = document.cursor.ns;
|
||||
}
|
||||
// Promote id to long if needed
|
||||
cursor.cursorState.cursorId = typeof id === 'number' ? Long.fromNumber(id) : id;
|
||||
cursor.cursorState.lastCursorId = cursor.cursorState.cursorId;
|
||||
cursor.cursorState.operationTime = document.operationTime;
|
||||
|
||||
// If we have a firstBatch set it
|
||||
if (Array.isArray(document.cursor.firstBatch)) {
|
||||
cursor.cursorState.documents = document.cursor.firstBatch; //.reverse();
|
||||
}
|
||||
|
||||
// Return after processing command cursor
|
||||
return done(null, result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Otherwise fall back to regular find path
|
||||
const cursorId = result.cursorId || 0;
|
||||
cursor.cursorState.cursorId = cursorId instanceof Long ? cursorId : Long.fromNumber(cursorId);
|
||||
cursor.cursorState.documents = result.documents;
|
||||
cursor.cursorState.lastCursorId = result.cursorId;
|
||||
|
||||
// Transform the results with passed in transformation method if provided
|
||||
if (
|
||||
cursor.cursorState.transforms &&
|
||||
typeof cursor.cursorState.transforms.query === 'function'
|
||||
) {
|
||||
cursor.cursorState.documents = cursor.cursorState.transforms.query(result);
|
||||
}
|
||||
|
||||
done(null, result);
|
||||
};
|
||||
|
||||
if (cursor.operation) {
|
||||
if (cursor.logger.isDebug()) {
|
||||
cursor.logger.debug(
|
||||
`issue initial query [${JSON.stringify(cursor.cmd)}] with flags [${JSON.stringify(
|
||||
cursor.query
|
||||
)}]`
|
||||
);
|
||||
}
|
||||
|
||||
executeOperation(cursor.topology, cursor.operation, (err, result) => {
|
||||
if (err) {
|
||||
done(err);
|
||||
return;
|
||||
}
|
||||
|
||||
cursor.server = cursor.operation.server;
|
||||
cursor.cursorState.init = true;
|
||||
|
||||
// NOTE: this is a special internal method for cloning a cursor, consider removing
|
||||
if (cursor.cursorState.cursorId != null) {
|
||||
return done();
|
||||
}
|
||||
|
||||
queryCallback(err, result);
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Very explicitly choose what is passed to selectServer
|
||||
const serverSelectOptions = {};
|
||||
if (cursor.cursorState.session) {
|
||||
serverSelectOptions.session = cursor.cursorState.session;
|
||||
}
|
||||
|
||||
if (cursor.operation) {
|
||||
serverSelectOptions.readPreference = cursor.operation.readPreference;
|
||||
} else if (cursor.options.readPreference) {
|
||||
serverSelectOptions.readPreference = cursor.options.readPreference;
|
||||
}
|
||||
|
||||
return cursor.topology.selectServer(serverSelectOptions, (err, server) => {
|
||||
if (err) {
|
||||
const disconnectHandler = cursor.disconnectHandler;
|
||||
if (disconnectHandler != null) {
|
||||
return disconnectHandler.addObjectAndMethod(
|
||||
'cursor',
|
||||
cursor,
|
||||
'next',
|
||||
[callback],
|
||||
callback
|
||||
);
|
||||
}
|
||||
|
||||
return callback(err);
|
||||
}
|
||||
|
||||
cursor.server = server;
|
||||
cursor.cursorState.init = true;
|
||||
if (collationNotSupported(cursor.server, cursor.cmd)) {
|
||||
return callback(new MongoError(`server ${cursor.server.name} does not support collation`));
|
||||
}
|
||||
|
||||
// NOTE: this is a special internal method for cloning a cursor, consider removing
|
||||
if (cursor.cursorState.cursorId != null) {
|
||||
return done();
|
||||
}
|
||||
|
||||
if (cursor.logger.isDebug()) {
|
||||
cursor.logger.debug(
|
||||
`issue initial query [${JSON.stringify(cursor.cmd)}] with flags [${JSON.stringify(
|
||||
cursor.query
|
||||
)}]`
|
||||
);
|
||||
}
|
||||
|
||||
if (cursor.cmd.find != null) {
|
||||
server.query(cursor.ns, cursor.cmd, cursor.cursorState, cursor.options, queryCallback);
|
||||
return;
|
||||
}
|
||||
|
||||
const commandOptions = Object.assign({ session: cursor.cursorState.session }, cursor.options);
|
||||
server.command(cursor.ns, cursor.cmd, commandOptions, queryCallback);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (SUPPORTS.ASYNC_ITERATOR) {
|
||||
CoreCursor.prototype[Symbol.asyncIterator] = require('../async/async_iterator').asyncIterator;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate if the pool is dead and return error
|
||||
*/
|
||||
function isConnectionDead(self, callback) {
|
||||
if (self.pool && self.pool.isDestroyed()) {
|
||||
self.cursorState.killed = true;
|
||||
const err = new MongoNetworkError(
|
||||
`connection to host ${self.pool.host}:${self.pool.port} was destroyed`
|
||||
);
|
||||
|
||||
_setCursorNotifiedImpl(self, () => callback(err));
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate if the cursor is dead but was not explicitly killed by user
|
||||
*/
|
||||
function isCursorDeadButNotkilled(self, callback) {
|
||||
// Cursor is dead but not marked killed, return null
|
||||
if (self.cursorState.dead && !self.cursorState.killed) {
|
||||
self.cursorState.killed = true;
|
||||
setCursorNotified(self, callback);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate if the cursor is dead and was killed by user
|
||||
*/
|
||||
function isCursorDeadAndKilled(self, callback) {
|
||||
if (self.cursorState.dead && self.cursorState.killed) {
|
||||
handleCallback(callback, new MongoError('cursor is dead'));
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate if the cursor was killed by the user
|
||||
*/
|
||||
function isCursorKilled(self, callback) {
|
||||
if (self.cursorState.killed) {
|
||||
setCursorNotified(self, callback);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark cursor as being dead and notified
|
||||
*/
|
||||
function setCursorDeadAndNotified(self, callback) {
|
||||
self.cursorState.dead = true;
|
||||
setCursorNotified(self, callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark cursor as being notified
|
||||
*/
|
||||
function setCursorNotified(self, callback) {
|
||||
_setCursorNotifiedImpl(self, () => handleCallback(callback, null, null));
|
||||
}
|
||||
|
||||
function _setCursorNotifiedImpl(self, callback) {
|
||||
self.cursorState.notified = true;
|
||||
self.cursorState.documents = [];
|
||||
self.cursorState.cursorIndex = 0;
|
||||
|
||||
if (self.cursorState.session) {
|
||||
self._endSession(callback);
|
||||
return;
|
||||
}
|
||||
|
||||
return callback();
|
||||
}
|
||||
|
||||
function nextFunction(self, callback) {
|
||||
// We have notified about it
|
||||
if (self.cursorState.notified) {
|
||||
return callback(new Error('cursor is exhausted'));
|
||||
}
|
||||
|
||||
// Cursor is killed return null
|
||||
if (isCursorKilled(self, callback)) return;
|
||||
|
||||
// Cursor is dead but not marked killed, return null
|
||||
if (isCursorDeadButNotkilled(self, callback)) return;
|
||||
|
||||
// We have a dead and killed cursor, attempting to call next should error
|
||||
if (isCursorDeadAndKilled(self, callback)) return;
|
||||
|
||||
// We have just started the cursor
|
||||
if (!self.cursorState.init) {
|
||||
// Topology is not connected, save the call in the provided store to be
|
||||
// Executed at some point when the handler deems it's reconnected
|
||||
if (!self.topology.isConnected(self.options)) {
|
||||
// Only need this for single server, because repl sets and mongos
|
||||
// will always continue trying to reconnect
|
||||
if (self.topology._type === 'server' && !self.topology.s.options.reconnect) {
|
||||
// Reconnect is disabled, so we'll never reconnect
|
||||
return callback(new MongoError('no connection available'));
|
||||
}
|
||||
|
||||
if (self.disconnectHandler != null) {
|
||||
if (self.topology.isDestroyed()) {
|
||||
// Topology was destroyed, so don't try to wait for it to reconnect
|
||||
return callback(new MongoError('Topology was destroyed'));
|
||||
}
|
||||
|
||||
self.disconnectHandler.addObjectAndMethod('cursor', self, 'next', [callback], callback);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
self._initializeCursor((err, result) => {
|
||||
if (err || result === null) {
|
||||
callback(err, result);
|
||||
return;
|
||||
}
|
||||
|
||||
nextFunction(self, callback);
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) {
|
||||
// Ensure we kill the cursor on the server
|
||||
self.kill(() =>
|
||||
// Set cursor in dead and notified state
|
||||
setCursorDeadAndNotified(self, callback)
|
||||
);
|
||||
} else if (
|
||||
self.cursorState.cursorIndex === self.cursorState.documents.length &&
|
||||
!Long.ZERO.equals(self.cursorState.cursorId)
|
||||
) {
|
||||
// Ensure an empty cursor state
|
||||
self.cursorState.documents = [];
|
||||
self.cursorState.cursorIndex = 0;
|
||||
|
||||
// Check if topology is destroyed
|
||||
if (self.topology.isDestroyed())
|
||||
return callback(
|
||||
new MongoNetworkError('connection destroyed, not possible to instantiate cursor')
|
||||
);
|
||||
|
||||
// Check if connection is dead and return if not possible to
|
||||
// execute a getMore on this connection
|
||||
if (isConnectionDead(self, callback)) return;
|
||||
|
||||
// Execute the next get more
|
||||
self._getMore(function(err, doc, connection) {
|
||||
if (err) {
|
||||
return handleCallback(callback, err);
|
||||
}
|
||||
|
||||
// Save the returned connection to ensure all getMore's fire over the same connection
|
||||
self.connection = connection;
|
||||
|
||||
// Tailable cursor getMore result, notify owner about it
|
||||
// No attempt is made here to retry, this is left to the user of the
|
||||
// core module to handle to keep core simple
|
||||
if (
|
||||
self.cursorState.documents.length === 0 &&
|
||||
self.cmd.tailable &&
|
||||
Long.ZERO.equals(self.cursorState.cursorId)
|
||||
) {
|
||||
// No more documents in the tailed cursor
|
||||
return handleCallback(
|
||||
callback,
|
||||
new MongoError({
|
||||
message: 'No more documents in tailed cursor',
|
||||
tailable: self.cmd.tailable,
|
||||
awaitData: self.cmd.awaitData
|
||||
})
|
||||
);
|
||||
} else if (
|
||||
self.cursorState.documents.length === 0 &&
|
||||
self.cmd.tailable &&
|
||||
!Long.ZERO.equals(self.cursorState.cursorId)
|
||||
) {
|
||||
return nextFunction(self, callback);
|
||||
}
|
||||
|
||||
if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) {
|
||||
return setCursorDeadAndNotified(self, callback);
|
||||
}
|
||||
|
||||
nextFunction(self, callback);
|
||||
});
|
||||
} else if (
|
||||
self.cursorState.documents.length === self.cursorState.cursorIndex &&
|
||||
self.cmd.tailable &&
|
||||
Long.ZERO.equals(self.cursorState.cursorId)
|
||||
) {
|
||||
return handleCallback(
|
||||
callback,
|
||||
new MongoError({
|
||||
message: 'No more documents in tailed cursor',
|
||||
tailable: self.cmd.tailable,
|
||||
awaitData: self.cmd.awaitData
|
||||
})
|
||||
);
|
||||
} else if (
|
||||
self.cursorState.documents.length === self.cursorState.cursorIndex &&
|
||||
Long.ZERO.equals(self.cursorState.cursorId)
|
||||
) {
|
||||
setCursorDeadAndNotified(self, callback);
|
||||
} else {
|
||||
if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) {
|
||||
// Ensure we kill the cursor on the server
|
||||
self.kill(() =>
|
||||
// Set cursor in dead and notified state
|
||||
setCursorDeadAndNotified(self, callback)
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Increment the current cursor limit
|
||||
self.cursorState.currentLimit += 1;
|
||||
|
||||
// Get the document
|
||||
let doc = self.cursorState.documents[self.cursorState.cursorIndex++];
|
||||
|
||||
// Doc overflow
|
||||
if (!doc || doc.$err) {
|
||||
// Ensure we kill the cursor on the server
|
||||
self.kill(() =>
|
||||
// Set cursor in dead and notified state
|
||||
setCursorDeadAndNotified(self, function() {
|
||||
handleCallback(callback, new MongoError(doc ? doc.$err : undefined));
|
||||
})
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Transform the doc with passed in transformation method if provided
|
||||
if (self.cursorState.transforms && typeof self.cursorState.transforms.doc === 'function') {
|
||||
doc = self.cursorState.transforms.doc(doc);
|
||||
}
|
||||
|
||||
// Return the document
|
||||
handleCallback(callback, null, doc);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
CursorState,
|
||||
CoreCursor
|
||||
};
|
||||
351
node_modules/mongodb/lib/core/error.js
generated
vendored
Normal file
351
node_modules/mongodb/lib/core/error.js
generated
vendored
Normal file
@@ -0,0 +1,351 @@
|
||||
'use strict';
|
||||
|
||||
const kErrorLabels = Symbol('errorLabels');
|
||||
|
||||
/**
|
||||
* Creates a new MongoError
|
||||
*
|
||||
* @augments Error
|
||||
* @param {Error|string|object} message The error message
|
||||
* @property {string} message The error message
|
||||
* @property {string} stack The error call stack
|
||||
*/
|
||||
class MongoError extends Error {
|
||||
constructor(message) {
|
||||
if (message instanceof Error) {
|
||||
super(message.message);
|
||||
this.stack = message.stack;
|
||||
} else {
|
||||
if (typeof message === 'string') {
|
||||
super(message);
|
||||
} else {
|
||||
super(message.message || message.errmsg || message.$err || 'n/a');
|
||||
if (message.errorLabels) {
|
||||
this[kErrorLabels] = new Set(message.errorLabels);
|
||||
}
|
||||
|
||||
for (var name in message) {
|
||||
if (name === 'errorLabels' || name === 'errmsg') {
|
||||
continue;
|
||||
}
|
||||
|
||||
this[name] = message[name];
|
||||
}
|
||||
}
|
||||
|
||||
Error.captureStackTrace(this, this.constructor);
|
||||
}
|
||||
|
||||
this.name = 'MongoError';
|
||||
}
|
||||
|
||||
/**
|
||||
* Legacy name for server error responses
|
||||
*/
|
||||
get errmsg() {
|
||||
return this.message;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new MongoError object
|
||||
*
|
||||
* @param {Error|string|object} options The options used to create the error.
|
||||
* @return {MongoError} A MongoError instance
|
||||
* @deprecated Use `new MongoError()` instead.
|
||||
*/
|
||||
static create(options) {
|
||||
return new MongoError(options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks the error to see if it has an error label
|
||||
* @param {string} label The error label to check for
|
||||
* @returns {boolean} returns true if the error has the provided error label
|
||||
*/
|
||||
hasErrorLabel(label) {
|
||||
if (this[kErrorLabels] == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return this[kErrorLabels].has(label);
|
||||
}
|
||||
|
||||
addErrorLabel(label) {
|
||||
if (this[kErrorLabels] == null) {
|
||||
this[kErrorLabels] = new Set();
|
||||
}
|
||||
|
||||
this[kErrorLabels].add(label);
|
||||
}
|
||||
|
||||
get errorLabels() {
|
||||
return this[kErrorLabels] ? Array.from(this[kErrorLabels]) : [];
|
||||
}
|
||||
}
|
||||
|
||||
const kBeforeHandshake = Symbol('beforeHandshake');
|
||||
function isNetworkErrorBeforeHandshake(err) {
|
||||
return err[kBeforeHandshake] === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* An error indicating an issue with the network, including TCP
|
||||
* errors and timeouts.
|
||||
*
|
||||
* @param {Error|string|object} message The error message
|
||||
* @property {string} message The error message
|
||||
* @property {string} stack The error call stack
|
||||
* @extends MongoError
|
||||
*/
|
||||
class MongoNetworkError extends MongoError {
|
||||
constructor(message, options) {
|
||||
super(message);
|
||||
this.name = 'MongoNetworkError';
|
||||
|
||||
if (options && options.beforeHandshake === true) {
|
||||
this[kBeforeHandshake] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An error indicating a network timeout occurred
|
||||
*
|
||||
* @param {Error|string|object} message The error message
|
||||
* @property {string} message The error message
|
||||
* @property {object} [options.beforeHandshake] Indicates the timeout happened before a connection handshake completed
|
||||
* @extends MongoError
|
||||
*/
|
||||
class MongoNetworkTimeoutError extends MongoNetworkError {
|
||||
constructor(message, options) {
|
||||
super(message, options);
|
||||
this.name = 'MongoNetworkTimeoutError';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An error used when attempting to parse a value (like a connection string)
|
||||
*
|
||||
* @param {Error|string|object} message The error message
|
||||
* @property {string} message The error message
|
||||
* @extends MongoError
|
||||
*/
|
||||
class MongoParseError extends MongoError {
|
||||
constructor(message) {
|
||||
super(message);
|
||||
this.name = 'MongoParseError';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An error signifying a client-side timeout event
|
||||
*
|
||||
* @param {Error|string|object} message The error message
|
||||
* @param {string|object} [reason] The reason the timeout occured
|
||||
* @property {string} message The error message
|
||||
* @property {string} [reason] An optional reason context for the timeout, generally an error saved during flow of monitoring and selecting servers
|
||||
* @extends MongoError
|
||||
*/
|
||||
class MongoTimeoutError extends MongoError {
|
||||
constructor(message, reason) {
|
||||
if (reason && reason.error) {
|
||||
super(reason.error.message || reason.error);
|
||||
} else {
|
||||
super(message);
|
||||
}
|
||||
|
||||
this.name = 'MongoTimeoutError';
|
||||
if (reason) {
|
||||
this.reason = reason;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An error signifying a client-side server selection error
|
||||
*
|
||||
* @param {Error|string|object} message The error message
|
||||
* @param {string|object} [reason] The reason the timeout occured
|
||||
* @property {string} message The error message
|
||||
* @property {string} [reason] An optional reason context for the timeout, generally an error saved during flow of monitoring and selecting servers
|
||||
* @extends MongoError
|
||||
*/
|
||||
class MongoServerSelectionError extends MongoTimeoutError {
|
||||
constructor(message, reason) {
|
||||
super(message, reason);
|
||||
this.name = 'MongoServerSelectionError';
|
||||
}
|
||||
}
|
||||
|
||||
function makeWriteConcernResultObject(input) {
|
||||
const output = Object.assign({}, input);
|
||||
|
||||
if (output.ok === 0) {
|
||||
output.ok = 1;
|
||||
delete output.errmsg;
|
||||
delete output.code;
|
||||
delete output.codeName;
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* An error thrown when the server reports a writeConcernError
|
||||
*
|
||||
* @param {Error|string|object} message The error message
|
||||
* @param {object} result The result document (provided if ok: 1)
|
||||
* @property {string} message The error message
|
||||
* @property {object} [result] The result document (provided if ok: 1)
|
||||
* @extends MongoError
|
||||
*/
|
||||
class MongoWriteConcernError extends MongoError {
|
||||
constructor(message, result) {
|
||||
super(message);
|
||||
this.name = 'MongoWriteConcernError';
|
||||
|
||||
if (result && Array.isArray(result.errorLabels)) {
|
||||
this[kErrorLabels] = new Set(result.errorLabels);
|
||||
}
|
||||
|
||||
if (result != null) {
|
||||
this.result = makeWriteConcernResultObject(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// see: https://github.com/mongodb/specifications/blob/master/source/retryable-writes/retryable-writes.rst#terms
|
||||
const RETRYABLE_ERROR_CODES = new Set([
|
||||
6, // HostUnreachable
|
||||
7, // HostNotFound
|
||||
89, // NetworkTimeout
|
||||
91, // ShutdownInProgress
|
||||
189, // PrimarySteppedDown
|
||||
9001, // SocketException
|
||||
10107, // NotMaster
|
||||
11600, // InterruptedAtShutdown
|
||||
11602, // InterruptedDueToReplStateChange
|
||||
13435, // NotMasterNoSlaveOk
|
||||
13436 // NotMasterOrSecondary
|
||||
]);
|
||||
|
||||
const RETRYABLE_WRITE_ERROR_CODES = new Set([
|
||||
11600, // InterruptedAtShutdown
|
||||
11602, // InterruptedDueToReplStateChange
|
||||
10107, // NotMaster
|
||||
13435, // NotMasterNoSlaveOk
|
||||
13436, // NotMasterOrSecondary
|
||||
189, // PrimarySteppedDown
|
||||
91, // ShutdownInProgress
|
||||
7, // HostNotFound
|
||||
6, // HostUnreachable
|
||||
89, // NetworkTimeout
|
||||
9001, // SocketException
|
||||
262 // ExceededTimeLimit
|
||||
]);
|
||||
|
||||
function isRetryableWriteError(error) {
|
||||
if (error instanceof MongoWriteConcernError) {
|
||||
return (
|
||||
RETRYABLE_WRITE_ERROR_CODES.has(error.code) ||
|
||||
RETRYABLE_WRITE_ERROR_CODES.has(error.result.code)
|
||||
);
|
||||
}
|
||||
|
||||
return RETRYABLE_WRITE_ERROR_CODES.has(error.code);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether an error is something the driver should attempt to retry
|
||||
*
|
||||
* @ignore
|
||||
* @param {MongoError|Error} error
|
||||
*/
|
||||
function isRetryableError(error) {
|
||||
return (
|
||||
RETRYABLE_ERROR_CODES.has(error.code) ||
|
||||
error instanceof MongoNetworkError ||
|
||||
error.message.match(/not master/) ||
|
||||
error.message.match(/node is recovering/)
|
||||
);
|
||||
}
|
||||
|
||||
const SDAM_RECOVERING_CODES = new Set([
|
||||
91, // ShutdownInProgress
|
||||
189, // PrimarySteppedDown
|
||||
11600, // InterruptedAtShutdown
|
||||
11602, // InterruptedDueToReplStateChange
|
||||
13436 // NotMasterOrSecondary
|
||||
]);
|
||||
|
||||
const SDAM_NOTMASTER_CODES = new Set([
|
||||
10107, // NotMaster
|
||||
13435 // NotMasterNoSlaveOk
|
||||
]);
|
||||
|
||||
const SDAM_NODE_SHUTTING_DOWN_ERROR_CODES = new Set([
|
||||
11600, // InterruptedAtShutdown
|
||||
91 // ShutdownInProgress
|
||||
]);
|
||||
|
||||
function isRecoveringError(err) {
|
||||
if (err.code && SDAM_RECOVERING_CODES.has(err.code)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return err.message.match(/not master or secondary/) || err.message.match(/node is recovering/);
|
||||
}
|
||||
|
||||
function isNotMasterError(err) {
|
||||
if (err.code && SDAM_NOTMASTER_CODES.has(err.code)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (isRecoveringError(err)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return err.message.match(/not master/);
|
||||
}
|
||||
|
||||
function isNodeShuttingDownError(err) {
|
||||
return err.code && SDAM_NODE_SHUTTING_DOWN_ERROR_CODES.has(err.code);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether SDAM can recover from a given error. If it cannot
|
||||
* then the pool will be cleared, and server state will completely reset
|
||||
* locally.
|
||||
*
|
||||
* @ignore
|
||||
* @see https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#not-master-and-node-is-recovering
|
||||
* @param {MongoError|Error} error
|
||||
*/
|
||||
function isSDAMUnrecoverableError(error) {
|
||||
// NOTE: null check is here for a strictly pre-CMAP world, a timeout or
|
||||
// close event are considered unrecoverable
|
||||
if (error instanceof MongoParseError || error == null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (isRecoveringError(error) || isNotMasterError(error)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
MongoError,
|
||||
MongoNetworkError,
|
||||
MongoNetworkTimeoutError,
|
||||
MongoParseError,
|
||||
MongoTimeoutError,
|
||||
MongoServerSelectionError,
|
||||
MongoWriteConcernError,
|
||||
isRetryableError,
|
||||
isSDAMUnrecoverableError,
|
||||
isNodeShuttingDownError,
|
||||
isRetryableWriteError,
|
||||
isNetworkErrorBeforeHandshake
|
||||
};
|
||||
50
node_modules/mongodb/lib/core/index.js
generated
vendored
Normal file
50
node_modules/mongodb/lib/core/index.js
generated
vendored
Normal file
@@ -0,0 +1,50 @@
|
||||
'use strict';
|
||||
|
||||
let BSON = require('bson');
|
||||
const require_optional = require('require_optional');
|
||||
const EJSON = require('./utils').retrieveEJSON();
|
||||
|
||||
try {
|
||||
// Attempt to grab the native BSON parser
|
||||
const BSONNative = require_optional('bson-ext');
|
||||
// If we got the native parser, use it instead of the
|
||||
// Javascript one
|
||||
if (BSONNative) {
|
||||
BSON = BSONNative;
|
||||
}
|
||||
} catch (err) {} // eslint-disable-line
|
||||
|
||||
module.exports = {
|
||||
// Errors
|
||||
MongoError: require('./error').MongoError,
|
||||
MongoNetworkError: require('./error').MongoNetworkError,
|
||||
MongoParseError: require('./error').MongoParseError,
|
||||
MongoTimeoutError: require('./error').MongoTimeoutError,
|
||||
MongoServerSelectionError: require('./error').MongoServerSelectionError,
|
||||
MongoWriteConcernError: require('./error').MongoWriteConcernError,
|
||||
// Core
|
||||
Connection: require('./connection/connection'),
|
||||
Server: require('./topologies/server'),
|
||||
ReplSet: require('./topologies/replset'),
|
||||
Mongos: require('./topologies/mongos'),
|
||||
Logger: require('./connection/logger'),
|
||||
Cursor: require('./cursor').CoreCursor,
|
||||
ReadPreference: require('./topologies/read_preference'),
|
||||
Sessions: require('./sessions'),
|
||||
BSON: BSON,
|
||||
EJSON: EJSON,
|
||||
Topology: require('./sdam/topology').Topology,
|
||||
// Raw operations
|
||||
Query: require('./connection/commands').Query,
|
||||
// Auth mechanisms
|
||||
MongoCredentials: require('./auth/mongo_credentials').MongoCredentials,
|
||||
defaultAuthProviders: require('./auth/defaultAuthProviders').defaultAuthProviders,
|
||||
MongoCR: require('./auth/mongocr'),
|
||||
X509: require('./auth/x509'),
|
||||
Plain: require('./auth/plain'),
|
||||
GSSAPI: require('./auth/gssapi'),
|
||||
ScramSHA1: require('./auth/scram').ScramSHA1,
|
||||
ScramSHA256: require('./auth/scram').ScramSHA256,
|
||||
// Utilities
|
||||
parseConnectionString: require('./uri_parser')
|
||||
};
|
||||
67
node_modules/mongodb/lib/core/sdam/common.js
generated
vendored
Normal file
67
node_modules/mongodb/lib/core/sdam/common.js
generated
vendored
Normal file
@@ -0,0 +1,67 @@
|
||||
'use strict';
|
||||
|
||||
// shared state names
|
||||
const STATE_CLOSING = 'closing';
|
||||
const STATE_CLOSED = 'closed';
|
||||
const STATE_CONNECTING = 'connecting';
|
||||
const STATE_CONNECTED = 'connected';
|
||||
|
||||
// An enumeration of topology types we know about
|
||||
const TopologyType = {
|
||||
Single: 'Single',
|
||||
ReplicaSetNoPrimary: 'ReplicaSetNoPrimary',
|
||||
ReplicaSetWithPrimary: 'ReplicaSetWithPrimary',
|
||||
Sharded: 'Sharded',
|
||||
Unknown: 'Unknown'
|
||||
};
|
||||
|
||||
// An enumeration of server types we know about
|
||||
const ServerType = {
|
||||
Standalone: 'Standalone',
|
||||
Mongos: 'Mongos',
|
||||
PossiblePrimary: 'PossiblePrimary',
|
||||
RSPrimary: 'RSPrimary',
|
||||
RSSecondary: 'RSSecondary',
|
||||
RSArbiter: 'RSArbiter',
|
||||
RSOther: 'RSOther',
|
||||
RSGhost: 'RSGhost',
|
||||
Unknown: 'Unknown'
|
||||
};
|
||||
|
||||
// helper to get a server's type that works for both legacy and unified topologies
|
||||
function serverType(server) {
|
||||
let description = server.s.description || server.s.serverDescription;
|
||||
if (description.topologyType === TopologyType.Single) return description.servers[0].type;
|
||||
return description.type;
|
||||
}
|
||||
|
||||
const TOPOLOGY_DEFAULTS = {
|
||||
useUnifiedTopology: true,
|
||||
localThresholdMS: 15,
|
||||
serverSelectionTimeoutMS: 30000,
|
||||
heartbeatFrequencyMS: 10000,
|
||||
minHeartbeatFrequencyMS: 500
|
||||
};
|
||||
|
||||
function drainTimerQueue(queue) {
|
||||
queue.forEach(clearTimeout);
|
||||
queue.clear();
|
||||
}
|
||||
|
||||
function clearAndRemoveTimerFrom(timer, timers) {
|
||||
clearTimeout(timer);
|
||||
return timers.delete(timer);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
STATE_CLOSING,
|
||||
STATE_CLOSED,
|
||||
STATE_CONNECTING,
|
||||
STATE_CONNECTED,
|
||||
TOPOLOGY_DEFAULTS,
|
||||
TopologyType,
|
||||
ServerType,
|
||||
serverType,
|
||||
drainTimerQueue,
|
||||
clearAndRemoveTimerFrom
|
||||
};
|
||||
124
node_modules/mongodb/lib/core/sdam/events.js
generated
vendored
Normal file
124
node_modules/mongodb/lib/core/sdam/events.js
generated
vendored
Normal file
@@ -0,0 +1,124 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Published when server description changes, but does NOT include changes to the RTT.
|
||||
*
|
||||
* @property {Object} topologyId A unique identifier for the topology
|
||||
* @property {ServerAddress} address The address (host/port pair) of the server
|
||||
* @property {ServerDescription} previousDescription The previous server description
|
||||
* @property {ServerDescription} newDescription The new server description
|
||||
*/
|
||||
class ServerDescriptionChangedEvent {
|
||||
constructor(topologyId, address, previousDescription, newDescription) {
|
||||
Object.assign(this, { topologyId, address, previousDescription, newDescription });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Published when server is initialized.
|
||||
*
|
||||
* @property {Object} topologyId A unique identifier for the topology
|
||||
* @property {ServerAddress} address The address (host/port pair) of the server
|
||||
*/
|
||||
class ServerOpeningEvent {
|
||||
constructor(topologyId, address) {
|
||||
Object.assign(this, { topologyId, address });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Published when server is closed.
|
||||
*
|
||||
* @property {ServerAddress} address The address (host/port pair) of the server
|
||||
* @property {Object} topologyId A unique identifier for the topology
|
||||
*/
|
||||
class ServerClosedEvent {
|
||||
constructor(topologyId, address) {
|
||||
Object.assign(this, { topologyId, address });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Published when topology description changes.
|
||||
*
|
||||
* @property {Object} topologyId
|
||||
* @property {TopologyDescription} previousDescription The old topology description
|
||||
* @property {TopologyDescription} newDescription The new topology description
|
||||
*/
|
||||
class TopologyDescriptionChangedEvent {
|
||||
constructor(topologyId, previousDescription, newDescription) {
|
||||
Object.assign(this, { topologyId, previousDescription, newDescription });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Published when topology is initialized.
|
||||
*
|
||||
* @param {Object} topologyId A unique identifier for the topology
|
||||
*/
|
||||
class TopologyOpeningEvent {
|
||||
constructor(topologyId) {
|
||||
Object.assign(this, { topologyId });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Published when topology is closed.
|
||||
*
|
||||
* @param {Object} topologyId A unique identifier for the topology
|
||||
*/
|
||||
class TopologyClosedEvent {
|
||||
constructor(topologyId) {
|
||||
Object.assign(this, { topologyId });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fired when the server monitor’s ismaster command is started - immediately before
|
||||
* the ismaster command is serialized into raw BSON and written to the socket.
|
||||
*
|
||||
* @property {Object} connectionId The connection id for the command
|
||||
*/
|
||||
class ServerHeartbeatStartedEvent {
|
||||
constructor(connectionId) {
|
||||
Object.assign(this, { connectionId });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fired when the server monitor’s ismaster succeeds.
|
||||
*
|
||||
* @param {Number} duration The execution time of the event in ms
|
||||
* @param {Object} reply The command reply
|
||||
* @param {Object} connectionId The connection id for the command
|
||||
*/
|
||||
class ServerHeartbeatSucceededEvent {
|
||||
constructor(duration, reply, connectionId) {
|
||||
Object.assign(this, { connectionId, duration, reply });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fired when the server monitor’s ismaster fails, either with an “ok: 0” or a socket exception.
|
||||
*
|
||||
* @param {Number} duration The execution time of the event in ms
|
||||
* @param {MongoError|Object} failure The command failure
|
||||
* @param {Object} connectionId The connection id for the command
|
||||
*/
|
||||
class ServerHeartbeatFailedEvent {
|
||||
constructor(duration, failure, connectionId) {
|
||||
Object.assign(this, { connectionId, duration, failure });
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
ServerDescriptionChangedEvent,
|
||||
ServerOpeningEvent,
|
||||
ServerClosedEvent,
|
||||
TopologyDescriptionChangedEvent,
|
||||
TopologyOpeningEvent,
|
||||
TopologyClosedEvent,
|
||||
ServerHeartbeatStartedEvent,
|
||||
ServerHeartbeatSucceededEvent,
|
||||
ServerHeartbeatFailedEvent
|
||||
};
|
||||
405
node_modules/mongodb/lib/core/sdam/monitor.js
generated
vendored
Normal file
405
node_modules/mongodb/lib/core/sdam/monitor.js
generated
vendored
Normal file
@@ -0,0 +1,405 @@
|
||||
'use strict';
|
||||
|
||||
const ServerType = require('./common').ServerType;
|
||||
const EventEmitter = require('events');
|
||||
const connect = require('../connection/connect');
|
||||
const Connection = require('../../cmap/connection').Connection;
|
||||
const common = require('./common');
|
||||
const makeStateMachine = require('../utils').makeStateMachine;
|
||||
const MongoNetworkError = require('../error').MongoNetworkError;
|
||||
const BSON = require('../connection/utils').retrieveBSON();
|
||||
const makeInterruptableAsyncInterval = require('../../utils').makeInterruptableAsyncInterval;
|
||||
const calculateDurationInMs = require('../../utils').calculateDurationInMs;
|
||||
const now = require('../../utils').now;
|
||||
|
||||
const sdamEvents = require('./events');
|
||||
const ServerHeartbeatStartedEvent = sdamEvents.ServerHeartbeatStartedEvent;
|
||||
const ServerHeartbeatSucceededEvent = sdamEvents.ServerHeartbeatSucceededEvent;
|
||||
const ServerHeartbeatFailedEvent = sdamEvents.ServerHeartbeatFailedEvent;
|
||||
|
||||
const kServer = Symbol('server');
|
||||
const kMonitorId = Symbol('monitorId');
|
||||
const kConnection = Symbol('connection');
|
||||
const kCancellationToken = Symbol('cancellationToken');
|
||||
const kRTTPinger = Symbol('rttPinger');
|
||||
const kRoundTripTime = Symbol('roundTripTime');
|
||||
|
||||
const STATE_CLOSED = common.STATE_CLOSED;
|
||||
const STATE_CLOSING = common.STATE_CLOSING;
|
||||
const STATE_IDLE = 'idle';
|
||||
const STATE_MONITORING = 'monitoring';
|
||||
const stateTransition = makeStateMachine({
|
||||
[STATE_CLOSING]: [STATE_CLOSING, STATE_IDLE, STATE_CLOSED],
|
||||
[STATE_CLOSED]: [STATE_CLOSED, STATE_MONITORING],
|
||||
[STATE_IDLE]: [STATE_IDLE, STATE_MONITORING, STATE_CLOSING],
|
||||
[STATE_MONITORING]: [STATE_MONITORING, STATE_IDLE, STATE_CLOSING]
|
||||
});
|
||||
|
||||
const INVALID_REQUEST_CHECK_STATES = new Set([STATE_CLOSING, STATE_CLOSED, STATE_MONITORING]);
|
||||
|
||||
function isInCloseState(monitor) {
|
||||
return monitor.s.state === STATE_CLOSED || monitor.s.state === STATE_CLOSING;
|
||||
}
|
||||
|
||||
class Monitor extends EventEmitter {
|
||||
constructor(server, options) {
|
||||
super(options);
|
||||
|
||||
this[kServer] = server;
|
||||
this[kConnection] = undefined;
|
||||
this[kCancellationToken] = new EventEmitter();
|
||||
this[kCancellationToken].setMaxListeners(Infinity);
|
||||
this[kMonitorId] = null;
|
||||
this.s = {
|
||||
state: STATE_CLOSED
|
||||
};
|
||||
|
||||
this.address = server.description.address;
|
||||
this.options = Object.freeze({
|
||||
connectTimeoutMS:
|
||||
typeof options.connectionTimeout === 'number'
|
||||
? options.connectionTimeout
|
||||
: typeof options.connectTimeoutMS === 'number'
|
||||
? options.connectTimeoutMS
|
||||
: 10000,
|
||||
heartbeatFrequencyMS:
|
||||
typeof options.heartbeatFrequencyMS === 'number' ? options.heartbeatFrequencyMS : 10000,
|
||||
minHeartbeatFrequencyMS:
|
||||
typeof options.minHeartbeatFrequencyMS === 'number' ? options.minHeartbeatFrequencyMS : 500
|
||||
});
|
||||
|
||||
// TODO: refactor this to pull it directly from the pool, requires new ConnectionPool integration
|
||||
const connectOptions = Object.assign(
|
||||
{
|
||||
id: '<monitor>',
|
||||
host: server.description.host,
|
||||
port: server.description.port,
|
||||
bson: server.s.bson,
|
||||
connectionType: Connection
|
||||
},
|
||||
server.s.options,
|
||||
this.options,
|
||||
|
||||
// force BSON serialization options
|
||||
{
|
||||
raw: false,
|
||||
promoteLongs: true,
|
||||
promoteValues: true,
|
||||
promoteBuffers: true
|
||||
}
|
||||
);
|
||||
|
||||
// ensure no authentication is used for monitoring
|
||||
delete connectOptions.credentials;
|
||||
this.connectOptions = Object.freeze(connectOptions);
|
||||
}
|
||||
|
||||
connect() {
|
||||
if (this.s.state !== STATE_CLOSED) {
|
||||
return;
|
||||
}
|
||||
|
||||
// start
|
||||
const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS;
|
||||
const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS;
|
||||
this[kMonitorId] = makeInterruptableAsyncInterval(monitorServer(this), {
|
||||
interval: heartbeatFrequencyMS,
|
||||
minInterval: minHeartbeatFrequencyMS,
|
||||
immediate: true
|
||||
});
|
||||
}
|
||||
|
||||
requestCheck() {
|
||||
if (INVALID_REQUEST_CHECK_STATES.has(this.s.state)) {
|
||||
return;
|
||||
}
|
||||
|
||||
this[kMonitorId].wake();
|
||||
}
|
||||
|
||||
reset() {
|
||||
if (isInCloseState(this)) {
|
||||
return;
|
||||
}
|
||||
|
||||
stateTransition(this, STATE_CLOSING);
|
||||
resetMonitorState(this);
|
||||
|
||||
// restart monitor
|
||||
stateTransition(this, STATE_IDLE);
|
||||
|
||||
// restart monitoring
|
||||
const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS;
|
||||
const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS;
|
||||
this[kMonitorId] = makeInterruptableAsyncInterval(monitorServer(this), {
|
||||
interval: heartbeatFrequencyMS,
|
||||
minInterval: minHeartbeatFrequencyMS
|
||||
});
|
||||
}
|
||||
|
||||
close() {
|
||||
if (isInCloseState(this)) {
|
||||
return;
|
||||
}
|
||||
|
||||
stateTransition(this, STATE_CLOSING);
|
||||
resetMonitorState(this);
|
||||
|
||||
// close monitor
|
||||
this.emit('close');
|
||||
stateTransition(this, STATE_CLOSED);
|
||||
}
|
||||
}
|
||||
|
||||
function resetMonitorState(monitor) {
|
||||
stateTransition(monitor, STATE_CLOSING);
|
||||
if (monitor[kMonitorId]) {
|
||||
monitor[kMonitorId].stop();
|
||||
monitor[kMonitorId] = null;
|
||||
}
|
||||
|
||||
if (monitor[kRTTPinger]) {
|
||||
monitor[kRTTPinger].close();
|
||||
monitor[kRTTPinger] = undefined;
|
||||
}
|
||||
|
||||
monitor[kCancellationToken].emit('cancel');
|
||||
if (monitor[kMonitorId]) {
|
||||
clearTimeout(monitor[kMonitorId]);
|
||||
monitor[kMonitorId] = undefined;
|
||||
}
|
||||
|
||||
if (monitor[kConnection]) {
|
||||
monitor[kConnection].destroy({ force: true });
|
||||
}
|
||||
}
|
||||
|
||||
function checkServer(monitor, callback) {
|
||||
let start = now();
|
||||
monitor.emit('serverHeartbeatStarted', new ServerHeartbeatStartedEvent(monitor.address));
|
||||
|
||||
function failureHandler(err) {
|
||||
if (monitor[kConnection]) {
|
||||
monitor[kConnection].destroy({ force: true });
|
||||
monitor[kConnection] = undefined;
|
||||
}
|
||||
|
||||
monitor.emit(
|
||||
'serverHeartbeatFailed',
|
||||
new ServerHeartbeatFailedEvent(calculateDurationInMs(start), err, monitor.address)
|
||||
);
|
||||
|
||||
monitor.emit('resetServer', err);
|
||||
monitor.emit('resetConnectionPool');
|
||||
callback(err);
|
||||
}
|
||||
|
||||
if (monitor[kConnection] != null && !monitor[kConnection].closed) {
|
||||
const connectTimeoutMS = monitor.options.connectTimeoutMS;
|
||||
const maxAwaitTimeMS = monitor.options.heartbeatFrequencyMS;
|
||||
const topologyVersion = monitor[kServer].description.topologyVersion;
|
||||
const isAwaitable = topologyVersion != null;
|
||||
|
||||
const cmd = isAwaitable
|
||||
? { ismaster: true, maxAwaitTimeMS, topologyVersion: makeTopologyVersion(topologyVersion) }
|
||||
: { ismaster: true };
|
||||
|
||||
const options = isAwaitable
|
||||
? { socketTimeout: connectTimeoutMS + maxAwaitTimeMS, exhaustAllowed: true }
|
||||
: { socketTimeout: connectTimeoutMS };
|
||||
|
||||
if (isAwaitable && monitor[kRTTPinger] == null) {
|
||||
monitor[kRTTPinger] = new RTTPinger(monitor[kCancellationToken], monitor.connectOptions);
|
||||
}
|
||||
|
||||
monitor[kConnection].command('admin.$cmd', cmd, options, (err, result) => {
|
||||
if (err) {
|
||||
failureHandler(err);
|
||||
return;
|
||||
}
|
||||
|
||||
const isMaster = result.result;
|
||||
const duration = isAwaitable
|
||||
? monitor[kRTTPinger].roundTripTime
|
||||
: calculateDurationInMs(start);
|
||||
|
||||
monitor.emit(
|
||||
'serverHeartbeatSucceeded',
|
||||
new ServerHeartbeatSucceededEvent(duration, isMaster, monitor.address)
|
||||
);
|
||||
|
||||
// if we are using the streaming protocol then we immediately issue another `started`
|
||||
// event, otherwise the "check" is complete and return to the main monitor loop
|
||||
if (isAwaitable && isMaster.topologyVersion) {
|
||||
monitor.emit('serverHeartbeatStarted', new ServerHeartbeatStartedEvent(monitor.address));
|
||||
start = now();
|
||||
} else {
|
||||
if (monitor[kRTTPinger]) {
|
||||
monitor[kRTTPinger].close();
|
||||
monitor[kRTTPinger] = undefined;
|
||||
}
|
||||
|
||||
callback(undefined, isMaster);
|
||||
}
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// connecting does an implicit `ismaster`
|
||||
connect(monitor.connectOptions, monitor[kCancellationToken], (err, conn) => {
|
||||
if (conn && isInCloseState(monitor)) {
|
||||
conn.destroy({ force: true });
|
||||
return;
|
||||
}
|
||||
|
||||
if (err) {
|
||||
monitor[kConnection] = undefined;
|
||||
|
||||
// we already reset the connection pool on network errors in all cases
|
||||
if (!(err instanceof MongoNetworkError)) {
|
||||
monitor.emit('resetConnectionPool');
|
||||
}
|
||||
|
||||
failureHandler(err);
|
||||
return;
|
||||
}
|
||||
|
||||
monitor[kConnection] = conn;
|
||||
monitor.emit(
|
||||
'serverHeartbeatSucceeded',
|
||||
new ServerHeartbeatSucceededEvent(
|
||||
calculateDurationInMs(start),
|
||||
conn.ismaster,
|
||||
monitor.address
|
||||
)
|
||||
);
|
||||
|
||||
callback(undefined, conn.ismaster);
|
||||
});
|
||||
}
|
||||
|
||||
function monitorServer(monitor) {
|
||||
return callback => {
|
||||
stateTransition(monitor, STATE_MONITORING);
|
||||
function done() {
|
||||
if (!isInCloseState(monitor)) {
|
||||
stateTransition(monitor, STATE_IDLE);
|
||||
}
|
||||
|
||||
callback();
|
||||
}
|
||||
|
||||
// TODO: the next line is a legacy event, remove in v4
|
||||
process.nextTick(() => monitor.emit('monitoring', monitor[kServer]));
|
||||
|
||||
checkServer(monitor, (err, isMaster) => {
|
||||
if (err) {
|
||||
// otherwise an error occured on initial discovery, also bail
|
||||
if (monitor[kServer].description.type === ServerType.Unknown) {
|
||||
monitor.emit('resetServer', err);
|
||||
return done();
|
||||
}
|
||||
}
|
||||
|
||||
// if the check indicates streaming is supported, immediately reschedule monitoring
|
||||
if (isMaster && isMaster.topologyVersion) {
|
||||
setTimeout(() => {
|
||||
if (!isInCloseState(monitor)) {
|
||||
monitor[kMonitorId].wake();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
done();
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
function makeTopologyVersion(tv) {
|
||||
return {
|
||||
processId: tv.processId,
|
||||
counter: BSON.Long.fromNumber(tv.counter)
|
||||
};
|
||||
}
|
||||
|
||||
class RTTPinger {
|
||||
constructor(cancellationToken, options) {
|
||||
this[kConnection] = null;
|
||||
this[kCancellationToken] = cancellationToken;
|
||||
this[kRoundTripTime] = 0;
|
||||
this.closed = false;
|
||||
|
||||
const heartbeatFrequencyMS = options.heartbeatFrequencyMS;
|
||||
this[kMonitorId] = setTimeout(() => measureRoundTripTime(this, options), heartbeatFrequencyMS);
|
||||
}
|
||||
|
||||
get roundTripTime() {
|
||||
return this[kRoundTripTime];
|
||||
}
|
||||
|
||||
close() {
|
||||
this.closed = true;
|
||||
|
||||
clearTimeout(this[kMonitorId]);
|
||||
this[kMonitorId] = undefined;
|
||||
|
||||
if (this[kConnection]) {
|
||||
this[kConnection].destroy({ force: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function measureRoundTripTime(rttPinger, options) {
|
||||
const start = now();
|
||||
const cancellationToken = rttPinger[kCancellationToken];
|
||||
const heartbeatFrequencyMS = options.heartbeatFrequencyMS;
|
||||
if (rttPinger.closed) {
|
||||
return;
|
||||
}
|
||||
|
||||
function measureAndReschedule(conn) {
|
||||
if (rttPinger.closed) {
|
||||
conn.destroy({ force: true });
|
||||
return;
|
||||
}
|
||||
|
||||
if (rttPinger[kConnection] == null) {
|
||||
rttPinger[kConnection] = conn;
|
||||
}
|
||||
|
||||
rttPinger[kRoundTripTime] = calculateDurationInMs(start);
|
||||
rttPinger[kMonitorId] = setTimeout(
|
||||
() => measureRoundTripTime(rttPinger, options),
|
||||
heartbeatFrequencyMS
|
||||
);
|
||||
}
|
||||
|
||||
if (rttPinger[kConnection] == null) {
|
||||
connect(options, cancellationToken, (err, conn) => {
|
||||
if (err) {
|
||||
rttPinger[kConnection] = undefined;
|
||||
rttPinger[kRoundTripTime] = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
measureAndReschedule(conn);
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
rttPinger[kConnection].command('admin.$cmd', { ismaster: 1 }, err => {
|
||||
if (err) {
|
||||
rttPinger[kConnection] = undefined;
|
||||
rttPinger[kRoundTripTime] = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
measureAndReschedule();
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
Monitor
|
||||
};
|
||||
564
node_modules/mongodb/lib/core/sdam/server.js
generated
vendored
Normal file
564
node_modules/mongodb/lib/core/sdam/server.js
generated
vendored
Normal file
@@ -0,0 +1,564 @@
|
||||
'use strict';
|
||||
const EventEmitter = require('events');
|
||||
const ConnectionPool = require('../../cmap/connection_pool').ConnectionPool;
|
||||
const CMAP_EVENT_NAMES = require('../../cmap/events').CMAP_EVENT_NAMES;
|
||||
const MongoError = require('../error').MongoError;
|
||||
const relayEvents = require('../utils').relayEvents;
|
||||
const BSON = require('../connection/utils').retrieveBSON();
|
||||
const Logger = require('../connection/logger');
|
||||
const ServerDescription = require('./server_description').ServerDescription;
|
||||
const compareTopologyVersion = require('./server_description').compareTopologyVersion;
|
||||
const ReadPreference = require('../topologies/read_preference');
|
||||
const Monitor = require('./monitor').Monitor;
|
||||
const MongoNetworkError = require('../error').MongoNetworkError;
|
||||
const MongoNetworkTimeoutError = require('../error').MongoNetworkTimeoutError;
|
||||
const collationNotSupported = require('../utils').collationNotSupported;
|
||||
const debugOptions = require('../connection/utils').debugOptions;
|
||||
const isSDAMUnrecoverableError = require('../error').isSDAMUnrecoverableError;
|
||||
const isRetryableWriteError = require('../error').isRetryableWriteError;
|
||||
const isNodeShuttingDownError = require('../error').isNodeShuttingDownError;
|
||||
const isNetworkErrorBeforeHandshake = require('../error').isNetworkErrorBeforeHandshake;
|
||||
const maxWireVersion = require('../utils').maxWireVersion;
|
||||
const makeStateMachine = require('../utils').makeStateMachine;
|
||||
const common = require('./common');
|
||||
const ServerType = common.ServerType;
|
||||
const isTransactionCommand = require('../transactions').isTransactionCommand;
|
||||
|
||||
// Used for filtering out fields for logging
|
||||
const DEBUG_FIELDS = [
|
||||
'reconnect',
|
||||
'reconnectTries',
|
||||
'reconnectInterval',
|
||||
'emitError',
|
||||
'cursorFactory',
|
||||
'host',
|
||||
'port',
|
||||
'size',
|
||||
'keepAlive',
|
||||
'keepAliveInitialDelay',
|
||||
'noDelay',
|
||||
'connectionTimeout',
|
||||
'checkServerIdentity',
|
||||
'socketTimeout',
|
||||
'ssl',
|
||||
'ca',
|
||||
'crl',
|
||||
'cert',
|
||||
'key',
|
||||
'rejectUnauthorized',
|
||||
'promoteLongs',
|
||||
'promoteValues',
|
||||
'promoteBuffers',
|
||||
'servername'
|
||||
];
|
||||
|
||||
const STATE_CLOSING = common.STATE_CLOSING;
|
||||
const STATE_CLOSED = common.STATE_CLOSED;
|
||||
const STATE_CONNECTING = common.STATE_CONNECTING;
|
||||
const STATE_CONNECTED = common.STATE_CONNECTED;
|
||||
const stateTransition = makeStateMachine({
|
||||
[STATE_CLOSED]: [STATE_CLOSED, STATE_CONNECTING],
|
||||
[STATE_CONNECTING]: [STATE_CONNECTING, STATE_CLOSING, STATE_CONNECTED, STATE_CLOSED],
|
||||
[STATE_CONNECTED]: [STATE_CONNECTED, STATE_CLOSING, STATE_CLOSED],
|
||||
[STATE_CLOSING]: [STATE_CLOSING, STATE_CLOSED]
|
||||
});
|
||||
|
||||
const kMonitor = Symbol('monitor');
|
||||
|
||||
/**
|
||||
*
|
||||
* @fires Server#serverHeartbeatStarted
|
||||
* @fires Server#serverHeartbeatSucceeded
|
||||
* @fires Server#serverHeartbeatFailed
|
||||
*/
|
||||
class Server extends EventEmitter {
|
||||
/**
|
||||
* Create a server
|
||||
*
|
||||
* @param {ServerDescription} description
|
||||
* @param {Object} options
|
||||
*/
|
||||
constructor(description, options, topology) {
|
||||
super();
|
||||
|
||||
this.s = {
|
||||
// the server description
|
||||
description,
|
||||
// a saved copy of the incoming options
|
||||
options,
|
||||
// the server logger
|
||||
logger: Logger('Server', options),
|
||||
// the bson parser
|
||||
bson:
|
||||
options.bson ||
|
||||
new BSON([
|
||||
BSON.Binary,
|
||||
BSON.Code,
|
||||
BSON.DBRef,
|
||||
BSON.Decimal128,
|
||||
BSON.Double,
|
||||
BSON.Int32,
|
||||
BSON.Long,
|
||||
BSON.Map,
|
||||
BSON.MaxKey,
|
||||
BSON.MinKey,
|
||||
BSON.ObjectId,
|
||||
BSON.BSONRegExp,
|
||||
BSON.Symbol,
|
||||
BSON.Timestamp
|
||||
]),
|
||||
// the server state
|
||||
state: STATE_CLOSED,
|
||||
credentials: options.credentials,
|
||||
topology
|
||||
};
|
||||
|
||||
// create the connection pool
|
||||
// NOTE: this used to happen in `connect`, we supported overriding pool options there
|
||||
const poolOptions = Object.assign(
|
||||
{ host: this.description.host, port: this.description.port, bson: this.s.bson },
|
||||
options
|
||||
);
|
||||
|
||||
this.s.pool = new ConnectionPool(poolOptions);
|
||||
relayEvents(
|
||||
this.s.pool,
|
||||
this,
|
||||
['commandStarted', 'commandSucceeded', 'commandFailed'].concat(CMAP_EVENT_NAMES)
|
||||
);
|
||||
|
||||
this.s.pool.on('clusterTimeReceived', clusterTime => {
|
||||
this.clusterTime = clusterTime;
|
||||
});
|
||||
|
||||
// create the monitor
|
||||
this[kMonitor] = new Monitor(this, this.s.options);
|
||||
relayEvents(this[kMonitor], this, [
|
||||
'serverHeartbeatStarted',
|
||||
'serverHeartbeatSucceeded',
|
||||
'serverHeartbeatFailed',
|
||||
|
||||
// legacy events
|
||||
'monitoring'
|
||||
]);
|
||||
|
||||
this[kMonitor].on('resetConnectionPool', () => {
|
||||
this.s.pool.clear();
|
||||
});
|
||||
|
||||
this[kMonitor].on('resetServer', error => markServerUnknown(this, error));
|
||||
this[kMonitor].on('serverHeartbeatSucceeded', event => {
|
||||
this.emit(
|
||||
'descriptionReceived',
|
||||
new ServerDescription(this.description.address, event.reply, {
|
||||
roundTripTime: calculateRoundTripTime(this.description.roundTripTime, event.duration)
|
||||
})
|
||||
);
|
||||
|
||||
if (this.s.state === STATE_CONNECTING) {
|
||||
stateTransition(this, STATE_CONNECTED);
|
||||
this.emit('connect', this);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
get description() {
|
||||
return this.s.description;
|
||||
}
|
||||
|
||||
get name() {
|
||||
return this.s.description.address;
|
||||
}
|
||||
|
||||
get autoEncrypter() {
|
||||
if (this.s.options && this.s.options.autoEncrypter) {
|
||||
return this.s.options.autoEncrypter;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initiate server connect
|
||||
*/
|
||||
connect() {
|
||||
if (this.s.state !== STATE_CLOSED) {
|
||||
return;
|
||||
}
|
||||
|
||||
stateTransition(this, STATE_CONNECTING);
|
||||
this[kMonitor].connect();
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroy the server connection
|
||||
*
|
||||
* @param {object} [options] Optional settings
|
||||
* @param {Boolean} [options.force=false] Force destroy the pool
|
||||
*/
|
||||
destroy(options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = Object.assign({}, { force: false }, options);
|
||||
|
||||
if (this.s.state === STATE_CLOSED) {
|
||||
if (typeof callback === 'function') {
|
||||
callback();
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
stateTransition(this, STATE_CLOSING);
|
||||
|
||||
this[kMonitor].close();
|
||||
this.s.pool.close(options, err => {
|
||||
stateTransition(this, STATE_CLOSED);
|
||||
this.emit('closed');
|
||||
if (typeof callback === 'function') {
|
||||
callback(err);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Immediately schedule monitoring of this server. If there already an attempt being made
|
||||
* this will be a no-op.
|
||||
*/
|
||||
requestCheck() {
|
||||
this[kMonitor].requestCheck();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a command
|
||||
*
|
||||
* @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)
|
||||
* @param {object} cmd The command hash
|
||||
* @param {object} [options] Optional settings
|
||||
* @param {ReadPreference} [options.readPreference] Specify read preference if command supports it
|
||||
* @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.
|
||||
* @param {Boolean} [options.checkKeys=false] Specify if the bson parser should validate keys.
|
||||
* @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
|
||||
* @param {Boolean} [options.fullResult=false] Return the full envelope instead of just the result document.
|
||||
* @param {ClientSession} [options.session] Session to use for the operation
|
||||
* @param {opResultCallback} callback A callback function
|
||||
*/
|
||||
command(ns, cmd, options, callback) {
|
||||
if (typeof options === 'function') {
|
||||
(callback = options), (options = {}), (options = options || {});
|
||||
}
|
||||
|
||||
if (this.s.state === STATE_CLOSING || this.s.state === STATE_CLOSED) {
|
||||
callback(new MongoError('server is closed'));
|
||||
return;
|
||||
}
|
||||
|
||||
const error = basicReadValidations(this, options);
|
||||
if (error) {
|
||||
return callback(error);
|
||||
}
|
||||
|
||||
// Clone the options
|
||||
options = Object.assign({}, options, { wireProtocolCommand: false });
|
||||
|
||||
// Debug log
|
||||
if (this.s.logger.isDebug()) {
|
||||
this.s.logger.debug(
|
||||
`executing command [${JSON.stringify({
|
||||
ns,
|
||||
cmd,
|
||||
options: debugOptions(DEBUG_FIELDS, options)
|
||||
})}] against ${this.name}`
|
||||
);
|
||||
}
|
||||
|
||||
// error if collation not supported
|
||||
if (collationNotSupported(this, cmd)) {
|
||||
callback(new MongoError(`server ${this.name} does not support collation`));
|
||||
return;
|
||||
}
|
||||
|
||||
this.s.pool.withConnection((err, conn, cb) => {
|
||||
if (err) {
|
||||
markServerUnknown(this, err);
|
||||
return cb(err);
|
||||
}
|
||||
|
||||
conn.command(ns, cmd, options, makeOperationHandler(this, conn, cmd, options, cb));
|
||||
}, callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a query against the server
|
||||
*
|
||||
* @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)
|
||||
* @param {object} cmd The command document for the query
|
||||
* @param {object} options Optional settings
|
||||
* @param {function} callback
|
||||
*/
|
||||
query(ns, cmd, cursorState, options, callback) {
|
||||
if (this.s.state === STATE_CLOSING || this.s.state === STATE_CLOSED) {
|
||||
callback(new MongoError('server is closed'));
|
||||
return;
|
||||
}
|
||||
|
||||
this.s.pool.withConnection((err, conn, cb) => {
|
||||
if (err) {
|
||||
markServerUnknown(this, err);
|
||||
return cb(err);
|
||||
}
|
||||
|
||||
conn.query(ns, cmd, cursorState, options, makeOperationHandler(this, conn, cmd, options, cb));
|
||||
}, callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a `getMore` against the server
|
||||
*
|
||||
* @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)
|
||||
* @param {object} cursorState State data associated with the cursor calling this method
|
||||
* @param {object} options Optional settings
|
||||
* @param {function} callback
|
||||
*/
|
||||
getMore(ns, cursorState, batchSize, options, callback) {
|
||||
if (this.s.state === STATE_CLOSING || this.s.state === STATE_CLOSED) {
|
||||
callback(new MongoError('server is closed'));
|
||||
return;
|
||||
}
|
||||
|
||||
this.s.pool.withConnection((err, conn, cb) => {
|
||||
if (err) {
|
||||
markServerUnknown(this, err);
|
||||
return cb(err);
|
||||
}
|
||||
|
||||
conn.getMore(
|
||||
ns,
|
||||
cursorState,
|
||||
batchSize,
|
||||
options,
|
||||
makeOperationHandler(this, conn, null, options, cb)
|
||||
);
|
||||
}, callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a `killCursors` command against the server
|
||||
*
|
||||
* @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)
|
||||
* @param {object} cursorState State data associated with the cursor calling this method
|
||||
* @param {function} callback
|
||||
*/
|
||||
killCursors(ns, cursorState, callback) {
|
||||
if (this.s.state === STATE_CLOSING || this.s.state === STATE_CLOSED) {
|
||||
if (typeof callback === 'function') {
|
||||
callback(new MongoError('server is closed'));
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
this.s.pool.withConnection((err, conn, cb) => {
|
||||
if (err) {
|
||||
markServerUnknown(this, err);
|
||||
return cb(err);
|
||||
}
|
||||
|
||||
conn.killCursors(ns, cursorState, makeOperationHandler(this, conn, null, undefined, cb));
|
||||
}, callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert one or more documents
|
||||
* @method
|
||||
* @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)
|
||||
* @param {array} ops An array of documents to insert
|
||||
* @param {boolean} [options.ordered=true] Execute in order or out of order
|
||||
* @param {object} [options.writeConcern={}] Write concern for the operation
|
||||
* @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.
|
||||
* @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
|
||||
* @param {ClientSession} [options.session] Session to use for the operation
|
||||
* @param {opResultCallback} callback A callback function
|
||||
*/
|
||||
insert(ns, ops, options, callback) {
|
||||
executeWriteOperation({ server: this, op: 'insert', ns, ops }, options, callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform one or more update operations
|
||||
* @method
|
||||
* @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)
|
||||
* @param {array} ops An array of updates
|
||||
* @param {boolean} [options.ordered=true] Execute in order or out of order
|
||||
* @param {object} [options.writeConcern={}] Write concern for the operation
|
||||
* @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.
|
||||
* @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
|
||||
* @param {ClientSession} [options.session] Session to use for the operation
|
||||
* @param {opResultCallback} callback A callback function
|
||||
*/
|
||||
update(ns, ops, options, callback) {
|
||||
executeWriteOperation({ server: this, op: 'update', ns, ops }, options, callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform one or more remove operations
|
||||
* @method
|
||||
* @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)
|
||||
* @param {array} ops An array of removes
|
||||
* @param {boolean} [options.ordered=true] Execute in order or out of order
|
||||
* @param {object} [options.writeConcern={}] Write concern for the operation
|
||||
* @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.
|
||||
* @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
|
||||
* @param {ClientSession} [options.session] Session to use for the operation
|
||||
* @param {opResultCallback} callback A callback function
|
||||
*/
|
||||
remove(ns, ops, options, callback) {
|
||||
executeWriteOperation({ server: this, op: 'remove', ns, ops }, options, callback);
|
||||
}
|
||||
}
|
||||
|
||||
Object.defineProperty(Server.prototype, 'clusterTime', {
|
||||
get: function() {
|
||||
return this.s.topology.clusterTime;
|
||||
},
|
||||
set: function(clusterTime) {
|
||||
this.s.topology.clusterTime = clusterTime;
|
||||
}
|
||||
});
|
||||
|
||||
function supportsRetryableWrites(server) {
|
||||
return (
|
||||
server.description.maxWireVersion >= 6 &&
|
||||
server.description.logicalSessionTimeoutMinutes &&
|
||||
server.description.type !== ServerType.Standalone
|
||||
);
|
||||
}
|
||||
|
||||
function calculateRoundTripTime(oldRtt, duration) {
|
||||
if (oldRtt === -1) {
|
||||
return duration;
|
||||
}
|
||||
|
||||
const alpha = 0.2;
|
||||
return alpha * duration + (1 - alpha) * oldRtt;
|
||||
}
|
||||
|
||||
function basicReadValidations(server, options) {
|
||||
if (options.readPreference && !(options.readPreference instanceof ReadPreference)) {
|
||||
return new MongoError('readPreference must be an instance of ReadPreference');
|
||||
}
|
||||
}
|
||||
|
||||
function executeWriteOperation(args, options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options || {};
|
||||
|
||||
// TODO: once we drop Node 4, use destructuring either here or in arguments.
|
||||
const server = args.server;
|
||||
const op = args.op;
|
||||
const ns = args.ns;
|
||||
const ops = Array.isArray(args.ops) ? args.ops : [args.ops];
|
||||
|
||||
if (server.s.state === STATE_CLOSING || server.s.state === STATE_CLOSED) {
|
||||
callback(new MongoError('server is closed'));
|
||||
return;
|
||||
}
|
||||
|
||||
if (collationNotSupported(server, options)) {
|
||||
callback(new MongoError(`server ${server.name} does not support collation`));
|
||||
return;
|
||||
}
|
||||
const unacknowledgedWrite = options.writeConcern && options.writeConcern.w === 0;
|
||||
if (unacknowledgedWrite || maxWireVersion(server) < 5) {
|
||||
if ((op === 'update' || op === 'remove') && ops.find(o => o.hint)) {
|
||||
callback(new MongoError(`servers < 3.4 do not support hint on ${op}`));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
server.s.pool.withConnection((err, conn, cb) => {
|
||||
if (err) {
|
||||
markServerUnknown(server, err);
|
||||
return cb(err);
|
||||
}
|
||||
|
||||
conn[op](ns, ops, options, makeOperationHandler(server, conn, ops, options, cb));
|
||||
}, callback);
|
||||
}
|
||||
|
||||
function markServerUnknown(server, error) {
|
||||
if (error instanceof MongoNetworkError && !(error instanceof MongoNetworkTimeoutError)) {
|
||||
server[kMonitor].reset();
|
||||
}
|
||||
|
||||
server.emit(
|
||||
'descriptionReceived',
|
||||
new ServerDescription(server.description.address, null, {
|
||||
error,
|
||||
topologyVersion:
|
||||
error && error.topologyVersion ? error.topologyVersion : server.description.topologyVersion
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
function connectionIsStale(pool, connection) {
|
||||
return connection.generation !== pool.generation;
|
||||
}
|
||||
|
||||
function shouldHandleStateChangeError(server, err) {
|
||||
const etv = err.topologyVersion;
|
||||
const stv = server.description.topologyVersion;
|
||||
|
||||
return compareTopologyVersion(stv, etv) < 0;
|
||||
}
|
||||
|
||||
function inActiveTransaction(session, cmd) {
|
||||
return session && session.inTransaction() && !isTransactionCommand(cmd);
|
||||
}
|
||||
|
||||
function makeOperationHandler(server, connection, cmd, options, callback) {
|
||||
const session = options && options.session;
|
||||
|
||||
return function handleOperationResult(err, result) {
|
||||
if (err && !connectionIsStale(server.s.pool, connection)) {
|
||||
if (err instanceof MongoNetworkError) {
|
||||
if (session && !session.hasEnded) {
|
||||
session.serverSession.isDirty = true;
|
||||
}
|
||||
|
||||
if (supportsRetryableWrites(server) && !inActiveTransaction(session, cmd)) {
|
||||
err.addErrorLabel('RetryableWriteError');
|
||||
}
|
||||
|
||||
if (!(err instanceof MongoNetworkTimeoutError) || isNetworkErrorBeforeHandshake(err)) {
|
||||
markServerUnknown(server, err);
|
||||
server.s.pool.clear();
|
||||
}
|
||||
} else {
|
||||
// if pre-4.4 server, then add error label if its a retryable write error
|
||||
if (
|
||||
maxWireVersion(server) < 9 &&
|
||||
isRetryableWriteError(err) &&
|
||||
!inActiveTransaction(session, cmd)
|
||||
) {
|
||||
err.addErrorLabel('RetryableWriteError');
|
||||
}
|
||||
|
||||
if (isSDAMUnrecoverableError(err)) {
|
||||
if (shouldHandleStateChangeError(server, err)) {
|
||||
if (maxWireVersion(server) <= 7 || isNodeShuttingDownError(err)) {
|
||||
server.s.pool.clear();
|
||||
}
|
||||
|
||||
markServerUnknown(server, err);
|
||||
process.nextTick(() => server.requestCheck());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
callback(err, result);
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
Server
|
||||
};
|
||||
227
node_modules/mongodb/lib/core/sdam/server_description.js
generated
vendored
Normal file
227
node_modules/mongodb/lib/core/sdam/server_description.js
generated
vendored
Normal file
@@ -0,0 +1,227 @@
|
||||
'use strict';
|
||||
|
||||
const arrayStrictEqual = require('../utils').arrayStrictEqual;
|
||||
const tagsStrictEqual = require('../utils').tagsStrictEqual;
|
||||
const errorStrictEqual = require('../utils').errorStrictEqual;
|
||||
const ServerType = require('./common').ServerType;
|
||||
const now = require('../../utils').now;
|
||||
|
||||
const WRITABLE_SERVER_TYPES = new Set([
|
||||
ServerType.RSPrimary,
|
||||
ServerType.Standalone,
|
||||
ServerType.Mongos
|
||||
]);
|
||||
|
||||
const DATA_BEARING_SERVER_TYPES = new Set([
|
||||
ServerType.RSPrimary,
|
||||
ServerType.RSSecondary,
|
||||
ServerType.Mongos,
|
||||
ServerType.Standalone
|
||||
]);
|
||||
|
||||
const ISMASTER_FIELDS = [
|
||||
'minWireVersion',
|
||||
'maxWireVersion',
|
||||
'maxBsonObjectSize',
|
||||
'maxMessageSizeBytes',
|
||||
'maxWriteBatchSize',
|
||||
'compression',
|
||||
'me',
|
||||
'hosts',
|
||||
'passives',
|
||||
'arbiters',
|
||||
'tags',
|
||||
'setName',
|
||||
'setVersion',
|
||||
'electionId',
|
||||
'primary',
|
||||
'logicalSessionTimeoutMinutes',
|
||||
'saslSupportedMechs',
|
||||
'__nodejs_mock_server__',
|
||||
'$clusterTime'
|
||||
];
|
||||
|
||||
/**
|
||||
* The client's view of a single server, based on the most recent ismaster outcome.
|
||||
*
|
||||
* Internal type, not meant to be directly instantiated
|
||||
*/
|
||||
class ServerDescription {
|
||||
/**
|
||||
* Create a ServerDescription
|
||||
* @param {String} address The address of the server
|
||||
* @param {Object} [ismaster] An optional ismaster response for this server
|
||||
* @param {Object} [options] Optional settings
|
||||
* @param {Number} [options.roundTripTime] The round trip time to ping this server (in ms)
|
||||
* @param {Error} [options.error] An Error used for better reporting debugging
|
||||
* @param {any} [options.topologyVersion] The topologyVersion
|
||||
*/
|
||||
constructor(address, ismaster, options) {
|
||||
options = options || {};
|
||||
ismaster = Object.assign(
|
||||
{
|
||||
minWireVersion: 0,
|
||||
maxWireVersion: 0,
|
||||
hosts: [],
|
||||
passives: [],
|
||||
arbiters: [],
|
||||
tags: []
|
||||
},
|
||||
ismaster
|
||||
);
|
||||
|
||||
this.address = address;
|
||||
this.error = options.error;
|
||||
this.roundTripTime = options.roundTripTime || -1;
|
||||
this.lastUpdateTime = now();
|
||||
this.lastWriteDate = ismaster.lastWrite ? ismaster.lastWrite.lastWriteDate : null;
|
||||
this.opTime = ismaster.lastWrite ? ismaster.lastWrite.opTime : null;
|
||||
this.type = parseServerType(ismaster);
|
||||
this.topologyVersion = options.topologyVersion || ismaster.topologyVersion;
|
||||
|
||||
// direct mappings
|
||||
ISMASTER_FIELDS.forEach(field => {
|
||||
if (typeof ismaster[field] !== 'undefined') this[field] = ismaster[field];
|
||||
});
|
||||
|
||||
// normalize case for hosts
|
||||
if (this.me) this.me = this.me.toLowerCase();
|
||||
this.hosts = this.hosts.map(host => host.toLowerCase());
|
||||
this.passives = this.passives.map(host => host.toLowerCase());
|
||||
this.arbiters = this.arbiters.map(host => host.toLowerCase());
|
||||
}
|
||||
|
||||
get allHosts() {
|
||||
return this.hosts.concat(this.arbiters).concat(this.passives);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return {Boolean} Is this server available for reads
|
||||
*/
|
||||
get isReadable() {
|
||||
return this.type === ServerType.RSSecondary || this.isWritable;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return {Boolean} Is this server data bearing
|
||||
*/
|
||||
get isDataBearing() {
|
||||
return DATA_BEARING_SERVER_TYPES.has(this.type);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return {Boolean} Is this server available for writes
|
||||
*/
|
||||
get isWritable() {
|
||||
return WRITABLE_SERVER_TYPES.has(this.type);
|
||||
}
|
||||
|
||||
get host() {
|
||||
const chopLength = `:${this.port}`.length;
|
||||
return this.address.slice(0, -chopLength);
|
||||
}
|
||||
|
||||
get port() {
|
||||
const port = this.address.split(':').pop();
|
||||
return port ? Number.parseInt(port, 10) : port;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if another `ServerDescription` is equal to this one per the rules defined
|
||||
* in the {@link https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#serverdescription|SDAM spec}
|
||||
*
|
||||
* @param {ServerDescription} other
|
||||
* @return {Boolean}
|
||||
*/
|
||||
equals(other) {
|
||||
const topologyVersionsEqual =
|
||||
this.topologyVersion === other.topologyVersion ||
|
||||
compareTopologyVersion(this.topologyVersion, other.topologyVersion) === 0;
|
||||
|
||||
return (
|
||||
other != null &&
|
||||
errorStrictEqual(this.error, other.error) &&
|
||||
this.type === other.type &&
|
||||
this.minWireVersion === other.minWireVersion &&
|
||||
this.me === other.me &&
|
||||
arrayStrictEqual(this.hosts, other.hosts) &&
|
||||
tagsStrictEqual(this.tags, other.tags) &&
|
||||
this.setName === other.setName &&
|
||||
this.setVersion === other.setVersion &&
|
||||
(this.electionId
|
||||
? other.electionId && this.electionId.equals(other.electionId)
|
||||
: this.electionId === other.electionId) &&
|
||||
this.primary === other.primary &&
|
||||
this.logicalSessionTimeoutMinutes === other.logicalSessionTimeoutMinutes &&
|
||||
topologyVersionsEqual
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses an `ismaster` message and determines the server type
|
||||
*
|
||||
* @param {Object} ismaster The `ismaster` message to parse
|
||||
* @return {ServerType}
|
||||
*/
|
||||
function parseServerType(ismaster) {
|
||||
if (!ismaster || !ismaster.ok) {
|
||||
return ServerType.Unknown;
|
||||
}
|
||||
|
||||
if (ismaster.isreplicaset) {
|
||||
return ServerType.RSGhost;
|
||||
}
|
||||
|
||||
if (ismaster.msg && ismaster.msg === 'isdbgrid') {
|
||||
return ServerType.Mongos;
|
||||
}
|
||||
|
||||
if (ismaster.setName) {
|
||||
if (ismaster.hidden) {
|
||||
return ServerType.RSOther;
|
||||
} else if (ismaster.ismaster) {
|
||||
return ServerType.RSPrimary;
|
||||
} else if (ismaster.secondary) {
|
||||
return ServerType.RSSecondary;
|
||||
} else if (ismaster.arbiterOnly) {
|
||||
return ServerType.RSArbiter;
|
||||
} else {
|
||||
return ServerType.RSOther;
|
||||
}
|
||||
}
|
||||
|
||||
return ServerType.Standalone;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares two topology versions.
|
||||
*
|
||||
* @param {object} lhs
|
||||
* @param {object} rhs
|
||||
* @returns A negative number if `lhs` is older than `rhs`; positive if `lhs` is newer than `rhs`; 0 if they are equivalent.
|
||||
*/
|
||||
function compareTopologyVersion(lhs, rhs) {
|
||||
if (lhs == null || rhs == null) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (lhs.processId.equals(rhs.processId)) {
|
||||
// TODO: handle counters as Longs
|
||||
if (lhs.counter === rhs.counter) {
|
||||
return 0;
|
||||
} else if (lhs.counter < rhs.counter) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
ServerDescription,
|
||||
parseServerType,
|
||||
compareTopologyVersion
|
||||
};
|
||||
238
node_modules/mongodb/lib/core/sdam/server_selection.js
generated
vendored
Normal file
238
node_modules/mongodb/lib/core/sdam/server_selection.js
generated
vendored
Normal file
@@ -0,0 +1,238 @@
|
||||
'use strict';
|
||||
const ServerType = require('./common').ServerType;
|
||||
const TopologyType = require('./common').TopologyType;
|
||||
const ReadPreference = require('../topologies/read_preference');
|
||||
const MongoError = require('../error').MongoError;
|
||||
|
||||
// max staleness constants
|
||||
const IDLE_WRITE_PERIOD = 10000;
|
||||
const SMALLEST_MAX_STALENESS_SECONDS = 90;
|
||||
|
||||
/**
|
||||
* Returns a server selector that selects for writable servers
|
||||
*/
|
||||
function writableServerSelector() {
|
||||
return function(topologyDescription, servers) {
|
||||
return latencyWindowReducer(
|
||||
topologyDescription,
|
||||
servers.filter(s => s.isWritable)
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Reduces the passed in array of servers by the rules of the "Max Staleness" specification
|
||||
* found here: https://github.com/mongodb/specifications/blob/master/source/max-staleness/max-staleness.rst
|
||||
*
|
||||
* @param {ReadPreference} readPreference The read preference providing max staleness guidance
|
||||
* @param {topologyDescription} topologyDescription The topology description
|
||||
* @param {ServerDescription[]} servers The list of server descriptions to be reduced
|
||||
* @return {ServerDescription[]} The list of servers that satisfy the requirements of max staleness
|
||||
*/
|
||||
function maxStalenessReducer(readPreference, topologyDescription, servers) {
|
||||
if (readPreference.maxStalenessSeconds == null || readPreference.maxStalenessSeconds < 0) {
|
||||
return servers;
|
||||
}
|
||||
|
||||
const maxStaleness = readPreference.maxStalenessSeconds;
|
||||
const maxStalenessVariance =
|
||||
(topologyDescription.heartbeatFrequencyMS + IDLE_WRITE_PERIOD) / 1000;
|
||||
if (maxStaleness < maxStalenessVariance) {
|
||||
throw new MongoError(`maxStalenessSeconds must be at least ${maxStalenessVariance} seconds`);
|
||||
}
|
||||
|
||||
if (maxStaleness < SMALLEST_MAX_STALENESS_SECONDS) {
|
||||
throw new MongoError(
|
||||
`maxStalenessSeconds must be at least ${SMALLEST_MAX_STALENESS_SECONDS} seconds`
|
||||
);
|
||||
}
|
||||
|
||||
if (topologyDescription.type === TopologyType.ReplicaSetWithPrimary) {
|
||||
const primary = Array.from(topologyDescription.servers.values()).filter(primaryFilter)[0];
|
||||
return servers.reduce((result, server) => {
|
||||
const stalenessMS =
|
||||
server.lastUpdateTime -
|
||||
server.lastWriteDate -
|
||||
(primary.lastUpdateTime - primary.lastWriteDate) +
|
||||
topologyDescription.heartbeatFrequencyMS;
|
||||
|
||||
const staleness = stalenessMS / 1000;
|
||||
if (staleness <= readPreference.maxStalenessSeconds) result.push(server);
|
||||
return result;
|
||||
}, []);
|
||||
}
|
||||
|
||||
if (topologyDescription.type === TopologyType.ReplicaSetNoPrimary) {
|
||||
if (servers.length === 0) {
|
||||
return servers;
|
||||
}
|
||||
|
||||
const sMax = servers.reduce((max, s) => (s.lastWriteDate > max.lastWriteDate ? s : max));
|
||||
return servers.reduce((result, server) => {
|
||||
const stalenessMS =
|
||||
sMax.lastWriteDate - server.lastWriteDate + topologyDescription.heartbeatFrequencyMS;
|
||||
|
||||
const staleness = stalenessMS / 1000;
|
||||
if (staleness <= readPreference.maxStalenessSeconds) result.push(server);
|
||||
return result;
|
||||
}, []);
|
||||
}
|
||||
|
||||
return servers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether a server's tags match a given set of tags
|
||||
*
|
||||
* @param {String[]} tagSet The requested tag set to match
|
||||
* @param {String[]} serverTags The server's tags
|
||||
*/
|
||||
function tagSetMatch(tagSet, serverTags) {
|
||||
const keys = Object.keys(tagSet);
|
||||
const serverTagKeys = Object.keys(serverTags);
|
||||
for (let i = 0; i < keys.length; ++i) {
|
||||
const key = keys[i];
|
||||
if (serverTagKeys.indexOf(key) === -1 || serverTags[key] !== tagSet[key]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reduces a set of server descriptions based on tags requested by the read preference
|
||||
*
|
||||
* @param {ReadPreference} readPreference The read preference providing the requested tags
|
||||
* @param {ServerDescription[]} servers The list of server descriptions to reduce
|
||||
* @return {ServerDescription[]} The list of servers matching the requested tags
|
||||
*/
|
||||
function tagSetReducer(readPreference, servers) {
|
||||
if (
|
||||
readPreference.tags == null ||
|
||||
(Array.isArray(readPreference.tags) && readPreference.tags.length === 0)
|
||||
) {
|
||||
return servers;
|
||||
}
|
||||
|
||||
for (let i = 0; i < readPreference.tags.length; ++i) {
|
||||
const tagSet = readPreference.tags[i];
|
||||
const serversMatchingTagset = servers.reduce((matched, server) => {
|
||||
if (tagSetMatch(tagSet, server.tags)) matched.push(server);
|
||||
return matched;
|
||||
}, []);
|
||||
|
||||
if (serversMatchingTagset.length) {
|
||||
return serversMatchingTagset;
|
||||
}
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Reduces a list of servers to ensure they fall within an acceptable latency window. This is
|
||||
* further specified in the "Server Selection" specification, found here:
|
||||
* https://github.com/mongodb/specifications/blob/master/source/server-selection/server-selection.rst
|
||||
*
|
||||
* @param {topologyDescription} topologyDescription The topology description
|
||||
* @param {ServerDescription[]} servers The list of servers to reduce
|
||||
* @returns {ServerDescription[]} The servers which fall within an acceptable latency window
|
||||
*/
|
||||
function latencyWindowReducer(topologyDescription, servers) {
|
||||
const low = servers.reduce(
|
||||
(min, server) => (min === -1 ? server.roundTripTime : Math.min(server.roundTripTime, min)),
|
||||
-1
|
||||
);
|
||||
|
||||
const high = low + topologyDescription.localThresholdMS;
|
||||
|
||||
return servers.reduce((result, server) => {
|
||||
if (server.roundTripTime <= high && server.roundTripTime >= low) result.push(server);
|
||||
return result;
|
||||
}, []);
|
||||
}
|
||||
|
||||
// filters
|
||||
function primaryFilter(server) {
|
||||
return server.type === ServerType.RSPrimary;
|
||||
}
|
||||
|
||||
function secondaryFilter(server) {
|
||||
return server.type === ServerType.RSSecondary;
|
||||
}
|
||||
|
||||
function nearestFilter(server) {
|
||||
return server.type === ServerType.RSSecondary || server.type === ServerType.RSPrimary;
|
||||
}
|
||||
|
||||
function knownFilter(server) {
|
||||
return server.type !== ServerType.Unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a function which selects servers based on a provided read preference
|
||||
*
|
||||
* @param {ReadPreference} readPreference The read preference to select with
|
||||
*/
|
||||
function readPreferenceServerSelector(readPreference) {
|
||||
if (!readPreference.isValid()) {
|
||||
throw new TypeError('Invalid read preference specified');
|
||||
}
|
||||
|
||||
return function(topologyDescription, servers) {
|
||||
const commonWireVersion = topologyDescription.commonWireVersion;
|
||||
if (
|
||||
commonWireVersion &&
|
||||
readPreference.minWireVersion &&
|
||||
readPreference.minWireVersion > commonWireVersion
|
||||
) {
|
||||
throw new MongoError(
|
||||
`Minimum wire version '${readPreference.minWireVersion}' required, but found '${commonWireVersion}'`
|
||||
);
|
||||
}
|
||||
|
||||
if (topologyDescription.type === TopologyType.Unknown) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (
|
||||
topologyDescription.type === TopologyType.Single ||
|
||||
topologyDescription.type === TopologyType.Sharded
|
||||
) {
|
||||
return latencyWindowReducer(topologyDescription, servers.filter(knownFilter));
|
||||
}
|
||||
|
||||
const mode = readPreference.mode;
|
||||
if (mode === ReadPreference.PRIMARY) {
|
||||
return servers.filter(primaryFilter);
|
||||
}
|
||||
|
||||
if (mode === ReadPreference.PRIMARY_PREFERRED) {
|
||||
const result = servers.filter(primaryFilter);
|
||||
if (result.length) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
const filter = mode === ReadPreference.NEAREST ? nearestFilter : secondaryFilter;
|
||||
const selectedServers = latencyWindowReducer(
|
||||
topologyDescription,
|
||||
tagSetReducer(
|
||||
readPreference,
|
||||
maxStalenessReducer(readPreference, topologyDescription, servers.filter(filter))
|
||||
)
|
||||
);
|
||||
|
||||
if (mode === ReadPreference.SECONDARY_PREFERRED && selectedServers.length === 0) {
|
||||
return servers.filter(primaryFilter);
|
||||
}
|
||||
|
||||
return selectedServers;
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
writableServerSelector,
|
||||
readPreferenceServerSelector
|
||||
};
|
||||
135
node_modules/mongodb/lib/core/sdam/srv_polling.js
generated
vendored
Normal file
135
node_modules/mongodb/lib/core/sdam/srv_polling.js
generated
vendored
Normal file
@@ -0,0 +1,135 @@
|
||||
'use strict';
|
||||
|
||||
const Logger = require('../connection/logger');
|
||||
const EventEmitter = require('events').EventEmitter;
|
||||
const dns = require('dns');
|
||||
/**
|
||||
* Determines whether a provided address matches the provided parent domain in order
|
||||
* to avoid certain attack vectors.
|
||||
*
|
||||
* @param {String} srvAddress The address to check against a domain
|
||||
* @param {String} parentDomain The domain to check the provided address against
|
||||
* @return {Boolean} Whether the provided address matches the parent domain
|
||||
*/
|
||||
function matchesParentDomain(srvAddress, parentDomain) {
|
||||
const regex = /^.*?\./;
|
||||
const srv = `.${srvAddress.replace(regex, '')}`;
|
||||
const parent = `.${parentDomain.replace(regex, '')}`;
|
||||
return srv.endsWith(parent);
|
||||
}
|
||||
|
||||
class SrvPollingEvent {
|
||||
constructor(srvRecords) {
|
||||
this.srvRecords = srvRecords;
|
||||
}
|
||||
|
||||
addresses() {
|
||||
return new Set(this.srvRecords.map(record => `${record.name}:${record.port}`));
|
||||
}
|
||||
}
|
||||
|
||||
class SrvPoller extends EventEmitter {
|
||||
/**
|
||||
* @param {object} options
|
||||
* @param {string} options.srvHost
|
||||
* @param {number} [options.heartbeatFrequencyMS]
|
||||
* @param {function} [options.logger]
|
||||
* @param {string} [options.loggerLevel]
|
||||
*/
|
||||
constructor(options) {
|
||||
super();
|
||||
|
||||
if (!options || !options.srvHost) {
|
||||
throw new TypeError('options for SrvPoller must exist and include srvHost');
|
||||
}
|
||||
|
||||
this.srvHost = options.srvHost;
|
||||
this.rescanSrvIntervalMS = 60000;
|
||||
this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 10000;
|
||||
this.logger = Logger('srvPoller', options);
|
||||
|
||||
this.haMode = false;
|
||||
this.generation = 0;
|
||||
|
||||
this._timeout = null;
|
||||
}
|
||||
|
||||
get srvAddress() {
|
||||
return `_mongodb._tcp.${this.srvHost}`;
|
||||
}
|
||||
|
||||
get intervalMS() {
|
||||
return this.haMode ? this.heartbeatFrequencyMS : this.rescanSrvIntervalMS;
|
||||
}
|
||||
|
||||
start() {
|
||||
if (!this._timeout) {
|
||||
this.schedule();
|
||||
}
|
||||
}
|
||||
|
||||
stop() {
|
||||
if (this._timeout) {
|
||||
clearTimeout(this._timeout);
|
||||
this.generation += 1;
|
||||
this._timeout = null;
|
||||
}
|
||||
}
|
||||
|
||||
schedule() {
|
||||
clearTimeout(this._timeout);
|
||||
this._timeout = setTimeout(() => this._poll(), this.intervalMS);
|
||||
}
|
||||
|
||||
success(srvRecords) {
|
||||
this.haMode = false;
|
||||
this.schedule();
|
||||
this.emit('srvRecordDiscovery', new SrvPollingEvent(srvRecords));
|
||||
}
|
||||
|
||||
failure(message, obj) {
|
||||
this.logger.warn(message, obj);
|
||||
this.haMode = true;
|
||||
this.schedule();
|
||||
}
|
||||
|
||||
parentDomainMismatch(srvRecord) {
|
||||
this.logger.warn(
|
||||
`parent domain mismatch on SRV record (${srvRecord.name}:${srvRecord.port})`,
|
||||
srvRecord
|
||||
);
|
||||
}
|
||||
|
||||
_poll() {
|
||||
const generation = this.generation;
|
||||
dns.resolveSrv(this.srvAddress, (err, srvRecords) => {
|
||||
if (generation !== this.generation) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (err) {
|
||||
this.failure('DNS error', err);
|
||||
return;
|
||||
}
|
||||
|
||||
const finalAddresses = [];
|
||||
srvRecords.forEach(record => {
|
||||
if (matchesParentDomain(record.name, this.srvHost)) {
|
||||
finalAddresses.push(record);
|
||||
} else {
|
||||
this.parentDomainMismatch(record);
|
||||
}
|
||||
});
|
||||
|
||||
if (!finalAddresses.length) {
|
||||
this.failure('No valid addresses found at host');
|
||||
return;
|
||||
}
|
||||
|
||||
this.success(finalAddresses);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports.SrvPollingEvent = SrvPollingEvent;
|
||||
module.exports.SrvPoller = SrvPoller;
|
||||
1142
node_modules/mongodb/lib/core/sdam/topology.js
generated
vendored
Normal file
1142
node_modules/mongodb/lib/core/sdam/topology.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
441
node_modules/mongodb/lib/core/sdam/topology_description.js
generated
vendored
Normal file
441
node_modules/mongodb/lib/core/sdam/topology_description.js
generated
vendored
Normal file
@@ -0,0 +1,441 @@
|
||||
'use strict';
|
||||
const ServerType = require('./common').ServerType;
|
||||
const ServerDescription = require('./server_description').ServerDescription;
|
||||
const WIRE_CONSTANTS = require('../wireprotocol/constants');
|
||||
const TopologyType = require('./common').TopologyType;
|
||||
|
||||
// contstants related to compatability checks
|
||||
const MIN_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_SERVER_VERSION;
|
||||
const MAX_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_SERVER_VERSION;
|
||||
const MIN_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_WIRE_VERSION;
|
||||
const MAX_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_WIRE_VERSION;
|
||||
|
||||
// Representation of a deployment of servers
|
||||
class TopologyDescription {
|
||||
/**
|
||||
* Create a TopologyDescription
|
||||
*
|
||||
* @param {string} topologyType
|
||||
* @param {Map<string, ServerDescription>} serverDescriptions the a map of address to ServerDescription
|
||||
* @param {string} setName
|
||||
* @param {number} maxSetVersion
|
||||
* @param {ObjectId} maxElectionId
|
||||
*/
|
||||
constructor(
|
||||
topologyType,
|
||||
serverDescriptions,
|
||||
setName,
|
||||
maxSetVersion,
|
||||
maxElectionId,
|
||||
commonWireVersion,
|
||||
options
|
||||
) {
|
||||
options = options || {};
|
||||
|
||||
// TODO: consider assigning all these values to a temporary value `s` which
|
||||
// we use `Object.freeze` on, ensuring the internal state of this type
|
||||
// is immutable.
|
||||
this.type = topologyType || TopologyType.Unknown;
|
||||
this.setName = setName || null;
|
||||
this.maxSetVersion = maxSetVersion || null;
|
||||
this.maxElectionId = maxElectionId || null;
|
||||
this.servers = serverDescriptions || new Map();
|
||||
this.stale = false;
|
||||
this.compatible = true;
|
||||
this.compatibilityError = null;
|
||||
this.logicalSessionTimeoutMinutes = null;
|
||||
this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 0;
|
||||
this.localThresholdMS = options.localThresholdMS || 0;
|
||||
this.commonWireVersion = commonWireVersion || null;
|
||||
|
||||
// save this locally, but don't display when printing the instance out
|
||||
Object.defineProperty(this, 'options', { value: options, enumberable: false });
|
||||
|
||||
// determine server compatibility
|
||||
for (const serverDescription of this.servers.values()) {
|
||||
if (serverDescription.type === ServerType.Unknown) continue;
|
||||
|
||||
if (serverDescription.minWireVersion > MAX_SUPPORTED_WIRE_VERSION) {
|
||||
this.compatible = false;
|
||||
this.compatibilityError = `Server at ${serverDescription.address} requires wire version ${serverDescription.minWireVersion}, but this version of the driver only supports up to ${MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${MAX_SUPPORTED_SERVER_VERSION})`;
|
||||
}
|
||||
|
||||
if (serverDescription.maxWireVersion < MIN_SUPPORTED_WIRE_VERSION) {
|
||||
this.compatible = false;
|
||||
this.compatibilityError = `Server at ${serverDescription.address} reports wire version ${serverDescription.maxWireVersion}, but this version of the driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION}).`;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Whenever a client updates the TopologyDescription from an ismaster response, it MUST set
|
||||
// TopologyDescription.logicalSessionTimeoutMinutes to the smallest logicalSessionTimeoutMinutes
|
||||
// value among ServerDescriptions of all data-bearing server types. If any have a null
|
||||
// logicalSessionTimeoutMinutes, then TopologyDescription.logicalSessionTimeoutMinutes MUST be
|
||||
// set to null.
|
||||
const readableServers = Array.from(this.servers.values()).filter(s => s.isReadable);
|
||||
this.logicalSessionTimeoutMinutes = readableServers.reduce((result, server) => {
|
||||
if (server.logicalSessionTimeoutMinutes == null) return null;
|
||||
if (result == null) return server.logicalSessionTimeoutMinutes;
|
||||
return Math.min(result, server.logicalSessionTimeoutMinutes);
|
||||
}, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a new TopologyDescription based on the SrvPollingEvent
|
||||
* @param {SrvPollingEvent} ev The event
|
||||
*/
|
||||
updateFromSrvPollingEvent(ev) {
|
||||
const newAddresses = ev.addresses();
|
||||
const serverDescriptions = new Map(this.servers);
|
||||
for (const server of this.servers) {
|
||||
if (newAddresses.has(server[0])) {
|
||||
newAddresses.delete(server[0]);
|
||||
} else {
|
||||
serverDescriptions.delete(server[0]);
|
||||
}
|
||||
}
|
||||
|
||||
if (serverDescriptions.size === this.servers.size && newAddresses.size === 0) {
|
||||
return this;
|
||||
}
|
||||
|
||||
for (const address of newAddresses) {
|
||||
serverDescriptions.set(address, new ServerDescription(address));
|
||||
}
|
||||
|
||||
return new TopologyDescription(
|
||||
this.type,
|
||||
serverDescriptions,
|
||||
this.setName,
|
||||
this.maxSetVersion,
|
||||
this.maxElectionId,
|
||||
this.commonWireVersion,
|
||||
this.options,
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a copy of this description updated with a given ServerDescription
|
||||
*
|
||||
* @param {ServerDescription} serverDescription
|
||||
*/
|
||||
update(serverDescription) {
|
||||
const address = serverDescription.address;
|
||||
// NOTE: there are a number of prime targets for refactoring here
|
||||
// once we support destructuring assignments
|
||||
|
||||
// potentially mutated values
|
||||
let topologyType = this.type;
|
||||
let setName = this.setName;
|
||||
let maxSetVersion = this.maxSetVersion;
|
||||
let maxElectionId = this.maxElectionId;
|
||||
let commonWireVersion = this.commonWireVersion;
|
||||
|
||||
if (serverDescription.setName && setName && serverDescription.setName !== setName) {
|
||||
serverDescription = new ServerDescription(address, null);
|
||||
}
|
||||
|
||||
const serverType = serverDescription.type;
|
||||
let serverDescriptions = new Map(this.servers);
|
||||
|
||||
// update common wire version
|
||||
if (serverDescription.maxWireVersion !== 0) {
|
||||
if (commonWireVersion == null) {
|
||||
commonWireVersion = serverDescription.maxWireVersion;
|
||||
} else {
|
||||
commonWireVersion = Math.min(commonWireVersion, serverDescription.maxWireVersion);
|
||||
}
|
||||
}
|
||||
|
||||
// update the actual server description
|
||||
serverDescriptions.set(address, serverDescription);
|
||||
|
||||
if (topologyType === TopologyType.Single) {
|
||||
// once we are defined as single, that never changes
|
||||
return new TopologyDescription(
|
||||
TopologyType.Single,
|
||||
serverDescriptions,
|
||||
setName,
|
||||
maxSetVersion,
|
||||
maxElectionId,
|
||||
commonWireVersion,
|
||||
this.options
|
||||
);
|
||||
}
|
||||
|
||||
if (topologyType === TopologyType.Unknown) {
|
||||
if (serverType === ServerType.Standalone && this.servers.size !== 1) {
|
||||
serverDescriptions.delete(address);
|
||||
} else {
|
||||
topologyType = topologyTypeForServerType(serverType);
|
||||
}
|
||||
}
|
||||
|
||||
if (topologyType === TopologyType.Sharded) {
|
||||
if ([ServerType.Mongos, ServerType.Unknown].indexOf(serverType) === -1) {
|
||||
serverDescriptions.delete(address);
|
||||
}
|
||||
}
|
||||
|
||||
if (topologyType === TopologyType.ReplicaSetNoPrimary) {
|
||||
if ([ServerType.Standalone, ServerType.Mongos].indexOf(serverType) >= 0) {
|
||||
serverDescriptions.delete(address);
|
||||
}
|
||||
|
||||
if (serverType === ServerType.RSPrimary) {
|
||||
const result = updateRsFromPrimary(
|
||||
serverDescriptions,
|
||||
setName,
|
||||
serverDescription,
|
||||
maxSetVersion,
|
||||
maxElectionId
|
||||
);
|
||||
|
||||
(topologyType = result[0]),
|
||||
(setName = result[1]),
|
||||
(maxSetVersion = result[2]),
|
||||
(maxElectionId = result[3]);
|
||||
} else if (
|
||||
[ServerType.RSSecondary, ServerType.RSArbiter, ServerType.RSOther].indexOf(serverType) >= 0
|
||||
) {
|
||||
const result = updateRsNoPrimaryFromMember(serverDescriptions, setName, serverDescription);
|
||||
(topologyType = result[0]), (setName = result[1]);
|
||||
}
|
||||
}
|
||||
|
||||
if (topologyType === TopologyType.ReplicaSetWithPrimary) {
|
||||
if ([ServerType.Standalone, ServerType.Mongos].indexOf(serverType) >= 0) {
|
||||
serverDescriptions.delete(address);
|
||||
topologyType = checkHasPrimary(serverDescriptions);
|
||||
} else if (serverType === ServerType.RSPrimary) {
|
||||
const result = updateRsFromPrimary(
|
||||
serverDescriptions,
|
||||
setName,
|
||||
serverDescription,
|
||||
maxSetVersion,
|
||||
maxElectionId
|
||||
);
|
||||
|
||||
(topologyType = result[0]),
|
||||
(setName = result[1]),
|
||||
(maxSetVersion = result[2]),
|
||||
(maxElectionId = result[3]);
|
||||
} else if (
|
||||
[ServerType.RSSecondary, ServerType.RSArbiter, ServerType.RSOther].indexOf(serverType) >= 0
|
||||
) {
|
||||
topologyType = updateRsWithPrimaryFromMember(
|
||||
serverDescriptions,
|
||||
setName,
|
||||
serverDescription
|
||||
);
|
||||
} else {
|
||||
topologyType = checkHasPrimary(serverDescriptions);
|
||||
}
|
||||
}
|
||||
|
||||
return new TopologyDescription(
|
||||
topologyType,
|
||||
serverDescriptions,
|
||||
setName,
|
||||
maxSetVersion,
|
||||
maxElectionId,
|
||||
commonWireVersion,
|
||||
this.options
|
||||
);
|
||||
}
|
||||
|
||||
get error() {
|
||||
const descriptionsWithError = Array.from(this.servers.values()).filter(sd => sd.error);
|
||||
if (descriptionsWithError.length > 0) {
|
||||
return descriptionsWithError[0].error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if the topology description has any known servers
|
||||
*/
|
||||
get hasKnownServers() {
|
||||
return Array.from(this.servers.values()).some(sd => sd.type !== ServerType.Unknown);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if this topology description has a data-bearing server available.
|
||||
*/
|
||||
get hasDataBearingServers() {
|
||||
return Array.from(this.servers.values()).some(sd => sd.isDataBearing);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if the topology has a definition for the provided address
|
||||
*
|
||||
* @param {String} address
|
||||
* @return {Boolean} Whether the topology knows about this server
|
||||
*/
|
||||
hasServer(address) {
|
||||
return this.servers.has(address);
|
||||
}
|
||||
}
|
||||
|
||||
function topologyTypeForServerType(serverType) {
|
||||
if (serverType === ServerType.Standalone) {
|
||||
return TopologyType.Single;
|
||||
}
|
||||
|
||||
if (serverType === ServerType.Mongos) {
|
||||
return TopologyType.Sharded;
|
||||
}
|
||||
|
||||
if (serverType === ServerType.RSPrimary) {
|
||||
return TopologyType.ReplicaSetWithPrimary;
|
||||
}
|
||||
|
||||
if (serverType === ServerType.RSGhost || serverType === ServerType.Unknown) {
|
||||
return TopologyType.Unknown;
|
||||
}
|
||||
|
||||
return TopologyType.ReplicaSetNoPrimary;
|
||||
}
|
||||
|
||||
function compareObjectId(oid1, oid2) {
|
||||
if (oid1 == null) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (oid2 == null) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (oid1.id instanceof Buffer && oid2.id instanceof Buffer) {
|
||||
const oid1Buffer = oid1.id;
|
||||
const oid2Buffer = oid2.id;
|
||||
return oid1Buffer.compare(oid2Buffer);
|
||||
}
|
||||
|
||||
const oid1String = oid1.toString();
|
||||
const oid2String = oid2.toString();
|
||||
return oid1String.localeCompare(oid2String);
|
||||
}
|
||||
|
||||
function updateRsFromPrimary(
|
||||
serverDescriptions,
|
||||
setName,
|
||||
serverDescription,
|
||||
maxSetVersion,
|
||||
maxElectionId
|
||||
) {
|
||||
setName = setName || serverDescription.setName;
|
||||
if (setName !== serverDescription.setName) {
|
||||
serverDescriptions.delete(serverDescription.address);
|
||||
return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId];
|
||||
}
|
||||
|
||||
const electionId = serverDescription.electionId ? serverDescription.electionId : null;
|
||||
if (serverDescription.setVersion && electionId) {
|
||||
if (maxSetVersion && maxElectionId) {
|
||||
if (
|
||||
maxSetVersion > serverDescription.setVersion ||
|
||||
compareObjectId(maxElectionId, electionId) > 0
|
||||
) {
|
||||
// this primary is stale, we must remove it
|
||||
serverDescriptions.set(
|
||||
serverDescription.address,
|
||||
new ServerDescription(serverDescription.address)
|
||||
);
|
||||
|
||||
return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId];
|
||||
}
|
||||
}
|
||||
|
||||
maxElectionId = serverDescription.electionId;
|
||||
}
|
||||
|
||||
if (
|
||||
serverDescription.setVersion != null &&
|
||||
(maxSetVersion == null || serverDescription.setVersion > maxSetVersion)
|
||||
) {
|
||||
maxSetVersion = serverDescription.setVersion;
|
||||
}
|
||||
|
||||
// We've heard from the primary. Is it the same primary as before?
|
||||
for (const address of serverDescriptions.keys()) {
|
||||
const server = serverDescriptions.get(address);
|
||||
|
||||
if (server.type === ServerType.RSPrimary && server.address !== serverDescription.address) {
|
||||
// Reset old primary's type to Unknown.
|
||||
serverDescriptions.set(address, new ServerDescription(server.address));
|
||||
|
||||
// There can only be one primary
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Discover new hosts from this primary's response.
|
||||
serverDescription.allHosts.forEach(address => {
|
||||
if (!serverDescriptions.has(address)) {
|
||||
serverDescriptions.set(address, new ServerDescription(address));
|
||||
}
|
||||
});
|
||||
|
||||
// Remove hosts not in the response.
|
||||
const currentAddresses = Array.from(serverDescriptions.keys());
|
||||
const responseAddresses = serverDescription.allHosts;
|
||||
currentAddresses
|
||||
.filter(addr => responseAddresses.indexOf(addr) === -1)
|
||||
.forEach(address => {
|
||||
serverDescriptions.delete(address);
|
||||
});
|
||||
|
||||
return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId];
|
||||
}
|
||||
|
||||
function updateRsWithPrimaryFromMember(serverDescriptions, setName, serverDescription) {
|
||||
if (setName == null) {
|
||||
throw new TypeError('setName is required');
|
||||
}
|
||||
|
||||
if (
|
||||
setName !== serverDescription.setName ||
|
||||
(serverDescription.me && serverDescription.address !== serverDescription.me)
|
||||
) {
|
||||
serverDescriptions.delete(serverDescription.address);
|
||||
}
|
||||
|
||||
return checkHasPrimary(serverDescriptions);
|
||||
}
|
||||
|
||||
function updateRsNoPrimaryFromMember(serverDescriptions, setName, serverDescription) {
|
||||
let topologyType = TopologyType.ReplicaSetNoPrimary;
|
||||
|
||||
setName = setName || serverDescription.setName;
|
||||
if (setName !== serverDescription.setName) {
|
||||
serverDescriptions.delete(serverDescription.address);
|
||||
return [topologyType, setName];
|
||||
}
|
||||
|
||||
serverDescription.allHosts.forEach(address => {
|
||||
if (!serverDescriptions.has(address)) {
|
||||
serverDescriptions.set(address, new ServerDescription(address));
|
||||
}
|
||||
});
|
||||
|
||||
if (serverDescription.me && serverDescription.address !== serverDescription.me) {
|
||||
serverDescriptions.delete(serverDescription.address);
|
||||
}
|
||||
|
||||
return [topologyType, setName];
|
||||
}
|
||||
|
||||
function checkHasPrimary(serverDescriptions) {
|
||||
for (const addr of serverDescriptions.keys()) {
|
||||
if (serverDescriptions.get(addr).type === ServerType.RSPrimary) {
|
||||
return TopologyType.ReplicaSetWithPrimary;
|
||||
}
|
||||
}
|
||||
|
||||
return TopologyType.ReplicaSetNoPrimary;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
TopologyDescription
|
||||
};
|
||||
780
node_modules/mongodb/lib/core/sessions.js
generated
vendored
Normal file
780
node_modules/mongodb/lib/core/sessions.js
generated
vendored
Normal file
@@ -0,0 +1,780 @@
|
||||
'use strict';
|
||||
|
||||
const retrieveBSON = require('./connection/utils').retrieveBSON;
|
||||
const EventEmitter = require('events');
|
||||
const BSON = retrieveBSON();
|
||||
const Binary = BSON.Binary;
|
||||
const uuidV4 = require('./utils').uuidV4;
|
||||
const MongoError = require('./error').MongoError;
|
||||
const isRetryableError = require('././error').isRetryableError;
|
||||
const MongoNetworkError = require('./error').MongoNetworkError;
|
||||
const MongoWriteConcernError = require('./error').MongoWriteConcernError;
|
||||
const Transaction = require('./transactions').Transaction;
|
||||
const TxnState = require('./transactions').TxnState;
|
||||
const isPromiseLike = require('./utils').isPromiseLike;
|
||||
const ReadPreference = require('./topologies/read_preference');
|
||||
const maybePromise = require('../utils').maybePromise;
|
||||
const isTransactionCommand = require('./transactions').isTransactionCommand;
|
||||
const resolveClusterTime = require('./topologies/shared').resolveClusterTime;
|
||||
const isSharded = require('./wireprotocol/shared').isSharded;
|
||||
const maxWireVersion = require('./utils').maxWireVersion;
|
||||
const now = require('./../utils').now;
|
||||
const calculateDurationInMs = require('./../utils').calculateDurationInMs;
|
||||
const minWireVersionForShardedTransactions = 8;
|
||||
|
||||
function assertAlive(session, callback) {
|
||||
if (session.serverSession == null) {
|
||||
const error = new MongoError('Cannot use a session that has ended');
|
||||
if (typeof callback === 'function') {
|
||||
callback(error, null);
|
||||
return false;
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Options to pass when creating a Client Session
|
||||
* @typedef {Object} SessionOptions
|
||||
* @property {boolean} [causalConsistency=true] Whether causal consistency should be enabled on this session
|
||||
* @property {TransactionOptions} [defaultTransactionOptions] The default TransactionOptions to use for transactions started on this session.
|
||||
*/
|
||||
|
||||
/**
|
||||
* A BSON document reflecting the lsid of a {@link ClientSession}
|
||||
* @typedef {Object} SessionId
|
||||
*/
|
||||
|
||||
const kServerSession = Symbol('serverSession');
|
||||
|
||||
/**
|
||||
* A class representing a client session on the server
|
||||
* WARNING: not meant to be instantiated directly.
|
||||
* @class
|
||||
* @hideconstructor
|
||||
*/
|
||||
class ClientSession extends EventEmitter {
|
||||
/**
|
||||
* Create a client session.
|
||||
* WARNING: not meant to be instantiated directly
|
||||
*
|
||||
* @param {Topology} topology The current client's topology (Internal Class)
|
||||
* @param {ServerSessionPool} sessionPool The server session pool (Internal Class)
|
||||
* @param {SessionOptions} [options] Optional settings
|
||||
* @param {Object} [clientOptions] Optional settings provided when creating a client in the porcelain driver
|
||||
*/
|
||||
constructor(topology, sessionPool, options, clientOptions) {
|
||||
super();
|
||||
|
||||
if (topology == null) {
|
||||
throw new Error('ClientSession requires a topology');
|
||||
}
|
||||
|
||||
if (sessionPool == null || !(sessionPool instanceof ServerSessionPool)) {
|
||||
throw new Error('ClientSession requires a ServerSessionPool');
|
||||
}
|
||||
|
||||
options = options || {};
|
||||
clientOptions = clientOptions || {};
|
||||
|
||||
this.topology = topology;
|
||||
this.sessionPool = sessionPool;
|
||||
this.hasEnded = false;
|
||||
this.clientOptions = clientOptions;
|
||||
this[kServerSession] = undefined;
|
||||
|
||||
this.supports = {
|
||||
causalConsistency:
|
||||
typeof options.causalConsistency !== 'undefined' ? options.causalConsistency : true
|
||||
};
|
||||
|
||||
this.clusterTime = options.initialClusterTime;
|
||||
|
||||
this.operationTime = null;
|
||||
this.explicit = !!options.explicit;
|
||||
this.owner = options.owner;
|
||||
this.defaultTransactionOptions = Object.assign({}, options.defaultTransactionOptions);
|
||||
this.transaction = new Transaction();
|
||||
}
|
||||
|
||||
/**
|
||||
* The server id associated with this session
|
||||
* @type {SessionId}
|
||||
*/
|
||||
get id() {
|
||||
return this.serverSession.id;
|
||||
}
|
||||
|
||||
get serverSession() {
|
||||
if (this[kServerSession] == null) {
|
||||
this[kServerSession] = this.sessionPool.acquire();
|
||||
}
|
||||
|
||||
return this[kServerSession];
|
||||
}
|
||||
|
||||
/**
|
||||
* Ends this session on the server
|
||||
*
|
||||
* @param {Object} [options] Optional settings. Currently reserved for future use
|
||||
* @param {Function} [callback] Optional callback for completion of this operation
|
||||
*/
|
||||
endSession(options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options || {};
|
||||
|
||||
const session = this;
|
||||
return maybePromise(this, callback, done => {
|
||||
if (session.hasEnded) {
|
||||
return done();
|
||||
}
|
||||
|
||||
function completeEndSession() {
|
||||
// release the server session back to the pool
|
||||
session.sessionPool.release(session.serverSession);
|
||||
session[kServerSession] = undefined;
|
||||
|
||||
// mark the session as ended, and emit a signal
|
||||
session.hasEnded = true;
|
||||
session.emit('ended', session);
|
||||
|
||||
// spec indicates that we should ignore all errors for `endSessions`
|
||||
done();
|
||||
}
|
||||
|
||||
if (session.serverSession && session.inTransaction()) {
|
||||
session.abortTransaction(err => {
|
||||
if (err) return done(err);
|
||||
completeEndSession();
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
completeEndSession();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Advances the operationTime for a ClientSession.
|
||||
*
|
||||
* @param {Timestamp} operationTime the `BSON.Timestamp` of the operation type it is desired to advance to
|
||||
*/
|
||||
advanceOperationTime(operationTime) {
|
||||
if (this.operationTime == null) {
|
||||
this.operationTime = operationTime;
|
||||
return;
|
||||
}
|
||||
|
||||
if (operationTime.greaterThan(this.operationTime)) {
|
||||
this.operationTime = operationTime;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Used to determine if this session equals another
|
||||
* @param {ClientSession} session
|
||||
* @return {boolean} true if the sessions are equal
|
||||
*/
|
||||
equals(session) {
|
||||
if (!(session instanceof ClientSession)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return this.id.id.buffer.equals(session.id.id.buffer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Increment the transaction number on the internal ServerSession
|
||||
*/
|
||||
incrementTransactionNumber() {
|
||||
this.serverSession.txnNumber++;
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {boolean} whether this session is currently in a transaction or not
|
||||
*/
|
||||
inTransaction() {
|
||||
return this.transaction.isActive;
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a new transaction with the given options.
|
||||
*
|
||||
* @param {TransactionOptions} options Options for the transaction
|
||||
*/
|
||||
startTransaction(options) {
|
||||
assertAlive(this);
|
||||
if (this.inTransaction()) {
|
||||
throw new MongoError('Transaction already in progress');
|
||||
}
|
||||
|
||||
const topologyMaxWireVersion = maxWireVersion(this.topology);
|
||||
if (
|
||||
isSharded(this.topology) &&
|
||||
topologyMaxWireVersion != null &&
|
||||
topologyMaxWireVersion < minWireVersionForShardedTransactions
|
||||
) {
|
||||
throw new MongoError('Transactions are not supported on sharded clusters in MongoDB < 4.2.');
|
||||
}
|
||||
|
||||
// increment txnNumber
|
||||
this.incrementTransactionNumber();
|
||||
|
||||
// create transaction state
|
||||
this.transaction = new Transaction(
|
||||
Object.assign({}, this.clientOptions, options || this.defaultTransactionOptions)
|
||||
);
|
||||
|
||||
this.transaction.transition(TxnState.STARTING_TRANSACTION);
|
||||
}
|
||||
|
||||
/**
|
||||
* Commits the currently active transaction in this session.
|
||||
*
|
||||
* @param {Function} [callback] optional callback for completion of this operation
|
||||
* @return {Promise} A promise is returned if no callback is provided
|
||||
*/
|
||||
commitTransaction(callback) {
|
||||
return maybePromise(this, callback, done => endTransaction(this, 'commitTransaction', done));
|
||||
}
|
||||
|
||||
/**
|
||||
* Aborts the currently active transaction in this session.
|
||||
*
|
||||
* @param {Function} [callback] optional callback for completion of this operation
|
||||
* @return {Promise} A promise is returned if no callback is provided
|
||||
*/
|
||||
abortTransaction(callback) {
|
||||
return maybePromise(this, callback, done => endTransaction(this, 'abortTransaction', done));
|
||||
}
|
||||
|
||||
/**
|
||||
* This is here to ensure that ClientSession is never serialized to BSON.
|
||||
* @ignore
|
||||
*/
|
||||
toBSON() {
|
||||
throw new Error('ClientSession cannot be serialized to BSON.');
|
||||
}
|
||||
|
||||
/**
|
||||
* A user provided function to be run within a transaction
|
||||
*
|
||||
* @callback WithTransactionCallback
|
||||
* @param {ClientSession} session The parent session of the transaction running the operation. This should be passed into each operation within the lambda.
|
||||
* @returns {Promise} The resulting Promise of operations run within this transaction
|
||||
*/
|
||||
|
||||
/**
|
||||
* Runs a provided lambda within a transaction, retrying either the commit operation
|
||||
* or entire transaction as needed (and when the error permits) to better ensure that
|
||||
* the transaction can complete successfully.
|
||||
*
|
||||
* IMPORTANT: This method requires the user to return a Promise, all lambdas that do not
|
||||
* return a Promise will result in undefined behavior.
|
||||
*
|
||||
* @param {WithTransactionCallback} fn
|
||||
* @param {TransactionOptions} [options] Optional settings for the transaction
|
||||
*/
|
||||
withTransaction(fn, options) {
|
||||
const startTime = now();
|
||||
return attemptTransaction(this, startTime, fn, options);
|
||||
}
|
||||
}
|
||||
|
||||
const MAX_WITH_TRANSACTION_TIMEOUT = 120000;
|
||||
const UNSATISFIABLE_WRITE_CONCERN_CODE = 100;
|
||||
const UNKNOWN_REPL_WRITE_CONCERN_CODE = 79;
|
||||
const MAX_TIME_MS_EXPIRED_CODE = 50;
|
||||
const NON_DETERMINISTIC_WRITE_CONCERN_ERRORS = new Set([
|
||||
'CannotSatisfyWriteConcern',
|
||||
'UnknownReplWriteConcern',
|
||||
'UnsatisfiableWriteConcern'
|
||||
]);
|
||||
|
||||
function hasNotTimedOut(startTime, max) {
|
||||
return calculateDurationInMs(startTime) < max;
|
||||
}
|
||||
|
||||
function isUnknownTransactionCommitResult(err) {
|
||||
return (
|
||||
isMaxTimeMSExpiredError(err) ||
|
||||
(!NON_DETERMINISTIC_WRITE_CONCERN_ERRORS.has(err.codeName) &&
|
||||
err.code !== UNSATISFIABLE_WRITE_CONCERN_CODE &&
|
||||
err.code !== UNKNOWN_REPL_WRITE_CONCERN_CODE)
|
||||
);
|
||||
}
|
||||
|
||||
function isMaxTimeMSExpiredError(err) {
|
||||
if (err == null) return false;
|
||||
return (
|
||||
err.code === MAX_TIME_MS_EXPIRED_CODE ||
|
||||
(err.writeConcernError && err.writeConcernError.code === MAX_TIME_MS_EXPIRED_CODE)
|
||||
);
|
||||
}
|
||||
|
||||
function attemptTransactionCommit(session, startTime, fn, options) {
|
||||
return session.commitTransaction().catch(err => {
|
||||
if (
|
||||
err instanceof MongoError &&
|
||||
hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT) &&
|
||||
!isMaxTimeMSExpiredError(err)
|
||||
) {
|
||||
if (err.hasErrorLabel('UnknownTransactionCommitResult')) {
|
||||
return attemptTransactionCommit(session, startTime, fn, options);
|
||||
}
|
||||
|
||||
if (err.hasErrorLabel('TransientTransactionError')) {
|
||||
return attemptTransaction(session, startTime, fn, options);
|
||||
}
|
||||
}
|
||||
|
||||
throw err;
|
||||
});
|
||||
}
|
||||
|
||||
const USER_EXPLICIT_TXN_END_STATES = new Set([
|
||||
TxnState.NO_TRANSACTION,
|
||||
TxnState.TRANSACTION_COMMITTED,
|
||||
TxnState.TRANSACTION_ABORTED
|
||||
]);
|
||||
|
||||
function userExplicitlyEndedTransaction(session) {
|
||||
return USER_EXPLICIT_TXN_END_STATES.has(session.transaction.state);
|
||||
}
|
||||
|
||||
function attemptTransaction(session, startTime, fn, options) {
|
||||
session.startTransaction(options);
|
||||
|
||||
let promise;
|
||||
try {
|
||||
promise = fn(session);
|
||||
} catch (err) {
|
||||
promise = Promise.reject(err);
|
||||
}
|
||||
|
||||
if (!isPromiseLike(promise)) {
|
||||
session.abortTransaction();
|
||||
throw new TypeError('Function provided to `withTransaction` must return a Promise');
|
||||
}
|
||||
|
||||
return promise
|
||||
.then(() => {
|
||||
if (userExplicitlyEndedTransaction(session)) {
|
||||
return;
|
||||
}
|
||||
|
||||
return attemptTransactionCommit(session, startTime, fn, options);
|
||||
})
|
||||
.catch(err => {
|
||||
function maybeRetryOrThrow(err) {
|
||||
if (
|
||||
err instanceof MongoError &&
|
||||
err.hasErrorLabel('TransientTransactionError') &&
|
||||
hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT)
|
||||
) {
|
||||
return attemptTransaction(session, startTime, fn, options);
|
||||
}
|
||||
|
||||
if (isMaxTimeMSExpiredError(err)) {
|
||||
err.addErrorLabel('UnknownTransactionCommitResult');
|
||||
}
|
||||
|
||||
throw err;
|
||||
}
|
||||
|
||||
if (session.transaction.isActive) {
|
||||
return session.abortTransaction().then(() => maybeRetryOrThrow(err));
|
||||
}
|
||||
|
||||
return maybeRetryOrThrow(err);
|
||||
});
|
||||
}
|
||||
|
||||
function endTransaction(session, commandName, callback) {
|
||||
if (!assertAlive(session, callback)) {
|
||||
// checking result in case callback was called
|
||||
return;
|
||||
}
|
||||
|
||||
// handle any initial problematic cases
|
||||
let txnState = session.transaction.state;
|
||||
|
||||
if (txnState === TxnState.NO_TRANSACTION) {
|
||||
callback(new MongoError('No transaction started'));
|
||||
return;
|
||||
}
|
||||
|
||||
if (commandName === 'commitTransaction') {
|
||||
if (
|
||||
txnState === TxnState.STARTING_TRANSACTION ||
|
||||
txnState === TxnState.TRANSACTION_COMMITTED_EMPTY
|
||||
) {
|
||||
// the transaction was never started, we can safely exit here
|
||||
session.transaction.transition(TxnState.TRANSACTION_COMMITTED_EMPTY);
|
||||
callback(null, null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (txnState === TxnState.TRANSACTION_ABORTED) {
|
||||
callback(new MongoError('Cannot call commitTransaction after calling abortTransaction'));
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
if (txnState === TxnState.STARTING_TRANSACTION) {
|
||||
// the transaction was never started, we can safely exit here
|
||||
session.transaction.transition(TxnState.TRANSACTION_ABORTED);
|
||||
callback(null, null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (txnState === TxnState.TRANSACTION_ABORTED) {
|
||||
callback(new MongoError('Cannot call abortTransaction twice'));
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
txnState === TxnState.TRANSACTION_COMMITTED ||
|
||||
txnState === TxnState.TRANSACTION_COMMITTED_EMPTY
|
||||
) {
|
||||
callback(new MongoError('Cannot call abortTransaction after calling commitTransaction'));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// construct and send the command
|
||||
const command = { [commandName]: 1 };
|
||||
|
||||
// apply a writeConcern if specified
|
||||
let writeConcern;
|
||||
if (session.transaction.options.writeConcern) {
|
||||
writeConcern = Object.assign({}, session.transaction.options.writeConcern);
|
||||
} else if (session.clientOptions && session.clientOptions.w) {
|
||||
writeConcern = { w: session.clientOptions.w };
|
||||
}
|
||||
|
||||
if (txnState === TxnState.TRANSACTION_COMMITTED) {
|
||||
writeConcern = Object.assign({ wtimeout: 10000 }, writeConcern, { w: 'majority' });
|
||||
}
|
||||
|
||||
if (writeConcern) {
|
||||
Object.assign(command, { writeConcern });
|
||||
}
|
||||
|
||||
if (commandName === 'commitTransaction' && session.transaction.options.maxTimeMS) {
|
||||
Object.assign(command, { maxTimeMS: session.transaction.options.maxTimeMS });
|
||||
}
|
||||
|
||||
function commandHandler(e, r) {
|
||||
if (commandName === 'commitTransaction') {
|
||||
session.transaction.transition(TxnState.TRANSACTION_COMMITTED);
|
||||
|
||||
if (
|
||||
e &&
|
||||
(e instanceof MongoNetworkError ||
|
||||
e instanceof MongoWriteConcernError ||
|
||||
isRetryableError(e) ||
|
||||
isMaxTimeMSExpiredError(e))
|
||||
) {
|
||||
if (isUnknownTransactionCommitResult(e)) {
|
||||
e.addErrorLabel('UnknownTransactionCommitResult');
|
||||
|
||||
// per txns spec, must unpin session in this case
|
||||
session.transaction.unpinServer();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
session.transaction.transition(TxnState.TRANSACTION_ABORTED);
|
||||
}
|
||||
|
||||
callback(e, r);
|
||||
}
|
||||
|
||||
// The spec indicates that we should ignore all errors on `abortTransaction`
|
||||
function transactionError(err) {
|
||||
return commandName === 'commitTransaction' ? err : null;
|
||||
}
|
||||
|
||||
if (
|
||||
// Assumption here that commandName is "commitTransaction" or "abortTransaction"
|
||||
session.transaction.recoveryToken &&
|
||||
supportsRecoveryToken(session)
|
||||
) {
|
||||
command.recoveryToken = session.transaction.recoveryToken;
|
||||
}
|
||||
|
||||
// send the command
|
||||
session.topology.command('admin.$cmd', command, { session }, (err, reply) => {
|
||||
if (err && isRetryableError(err)) {
|
||||
// SPEC-1185: apply majority write concern when retrying commitTransaction
|
||||
if (command.commitTransaction) {
|
||||
// per txns spec, must unpin session in this case
|
||||
session.transaction.unpinServer();
|
||||
|
||||
command.writeConcern = Object.assign({ wtimeout: 10000 }, command.writeConcern, {
|
||||
w: 'majority'
|
||||
});
|
||||
}
|
||||
|
||||
return session.topology.command('admin.$cmd', command, { session }, (_err, _reply) =>
|
||||
commandHandler(transactionError(_err), _reply)
|
||||
);
|
||||
}
|
||||
|
||||
commandHandler(transactionError(err), reply);
|
||||
});
|
||||
}
|
||||
|
||||
function supportsRecoveryToken(session) {
|
||||
const topology = session.topology;
|
||||
return !!topology.s.options.useRecoveryToken;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reflects the existence of a session on the server. Can be reused by the session pool.
|
||||
* WARNING: not meant to be instantiated directly. For internal use only.
|
||||
* @ignore
|
||||
*/
|
||||
class ServerSession {
|
||||
constructor() {
|
||||
this.id = { id: new Binary(uuidV4(), Binary.SUBTYPE_UUID) };
|
||||
this.lastUse = now();
|
||||
this.txnNumber = 0;
|
||||
this.isDirty = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if the server session has timed out.
|
||||
* @ignore
|
||||
* @param {Date} sessionTimeoutMinutes The server's "logicalSessionTimeoutMinutes"
|
||||
* @return {boolean} true if the session has timed out.
|
||||
*/
|
||||
hasTimedOut(sessionTimeoutMinutes) {
|
||||
// Take the difference of the lastUse timestamp and now, which will result in a value in
|
||||
// milliseconds, and then convert milliseconds to minutes to compare to `sessionTimeoutMinutes`
|
||||
const idleTimeMinutes = Math.round(
|
||||
((calculateDurationInMs(this.lastUse) % 86400000) % 3600000) / 60000
|
||||
);
|
||||
|
||||
return idleTimeMinutes > sessionTimeoutMinutes - 1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Maintains a pool of Server Sessions.
|
||||
* For internal use only
|
||||
* @ignore
|
||||
*/
|
||||
class ServerSessionPool {
|
||||
constructor(topology) {
|
||||
if (topology == null) {
|
||||
throw new Error('ServerSessionPool requires a topology');
|
||||
}
|
||||
|
||||
this.topology = topology;
|
||||
this.sessions = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Ends all sessions in the session pool.
|
||||
* @ignore
|
||||
*/
|
||||
endAllPooledSessions(callback) {
|
||||
if (this.sessions.length) {
|
||||
this.topology.endSessions(
|
||||
this.sessions.map(session => session.id),
|
||||
() => {
|
||||
this.sessions = [];
|
||||
if (typeof callback === 'function') {
|
||||
callback();
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof callback === 'function') {
|
||||
callback();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Acquire a Server Session from the pool.
|
||||
* Iterates through each session in the pool, removing any stale sessions
|
||||
* along the way. The first non-stale session found is removed from the
|
||||
* pool and returned. If no non-stale session is found, a new ServerSession
|
||||
* is created.
|
||||
* @ignore
|
||||
* @returns {ServerSession}
|
||||
*/
|
||||
acquire() {
|
||||
const sessionTimeoutMinutes = this.topology.logicalSessionTimeoutMinutes;
|
||||
while (this.sessions.length) {
|
||||
const session = this.sessions.shift();
|
||||
if (!session.hasTimedOut(sessionTimeoutMinutes)) {
|
||||
return session;
|
||||
}
|
||||
}
|
||||
|
||||
return new ServerSession();
|
||||
}
|
||||
|
||||
/**
|
||||
* Release a session to the session pool
|
||||
* Adds the session back to the session pool if the session has not timed out yet.
|
||||
* This method also removes any stale sessions from the pool.
|
||||
* @ignore
|
||||
* @param {ServerSession} session The session to release to the pool
|
||||
*/
|
||||
release(session) {
|
||||
const sessionTimeoutMinutes = this.topology.logicalSessionTimeoutMinutes;
|
||||
while (this.sessions.length) {
|
||||
const pooledSession = this.sessions[this.sessions.length - 1];
|
||||
if (pooledSession.hasTimedOut(sessionTimeoutMinutes)) {
|
||||
this.sessions.pop();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!session.hasTimedOut(sessionTimeoutMinutes)) {
|
||||
if (session.isDirty) {
|
||||
return;
|
||||
}
|
||||
|
||||
// otherwise, readd this session to the session pool
|
||||
this.sessions.unshift(session);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: this should be codified in command construction
|
||||
// @see https://github.com/mongodb/specifications/blob/master/source/read-write-concern/read-write-concern.rst#read-concern
|
||||
function commandSupportsReadConcern(command, options) {
|
||||
if (
|
||||
command.aggregate ||
|
||||
command.count ||
|
||||
command.distinct ||
|
||||
command.find ||
|
||||
command.parallelCollectionScan ||
|
||||
command.geoNear ||
|
||||
command.geoSearch
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (
|
||||
command.mapReduce &&
|
||||
options &&
|
||||
options.out &&
|
||||
(options.out.inline === 1 || options.out === 'inline')
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Optionally decorate a command with sessions specific keys
|
||||
*
|
||||
* @ignore
|
||||
* @param {ClientSession} session the session tracking transaction state
|
||||
* @param {Object} command the command to decorate
|
||||
* @param {Object} topology the topology for tracking the cluster time
|
||||
* @param {Object} [options] Optional settings passed to calling operation
|
||||
* @return {MongoError|null} An error, if some error condition was met
|
||||
*/
|
||||
function applySession(session, command, options) {
|
||||
if (session.hasEnded) {
|
||||
// TODO: merge this with `assertAlive`, did not want to throw a try/catch here
|
||||
return new MongoError('Cannot use a session that has ended');
|
||||
}
|
||||
|
||||
// SPEC-1019: silently ignore explicit session with unacknowledged write for backwards compatibility
|
||||
if (options && options.writeConcern && options.writeConcern.w === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const serverSession = session.serverSession;
|
||||
serverSession.lastUse = now();
|
||||
command.lsid = serverSession.id;
|
||||
|
||||
// first apply non-transaction-specific sessions data
|
||||
const inTransaction = session.inTransaction() || isTransactionCommand(command);
|
||||
const isRetryableWrite = options.willRetryWrite;
|
||||
const shouldApplyReadConcern = commandSupportsReadConcern(command, options);
|
||||
|
||||
if (serverSession.txnNumber && (isRetryableWrite || inTransaction)) {
|
||||
command.txnNumber = BSON.Long.fromNumber(serverSession.txnNumber);
|
||||
}
|
||||
|
||||
// now attempt to apply transaction-specific sessions data
|
||||
if (!inTransaction) {
|
||||
if (session.transaction.state !== TxnState.NO_TRANSACTION) {
|
||||
session.transaction.transition(TxnState.NO_TRANSACTION);
|
||||
}
|
||||
|
||||
// TODO: the following should only be applied to read operation per spec.
|
||||
// for causal consistency
|
||||
if (session.supports.causalConsistency && session.operationTime && shouldApplyReadConcern) {
|
||||
command.readConcern = command.readConcern || {};
|
||||
Object.assign(command.readConcern, { afterClusterTime: session.operationTime });
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (options.readPreference && !options.readPreference.equals(ReadPreference.primary)) {
|
||||
return new MongoError(
|
||||
`Read preference in a transaction must be primary, not: ${options.readPreference.mode}`
|
||||
);
|
||||
}
|
||||
|
||||
// `autocommit` must always be false to differentiate from retryable writes
|
||||
command.autocommit = false;
|
||||
|
||||
if (session.transaction.state === TxnState.STARTING_TRANSACTION) {
|
||||
session.transaction.transition(TxnState.TRANSACTION_IN_PROGRESS);
|
||||
command.startTransaction = true;
|
||||
|
||||
const readConcern =
|
||||
session.transaction.options.readConcern || session.clientOptions.readConcern;
|
||||
if (readConcern) {
|
||||
command.readConcern = readConcern;
|
||||
}
|
||||
|
||||
if (session.supports.causalConsistency && session.operationTime) {
|
||||
command.readConcern = command.readConcern || {};
|
||||
Object.assign(command.readConcern, { afterClusterTime: session.operationTime });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function updateSessionFromResponse(session, document) {
|
||||
if (document.$clusterTime) {
|
||||
resolveClusterTime(session, document.$clusterTime);
|
||||
}
|
||||
|
||||
if (document.operationTime && session && session.supports.causalConsistency) {
|
||||
session.advanceOperationTime(document.operationTime);
|
||||
}
|
||||
|
||||
if (document.recoveryToken && session && session.inTransaction()) {
|
||||
session.transaction._recoveryToken = document.recoveryToken;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
ClientSession,
|
||||
ServerSession,
|
||||
ServerSessionPool,
|
||||
TxnState,
|
||||
applySession,
|
||||
updateSessionFromResponse,
|
||||
commandSupportsReadConcern
|
||||
};
|
||||
61
node_modules/mongodb/lib/core/tools/smoke_plugin.js
generated
vendored
Normal file
61
node_modules/mongodb/lib/core/tools/smoke_plugin.js
generated
vendored
Normal file
@@ -0,0 +1,61 @@
|
||||
'use strict';
|
||||
|
||||
var fs = require('fs');
|
||||
|
||||
/* Note: because this plugin uses process.on('uncaughtException'), only one
|
||||
* of these can exist at any given time. This plugin and anything else that
|
||||
* uses process.on('uncaughtException') will conflict. */
|
||||
exports.attachToRunner = function(runner, outputFile) {
|
||||
var smokeOutput = { results: [] };
|
||||
var runningTests = {};
|
||||
|
||||
var integraPlugin = {
|
||||
beforeTest: function(test, callback) {
|
||||
test.startTime = Date.now();
|
||||
runningTests[test.name] = test;
|
||||
callback();
|
||||
},
|
||||
afterTest: function(test, callback) {
|
||||
smokeOutput.results.push({
|
||||
status: test.status,
|
||||
start: test.startTime,
|
||||
end: Date.now(),
|
||||
test_file: test.name,
|
||||
exit_code: 0,
|
||||
url: ''
|
||||
});
|
||||
delete runningTests[test.name];
|
||||
callback();
|
||||
},
|
||||
beforeExit: function(obj, callback) {
|
||||
fs.writeFile(outputFile, JSON.stringify(smokeOutput), function() {
|
||||
callback();
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// In case of exception, make sure we write file
|
||||
process.on('uncaughtException', function(err) {
|
||||
// Mark all currently running tests as failed
|
||||
for (var testName in runningTests) {
|
||||
smokeOutput.results.push({
|
||||
status: 'fail',
|
||||
start: runningTests[testName].startTime,
|
||||
end: Date.now(),
|
||||
test_file: testName,
|
||||
exit_code: 0,
|
||||
url: ''
|
||||
});
|
||||
}
|
||||
|
||||
// write file
|
||||
fs.writeFileSync(outputFile, JSON.stringify(smokeOutput));
|
||||
|
||||
// Standard NodeJS uncaught exception handler
|
||||
console.error(err.stack);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
runner.plugin(integraPlugin);
|
||||
return integraPlugin;
|
||||
};
|
||||
1396
node_modules/mongodb/lib/core/topologies/mongos.js
generated
vendored
Normal file
1396
node_modules/mongodb/lib/core/topologies/mongos.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
266
node_modules/mongodb/lib/core/topologies/read_preference.js
generated
vendored
Normal file
266
node_modules/mongodb/lib/core/topologies/read_preference.js
generated
vendored
Normal file
@@ -0,0 +1,266 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is
|
||||
* used to construct connections.
|
||||
* @class
|
||||
* @param {string} mode A string describing the read preference mode (primary|primaryPreferred|secondary|secondaryPreferred|nearest)
|
||||
* @param {array} tags The tags object
|
||||
* @param {object} [options] Additional read preference options
|
||||
* @param {number} [options.maxStalenessSeconds] Max secondary read staleness in seconds, Minimum value is 90 seconds.
|
||||
* @param {object} [options.hedge] Server mode in which the same query is dispatched in parallel to multiple replica set members.
|
||||
* @param {boolean} [options.hedge.enabled] Explicitly enable or disable hedged reads.
|
||||
* @see https://docs.mongodb.com/manual/core/read-preference/
|
||||
* @return {ReadPreference}
|
||||
*/
|
||||
const ReadPreference = function(mode, tags, options) {
|
||||
if (!ReadPreference.isValid(mode)) {
|
||||
throw new TypeError(`Invalid read preference mode ${mode}`);
|
||||
}
|
||||
|
||||
// TODO(major): tags MUST be an array of tagsets
|
||||
if (tags && !Array.isArray(tags)) {
|
||||
console.warn(
|
||||
'ReadPreference tags must be an array, this will change in the next major version'
|
||||
);
|
||||
|
||||
const tagsHasMaxStalenessSeconds = typeof tags.maxStalenessSeconds !== 'undefined';
|
||||
const tagsHasHedge = typeof tags.hedge !== 'undefined';
|
||||
const tagsHasOptions = tagsHasMaxStalenessSeconds || tagsHasHedge;
|
||||
if (tagsHasOptions) {
|
||||
// this is likely an options object
|
||||
options = tags;
|
||||
tags = undefined;
|
||||
} else {
|
||||
tags = [tags];
|
||||
}
|
||||
}
|
||||
|
||||
this.mode = mode;
|
||||
this.tags = tags;
|
||||
this.hedge = options && options.hedge;
|
||||
|
||||
options = options || {};
|
||||
if (options.maxStalenessSeconds != null) {
|
||||
if (options.maxStalenessSeconds <= 0) {
|
||||
throw new TypeError('maxStalenessSeconds must be a positive integer');
|
||||
}
|
||||
|
||||
this.maxStalenessSeconds = options.maxStalenessSeconds;
|
||||
|
||||
// NOTE: The minimum required wire version is 5 for this read preference. If the existing
|
||||
// topology has a lower value then a MongoError will be thrown during server selection.
|
||||
this.minWireVersion = 5;
|
||||
}
|
||||
|
||||
if (this.mode === ReadPreference.PRIMARY) {
|
||||
if (this.tags && Array.isArray(this.tags) && this.tags.length > 0) {
|
||||
throw new TypeError('Primary read preference cannot be combined with tags');
|
||||
}
|
||||
|
||||
if (this.maxStalenessSeconds) {
|
||||
throw new TypeError('Primary read preference cannot be combined with maxStalenessSeconds');
|
||||
}
|
||||
|
||||
if (this.hedge) {
|
||||
throw new TypeError('Primary read preference cannot be combined with hedge');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Support the deprecated `preference` property introduced in the porcelain layer
|
||||
Object.defineProperty(ReadPreference.prototype, 'preference', {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return this.mode;
|
||||
}
|
||||
});
|
||||
|
||||
/*
|
||||
* Read preference mode constants
|
||||
*/
|
||||
ReadPreference.PRIMARY = 'primary';
|
||||
ReadPreference.PRIMARY_PREFERRED = 'primaryPreferred';
|
||||
ReadPreference.SECONDARY = 'secondary';
|
||||
ReadPreference.SECONDARY_PREFERRED = 'secondaryPreferred';
|
||||
ReadPreference.NEAREST = 'nearest';
|
||||
|
||||
const VALID_MODES = [
|
||||
ReadPreference.PRIMARY,
|
||||
ReadPreference.PRIMARY_PREFERRED,
|
||||
ReadPreference.SECONDARY,
|
||||
ReadPreference.SECONDARY_PREFERRED,
|
||||
ReadPreference.NEAREST,
|
||||
null
|
||||
];
|
||||
|
||||
/**
|
||||
* Construct a ReadPreference given an options object.
|
||||
*
|
||||
* @param {object} options The options object from which to extract the read preference.
|
||||
* @return {ReadPreference}
|
||||
*/
|
||||
ReadPreference.fromOptions = function(options) {
|
||||
if (!options) return null;
|
||||
const readPreference = options.readPreference;
|
||||
if (!readPreference) return null;
|
||||
const readPreferenceTags = options.readPreferenceTags;
|
||||
const maxStalenessSeconds = options.maxStalenessSeconds;
|
||||
if (typeof readPreference === 'string') {
|
||||
return new ReadPreference(readPreference, readPreferenceTags);
|
||||
} else if (!(readPreference instanceof ReadPreference) && typeof readPreference === 'object') {
|
||||
const mode = readPreference.mode || readPreference.preference;
|
||||
if (mode && typeof mode === 'string') {
|
||||
return new ReadPreference(mode, readPreference.tags, {
|
||||
maxStalenessSeconds: readPreference.maxStalenessSeconds || maxStalenessSeconds,
|
||||
hedge: readPreference.hedge
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return readPreference;
|
||||
};
|
||||
|
||||
/**
|
||||
* Resolves a read preference based on well-defined inheritance rules. This method will not only
|
||||
* determine the read preference (if there is one), but will also ensure the returned value is a
|
||||
* properly constructed instance of `ReadPreference`.
|
||||
*
|
||||
* @param {Collection|Db|MongoClient} parent The parent of the operation on which to determine the read
|
||||
* preference, used for determining the inherited read preference.
|
||||
* @param {object} options The options passed into the method, potentially containing a read preference
|
||||
* @returns {(ReadPreference|null)} The resolved read preference
|
||||
*/
|
||||
ReadPreference.resolve = function(parent, options) {
|
||||
options = options || {};
|
||||
const session = options.session;
|
||||
|
||||
const inheritedReadPreference = parent && parent.readPreference;
|
||||
|
||||
let readPreference;
|
||||
if (options.readPreference) {
|
||||
readPreference = ReadPreference.fromOptions(options);
|
||||
} else if (session && session.inTransaction() && session.transaction.options.readPreference) {
|
||||
// The transaction’s read preference MUST override all other user configurable read preferences.
|
||||
readPreference = session.transaction.options.readPreference;
|
||||
} else if (inheritedReadPreference != null) {
|
||||
readPreference = inheritedReadPreference;
|
||||
} else {
|
||||
readPreference = ReadPreference.primary;
|
||||
}
|
||||
|
||||
return typeof readPreference === 'string' ? new ReadPreference(readPreference) : readPreference;
|
||||
};
|
||||
|
||||
/**
|
||||
* Replaces options.readPreference with a ReadPreference instance
|
||||
*/
|
||||
ReadPreference.translate = function(options) {
|
||||
if (options.readPreference == null) return options;
|
||||
const r = options.readPreference;
|
||||
|
||||
if (typeof r === 'string') {
|
||||
options.readPreference = new ReadPreference(r);
|
||||
} else if (r && !(r instanceof ReadPreference) && typeof r === 'object') {
|
||||
const mode = r.mode || r.preference;
|
||||
if (mode && typeof mode === 'string') {
|
||||
options.readPreference = new ReadPreference(mode, r.tags, {
|
||||
maxStalenessSeconds: r.maxStalenessSeconds
|
||||
});
|
||||
}
|
||||
} else if (!(r instanceof ReadPreference)) {
|
||||
throw new TypeError('Invalid read preference: ' + r);
|
||||
}
|
||||
|
||||
return options;
|
||||
};
|
||||
|
||||
/**
|
||||
* Validate if a mode is legal
|
||||
*
|
||||
* @method
|
||||
* @param {string} mode The string representing the read preference mode.
|
||||
* @return {boolean} True if a mode is valid
|
||||
*/
|
||||
ReadPreference.isValid = function(mode) {
|
||||
return VALID_MODES.indexOf(mode) !== -1;
|
||||
};
|
||||
|
||||
/**
|
||||
* Validate if a mode is legal
|
||||
*
|
||||
* @method
|
||||
* @param {string} mode The string representing the read preference mode.
|
||||
* @return {boolean} True if a mode is valid
|
||||
*/
|
||||
ReadPreference.prototype.isValid = function(mode) {
|
||||
return ReadPreference.isValid(typeof mode === 'string' ? mode : this.mode);
|
||||
};
|
||||
|
||||
const needSlaveOk = ['primaryPreferred', 'secondary', 'secondaryPreferred', 'nearest'];
|
||||
|
||||
/**
|
||||
* Indicates that this readPreference needs the "slaveOk" bit when sent over the wire
|
||||
* @method
|
||||
* @return {boolean}
|
||||
* @see https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#op-query
|
||||
*/
|
||||
ReadPreference.prototype.slaveOk = function() {
|
||||
return needSlaveOk.indexOf(this.mode) !== -1;
|
||||
};
|
||||
|
||||
/**
|
||||
* Are the two read preference equal
|
||||
* @method
|
||||
* @param {ReadPreference} readPreference The read preference with which to check equality
|
||||
* @return {boolean} True if the two ReadPreferences are equivalent
|
||||
*/
|
||||
ReadPreference.prototype.equals = function(readPreference) {
|
||||
return readPreference.mode === this.mode;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return JSON representation
|
||||
* @method
|
||||
* @return {Object} A JSON representation of the ReadPreference
|
||||
*/
|
||||
ReadPreference.prototype.toJSON = function() {
|
||||
const readPreference = { mode: this.mode };
|
||||
if (Array.isArray(this.tags)) readPreference.tags = this.tags;
|
||||
if (this.maxStalenessSeconds) readPreference.maxStalenessSeconds = this.maxStalenessSeconds;
|
||||
if (this.hedge) readPreference.hedge = this.hedge;
|
||||
return readPreference;
|
||||
};
|
||||
|
||||
/**
|
||||
* Primary read preference
|
||||
* @member
|
||||
* @type {ReadPreference}
|
||||
*/
|
||||
ReadPreference.primary = new ReadPreference('primary');
|
||||
/**
|
||||
* Primary Preferred read preference
|
||||
* @member
|
||||
* @type {ReadPreference}
|
||||
*/
|
||||
ReadPreference.primaryPreferred = new ReadPreference('primaryPreferred');
|
||||
/**
|
||||
* Secondary read preference
|
||||
* @member
|
||||
* @type {ReadPreference}
|
||||
*/
|
||||
ReadPreference.secondary = new ReadPreference('secondary');
|
||||
/**
|
||||
* Secondary Preferred read preference
|
||||
* @member
|
||||
* @type {ReadPreference}
|
||||
*/
|
||||
ReadPreference.secondaryPreferred = new ReadPreference('secondaryPreferred');
|
||||
/**
|
||||
* Nearest read preference
|
||||
* @member
|
||||
* @type {ReadPreference}
|
||||
*/
|
||||
ReadPreference.nearest = new ReadPreference('nearest');
|
||||
|
||||
module.exports = ReadPreference;
|
||||
1559
node_modules/mongodb/lib/core/topologies/replset.js
generated
vendored
Normal file
1559
node_modules/mongodb/lib/core/topologies/replset.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
1121
node_modules/mongodb/lib/core/topologies/replset_state.js
generated
vendored
Normal file
1121
node_modules/mongodb/lib/core/topologies/replset_state.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
990
node_modules/mongodb/lib/core/topologies/server.js
generated
vendored
Normal file
990
node_modules/mongodb/lib/core/topologies/server.js
generated
vendored
Normal file
@@ -0,0 +1,990 @@
|
||||
'use strict';
|
||||
|
||||
var inherits = require('util').inherits,
|
||||
f = require('util').format,
|
||||
EventEmitter = require('events').EventEmitter,
|
||||
ReadPreference = require('./read_preference'),
|
||||
Logger = require('../connection/logger'),
|
||||
debugOptions = require('../connection/utils').debugOptions,
|
||||
retrieveBSON = require('../connection/utils').retrieveBSON,
|
||||
Pool = require('../connection/pool'),
|
||||
MongoError = require('../error').MongoError,
|
||||
MongoNetworkError = require('../error').MongoNetworkError,
|
||||
wireProtocol = require('../wireprotocol'),
|
||||
CoreCursor = require('../cursor').CoreCursor,
|
||||
sdam = require('./shared'),
|
||||
createCompressionInfo = require('./shared').createCompressionInfo,
|
||||
resolveClusterTime = require('./shared').resolveClusterTime,
|
||||
SessionMixins = require('./shared').SessionMixins,
|
||||
relayEvents = require('../utils').relayEvents;
|
||||
|
||||
const collationNotSupported = require('../utils').collationNotSupported;
|
||||
const makeClientMetadata = require('../utils').makeClientMetadata;
|
||||
|
||||
// Used for filtering out fields for loggin
|
||||
var debugFields = [
|
||||
'reconnect',
|
||||
'reconnectTries',
|
||||
'reconnectInterval',
|
||||
'emitError',
|
||||
'cursorFactory',
|
||||
'host',
|
||||
'port',
|
||||
'size',
|
||||
'keepAlive',
|
||||
'keepAliveInitialDelay',
|
||||
'noDelay',
|
||||
'connectionTimeout',
|
||||
'checkServerIdentity',
|
||||
'socketTimeout',
|
||||
'ssl',
|
||||
'ca',
|
||||
'crl',
|
||||
'cert',
|
||||
'key',
|
||||
'rejectUnauthorized',
|
||||
'promoteLongs',
|
||||
'promoteValues',
|
||||
'promoteBuffers',
|
||||
'servername'
|
||||
];
|
||||
|
||||
// Server instance id
|
||||
var id = 0;
|
||||
var serverAccounting = false;
|
||||
var servers = {};
|
||||
var BSON = retrieveBSON();
|
||||
|
||||
function topologyId(server) {
|
||||
return server.s.parent == null ? server.id : server.s.parent.id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new Server instance
|
||||
* @class
|
||||
* @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection
|
||||
* @param {number} [options.reconnectTries=30] Server attempt to reconnect #times
|
||||
* @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries
|
||||
* @param {number} [options.monitoring=true] Enable the server state monitoring (calling ismaster at monitoringInterval)
|
||||
* @param {number} [options.monitoringInterval=5000] The interval of calling ismaster when monitoring is enabled.
|
||||
* @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors
|
||||
* @param {string} options.host The server host
|
||||
* @param {number} options.port The server port
|
||||
* @param {number} [options.size=5] Server connection pool size
|
||||
* @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled
|
||||
* @param {number} [options.keepAliveInitialDelay=120000] Initial delay before TCP keep alive enabled
|
||||
* @param {boolean} [options.noDelay=true] TCP Connection no delay
|
||||
* @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting
|
||||
* @param {number} [options.socketTimeout=360000] TCP Socket timeout setting
|
||||
* @param {boolean} [options.ssl=false] Use SSL for connection
|
||||
* @param {boolean|function} [options.checkServerIdentity=true] 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.
|
||||
* @param {Buffer} [options.ca] SSL Certificate store binary buffer
|
||||
* @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer
|
||||
* @param {Buffer} [options.cert] SSL Certificate binary buffer
|
||||
* @param {Buffer} [options.key] SSL Key file binary buffer
|
||||
* @param {string} [options.passphrase] SSL Certificate pass phrase
|
||||
* @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates
|
||||
* @param {string} [options.servername=null] String containing the server name requested via TLS SNI.
|
||||
* @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits
|
||||
* @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types.
|
||||
* @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers.
|
||||
* @param {string} [options.appname=null] Application name, passed in on ismaster call and logged in mongod server logs. Maximum size 128 bytes.
|
||||
* @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit.
|
||||
* @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology
|
||||
* @return {Server} A cursor instance
|
||||
* @fires Server#connect
|
||||
* @fires Server#close
|
||||
* @fires Server#error
|
||||
* @fires Server#timeout
|
||||
* @fires Server#parseError
|
||||
* @fires Server#reconnect
|
||||
* @fires Server#reconnectFailed
|
||||
* @fires Server#serverHeartbeatStarted
|
||||
* @fires Server#serverHeartbeatSucceeded
|
||||
* @fires Server#serverHeartbeatFailed
|
||||
* @fires Server#topologyOpening
|
||||
* @fires Server#topologyClosed
|
||||
* @fires Server#topologyDescriptionChanged
|
||||
* @property {string} type the topology type.
|
||||
* @property {string} parserType the parser type used (c++ or js).
|
||||
*/
|
||||
var Server = function(options) {
|
||||
options = options || {};
|
||||
|
||||
// Add event listener
|
||||
EventEmitter.call(this);
|
||||
|
||||
// Server instance id
|
||||
this.id = id++;
|
||||
|
||||
// Internal state
|
||||
this.s = {
|
||||
// Options
|
||||
options: Object.assign({ metadata: makeClientMetadata(options) }, options),
|
||||
// Logger
|
||||
logger: Logger('Server', options),
|
||||
// Factory overrides
|
||||
Cursor: options.cursorFactory || CoreCursor,
|
||||
// BSON instance
|
||||
bson:
|
||||
options.bson ||
|
||||
new BSON([
|
||||
BSON.Binary,
|
||||
BSON.Code,
|
||||
BSON.DBRef,
|
||||
BSON.Decimal128,
|
||||
BSON.Double,
|
||||
BSON.Int32,
|
||||
BSON.Long,
|
||||
BSON.Map,
|
||||
BSON.MaxKey,
|
||||
BSON.MinKey,
|
||||
BSON.ObjectId,
|
||||
BSON.BSONRegExp,
|
||||
BSON.Symbol,
|
||||
BSON.Timestamp
|
||||
]),
|
||||
// Pool
|
||||
pool: null,
|
||||
// Disconnect handler
|
||||
disconnectHandler: options.disconnectHandler,
|
||||
// Monitor thread (keeps the connection alive)
|
||||
monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : true,
|
||||
// Is the server in a topology
|
||||
inTopology: !!options.parent,
|
||||
// Monitoring timeout
|
||||
monitoringInterval:
|
||||
typeof options.monitoringInterval === 'number' ? options.monitoringInterval : 5000,
|
||||
compression: { compressors: createCompressionInfo(options) },
|
||||
// Optional parent topology
|
||||
parent: options.parent
|
||||
};
|
||||
|
||||
// If this is a single deployment we need to track the clusterTime here
|
||||
if (!this.s.parent) {
|
||||
this.s.clusterTime = null;
|
||||
}
|
||||
|
||||
// Curent ismaster
|
||||
this.ismaster = null;
|
||||
// Current ping time
|
||||
this.lastIsMasterMS = -1;
|
||||
// The monitoringProcessId
|
||||
this.monitoringProcessId = null;
|
||||
// Initial connection
|
||||
this.initialConnect = true;
|
||||
// Default type
|
||||
this._type = 'server';
|
||||
|
||||
// Max Stalleness values
|
||||
// last time we updated the ismaster state
|
||||
this.lastUpdateTime = 0;
|
||||
// Last write time
|
||||
this.lastWriteDate = 0;
|
||||
// Stalleness
|
||||
this.staleness = 0;
|
||||
};
|
||||
|
||||
inherits(Server, EventEmitter);
|
||||
Object.assign(Server.prototype, SessionMixins);
|
||||
|
||||
Object.defineProperty(Server.prototype, 'type', {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return this._type;
|
||||
}
|
||||
});
|
||||
|
||||
Object.defineProperty(Server.prototype, 'parserType', {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return BSON.native ? 'c++' : 'js';
|
||||
}
|
||||
});
|
||||
|
||||
Object.defineProperty(Server.prototype, 'logicalSessionTimeoutMinutes', {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
if (!this.ismaster) return null;
|
||||
return this.ismaster.logicalSessionTimeoutMinutes || null;
|
||||
}
|
||||
});
|
||||
|
||||
Object.defineProperty(Server.prototype, 'clientMetadata', {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return this.s.options.metadata;
|
||||
}
|
||||
});
|
||||
|
||||
// In single server deployments we track the clusterTime directly on the topology, however
|
||||
// in Mongos and ReplSet deployments we instead need to delegate the clusterTime up to the
|
||||
// tracking objects so we can ensure we are gossiping the maximum time received from the
|
||||
// server.
|
||||
Object.defineProperty(Server.prototype, 'clusterTime', {
|
||||
enumerable: true,
|
||||
set: function(clusterTime) {
|
||||
const settings = this.s.parent ? this.s.parent : this.s;
|
||||
resolveClusterTime(settings, clusterTime);
|
||||
},
|
||||
get: function() {
|
||||
const settings = this.s.parent ? this.s.parent : this.s;
|
||||
return settings.clusterTime || null;
|
||||
}
|
||||
});
|
||||
|
||||
Server.enableServerAccounting = function() {
|
||||
serverAccounting = true;
|
||||
servers = {};
|
||||
};
|
||||
|
||||
Server.disableServerAccounting = function() {
|
||||
serverAccounting = false;
|
||||
};
|
||||
|
||||
Server.servers = function() {
|
||||
return servers;
|
||||
};
|
||||
|
||||
Object.defineProperty(Server.prototype, 'name', {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return this.s.options.host + ':' + this.s.options.port;
|
||||
}
|
||||
});
|
||||
|
||||
function disconnectHandler(self, type, ns, cmd, options, callback) {
|
||||
// Topology is not connected, save the call in the provided store to be
|
||||
// Executed at some point when the handler deems it's reconnected
|
||||
if (
|
||||
!self.s.pool.isConnected() &&
|
||||
self.s.options.reconnect &&
|
||||
self.s.disconnectHandler != null &&
|
||||
!options.monitoring
|
||||
) {
|
||||
self.s.disconnectHandler.add(type, ns, cmd, options, callback);
|
||||
return true;
|
||||
}
|
||||
|
||||
// If we have no connection error
|
||||
if (!self.s.pool.isConnected()) {
|
||||
callback(new MongoError(f('no connection available to server %s', self.name)));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
function monitoringProcess(self) {
|
||||
return function() {
|
||||
// Pool was destroyed do not continue process
|
||||
if (self.s.pool.isDestroyed()) return;
|
||||
// Emit monitoring Process event
|
||||
self.emit('monitoring', self);
|
||||
// Perform ismaster call
|
||||
// Get start time
|
||||
var start = new Date().getTime();
|
||||
|
||||
// Execute the ismaster query
|
||||
self.command(
|
||||
'admin.$cmd',
|
||||
{ ismaster: true },
|
||||
{
|
||||
socketTimeout:
|
||||
typeof self.s.options.connectionTimeout !== 'number'
|
||||
? 2000
|
||||
: self.s.options.connectionTimeout,
|
||||
monitoring: true
|
||||
},
|
||||
(err, result) => {
|
||||
// Set initial lastIsMasterMS
|
||||
self.lastIsMasterMS = new Date().getTime() - start;
|
||||
if (self.s.pool.isDestroyed()) return;
|
||||
// Update the ismaster view if we have a result
|
||||
if (result) {
|
||||
self.ismaster = result.result;
|
||||
}
|
||||
// Re-schedule the monitoring process
|
||||
self.monitoringProcessId = setTimeout(monitoringProcess(self), self.s.monitoringInterval);
|
||||
}
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
var eventHandler = function(self, event) {
|
||||
return function(err, conn) {
|
||||
// Log information of received information if in info mode
|
||||
if (self.s.logger.isInfo()) {
|
||||
var object = err instanceof MongoError ? JSON.stringify(err) : {};
|
||||
self.s.logger.info(
|
||||
f('server %s fired event %s out with message %s', self.name, event, object)
|
||||
);
|
||||
}
|
||||
|
||||
// Handle connect event
|
||||
if (event === 'connect') {
|
||||
self.initialConnect = false;
|
||||
self.ismaster = conn.ismaster;
|
||||
self.lastIsMasterMS = conn.lastIsMasterMS;
|
||||
if (conn.agreedCompressor) {
|
||||
self.s.pool.options.agreedCompressor = conn.agreedCompressor;
|
||||
}
|
||||
|
||||
if (conn.zlibCompressionLevel) {
|
||||
self.s.pool.options.zlibCompressionLevel = conn.zlibCompressionLevel;
|
||||
}
|
||||
|
||||
if (conn.ismaster.$clusterTime) {
|
||||
const $clusterTime = conn.ismaster.$clusterTime;
|
||||
self.clusterTime = $clusterTime;
|
||||
}
|
||||
|
||||
// It's a proxy change the type so
|
||||
// the wireprotocol will send $readPreference
|
||||
if (self.ismaster.msg === 'isdbgrid') {
|
||||
self._type = 'mongos';
|
||||
}
|
||||
|
||||
// Have we defined self monitoring
|
||||
if (self.s.monitoring) {
|
||||
self.monitoringProcessId = setTimeout(monitoringProcess(self), self.s.monitoringInterval);
|
||||
}
|
||||
|
||||
// Emit server description changed if something listening
|
||||
sdam.emitServerDescriptionChanged(self, {
|
||||
address: self.name,
|
||||
arbiters: [],
|
||||
hosts: [],
|
||||
passives: [],
|
||||
type: sdam.getTopologyType(self)
|
||||
});
|
||||
|
||||
if (!self.s.inTopology) {
|
||||
// Emit topology description changed if something listening
|
||||
sdam.emitTopologyDescriptionChanged(self, {
|
||||
topologyType: 'Single',
|
||||
servers: [
|
||||
{
|
||||
address: self.name,
|
||||
arbiters: [],
|
||||
hosts: [],
|
||||
passives: [],
|
||||
type: sdam.getTopologyType(self)
|
||||
}
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
// Log the ismaster if available
|
||||
if (self.s.logger.isInfo()) {
|
||||
self.s.logger.info(
|
||||
f('server %s connected with ismaster [%s]', self.name, JSON.stringify(self.ismaster))
|
||||
);
|
||||
}
|
||||
|
||||
// Emit connect
|
||||
self.emit('connect', self);
|
||||
} else if (
|
||||
event === 'error' ||
|
||||
event === 'parseError' ||
|
||||
event === 'close' ||
|
||||
event === 'timeout' ||
|
||||
event === 'reconnect' ||
|
||||
event === 'attemptReconnect' ||
|
||||
'reconnectFailed'
|
||||
) {
|
||||
// Remove server instance from accounting
|
||||
if (
|
||||
serverAccounting &&
|
||||
['close', 'timeout', 'error', 'parseError', 'reconnectFailed'].indexOf(event) !== -1
|
||||
) {
|
||||
// Emit toplogy opening event if not in topology
|
||||
if (!self.s.inTopology) {
|
||||
self.emit('topologyOpening', { topologyId: self.id });
|
||||
}
|
||||
|
||||
delete servers[self.id];
|
||||
}
|
||||
|
||||
if (event === 'close') {
|
||||
// Closing emits a server description changed event going to unknown.
|
||||
sdam.emitServerDescriptionChanged(self, {
|
||||
address: self.name,
|
||||
arbiters: [],
|
||||
hosts: [],
|
||||
passives: [],
|
||||
type: 'Unknown'
|
||||
});
|
||||
}
|
||||
|
||||
// Reconnect failed return error
|
||||
if (event === 'reconnectFailed') {
|
||||
self.emit('reconnectFailed', err);
|
||||
// Emit error if any listeners
|
||||
if (self.listeners('error').length > 0) {
|
||||
self.emit('error', err);
|
||||
}
|
||||
// Terminate
|
||||
return;
|
||||
}
|
||||
|
||||
// On first connect fail
|
||||
if (
|
||||
['disconnected', 'connecting'].indexOf(self.s.pool.state) !== -1 &&
|
||||
self.initialConnect &&
|
||||
['close', 'timeout', 'error', 'parseError'].indexOf(event) !== -1
|
||||
) {
|
||||
self.initialConnect = false;
|
||||
return self.emit(
|
||||
'error',
|
||||
new MongoNetworkError(
|
||||
f('failed to connect to server [%s] on first connect [%s]', self.name, err)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Reconnect event, emit the server
|
||||
if (event === 'reconnect') {
|
||||
// Reconnecting emits a server description changed event going from unknown to the
|
||||
// current server type.
|
||||
sdam.emitServerDescriptionChanged(self, {
|
||||
address: self.name,
|
||||
arbiters: [],
|
||||
hosts: [],
|
||||
passives: [],
|
||||
type: sdam.getTopologyType(self)
|
||||
});
|
||||
return self.emit(event, self);
|
||||
}
|
||||
|
||||
// Emit the event
|
||||
self.emit(event, err);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Initiate server connect
|
||||
*/
|
||||
Server.prototype.connect = function(options) {
|
||||
var self = this;
|
||||
options = options || {};
|
||||
|
||||
// Set the connections
|
||||
if (serverAccounting) servers[this.id] = this;
|
||||
|
||||
// Do not allow connect to be called on anything that's not disconnected
|
||||
if (self.s.pool && !self.s.pool.isDisconnected() && !self.s.pool.isDestroyed()) {
|
||||
throw new MongoError(f('server instance in invalid state %s', self.s.pool.state));
|
||||
}
|
||||
|
||||
// Create a pool
|
||||
self.s.pool = new Pool(this, Object.assign(self.s.options, options, { bson: this.s.bson }));
|
||||
|
||||
// Set up listeners
|
||||
self.s.pool.on('close', eventHandler(self, 'close'));
|
||||
self.s.pool.on('error', eventHandler(self, 'error'));
|
||||
self.s.pool.on('timeout', eventHandler(self, 'timeout'));
|
||||
self.s.pool.on('parseError', eventHandler(self, 'parseError'));
|
||||
self.s.pool.on('connect', eventHandler(self, 'connect'));
|
||||
self.s.pool.on('reconnect', eventHandler(self, 'reconnect'));
|
||||
self.s.pool.on('reconnectFailed', eventHandler(self, 'reconnectFailed'));
|
||||
|
||||
// Set up listeners for command monitoring
|
||||
relayEvents(self.s.pool, self, ['commandStarted', 'commandSucceeded', 'commandFailed']);
|
||||
|
||||
// Emit toplogy opening event if not in topology
|
||||
if (!self.s.inTopology) {
|
||||
this.emit('topologyOpening', { topologyId: topologyId(self) });
|
||||
}
|
||||
|
||||
// Emit opening server event
|
||||
self.emit('serverOpening', { topologyId: topologyId(self), address: self.name });
|
||||
|
||||
self.s.pool.connect();
|
||||
};
|
||||
|
||||
/**
|
||||
* Authenticate the topology.
|
||||
* @method
|
||||
* @param {MongoCredentials} credentials The credentials for authentication we are using
|
||||
* @param {authResultCallback} callback A callback function
|
||||
*/
|
||||
Server.prototype.auth = function(credentials, callback) {
|
||||
if (typeof callback === 'function') callback(null, null);
|
||||
};
|
||||
|
||||
/**
|
||||
* Get the server description
|
||||
* @method
|
||||
* @return {object}
|
||||
*/
|
||||
Server.prototype.getDescription = function() {
|
||||
var ismaster = this.ismaster || {};
|
||||
var description = {
|
||||
type: sdam.getTopologyType(this),
|
||||
address: this.name
|
||||
};
|
||||
|
||||
// Add fields if available
|
||||
if (ismaster.hosts) description.hosts = ismaster.hosts;
|
||||
if (ismaster.arbiters) description.arbiters = ismaster.arbiters;
|
||||
if (ismaster.passives) description.passives = ismaster.passives;
|
||||
if (ismaster.setName) description.setName = ismaster.setName;
|
||||
return description;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the last known ismaster document for this server
|
||||
* @method
|
||||
* @return {object}
|
||||
*/
|
||||
Server.prototype.lastIsMaster = function() {
|
||||
return this.ismaster;
|
||||
};
|
||||
|
||||
/**
|
||||
* Unref all connections belong to this server
|
||||
* @method
|
||||
*/
|
||||
Server.prototype.unref = function() {
|
||||
this.s.pool.unref();
|
||||
};
|
||||
|
||||
/**
|
||||
* Figure out if the server is connected
|
||||
* @method
|
||||
* @return {boolean}
|
||||
*/
|
||||
Server.prototype.isConnected = function() {
|
||||
if (!this.s.pool) return false;
|
||||
return this.s.pool.isConnected();
|
||||
};
|
||||
|
||||
/**
|
||||
* Figure out if the server instance was destroyed by calling destroy
|
||||
* @method
|
||||
* @return {boolean}
|
||||
*/
|
||||
Server.prototype.isDestroyed = function() {
|
||||
if (!this.s.pool) return false;
|
||||
return this.s.pool.isDestroyed();
|
||||
};
|
||||
|
||||
function basicWriteValidations(self) {
|
||||
if (!self.s.pool) return new MongoError('server instance is not connected');
|
||||
if (self.s.pool.isDestroyed()) return new MongoError('server instance pool was destroyed');
|
||||
}
|
||||
|
||||
function basicReadValidations(self, options) {
|
||||
basicWriteValidations(self, options);
|
||||
|
||||
if (options.readPreference && !(options.readPreference instanceof ReadPreference)) {
|
||||
throw new Error('readPreference must be an instance of ReadPreference');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a command
|
||||
* @method
|
||||
* @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)
|
||||
* @param {object} cmd The command hash
|
||||
* @param {ReadPreference} [options.readPreference] Specify read preference if command supports it
|
||||
* @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.
|
||||
* @param {Boolean} [options.checkKeys=false] Specify if the bson parser should validate keys.
|
||||
* @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
|
||||
* @param {Boolean} [options.fullResult=false] Return the full envelope instead of just the result document.
|
||||
* @param {ClientSession} [options.session=null] Session to use for the operation
|
||||
* @param {opResultCallback} callback A callback function
|
||||
*/
|
||||
Server.prototype.command = function(ns, cmd, options, callback) {
|
||||
var self = this;
|
||||
if (typeof options === 'function') {
|
||||
(callback = options), (options = {}), (options = options || {});
|
||||
}
|
||||
|
||||
var result = basicReadValidations(self, options);
|
||||
if (result) return callback(result);
|
||||
|
||||
// Clone the options
|
||||
options = Object.assign({}, options, { wireProtocolCommand: false });
|
||||
|
||||
// Debug log
|
||||
if (self.s.logger.isDebug())
|
||||
self.s.logger.debug(
|
||||
f(
|
||||
'executing command [%s] against %s',
|
||||
JSON.stringify({
|
||||
ns: ns,
|
||||
cmd: cmd,
|
||||
options: debugOptions(debugFields, options)
|
||||
}),
|
||||
self.name
|
||||
)
|
||||
);
|
||||
|
||||
// If we are not connected or have a disconnectHandler specified
|
||||
if (disconnectHandler(self, 'command', ns, cmd, options, callback)) return;
|
||||
|
||||
// error if collation not supported
|
||||
if (collationNotSupported(this, cmd)) {
|
||||
return callback(new MongoError(`server ${this.name} does not support collation`));
|
||||
}
|
||||
|
||||
wireProtocol.command(self, ns, cmd, options, callback);
|
||||
};
|
||||
|
||||
/**
|
||||
* Execute a query against the server
|
||||
*
|
||||
* @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)
|
||||
* @param {object} cmd The command document for the query
|
||||
* @param {object} options Optional settings
|
||||
* @param {function} callback
|
||||
*/
|
||||
Server.prototype.query = function(ns, cmd, cursorState, options, callback) {
|
||||
wireProtocol.query(this, ns, cmd, cursorState, options, callback);
|
||||
};
|
||||
|
||||
/**
|
||||
* Execute a `getMore` against the server
|
||||
*
|
||||
* @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)
|
||||
* @param {object} cursorState State data associated with the cursor calling this method
|
||||
* @param {object} options Optional settings
|
||||
* @param {function} callback
|
||||
*/
|
||||
Server.prototype.getMore = function(ns, cursorState, batchSize, options, callback) {
|
||||
wireProtocol.getMore(this, ns, cursorState, batchSize, options, callback);
|
||||
};
|
||||
|
||||
/**
|
||||
* Execute a `killCursors` command against the server
|
||||
*
|
||||
* @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)
|
||||
* @param {object} cursorState State data associated with the cursor calling this method
|
||||
* @param {function} callback
|
||||
*/
|
||||
Server.prototype.killCursors = function(ns, cursorState, callback) {
|
||||
wireProtocol.killCursors(this, ns, cursorState, callback);
|
||||
};
|
||||
|
||||
/**
|
||||
* Insert one or more documents
|
||||
* @method
|
||||
* @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)
|
||||
* @param {array} ops An array of documents to insert
|
||||
* @param {boolean} [options.ordered=true] Execute in order or out of order
|
||||
* @param {object} [options.writeConcern={}] Write concern for the operation
|
||||
* @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.
|
||||
* @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
|
||||
* @param {ClientSession} [options.session=null] Session to use for the operation
|
||||
* @param {opResultCallback} callback A callback function
|
||||
*/
|
||||
Server.prototype.insert = function(ns, ops, options, callback) {
|
||||
var self = this;
|
||||
if (typeof options === 'function') {
|
||||
(callback = options), (options = {}), (options = options || {});
|
||||
}
|
||||
|
||||
var result = basicWriteValidations(self, options);
|
||||
if (result) return callback(result);
|
||||
|
||||
// If we are not connected or have a disconnectHandler specified
|
||||
if (disconnectHandler(self, 'insert', ns, ops, options, callback)) return;
|
||||
|
||||
// Setup the docs as an array
|
||||
ops = Array.isArray(ops) ? ops : [ops];
|
||||
|
||||
// Execute write
|
||||
return wireProtocol.insert(self, ns, ops, options, callback);
|
||||
};
|
||||
|
||||
/**
|
||||
* Perform one or more update operations
|
||||
* @method
|
||||
* @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)
|
||||
* @param {array} ops An array of updates
|
||||
* @param {boolean} [options.ordered=true] Execute in order or out of order
|
||||
* @param {object} [options.writeConcern={}] Write concern for the operation
|
||||
* @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.
|
||||
* @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
|
||||
* @param {ClientSession} [options.session=null] Session to use for the operation
|
||||
* @param {opResultCallback} callback A callback function
|
||||
*/
|
||||
Server.prototype.update = function(ns, ops, options, callback) {
|
||||
var self = this;
|
||||
if (typeof options === 'function') {
|
||||
(callback = options), (options = {}), (options = options || {});
|
||||
}
|
||||
|
||||
var result = basicWriteValidations(self, options);
|
||||
if (result) return callback(result);
|
||||
|
||||
// If we are not connected or have a disconnectHandler specified
|
||||
if (disconnectHandler(self, 'update', ns, ops, options, callback)) return;
|
||||
|
||||
// error if collation not supported
|
||||
if (collationNotSupported(this, options)) {
|
||||
return callback(new MongoError(`server ${this.name} does not support collation`));
|
||||
}
|
||||
|
||||
// Setup the docs as an array
|
||||
ops = Array.isArray(ops) ? ops : [ops];
|
||||
// Execute write
|
||||
return wireProtocol.update(self, ns, ops, options, callback);
|
||||
};
|
||||
|
||||
/**
|
||||
* Perform one or more remove operations
|
||||
* @method
|
||||
* @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)
|
||||
* @param {array} ops An array of removes
|
||||
* @param {boolean} [options.ordered=true] Execute in order or out of order
|
||||
* @param {object} [options.writeConcern={}] Write concern for the operation
|
||||
* @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.
|
||||
* @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
|
||||
* @param {ClientSession} [options.session=null] Session to use for the operation
|
||||
* @param {opResultCallback} callback A callback function
|
||||
*/
|
||||
Server.prototype.remove = function(ns, ops, options, callback) {
|
||||
var self = this;
|
||||
if (typeof options === 'function') {
|
||||
(callback = options), (options = {}), (options = options || {});
|
||||
}
|
||||
|
||||
var result = basicWriteValidations(self, options);
|
||||
if (result) return callback(result);
|
||||
|
||||
// If we are not connected or have a disconnectHandler specified
|
||||
if (disconnectHandler(self, 'remove', ns, ops, options, callback)) return;
|
||||
|
||||
// error if collation not supported
|
||||
if (collationNotSupported(this, options)) {
|
||||
return callback(new MongoError(`server ${this.name} does not support collation`));
|
||||
}
|
||||
|
||||
// Setup the docs as an array
|
||||
ops = Array.isArray(ops) ? ops : [ops];
|
||||
// Execute write
|
||||
return wireProtocol.remove(self, ns, ops, options, callback);
|
||||
};
|
||||
|
||||
/**
|
||||
* Get a new cursor
|
||||
* @method
|
||||
* @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)
|
||||
* @param {object|Long} cmd Can be either a command returning a cursor or a cursorId
|
||||
* @param {object} [options] Options for the cursor
|
||||
* @param {object} [options.batchSize=0] Batchsize for the operation
|
||||
* @param {array} [options.documents=[]] Initial documents list for cursor
|
||||
* @param {ReadPreference} [options.readPreference] Specify read preference if command supports it
|
||||
* @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.
|
||||
* @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
|
||||
* @param {ClientSession} [options.session=null] Session to use for the operation
|
||||
* @param {object} [options.topology] The internal topology of the created cursor
|
||||
* @returns {Cursor}
|
||||
*/
|
||||
Server.prototype.cursor = function(ns, cmd, options) {
|
||||
options = options || {};
|
||||
const topology = options.topology || this;
|
||||
|
||||
// Set up final cursor type
|
||||
var FinalCursor = options.cursorFactory || this.s.Cursor;
|
||||
|
||||
// Return the cursor
|
||||
return new FinalCursor(topology, ns, cmd, options);
|
||||
};
|
||||
|
||||
/**
|
||||
* Compare two server instances
|
||||
* @method
|
||||
* @param {Server} server Server to compare equality against
|
||||
* @return {boolean}
|
||||
*/
|
||||
Server.prototype.equals = function(server) {
|
||||
if (typeof server === 'string') return this.name.toLowerCase() === server.toLowerCase();
|
||||
if (server.name) return this.name.toLowerCase() === server.name.toLowerCase();
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
* All raw connections
|
||||
* @method
|
||||
* @return {Connection[]}
|
||||
*/
|
||||
Server.prototype.connections = function() {
|
||||
return this.s.pool.allConnections();
|
||||
};
|
||||
|
||||
/**
|
||||
* Selects a server
|
||||
* @method
|
||||
* @param {function} selector Unused
|
||||
* @param {ReadPreference} [options.readPreference] Unused
|
||||
* @param {ClientSession} [options.session] Unused
|
||||
* @return {Server}
|
||||
*/
|
||||
Server.prototype.selectServer = function(selector, options, callback) {
|
||||
if (typeof selector === 'function' && typeof callback === 'undefined')
|
||||
(callback = selector), (selector = undefined), (options = {});
|
||||
if (typeof options === 'function')
|
||||
(callback = options), (options = selector), (selector = undefined);
|
||||
|
||||
callback(null, this);
|
||||
};
|
||||
|
||||
var listeners = ['close', 'error', 'timeout', 'parseError', 'connect'];
|
||||
|
||||
/**
|
||||
* Destroy the server connection
|
||||
* @method
|
||||
* @param {boolean} [options.emitClose=false] Emit close event on destroy
|
||||
* @param {boolean} [options.emitDestroy=false] Emit destroy event on destroy
|
||||
* @param {boolean} [options.force=false] Force destroy the pool
|
||||
*/
|
||||
Server.prototype.destroy = function(options, callback) {
|
||||
if (this._destroyed) {
|
||||
if (typeof callback === 'function') callback(null, null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof options === 'function') {
|
||||
callback = options;
|
||||
options = {};
|
||||
}
|
||||
|
||||
options = options || {};
|
||||
var self = this;
|
||||
|
||||
// Set the connections
|
||||
if (serverAccounting) delete servers[this.id];
|
||||
|
||||
// Destroy the monitoring process if any
|
||||
if (this.monitoringProcessId) {
|
||||
clearTimeout(this.monitoringProcessId);
|
||||
}
|
||||
|
||||
// No pool, return
|
||||
if (!self.s.pool) {
|
||||
this._destroyed = true;
|
||||
if (typeof callback === 'function') callback(null, null);
|
||||
return;
|
||||
}
|
||||
|
||||
// Emit close event
|
||||
if (options.emitClose) {
|
||||
self.emit('close', self);
|
||||
}
|
||||
|
||||
// Emit destroy event
|
||||
if (options.emitDestroy) {
|
||||
self.emit('destroy', self);
|
||||
}
|
||||
|
||||
// Remove all listeners
|
||||
listeners.forEach(function(event) {
|
||||
self.s.pool.removeAllListeners(event);
|
||||
});
|
||||
|
||||
// Emit opening server event
|
||||
if (self.listeners('serverClosed').length > 0)
|
||||
self.emit('serverClosed', { topologyId: topologyId(self), address: self.name });
|
||||
|
||||
// Emit toplogy opening event if not in topology
|
||||
if (self.listeners('topologyClosed').length > 0 && !self.s.inTopology) {
|
||||
self.emit('topologyClosed', { topologyId: topologyId(self) });
|
||||
}
|
||||
|
||||
if (self.s.logger.isDebug()) {
|
||||
self.s.logger.debug(f('destroy called on server %s', self.name));
|
||||
}
|
||||
|
||||
// Destroy the pool
|
||||
this.s.pool.destroy(options.force, callback);
|
||||
this._destroyed = true;
|
||||
};
|
||||
|
||||
/**
|
||||
* A server connect event, used to verify that the connection is up and running
|
||||
*
|
||||
* @event Server#connect
|
||||
* @type {Server}
|
||||
*/
|
||||
|
||||
/**
|
||||
* A server reconnect event, used to verify that the server topology has reconnected
|
||||
*
|
||||
* @event Server#reconnect
|
||||
* @type {Server}
|
||||
*/
|
||||
|
||||
/**
|
||||
* A server opening SDAM monitoring event
|
||||
*
|
||||
* @event Server#serverOpening
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* A server closed SDAM monitoring event
|
||||
*
|
||||
* @event Server#serverClosed
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* A server description SDAM change monitoring event
|
||||
*
|
||||
* @event Server#serverDescriptionChanged
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* A topology open SDAM event
|
||||
*
|
||||
* @event Server#topologyOpening
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* A topology closed SDAM event
|
||||
*
|
||||
* @event Server#topologyClosed
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* A topology structure SDAM change event
|
||||
*
|
||||
* @event Server#topologyDescriptionChanged
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Server reconnect failed
|
||||
*
|
||||
* @event Server#reconnectFailed
|
||||
* @type {Error}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Server connection pool closed
|
||||
*
|
||||
* @event Server#close
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Server connection pool caused an error
|
||||
*
|
||||
* @event Server#error
|
||||
* @type {Error}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Server destroyed was called
|
||||
*
|
||||
* @event Server#destroy
|
||||
* @type {Server}
|
||||
*/
|
||||
|
||||
module.exports = Server;
|
||||
456
node_modules/mongodb/lib/core/topologies/shared.js
generated
vendored
Normal file
456
node_modules/mongodb/lib/core/topologies/shared.js
generated
vendored
Normal file
@@ -0,0 +1,456 @@
|
||||
'use strict';
|
||||
const ReadPreference = require('./read_preference');
|
||||
const TopologyType = require('../sdam/common').TopologyType;
|
||||
const MongoError = require('../error').MongoError;
|
||||
const isRetryableWriteError = require('../error').isRetryableWriteError;
|
||||
const maxWireVersion = require('../utils').maxWireVersion;
|
||||
const MongoNetworkError = require('../error').MongoNetworkError;
|
||||
const MMAPv1_RETRY_WRITES_ERROR_CODE = 20;
|
||||
|
||||
/**
|
||||
* Emit event if it exists
|
||||
* @method
|
||||
*/
|
||||
function emitSDAMEvent(self, event, description) {
|
||||
if (self.listeners(event).length > 0) {
|
||||
self.emit(event, description);
|
||||
}
|
||||
}
|
||||
|
||||
function createCompressionInfo(options) {
|
||||
if (!options.compression || !options.compression.compressors) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Check that all supplied compressors are valid
|
||||
options.compression.compressors.forEach(function(compressor) {
|
||||
if (compressor !== 'snappy' && compressor !== 'zlib') {
|
||||
throw new Error('compressors must be at least one of snappy or zlib');
|
||||
}
|
||||
});
|
||||
|
||||
return options.compression.compressors;
|
||||
}
|
||||
|
||||
function clone(object) {
|
||||
return JSON.parse(JSON.stringify(object));
|
||||
}
|
||||
|
||||
var getPreviousDescription = function(self) {
|
||||
if (!self.s.serverDescription) {
|
||||
self.s.serverDescription = {
|
||||
address: self.name,
|
||||
arbiters: [],
|
||||
hosts: [],
|
||||
passives: [],
|
||||
type: 'Unknown'
|
||||
};
|
||||
}
|
||||
|
||||
return self.s.serverDescription;
|
||||
};
|
||||
|
||||
var emitServerDescriptionChanged = function(self, description) {
|
||||
if (self.listeners('serverDescriptionChanged').length > 0) {
|
||||
// Emit the server description changed events
|
||||
self.emit('serverDescriptionChanged', {
|
||||
topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id,
|
||||
address: self.name,
|
||||
previousDescription: getPreviousDescription(self),
|
||||
newDescription: description
|
||||
});
|
||||
|
||||
self.s.serverDescription = description;
|
||||
}
|
||||
};
|
||||
|
||||
var getPreviousTopologyDescription = function(self) {
|
||||
if (!self.s.topologyDescription) {
|
||||
self.s.topologyDescription = {
|
||||
topologyType: 'Unknown',
|
||||
servers: [
|
||||
{
|
||||
address: self.name,
|
||||
arbiters: [],
|
||||
hosts: [],
|
||||
passives: [],
|
||||
type: 'Unknown'
|
||||
}
|
||||
]
|
||||
};
|
||||
}
|
||||
|
||||
return self.s.topologyDescription;
|
||||
};
|
||||
|
||||
var emitTopologyDescriptionChanged = function(self, description) {
|
||||
if (self.listeners('topologyDescriptionChanged').length > 0) {
|
||||
// Emit the server description changed events
|
||||
self.emit('topologyDescriptionChanged', {
|
||||
topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id,
|
||||
address: self.name,
|
||||
previousDescription: getPreviousTopologyDescription(self),
|
||||
newDescription: description
|
||||
});
|
||||
|
||||
self.s.serverDescription = description;
|
||||
}
|
||||
};
|
||||
|
||||
var changedIsMaster = function(self, currentIsmaster, ismaster) {
|
||||
var currentType = getTopologyType(self, currentIsmaster);
|
||||
var newType = getTopologyType(self, ismaster);
|
||||
if (newType !== currentType) return true;
|
||||
return false;
|
||||
};
|
||||
|
||||
var getTopologyType = function(self, ismaster) {
|
||||
if (!ismaster) {
|
||||
ismaster = self.ismaster;
|
||||
}
|
||||
|
||||
if (!ismaster) return 'Unknown';
|
||||
if (ismaster.ismaster && ismaster.msg === 'isdbgrid') return 'Mongos';
|
||||
if (ismaster.ismaster && !ismaster.hosts) return 'Standalone';
|
||||
if (ismaster.ismaster) return 'RSPrimary';
|
||||
if (ismaster.secondary) return 'RSSecondary';
|
||||
if (ismaster.arbiterOnly) return 'RSArbiter';
|
||||
return 'Unknown';
|
||||
};
|
||||
|
||||
var inquireServerState = function(self) {
|
||||
return function(callback) {
|
||||
if (self.s.state === 'destroyed') return;
|
||||
// Record response time
|
||||
var start = new Date().getTime();
|
||||
|
||||
// emitSDAMEvent
|
||||
emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: self.name });
|
||||
|
||||
// Attempt to execute ismaster command
|
||||
self.command('admin.$cmd', { ismaster: true }, { monitoring: true }, function(err, r) {
|
||||
if (!err) {
|
||||
// Legacy event sender
|
||||
self.emit('ismaster', r, self);
|
||||
|
||||
// Calculate latencyMS
|
||||
var latencyMS = new Date().getTime() - start;
|
||||
|
||||
// Server heart beat event
|
||||
emitSDAMEvent(self, 'serverHeartbeatSucceeded', {
|
||||
durationMS: latencyMS,
|
||||
reply: r.result,
|
||||
connectionId: self.name
|
||||
});
|
||||
|
||||
// Did the server change
|
||||
if (changedIsMaster(self, self.s.ismaster, r.result)) {
|
||||
// Emit server description changed if something listening
|
||||
emitServerDescriptionChanged(self, {
|
||||
address: self.name,
|
||||
arbiters: [],
|
||||
hosts: [],
|
||||
passives: [],
|
||||
type: !self.s.inTopology ? 'Standalone' : getTopologyType(self)
|
||||
});
|
||||
}
|
||||
|
||||
// Updat ismaster view
|
||||
self.s.ismaster = r.result;
|
||||
|
||||
// Set server response time
|
||||
self.s.isMasterLatencyMS = latencyMS;
|
||||
} else {
|
||||
emitSDAMEvent(self, 'serverHeartbeatFailed', {
|
||||
durationMS: latencyMS,
|
||||
failure: err,
|
||||
connectionId: self.name
|
||||
});
|
||||
}
|
||||
|
||||
// Peforming an ismaster monitoring callback operation
|
||||
if (typeof callback === 'function') {
|
||||
return callback(err, r);
|
||||
}
|
||||
|
||||
// Perform another sweep
|
||||
self.s.inquireServerStateTimeout = setTimeout(inquireServerState(self), self.s.haInterval);
|
||||
});
|
||||
};
|
||||
};
|
||||
|
||||
//
|
||||
// Clone the options
|
||||
var cloneOptions = function(options) {
|
||||
var opts = {};
|
||||
for (var name in options) {
|
||||
opts[name] = options[name];
|
||||
}
|
||||
return opts;
|
||||
};
|
||||
|
||||
function Interval(fn, time) {
|
||||
var timer = false;
|
||||
|
||||
this.start = function() {
|
||||
if (!this.isRunning()) {
|
||||
timer = setInterval(fn, time);
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
this.stop = function() {
|
||||
clearInterval(timer);
|
||||
timer = false;
|
||||
return this;
|
||||
};
|
||||
|
||||
this.isRunning = function() {
|
||||
return timer !== false;
|
||||
};
|
||||
}
|
||||
|
||||
function Timeout(fn, time) {
|
||||
var timer = false;
|
||||
var func = () => {
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
timer = false;
|
||||
|
||||
fn();
|
||||
}
|
||||
};
|
||||
|
||||
this.start = function() {
|
||||
if (!this.isRunning()) {
|
||||
timer = setTimeout(func, time);
|
||||
}
|
||||
return this;
|
||||
};
|
||||
|
||||
this.stop = function() {
|
||||
clearTimeout(timer);
|
||||
timer = false;
|
||||
return this;
|
||||
};
|
||||
|
||||
this.isRunning = function() {
|
||||
return timer !== false;
|
||||
};
|
||||
}
|
||||
|
||||
function diff(previous, current) {
|
||||
// Difference document
|
||||
var diff = {
|
||||
servers: []
|
||||
};
|
||||
|
||||
// Previous entry
|
||||
if (!previous) {
|
||||
previous = { servers: [] };
|
||||
}
|
||||
|
||||
// Check if we have any previous servers missing in the current ones
|
||||
for (var i = 0; i < previous.servers.length; i++) {
|
||||
var found = false;
|
||||
|
||||
for (var j = 0; j < current.servers.length; j++) {
|
||||
if (current.servers[j].address.toLowerCase() === previous.servers[i].address.toLowerCase()) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!found) {
|
||||
// Add to the diff
|
||||
diff.servers.push({
|
||||
address: previous.servers[i].address,
|
||||
from: previous.servers[i].type,
|
||||
to: 'Unknown'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Check if there are any severs that don't exist
|
||||
for (j = 0; j < current.servers.length; j++) {
|
||||
found = false;
|
||||
|
||||
// Go over all the previous servers
|
||||
for (i = 0; i < previous.servers.length; i++) {
|
||||
if (previous.servers[i].address.toLowerCase() === current.servers[j].address.toLowerCase()) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Add the server to the diff
|
||||
if (!found) {
|
||||
diff.servers.push({
|
||||
address: current.servers[j].address,
|
||||
from: 'Unknown',
|
||||
to: current.servers[j].type
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Got through all the servers
|
||||
for (i = 0; i < previous.servers.length; i++) {
|
||||
var prevServer = previous.servers[i];
|
||||
|
||||
// Go through all current servers
|
||||
for (j = 0; j < current.servers.length; j++) {
|
||||
var currServer = current.servers[j];
|
||||
|
||||
// Matching server
|
||||
if (prevServer.address.toLowerCase() === currServer.address.toLowerCase()) {
|
||||
// We had a change in state
|
||||
if (prevServer.type !== currServer.type) {
|
||||
diff.servers.push({
|
||||
address: prevServer.address,
|
||||
from: prevServer.type,
|
||||
to: currServer.type
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Return difference
|
||||
return diff;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared function to determine clusterTime for a given topology
|
||||
*
|
||||
* @param {*} topology
|
||||
* @param {*} clusterTime
|
||||
*/
|
||||
function resolveClusterTime(topology, $clusterTime) {
|
||||
if (topology.clusterTime == null) {
|
||||
topology.clusterTime = $clusterTime;
|
||||
} else {
|
||||
if ($clusterTime.clusterTime.greaterThan(topology.clusterTime.clusterTime)) {
|
||||
topology.clusterTime = $clusterTime;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// NOTE: this is a temporary move until the topologies can be more formally refactored
|
||||
// to share code.
|
||||
const SessionMixins = {
|
||||
endSessions: function(sessions, callback) {
|
||||
if (!Array.isArray(sessions)) {
|
||||
sessions = [sessions];
|
||||
}
|
||||
|
||||
// TODO:
|
||||
// When connected to a sharded cluster the endSessions command
|
||||
// can be sent to any mongos. When connected to a replica set the
|
||||
// endSessions command MUST be sent to the primary if the primary
|
||||
// is available, otherwise it MUST be sent to any available secondary.
|
||||
// Is it enough to use: ReadPreference.primaryPreferred ?
|
||||
this.command(
|
||||
'admin.$cmd',
|
||||
{ endSessions: sessions },
|
||||
{ readPreference: ReadPreference.primaryPreferred },
|
||||
() => {
|
||||
// intentionally ignored, per spec
|
||||
if (typeof callback === 'function') callback();
|
||||
}
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
function topologyType(topology) {
|
||||
if (topology.description) {
|
||||
return topology.description.type;
|
||||
}
|
||||
|
||||
if (topology.type === 'mongos') {
|
||||
return TopologyType.Sharded;
|
||||
} else if (topology.type === 'replset') {
|
||||
return TopologyType.ReplicaSetWithPrimary;
|
||||
}
|
||||
|
||||
return TopologyType.Single;
|
||||
}
|
||||
|
||||
const RETRYABLE_WIRE_VERSION = 6;
|
||||
|
||||
/**
|
||||
* Determines whether the provided topology supports retryable writes
|
||||
*
|
||||
* @param {Mongos|Replset} topology
|
||||
*/
|
||||
const isRetryableWritesSupported = function(topology) {
|
||||
const maxWireVersion = topology.lastIsMaster().maxWireVersion;
|
||||
if (maxWireVersion < RETRYABLE_WIRE_VERSION) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!topology.logicalSessionTimeoutMinutes) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (topologyType(topology) === TopologyType.Single) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
const MMAPv1_RETRY_WRITES_ERROR_MESSAGE =
|
||||
'This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.';
|
||||
|
||||
function getMMAPError(err) {
|
||||
if (err.code !== MMAPv1_RETRY_WRITES_ERROR_CODE || !err.errmsg.includes('Transaction numbers')) {
|
||||
return err;
|
||||
}
|
||||
|
||||
// According to the retryable writes spec, we must replace the error message in this case.
|
||||
// We need to replace err.message so the thrown message is correct and we need to replace err.errmsg to meet the spec requirement.
|
||||
const newErr = new MongoError({
|
||||
message: MMAPv1_RETRY_WRITES_ERROR_MESSAGE,
|
||||
errmsg: MMAPv1_RETRY_WRITES_ERROR_MESSAGE,
|
||||
originalError: err
|
||||
});
|
||||
return newErr;
|
||||
}
|
||||
|
||||
// NOTE: only used for legacy topology types
|
||||
function legacyIsRetryableWriteError(err, topology) {
|
||||
if (!(err instanceof MongoError)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// if pre-4.4 server, then add error label if its a retryable write error
|
||||
if (
|
||||
isRetryableWritesSupported(topology) &&
|
||||
(err instanceof MongoNetworkError ||
|
||||
(maxWireVersion(topology) < 9 && isRetryableWriteError(err)))
|
||||
) {
|
||||
err.addErrorLabel('RetryableWriteError');
|
||||
}
|
||||
|
||||
return err.hasErrorLabel('RetryableWriteError');
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
SessionMixins,
|
||||
resolveClusterTime,
|
||||
inquireServerState,
|
||||
getTopologyType,
|
||||
emitServerDescriptionChanged,
|
||||
emitTopologyDescriptionChanged,
|
||||
cloneOptions,
|
||||
createCompressionInfo,
|
||||
clone,
|
||||
diff,
|
||||
Interval,
|
||||
Timeout,
|
||||
isRetryableWritesSupported,
|
||||
getMMAPError,
|
||||
topologyType,
|
||||
legacyIsRetryableWriteError
|
||||
};
|
||||
179
node_modules/mongodb/lib/core/transactions.js
generated
vendored
Normal file
179
node_modules/mongodb/lib/core/transactions.js
generated
vendored
Normal file
@@ -0,0 +1,179 @@
|
||||
'use strict';
|
||||
const MongoError = require('./error').MongoError;
|
||||
const ReadPreference = require('./topologies/read_preference');
|
||||
const ReadConcern = require('../read_concern');
|
||||
const WriteConcern = require('../write_concern');
|
||||
|
||||
let TxnState;
|
||||
let stateMachine;
|
||||
|
||||
(() => {
|
||||
const NO_TRANSACTION = 'NO_TRANSACTION';
|
||||
const STARTING_TRANSACTION = 'STARTING_TRANSACTION';
|
||||
const TRANSACTION_IN_PROGRESS = 'TRANSACTION_IN_PROGRESS';
|
||||
const TRANSACTION_COMMITTED = 'TRANSACTION_COMMITTED';
|
||||
const TRANSACTION_COMMITTED_EMPTY = 'TRANSACTION_COMMITTED_EMPTY';
|
||||
const TRANSACTION_ABORTED = 'TRANSACTION_ABORTED';
|
||||
|
||||
TxnState = {
|
||||
NO_TRANSACTION,
|
||||
STARTING_TRANSACTION,
|
||||
TRANSACTION_IN_PROGRESS,
|
||||
TRANSACTION_COMMITTED,
|
||||
TRANSACTION_COMMITTED_EMPTY,
|
||||
TRANSACTION_ABORTED
|
||||
};
|
||||
|
||||
stateMachine = {
|
||||
[NO_TRANSACTION]: [NO_TRANSACTION, STARTING_TRANSACTION],
|
||||
[STARTING_TRANSACTION]: [
|
||||
TRANSACTION_IN_PROGRESS,
|
||||
TRANSACTION_COMMITTED,
|
||||
TRANSACTION_COMMITTED_EMPTY,
|
||||
TRANSACTION_ABORTED
|
||||
],
|
||||
[TRANSACTION_IN_PROGRESS]: [
|
||||
TRANSACTION_IN_PROGRESS,
|
||||
TRANSACTION_COMMITTED,
|
||||
TRANSACTION_ABORTED
|
||||
],
|
||||
[TRANSACTION_COMMITTED]: [
|
||||
TRANSACTION_COMMITTED,
|
||||
TRANSACTION_COMMITTED_EMPTY,
|
||||
STARTING_TRANSACTION,
|
||||
NO_TRANSACTION
|
||||
],
|
||||
[TRANSACTION_ABORTED]: [STARTING_TRANSACTION, NO_TRANSACTION],
|
||||
[TRANSACTION_COMMITTED_EMPTY]: [TRANSACTION_COMMITTED_EMPTY, NO_TRANSACTION]
|
||||
};
|
||||
})();
|
||||
|
||||
/**
|
||||
* The MongoDB ReadConcern, which allows for control of the consistency and isolation properties
|
||||
* of the data read from replica sets and replica set shards.
|
||||
* @typedef {Object} ReadConcern
|
||||
* @property {'local'|'available'|'majority'|'linearizable'|'snapshot'} level The readConcern Level
|
||||
* @see https://docs.mongodb.com/manual/reference/read-concern/
|
||||
*/
|
||||
|
||||
/**
|
||||
* A MongoDB WriteConcern, which describes the level of acknowledgement
|
||||
* requested from MongoDB for write operations.
|
||||
* @typedef {Object} WriteConcern
|
||||
* @property {number|'majority'|string} [w=1] requests acknowledgement that the write operation has
|
||||
* propagated to a specified number of mongod hosts
|
||||
* @property {boolean} [j=false] requests acknowledgement from MongoDB that the write operation has
|
||||
* been written to the journal
|
||||
* @property {number} [wtimeout] a time limit, in milliseconds, for the write concern
|
||||
* @see https://docs.mongodb.com/manual/reference/write-concern/
|
||||
*/
|
||||
|
||||
/**
|
||||
* Configuration options for a transaction.
|
||||
* @typedef {Object} TransactionOptions
|
||||
* @property {ReadConcern} [readConcern] A default read concern for commands in this transaction
|
||||
* @property {WriteConcern} [writeConcern] A default writeConcern for commands in this transaction
|
||||
* @property {ReadPreference} [readPreference] A default read preference for commands in this transaction
|
||||
*/
|
||||
|
||||
/**
|
||||
* A class maintaining state related to a server transaction. Internal Only
|
||||
* @ignore
|
||||
*/
|
||||
class Transaction {
|
||||
/**
|
||||
* Create a transaction
|
||||
*
|
||||
* @ignore
|
||||
* @param {TransactionOptions} [options] Optional settings
|
||||
*/
|
||||
constructor(options) {
|
||||
options = options || {};
|
||||
|
||||
this.state = TxnState.NO_TRANSACTION;
|
||||
this.options = {};
|
||||
|
||||
const writeConcern = WriteConcern.fromOptions(options);
|
||||
if (writeConcern) {
|
||||
if (writeConcern.w <= 0) {
|
||||
throw new MongoError('Transactions do not support unacknowledged write concern');
|
||||
}
|
||||
|
||||
this.options.writeConcern = writeConcern;
|
||||
}
|
||||
|
||||
if (options.readConcern) {
|
||||
this.options.readConcern = ReadConcern.fromOptions(options);
|
||||
}
|
||||
|
||||
if (options.readPreference) {
|
||||
this.options.readPreference = ReadPreference.fromOptions(options);
|
||||
}
|
||||
|
||||
if (options.maxCommitTimeMS) {
|
||||
this.options.maxTimeMS = options.maxCommitTimeMS;
|
||||
}
|
||||
|
||||
// TODO: This isn't technically necessary
|
||||
this._pinnedServer = undefined;
|
||||
this._recoveryToken = undefined;
|
||||
}
|
||||
|
||||
get server() {
|
||||
return this._pinnedServer;
|
||||
}
|
||||
|
||||
get recoveryToken() {
|
||||
return this._recoveryToken;
|
||||
}
|
||||
|
||||
get isPinned() {
|
||||
return !!this.server;
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
* @return Whether this session is presently in a transaction
|
||||
*/
|
||||
get isActive() {
|
||||
return (
|
||||
[TxnState.STARTING_TRANSACTION, TxnState.TRANSACTION_IN_PROGRESS].indexOf(this.state) !== -1
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Transition the transaction in the state machine
|
||||
* @ignore
|
||||
* @param {TxnState} state The new state to transition to
|
||||
*/
|
||||
transition(nextState) {
|
||||
const nextStates = stateMachine[this.state];
|
||||
if (nextStates && nextStates.indexOf(nextState) !== -1) {
|
||||
this.state = nextState;
|
||||
if (this.state === TxnState.NO_TRANSACTION || this.state === TxnState.STARTING_TRANSACTION) {
|
||||
this.unpinServer();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
throw new MongoError(
|
||||
`Attempted illegal state transition from [${this.state}] to [${nextState}]`
|
||||
);
|
||||
}
|
||||
|
||||
pinServer(server) {
|
||||
if (this.isActive) {
|
||||
this._pinnedServer = server;
|
||||
}
|
||||
}
|
||||
|
||||
unpinServer() {
|
||||
this._pinnedServer = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function isTransactionCommand(command) {
|
||||
return !!(command.commitTransaction || command.abortTransaction);
|
||||
}
|
||||
|
||||
module.exports = { TxnState, Transaction, isTransactionCommand };
|
||||
723
node_modules/mongodb/lib/core/uri_parser.js
generated
vendored
Normal file
723
node_modules/mongodb/lib/core/uri_parser.js
generated
vendored
Normal file
@@ -0,0 +1,723 @@
|
||||
'use strict';
|
||||
const URL = require('url');
|
||||
const qs = require('querystring');
|
||||
const dns = require('dns');
|
||||
const MongoParseError = require('./error').MongoParseError;
|
||||
const ReadPreference = require('./topologies/read_preference');
|
||||
|
||||
/**
|
||||
* The following regular expression validates a connection string and breaks the
|
||||
* provide string into the following capture groups: [protocol, username, password, hosts]
|
||||
*/
|
||||
const HOSTS_RX = /(mongodb(?:\+srv|)):\/\/(?: (?:[^:]*) (?: : ([^@]*) )? @ )?([^/?]*)(?:\/|)(.*)/;
|
||||
|
||||
/**
|
||||
* Determines whether a provided address matches the provided parent domain in order
|
||||
* to avoid certain attack vectors.
|
||||
*
|
||||
* @param {String} srvAddress The address to check against a domain
|
||||
* @param {String} parentDomain The domain to check the provided address against
|
||||
* @return {Boolean} Whether the provided address matches the parent domain
|
||||
*/
|
||||
function matchesParentDomain(srvAddress, parentDomain) {
|
||||
const regex = /^.*?\./;
|
||||
const srv = `.${srvAddress.replace(regex, '')}`;
|
||||
const parent = `.${parentDomain.replace(regex, '')}`;
|
||||
return srv.endsWith(parent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Lookup a `mongodb+srv` connection string, combine the parts and reparse it as a normal
|
||||
* connection string.
|
||||
*
|
||||
* @param {string} uri The connection string to parse
|
||||
* @param {object} options Optional user provided connection string options
|
||||
* @param {function} callback
|
||||
*/
|
||||
function parseSrvConnectionString(uri, options, callback) {
|
||||
const result = URL.parse(uri, true);
|
||||
|
||||
if (options.directConnection || options.directconnection) {
|
||||
return callback(new MongoParseError('directConnection not supported with SRV URI'));
|
||||
}
|
||||
|
||||
if (result.hostname.split('.').length < 3) {
|
||||
return callback(new MongoParseError('URI does not have hostname, domain name and tld'));
|
||||
}
|
||||
|
||||
result.domainLength = result.hostname.split('.').length;
|
||||
if (result.pathname && result.pathname.match(',')) {
|
||||
return callback(new MongoParseError('Invalid URI, cannot contain multiple hostnames'));
|
||||
}
|
||||
|
||||
if (result.port) {
|
||||
return callback(new MongoParseError(`Ports not accepted with '${PROTOCOL_MONGODB_SRV}' URIs`));
|
||||
}
|
||||
|
||||
// Resolve the SRV record and use the result as the list of hosts to connect to.
|
||||
const lookupAddress = result.host;
|
||||
dns.resolveSrv(`_mongodb._tcp.${lookupAddress}`, (err, addresses) => {
|
||||
if (err) return callback(err);
|
||||
|
||||
if (addresses.length === 0) {
|
||||
return callback(new MongoParseError('No addresses found at host'));
|
||||
}
|
||||
|
||||
for (let i = 0; i < addresses.length; i++) {
|
||||
if (!matchesParentDomain(addresses[i].name, result.hostname, result.domainLength)) {
|
||||
return callback(
|
||||
new MongoParseError('Server record does not share hostname with parent URI')
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Convert the original URL to a non-SRV URL.
|
||||
result.protocol = 'mongodb';
|
||||
result.host = addresses.map(address => `${address.name}:${address.port}`).join(',');
|
||||
|
||||
// Default to SSL true if it's not specified.
|
||||
if (
|
||||
!('ssl' in options) &&
|
||||
(!result.search || !('ssl' in result.query) || result.query.ssl === null)
|
||||
) {
|
||||
result.query.ssl = true;
|
||||
}
|
||||
|
||||
// Resolve TXT record and add options from there if they exist.
|
||||
dns.resolveTxt(lookupAddress, (err, record) => {
|
||||
if (err) {
|
||||
if (err.code !== 'ENODATA') {
|
||||
return callback(err);
|
||||
}
|
||||
record = null;
|
||||
}
|
||||
|
||||
if (record) {
|
||||
if (record.length > 1) {
|
||||
return callback(new MongoParseError('Multiple text records not allowed'));
|
||||
}
|
||||
|
||||
record = qs.parse(record[0].join(''));
|
||||
if (Object.keys(record).some(key => key !== 'authSource' && key !== 'replicaSet')) {
|
||||
return callback(
|
||||
new MongoParseError('Text record must only set `authSource` or `replicaSet`')
|
||||
);
|
||||
}
|
||||
|
||||
result.query = Object.assign({}, record, result.query);
|
||||
}
|
||||
|
||||
// Set completed options back into the URL object.
|
||||
result.search = qs.stringify(result.query);
|
||||
|
||||
const finalString = URL.format(result);
|
||||
parseConnectionString(finalString, options, (err, ret) => {
|
||||
if (err) {
|
||||
callback(err);
|
||||
return;
|
||||
}
|
||||
|
||||
callback(null, Object.assign({}, ret, { srvHost: lookupAddress }));
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a query string item according to the connection string spec
|
||||
*
|
||||
* @param {string} key The key for the parsed value
|
||||
* @param {Array|String} value The value to parse
|
||||
* @return {Array|Object|String} The parsed value
|
||||
*/
|
||||
function parseQueryStringItemValue(key, value) {
|
||||
if (Array.isArray(value)) {
|
||||
// deduplicate and simplify arrays
|
||||
value = value.filter((v, idx) => value.indexOf(v) === idx);
|
||||
if (value.length === 1) value = value[0];
|
||||
} else if (value.indexOf(':') > 0) {
|
||||
value = value.split(',').reduce((result, pair) => {
|
||||
const parts = pair.split(':');
|
||||
result[parts[0]] = parseQueryStringItemValue(key, parts[1]);
|
||||
return result;
|
||||
}, {});
|
||||
} else if (value.indexOf(',') > 0) {
|
||||
value = value.split(',').map(v => {
|
||||
return parseQueryStringItemValue(key, v);
|
||||
});
|
||||
} else if (value.toLowerCase() === 'true' || value.toLowerCase() === 'false') {
|
||||
value = value.toLowerCase() === 'true';
|
||||
} else if (!Number.isNaN(value) && !STRING_OPTIONS.has(key)) {
|
||||
const numericValue = parseFloat(value);
|
||||
if (!Number.isNaN(numericValue)) {
|
||||
value = parseFloat(value);
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
// Options that are known boolean types
|
||||
const BOOLEAN_OPTIONS = new Set([
|
||||
'slaveok',
|
||||
'slave_ok',
|
||||
'sslvalidate',
|
||||
'fsync',
|
||||
'safe',
|
||||
'retrywrites',
|
||||
'j'
|
||||
]);
|
||||
|
||||
// Known string options, only used to bypass Number coercion in `parseQueryStringItemValue`
|
||||
const STRING_OPTIONS = new Set(['authsource', 'replicaset']);
|
||||
|
||||
// Supported text representations of auth mechanisms
|
||||
// NOTE: this list exists in native already, if it is merged here we should deduplicate
|
||||
const AUTH_MECHANISMS = new Set([
|
||||
'GSSAPI',
|
||||
'MONGODB-AWS',
|
||||
'MONGODB-X509',
|
||||
'MONGODB-CR',
|
||||
'DEFAULT',
|
||||
'SCRAM-SHA-1',
|
||||
'SCRAM-SHA-256',
|
||||
'PLAIN'
|
||||
]);
|
||||
|
||||
// Lookup table used to translate normalized (lower-cased) forms of connection string
|
||||
// options to their expected camelCase version
|
||||
const CASE_TRANSLATION = {
|
||||
replicaset: 'replicaSet',
|
||||
connecttimeoutms: 'connectTimeoutMS',
|
||||
sockettimeoutms: 'socketTimeoutMS',
|
||||
maxpoolsize: 'maxPoolSize',
|
||||
minpoolsize: 'minPoolSize',
|
||||
maxidletimems: 'maxIdleTimeMS',
|
||||
waitqueuemultiple: 'waitQueueMultiple',
|
||||
waitqueuetimeoutms: 'waitQueueTimeoutMS',
|
||||
wtimeoutms: 'wtimeoutMS',
|
||||
readconcern: 'readConcern',
|
||||
readconcernlevel: 'readConcernLevel',
|
||||
readpreference: 'readPreference',
|
||||
maxstalenessseconds: 'maxStalenessSeconds',
|
||||
readpreferencetags: 'readPreferenceTags',
|
||||
authsource: 'authSource',
|
||||
authmechanism: 'authMechanism',
|
||||
authmechanismproperties: 'authMechanismProperties',
|
||||
gssapiservicename: 'gssapiServiceName',
|
||||
localthresholdms: 'localThresholdMS',
|
||||
serverselectiontimeoutms: 'serverSelectionTimeoutMS',
|
||||
serverselectiontryonce: 'serverSelectionTryOnce',
|
||||
heartbeatfrequencyms: 'heartbeatFrequencyMS',
|
||||
retrywrites: 'retryWrites',
|
||||
uuidrepresentation: 'uuidRepresentation',
|
||||
zlibcompressionlevel: 'zlibCompressionLevel',
|
||||
tlsallowinvalidcertificates: 'tlsAllowInvalidCertificates',
|
||||
tlsallowinvalidhostnames: 'tlsAllowInvalidHostnames',
|
||||
tlsinsecure: 'tlsInsecure',
|
||||
tlscafile: 'tlsCAFile',
|
||||
tlscertificatekeyfile: 'tlsCertificateKeyFile',
|
||||
tlscertificatekeyfilepassword: 'tlsCertificateKeyFilePassword',
|
||||
wtimeout: 'wTimeoutMS',
|
||||
j: 'journal',
|
||||
directconnection: 'directConnection'
|
||||
};
|
||||
|
||||
/**
|
||||
* Sets the value for `key`, allowing for any required translation
|
||||
*
|
||||
* @param {object} obj The object to set the key on
|
||||
* @param {string} key The key to set the value for
|
||||
* @param {*} value The value to set
|
||||
* @param {object} options The options used for option parsing
|
||||
*/
|
||||
function applyConnectionStringOption(obj, key, value, options) {
|
||||
// simple key translation
|
||||
if (key === 'journal') {
|
||||
key = 'j';
|
||||
} else if (key === 'wtimeoutms') {
|
||||
key = 'wtimeout';
|
||||
}
|
||||
|
||||
// more complicated translation
|
||||
if (BOOLEAN_OPTIONS.has(key)) {
|
||||
value = value === 'true' || value === true;
|
||||
} else if (key === 'appname') {
|
||||
value = decodeURIComponent(value);
|
||||
} else if (key === 'readconcernlevel') {
|
||||
obj['readConcernLevel'] = value;
|
||||
key = 'readconcern';
|
||||
value = { level: value };
|
||||
}
|
||||
|
||||
// simple validation
|
||||
if (key === 'compressors') {
|
||||
value = Array.isArray(value) ? value : [value];
|
||||
|
||||
if (!value.every(c => c === 'snappy' || c === 'zlib')) {
|
||||
throw new MongoParseError(
|
||||
'Value for `compressors` must be at least one of: `snappy`, `zlib`'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (key === 'authmechanism' && !AUTH_MECHANISMS.has(value)) {
|
||||
throw new MongoParseError(
|
||||
`Value for authMechanism must be one of: ${Array.from(AUTH_MECHANISMS).join(
|
||||
', '
|
||||
)}, found: ${value}`
|
||||
);
|
||||
}
|
||||
|
||||
if (key === 'readpreference' && !ReadPreference.isValid(value)) {
|
||||
throw new MongoParseError(
|
||||
'Value for `readPreference` must be one of: `primary`, `primaryPreferred`, `secondary`, `secondaryPreferred`, `nearest`'
|
||||
);
|
||||
}
|
||||
|
||||
if (key === 'zlibcompressionlevel' && (value < -1 || value > 9)) {
|
||||
throw new MongoParseError('zlibCompressionLevel must be an integer between -1 and 9');
|
||||
}
|
||||
|
||||
// special cases
|
||||
if (key === 'compressors' || key === 'zlibcompressionlevel') {
|
||||
obj.compression = obj.compression || {};
|
||||
obj = obj.compression;
|
||||
}
|
||||
|
||||
if (key === 'authmechanismproperties') {
|
||||
if (typeof value.SERVICE_NAME === 'string') obj.gssapiServiceName = value.SERVICE_NAME;
|
||||
if (typeof value.SERVICE_REALM === 'string') obj.gssapiServiceRealm = value.SERVICE_REALM;
|
||||
if (typeof value.CANONICALIZE_HOST_NAME !== 'undefined') {
|
||||
obj.gssapiCanonicalizeHostName = value.CANONICALIZE_HOST_NAME;
|
||||
}
|
||||
}
|
||||
|
||||
if (key === 'readpreferencetags') {
|
||||
value = Array.isArray(value) ? splitArrayOfMultipleReadPreferenceTags(value) : [value];
|
||||
}
|
||||
|
||||
// set the actual value
|
||||
if (options.caseTranslate && CASE_TRANSLATION[key]) {
|
||||
obj[CASE_TRANSLATION[key]] = value;
|
||||
return;
|
||||
}
|
||||
|
||||
obj[key] = value;
|
||||
}
|
||||
|
||||
const USERNAME_REQUIRED_MECHANISMS = new Set([
|
||||
'GSSAPI',
|
||||
'MONGODB-CR',
|
||||
'PLAIN',
|
||||
'SCRAM-SHA-1',
|
||||
'SCRAM-SHA-256'
|
||||
]);
|
||||
|
||||
function splitArrayOfMultipleReadPreferenceTags(value) {
|
||||
const parsedTags = [];
|
||||
|
||||
for (let i = 0; i < value.length; i++) {
|
||||
parsedTags[i] = {};
|
||||
value[i].split(',').forEach(individualTag => {
|
||||
const splitTag = individualTag.split(':');
|
||||
parsedTags[i][splitTag[0]] = splitTag[1];
|
||||
});
|
||||
}
|
||||
|
||||
return parsedTags;
|
||||
}
|
||||
|
||||
/**
|
||||
* Modifies the parsed connection string object taking into account expectations we
|
||||
* have for authentication-related options.
|
||||
*
|
||||
* @param {object} parsed The parsed connection string result
|
||||
* @return The parsed connection string result possibly modified for auth expectations
|
||||
*/
|
||||
function applyAuthExpectations(parsed) {
|
||||
if (parsed.options == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const options = parsed.options;
|
||||
const authSource = options.authsource || options.authSource;
|
||||
if (authSource != null) {
|
||||
parsed.auth = Object.assign({}, parsed.auth, { db: authSource });
|
||||
}
|
||||
|
||||
const authMechanism = options.authmechanism || options.authMechanism;
|
||||
if (authMechanism != null) {
|
||||
if (
|
||||
USERNAME_REQUIRED_MECHANISMS.has(authMechanism) &&
|
||||
(!parsed.auth || parsed.auth.username == null)
|
||||
) {
|
||||
throw new MongoParseError(`Username required for mechanism \`${authMechanism}\``);
|
||||
}
|
||||
|
||||
if (authMechanism === 'GSSAPI') {
|
||||
if (authSource != null && authSource !== '$external') {
|
||||
throw new MongoParseError(
|
||||
`Invalid source \`${authSource}\` for mechanism \`${authMechanism}\` specified.`
|
||||
);
|
||||
}
|
||||
|
||||
parsed.auth = Object.assign({}, parsed.auth, { db: '$external' });
|
||||
}
|
||||
|
||||
if (authMechanism === 'MONGODB-AWS') {
|
||||
if (authSource != null && authSource !== '$external') {
|
||||
throw new MongoParseError(
|
||||
`Invalid source \`${authSource}\` for mechanism \`${authMechanism}\` specified.`
|
||||
);
|
||||
}
|
||||
|
||||
parsed.auth = Object.assign({}, parsed.auth, { db: '$external' });
|
||||
}
|
||||
|
||||
if (authMechanism === 'MONGODB-X509') {
|
||||
if (parsed.auth && parsed.auth.password != null) {
|
||||
throw new MongoParseError(`Password not allowed for mechanism \`${authMechanism}\``);
|
||||
}
|
||||
|
||||
if (authSource != null && authSource !== '$external') {
|
||||
throw new MongoParseError(
|
||||
`Invalid source \`${authSource}\` for mechanism \`${authMechanism}\` specified.`
|
||||
);
|
||||
}
|
||||
|
||||
parsed.auth = Object.assign({}, parsed.auth, { db: '$external' });
|
||||
}
|
||||
|
||||
if (authMechanism === 'PLAIN') {
|
||||
if (parsed.auth && parsed.auth.db == null) {
|
||||
parsed.auth = Object.assign({}, parsed.auth, { db: '$external' });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// default to `admin` if nothing else was resolved
|
||||
if (parsed.auth && parsed.auth.db == null) {
|
||||
parsed.auth = Object.assign({}, parsed.auth, { db: 'admin' });
|
||||
}
|
||||
|
||||
return parsed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a query string according the connection string spec.
|
||||
*
|
||||
* @param {String} query The query string to parse
|
||||
* @param {object} [options] The options used for options parsing
|
||||
* @return {Object|Error} The parsed query string as an object, or an error if one was encountered
|
||||
*/
|
||||
function parseQueryString(query, options) {
|
||||
const result = {};
|
||||
let parsedQueryString = qs.parse(query);
|
||||
|
||||
checkTLSOptions(parsedQueryString);
|
||||
|
||||
for (const key in parsedQueryString) {
|
||||
const value = parsedQueryString[key];
|
||||
if (value === '' || value == null) {
|
||||
throw new MongoParseError('Incomplete key value pair for option');
|
||||
}
|
||||
|
||||
const normalizedKey = key.toLowerCase();
|
||||
const parsedValue = parseQueryStringItemValue(normalizedKey, value);
|
||||
applyConnectionStringOption(result, normalizedKey, parsedValue, options);
|
||||
}
|
||||
|
||||
// special cases for known deprecated options
|
||||
if (result.wtimeout && result.wtimeoutms) {
|
||||
delete result.wtimeout;
|
||||
console.warn('Unsupported option `wtimeout` specified');
|
||||
}
|
||||
|
||||
return Object.keys(result).length ? result : null;
|
||||
}
|
||||
|
||||
/// Adds support for modern `tls` variants of out `ssl` options
|
||||
function translateTLSOptions(queryString) {
|
||||
if (queryString.tls) {
|
||||
queryString.ssl = queryString.tls;
|
||||
}
|
||||
|
||||
if (queryString.tlsInsecure) {
|
||||
queryString.checkServerIdentity = false;
|
||||
queryString.sslValidate = false;
|
||||
} else {
|
||||
Object.assign(queryString, {
|
||||
checkServerIdentity: queryString.tlsAllowInvalidHostnames ? false : true,
|
||||
sslValidate: queryString.tlsAllowInvalidCertificates ? false : true
|
||||
});
|
||||
}
|
||||
|
||||
if (queryString.tlsCAFile) {
|
||||
queryString.ssl = true;
|
||||
queryString.sslCA = queryString.tlsCAFile;
|
||||
}
|
||||
|
||||
if (queryString.tlsCertificateKeyFile) {
|
||||
queryString.ssl = true;
|
||||
if (queryString.tlsCertificateFile) {
|
||||
queryString.sslCert = queryString.tlsCertificateFile;
|
||||
queryString.sslKey = queryString.tlsCertificateKeyFile;
|
||||
} else {
|
||||
queryString.sslKey = queryString.tlsCertificateKeyFile;
|
||||
queryString.sslCert = queryString.tlsCertificateKeyFile;
|
||||
}
|
||||
}
|
||||
|
||||
if (queryString.tlsCertificateKeyFilePassword) {
|
||||
queryString.ssl = true;
|
||||
queryString.sslPass = queryString.tlsCertificateKeyFilePassword;
|
||||
}
|
||||
|
||||
return queryString;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks a query string for invalid tls options according to the URI options spec.
|
||||
*
|
||||
* @param {string} queryString The query string to check
|
||||
* @throws {MongoParseError}
|
||||
*/
|
||||
function checkTLSOptions(queryString) {
|
||||
const queryStringKeys = Object.keys(queryString);
|
||||
if (
|
||||
queryStringKeys.indexOf('tlsInsecure') !== -1 &&
|
||||
(queryStringKeys.indexOf('tlsAllowInvalidCertificates') !== -1 ||
|
||||
queryStringKeys.indexOf('tlsAllowInvalidHostnames') !== -1)
|
||||
) {
|
||||
throw new MongoParseError(
|
||||
'The `tlsInsecure` option cannot be used with `tlsAllowInvalidCertificates` or `tlsAllowInvalidHostnames`.'
|
||||
);
|
||||
}
|
||||
|
||||
const tlsValue = assertTlsOptionsAreEqual('tls', queryString, queryStringKeys);
|
||||
const sslValue = assertTlsOptionsAreEqual('ssl', queryString, queryStringKeys);
|
||||
|
||||
if (tlsValue != null && sslValue != null) {
|
||||
if (tlsValue !== sslValue) {
|
||||
throw new MongoParseError('All values of `tls` and `ssl` must be the same.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks a query string to ensure all tls/ssl options are the same.
|
||||
*
|
||||
* @param {string} key The key (tls or ssl) to check
|
||||
* @param {string} queryString The query string to check
|
||||
* @throws {MongoParseError}
|
||||
* @return The value of the tls/ssl option
|
||||
*/
|
||||
function assertTlsOptionsAreEqual(optionName, queryString, queryStringKeys) {
|
||||
const queryStringHasTLSOption = queryStringKeys.indexOf(optionName) !== -1;
|
||||
|
||||
let optionValue;
|
||||
if (Array.isArray(queryString[optionName])) {
|
||||
optionValue = queryString[optionName][0];
|
||||
} else {
|
||||
optionValue = queryString[optionName];
|
||||
}
|
||||
|
||||
if (queryStringHasTLSOption) {
|
||||
if (Array.isArray(queryString[optionName])) {
|
||||
const firstValue = queryString[optionName][0];
|
||||
queryString[optionName].forEach(tlsValue => {
|
||||
if (tlsValue !== firstValue) {
|
||||
throw new MongoParseError(`All values of ${optionName} must be the same.`);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return optionValue;
|
||||
}
|
||||
|
||||
const PROTOCOL_MONGODB = 'mongodb';
|
||||
const PROTOCOL_MONGODB_SRV = 'mongodb+srv';
|
||||
const SUPPORTED_PROTOCOLS = [PROTOCOL_MONGODB, PROTOCOL_MONGODB_SRV];
|
||||
|
||||
/**
|
||||
* Parses a MongoDB connection string
|
||||
*
|
||||
* @param {*} uri the MongoDB connection string to parse
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {boolean} [options.caseTranslate] Whether the parser should translate options back into camelCase after normalization
|
||||
* @param {parseCallback} callback
|
||||
*/
|
||||
function parseConnectionString(uri, options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = Object.assign({}, { caseTranslate: true }, options);
|
||||
|
||||
// Check for bad uris before we parse
|
||||
try {
|
||||
URL.parse(uri);
|
||||
} catch (e) {
|
||||
return callback(new MongoParseError('URI malformed, cannot be parsed'));
|
||||
}
|
||||
|
||||
const cap = uri.match(HOSTS_RX);
|
||||
if (!cap) {
|
||||
return callback(new MongoParseError('Invalid connection string'));
|
||||
}
|
||||
|
||||
const protocol = cap[1];
|
||||
if (SUPPORTED_PROTOCOLS.indexOf(protocol) === -1) {
|
||||
return callback(new MongoParseError('Invalid protocol provided'));
|
||||
}
|
||||
|
||||
const dbAndQuery = cap[4].split('?');
|
||||
const db = dbAndQuery.length > 0 ? dbAndQuery[0] : null;
|
||||
const query = dbAndQuery.length > 1 ? dbAndQuery[1] : null;
|
||||
|
||||
let parsedOptions;
|
||||
try {
|
||||
parsedOptions = parseQueryString(query, options);
|
||||
} catch (parseError) {
|
||||
return callback(parseError);
|
||||
}
|
||||
|
||||
parsedOptions = Object.assign({}, parsedOptions, options);
|
||||
|
||||
if (protocol === PROTOCOL_MONGODB_SRV) {
|
||||
return parseSrvConnectionString(uri, parsedOptions, callback);
|
||||
}
|
||||
|
||||
const auth = { username: null, password: null, db: db && db !== '' ? qs.unescape(db) : null };
|
||||
if (parsedOptions.auth) {
|
||||
// maintain support for legacy options passed into `MongoClient`
|
||||
if (parsedOptions.auth.username) auth.username = parsedOptions.auth.username;
|
||||
if (parsedOptions.auth.user) auth.username = parsedOptions.auth.user;
|
||||
if (parsedOptions.auth.password) auth.password = parsedOptions.auth.password;
|
||||
} else {
|
||||
if (parsedOptions.username) auth.username = parsedOptions.username;
|
||||
if (parsedOptions.user) auth.username = parsedOptions.user;
|
||||
if (parsedOptions.password) auth.password = parsedOptions.password;
|
||||
}
|
||||
|
||||
if (cap[4].split('?')[0].indexOf('@') !== -1) {
|
||||
return callback(new MongoParseError('Unescaped slash in userinfo section'));
|
||||
}
|
||||
|
||||
const authorityParts = cap[3].split('@');
|
||||
if (authorityParts.length > 2) {
|
||||
return callback(new MongoParseError('Unescaped at-sign in authority section'));
|
||||
}
|
||||
|
||||
if (authorityParts[0] == null || authorityParts[0] === '') {
|
||||
return callback(new MongoParseError('No username provided in authority section'));
|
||||
}
|
||||
|
||||
if (authorityParts.length > 1) {
|
||||
const authParts = authorityParts.shift().split(':');
|
||||
if (authParts.length > 2) {
|
||||
return callback(new MongoParseError('Unescaped colon in authority section'));
|
||||
}
|
||||
|
||||
if (authParts[0] === '') {
|
||||
return callback(new MongoParseError('Invalid empty username provided'));
|
||||
}
|
||||
|
||||
if (!auth.username) auth.username = qs.unescape(authParts[0]);
|
||||
if (!auth.password) auth.password = authParts[1] ? qs.unescape(authParts[1]) : null;
|
||||
}
|
||||
|
||||
let hostParsingError = null;
|
||||
const hosts = authorityParts
|
||||
.shift()
|
||||
.split(',')
|
||||
.map(host => {
|
||||
let parsedHost = URL.parse(`mongodb://${host}`);
|
||||
if (parsedHost.path === '/:') {
|
||||
hostParsingError = new MongoParseError('Double colon in host identifier');
|
||||
return null;
|
||||
}
|
||||
|
||||
// heuristically determine if we're working with a domain socket
|
||||
if (host.match(/\.sock/)) {
|
||||
parsedHost.hostname = qs.unescape(host);
|
||||
parsedHost.port = null;
|
||||
}
|
||||
|
||||
if (Number.isNaN(parsedHost.port)) {
|
||||
hostParsingError = new MongoParseError('Invalid port (non-numeric string)');
|
||||
return;
|
||||
}
|
||||
|
||||
const result = {
|
||||
host: parsedHost.hostname,
|
||||
port: parsedHost.port ? parseInt(parsedHost.port) : 27017
|
||||
};
|
||||
|
||||
if (result.port === 0) {
|
||||
hostParsingError = new MongoParseError('Invalid port (zero) with hostname');
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.port > 65535) {
|
||||
hostParsingError = new MongoParseError('Invalid port (larger than 65535) with hostname');
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.port < 0) {
|
||||
hostParsingError = new MongoParseError('Invalid port (negative number)');
|
||||
return;
|
||||
}
|
||||
|
||||
return result;
|
||||
})
|
||||
.filter(host => !!host);
|
||||
|
||||
if (hostParsingError) {
|
||||
return callback(hostParsingError);
|
||||
}
|
||||
|
||||
if (hosts.length === 0 || hosts[0].host === '' || hosts[0].host === null) {
|
||||
return callback(new MongoParseError('No hostname or hostnames provided in connection string'));
|
||||
}
|
||||
|
||||
const directConnection = !!parsedOptions.directConnection;
|
||||
if (directConnection && hosts.length !== 1) {
|
||||
// If the option is set to true, the driver MUST validate that there is exactly one host given
|
||||
// in the host list in the URI, and fail client creation otherwise.
|
||||
return callback(new MongoParseError('directConnection option requires exactly one host'));
|
||||
}
|
||||
|
||||
// NOTE: this behavior will go away in v4.0, we will always auto discover there
|
||||
if (
|
||||
parsedOptions.directConnection == null &&
|
||||
hosts.length === 1 &&
|
||||
parsedOptions.replicaSet == null
|
||||
) {
|
||||
parsedOptions.directConnection = true;
|
||||
}
|
||||
|
||||
const result = {
|
||||
hosts: hosts,
|
||||
auth: auth.db || auth.username ? auth : null,
|
||||
options: Object.keys(parsedOptions).length ? parsedOptions : null
|
||||
};
|
||||
|
||||
if (result.auth && result.auth.db) {
|
||||
result.defaultDatabase = result.auth.db;
|
||||
} else {
|
||||
result.defaultDatabase = 'test';
|
||||
}
|
||||
|
||||
// support modern `tls` variants to SSL options
|
||||
result.options = translateTLSOptions(result.options);
|
||||
|
||||
try {
|
||||
applyAuthExpectations(result);
|
||||
} catch (authError) {
|
||||
return callback(authError);
|
||||
}
|
||||
|
||||
callback(null, result);
|
||||
}
|
||||
|
||||
module.exports = parseConnectionString;
|
||||
297
node_modules/mongodb/lib/core/utils.js
generated
vendored
Normal file
297
node_modules/mongodb/lib/core/utils.js
generated
vendored
Normal file
@@ -0,0 +1,297 @@
|
||||
'use strict';
|
||||
const os = require('os');
|
||||
const crypto = require('crypto');
|
||||
const requireOptional = require('require_optional');
|
||||
|
||||
/**
|
||||
* Generate a UUIDv4
|
||||
*/
|
||||
const uuidV4 = () => {
|
||||
const result = crypto.randomBytes(16);
|
||||
result[6] = (result[6] & 0x0f) | 0x40;
|
||||
result[8] = (result[8] & 0x3f) | 0x80;
|
||||
return result;
|
||||
};
|
||||
|
||||
/**
|
||||
* Relays events for a given listener and emitter
|
||||
*
|
||||
* @param {EventEmitter} listener the EventEmitter to listen to the events from
|
||||
* @param {EventEmitter} emitter the EventEmitter to relay the events to
|
||||
*/
|
||||
function relayEvents(listener, emitter, events) {
|
||||
events.forEach(eventName => listener.on(eventName, event => emitter.emit(eventName, event)));
|
||||
}
|
||||
|
||||
function retrieveKerberos() {
|
||||
let kerberos;
|
||||
|
||||
try {
|
||||
kerberos = requireOptional('kerberos');
|
||||
} catch (err) {
|
||||
if (err.code === 'MODULE_NOT_FOUND') {
|
||||
throw new Error('The `kerberos` module was not found. Please install it and try again.');
|
||||
}
|
||||
|
||||
throw err;
|
||||
}
|
||||
|
||||
return kerberos;
|
||||
}
|
||||
|
||||
// Throw an error if an attempt to use EJSON is made when it is not installed
|
||||
const noEJSONError = function() {
|
||||
throw new Error('The `mongodb-extjson` module was not found. Please install it and try again.');
|
||||
};
|
||||
|
||||
// Facilitate loading EJSON optionally
|
||||
function retrieveEJSON() {
|
||||
let EJSON = null;
|
||||
try {
|
||||
EJSON = requireOptional('mongodb-extjson');
|
||||
} catch (error) {} // eslint-disable-line
|
||||
if (!EJSON) {
|
||||
EJSON = {
|
||||
parse: noEJSONError,
|
||||
deserialize: noEJSONError,
|
||||
serialize: noEJSONError,
|
||||
stringify: noEJSONError,
|
||||
setBSONModule: noEJSONError,
|
||||
BSON: noEJSONError
|
||||
};
|
||||
}
|
||||
|
||||
return EJSON;
|
||||
}
|
||||
|
||||
/**
|
||||
* A helper function for determining `maxWireVersion` between legacy and new topology
|
||||
* instances
|
||||
*
|
||||
* @private
|
||||
* @param {(Topology|Server)} topologyOrServer
|
||||
*/
|
||||
function maxWireVersion(topologyOrServer) {
|
||||
if (topologyOrServer) {
|
||||
if (topologyOrServer.ismaster) {
|
||||
return topologyOrServer.ismaster.maxWireVersion;
|
||||
}
|
||||
|
||||
if (typeof topologyOrServer.lastIsMaster === 'function') {
|
||||
const lastIsMaster = topologyOrServer.lastIsMaster();
|
||||
if (lastIsMaster) {
|
||||
return lastIsMaster.maxWireVersion;
|
||||
}
|
||||
}
|
||||
|
||||
if (topologyOrServer.description) {
|
||||
return topologyOrServer.description.maxWireVersion;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Checks that collation is supported by server.
|
||||
*
|
||||
* @param {Server} [server] to check against
|
||||
* @param {object} [cmd] object where collation may be specified
|
||||
* @param {function} [callback] callback function
|
||||
* @return true if server does not support collation
|
||||
*/
|
||||
function collationNotSupported(server, cmd) {
|
||||
return cmd && cmd.collation && maxWireVersion(server) < 5;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a given value is a Promise
|
||||
*
|
||||
* @param {*} maybePromise
|
||||
* @return true if the provided value is a Promise
|
||||
*/
|
||||
function isPromiseLike(maybePromise) {
|
||||
return maybePromise && typeof maybePromise.then === 'function';
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the function `eachFn` to each item in `arr`, in parallel.
|
||||
*
|
||||
* @param {array} arr an array of items to asynchronusly iterate over
|
||||
* @param {function} eachFn A function to call on each item of the array. The callback signature is `(item, callback)`, where the callback indicates iteration is complete.
|
||||
* @param {function} callback The callback called after every item has been iterated
|
||||
*/
|
||||
function eachAsync(arr, eachFn, callback) {
|
||||
arr = arr || [];
|
||||
|
||||
let idx = 0;
|
||||
let awaiting = 0;
|
||||
for (idx = 0; idx < arr.length; ++idx) {
|
||||
awaiting++;
|
||||
eachFn(arr[idx], eachCallback);
|
||||
}
|
||||
|
||||
if (awaiting === 0) {
|
||||
callback();
|
||||
return;
|
||||
}
|
||||
|
||||
function eachCallback(err) {
|
||||
awaiting--;
|
||||
if (err) {
|
||||
callback(err);
|
||||
return;
|
||||
}
|
||||
|
||||
if (idx === arr.length && awaiting <= 0) {
|
||||
callback();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function eachAsyncSeries(arr, eachFn, callback) {
|
||||
arr = arr || [];
|
||||
|
||||
let idx = 0;
|
||||
let awaiting = arr.length;
|
||||
if (awaiting === 0) {
|
||||
callback();
|
||||
return;
|
||||
}
|
||||
|
||||
function eachCallback(err) {
|
||||
idx++;
|
||||
awaiting--;
|
||||
if (err) {
|
||||
callback(err);
|
||||
return;
|
||||
}
|
||||
|
||||
if (idx === arr.length && awaiting <= 0) {
|
||||
callback();
|
||||
return;
|
||||
}
|
||||
|
||||
eachFn(arr[idx], eachCallback);
|
||||
}
|
||||
|
||||
eachFn(arr[idx], eachCallback);
|
||||
}
|
||||
|
||||
function isUnifiedTopology(topology) {
|
||||
return topology.description != null;
|
||||
}
|
||||
|
||||
function arrayStrictEqual(arr, arr2) {
|
||||
if (!Array.isArray(arr) || !Array.isArray(arr2)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return arr.length === arr2.length && arr.every((elt, idx) => elt === arr2[idx]);
|
||||
}
|
||||
|
||||
function tagsStrictEqual(tags, tags2) {
|
||||
const tagsKeys = Object.keys(tags);
|
||||
const tags2Keys = Object.keys(tags2);
|
||||
return tagsKeys.length === tags2Keys.length && tagsKeys.every(key => tags2[key] === tags[key]);
|
||||
}
|
||||
|
||||
function errorStrictEqual(lhs, rhs) {
|
||||
if (lhs === rhs) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ((lhs == null && rhs != null) || (lhs != null && rhs == null)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (lhs.constructor.name !== rhs.constructor.name) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (lhs.message !== rhs.message) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function makeStateMachine(stateTable) {
|
||||
return function stateTransition(target, newState) {
|
||||
const legalStates = stateTable[target.s.state];
|
||||
if (legalStates && legalStates.indexOf(newState) < 0) {
|
||||
throw new TypeError(
|
||||
`illegal state transition from [${target.s.state}] => [${newState}], allowed: [${legalStates}]`
|
||||
);
|
||||
}
|
||||
|
||||
target.emit('stateChanged', target.s.state, newState);
|
||||
target.s.state = newState;
|
||||
};
|
||||
}
|
||||
|
||||
function makeClientMetadata(options) {
|
||||
options = options || {};
|
||||
|
||||
const metadata = {
|
||||
driver: {
|
||||
name: 'nodejs',
|
||||
version: require('../../package.json').version
|
||||
},
|
||||
os: {
|
||||
type: os.type(),
|
||||
name: process.platform,
|
||||
architecture: process.arch,
|
||||
version: os.release()
|
||||
},
|
||||
platform: `'Node.js ${process.version}, ${os.endianness} (${
|
||||
options.useUnifiedTopology ? 'unified' : 'legacy'
|
||||
})`
|
||||
};
|
||||
|
||||
// support optionally provided wrapping driver info
|
||||
if (options.driverInfo) {
|
||||
if (options.driverInfo.name) {
|
||||
metadata.driver.name = `${metadata.driver.name}|${options.driverInfo.name}`;
|
||||
}
|
||||
|
||||
if (options.driverInfo.version) {
|
||||
metadata.version = `${metadata.driver.version}|${options.driverInfo.version}`;
|
||||
}
|
||||
|
||||
if (options.driverInfo.platform) {
|
||||
metadata.platform = `${metadata.platform}|${options.driverInfo.platform}`;
|
||||
}
|
||||
}
|
||||
|
||||
if (options.appname) {
|
||||
// MongoDB requires the appname not exceed a byte length of 128
|
||||
const buffer = Buffer.from(options.appname);
|
||||
metadata.application = {
|
||||
name: buffer.length > 128 ? buffer.slice(0, 128).toString('utf8') : options.appname
|
||||
};
|
||||
}
|
||||
|
||||
return metadata;
|
||||
}
|
||||
|
||||
const noop = () => {};
|
||||
|
||||
module.exports = {
|
||||
uuidV4,
|
||||
relayEvents,
|
||||
collationNotSupported,
|
||||
retrieveEJSON,
|
||||
retrieveKerberos,
|
||||
maxWireVersion,
|
||||
isPromiseLike,
|
||||
eachAsync,
|
||||
eachAsyncSeries,
|
||||
isUnifiedTopology,
|
||||
arrayStrictEqual,
|
||||
tagsStrictEqual,
|
||||
errorStrictEqual,
|
||||
makeStateMachine,
|
||||
makeClientMetadata,
|
||||
noop
|
||||
};
|
||||
177
node_modules/mongodb/lib/core/wireprotocol/command.js
generated
vendored
Normal file
177
node_modules/mongodb/lib/core/wireprotocol/command.js
generated
vendored
Normal file
@@ -0,0 +1,177 @@
|
||||
'use strict';
|
||||
|
||||
const Query = require('../connection/commands').Query;
|
||||
const Msg = require('../connection/msg').Msg;
|
||||
const MongoError = require('../error').MongoError;
|
||||
const getReadPreference = require('./shared').getReadPreference;
|
||||
const isSharded = require('./shared').isSharded;
|
||||
const databaseNamespace = require('./shared').databaseNamespace;
|
||||
const isTransactionCommand = require('../transactions').isTransactionCommand;
|
||||
const applySession = require('../sessions').applySession;
|
||||
const MongoNetworkError = require('../error').MongoNetworkError;
|
||||
const maxWireVersion = require('../utils').maxWireVersion;
|
||||
|
||||
function isClientEncryptionEnabled(server) {
|
||||
const wireVersion = maxWireVersion(server);
|
||||
return wireVersion && server.autoEncrypter;
|
||||
}
|
||||
|
||||
function command(server, ns, cmd, options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options || {};
|
||||
|
||||
if (cmd == null) {
|
||||
return callback(new MongoError(`command ${JSON.stringify(cmd)} does not return a cursor`));
|
||||
}
|
||||
|
||||
if (!isClientEncryptionEnabled(server)) {
|
||||
_command(server, ns, cmd, options, callback);
|
||||
return;
|
||||
}
|
||||
|
||||
const wireVersion = maxWireVersion(server);
|
||||
if (typeof wireVersion !== 'number' || wireVersion < 8) {
|
||||
callback(new MongoError('Auto-encryption requires a minimum MongoDB version of 4.2'));
|
||||
return;
|
||||
}
|
||||
|
||||
_cryptCommand(server, ns, cmd, options, callback);
|
||||
}
|
||||
|
||||
function _command(server, ns, cmd, options, callback) {
|
||||
const bson = server.s.bson;
|
||||
const pool = server.s.pool;
|
||||
const readPreference = getReadPreference(cmd, options);
|
||||
const shouldUseOpMsg = supportsOpMsg(server);
|
||||
const session = options.session;
|
||||
|
||||
let clusterTime = server.clusterTime;
|
||||
let finalCmd = Object.assign({}, cmd);
|
||||
if (hasSessionSupport(server) && session) {
|
||||
if (
|
||||
session.clusterTime &&
|
||||
session.clusterTime.clusterTime.greaterThan(clusterTime.clusterTime)
|
||||
) {
|
||||
clusterTime = session.clusterTime;
|
||||
}
|
||||
|
||||
const err = applySession(session, finalCmd, options);
|
||||
if (err) {
|
||||
return callback(err);
|
||||
}
|
||||
}
|
||||
|
||||
// if we have a known cluster time, gossip it
|
||||
if (clusterTime) {
|
||||
finalCmd.$clusterTime = clusterTime;
|
||||
}
|
||||
|
||||
if (isSharded(server) && !shouldUseOpMsg && readPreference && readPreference.mode !== 'primary') {
|
||||
finalCmd = {
|
||||
$query: finalCmd,
|
||||
$readPreference: readPreference.toJSON()
|
||||
};
|
||||
}
|
||||
|
||||
const commandOptions = Object.assign(
|
||||
{
|
||||
command: true,
|
||||
numberToSkip: 0,
|
||||
numberToReturn: -1,
|
||||
checkKeys: false
|
||||
},
|
||||
options
|
||||
);
|
||||
|
||||
// This value is not overridable
|
||||
commandOptions.slaveOk = readPreference.slaveOk();
|
||||
|
||||
const cmdNs = `${databaseNamespace(ns)}.$cmd`;
|
||||
const message = shouldUseOpMsg
|
||||
? new Msg(bson, cmdNs, finalCmd, commandOptions)
|
||||
: new Query(bson, cmdNs, finalCmd, commandOptions);
|
||||
|
||||
const inTransaction = session && (session.inTransaction() || isTransactionCommand(finalCmd));
|
||||
const commandResponseHandler = inTransaction
|
||||
? function(err) {
|
||||
// We need to add a TransientTransactionError errorLabel, as stated in the transaction spec.
|
||||
if (
|
||||
err &&
|
||||
err instanceof MongoNetworkError &&
|
||||
!err.hasErrorLabel('TransientTransactionError')
|
||||
) {
|
||||
err.addErrorLabel('TransientTransactionError');
|
||||
}
|
||||
|
||||
if (
|
||||
!cmd.commitTransaction &&
|
||||
err &&
|
||||
err instanceof MongoError &&
|
||||
err.hasErrorLabel('TransientTransactionError')
|
||||
) {
|
||||
session.transaction.unpinServer();
|
||||
}
|
||||
|
||||
return callback.apply(null, arguments);
|
||||
}
|
||||
: callback;
|
||||
|
||||
try {
|
||||
pool.write(message, commandOptions, commandResponseHandler);
|
||||
} catch (err) {
|
||||
commandResponseHandler(err);
|
||||
}
|
||||
}
|
||||
|
||||
function hasSessionSupport(topology) {
|
||||
if (topology == null) return false;
|
||||
if (topology.description) {
|
||||
return topology.description.maxWireVersion >= 6;
|
||||
}
|
||||
|
||||
return topology.ismaster == null ? false : topology.ismaster.maxWireVersion >= 6;
|
||||
}
|
||||
|
||||
function supportsOpMsg(topologyOrServer) {
|
||||
const description = topologyOrServer.ismaster
|
||||
? topologyOrServer.ismaster
|
||||
: topologyOrServer.description;
|
||||
|
||||
if (description == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return description.maxWireVersion >= 6 && description.__nodejs_mock_server__ == null;
|
||||
}
|
||||
|
||||
function _cryptCommand(server, ns, cmd, options, callback) {
|
||||
const autoEncrypter = server.autoEncrypter;
|
||||
function commandResponseHandler(err, response) {
|
||||
if (err || response == null) {
|
||||
callback(err, response);
|
||||
return;
|
||||
}
|
||||
|
||||
autoEncrypter.decrypt(response.result, options, (err, decrypted) => {
|
||||
if (err) {
|
||||
callback(err, null);
|
||||
return;
|
||||
}
|
||||
|
||||
response.result = decrypted;
|
||||
response.message.documents = [decrypted];
|
||||
callback(null, response);
|
||||
});
|
||||
}
|
||||
|
||||
autoEncrypter.encrypt(ns, cmd, options, (err, encrypted) => {
|
||||
if (err) {
|
||||
callback(err, null);
|
||||
return;
|
||||
}
|
||||
|
||||
_command(server, ns, encrypted, options, commandResponseHandler);
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = command;
|
||||
73
node_modules/mongodb/lib/core/wireprotocol/compression.js
generated
vendored
Normal file
73
node_modules/mongodb/lib/core/wireprotocol/compression.js
generated
vendored
Normal file
@@ -0,0 +1,73 @@
|
||||
'use strict';
|
||||
|
||||
const Snappy = require('../connection/utils').retrieveSnappy();
|
||||
const zlib = require('zlib');
|
||||
|
||||
const compressorIDs = {
|
||||
snappy: 1,
|
||||
zlib: 2
|
||||
};
|
||||
|
||||
const uncompressibleCommands = new Set([
|
||||
'ismaster',
|
||||
'saslStart',
|
||||
'saslContinue',
|
||||
'getnonce',
|
||||
'authenticate',
|
||||
'createUser',
|
||||
'updateUser',
|
||||
'copydbSaslStart',
|
||||
'copydbgetnonce',
|
||||
'copydb'
|
||||
]);
|
||||
|
||||
// Facilitate compressing a message using an agreed compressor
|
||||
function compress(self, dataToBeCompressed, callback) {
|
||||
switch (self.options.agreedCompressor) {
|
||||
case 'snappy':
|
||||
Snappy.compress(dataToBeCompressed, callback);
|
||||
break;
|
||||
case 'zlib':
|
||||
// Determine zlibCompressionLevel
|
||||
var zlibOptions = {};
|
||||
if (self.options.zlibCompressionLevel) {
|
||||
zlibOptions.level = self.options.zlibCompressionLevel;
|
||||
}
|
||||
zlib.deflate(dataToBeCompressed, zlibOptions, callback);
|
||||
break;
|
||||
default:
|
||||
throw new Error(
|
||||
'Attempt to compress message using unknown compressor "' +
|
||||
self.options.agreedCompressor +
|
||||
'".'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Decompress a message using the given compressor
|
||||
function decompress(compressorID, compressedData, callback) {
|
||||
if (compressorID < 0 || compressorID > compressorIDs.length) {
|
||||
throw new Error(
|
||||
'Server sent message compressed using an unsupported compressor. (Received compressor ID ' +
|
||||
compressorID +
|
||||
')'
|
||||
);
|
||||
}
|
||||
switch (compressorID) {
|
||||
case compressorIDs.snappy:
|
||||
Snappy.uncompress(compressedData, callback);
|
||||
break;
|
||||
case compressorIDs.zlib:
|
||||
zlib.inflate(compressedData, callback);
|
||||
break;
|
||||
default:
|
||||
callback(null, compressedData);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
compressorIDs,
|
||||
uncompressibleCommands,
|
||||
compress,
|
||||
decompress
|
||||
};
|
||||
13
node_modules/mongodb/lib/core/wireprotocol/constants.js
generated
vendored
Normal file
13
node_modules/mongodb/lib/core/wireprotocol/constants.js
generated
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
'use strict';
|
||||
|
||||
const MIN_SUPPORTED_SERVER_VERSION = '2.6';
|
||||
const MAX_SUPPORTED_SERVER_VERSION = '4.4';
|
||||
const MIN_SUPPORTED_WIRE_VERSION = 2;
|
||||
const MAX_SUPPORTED_WIRE_VERSION = 9;
|
||||
|
||||
module.exports = {
|
||||
MIN_SUPPORTED_SERVER_VERSION,
|
||||
MAX_SUPPORTED_SERVER_VERSION,
|
||||
MIN_SUPPORTED_WIRE_VERSION,
|
||||
MAX_SUPPORTED_WIRE_VERSION
|
||||
};
|
||||
95
node_modules/mongodb/lib/core/wireprotocol/get_more.js
generated
vendored
Normal file
95
node_modules/mongodb/lib/core/wireprotocol/get_more.js
generated
vendored
Normal file
@@ -0,0 +1,95 @@
|
||||
'use strict';
|
||||
|
||||
const GetMore = require('../connection/commands').GetMore;
|
||||
const retrieveBSON = require('../connection/utils').retrieveBSON;
|
||||
const MongoError = require('../error').MongoError;
|
||||
const MongoNetworkError = require('../error').MongoNetworkError;
|
||||
const BSON = retrieveBSON();
|
||||
const Long = BSON.Long;
|
||||
const collectionNamespace = require('./shared').collectionNamespace;
|
||||
const maxWireVersion = require('../utils').maxWireVersion;
|
||||
const applyCommonQueryOptions = require('./shared').applyCommonQueryOptions;
|
||||
const command = require('./command');
|
||||
|
||||
function getMore(server, ns, cursorState, batchSize, options, callback) {
|
||||
options = options || {};
|
||||
|
||||
const wireVersion = maxWireVersion(server);
|
||||
function queryCallback(err, result) {
|
||||
if (err) return callback(err);
|
||||
const response = result.message;
|
||||
|
||||
// If we have a timed out query or a cursor that was killed
|
||||
if (response.cursorNotFound) {
|
||||
return callback(new MongoNetworkError('cursor killed or timed out'), null);
|
||||
}
|
||||
|
||||
if (wireVersion < 4) {
|
||||
const cursorId =
|
||||
typeof response.cursorId === 'number'
|
||||
? Long.fromNumber(response.cursorId)
|
||||
: response.cursorId;
|
||||
|
||||
cursorState.documents = response.documents;
|
||||
cursorState.cursorId = cursorId;
|
||||
|
||||
callback(null, null, response.connection);
|
||||
return;
|
||||
}
|
||||
|
||||
// We have an error detected
|
||||
if (response.documents[0].ok === 0) {
|
||||
return callback(new MongoError(response.documents[0]));
|
||||
}
|
||||
|
||||
// Ensure we have a Long valid cursor id
|
||||
const cursorId =
|
||||
typeof response.documents[0].cursor.id === 'number'
|
||||
? Long.fromNumber(response.documents[0].cursor.id)
|
||||
: response.documents[0].cursor.id;
|
||||
|
||||
cursorState.documents = response.documents[0].cursor.nextBatch;
|
||||
cursorState.cursorId = cursorId;
|
||||
|
||||
callback(null, response.documents[0], response.connection);
|
||||
}
|
||||
|
||||
if (wireVersion < 4) {
|
||||
const bson = server.s.bson;
|
||||
const getMoreOp = new GetMore(bson, ns, cursorState.cursorId, { numberToReturn: batchSize });
|
||||
const queryOptions = applyCommonQueryOptions({}, cursorState);
|
||||
server.s.pool.write(getMoreOp, queryOptions, queryCallback);
|
||||
return;
|
||||
}
|
||||
|
||||
const cursorId =
|
||||
cursorState.cursorId instanceof Long
|
||||
? cursorState.cursorId
|
||||
: Long.fromNumber(cursorState.cursorId);
|
||||
|
||||
const getMoreCmd = {
|
||||
getMore: cursorId,
|
||||
collection: collectionNamespace(ns),
|
||||
batchSize: Math.abs(batchSize)
|
||||
};
|
||||
|
||||
if (cursorState.cmd.tailable && typeof cursorState.cmd.maxAwaitTimeMS === 'number') {
|
||||
getMoreCmd.maxTimeMS = cursorState.cmd.maxAwaitTimeMS;
|
||||
}
|
||||
|
||||
const commandOptions = Object.assign(
|
||||
{
|
||||
returnFieldSelector: null,
|
||||
documentsReturnedIn: 'nextBatch'
|
||||
},
|
||||
options
|
||||
);
|
||||
|
||||
if (cursorState.session) {
|
||||
commandOptions.session = cursorState.session;
|
||||
}
|
||||
|
||||
command(server, ns, getMoreCmd, commandOptions, queryCallback);
|
||||
}
|
||||
|
||||
module.exports = getMore;
|
||||
18
node_modules/mongodb/lib/core/wireprotocol/index.js
generated
vendored
Normal file
18
node_modules/mongodb/lib/core/wireprotocol/index.js
generated
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
'use strict';
|
||||
const writeCommand = require('./write_command');
|
||||
|
||||
module.exports = {
|
||||
insert: function insert(server, ns, ops, options, callback) {
|
||||
writeCommand(server, 'insert', 'documents', ns, ops, options, callback);
|
||||
},
|
||||
update: function update(server, ns, ops, options, callback) {
|
||||
writeCommand(server, 'update', 'updates', ns, ops, options, callback);
|
||||
},
|
||||
remove: function remove(server, ns, ops, options, callback) {
|
||||
writeCommand(server, 'delete', 'deletes', ns, ops, options, callback);
|
||||
},
|
||||
killCursors: require('./kill_cursors'),
|
||||
getMore: require('./get_more'),
|
||||
query: require('./query'),
|
||||
command: require('./command')
|
||||
};
|
||||
70
node_modules/mongodb/lib/core/wireprotocol/kill_cursors.js
generated
vendored
Normal file
70
node_modules/mongodb/lib/core/wireprotocol/kill_cursors.js
generated
vendored
Normal file
@@ -0,0 +1,70 @@
|
||||
'use strict';
|
||||
|
||||
const KillCursor = require('../connection/commands').KillCursor;
|
||||
const MongoError = require('../error').MongoError;
|
||||
const MongoNetworkError = require('../error').MongoNetworkError;
|
||||
const collectionNamespace = require('./shared').collectionNamespace;
|
||||
const maxWireVersion = require('../utils').maxWireVersion;
|
||||
const command = require('./command');
|
||||
|
||||
function killCursors(server, ns, cursorState, callback) {
|
||||
callback = typeof callback === 'function' ? callback : () => {};
|
||||
const cursorId = cursorState.cursorId;
|
||||
|
||||
if (maxWireVersion(server) < 4) {
|
||||
const bson = server.s.bson;
|
||||
const pool = server.s.pool;
|
||||
const killCursor = new KillCursor(bson, ns, [cursorId]);
|
||||
const options = {
|
||||
immediateRelease: true,
|
||||
noResponse: true
|
||||
};
|
||||
|
||||
if (typeof cursorState.session === 'object') {
|
||||
options.session = cursorState.session;
|
||||
}
|
||||
|
||||
if (pool && pool.isConnected()) {
|
||||
try {
|
||||
pool.write(killCursor, options, callback);
|
||||
} catch (err) {
|
||||
if (typeof callback === 'function') {
|
||||
callback(err, null);
|
||||
} else {
|
||||
console.warn(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const killCursorCmd = {
|
||||
killCursors: collectionNamespace(ns),
|
||||
cursors: [cursorId]
|
||||
};
|
||||
|
||||
const options = {};
|
||||
if (typeof cursorState.session === 'object') options.session = cursorState.session;
|
||||
|
||||
command(server, ns, killCursorCmd, options, (err, result) => {
|
||||
if (err) {
|
||||
return callback(err);
|
||||
}
|
||||
|
||||
const response = result.message;
|
||||
if (response.cursorNotFound) {
|
||||
return callback(new MongoNetworkError('cursor killed or timed out'), null);
|
||||
}
|
||||
|
||||
if (!Array.isArray(response.documents) || response.documents.length === 0) {
|
||||
return callback(
|
||||
new MongoError(`invalid killCursors result returned for cursor id ${cursorId}`)
|
||||
);
|
||||
}
|
||||
|
||||
callback(null, response.documents[0]);
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = killCursors;
|
||||
235
node_modules/mongodb/lib/core/wireprotocol/query.js
generated
vendored
Normal file
235
node_modules/mongodb/lib/core/wireprotocol/query.js
generated
vendored
Normal file
@@ -0,0 +1,235 @@
|
||||
'use strict';
|
||||
|
||||
const Query = require('../connection/commands').Query;
|
||||
const MongoError = require('../error').MongoError;
|
||||
const getReadPreference = require('./shared').getReadPreference;
|
||||
const collectionNamespace = require('./shared').collectionNamespace;
|
||||
const isSharded = require('./shared').isSharded;
|
||||
const maxWireVersion = require('../utils').maxWireVersion;
|
||||
const applyCommonQueryOptions = require('./shared').applyCommonQueryOptions;
|
||||
const command = require('./command');
|
||||
|
||||
function query(server, ns, cmd, cursorState, options, callback) {
|
||||
options = options || {};
|
||||
if (cursorState.cursorId != null) {
|
||||
return callback();
|
||||
}
|
||||
|
||||
if (cmd == null) {
|
||||
return callback(new MongoError(`command ${JSON.stringify(cmd)} does not return a cursor`));
|
||||
}
|
||||
|
||||
if (maxWireVersion(server) < 4) {
|
||||
const query = prepareLegacyFindQuery(server, ns, cmd, cursorState, options);
|
||||
const queryOptions = applyCommonQueryOptions({}, cursorState);
|
||||
if (typeof query.documentsReturnedIn === 'string') {
|
||||
queryOptions.documentsReturnedIn = query.documentsReturnedIn;
|
||||
}
|
||||
|
||||
server.s.pool.write(query, queryOptions, callback);
|
||||
return;
|
||||
}
|
||||
|
||||
const readPreference = getReadPreference(cmd, options);
|
||||
const findCmd = prepareFindCommand(server, ns, cmd, cursorState, options);
|
||||
|
||||
// NOTE: This actually modifies the passed in cmd, and our code _depends_ on this
|
||||
// side-effect. Change this ASAP
|
||||
cmd.virtual = false;
|
||||
|
||||
const commandOptions = Object.assign(
|
||||
{
|
||||
documentsReturnedIn: 'firstBatch',
|
||||
numberToReturn: 1,
|
||||
slaveOk: readPreference.slaveOk()
|
||||
},
|
||||
options
|
||||
);
|
||||
|
||||
if (cmd.readPreference) {
|
||||
commandOptions.readPreference = readPreference;
|
||||
}
|
||||
|
||||
if (cursorState.session) {
|
||||
commandOptions.session = cursorState.session;
|
||||
}
|
||||
|
||||
command(server, ns, findCmd, commandOptions, callback);
|
||||
}
|
||||
|
||||
function prepareFindCommand(server, ns, cmd, cursorState) {
|
||||
cursorState.batchSize = cmd.batchSize || cursorState.batchSize;
|
||||
let findCmd = {
|
||||
find: collectionNamespace(ns)
|
||||
};
|
||||
|
||||
if (cmd.query) {
|
||||
if (cmd.query['$query']) {
|
||||
findCmd.filter = cmd.query['$query'];
|
||||
} else {
|
||||
findCmd.filter = cmd.query;
|
||||
}
|
||||
}
|
||||
|
||||
let sortValue = cmd.sort;
|
||||
if (Array.isArray(sortValue)) {
|
||||
const sortObject = {};
|
||||
|
||||
if (sortValue.length > 0 && !Array.isArray(sortValue[0])) {
|
||||
let sortDirection = sortValue[1];
|
||||
if (sortDirection === 'asc') {
|
||||
sortDirection = 1;
|
||||
} else if (sortDirection === 'desc') {
|
||||
sortDirection = -1;
|
||||
}
|
||||
|
||||
sortObject[sortValue[0]] = sortDirection;
|
||||
} else {
|
||||
for (let i = 0; i < sortValue.length; i++) {
|
||||
let sortDirection = sortValue[i][1];
|
||||
if (sortDirection === 'asc') {
|
||||
sortDirection = 1;
|
||||
} else if (sortDirection === 'desc') {
|
||||
sortDirection = -1;
|
||||
}
|
||||
|
||||
sortObject[sortValue[i][0]] = sortDirection;
|
||||
}
|
||||
}
|
||||
|
||||
sortValue = sortObject;
|
||||
}
|
||||
|
||||
if (typeof cmd.allowDiskUse === 'boolean') {
|
||||
findCmd.allowDiskUse = cmd.allowDiskUse;
|
||||
}
|
||||
|
||||
if (cmd.sort) findCmd.sort = sortValue;
|
||||
if (cmd.fields) findCmd.projection = cmd.fields;
|
||||
if (cmd.hint) findCmd.hint = cmd.hint;
|
||||
if (cmd.skip) findCmd.skip = cmd.skip;
|
||||
if (cmd.limit) findCmd.limit = cmd.limit;
|
||||
if (cmd.limit < 0) {
|
||||
findCmd.limit = Math.abs(cmd.limit);
|
||||
findCmd.singleBatch = true;
|
||||
}
|
||||
|
||||
if (typeof cmd.batchSize === 'number') {
|
||||
if (cmd.batchSize < 0) {
|
||||
if (cmd.limit !== 0 && Math.abs(cmd.batchSize) < Math.abs(cmd.limit)) {
|
||||
findCmd.limit = Math.abs(cmd.batchSize);
|
||||
}
|
||||
|
||||
findCmd.singleBatch = true;
|
||||
}
|
||||
|
||||
findCmd.batchSize = Math.abs(cmd.batchSize);
|
||||
}
|
||||
|
||||
if (cmd.comment) findCmd.comment = cmd.comment;
|
||||
if (cmd.maxScan) findCmd.maxScan = cmd.maxScan;
|
||||
if (cmd.maxTimeMS) findCmd.maxTimeMS = cmd.maxTimeMS;
|
||||
if (cmd.min) findCmd.min = cmd.min;
|
||||
if (cmd.max) findCmd.max = cmd.max;
|
||||
findCmd.returnKey = cmd.returnKey ? cmd.returnKey : false;
|
||||
findCmd.showRecordId = cmd.showDiskLoc ? cmd.showDiskLoc : false;
|
||||
if (cmd.snapshot) findCmd.snapshot = cmd.snapshot;
|
||||
if (cmd.tailable) findCmd.tailable = cmd.tailable;
|
||||
if (cmd.oplogReplay) findCmd.oplogReplay = cmd.oplogReplay;
|
||||
if (cmd.noCursorTimeout) findCmd.noCursorTimeout = cmd.noCursorTimeout;
|
||||
if (cmd.awaitData) findCmd.awaitData = cmd.awaitData;
|
||||
if (cmd.awaitdata) findCmd.awaitData = cmd.awaitdata;
|
||||
if (cmd.partial) findCmd.partial = cmd.partial;
|
||||
if (cmd.collation) findCmd.collation = cmd.collation;
|
||||
if (cmd.readConcern) findCmd.readConcern = cmd.readConcern;
|
||||
|
||||
// If we have explain, we need to rewrite the find command
|
||||
// to wrap it in the explain command
|
||||
if (cmd.explain) {
|
||||
findCmd = {
|
||||
explain: findCmd
|
||||
};
|
||||
}
|
||||
|
||||
return findCmd;
|
||||
}
|
||||
|
||||
function prepareLegacyFindQuery(server, ns, cmd, cursorState, options) {
|
||||
options = options || {};
|
||||
const bson = server.s.bson;
|
||||
const readPreference = getReadPreference(cmd, options);
|
||||
cursorState.batchSize = cmd.batchSize || cursorState.batchSize;
|
||||
|
||||
let numberToReturn = 0;
|
||||
if (
|
||||
cursorState.limit < 0 ||
|
||||
(cursorState.limit !== 0 && cursorState.limit < cursorState.batchSize) ||
|
||||
(cursorState.limit > 0 && cursorState.batchSize === 0)
|
||||
) {
|
||||
numberToReturn = cursorState.limit;
|
||||
} else {
|
||||
numberToReturn = cursorState.batchSize;
|
||||
}
|
||||
|
||||
const numberToSkip = cursorState.skip || 0;
|
||||
|
||||
const findCmd = {};
|
||||
if (isSharded(server) && readPreference) {
|
||||
findCmd['$readPreference'] = readPreference.toJSON();
|
||||
}
|
||||
|
||||
if (cmd.sort) findCmd['$orderby'] = cmd.sort;
|
||||
if (cmd.hint) findCmd['$hint'] = cmd.hint;
|
||||
if (cmd.snapshot) findCmd['$snapshot'] = cmd.snapshot;
|
||||
if (typeof cmd.returnKey !== 'undefined') findCmd['$returnKey'] = cmd.returnKey;
|
||||
if (cmd.maxScan) findCmd['$maxScan'] = cmd.maxScan;
|
||||
if (cmd.min) findCmd['$min'] = cmd.min;
|
||||
if (cmd.max) findCmd['$max'] = cmd.max;
|
||||
if (typeof cmd.showDiskLoc !== 'undefined') findCmd['$showDiskLoc'] = cmd.showDiskLoc;
|
||||
if (cmd.comment) findCmd['$comment'] = cmd.comment;
|
||||
if (cmd.maxTimeMS) findCmd['$maxTimeMS'] = cmd.maxTimeMS;
|
||||
if (cmd.explain) {
|
||||
// nToReturn must be 0 (match all) or negative (match N and close cursor)
|
||||
// nToReturn > 0 will give explain results equivalent to limit(0)
|
||||
numberToReturn = -Math.abs(cmd.limit || 0);
|
||||
findCmd['$explain'] = true;
|
||||
}
|
||||
|
||||
findCmd['$query'] = cmd.query;
|
||||
if (cmd.readConcern && cmd.readConcern.level !== 'local') {
|
||||
throw new MongoError(
|
||||
`server find command does not support a readConcern level of ${cmd.readConcern.level}`
|
||||
);
|
||||
}
|
||||
|
||||
if (cmd.readConcern) {
|
||||
cmd = Object.assign({}, cmd);
|
||||
delete cmd['readConcern'];
|
||||
}
|
||||
|
||||
const serializeFunctions =
|
||||
typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
|
||||
const ignoreUndefined =
|
||||
typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false;
|
||||
|
||||
const query = new Query(bson, ns, findCmd, {
|
||||
numberToSkip: numberToSkip,
|
||||
numberToReturn: numberToReturn,
|
||||
pre32Limit: typeof cmd.limit !== 'undefined' ? cmd.limit : undefined,
|
||||
checkKeys: false,
|
||||
returnFieldSelector: cmd.fields,
|
||||
serializeFunctions: serializeFunctions,
|
||||
ignoreUndefined: ignoreUndefined
|
||||
});
|
||||
|
||||
if (typeof cmd.tailable === 'boolean') query.tailable = cmd.tailable;
|
||||
if (typeof cmd.oplogReplay === 'boolean') query.oplogReplay = cmd.oplogReplay;
|
||||
if (typeof cmd.noCursorTimeout === 'boolean') query.noCursorTimeout = cmd.noCursorTimeout;
|
||||
if (typeof cmd.awaitData === 'boolean') query.awaitData = cmd.awaitData;
|
||||
if (typeof cmd.partial === 'boolean') query.partial = cmd.partial;
|
||||
|
||||
query.slaveOk = readPreference.slaveOk();
|
||||
return query;
|
||||
}
|
||||
|
||||
module.exports = query;
|
||||
115
node_modules/mongodb/lib/core/wireprotocol/shared.js
generated
vendored
Normal file
115
node_modules/mongodb/lib/core/wireprotocol/shared.js
generated
vendored
Normal file
@@ -0,0 +1,115 @@
|
||||
'use strict';
|
||||
|
||||
const ReadPreference = require('../topologies/read_preference');
|
||||
const MongoError = require('../error').MongoError;
|
||||
const ServerType = require('../sdam/common').ServerType;
|
||||
const TopologyDescription = require('../sdam/topology_description').TopologyDescription;
|
||||
|
||||
const MESSAGE_HEADER_SIZE = 16;
|
||||
const COMPRESSION_DETAILS_SIZE = 9; // originalOpcode + uncompressedSize, compressorID
|
||||
|
||||
// OPCODE Numbers
|
||||
// Defined at https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#request-opcodes
|
||||
var opcodes = {
|
||||
OP_REPLY: 1,
|
||||
OP_UPDATE: 2001,
|
||||
OP_INSERT: 2002,
|
||||
OP_QUERY: 2004,
|
||||
OP_GETMORE: 2005,
|
||||
OP_DELETE: 2006,
|
||||
OP_KILL_CURSORS: 2007,
|
||||
OP_COMPRESSED: 2012,
|
||||
OP_MSG: 2013
|
||||
};
|
||||
|
||||
var getReadPreference = function(cmd, options) {
|
||||
// Default to command version of the readPreference
|
||||
var readPreference = cmd.readPreference || new ReadPreference('primary');
|
||||
// If we have an option readPreference override the command one
|
||||
if (options.readPreference) {
|
||||
readPreference = options.readPreference;
|
||||
}
|
||||
|
||||
if (typeof readPreference === 'string') {
|
||||
readPreference = new ReadPreference(readPreference);
|
||||
}
|
||||
|
||||
if (!(readPreference instanceof ReadPreference)) {
|
||||
throw new MongoError('read preference must be a ReadPreference instance');
|
||||
}
|
||||
|
||||
return readPreference;
|
||||
};
|
||||
|
||||
// Parses the header of a wire protocol message
|
||||
var parseHeader = function(message) {
|
||||
return {
|
||||
length: message.readInt32LE(0),
|
||||
requestId: message.readInt32LE(4),
|
||||
responseTo: message.readInt32LE(8),
|
||||
opCode: message.readInt32LE(12)
|
||||
};
|
||||
};
|
||||
|
||||
function applyCommonQueryOptions(queryOptions, options) {
|
||||
Object.assign(queryOptions, {
|
||||
raw: typeof options.raw === 'boolean' ? options.raw : false,
|
||||
promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true,
|
||||
promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true,
|
||||
promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false,
|
||||
monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : false,
|
||||
fullResult: typeof options.fullResult === 'boolean' ? options.fullResult : false
|
||||
});
|
||||
|
||||
if (typeof options.socketTimeout === 'number') {
|
||||
queryOptions.socketTimeout = options.socketTimeout;
|
||||
}
|
||||
|
||||
if (options.session) {
|
||||
queryOptions.session = options.session;
|
||||
}
|
||||
|
||||
if (typeof options.documentsReturnedIn === 'string') {
|
||||
queryOptions.documentsReturnedIn = options.documentsReturnedIn;
|
||||
}
|
||||
|
||||
return queryOptions;
|
||||
}
|
||||
|
||||
function isSharded(topologyOrServer) {
|
||||
if (topologyOrServer.type === 'mongos') return true;
|
||||
if (topologyOrServer.description && topologyOrServer.description.type === ServerType.Mongos) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// NOTE: This is incredibly inefficient, and should be removed once command construction
|
||||
// happens based on `Server` not `Topology`.
|
||||
if (topologyOrServer.description && topologyOrServer.description instanceof TopologyDescription) {
|
||||
const servers = Array.from(topologyOrServer.description.servers.values());
|
||||
return servers.some(server => server.type === ServerType.Mongos);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function databaseNamespace(ns) {
|
||||
return ns.split('.')[0];
|
||||
}
|
||||
function collectionNamespace(ns) {
|
||||
return ns
|
||||
.split('.')
|
||||
.slice(1)
|
||||
.join('.');
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getReadPreference,
|
||||
MESSAGE_HEADER_SIZE,
|
||||
COMPRESSION_DETAILS_SIZE,
|
||||
opcodes,
|
||||
parseHeader,
|
||||
applyCommonQueryOptions,
|
||||
isSharded,
|
||||
databaseNamespace,
|
||||
collectionNamespace
|
||||
};
|
||||
50
node_modules/mongodb/lib/core/wireprotocol/write_command.js
generated
vendored
Normal file
50
node_modules/mongodb/lib/core/wireprotocol/write_command.js
generated
vendored
Normal file
@@ -0,0 +1,50 @@
|
||||
'use strict';
|
||||
|
||||
const MongoError = require('../error').MongoError;
|
||||
const collectionNamespace = require('./shared').collectionNamespace;
|
||||
const command = require('./command');
|
||||
|
||||
function writeCommand(server, type, opsField, ns, ops, options, callback) {
|
||||
if (ops.length === 0) throw new MongoError(`${type} must contain at least one document`);
|
||||
if (typeof options === 'function') {
|
||||
callback = options;
|
||||
options = {};
|
||||
}
|
||||
|
||||
options = options || {};
|
||||
const ordered = typeof options.ordered === 'boolean' ? options.ordered : true;
|
||||
const writeConcern = options.writeConcern;
|
||||
|
||||
const writeCommand = {};
|
||||
writeCommand[type] = collectionNamespace(ns);
|
||||
writeCommand[opsField] = ops;
|
||||
writeCommand.ordered = ordered;
|
||||
|
||||
if (writeConcern && Object.keys(writeConcern).length > 0) {
|
||||
writeCommand.writeConcern = writeConcern;
|
||||
}
|
||||
|
||||
if (options.collation) {
|
||||
for (let i = 0; i < writeCommand[opsField].length; i++) {
|
||||
if (!writeCommand[opsField][i].collation) {
|
||||
writeCommand[opsField][i].collation = options.collation;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (options.bypassDocumentValidation === true) {
|
||||
writeCommand.bypassDocumentValidation = options.bypassDocumentValidation;
|
||||
}
|
||||
|
||||
const commandOptions = Object.assign(
|
||||
{
|
||||
checkKeys: type === 'insert',
|
||||
numberToReturn: 1
|
||||
},
|
||||
options
|
||||
);
|
||||
|
||||
command(server, ns, writeCommand, commandOptions, callback);
|
||||
}
|
||||
|
||||
module.exports = writeCommand;
|
||||
1135
node_modules/mongodb/lib/cursor.js
generated
vendored
Normal file
1135
node_modules/mongodb/lib/cursor.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
1032
node_modules/mongodb/lib/db.js
generated
vendored
Normal file
1032
node_modules/mongodb/lib/db.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
32
node_modules/mongodb/lib/dynamic_loaders.js
generated
vendored
Normal file
32
node_modules/mongodb/lib/dynamic_loaders.js
generated
vendored
Normal file
@@ -0,0 +1,32 @@
|
||||
'use strict';
|
||||
|
||||
let collection;
|
||||
let cursor;
|
||||
let db;
|
||||
|
||||
function loadCollection() {
|
||||
if (!collection) {
|
||||
collection = require('./collection');
|
||||
}
|
||||
return collection;
|
||||
}
|
||||
|
||||
function loadCursor() {
|
||||
if (!cursor) {
|
||||
cursor = require('./cursor');
|
||||
}
|
||||
return cursor;
|
||||
}
|
||||
|
||||
function loadDb() {
|
||||
if (!db) {
|
||||
db = require('./db');
|
||||
}
|
||||
return db;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
loadCollection,
|
||||
loadCursor,
|
||||
loadDb
|
||||
};
|
||||
43
node_modules/mongodb/lib/error.js
generated
vendored
Normal file
43
node_modules/mongodb/lib/error.js
generated
vendored
Normal file
@@ -0,0 +1,43 @@
|
||||
'use strict';
|
||||
|
||||
const MongoNetworkError = require('./core').MongoNetworkError;
|
||||
|
||||
// From spec@https://github.com/mongodb/specifications/blob/f93d78191f3db2898a59013a7ed5650352ef6da8/source/change-streams/change-streams.rst#resumable-error
|
||||
const GET_MORE_RESUMABLE_CODES = new Set([
|
||||
6, // HostUnreachable
|
||||
7, // HostNotFound
|
||||
89, // NetworkTimeout
|
||||
91, // ShutdownInProgress
|
||||
189, // PrimarySteppedDown
|
||||
262, // ExceededTimeLimit
|
||||
9001, // SocketException
|
||||
10107, // NotMaster
|
||||
11600, // InterruptedAtShutdown
|
||||
11602, // InterruptedDueToReplStateChange
|
||||
13435, // NotMasterNoSlaveOk
|
||||
13436, // NotMasterOrSecondary
|
||||
63, // StaleShardVersion
|
||||
150, // StaleEpoch
|
||||
13388, // StaleConfig
|
||||
234, // RetryChangeStream
|
||||
133, // FailedToSatisfyReadPreference
|
||||
43 // CursorNotFound
|
||||
]);
|
||||
|
||||
function isResumableError(error, wireVersion) {
|
||||
if (error instanceof MongoNetworkError) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (wireVersion >= 9) {
|
||||
// DRIVERS-1308: For 4.4 drivers running against 4.4 servers, drivers will add a special case to treat the CursorNotFound error code as resumable
|
||||
if (error.code === 43) {
|
||||
return true;
|
||||
}
|
||||
return error.hasErrorLabel('ResumableChangeStreamError');
|
||||
}
|
||||
|
||||
return GET_MORE_RESUMABLE_CODES.has(error.code);
|
||||
}
|
||||
|
||||
module.exports = { GET_MORE_RESUMABLE_CODES, isResumableError };
|
||||
433
node_modules/mongodb/lib/gridfs-stream/download.js
generated
vendored
Normal file
433
node_modules/mongodb/lib/gridfs-stream/download.js
generated
vendored
Normal file
@@ -0,0 +1,433 @@
|
||||
'use strict';
|
||||
|
||||
var stream = require('stream'),
|
||||
util = require('util');
|
||||
|
||||
module.exports = GridFSBucketReadStream;
|
||||
|
||||
/**
|
||||
* A readable stream that enables you to read buffers from GridFS.
|
||||
*
|
||||
* Do not instantiate this class directly. Use `openDownloadStream()` instead.
|
||||
*
|
||||
* @class
|
||||
* @extends external:Readable
|
||||
* @param {Collection} chunks Handle for chunks collection
|
||||
* @param {Collection} files Handle for files collection
|
||||
* @param {Object} readPreference The read preference to use
|
||||
* @param {Object} filter The query to use to find the file document
|
||||
* @param {Object} [options] Optional settings.
|
||||
* @param {Number} [options.sort] Optional sort for the file find query
|
||||
* @param {Number} [options.skip] Optional skip for the file find query
|
||||
* @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from
|
||||
* @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before
|
||||
* @fires GridFSBucketReadStream#error
|
||||
* @fires GridFSBucketReadStream#file
|
||||
*/
|
||||
function GridFSBucketReadStream(chunks, files, readPreference, filter, options) {
|
||||
this.s = {
|
||||
bytesRead: 0,
|
||||
chunks: chunks,
|
||||
cursor: null,
|
||||
expected: 0,
|
||||
files: files,
|
||||
filter: filter,
|
||||
init: false,
|
||||
expectedEnd: 0,
|
||||
file: null,
|
||||
options: options,
|
||||
readPreference: readPreference
|
||||
};
|
||||
|
||||
stream.Readable.call(this);
|
||||
}
|
||||
|
||||
util.inherits(GridFSBucketReadStream, stream.Readable);
|
||||
|
||||
/**
|
||||
* An error occurred
|
||||
*
|
||||
* @event GridFSBucketReadStream#error
|
||||
* @type {Error}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Fires when the stream loaded the file document corresponding to the
|
||||
* provided id.
|
||||
*
|
||||
* @event GridFSBucketReadStream#file
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Emitted when a chunk of data is available to be consumed.
|
||||
*
|
||||
* @event GridFSBucketReadStream#data
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Fired when the stream is exhausted (no more data events).
|
||||
*
|
||||
* @event GridFSBucketReadStream#end
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Fired when the stream is exhausted and the underlying cursor is killed
|
||||
*
|
||||
* @event GridFSBucketReadStream#close
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Reads from the cursor and pushes to the stream.
|
||||
* Private Impl, do not call directly
|
||||
* @ignore
|
||||
* @method
|
||||
*/
|
||||
|
||||
GridFSBucketReadStream.prototype._read = function() {
|
||||
var _this = this;
|
||||
if (this.destroyed) {
|
||||
return;
|
||||
}
|
||||
|
||||
waitForFile(_this, function() {
|
||||
doRead(_this);
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Sets the 0-based offset in bytes to start streaming from. Throws
|
||||
* an error if this stream has entered flowing mode
|
||||
* (e.g. if you've already called `on('data')`)
|
||||
* @method
|
||||
* @param {Number} start Offset in bytes to start reading at
|
||||
* @return {GridFSBucketReadStream} Reference to Self
|
||||
*/
|
||||
|
||||
GridFSBucketReadStream.prototype.start = function(start) {
|
||||
throwIfInitialized(this);
|
||||
this.s.options.start = start;
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Sets the 0-based offset in bytes to start streaming from. Throws
|
||||
* an error if this stream has entered flowing mode
|
||||
* (e.g. if you've already called `on('data')`)
|
||||
* @method
|
||||
* @param {Number} end Offset in bytes to stop reading at
|
||||
* @return {GridFSBucketReadStream} Reference to self
|
||||
*/
|
||||
|
||||
GridFSBucketReadStream.prototype.end = function(end) {
|
||||
throwIfInitialized(this);
|
||||
this.s.options.end = end;
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Marks this stream as aborted (will never push another `data` event)
|
||||
* and kills the underlying cursor. Will emit the 'end' event, and then
|
||||
* the 'close' event once the cursor is successfully killed.
|
||||
*
|
||||
* @method
|
||||
* @param {GridFSBucket~errorCallback} [callback] called when the cursor is successfully closed or an error occurred.
|
||||
* @fires GridFSBucketWriteStream#close
|
||||
* @fires GridFSBucketWriteStream#end
|
||||
*/
|
||||
|
||||
GridFSBucketReadStream.prototype.abort = function(callback) {
|
||||
var _this = this;
|
||||
this.push(null);
|
||||
this.destroyed = true;
|
||||
if (this.s.cursor) {
|
||||
this.s.cursor.close(function(error) {
|
||||
_this.emit('close');
|
||||
callback && callback(error);
|
||||
});
|
||||
} else {
|
||||
if (!this.s.init) {
|
||||
// If not initialized, fire close event because we will never
|
||||
// get a cursor
|
||||
_this.emit('close');
|
||||
}
|
||||
callback && callback();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function throwIfInitialized(self) {
|
||||
if (self.s.init) {
|
||||
throw new Error('You cannot change options after the stream has entered' + 'flowing mode!');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function doRead(_this) {
|
||||
if (_this.destroyed) {
|
||||
return;
|
||||
}
|
||||
|
||||
_this.s.cursor.next(function(error, doc) {
|
||||
if (_this.destroyed) {
|
||||
return;
|
||||
}
|
||||
if (error) {
|
||||
return __handleError(_this, error);
|
||||
}
|
||||
if (!doc) {
|
||||
_this.push(null);
|
||||
|
||||
process.nextTick(() => {
|
||||
_this.s.cursor.close(function(error) {
|
||||
if (error) {
|
||||
__handleError(_this, error);
|
||||
return;
|
||||
}
|
||||
|
||||
_this.emit('close');
|
||||
});
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
var bytesRemaining = _this.s.file.length - _this.s.bytesRead;
|
||||
var expectedN = _this.s.expected++;
|
||||
var expectedLength = Math.min(_this.s.file.chunkSize, bytesRemaining);
|
||||
|
||||
if (doc.n > expectedN) {
|
||||
var errmsg = 'ChunkIsMissing: Got unexpected n: ' + doc.n + ', expected: ' + expectedN;
|
||||
return __handleError(_this, new Error(errmsg));
|
||||
}
|
||||
|
||||
if (doc.n < expectedN) {
|
||||
errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n + ', expected: ' + expectedN;
|
||||
return __handleError(_this, new Error(errmsg));
|
||||
}
|
||||
|
||||
var buf = Buffer.isBuffer(doc.data) ? doc.data : doc.data.buffer;
|
||||
|
||||
if (buf.length !== expectedLength) {
|
||||
if (bytesRemaining <= 0) {
|
||||
errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n;
|
||||
return __handleError(_this, new Error(errmsg));
|
||||
}
|
||||
|
||||
errmsg =
|
||||
'ChunkIsWrongSize: Got unexpected length: ' + buf.length + ', expected: ' + expectedLength;
|
||||
return __handleError(_this, new Error(errmsg));
|
||||
}
|
||||
|
||||
_this.s.bytesRead += buf.length;
|
||||
|
||||
if (buf.length === 0) {
|
||||
return _this.push(null);
|
||||
}
|
||||
|
||||
var sliceStart = null;
|
||||
var sliceEnd = null;
|
||||
|
||||
if (_this.s.bytesToSkip != null) {
|
||||
sliceStart = _this.s.bytesToSkip;
|
||||
_this.s.bytesToSkip = 0;
|
||||
}
|
||||
|
||||
const atEndOfStream = expectedN === _this.s.expectedEnd - 1;
|
||||
const bytesLeftToRead = _this.s.options.end - _this.s.bytesToSkip;
|
||||
if (atEndOfStream && _this.s.bytesToTrim != null) {
|
||||
sliceEnd = _this.s.file.chunkSize - _this.s.bytesToTrim;
|
||||
} else if (_this.s.options.end && bytesLeftToRead < doc.data.length()) {
|
||||
sliceEnd = bytesLeftToRead;
|
||||
}
|
||||
|
||||
if (sliceStart != null || sliceEnd != null) {
|
||||
buf = buf.slice(sliceStart || 0, sliceEnd || buf.length);
|
||||
}
|
||||
|
||||
_this.push(buf);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function init(self) {
|
||||
var findOneOptions = {};
|
||||
if (self.s.readPreference) {
|
||||
findOneOptions.readPreference = self.s.readPreference;
|
||||
}
|
||||
if (self.s.options && self.s.options.sort) {
|
||||
findOneOptions.sort = self.s.options.sort;
|
||||
}
|
||||
if (self.s.options && self.s.options.skip) {
|
||||
findOneOptions.skip = self.s.options.skip;
|
||||
}
|
||||
|
||||
self.s.files.findOne(self.s.filter, findOneOptions, function(error, doc) {
|
||||
if (error) {
|
||||
return __handleError(self, error);
|
||||
}
|
||||
|
||||
if (!doc) {
|
||||
var identifier = self.s.filter._id ? self.s.filter._id.toString() : self.s.filter.filename;
|
||||
var errmsg = 'FileNotFound: file ' + identifier + ' was not found';
|
||||
var err = new Error(errmsg);
|
||||
err.code = 'ENOENT';
|
||||
return __handleError(self, err);
|
||||
}
|
||||
|
||||
// If document is empty, kill the stream immediately and don't
|
||||
// execute any reads
|
||||
if (doc.length <= 0) {
|
||||
self.push(null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (self.destroyed) {
|
||||
// If user destroys the stream before we have a cursor, wait
|
||||
// until the query is done to say we're 'closed' because we can't
|
||||
// cancel a query.
|
||||
self.emit('close');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
self.s.bytesToSkip = handleStartOption(self, doc, self.s.options);
|
||||
} catch (error) {
|
||||
return __handleError(self, error);
|
||||
}
|
||||
|
||||
var filter = { files_id: doc._id };
|
||||
|
||||
// Currently (MongoDB 3.4.4) skip function does not support the index,
|
||||
// it needs to retrieve all the documents first and then skip them. (CS-25811)
|
||||
// As work around we use $gte on the "n" field.
|
||||
if (self.s.options && self.s.options.start != null) {
|
||||
var skip = Math.floor(self.s.options.start / doc.chunkSize);
|
||||
if (skip > 0) {
|
||||
filter['n'] = { $gte: skip };
|
||||
}
|
||||
}
|
||||
self.s.cursor = self.s.chunks.find(filter).sort({ n: 1 });
|
||||
|
||||
if (self.s.readPreference) {
|
||||
self.s.cursor.setReadPreference(self.s.readPreference);
|
||||
}
|
||||
|
||||
self.s.expectedEnd = Math.ceil(doc.length / doc.chunkSize);
|
||||
self.s.file = doc;
|
||||
|
||||
try {
|
||||
self.s.bytesToTrim = handleEndOption(self, doc, self.s.cursor, self.s.options);
|
||||
} catch (error) {
|
||||
return __handleError(self, error);
|
||||
}
|
||||
|
||||
self.emit('file', doc);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function waitForFile(_this, callback) {
|
||||
if (_this.s.file) {
|
||||
return callback();
|
||||
}
|
||||
|
||||
if (!_this.s.init) {
|
||||
init(_this);
|
||||
_this.s.init = true;
|
||||
}
|
||||
|
||||
_this.once('file', function() {
|
||||
callback();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function handleStartOption(stream, doc, options) {
|
||||
if (options && options.start != null) {
|
||||
if (options.start > doc.length) {
|
||||
throw new Error(
|
||||
'Stream start (' +
|
||||
options.start +
|
||||
') must not be ' +
|
||||
'more than the length of the file (' +
|
||||
doc.length +
|
||||
')'
|
||||
);
|
||||
}
|
||||
if (options.start < 0) {
|
||||
throw new Error('Stream start (' + options.start + ') must not be ' + 'negative');
|
||||
}
|
||||
if (options.end != null && options.end < options.start) {
|
||||
throw new Error(
|
||||
'Stream start (' +
|
||||
options.start +
|
||||
') must not be ' +
|
||||
'greater than stream end (' +
|
||||
options.end +
|
||||
')'
|
||||
);
|
||||
}
|
||||
|
||||
stream.s.bytesRead = Math.floor(options.start / doc.chunkSize) * doc.chunkSize;
|
||||
stream.s.expected = Math.floor(options.start / doc.chunkSize);
|
||||
|
||||
return options.start - stream.s.bytesRead;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function handleEndOption(stream, doc, cursor, options) {
|
||||
if (options && options.end != null) {
|
||||
if (options.end > doc.length) {
|
||||
throw new Error(
|
||||
'Stream end (' +
|
||||
options.end +
|
||||
') must not be ' +
|
||||
'more than the length of the file (' +
|
||||
doc.length +
|
||||
')'
|
||||
);
|
||||
}
|
||||
if (options.start < 0) {
|
||||
throw new Error('Stream end (' + options.end + ') must not be ' + 'negative');
|
||||
}
|
||||
|
||||
var start = options.start != null ? Math.floor(options.start / doc.chunkSize) : 0;
|
||||
|
||||
cursor.limit(Math.ceil(options.end / doc.chunkSize) - start);
|
||||
|
||||
stream.s.expectedEnd = Math.ceil(options.end / doc.chunkSize);
|
||||
|
||||
return Math.ceil(options.end / doc.chunkSize) * doc.chunkSize - options.end;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function __handleError(_this, error) {
|
||||
_this.emit('error', error);
|
||||
}
|
||||
359
node_modules/mongodb/lib/gridfs-stream/index.js
generated
vendored
Normal file
359
node_modules/mongodb/lib/gridfs-stream/index.js
generated
vendored
Normal file
@@ -0,0 +1,359 @@
|
||||
'use strict';
|
||||
|
||||
var Emitter = require('events').EventEmitter;
|
||||
var GridFSBucketReadStream = require('./download');
|
||||
var GridFSBucketWriteStream = require('./upload');
|
||||
var shallowClone = require('../utils').shallowClone;
|
||||
var toError = require('../utils').toError;
|
||||
var util = require('util');
|
||||
var executeLegacyOperation = require('../utils').executeLegacyOperation;
|
||||
|
||||
var DEFAULT_GRIDFS_BUCKET_OPTIONS = {
|
||||
bucketName: 'fs',
|
||||
chunkSizeBytes: 255 * 1024
|
||||
};
|
||||
|
||||
module.exports = GridFSBucket;
|
||||
|
||||
/**
|
||||
* Constructor for a streaming GridFS interface
|
||||
* @class
|
||||
* @extends external:EventEmitter
|
||||
* @param {Db} db A db handle
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {string} [options.bucketName="fs"] The 'files' and 'chunks' collections will be prefixed with the bucket name followed by a dot.
|
||||
* @param {number} [options.chunkSizeBytes=255 * 1024] Number of bytes stored in each chunk. Defaults to 255KB
|
||||
* @param {object} [options.writeConcern] Optional write concern to be passed to write operations, for instance `{ w: 1 }`
|
||||
* @param {object} [options.readPreference] Optional read preference to be passed to read operations
|
||||
* @fires GridFSBucketWriteStream#index
|
||||
*/
|
||||
|
||||
function GridFSBucket(db, options) {
|
||||
Emitter.apply(this);
|
||||
this.setMaxListeners(0);
|
||||
|
||||
if (options && typeof options === 'object') {
|
||||
options = shallowClone(options);
|
||||
var keys = Object.keys(DEFAULT_GRIDFS_BUCKET_OPTIONS);
|
||||
for (var i = 0; i < keys.length; ++i) {
|
||||
if (!options[keys[i]]) {
|
||||
options[keys[i]] = DEFAULT_GRIDFS_BUCKET_OPTIONS[keys[i]];
|
||||
}
|
||||
}
|
||||
} else {
|
||||
options = DEFAULT_GRIDFS_BUCKET_OPTIONS;
|
||||
}
|
||||
|
||||
this.s = {
|
||||
db: db,
|
||||
options: options,
|
||||
_chunksCollection: db.collection(options.bucketName + '.chunks'),
|
||||
_filesCollection: db.collection(options.bucketName + '.files'),
|
||||
checkedIndexes: false,
|
||||
calledOpenUploadStream: false,
|
||||
promiseLibrary: db.s.promiseLibrary || Promise
|
||||
};
|
||||
}
|
||||
|
||||
util.inherits(GridFSBucket, Emitter);
|
||||
|
||||
/**
|
||||
* When the first call to openUploadStream is made, the upload stream will
|
||||
* check to see if it needs to create the proper indexes on the chunks and
|
||||
* files collections. This event is fired either when 1) it determines that
|
||||
* no index creation is necessary, 2) when it successfully creates the
|
||||
* necessary indexes.
|
||||
*
|
||||
* @event GridFSBucket#index
|
||||
* @type {Error}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Returns a writable stream (GridFSBucketWriteStream) for writing
|
||||
* buffers to GridFS. The stream's 'id' property contains the resulting
|
||||
* file's id.
|
||||
* @method
|
||||
* @param {string} filename The value of the 'filename' key in the files doc
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {number} [options.chunkSizeBytes] Optional overwrite this bucket's chunkSizeBytes for this file
|
||||
* @param {object} [options.metadata] Optional object to store in the file document's `metadata` field
|
||||
* @param {string} [options.contentType] Optional string to store in the file document's `contentType` field
|
||||
* @param {array} [options.aliases] Optional array of strings to store in the file document's `aliases` field
|
||||
* @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data
|
||||
* @return {GridFSBucketWriteStream}
|
||||
*/
|
||||
|
||||
GridFSBucket.prototype.openUploadStream = function(filename, options) {
|
||||
if (options) {
|
||||
options = shallowClone(options);
|
||||
} else {
|
||||
options = {};
|
||||
}
|
||||
if (!options.chunkSizeBytes) {
|
||||
options.chunkSizeBytes = this.s.options.chunkSizeBytes;
|
||||
}
|
||||
return new GridFSBucketWriteStream(this, filename, options);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a writable stream (GridFSBucketWriteStream) for writing
|
||||
* buffers to GridFS for a custom file id. The stream's 'id' property contains the resulting
|
||||
* file's id.
|
||||
* @method
|
||||
* @param {string|number|object} id A custom id used to identify the file
|
||||
* @param {string} filename The value of the 'filename' key in the files doc
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {number} [options.chunkSizeBytes] Optional overwrite this bucket's chunkSizeBytes for this file
|
||||
* @param {object} [options.metadata] Optional object to store in the file document's `metadata` field
|
||||
* @param {string} [options.contentType] Optional string to store in the file document's `contentType` field
|
||||
* @param {array} [options.aliases] Optional array of strings to store in the file document's `aliases` field
|
||||
* @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data
|
||||
* @return {GridFSBucketWriteStream}
|
||||
*/
|
||||
|
||||
GridFSBucket.prototype.openUploadStreamWithId = function(id, filename, options) {
|
||||
if (options) {
|
||||
options = shallowClone(options);
|
||||
} else {
|
||||
options = {};
|
||||
}
|
||||
|
||||
if (!options.chunkSizeBytes) {
|
||||
options.chunkSizeBytes = this.s.options.chunkSizeBytes;
|
||||
}
|
||||
|
||||
options.id = id;
|
||||
|
||||
return new GridFSBucketWriteStream(this, filename, options);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a readable stream (GridFSBucketReadStream) for streaming file
|
||||
* data from GridFS.
|
||||
* @method
|
||||
* @param {ObjectId} id The id of the file doc
|
||||
* @param {Object} [options] Optional settings.
|
||||
* @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from
|
||||
* @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before
|
||||
* @return {GridFSBucketReadStream}
|
||||
*/
|
||||
|
||||
GridFSBucket.prototype.openDownloadStream = function(id, options) {
|
||||
var filter = { _id: id };
|
||||
options = {
|
||||
start: options && options.start,
|
||||
end: options && options.end
|
||||
};
|
||||
|
||||
return new GridFSBucketReadStream(
|
||||
this.s._chunksCollection,
|
||||
this.s._filesCollection,
|
||||
this.s.options.readPreference,
|
||||
filter,
|
||||
options
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Deletes a file with the given id
|
||||
* @method
|
||||
* @param {ObjectId} id The id of the file doc
|
||||
* @param {GridFSBucket~errorCallback} [callback]
|
||||
*/
|
||||
|
||||
GridFSBucket.prototype.delete = function(id, callback) {
|
||||
return executeLegacyOperation(this.s.db.s.topology, _delete, [this, id, callback], {
|
||||
skipSessions: true
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function _delete(_this, id, callback) {
|
||||
_this.s._filesCollection.deleteOne({ _id: id }, function(error, res) {
|
||||
if (error) {
|
||||
return callback(error);
|
||||
}
|
||||
|
||||
_this.s._chunksCollection.deleteMany({ files_id: id }, function(error) {
|
||||
if (error) {
|
||||
return callback(error);
|
||||
}
|
||||
|
||||
// Delete orphaned chunks before returning FileNotFound
|
||||
if (!res.result.n) {
|
||||
var errmsg = 'FileNotFound: no file with id ' + id + ' found';
|
||||
return callback(new Error(errmsg));
|
||||
}
|
||||
|
||||
callback();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience wrapper around find on the files collection
|
||||
* @method
|
||||
* @param {Object} filter
|
||||
* @param {Object} [options] Optional settings for cursor
|
||||
* @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find|find command documentation}.
|
||||
* @param {number} [options.limit] Optional limit for cursor
|
||||
* @param {number} [options.maxTimeMS] Optional maxTimeMS for cursor
|
||||
* @param {boolean} [options.noCursorTimeout] Optionally set cursor's `noCursorTimeout` flag
|
||||
* @param {number} [options.skip] Optional skip for cursor
|
||||
* @param {object} [options.sort] Optional sort for cursor
|
||||
* @return {Cursor}
|
||||
*/
|
||||
|
||||
GridFSBucket.prototype.find = function(filter, options) {
|
||||
filter = filter || {};
|
||||
options = options || {};
|
||||
|
||||
var cursor = this.s._filesCollection.find(filter);
|
||||
|
||||
if (options.batchSize != null) {
|
||||
cursor.batchSize(options.batchSize);
|
||||
}
|
||||
if (options.limit != null) {
|
||||
cursor.limit(options.limit);
|
||||
}
|
||||
if (options.maxTimeMS != null) {
|
||||
cursor.maxTimeMS(options.maxTimeMS);
|
||||
}
|
||||
if (options.noCursorTimeout != null) {
|
||||
cursor.addCursorFlag('noCursorTimeout', options.noCursorTimeout);
|
||||
}
|
||||
if (options.skip != null) {
|
||||
cursor.skip(options.skip);
|
||||
}
|
||||
if (options.sort != null) {
|
||||
cursor.sort(options.sort);
|
||||
}
|
||||
|
||||
return cursor;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a readable stream (GridFSBucketReadStream) for streaming the
|
||||
* file with the given name from GridFS. If there are multiple files with
|
||||
* the same name, this will stream the most recent file with the given name
|
||||
* (as determined by the `uploadDate` field). You can set the `revision`
|
||||
* option to change this behavior.
|
||||
* @method
|
||||
* @param {String} filename The name of the file to stream
|
||||
* @param {Object} [options] Optional settings
|
||||
* @param {number} [options.revision=-1] The revision number relative to the oldest file with the given filename. 0 gets you the oldest file, 1 gets you the 2nd oldest, -1 gets you the newest.
|
||||
* @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from
|
||||
* @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before
|
||||
* @return {GridFSBucketReadStream}
|
||||
*/
|
||||
|
||||
GridFSBucket.prototype.openDownloadStreamByName = function(filename, options) {
|
||||
var sort = { uploadDate: -1 };
|
||||
var skip = null;
|
||||
if (options && options.revision != null) {
|
||||
if (options.revision >= 0) {
|
||||
sort = { uploadDate: 1 };
|
||||
skip = options.revision;
|
||||
} else {
|
||||
skip = -options.revision - 1;
|
||||
}
|
||||
}
|
||||
|
||||
var filter = { filename: filename };
|
||||
options = {
|
||||
sort: sort,
|
||||
skip: skip,
|
||||
start: options && options.start,
|
||||
end: options && options.end
|
||||
};
|
||||
return new GridFSBucketReadStream(
|
||||
this.s._chunksCollection,
|
||||
this.s._filesCollection,
|
||||
this.s.options.readPreference,
|
||||
filter,
|
||||
options
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Renames the file with the given _id to the given string
|
||||
* @method
|
||||
* @param {ObjectId} id the id of the file to rename
|
||||
* @param {String} filename new name for the file
|
||||
* @param {GridFSBucket~errorCallback} [callback]
|
||||
*/
|
||||
|
||||
GridFSBucket.prototype.rename = function(id, filename, callback) {
|
||||
return executeLegacyOperation(this.s.db.s.topology, _rename, [this, id, filename, callback], {
|
||||
skipSessions: true
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function _rename(_this, id, filename, callback) {
|
||||
var filter = { _id: id };
|
||||
var update = { $set: { filename: filename } };
|
||||
_this.s._filesCollection.updateOne(filter, update, function(error, res) {
|
||||
if (error) {
|
||||
return callback(error);
|
||||
}
|
||||
if (!res.result.n) {
|
||||
return callback(toError('File with id ' + id + ' not found'));
|
||||
}
|
||||
callback();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes this bucket's files collection, followed by its chunks collection.
|
||||
* @method
|
||||
* @param {GridFSBucket~errorCallback} [callback]
|
||||
*/
|
||||
|
||||
GridFSBucket.prototype.drop = function(callback) {
|
||||
return executeLegacyOperation(this.s.db.s.topology, _drop, [this, callback], {
|
||||
skipSessions: true
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the db logger
|
||||
* @method
|
||||
* @return {Logger} return the db logger
|
||||
* @ignore
|
||||
*/
|
||||
GridFSBucket.prototype.getLogger = function() {
|
||||
return this.s.db.s.logger;
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function _drop(_this, callback) {
|
||||
_this.s._filesCollection.drop(function(error) {
|
||||
if (error) {
|
||||
return callback(error);
|
||||
}
|
||||
_this.s._chunksCollection.drop(function(error) {
|
||||
if (error) {
|
||||
return callback(error);
|
||||
}
|
||||
|
||||
return callback();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Callback format for all GridFSBucket methods that can accept a callback.
|
||||
* @callback GridFSBucket~errorCallback
|
||||
* @param {MongoError|undefined} error If present, an error instance representing any errors that occurred
|
||||
* @param {*} result If present, a returned result for the method
|
||||
*/
|
||||
538
node_modules/mongodb/lib/gridfs-stream/upload.js
generated
vendored
Normal file
538
node_modules/mongodb/lib/gridfs-stream/upload.js
generated
vendored
Normal file
@@ -0,0 +1,538 @@
|
||||
'use strict';
|
||||
|
||||
var core = require('../core');
|
||||
var crypto = require('crypto');
|
||||
var stream = require('stream');
|
||||
var util = require('util');
|
||||
var Buffer = require('safe-buffer').Buffer;
|
||||
|
||||
var ERROR_NAMESPACE_NOT_FOUND = 26;
|
||||
|
||||
module.exports = GridFSBucketWriteStream;
|
||||
|
||||
/**
|
||||
* A writable stream that enables you to write buffers to GridFS.
|
||||
*
|
||||
* Do not instantiate this class directly. Use `openUploadStream()` instead.
|
||||
*
|
||||
* @class
|
||||
* @extends external:Writable
|
||||
* @param {GridFSBucket} bucket Handle for this stream's corresponding bucket
|
||||
* @param {string} filename The value of the 'filename' key in the files doc
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {string|number|object} [options.id] Custom file id for the GridFS file.
|
||||
* @param {number} [options.chunkSizeBytes] The chunk size to use, in bytes
|
||||
* @param {number} [options.w] The write concern
|
||||
* @param {number} [options.wtimeout] The write concern timeout
|
||||
* @param {number} [options.j] The journal write concern
|
||||
* @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data
|
||||
* @fires GridFSBucketWriteStream#error
|
||||
* @fires GridFSBucketWriteStream#finish
|
||||
*/
|
||||
|
||||
function GridFSBucketWriteStream(bucket, filename, options) {
|
||||
options = options || {};
|
||||
this.bucket = bucket;
|
||||
this.chunks = bucket.s._chunksCollection;
|
||||
this.filename = filename;
|
||||
this.files = bucket.s._filesCollection;
|
||||
this.options = options;
|
||||
// Signals the write is all done
|
||||
this.done = false;
|
||||
|
||||
this.id = options.id ? options.id : core.BSON.ObjectId();
|
||||
this.chunkSizeBytes = this.options.chunkSizeBytes;
|
||||
this.bufToStore = Buffer.alloc(this.chunkSizeBytes);
|
||||
this.length = 0;
|
||||
this.md5 = !options.disableMD5 && crypto.createHash('md5');
|
||||
this.n = 0;
|
||||
this.pos = 0;
|
||||
this.state = {
|
||||
streamEnd: false,
|
||||
outstandingRequests: 0,
|
||||
errored: false,
|
||||
aborted: false,
|
||||
promiseLibrary: this.bucket.s.promiseLibrary
|
||||
};
|
||||
|
||||
if (!this.bucket.s.calledOpenUploadStream) {
|
||||
this.bucket.s.calledOpenUploadStream = true;
|
||||
|
||||
var _this = this;
|
||||
checkIndexes(this, function() {
|
||||
_this.bucket.s.checkedIndexes = true;
|
||||
_this.bucket.emit('index');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
util.inherits(GridFSBucketWriteStream, stream.Writable);
|
||||
|
||||
/**
|
||||
* An error occurred
|
||||
*
|
||||
* @event GridFSBucketWriteStream#error
|
||||
* @type {Error}
|
||||
*/
|
||||
|
||||
/**
|
||||
* `end()` was called and the write stream successfully wrote the file
|
||||
* metadata and all the chunks to MongoDB.
|
||||
*
|
||||
* @event GridFSBucketWriteStream#finish
|
||||
* @type {object}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Write a buffer to the stream.
|
||||
*
|
||||
* @method
|
||||
* @param {Buffer} chunk Buffer to write
|
||||
* @param {String} encoding Optional encoding for the buffer
|
||||
* @param {GridFSBucket~errorCallback} callback Function to call when the chunk was added to the buffer, or if the entire chunk was persisted to MongoDB if this chunk caused a flush.
|
||||
* @return {Boolean} False if this write required flushing a chunk to MongoDB. True otherwise.
|
||||
*/
|
||||
|
||||
GridFSBucketWriteStream.prototype.write = function(chunk, encoding, callback) {
|
||||
var _this = this;
|
||||
return waitForIndexes(this, function() {
|
||||
return doWrite(_this, chunk, encoding, callback);
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Places this write stream into an aborted state (all future writes fail)
|
||||
* and deletes all chunks that have already been written.
|
||||
*
|
||||
* @method
|
||||
* @param {GridFSBucket~errorCallback} callback called when chunks are successfully removed or error occurred
|
||||
* @return {Promise} if no callback specified
|
||||
*/
|
||||
|
||||
GridFSBucketWriteStream.prototype.abort = function(callback) {
|
||||
if (this.state.streamEnd) {
|
||||
var error = new Error('Cannot abort a stream that has already completed');
|
||||
if (typeof callback === 'function') {
|
||||
return callback(error);
|
||||
}
|
||||
return this.state.promiseLibrary.reject(error);
|
||||
}
|
||||
if (this.state.aborted) {
|
||||
error = new Error('Cannot call abort() on a stream twice');
|
||||
if (typeof callback === 'function') {
|
||||
return callback(error);
|
||||
}
|
||||
return this.state.promiseLibrary.reject(error);
|
||||
}
|
||||
this.state.aborted = true;
|
||||
this.chunks.deleteMany({ files_id: this.id }, function(error) {
|
||||
if (typeof callback === 'function') callback(error);
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Tells the stream that no more data will be coming in. The stream will
|
||||
* persist the remaining data to MongoDB, write the files document, and
|
||||
* then emit a 'finish' event.
|
||||
*
|
||||
* @method
|
||||
* @param {Buffer} chunk Buffer to write
|
||||
* @param {String} encoding Optional encoding for the buffer
|
||||
* @param {GridFSBucket~errorCallback} callback Function to call when all files and chunks have been persisted to MongoDB
|
||||
*/
|
||||
|
||||
GridFSBucketWriteStream.prototype.end = function(chunk, encoding, callback) {
|
||||
var _this = this;
|
||||
if (typeof chunk === 'function') {
|
||||
(callback = chunk), (chunk = null), (encoding = null);
|
||||
} else if (typeof encoding === 'function') {
|
||||
(callback = encoding), (encoding = null);
|
||||
}
|
||||
|
||||
if (checkAborted(this, callback)) {
|
||||
return;
|
||||
}
|
||||
this.state.streamEnd = true;
|
||||
|
||||
if (callback) {
|
||||
this.once('finish', function(result) {
|
||||
callback(null, result);
|
||||
});
|
||||
}
|
||||
|
||||
if (!chunk) {
|
||||
waitForIndexes(this, function() {
|
||||
writeRemnant(_this);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
this.write(chunk, encoding, function() {
|
||||
writeRemnant(_this);
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function __handleError(_this, error, callback) {
|
||||
if (_this.state.errored) {
|
||||
return;
|
||||
}
|
||||
_this.state.errored = true;
|
||||
if (callback) {
|
||||
return callback(error);
|
||||
}
|
||||
_this.emit('error', error);
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function createChunkDoc(filesId, n, data) {
|
||||
return {
|
||||
_id: core.BSON.ObjectId(),
|
||||
files_id: filesId,
|
||||
n: n,
|
||||
data: data
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function checkChunksIndex(_this, callback) {
|
||||
_this.chunks.listIndexes().toArray(function(error, indexes) {
|
||||
if (error) {
|
||||
// Collection doesn't exist so create index
|
||||
if (error.code === ERROR_NAMESPACE_NOT_FOUND) {
|
||||
var index = { files_id: 1, n: 1 };
|
||||
_this.chunks.createIndex(index, { background: false, unique: true }, function(error) {
|
||||
if (error) {
|
||||
return callback(error);
|
||||
}
|
||||
|
||||
callback();
|
||||
});
|
||||
return;
|
||||
}
|
||||
return callback(error);
|
||||
}
|
||||
|
||||
var hasChunksIndex = false;
|
||||
indexes.forEach(function(index) {
|
||||
if (index.key) {
|
||||
var keys = Object.keys(index.key);
|
||||
if (keys.length === 2 && index.key.files_id === 1 && index.key.n === 1) {
|
||||
hasChunksIndex = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (hasChunksIndex) {
|
||||
callback();
|
||||
} else {
|
||||
index = { files_id: 1, n: 1 };
|
||||
var indexOptions = getWriteOptions(_this);
|
||||
|
||||
indexOptions.background = false;
|
||||
indexOptions.unique = true;
|
||||
|
||||
_this.chunks.createIndex(index, indexOptions, function(error) {
|
||||
if (error) {
|
||||
return callback(error);
|
||||
}
|
||||
|
||||
callback();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function checkDone(_this, callback) {
|
||||
if (_this.done) return true;
|
||||
if (_this.state.streamEnd && _this.state.outstandingRequests === 0 && !_this.state.errored) {
|
||||
// Set done so we dont' trigger duplicate createFilesDoc
|
||||
_this.done = true;
|
||||
// Create a new files doc
|
||||
var filesDoc = createFilesDoc(
|
||||
_this.id,
|
||||
_this.length,
|
||||
_this.chunkSizeBytes,
|
||||
_this.md5 && _this.md5.digest('hex'),
|
||||
_this.filename,
|
||||
_this.options.contentType,
|
||||
_this.options.aliases,
|
||||
_this.options.metadata
|
||||
);
|
||||
|
||||
if (checkAborted(_this, callback)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
_this.files.insertOne(filesDoc, getWriteOptions(_this), function(error) {
|
||||
if (error) {
|
||||
return __handleError(_this, error, callback);
|
||||
}
|
||||
_this.emit('finish', filesDoc);
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function checkIndexes(_this, callback) {
|
||||
_this.files.findOne({}, { _id: 1 }, function(error, doc) {
|
||||
if (error) {
|
||||
return callback(error);
|
||||
}
|
||||
if (doc) {
|
||||
return callback();
|
||||
}
|
||||
|
||||
_this.files.listIndexes().toArray(function(error, indexes) {
|
||||
if (error) {
|
||||
// Collection doesn't exist so create index
|
||||
if (error.code === ERROR_NAMESPACE_NOT_FOUND) {
|
||||
var index = { filename: 1, uploadDate: 1 };
|
||||
_this.files.createIndex(index, { background: false }, function(error) {
|
||||
if (error) {
|
||||
return callback(error);
|
||||
}
|
||||
|
||||
checkChunksIndex(_this, callback);
|
||||
});
|
||||
return;
|
||||
}
|
||||
return callback(error);
|
||||
}
|
||||
|
||||
var hasFileIndex = false;
|
||||
indexes.forEach(function(index) {
|
||||
var keys = Object.keys(index.key);
|
||||
if (keys.length === 2 && index.key.filename === 1 && index.key.uploadDate === 1) {
|
||||
hasFileIndex = true;
|
||||
}
|
||||
});
|
||||
|
||||
if (hasFileIndex) {
|
||||
checkChunksIndex(_this, callback);
|
||||
} else {
|
||||
index = { filename: 1, uploadDate: 1 };
|
||||
|
||||
var indexOptions = getWriteOptions(_this);
|
||||
|
||||
indexOptions.background = false;
|
||||
|
||||
_this.files.createIndex(index, indexOptions, function(error) {
|
||||
if (error) {
|
||||
return callback(error);
|
||||
}
|
||||
|
||||
checkChunksIndex(_this, callback);
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function createFilesDoc(_id, length, chunkSize, md5, filename, contentType, aliases, metadata) {
|
||||
var ret = {
|
||||
_id: _id,
|
||||
length: length,
|
||||
chunkSize: chunkSize,
|
||||
uploadDate: new Date(),
|
||||
filename: filename
|
||||
};
|
||||
|
||||
if (md5) {
|
||||
ret.md5 = md5;
|
||||
}
|
||||
|
||||
if (contentType) {
|
||||
ret.contentType = contentType;
|
||||
}
|
||||
|
||||
if (aliases) {
|
||||
ret.aliases = aliases;
|
||||
}
|
||||
|
||||
if (metadata) {
|
||||
ret.metadata = metadata;
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function doWrite(_this, chunk, encoding, callback) {
|
||||
if (checkAborted(_this, callback)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
var inputBuf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding);
|
||||
|
||||
_this.length += inputBuf.length;
|
||||
|
||||
// Input is small enough to fit in our buffer
|
||||
if (_this.pos + inputBuf.length < _this.chunkSizeBytes) {
|
||||
inputBuf.copy(_this.bufToStore, _this.pos);
|
||||
_this.pos += inputBuf.length;
|
||||
|
||||
callback && callback();
|
||||
|
||||
// Note that we reverse the typical semantics of write's return value
|
||||
// to be compatible with node's `.pipe()` function.
|
||||
// True means client can keep writing.
|
||||
return true;
|
||||
}
|
||||
|
||||
// Otherwise, buffer is too big for current chunk, so we need to flush
|
||||
// to MongoDB.
|
||||
var inputBufRemaining = inputBuf.length;
|
||||
var spaceRemaining = _this.chunkSizeBytes - _this.pos;
|
||||
var numToCopy = Math.min(spaceRemaining, inputBuf.length);
|
||||
var outstandingRequests = 0;
|
||||
while (inputBufRemaining > 0) {
|
||||
var inputBufPos = inputBuf.length - inputBufRemaining;
|
||||
inputBuf.copy(_this.bufToStore, _this.pos, inputBufPos, inputBufPos + numToCopy);
|
||||
_this.pos += numToCopy;
|
||||
spaceRemaining -= numToCopy;
|
||||
if (spaceRemaining === 0) {
|
||||
if (_this.md5) {
|
||||
_this.md5.update(_this.bufToStore);
|
||||
}
|
||||
var doc = createChunkDoc(_this.id, _this.n, Buffer.from(_this.bufToStore));
|
||||
++_this.state.outstandingRequests;
|
||||
++outstandingRequests;
|
||||
|
||||
if (checkAborted(_this, callback)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
_this.chunks.insertOne(doc, getWriteOptions(_this), function(error) {
|
||||
if (error) {
|
||||
return __handleError(_this, error);
|
||||
}
|
||||
--_this.state.outstandingRequests;
|
||||
--outstandingRequests;
|
||||
|
||||
if (!outstandingRequests) {
|
||||
_this.emit('drain', doc);
|
||||
callback && callback();
|
||||
checkDone(_this);
|
||||
}
|
||||
});
|
||||
|
||||
spaceRemaining = _this.chunkSizeBytes;
|
||||
_this.pos = 0;
|
||||
++_this.n;
|
||||
}
|
||||
inputBufRemaining -= numToCopy;
|
||||
numToCopy = Math.min(spaceRemaining, inputBufRemaining);
|
||||
}
|
||||
|
||||
// Note that we reverse the typical semantics of write's return value
|
||||
// to be compatible with node's `.pipe()` function.
|
||||
// False means the client should wait for the 'drain' event.
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function getWriteOptions(_this) {
|
||||
var obj = {};
|
||||
if (_this.options.writeConcern) {
|
||||
obj.w = _this.options.writeConcern.w;
|
||||
obj.wtimeout = _this.options.writeConcern.wtimeout;
|
||||
obj.j = _this.options.writeConcern.j;
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function waitForIndexes(_this, callback) {
|
||||
if (_this.bucket.s.checkedIndexes) {
|
||||
return callback(false);
|
||||
}
|
||||
|
||||
_this.bucket.once('index', function() {
|
||||
callback(true);
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function writeRemnant(_this, callback) {
|
||||
// Buffer is empty, so don't bother to insert
|
||||
if (_this.pos === 0) {
|
||||
return checkDone(_this, callback);
|
||||
}
|
||||
|
||||
++_this.state.outstandingRequests;
|
||||
|
||||
// Create a new buffer to make sure the buffer isn't bigger than it needs
|
||||
// to be.
|
||||
var remnant = Buffer.alloc(_this.pos);
|
||||
_this.bufToStore.copy(remnant, 0, 0, _this.pos);
|
||||
if (_this.md5) {
|
||||
_this.md5.update(remnant);
|
||||
}
|
||||
var doc = createChunkDoc(_this.id, _this.n, remnant);
|
||||
|
||||
// If the stream was aborted, do not write remnant
|
||||
if (checkAborted(_this, callback)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
_this.chunks.insertOne(doc, getWriteOptions(_this), function(error) {
|
||||
if (error) {
|
||||
return __handleError(_this, error);
|
||||
}
|
||||
--_this.state.outstandingRequests;
|
||||
checkDone(_this);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
function checkAborted(_this, callback) {
|
||||
if (_this.state.aborted) {
|
||||
if (typeof callback === 'function') {
|
||||
callback(new Error('this stream has been aborted'));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
236
node_modules/mongodb/lib/gridfs/chunk.js
generated
vendored
Normal file
236
node_modules/mongodb/lib/gridfs/chunk.js
generated
vendored
Normal file
@@ -0,0 +1,236 @@
|
||||
'use strict';
|
||||
|
||||
var Binary = require('../core').BSON.Binary,
|
||||
ObjectID = require('../core').BSON.ObjectID;
|
||||
|
||||
var Buffer = require('safe-buffer').Buffer;
|
||||
|
||||
/**
|
||||
* Class for representing a single chunk in GridFS.
|
||||
*
|
||||
* @class
|
||||
*
|
||||
* @param file {GridStore} The {@link GridStore} object holding this chunk.
|
||||
* @param mongoObject {object} The mongo object representation of this chunk.
|
||||
*
|
||||
* @throws Error when the type of data field for {@link mongoObject} is not
|
||||
* supported. Currently supported types for data field are instances of
|
||||
* {@link String}, {@link Array}, {@link Binary} and {@link Binary}
|
||||
* from the bson module
|
||||
*
|
||||
* @see Chunk#buildMongoObject
|
||||
*/
|
||||
var Chunk = function(file, mongoObject, writeConcern) {
|
||||
if (!(this instanceof Chunk)) return new Chunk(file, mongoObject);
|
||||
|
||||
this.file = file;
|
||||
var mongoObjectFinal = mongoObject == null ? {} : mongoObject;
|
||||
this.writeConcern = writeConcern || { w: 1 };
|
||||
this.objectId = mongoObjectFinal._id == null ? new ObjectID() : mongoObjectFinal._id;
|
||||
this.chunkNumber = mongoObjectFinal.n == null ? 0 : mongoObjectFinal.n;
|
||||
this.data = new Binary();
|
||||
|
||||
if (typeof mongoObjectFinal.data === 'string') {
|
||||
var buffer = Buffer.alloc(mongoObjectFinal.data.length);
|
||||
buffer.write(mongoObjectFinal.data, 0, mongoObjectFinal.data.length, 'binary');
|
||||
this.data = new Binary(buffer);
|
||||
} else if (Array.isArray(mongoObjectFinal.data)) {
|
||||
buffer = Buffer.alloc(mongoObjectFinal.data.length);
|
||||
var data = mongoObjectFinal.data.join('');
|
||||
buffer.write(data, 0, data.length, 'binary');
|
||||
this.data = new Binary(buffer);
|
||||
} else if (mongoObjectFinal.data && mongoObjectFinal.data._bsontype === 'Binary') {
|
||||
this.data = mongoObjectFinal.data;
|
||||
} else if (!Buffer.isBuffer(mongoObjectFinal.data) && !(mongoObjectFinal.data == null)) {
|
||||
throw Error('Illegal chunk format');
|
||||
}
|
||||
|
||||
// Update position
|
||||
this.internalPosition = 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Writes a data to this object and advance the read/write head.
|
||||
*
|
||||
* @param data {string} the data to write
|
||||
* @param callback {function(*, GridStore)} This will be called after executing
|
||||
* this method. The first parameter will contain null and the second one
|
||||
* will contain a reference to this object.
|
||||
*/
|
||||
Chunk.prototype.write = function(data, callback) {
|
||||
this.data.write(data, this.internalPosition, data.length, 'binary');
|
||||
this.internalPosition = this.data.length();
|
||||
if (callback != null) return callback(null, this);
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Reads data and advances the read/write head.
|
||||
*
|
||||
* @param length {number} The length of data to read.
|
||||
*
|
||||
* @return {string} The data read if the given length will not exceed the end of
|
||||
* the chunk. Returns an empty String otherwise.
|
||||
*/
|
||||
Chunk.prototype.read = function(length) {
|
||||
// Default to full read if no index defined
|
||||
length = length == null || length === 0 ? this.length() : length;
|
||||
|
||||
if (this.length() - this.internalPosition + 1 >= length) {
|
||||
var data = this.data.read(this.internalPosition, length);
|
||||
this.internalPosition = this.internalPosition + length;
|
||||
return data;
|
||||
} else {
|
||||
return '';
|
||||
}
|
||||
};
|
||||
|
||||
Chunk.prototype.readSlice = function(length) {
|
||||
if (this.length() - this.internalPosition >= length) {
|
||||
var data = null;
|
||||
if (this.data.buffer != null) {
|
||||
//Pure BSON
|
||||
data = this.data.buffer.slice(this.internalPosition, this.internalPosition + length);
|
||||
} else {
|
||||
//Native BSON
|
||||
data = Buffer.alloc(length);
|
||||
length = this.data.readInto(data, this.internalPosition);
|
||||
}
|
||||
this.internalPosition = this.internalPosition + length;
|
||||
return data;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Checks if the read/write head is at the end.
|
||||
*
|
||||
* @return {boolean} Whether the read/write head has reached the end of this
|
||||
* chunk.
|
||||
*/
|
||||
Chunk.prototype.eof = function() {
|
||||
return this.internalPosition === this.length() ? true : false;
|
||||
};
|
||||
|
||||
/**
|
||||
* Reads one character from the data of this chunk and advances the read/write
|
||||
* head.
|
||||
*
|
||||
* @return {string} a single character data read if the the read/write head is
|
||||
* not at the end of the chunk. Returns an empty String otherwise.
|
||||
*/
|
||||
Chunk.prototype.getc = function() {
|
||||
return this.read(1);
|
||||
};
|
||||
|
||||
/**
|
||||
* Clears the contents of the data in this chunk and resets the read/write head
|
||||
* to the initial position.
|
||||
*/
|
||||
Chunk.prototype.rewind = function() {
|
||||
this.internalPosition = 0;
|
||||
this.data = new Binary();
|
||||
};
|
||||
|
||||
/**
|
||||
* Saves this chunk to the database. Also overwrites existing entries having the
|
||||
* same id as this chunk.
|
||||
*
|
||||
* @param callback {function(*, GridStore)} This will be called after executing
|
||||
* this method. The first parameter will contain null and the second one
|
||||
* will contain a reference to this object.
|
||||
*/
|
||||
Chunk.prototype.save = function(options, callback) {
|
||||
var self = this;
|
||||
if (typeof options === 'function') {
|
||||
callback = options;
|
||||
options = {};
|
||||
}
|
||||
|
||||
self.file.chunkCollection(function(err, collection) {
|
||||
if (err) return callback(err);
|
||||
|
||||
// Merge the options
|
||||
var writeOptions = { upsert: true };
|
||||
for (var name in options) writeOptions[name] = options[name];
|
||||
for (name in self.writeConcern) writeOptions[name] = self.writeConcern[name];
|
||||
|
||||
if (self.data.length() > 0) {
|
||||
self.buildMongoObject(function(mongoObject) {
|
||||
var options = { forceServerObjectId: true };
|
||||
for (var name in self.writeConcern) {
|
||||
options[name] = self.writeConcern[name];
|
||||
}
|
||||
|
||||
collection.replaceOne({ _id: self.objectId }, mongoObject, writeOptions, function(err) {
|
||||
callback(err, self);
|
||||
});
|
||||
});
|
||||
} else {
|
||||
callback(null, self);
|
||||
}
|
||||
// });
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates a mongoDB object representation of this chunk.
|
||||
*
|
||||
* @param callback {function(Object)} This will be called after executing this
|
||||
* method. The object will be passed to the first parameter and will have
|
||||
* the structure:
|
||||
*
|
||||
* <pre><code>
|
||||
* {
|
||||
* '_id' : , // {number} id for this chunk
|
||||
* 'files_id' : , // {number} foreign key to the file collection
|
||||
* 'n' : , // {number} chunk number
|
||||
* 'data' : , // {bson#Binary} the chunk data itself
|
||||
* }
|
||||
* </code></pre>
|
||||
*
|
||||
* @see <a href="http://www.mongodb.org/display/DOCS/GridFS+Specification#GridFSSpecification-{{chunks}}">MongoDB GridFS Chunk Object Structure</a>
|
||||
*/
|
||||
Chunk.prototype.buildMongoObject = function(callback) {
|
||||
var mongoObject = {
|
||||
files_id: this.file.fileId,
|
||||
n: this.chunkNumber,
|
||||
data: this.data
|
||||
};
|
||||
// If we are saving using a specific ObjectId
|
||||
if (this.objectId != null) mongoObject._id = this.objectId;
|
||||
|
||||
callback(mongoObject);
|
||||
};
|
||||
|
||||
/**
|
||||
* @return {number} the length of the data
|
||||
*/
|
||||
Chunk.prototype.length = function() {
|
||||
return this.data.length();
|
||||
};
|
||||
|
||||
/**
|
||||
* The position of the read/write head
|
||||
* @name position
|
||||
* @lends Chunk#
|
||||
* @field
|
||||
*/
|
||||
Object.defineProperty(Chunk.prototype, 'position', {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return this.internalPosition;
|
||||
},
|
||||
set: function(value) {
|
||||
this.internalPosition = value;
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* The default chunk size
|
||||
* @constant
|
||||
*/
|
||||
Chunk.DEFAULT_CHUNK_SIZE = 1024 * 255;
|
||||
|
||||
module.exports = Chunk;
|
||||
1920
node_modules/mongodb/lib/gridfs/grid_store.js
generated
vendored
Normal file
1920
node_modules/mongodb/lib/gridfs/grid_store.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
542
node_modules/mongodb/lib/mongo_client.js
generated
vendored
Normal file
542
node_modules/mongodb/lib/mongo_client.js
generated
vendored
Normal file
@@ -0,0 +1,542 @@
|
||||
'use strict';
|
||||
|
||||
const ChangeStream = require('./change_stream');
|
||||
const Db = require('./db');
|
||||
const EventEmitter = require('events').EventEmitter;
|
||||
const inherits = require('util').inherits;
|
||||
const MongoError = require('./core').MongoError;
|
||||
const deprecate = require('util').deprecate;
|
||||
const WriteConcern = require('./write_concern');
|
||||
const MongoDBNamespace = require('./utils').MongoDBNamespace;
|
||||
const ReadPreference = require('./core/topologies/read_preference');
|
||||
const maybePromise = require('./utils').maybePromise;
|
||||
const NativeTopology = require('./topologies/native_topology');
|
||||
const connect = require('./operations/connect').connect;
|
||||
const validOptions = require('./operations/connect').validOptions;
|
||||
|
||||
/**
|
||||
* @fileOverview The **MongoClient** class is a class that allows for making Connections to MongoDB.
|
||||
*
|
||||
* @example
|
||||
* // Connect using a MongoClient instance
|
||||
* const MongoClient = require('mongodb').MongoClient;
|
||||
* const test = require('assert');
|
||||
* // Connection url
|
||||
* const url = 'mongodb://localhost:27017';
|
||||
* // Database Name
|
||||
* const dbName = 'test';
|
||||
* // Connect using MongoClient
|
||||
* const mongoClient = new MongoClient(url);
|
||||
* mongoClient.connect(function(err, client) {
|
||||
* const db = client.db(dbName);
|
||||
* client.close();
|
||||
* });
|
||||
*
|
||||
* @example
|
||||
* // Connect using the MongoClient.connect static method
|
||||
* const MongoClient = require('mongodb').MongoClient;
|
||||
* const test = require('assert');
|
||||
* // Connection url
|
||||
* const url = 'mongodb://localhost:27017';
|
||||
* // Database Name
|
||||
* const dbName = 'test';
|
||||
* // Connect using MongoClient
|
||||
* MongoClient.connect(url, function(err, client) {
|
||||
* const db = client.db(dbName);
|
||||
* client.close();
|
||||
* });
|
||||
*/
|
||||
|
||||
/**
|
||||
* A string specifying the level of a ReadConcern
|
||||
* @typedef {'local'|'available'|'majority'|'linearizable'|'snapshot'} ReadConcernLevel
|
||||
* @see https://docs.mongodb.com/manual/reference/read-concern/index.html#read-concern-levels
|
||||
*/
|
||||
|
||||
/**
|
||||
* Configuration options for drivers wrapping the node driver.
|
||||
*
|
||||
* @typedef {Object} DriverInfoOptions
|
||||
* @property {string} [name] The name of the driver
|
||||
* @property {string} [version] The version of the driver
|
||||
* @property {string} [platform] Optional platform information
|
||||
*/
|
||||
|
||||
/**
|
||||
* Configuration options for drivers wrapping the node driver.
|
||||
*
|
||||
* @typedef {Object} DriverInfoOptions
|
||||
* @property {string} [name] The name of the driver
|
||||
* @property {string} [version] The version of the driver
|
||||
* @property {string} [platform] Optional platform information
|
||||
*/
|
||||
|
||||
/**
|
||||
* Creates a new MongoClient instance
|
||||
* @class
|
||||
* @param {string} url The connection URI string
|
||||
* @param {object} [options] Optional settings
|
||||
* @param {number} [options.poolSize=5] The maximum size of the individual server pool
|
||||
* @param {boolean} [options.ssl=false] Enable SSL connection. *deprecated* use `tls` variants
|
||||
* @param {boolean} [options.sslValidate=false] Validate mongod server certificate against Certificate Authority
|
||||
* @param {buffer} [options.sslCA=undefined] SSL Certificate store binary buffer *deprecated* use `tls` variants
|
||||
* @param {buffer} [options.sslCert=undefined] SSL Certificate binary buffer *deprecated* use `tls` variants
|
||||
* @param {buffer} [options.sslKey=undefined] SSL Key file binary buffer *deprecated* use `tls` variants
|
||||
* @param {string} [options.sslPass=undefined] SSL Certificate pass phrase *deprecated* use `tls` variants
|
||||
* @param {buffer} [options.sslCRL=undefined] SSL Certificate revocation list binary buffer *deprecated* use `tls` variants
|
||||
* @param {boolean|function} [options.checkServerIdentity=true] 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. *deprecated* use `tls` variants
|
||||
* @param {boolean} [options.tls=false] Enable TLS connections
|
||||
* @param {boolean} [options.tlsInsecure=false] Relax TLS constraints, disabling validation
|
||||
* @param {string} [options.tlsCAFile] A path to file with either a single or bundle of certificate authorities to be considered trusted when making a TLS connection
|
||||
* @param {string} [options.tlsCertificateKeyFile] A path to the client certificate file or the client private key file; in the case that they both are needed, the files should be concatenated
|
||||
* @param {string} [options.tlsCertificateKeyFilePassword] The password to decrypt the client private key to be used for TLS connections
|
||||
* @param {boolean} [options.tlsAllowInvalidCertificates] Specifies whether or not the driver should error when the server’s TLS certificate is invalid
|
||||
* @param {boolean} [options.tlsAllowInvalidHostnames] Specifies whether or not the driver should error when there is a mismatch between the server’s hostname and the hostname specified by the TLS certificate
|
||||
* @param {boolean} [options.autoReconnect=true] Enable autoReconnect for single server instances
|
||||
* @param {boolean} [options.noDelay=true] TCP Connection no delay
|
||||
* @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled
|
||||
* @param {number} [options.keepAliveInitialDelay=120000] The number of milliseconds to wait before initiating keepAlive on the TCP socket
|
||||
* @param {number} [options.connectTimeoutMS=10000] How long to wait for a connection to be established before timing out
|
||||
* @param {number} [options.socketTimeoutMS=360000] How long a send or receive on a socket can take before timing out
|
||||
* @param {number} [options.family] Version of IP stack. Can be 4, 6 or null (default).
|
||||
* If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure
|
||||
* @param {number} [options.reconnectTries=30] Server attempt to reconnect #times
|
||||
* @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries
|
||||
* @param {boolean} [options.ha=true] Control if high availability monitoring runs for Replicaset or Mongos proxies
|
||||
* @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry
|
||||
* @param {string} [options.replicaSet=undefined] The Replicaset set name
|
||||
* @param {number} [options.secondaryAcceptableLatencyMS=15] Cutoff latency point in MS for Replicaset member selection
|
||||
* @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for Mongos proxies selection
|
||||
* @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available
|
||||
* @param {string} [options.authSource=undefined] Define the database to authenticate against
|
||||
* @param {(number|string)} [options.w] The write concern
|
||||
* @param {number} [options.wtimeout] The write concern timeout
|
||||
* @param {boolean} [options.j=false] Specify a journal write concern
|
||||
* @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver
|
||||
* @param {boolean} [options.serializeFunctions=false] Serialize functions on any object
|
||||
* @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields
|
||||
* @param {boolean} [options.raw=false] Return document results as raw BSON buffers
|
||||
* @param {number} [options.bufferMaxEntries=-1] 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
|
||||
* @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST)
|
||||
* @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys
|
||||
* @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible
|
||||
* @param {object} [options.readConcern] Specify a read concern for the collection (only MongoDB 3.2 or higher supported)
|
||||
* @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported)
|
||||
* @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed)
|
||||
* @param {string} [options.loggerLevel=undefined] The logging level (error/warn/info/debug)
|
||||
* @param {object} [options.logger=undefined] Custom logger object
|
||||
* @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types
|
||||
* @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers
|
||||
* @param {boolean} [options.promoteLongs=true] Promotes long values to number if they fit inside the 53 bits resolution
|
||||
* @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit
|
||||
* @param {object} [options.validateOptions=false] Validate MongoClient passed in options for correctness
|
||||
* @param {string} [options.appname=undefined] 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
|
||||
* @param {string} [options.auth.user=undefined] The username for auth
|
||||
* @param {string} [options.auth.password=undefined] The password for auth
|
||||
* @param {string} [options.authMechanism] An authentication mechanism to use for connection authentication, see the {@link https://docs.mongodb.com/manual/reference/connection-string/#urioption.authMechanism|authMechanism} reference for supported options.
|
||||
* @param {object} [options.compression] Type of compression to use: snappy or zlib
|
||||
* @param {boolean} [options.fsync=false] Specify a file sync write concern
|
||||
* @param {array} [options.readPreferenceTags] Read preference tags
|
||||
* @param {number} [options.numberOfRetries=5] The number of retries for a tailable cursor
|
||||
* @param {boolean} [options.auto_reconnect=true] Enable auto reconnecting for single server instances
|
||||
* @param {boolean} [options.monitorCommands=false] Enable command monitoring for this client
|
||||
* @param {number} [options.minSize] If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections
|
||||
* @param {boolean} [options.useNewUrlParser=true] Determines whether or not to use the new url parser. Enables the new, spec-compliant, url parser shipped in the core driver. This url parser fixes a number of problems with the original parser, and aims to outright replace that parser in the near future. Defaults to true, and must be explicitly set to false to use the legacy url parser.
|
||||
* @param {boolean} [options.useUnifiedTopology] Enables the new unified topology layer
|
||||
* @param {Number} [options.localThresholdMS=15] **Only applies to the unified topology** The size of the latency window for selecting among multiple suitable servers
|
||||
* @param {Number} [options.serverSelectionTimeoutMS=30000] **Only applies to the unified topology** How long to block for server selection before throwing an error
|
||||
* @param {Number} [options.heartbeatFrequencyMS=10000] **Only applies to the unified topology** The frequency with which topology updates are scheduled
|
||||
* @param {number} [options.maxPoolSize=10] **Only applies to the unified topology** The maximum number of connections that may be associated with a pool at a given time. This includes in use and available connections.
|
||||
* @param {number} [options.minPoolSize=0] **Only applies to the unified topology** The minimum number of connections that MUST exist at any moment in a single connection pool.
|
||||
* @param {number} [options.maxIdleTimeMS] **Only applies to the unified topology** The maximum amount of time a connection should remain idle in the connection pool before being marked idle. The default is infinity.
|
||||
* @param {number} [options.waitQueueTimeoutMS=0] **Only applies to the unified topology** The maximum amount of time operation execution should wait for a connection to become available. The default is 0 which means there is no limit.
|
||||
* @param {AutoEncrypter~AutoEncryptionOptions} [options.autoEncryption] Optionally enable client side auto encryption
|
||||
* @param {DriverInfoOptions} [options.driverInfo] Allows a wrapping driver to amend the client metadata generated by the driver to include information about the wrapping driver
|
||||
* @param {boolean} [options.directConnection=false] Enable directConnection
|
||||
* @param {MongoClient~connectCallback} [callback] The command result callback
|
||||
* @return {MongoClient} a MongoClient instance
|
||||
*/
|
||||
function MongoClient(url, options) {
|
||||
if (!(this instanceof MongoClient)) return new MongoClient(url, options);
|
||||
// Set up event emitter
|
||||
EventEmitter.call(this);
|
||||
|
||||
// The internal state
|
||||
this.s = {
|
||||
url: url,
|
||||
options: options || {},
|
||||
promiseLibrary: (options && options.promiseLibrary) || Promise,
|
||||
dbCache: new Map(),
|
||||
sessions: new Set(),
|
||||
writeConcern: WriteConcern.fromOptions(options),
|
||||
namespace: new MongoDBNamespace('admin')
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
inherits(MongoClient, EventEmitter);
|
||||
|
||||
Object.defineProperty(MongoClient.prototype, 'writeConcern', {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return this.s.writeConcern;
|
||||
}
|
||||
});
|
||||
|
||||
Object.defineProperty(MongoClient.prototype, 'readPreference', {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return ReadPreference.primary;
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* The callback format for results
|
||||
* @callback MongoClient~connectCallback
|
||||
* @param {MongoError} error An error instance representing the error during the execution.
|
||||
* @param {MongoClient} client The connected client.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Connect to MongoDB using a url as documented at
|
||||
*
|
||||
* docs.mongodb.org/manual/reference/connection-string/
|
||||
*
|
||||
* Note that for replicasets the replicaSet query parameter is required in the 2.0 driver
|
||||
*
|
||||
* @method
|
||||
* @param {MongoClient~connectCallback} [callback] The command result callback
|
||||
* @return {Promise<MongoClient>} returns Promise if no callback passed
|
||||
*/
|
||||
MongoClient.prototype.connect = function(callback) {
|
||||
if (typeof callback === 'string') {
|
||||
throw new TypeError('`connect` only accepts a callback');
|
||||
}
|
||||
|
||||
const client = this;
|
||||
return maybePromise(this, callback, cb => {
|
||||
const err = validOptions(client.s.options);
|
||||
if (err) return cb(err);
|
||||
|
||||
connect(client, client.s.url, client.s.options, err => {
|
||||
if (err) return cb(err);
|
||||
cb(null, client);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
MongoClient.prototype.logout = deprecate(function(options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
if (typeof callback === 'function') callback(null, true);
|
||||
}, 'Multiple authentication is prohibited on a connected client, please only authenticate once per MongoClient');
|
||||
|
||||
/**
|
||||
* Close the db and its underlying connections
|
||||
* @method
|
||||
* @param {boolean} [force=false] Force close, emitting no events
|
||||
* @param {Db~noResultCallback} [callback] The result callback
|
||||
* @return {Promise} returns Promise if no callback passed
|
||||
*/
|
||||
MongoClient.prototype.close = function(force, callback) {
|
||||
if (typeof force === 'function') {
|
||||
callback = force;
|
||||
force = false;
|
||||
}
|
||||
|
||||
const client = this;
|
||||
return maybePromise(this, callback, cb => {
|
||||
const completeClose = err => {
|
||||
client.emit('close', client);
|
||||
|
||||
if (!(client.topology instanceof NativeTopology)) {
|
||||
for (const item of client.s.dbCache) {
|
||||
item[1].emit('close', client);
|
||||
}
|
||||
}
|
||||
|
||||
client.removeAllListeners('close');
|
||||
cb(err);
|
||||
};
|
||||
|
||||
if (client.topology == null) {
|
||||
completeClose();
|
||||
return;
|
||||
}
|
||||
|
||||
client.topology.close(force, err => {
|
||||
const autoEncrypter = client.topology.s.options.autoEncrypter;
|
||||
if (!autoEncrypter) {
|
||||
completeClose(err);
|
||||
return;
|
||||
}
|
||||
|
||||
autoEncrypter.teardown(force, err2 => completeClose(err || err2));
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Create a new Db instance sharing the current socket connections. Be aware that the new db instances are
|
||||
* related in a parent-child relationship to the original instance so that events are correctly emitted on child
|
||||
* db instances. Child db instances are cached so performing db('db1') twice will return the same instance.
|
||||
* You can control these behaviors with the options noListener and returnNonCachedInstance.
|
||||
*
|
||||
* @method
|
||||
* @param {string} [dbName] The name of the database we want to use. If not provided, use database name from connection string.
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection.
|
||||
* @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created
|
||||
* @return {Db}
|
||||
*/
|
||||
MongoClient.prototype.db = function(dbName, options) {
|
||||
options = options || {};
|
||||
|
||||
// Default to db from connection string if not provided
|
||||
if (!dbName) {
|
||||
dbName = this.s.options.dbName;
|
||||
}
|
||||
|
||||
// Copy the options and add out internal override of the not shared flag
|
||||
const finalOptions = Object.assign({}, this.s.options, options);
|
||||
|
||||
// Do we have the db in the cache already
|
||||
if (this.s.dbCache.has(dbName) && finalOptions.returnNonCachedInstance !== true) {
|
||||
return this.s.dbCache.get(dbName);
|
||||
}
|
||||
|
||||
// Add promiseLibrary
|
||||
finalOptions.promiseLibrary = this.s.promiseLibrary;
|
||||
|
||||
// If no topology throw an error message
|
||||
if (!this.topology) {
|
||||
throw new MongoError('MongoClient must be connected before calling MongoClient.prototype.db');
|
||||
}
|
||||
|
||||
// Return the db object
|
||||
const db = new Db(dbName, this.topology, finalOptions);
|
||||
|
||||
// Add the db to the cache
|
||||
this.s.dbCache.set(dbName, db);
|
||||
// Return the database
|
||||
return db;
|
||||
};
|
||||
|
||||
/**
|
||||
* Check if MongoClient is connected
|
||||
*
|
||||
* @method
|
||||
* @param {object} [options] Optional settings.
|
||||
* @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection.
|
||||
* @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created
|
||||
* @return {boolean}
|
||||
*/
|
||||
MongoClient.prototype.isConnected = function(options) {
|
||||
options = options || {};
|
||||
|
||||
if (!this.topology) return false;
|
||||
return this.topology.isConnected(options);
|
||||
};
|
||||
|
||||
/**
|
||||
* Connect to MongoDB using a url as documented at
|
||||
*
|
||||
* docs.mongodb.org/manual/reference/connection-string/
|
||||
*
|
||||
* Note that for replicasets the replicaSet query parameter is required in the 2.0 driver
|
||||
*
|
||||
* @method
|
||||
* @static
|
||||
* @param {string} url The connection URI string
|
||||
* @param {object} [options] Optional settings
|
||||
* @param {number} [options.poolSize=5] The maximum size of the individual server pool
|
||||
* @param {boolean} [options.ssl=false] Enable SSL connection. *deprecated* use `tls` variants
|
||||
* @param {boolean} [options.sslValidate=false] Validate mongod server certificate against Certificate Authority
|
||||
* @param {buffer} [options.sslCA=undefined] SSL Certificate store binary buffer *deprecated* use `tls` variants
|
||||
* @param {buffer} [options.sslCert=undefined] SSL Certificate binary buffer *deprecated* use `tls` variants
|
||||
* @param {buffer} [options.sslKey=undefined] SSL Key file binary buffer *deprecated* use `tls` variants
|
||||
* @param {string} [options.sslPass=undefined] SSL Certificate pass phrase *deprecated* use `tls` variants
|
||||
* @param {buffer} [options.sslCRL=undefined] SSL Certificate revocation list binary buffer *deprecated* use `tls` variants
|
||||
* @param {boolean|function} [options.checkServerIdentity=true] 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. *deprecated* use `tls` variants
|
||||
* @param {boolean} [options.tls=false] Enable TLS connections
|
||||
* @param {boolean} [options.tlsInsecure=false] Relax TLS constraints, disabling validation
|
||||
* @param {string} [options.tlsCAFile] A path to file with either a single or bundle of certificate authorities to be considered trusted when making a TLS connection
|
||||
* @param {string} [options.tlsCertificateKeyFile] A path to the client certificate file or the client private key file; in the case that they both are needed, the files should be concatenated
|
||||
* @param {string} [options.tlsCertificateKeyFilePassword] The password to decrypt the client private key to be used for TLS connections
|
||||
* @param {boolean} [options.tlsAllowInvalidCertificates] Specifies whether or not the driver should error when the server’s TLS certificate is invalid
|
||||
* @param {boolean} [options.tlsAllowInvalidHostnames] Specifies whether or not the driver should error when there is a mismatch between the server’s hostname and the hostname specified by the TLS certificate
|
||||
* @param {boolean} [options.autoReconnect=true] Enable autoReconnect for single server instances
|
||||
* @param {boolean} [options.noDelay=true] TCP Connection no delay
|
||||
* @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled
|
||||
* @param {number} [options.keepAliveInitialDelay=120000] The number of milliseconds to wait before initiating keepAlive on the TCP socket
|
||||
* @param {number} [options.connectTimeoutMS=10000] How long to wait for a connection to be established before timing out
|
||||
* @param {number} [options.socketTimeoutMS=360000] How long a send or receive on a socket can take before timing out
|
||||
* @param {number} [options.family] Version of IP stack. Can be 4, 6 or null (default).
|
||||
* If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure
|
||||
* @param {number} [options.reconnectTries=30] Server attempt to reconnect #times
|
||||
* @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries
|
||||
* @param {boolean} [options.ha=true] Control if high availability monitoring runs for Replicaset or Mongos proxies
|
||||
* @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry
|
||||
* @param {string} [options.replicaSet=undefined] The Replicaset set name
|
||||
* @param {number} [options.secondaryAcceptableLatencyMS=15] Cutoff latency point in MS for Replicaset member selection
|
||||
* @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for Mongos proxies selection
|
||||
* @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available
|
||||
* @param {string} [options.authSource=undefined] Define the database to authenticate against
|
||||
* @param {(number|string)} [options.w] The write concern
|
||||
* @param {number} [options.wtimeout] The write concern timeout
|
||||
* @param {boolean} [options.j=false] Specify a journal write concern
|
||||
* @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver
|
||||
* @param {boolean} [options.serializeFunctions=false] Serialize functions on any object
|
||||
* @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields
|
||||
* @param {boolean} [options.raw=false] Return document results as raw BSON buffers
|
||||
* @param {number} [options.bufferMaxEntries=-1] 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
|
||||
* @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST)
|
||||
* @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys
|
||||
* @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible
|
||||
* @param {object} [options.readConcern] Specify a read concern for the collection (only MongoDB 3.2 or higher supported)
|
||||
* @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported)
|
||||
* @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed)
|
||||
* @param {string} [options.loggerLevel=undefined] The logging level (error/warn/info/debug)
|
||||
* @param {object} [options.logger=undefined] Custom logger object
|
||||
* @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types
|
||||
* @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers
|
||||
* @param {boolean} [options.promoteLongs=true] Promotes long values to number if they fit inside the 53 bits resolution
|
||||
* @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit
|
||||
* @param {object} [options.validateOptions=false] Validate MongoClient passed in options for correctness
|
||||
* @param {string} [options.appname=undefined] 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
|
||||
* @param {string} [options.auth.user=undefined] The username for auth
|
||||
* @param {string} [options.auth.password=undefined] The password for auth
|
||||
* @param {string} [options.authMechanism] An authentication mechanism to use for connection authentication, see the {@link https://docs.mongodb.com/manual/reference/connection-string/#urioption.authMechanism|authMechanism} reference for supported options.
|
||||
* @param {object} [options.compression] Type of compression to use: snappy or zlib
|
||||
* @param {boolean} [options.fsync=false] Specify a file sync write concern
|
||||
* @param {array} [options.readPreferenceTags] Read preference tags
|
||||
* @param {number} [options.numberOfRetries=5] The number of retries for a tailable cursor
|
||||
* @param {boolean} [options.auto_reconnect=true] Enable auto reconnecting for single server instances
|
||||
* @param {boolean} [options.monitorCommands=false] Enable command monitoring for this client
|
||||
* @param {number} [options.minSize] If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections
|
||||
* @param {boolean} [options.directConnection=false] Enable directConnection
|
||||
* @param {boolean} [options.useNewUrlParser=true] Determines whether or not to use the new url parser. Enables the new, spec-compliant, url parser shipped in the core driver. This url parser fixes a number of problems with the original parser, and aims to outright replace that parser in the near future. Defaults to true, and must be explicitly set to false to use the legacy url parser.
|
||||
* @param {boolean} [options.useUnifiedTopology] Enables the new unified topology layer
|
||||
* @param {Number} [options.localThresholdMS=15] **Only applies to the unified topology** The size of the latency window for selecting among multiple suitable servers
|
||||
* @param {Number} [options.serverSelectionTimeoutMS=30000] **Only applies to the unified topology** How long to block for server selection before throwing an error
|
||||
* @param {Number} [options.heartbeatFrequencyMS=10000] **Only applies to the unified topology** The frequency with which topology updates are scheduled
|
||||
* @param {number} [options.maxPoolSize=10] **Only applies to the unified topology** The maximum number of connections that may be associated with a pool at a given time. This includes in use and available connections.
|
||||
* @param {number} [options.minPoolSize=0] **Only applies to the unified topology** The minimum number of connections that MUST exist at any moment in a single connection pool.
|
||||
* @param {number} [options.maxIdleTimeMS] **Only applies to the unified topology** The maximum amount of time a connection should remain idle in the connection pool before being marked idle. The default is infinity.
|
||||
* @param {number} [options.waitQueueTimeoutMS=0] **Only applies to the unified topology** The maximum amount of time operation execution should wait for a connection to become available. The default is 0 which means there is no limit.
|
||||
* @param {AutoEncrypter~AutoEncryptionOptions} [options.autoEncryption] Optionally enable client side auto encryption
|
||||
* @param {DriverInfoOptions} [options.driverInfo] Allows a wrapping driver to amend the client metadata generated by the driver to include information about the wrapping driver
|
||||
* @param {MongoClient~connectCallback} [callback] The command result callback
|
||||
* @return {Promise<MongoClient>} returns Promise if no callback passed
|
||||
*/
|
||||
MongoClient.connect = function(url, options, callback) {
|
||||
const args = Array.prototype.slice.call(arguments, 1);
|
||||
callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
|
||||
options = args.length ? args.shift() : null;
|
||||
options = options || {};
|
||||
|
||||
// Create client
|
||||
const mongoClient = new MongoClient(url, options);
|
||||
// Execute the connect method
|
||||
return mongoClient.connect(callback);
|
||||
};
|
||||
|
||||
/**
|
||||
* Starts a new session on the server
|
||||
*
|
||||
* @param {SessionOptions} [options] optional settings for a driver session
|
||||
* @return {ClientSession} the newly established session
|
||||
*/
|
||||
MongoClient.prototype.startSession = function(options) {
|
||||
options = Object.assign({ explicit: true }, options);
|
||||
if (!this.topology) {
|
||||
throw new MongoError('Must connect to a server before calling this method');
|
||||
}
|
||||
|
||||
if (!this.topology.hasSessionSupport()) {
|
||||
throw new MongoError('Current topology does not support sessions');
|
||||
}
|
||||
|
||||
return this.topology.startSession(options, this.s.options);
|
||||
};
|
||||
|
||||
/**
|
||||
* Runs a given operation with an implicitly created session. The lifetime of the session
|
||||
* will be handled without the need for user interaction.
|
||||
*
|
||||
* NOTE: presently the operation MUST return a Promise (either explicit or implicity as an async function)
|
||||
*
|
||||
* @param {Object} [options] Optional settings to be appled to implicitly created session
|
||||
* @param {Function} operation An operation to execute with an implicitly created session. The signature of this MUST be `(session) => {}`
|
||||
* @return {Promise}
|
||||
*/
|
||||
MongoClient.prototype.withSession = function(options, operation) {
|
||||
if (typeof options === 'function') (operation = options), (options = undefined);
|
||||
const session = this.startSession(options);
|
||||
|
||||
let cleanupHandler = (err, result, opts) => {
|
||||
// prevent multiple calls to cleanupHandler
|
||||
cleanupHandler = () => {
|
||||
throw new ReferenceError('cleanupHandler was called too many times');
|
||||
};
|
||||
|
||||
opts = Object.assign({ throw: true }, opts);
|
||||
session.endSession();
|
||||
|
||||
if (err) {
|
||||
if (opts.throw) throw err;
|
||||
return Promise.reject(err);
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
const result = operation(session);
|
||||
return Promise.resolve(result)
|
||||
.then(result => cleanupHandler(null, result))
|
||||
.catch(err => cleanupHandler(err, null, { throw: true }));
|
||||
} catch (err) {
|
||||
return cleanupHandler(err, null, { throw: false });
|
||||
}
|
||||
};
|
||||
/**
|
||||
* Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this cluster. Will ignore all changes to system collections, as well as the local, admin,
|
||||
* and config databases.
|
||||
* @method
|
||||
* @since 3.1.0
|
||||
* @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents.
|
||||
* @param {object} [options] Optional settings
|
||||
* @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred.
|
||||
* @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document.
|
||||
* @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query
|
||||
* @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.
|
||||
* @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.
|
||||
* @param {ReadPreference} [options.readPreference] The read preference. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}.
|
||||
* @param {Timestamp} [options.startAtOperationTime] receive change events that occur after the specified timestamp
|
||||
* @param {ClientSession} [options.session] optional session to use for this operation
|
||||
* @return {ChangeStream} a ChangeStream instance.
|
||||
*/
|
||||
MongoClient.prototype.watch = function(pipeline, options) {
|
||||
pipeline = pipeline || [];
|
||||
options = options || {};
|
||||
|
||||
// Allow optionally not specifying a pipeline
|
||||
if (!Array.isArray(pipeline)) {
|
||||
options = pipeline;
|
||||
pipeline = [];
|
||||
}
|
||||
|
||||
return new ChangeStream(this, pipeline, options);
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the mongo client logger
|
||||
* @method
|
||||
* @return {Logger} return the mongo client logger
|
||||
* @ignore
|
||||
*/
|
||||
MongoClient.prototype.getLogger = function() {
|
||||
return this.s.options.logger;
|
||||
};
|
||||
|
||||
module.exports = MongoClient;
|
||||
96
node_modules/mongodb/lib/operations/add_user.js
generated
vendored
Normal file
96
node_modules/mongodb/lib/operations/add_user.js
generated
vendored
Normal file
@@ -0,0 +1,96 @@
|
||||
'use strict';
|
||||
|
||||
const Aspect = require('./operation').Aspect;
|
||||
const CommandOperation = require('./command');
|
||||
const defineAspects = require('./operation').defineAspects;
|
||||
const crypto = require('crypto');
|
||||
const handleCallback = require('../utils').handleCallback;
|
||||
const toError = require('../utils').toError;
|
||||
|
||||
class AddUserOperation extends CommandOperation {
|
||||
constructor(db, username, password, options) {
|
||||
super(db, options);
|
||||
|
||||
this.username = username;
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
_buildCommand() {
|
||||
const db = this.db;
|
||||
const username = this.username;
|
||||
const password = this.password;
|
||||
const options = this.options;
|
||||
|
||||
// Get additional values
|
||||
let roles = Array.isArray(options.roles) ? options.roles : [];
|
||||
|
||||
// If not roles defined print deprecated message
|
||||
// TODO: handle deprecation properly
|
||||
if (roles.length === 0) {
|
||||
console.log('Creating a user without roles is deprecated in MongoDB >= 2.6');
|
||||
}
|
||||
|
||||
// Check the db name and add roles if needed
|
||||
if (
|
||||
(db.databaseName.toLowerCase() === 'admin' || options.dbName === 'admin') &&
|
||||
!Array.isArray(options.roles)
|
||||
) {
|
||||
roles = ['root'];
|
||||
} else if (!Array.isArray(options.roles)) {
|
||||
roles = ['dbOwner'];
|
||||
}
|
||||
|
||||
const digestPassword = db.s.topology.lastIsMaster().maxWireVersion >= 7;
|
||||
|
||||
let userPassword = password;
|
||||
|
||||
if (!digestPassword) {
|
||||
// Use node md5 generator
|
||||
const md5 = crypto.createHash('md5');
|
||||
// Generate keys used for authentication
|
||||
md5.update(username + ':mongo:' + password);
|
||||
userPassword = md5.digest('hex');
|
||||
}
|
||||
|
||||
// Build the command to execute
|
||||
const command = {
|
||||
createUser: username,
|
||||
customData: options.customData || {},
|
||||
roles: roles,
|
||||
digestPassword
|
||||
};
|
||||
|
||||
// No password
|
||||
if (typeof password === 'string') {
|
||||
command.pwd = userPassword;
|
||||
}
|
||||
|
||||
return command;
|
||||
}
|
||||
|
||||
execute(callback) {
|
||||
const options = this.options;
|
||||
|
||||
// Error out if digestPassword set
|
||||
if (options.digestPassword != null) {
|
||||
return callback(
|
||||
toError(
|
||||
"The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option."
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Attempt to execute auth command
|
||||
super.execute((err, r) => {
|
||||
if (!err) {
|
||||
return handleCallback(callback, err, r);
|
||||
}
|
||||
|
||||
return handleCallback(callback, err, null);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
defineAspects(AddUserOperation, Aspect.WRITE_OPERATION);
|
||||
|
||||
module.exports = AddUserOperation;
|
||||
62
node_modules/mongodb/lib/operations/admin_ops.js
generated
vendored
Normal file
62
node_modules/mongodb/lib/operations/admin_ops.js
generated
vendored
Normal file
@@ -0,0 +1,62 @@
|
||||
'use strict';
|
||||
|
||||
const executeCommand = require('./db_ops').executeCommand;
|
||||
const executeDbAdminCommand = require('./db_ops').executeDbAdminCommand;
|
||||
|
||||
/**
|
||||
* Get ReplicaSet status
|
||||
*
|
||||
* @param {Admin} a collection instance.
|
||||
* @param {Object} [options] Optional settings. See Admin.prototype.replSetGetStatus for a list of options.
|
||||
* @param {Admin~resultCallback} [callback] The command result callback.
|
||||
*/
|
||||
function replSetGetStatus(admin, options, callback) {
|
||||
executeDbAdminCommand(admin.s.db, { replSetGetStatus: 1 }, options, callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve this db's server status.
|
||||
*
|
||||
* @param {Admin} a collection instance.
|
||||
* @param {Object} [options] Optional settings. See Admin.prototype.serverStatus for a list of options.
|
||||
* @param {Admin~resultCallback} [callback] The command result callback
|
||||
*/
|
||||
function serverStatus(admin, options, callback) {
|
||||
executeDbAdminCommand(admin.s.db, { serverStatus: 1 }, options, callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an existing collection
|
||||
*
|
||||
* @param {Admin} a collection instance.
|
||||
* @param {string} collectionName The name of the collection to validate.
|
||||
* @param {Object} [options] Optional settings. See Admin.prototype.validateCollection for a list of options.
|
||||
* @param {Admin~resultCallback} [callback] The command result callback.
|
||||
*/
|
||||
function validateCollection(admin, collectionName, options, callback) {
|
||||
const command = { validate: collectionName };
|
||||
const keys = Object.keys(options);
|
||||
|
||||
// Decorate command with extra options
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
if (options.hasOwnProperty(keys[i]) && keys[i] !== 'session') {
|
||||
command[keys[i]] = options[keys[i]];
|
||||
}
|
||||
}
|
||||
|
||||
executeCommand(admin.s.db, command, options, (err, doc) => {
|
||||
if (err != null) return callback(err, null);
|
||||
|
||||
if (doc.ok === 0) return callback(new Error('Error with validate command'), null);
|
||||
if (doc.result != null && doc.result.constructor !== String)
|
||||
return callback(new Error('Error with validation data'), null);
|
||||
if (doc.result != null && doc.result.match(/exception|corrupt/) != null)
|
||||
return callback(new Error('Error: invalid collection ' + collectionName), null);
|
||||
if (doc.valid != null && !doc.valid)
|
||||
return callback(new Error('Error: invalid collection ' + collectionName), null);
|
||||
|
||||
return callback(null, doc);
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { replSetGetStatus, serverStatus, validateCollection };
|
||||
106
node_modules/mongodb/lib/operations/aggregate.js
generated
vendored
Normal file
106
node_modules/mongodb/lib/operations/aggregate.js
generated
vendored
Normal file
@@ -0,0 +1,106 @@
|
||||
'use strict';
|
||||
|
||||
const CommandOperationV2 = require('./command_v2');
|
||||
const MongoError = require('../core').MongoError;
|
||||
const maxWireVersion = require('../core/utils').maxWireVersion;
|
||||
const ReadPreference = require('../core').ReadPreference;
|
||||
const Aspect = require('./operation').Aspect;
|
||||
const defineAspects = require('./operation').defineAspects;
|
||||
|
||||
const DB_AGGREGATE_COLLECTION = 1;
|
||||
const MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT = 8;
|
||||
|
||||
class AggregateOperation extends CommandOperationV2 {
|
||||
constructor(parent, pipeline, options) {
|
||||
super(parent, options, { fullResponse: true });
|
||||
|
||||
this.target =
|
||||
parent.s.namespace && parent.s.namespace.collection
|
||||
? parent.s.namespace.collection
|
||||
: DB_AGGREGATE_COLLECTION;
|
||||
|
||||
this.pipeline = pipeline;
|
||||
|
||||
// determine if we have a write stage, override read preference if so
|
||||
this.hasWriteStage = false;
|
||||
if (typeof options.out === 'string') {
|
||||
this.pipeline = this.pipeline.concat({ $out: options.out });
|
||||
this.hasWriteStage = true;
|
||||
} else if (pipeline.length > 0) {
|
||||
const finalStage = pipeline[pipeline.length - 1];
|
||||
if (finalStage.$out || finalStage.$merge) {
|
||||
this.hasWriteStage = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.hasWriteStage) {
|
||||
this.readPreference = ReadPreference.primary;
|
||||
}
|
||||
|
||||
if (options.explain && (this.readConcern || this.writeConcern)) {
|
||||
throw new MongoError(
|
||||
'"explain" cannot be used on an aggregate call with readConcern/writeConcern'
|
||||
);
|
||||
}
|
||||
|
||||
if (options.cursor != null && typeof options.cursor !== 'object') {
|
||||
throw new MongoError('cursor options must be an object');
|
||||
}
|
||||
}
|
||||
|
||||
get canRetryRead() {
|
||||
return !this.hasWriteStage;
|
||||
}
|
||||
|
||||
addToPipeline(stage) {
|
||||
this.pipeline.push(stage);
|
||||
}
|
||||
|
||||
execute(server, callback) {
|
||||
const options = this.options;
|
||||
const serverWireVersion = maxWireVersion(server);
|
||||
const command = { aggregate: this.target, pipeline: this.pipeline };
|
||||
|
||||
if (this.hasWriteStage && serverWireVersion < MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT) {
|
||||
this.readConcern = null;
|
||||
}
|
||||
|
||||
if (serverWireVersion >= 5) {
|
||||
if (this.hasWriteStage && this.writeConcern) {
|
||||
Object.assign(command, { writeConcern: this.writeConcern });
|
||||
}
|
||||
}
|
||||
|
||||
if (options.bypassDocumentValidation === true) {
|
||||
command.bypassDocumentValidation = options.bypassDocumentValidation;
|
||||
}
|
||||
|
||||
if (typeof options.allowDiskUse === 'boolean') {
|
||||
command.allowDiskUse = options.allowDiskUse;
|
||||
}
|
||||
|
||||
if (options.hint) {
|
||||
command.hint = options.hint;
|
||||
}
|
||||
|
||||
if (options.explain) {
|
||||
options.full = false;
|
||||
command.explain = options.explain;
|
||||
}
|
||||
|
||||
command.cursor = options.cursor || {};
|
||||
if (options.batchSize && !this.hasWriteStage) {
|
||||
command.cursor.batchSize = options.batchSize;
|
||||
}
|
||||
|
||||
super.executeCommand(server, command, callback);
|
||||
}
|
||||
}
|
||||
|
||||
defineAspects(AggregateOperation, [
|
||||
Aspect.READ_OPERATION,
|
||||
Aspect.RETRYABLE,
|
||||
Aspect.EXECUTE_WITH_SELECTION
|
||||
]);
|
||||
|
||||
module.exports = AggregateOperation;
|
||||
104
node_modules/mongodb/lib/operations/bulk_write.js
generated
vendored
Normal file
104
node_modules/mongodb/lib/operations/bulk_write.js
generated
vendored
Normal file
@@ -0,0 +1,104 @@
|
||||
'use strict';
|
||||
|
||||
const applyRetryableWrites = require('../utils').applyRetryableWrites;
|
||||
const applyWriteConcern = require('../utils').applyWriteConcern;
|
||||
const MongoError = require('../core').MongoError;
|
||||
const OperationBase = require('./operation').OperationBase;
|
||||
|
||||
class BulkWriteOperation extends OperationBase {
|
||||
constructor(collection, operations, options) {
|
||||
super(options);
|
||||
|
||||
this.collection = collection;
|
||||
this.operations = operations;
|
||||
}
|
||||
|
||||
execute(callback) {
|
||||
const coll = this.collection;
|
||||
const operations = this.operations;
|
||||
let options = this.options;
|
||||
|
||||
// Add ignoreUndfined
|
||||
if (coll.s.options.ignoreUndefined) {
|
||||
options = Object.assign({}, options);
|
||||
options.ignoreUndefined = coll.s.options.ignoreUndefined;
|
||||
}
|
||||
|
||||
// Create the bulk operation
|
||||
const bulk =
|
||||
options.ordered === true || options.ordered == null
|
||||
? coll.initializeOrderedBulkOp(options)
|
||||
: coll.initializeUnorderedBulkOp(options);
|
||||
|
||||
// Do we have a collation
|
||||
let collation = false;
|
||||
|
||||
// for each op go through and add to the bulk
|
||||
try {
|
||||
for (let i = 0; i < operations.length; i++) {
|
||||
// Get the operation type
|
||||
const key = Object.keys(operations[i])[0];
|
||||
// Check if we have a collation
|
||||
if (operations[i][key].collation) {
|
||||
collation = true;
|
||||
}
|
||||
|
||||
// Pass to the raw bulk
|
||||
bulk.raw(operations[i]);
|
||||
}
|
||||
} catch (err) {
|
||||
return callback(err, null);
|
||||
}
|
||||
|
||||
// Final options for retryable writes and write concern
|
||||
let finalOptions = Object.assign({}, options);
|
||||
finalOptions = applyRetryableWrites(finalOptions, coll.s.db);
|
||||
finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options);
|
||||
|
||||
const writeCon = finalOptions.writeConcern ? finalOptions.writeConcern : {};
|
||||
const capabilities = coll.s.topology.capabilities();
|
||||
|
||||
// Did the user pass in a collation, check if our write server supports it
|
||||
if (collation && capabilities && !capabilities.commandsTakeCollation) {
|
||||
return callback(new MongoError('server/primary/mongos does not support collation'));
|
||||
}
|
||||
|
||||
// Execute the bulk
|
||||
bulk.execute(writeCon, finalOptions, (err, r) => {
|
||||
// We have connection level error
|
||||
if (!r && err) {
|
||||
return callback(err, null);
|
||||
}
|
||||
|
||||
r.insertedCount = r.nInserted;
|
||||
r.matchedCount = r.nMatched;
|
||||
r.modifiedCount = r.nModified || 0;
|
||||
r.deletedCount = r.nRemoved;
|
||||
r.upsertedCount = r.getUpsertedIds().length;
|
||||
r.upsertedIds = {};
|
||||
r.insertedIds = {};
|
||||
|
||||
// Update the n
|
||||
r.n = r.insertedCount;
|
||||
|
||||
// Inserted documents
|
||||
const inserted = r.getInsertedIds();
|
||||
// Map inserted ids
|
||||
for (let i = 0; i < inserted.length; i++) {
|
||||
r.insertedIds[inserted[i].index] = inserted[i]._id;
|
||||
}
|
||||
|
||||
// Upserted documents
|
||||
const upserted = r.getUpsertedIds();
|
||||
// Map upserted ids
|
||||
for (let i = 0; i < upserted.length; i++) {
|
||||
r.upsertedIds[upserted[i].index] = upserted[i]._id;
|
||||
}
|
||||
|
||||
// Return the results
|
||||
callback(null, r);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = BulkWriteOperation;
|
||||
353
node_modules/mongodb/lib/operations/collection_ops.js
generated
vendored
Normal file
353
node_modules/mongodb/lib/operations/collection_ops.js
generated
vendored
Normal file
@@ -0,0 +1,353 @@
|
||||
'use strict';
|
||||
|
||||
const applyWriteConcern = require('../utils').applyWriteConcern;
|
||||
const Code = require('../core').BSON.Code;
|
||||
const createIndexDb = require('./db_ops').createIndex;
|
||||
const decorateWithCollation = require('../utils').decorateWithCollation;
|
||||
const decorateWithReadConcern = require('../utils').decorateWithReadConcern;
|
||||
const ensureIndexDb = require('./db_ops').ensureIndex;
|
||||
const evaluate = require('./db_ops').evaluate;
|
||||
const executeCommand = require('./db_ops').executeCommand;
|
||||
const handleCallback = require('../utils').handleCallback;
|
||||
const indexInformationDb = require('./db_ops').indexInformation;
|
||||
const Long = require('../core').BSON.Long;
|
||||
const MongoError = require('../core').MongoError;
|
||||
const ReadPreference = require('../core').ReadPreference;
|
||||
const insertDocuments = require('./common_functions').insertDocuments;
|
||||
const updateDocuments = require('./common_functions').updateDocuments;
|
||||
|
||||
/**
|
||||
* Group function helper
|
||||
* @ignore
|
||||
*/
|
||||
// var groupFunction = function () {
|
||||
// var c = db[ns].find(condition);
|
||||
// var map = new Map();
|
||||
// var reduce_function = reduce;
|
||||
//
|
||||
// while (c.hasNext()) {
|
||||
// var obj = c.next();
|
||||
// var key = {};
|
||||
//
|
||||
// for (var i = 0, len = keys.length; i < len; ++i) {
|
||||
// var k = keys[i];
|
||||
// key[k] = obj[k];
|
||||
// }
|
||||
//
|
||||
// var aggObj = map.get(key);
|
||||
//
|
||||
// if (aggObj == null) {
|
||||
// var newObj = Object.extend({}, key);
|
||||
// aggObj = Object.extend(newObj, initial);
|
||||
// map.put(key, aggObj);
|
||||
// }
|
||||
//
|
||||
// reduce_function(obj, aggObj);
|
||||
// }
|
||||
//
|
||||
// return { "result": map.values() };
|
||||
// }.toString();
|
||||
const groupFunction =
|
||||
'function () {\nvar c = db[ns].find(condition);\nvar map = new Map();\nvar reduce_function = reduce;\n\nwhile (c.hasNext()) {\nvar obj = c.next();\nvar key = {};\n\nfor (var i = 0, len = keys.length; i < len; ++i) {\nvar k = keys[i];\nkey[k] = obj[k];\n}\n\nvar aggObj = map.get(key);\n\nif (aggObj == null) {\nvar newObj = Object.extend({}, key);\naggObj = Object.extend(newObj, initial);\nmap.put(key, aggObj);\n}\n\nreduce_function(obj, aggObj);\n}\n\nreturn { "result": map.values() };\n}';
|
||||
|
||||
/**
|
||||
* Create an index on the db and collection.
|
||||
*
|
||||
* @method
|
||||
* @param {Collection} a Collection instance.
|
||||
* @param {(string|object)} fieldOrSpec Defines the index.
|
||||
* @param {object} [options] Optional settings. See Collection.prototype.createIndex for a list of options.
|
||||
* @param {Collection~resultCallback} [callback] The command result callback
|
||||
*/
|
||||
function createIndex(coll, fieldOrSpec, options, callback) {
|
||||
createIndexDb(coll.s.db, coll.collectionName, fieldOrSpec, options, callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create multiple indexes in the collection. This method is only supported for
|
||||
* MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported
|
||||
* error. Index specifications are defined at http://docs.mongodb.org/manual/reference/command/createIndexes/.
|
||||
*
|
||||
* @method
|
||||
* @param {Collection} a Collection instance.
|
||||
* @param {array} indexSpecs An array of index specifications to be created
|
||||
* @param {Object} [options] Optional settings. See Collection.prototype.createIndexes for a list of options.
|
||||
* @param {Collection~resultCallback} [callback] The command result callback
|
||||
*/
|
||||
function createIndexes(coll, indexSpecs, options, callback) {
|
||||
const capabilities = coll.s.topology.capabilities();
|
||||
|
||||
// Ensure we generate the correct name if the parameter is not set
|
||||
for (let i = 0; i < indexSpecs.length; i++) {
|
||||
if (indexSpecs[i].name == null) {
|
||||
const keys = [];
|
||||
|
||||
// Did the user pass in a collation, check if our write server supports it
|
||||
if (indexSpecs[i].collation && capabilities && !capabilities.commandsTakeCollation) {
|
||||
return callback(new MongoError('server/primary/mongos does not support collation'));
|
||||
}
|
||||
|
||||
for (let name in indexSpecs[i].key) {
|
||||
keys.push(`${name}_${indexSpecs[i].key[name]}`);
|
||||
}
|
||||
|
||||
// Set the name
|
||||
indexSpecs[i].name = keys.join('_');
|
||||
}
|
||||
}
|
||||
|
||||
options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY });
|
||||
|
||||
// Execute the index
|
||||
executeCommand(
|
||||
coll.s.db,
|
||||
{
|
||||
createIndexes: coll.collectionName,
|
||||
indexes: indexSpecs
|
||||
},
|
||||
options,
|
||||
callback
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure that an index exists. If the index does not exist, this function creates it.
|
||||
*
|
||||
* @method
|
||||
* @param {Collection} a Collection instance.
|
||||
* @param {(string|object)} fieldOrSpec Defines the index.
|
||||
* @param {object} [options] Optional settings. See Collection.prototype.ensureIndex for a list of options.
|
||||
* @param {Collection~resultCallback} [callback] The command result callback
|
||||
*/
|
||||
function ensureIndex(coll, fieldOrSpec, options, callback) {
|
||||
ensureIndexDb(coll.s.db, coll.collectionName, fieldOrSpec, options, callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Run a group command across a collection.
|
||||
*
|
||||
* @method
|
||||
* @param {Collection} a Collection instance.
|
||||
* @param {(object|array|function|code)} keys An object, array or function expressing the keys to group by.
|
||||
* @param {object} condition An optional condition that must be true for a row to be considered.
|
||||
* @param {object} initial Initial value of the aggregation counter object.
|
||||
* @param {(function|Code)} reduce The reduce function aggregates (reduces) the objects iterated
|
||||
* @param {(function|Code)} finalize An optional function to be run on each item in the result set just before the item is returned.
|
||||
* @param {boolean} command Specify if you wish to run using the internal group command or using eval, default is true.
|
||||
* @param {object} [options] Optional settings. See Collection.prototype.group for a list of options.
|
||||
* @param {Collection~resultCallback} [callback] The command result callback
|
||||
* @deprecated MongoDB 3.6 or higher will no longer support the group command. We recommend rewriting using the aggregation framework.
|
||||
*/
|
||||
function group(coll, keys, condition, initial, reduce, finalize, command, options, callback) {
|
||||
// Execute using the command
|
||||
if (command) {
|
||||
const reduceFunction = reduce && reduce._bsontype === 'Code' ? reduce : new Code(reduce);
|
||||
|
||||
const selector = {
|
||||
group: {
|
||||
ns: coll.collectionName,
|
||||
$reduce: reduceFunction,
|
||||
cond: condition,
|
||||
initial: initial,
|
||||
out: 'inline'
|
||||
}
|
||||
};
|
||||
|
||||
// if finalize is defined
|
||||
if (finalize != null) selector.group['finalize'] = finalize;
|
||||
// Set up group selector
|
||||
if ('function' === typeof keys || (keys && keys._bsontype === 'Code')) {
|
||||
selector.group.$keyf = keys && keys._bsontype === 'Code' ? keys : new Code(keys);
|
||||
} else {
|
||||
const hash = {};
|
||||
keys.forEach(key => {
|
||||
hash[key] = 1;
|
||||
});
|
||||
selector.group.key = hash;
|
||||
}
|
||||
|
||||
options = Object.assign({}, options);
|
||||
// Ensure we have the right read preference inheritance
|
||||
options.readPreference = ReadPreference.resolve(coll, options);
|
||||
|
||||
// Do we have a readConcern specified
|
||||
decorateWithReadConcern(selector, coll, options);
|
||||
|
||||
// Have we specified collation
|
||||
try {
|
||||
decorateWithCollation(selector, coll, options);
|
||||
} catch (err) {
|
||||
return callback(err, null);
|
||||
}
|
||||
|
||||
// Execute command
|
||||
executeCommand(coll.s.db, selector, options, (err, result) => {
|
||||
if (err) return handleCallback(callback, err, null);
|
||||
handleCallback(callback, null, result.retval);
|
||||
});
|
||||
} else {
|
||||
// Create execution scope
|
||||
const scope = reduce != null && reduce._bsontype === 'Code' ? reduce.scope : {};
|
||||
|
||||
scope.ns = coll.collectionName;
|
||||
scope.keys = keys;
|
||||
scope.condition = condition;
|
||||
scope.initial = initial;
|
||||
|
||||
// Pass in the function text to execute within mongodb.
|
||||
const groupfn = groupFunction.replace(/ reduce;/, reduce.toString() + ';');
|
||||
|
||||
evaluate(coll.s.db, new Code(groupfn, scope), null, options, (err, results) => {
|
||||
if (err) return handleCallback(callback, err, null);
|
||||
handleCallback(callback, null, results.result || results);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve all the indexes on the collection.
|
||||
*
|
||||
* @method
|
||||
* @param {Collection} a Collection instance.
|
||||
* @param {Object} [options] Optional settings. See Collection.prototype.indexes for a list of options.
|
||||
* @param {Collection~resultCallback} [callback] The command result callback
|
||||
*/
|
||||
function indexes(coll, options, callback) {
|
||||
options = Object.assign({}, { full: true }, options);
|
||||
indexInformationDb(coll.s.db, coll.collectionName, options, callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if one or more indexes exist on the collection. This fails on the first index that doesn't exist.
|
||||
*
|
||||
* @method
|
||||
* @param {Collection} a Collection instance.
|
||||
* @param {(string|array)} indexes One or more index names to check.
|
||||
* @param {Object} [options] Optional settings. See Collection.prototype.indexExists for a list of options.
|
||||
* @param {Collection~resultCallback} [callback] The command result callback
|
||||
*/
|
||||
function indexExists(coll, indexes, options, callback) {
|
||||
indexInformation(coll, options, (err, indexInformation) => {
|
||||
// If we have an error return
|
||||
if (err != null) return handleCallback(callback, err, null);
|
||||
// Let's check for the index names
|
||||
if (!Array.isArray(indexes))
|
||||
return handleCallback(callback, null, indexInformation[indexes] != null);
|
||||
// Check in list of indexes
|
||||
for (let i = 0; i < indexes.length; i++) {
|
||||
if (indexInformation[indexes[i]] == null) {
|
||||
return handleCallback(callback, null, false);
|
||||
}
|
||||
}
|
||||
|
||||
// All keys found return true
|
||||
return handleCallback(callback, null, true);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve this collection's index info.
|
||||
*
|
||||
* @method
|
||||
* @param {Collection} a Collection instance.
|
||||
* @param {object} [options] Optional settings. See Collection.prototype.indexInformation for a list of options.
|
||||
* @param {Collection~resultCallback} [callback] The command result callback
|
||||
*/
|
||||
function indexInformation(coll, options, callback) {
|
||||
indexInformationDb(coll.s.db, coll.collectionName, options, callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return N parallel cursors for a collection to allow parallel reading of the entire collection. There are
|
||||
* no ordering guarantees for returned results.
|
||||
*
|
||||
* @method
|
||||
* @param {Collection} a Collection instance.
|
||||
* @param {object} [options] Optional settings. See Collection.prototype.parallelCollectionScan for a list of options.
|
||||
* @param {Collection~parallelCollectionScanCallback} [callback] The command result callback
|
||||
*/
|
||||
function parallelCollectionScan(coll, options, callback) {
|
||||
// Create command object
|
||||
const commandObject = {
|
||||
parallelCollectionScan: coll.collectionName,
|
||||
numCursors: options.numCursors
|
||||
};
|
||||
|
||||
// Do we have a readConcern specified
|
||||
decorateWithReadConcern(commandObject, coll, options);
|
||||
|
||||
// Store the raw value
|
||||
const raw = options.raw;
|
||||
delete options['raw'];
|
||||
|
||||
// Execute the command
|
||||
executeCommand(coll.s.db, commandObject, options, (err, result) => {
|
||||
if (err) return handleCallback(callback, err, null);
|
||||
if (result == null)
|
||||
return handleCallback(
|
||||
callback,
|
||||
new Error('no result returned for parallelCollectionScan'),
|
||||
null
|
||||
);
|
||||
|
||||
options = Object.assign({ explicitlyIgnoreSession: true }, options);
|
||||
|
||||
const cursors = [];
|
||||
// Add the raw back to the option
|
||||
if (raw) options.raw = raw;
|
||||
// Create command cursors for each item
|
||||
for (let i = 0; i < result.cursors.length; i++) {
|
||||
const rawId = result.cursors[i].cursor.id;
|
||||
// Convert cursorId to Long if needed
|
||||
const cursorId = typeof rawId === 'number' ? Long.fromNumber(rawId) : rawId;
|
||||
// Add a command cursor
|
||||
cursors.push(coll.s.topology.cursor(coll.namespace, cursorId, options));
|
||||
}
|
||||
|
||||
handleCallback(callback, null, cursors);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Save a document.
|
||||
*
|
||||
* @method
|
||||
* @param {Collection} a Collection instance.
|
||||
* @param {object} doc Document to save
|
||||
* @param {object} [options] Optional settings. See Collection.prototype.save for a list of options.
|
||||
* @param {Collection~writeOpCallback} [callback] The command result callback
|
||||
* @deprecated use insertOne, insertMany, updateOne or updateMany
|
||||
*/
|
||||
function save(coll, doc, options, callback) {
|
||||
// Get the write concern options
|
||||
const finalOptions = applyWriteConcern(
|
||||
Object.assign({}, options),
|
||||
{ db: coll.s.db, collection: coll },
|
||||
options
|
||||
);
|
||||
// Establish if we need to perform an insert or update
|
||||
if (doc._id != null) {
|
||||
finalOptions.upsert = true;
|
||||
return updateDocuments(coll, { _id: doc._id }, doc, finalOptions, callback);
|
||||
}
|
||||
|
||||
// Insert the document
|
||||
insertDocuments(coll, [doc], finalOptions, (err, result) => {
|
||||
if (callback == null) return;
|
||||
if (doc == null) return handleCallback(callback, null, null);
|
||||
if (err) return handleCallback(callback, err, null);
|
||||
handleCallback(callback, null, result);
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
createIndex,
|
||||
createIndexes,
|
||||
ensureIndex,
|
||||
group,
|
||||
indexes,
|
||||
indexExists,
|
||||
indexInformation,
|
||||
parallelCollectionScan,
|
||||
save
|
||||
};
|
||||
55
node_modules/mongodb/lib/operations/collections.js
generated
vendored
Normal file
55
node_modules/mongodb/lib/operations/collections.js
generated
vendored
Normal file
@@ -0,0 +1,55 @@
|
||||
'use strict';
|
||||
|
||||
const OperationBase = require('./operation').OperationBase;
|
||||
const handleCallback = require('../utils').handleCallback;
|
||||
|
||||
let collection;
|
||||
function loadCollection() {
|
||||
if (!collection) {
|
||||
collection = require('../collection');
|
||||
}
|
||||
return collection;
|
||||
}
|
||||
|
||||
class CollectionsOperation extends OperationBase {
|
||||
constructor(db, options) {
|
||||
super(options);
|
||||
|
||||
this.db = db;
|
||||
}
|
||||
|
||||
execute(callback) {
|
||||
const db = this.db;
|
||||
let options = this.options;
|
||||
|
||||
let Collection = loadCollection();
|
||||
|
||||
options = Object.assign({}, options, { nameOnly: true });
|
||||
// Let's get the collection names
|
||||
db.listCollections({}, options).toArray((err, documents) => {
|
||||
if (err != null) return handleCallback(callback, err, null);
|
||||
// Filter collections removing any illegal ones
|
||||
documents = documents.filter(doc => {
|
||||
return doc.name.indexOf('$') === -1;
|
||||
});
|
||||
|
||||
// Return the collection objects
|
||||
handleCallback(
|
||||
callback,
|
||||
null,
|
||||
documents.map(d => {
|
||||
return new Collection(
|
||||
db,
|
||||
db.s.topology,
|
||||
db.databaseName,
|
||||
d.name,
|
||||
db.s.pkFactory,
|
||||
db.s.options
|
||||
);
|
||||
})
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = CollectionsOperation;
|
||||
119
node_modules/mongodb/lib/operations/command.js
generated
vendored
Normal file
119
node_modules/mongodb/lib/operations/command.js
generated
vendored
Normal file
@@ -0,0 +1,119 @@
|
||||
'use strict';
|
||||
|
||||
const Aspect = require('./operation').Aspect;
|
||||
const OperationBase = require('./operation').OperationBase;
|
||||
const applyWriteConcern = require('../utils').applyWriteConcern;
|
||||
const debugOptions = require('../utils').debugOptions;
|
||||
const handleCallback = require('../utils').handleCallback;
|
||||
const MongoError = require('../core').MongoError;
|
||||
const ReadPreference = require('../core').ReadPreference;
|
||||
const MongoDBNamespace = require('../utils').MongoDBNamespace;
|
||||
|
||||
const debugFields = [
|
||||
'authSource',
|
||||
'w',
|
||||
'wtimeout',
|
||||
'j',
|
||||
'native_parser',
|
||||
'forceServerObjectId',
|
||||
'serializeFunctions',
|
||||
'raw',
|
||||
'promoteLongs',
|
||||
'promoteValues',
|
||||
'promoteBuffers',
|
||||
'bufferMaxEntries',
|
||||
'numberOfRetries',
|
||||
'retryMiliSeconds',
|
||||
'readPreference',
|
||||
'pkFactory',
|
||||
'parentDb',
|
||||
'promiseLibrary',
|
||||
'noListener'
|
||||
];
|
||||
|
||||
class CommandOperation extends OperationBase {
|
||||
constructor(db, options, collection, command) {
|
||||
super(options);
|
||||
|
||||
if (!this.hasAspect(Aspect.WRITE_OPERATION)) {
|
||||
if (collection != null) {
|
||||
this.options.readPreference = ReadPreference.resolve(collection, options);
|
||||
} else {
|
||||
this.options.readPreference = ReadPreference.resolve(db, options);
|
||||
}
|
||||
} else {
|
||||
if (collection != null) {
|
||||
applyWriteConcern(this.options, { db, coll: collection }, this.options);
|
||||
} else {
|
||||
applyWriteConcern(this.options, { db }, this.options);
|
||||
}
|
||||
this.options.readPreference = ReadPreference.primary;
|
||||
}
|
||||
|
||||
this.db = db;
|
||||
|
||||
if (command != null) {
|
||||
this.command = command;
|
||||
}
|
||||
|
||||
if (collection != null) {
|
||||
this.collection = collection;
|
||||
}
|
||||
}
|
||||
|
||||
_buildCommand() {
|
||||
if (this.command != null) {
|
||||
return this.command;
|
||||
}
|
||||
}
|
||||
|
||||
execute(callback) {
|
||||
const db = this.db;
|
||||
const options = Object.assign({}, this.options);
|
||||
|
||||
// Did the user destroy the topology
|
||||
if (db.serverConfig && db.serverConfig.isDestroyed()) {
|
||||
return callback(new MongoError('topology was destroyed'));
|
||||
}
|
||||
|
||||
let command;
|
||||
try {
|
||||
command = this._buildCommand();
|
||||
} catch (e) {
|
||||
return callback(e);
|
||||
}
|
||||
|
||||
// Get the db name we are executing against
|
||||
const dbName = options.dbName || options.authdb || db.databaseName;
|
||||
|
||||
// Convert the readPreference if its not a write
|
||||
if (this.hasAspect(Aspect.WRITE_OPERATION)) {
|
||||
if (options.writeConcern && (!options.session || !options.session.inTransaction())) {
|
||||
command.writeConcern = options.writeConcern;
|
||||
}
|
||||
}
|
||||
|
||||
// Debug information
|
||||
if (db.s.logger.isDebug()) {
|
||||
db.s.logger.debug(
|
||||
`executing command ${JSON.stringify(
|
||||
command
|
||||
)} against ${dbName}.$cmd with options [${JSON.stringify(
|
||||
debugOptions(debugFields, options)
|
||||
)}]`
|
||||
);
|
||||
}
|
||||
|
||||
const namespace =
|
||||
this.namespace != null ? this.namespace : new MongoDBNamespace(dbName, '$cmd');
|
||||
|
||||
// Execute command
|
||||
db.s.topology.command(namespace, command, options, (err, result) => {
|
||||
if (err) return handleCallback(callback, err);
|
||||
if (options.full) return handleCallback(callback, null, result);
|
||||
handleCallback(callback, null, result.result);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = CommandOperation;
|
||||
108
node_modules/mongodb/lib/operations/command_v2.js
generated
vendored
Normal file
108
node_modules/mongodb/lib/operations/command_v2.js
generated
vendored
Normal file
@@ -0,0 +1,108 @@
|
||||
'use strict';
|
||||
|
||||
const Aspect = require('./operation').Aspect;
|
||||
const OperationBase = require('./operation').OperationBase;
|
||||
const ReadPreference = require('../core').ReadPreference;
|
||||
const ReadConcern = require('../read_concern');
|
||||
const WriteConcern = require('../write_concern');
|
||||
const maxWireVersion = require('../core/utils').maxWireVersion;
|
||||
const commandSupportsReadConcern = require('../core/sessions').commandSupportsReadConcern;
|
||||
const MongoError = require('../core/error').MongoError;
|
||||
|
||||
const SUPPORTS_WRITE_CONCERN_AND_COLLATION = 5;
|
||||
|
||||
class CommandOperationV2 extends OperationBase {
|
||||
constructor(parent, options, operationOptions) {
|
||||
super(options);
|
||||
|
||||
this.ns = parent.s.namespace.withCollection('$cmd');
|
||||
const propertyProvider = this.hasAspect(Aspect.NO_INHERIT_OPTIONS) ? undefined : parent;
|
||||
this.readPreference = ReadPreference.resolve(propertyProvider, this.options);
|
||||
this.readConcern = resolveReadConcern(propertyProvider, this.options);
|
||||
this.writeConcern = resolveWriteConcern(propertyProvider, this.options);
|
||||
this.explain = false;
|
||||
|
||||
if (operationOptions && typeof operationOptions.fullResponse === 'boolean') {
|
||||
this.fullResponse = true;
|
||||
}
|
||||
|
||||
// TODO: A lot of our code depends on having the read preference in the options. This should
|
||||
// go away, but also requires massive test rewrites.
|
||||
this.options.readPreference = this.readPreference;
|
||||
|
||||
// TODO(NODE-2056): make logger another "inheritable" property
|
||||
if (parent.s.logger) {
|
||||
this.logger = parent.s.logger;
|
||||
} else if (parent.s.db && parent.s.db.logger) {
|
||||
this.logger = parent.s.db.logger;
|
||||
}
|
||||
}
|
||||
|
||||
executeCommand(server, cmd, callback) {
|
||||
// TODO: consider making this a non-enumerable property
|
||||
this.server = server;
|
||||
|
||||
const options = this.options;
|
||||
const serverWireVersion = maxWireVersion(server);
|
||||
const inTransaction = this.session && this.session.inTransaction();
|
||||
|
||||
if (this.readConcern && commandSupportsReadConcern(cmd) && !inTransaction) {
|
||||
Object.assign(cmd, { readConcern: this.readConcern });
|
||||
}
|
||||
|
||||
if (options.collation && serverWireVersion < SUPPORTS_WRITE_CONCERN_AND_COLLATION) {
|
||||
callback(
|
||||
new MongoError(
|
||||
`Server ${server.name}, which reports wire version ${serverWireVersion}, does not support collation`
|
||||
)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (serverWireVersion >= SUPPORTS_WRITE_CONCERN_AND_COLLATION) {
|
||||
if (this.writeConcern && this.hasAspect(Aspect.WRITE_OPERATION)) {
|
||||
Object.assign(cmd, { writeConcern: this.writeConcern });
|
||||
}
|
||||
|
||||
if (options.collation && typeof options.collation === 'object') {
|
||||
Object.assign(cmd, { collation: options.collation });
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof options.maxTimeMS === 'number') {
|
||||
cmd.maxTimeMS = options.maxTimeMS;
|
||||
}
|
||||
|
||||
if (typeof options.comment === 'string') {
|
||||
cmd.comment = options.comment;
|
||||
}
|
||||
|
||||
if (this.logger && this.logger.isDebug()) {
|
||||
this.logger.debug(`executing command ${JSON.stringify(cmd)} against ${this.ns}`);
|
||||
}
|
||||
|
||||
server.command(this.ns.toString(), cmd, this.options, (err, result) => {
|
||||
if (err) {
|
||||
callback(err, null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.fullResponse) {
|
||||
callback(null, result);
|
||||
return;
|
||||
}
|
||||
|
||||
callback(null, result.result);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function resolveWriteConcern(parent, options) {
|
||||
return WriteConcern.fromOptions(options) || (parent && parent.writeConcern);
|
||||
}
|
||||
|
||||
function resolveReadConcern(parent, options) {
|
||||
return ReadConcern.fromOptions(options) || (parent && parent.readConcern);
|
||||
}
|
||||
|
||||
module.exports = CommandOperationV2;
|
||||
412
node_modules/mongodb/lib/operations/common_functions.js
generated
vendored
Normal file
412
node_modules/mongodb/lib/operations/common_functions.js
generated
vendored
Normal file
@@ -0,0 +1,412 @@
|
||||
'use strict';
|
||||
|
||||
const applyRetryableWrites = require('../utils').applyRetryableWrites;
|
||||
const applyWriteConcern = require('../utils').applyWriteConcern;
|
||||
const decorateWithCollation = require('../utils').decorateWithCollation;
|
||||
const decorateWithReadConcern = require('../utils').decorateWithReadConcern;
|
||||
const executeCommand = require('./db_ops').executeCommand;
|
||||
const formattedOrderClause = require('../utils').formattedOrderClause;
|
||||
const handleCallback = require('../utils').handleCallback;
|
||||
const MongoError = require('../core').MongoError;
|
||||
const ReadPreference = require('../core').ReadPreference;
|
||||
const toError = require('../utils').toError;
|
||||
const CursorState = require('../core/cursor').CursorState;
|
||||
|
||||
/**
|
||||
* Build the count command.
|
||||
*
|
||||
* @method
|
||||
* @param {collectionOrCursor} an instance of a collection or cursor
|
||||
* @param {object} query The query for the count.
|
||||
* @param {object} [options] Optional settings. See Collection.prototype.count and Cursor.prototype.count for a list of options.
|
||||
*/
|
||||
function buildCountCommand(collectionOrCursor, query, options) {
|
||||
const skip = options.skip;
|
||||
const limit = options.limit;
|
||||
let hint = options.hint;
|
||||
const maxTimeMS = options.maxTimeMS;
|
||||
query = query || {};
|
||||
|
||||
// Final query
|
||||
const cmd = {
|
||||
count: options.collectionName,
|
||||
query: query
|
||||
};
|
||||
|
||||
if (collectionOrCursor.s.numberOfRetries) {
|
||||
// collectionOrCursor is a cursor
|
||||
if (collectionOrCursor.options.hint) {
|
||||
hint = collectionOrCursor.options.hint;
|
||||
} else if (collectionOrCursor.cmd.hint) {
|
||||
hint = collectionOrCursor.cmd.hint;
|
||||
}
|
||||
decorateWithCollation(cmd, collectionOrCursor, collectionOrCursor.cmd);
|
||||
} else {
|
||||
decorateWithCollation(cmd, collectionOrCursor, options);
|
||||
}
|
||||
|
||||
// Add limit, skip and maxTimeMS if defined
|
||||
if (typeof skip === 'number') cmd.skip = skip;
|
||||
if (typeof limit === 'number') cmd.limit = limit;
|
||||
if (typeof maxTimeMS === 'number') cmd.maxTimeMS = maxTimeMS;
|
||||
if (hint) cmd.hint = hint;
|
||||
|
||||
// Do we have a readConcern specified
|
||||
decorateWithReadConcern(cmd, collectionOrCursor);
|
||||
|
||||
return cmd;
|
||||
}
|
||||
|
||||
function deleteCallback(err, r, callback) {
|
||||
if (callback == null) return;
|
||||
if (err && callback) return callback(err);
|
||||
if (r == null) return callback(null, { result: { ok: 1 } });
|
||||
r.deletedCount = r.result.n;
|
||||
if (callback) callback(null, r);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find and update a document.
|
||||
*
|
||||
* @method
|
||||
* @param {Collection} a Collection instance.
|
||||
* @param {object} query Query object to locate the object to modify.
|
||||
* @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate.
|
||||
* @param {object} doc The fields/vals to be updated.
|
||||
* @param {object} [options] Optional settings. See Collection.prototype.findAndModify for a list of options.
|
||||
* @param {Collection~findAndModifyCallback} [callback] The command result callback
|
||||
* @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead
|
||||
*/
|
||||
function findAndModify(coll, query, sort, doc, options, callback) {
|
||||
// Create findAndModify command object
|
||||
const queryObject = {
|
||||
findAndModify: coll.collectionName,
|
||||
query: query
|
||||
};
|
||||
|
||||
sort = formattedOrderClause(sort);
|
||||
if (sort) {
|
||||
queryObject.sort = sort;
|
||||
}
|
||||
|
||||
queryObject.new = options.new ? true : false;
|
||||
queryObject.remove = options.remove ? true : false;
|
||||
queryObject.upsert = options.upsert ? true : false;
|
||||
|
||||
const projection = options.projection || options.fields;
|
||||
|
||||
if (projection) {
|
||||
queryObject.fields = projection;
|
||||
}
|
||||
|
||||
if (options.arrayFilters) {
|
||||
queryObject.arrayFilters = options.arrayFilters;
|
||||
delete options.arrayFilters;
|
||||
}
|
||||
|
||||
if (doc && !options.remove) {
|
||||
queryObject.update = doc;
|
||||
}
|
||||
|
||||
if (options.maxTimeMS) queryObject.maxTimeMS = options.maxTimeMS;
|
||||
|
||||
// Either use override on the function, or go back to default on either the collection
|
||||
// level or db
|
||||
options.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions;
|
||||
|
||||
// No check on the documents
|
||||
options.checkKeys = false;
|
||||
|
||||
// Final options for retryable writes and write concern
|
||||
let finalOptions = Object.assign({}, options);
|
||||
finalOptions = applyRetryableWrites(finalOptions, coll.s.db);
|
||||
finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options);
|
||||
|
||||
// Decorate the findAndModify command with the write Concern
|
||||
if (finalOptions.writeConcern) {
|
||||
queryObject.writeConcern = finalOptions.writeConcern;
|
||||
}
|
||||
|
||||
// Have we specified bypassDocumentValidation
|
||||
if (finalOptions.bypassDocumentValidation === true) {
|
||||
queryObject.bypassDocumentValidation = finalOptions.bypassDocumentValidation;
|
||||
}
|
||||
|
||||
finalOptions.readPreference = ReadPreference.primary;
|
||||
|
||||
// Have we specified collation
|
||||
try {
|
||||
decorateWithCollation(queryObject, coll, finalOptions);
|
||||
} catch (err) {
|
||||
return callback(err, null);
|
||||
}
|
||||
|
||||
// Execute the command
|
||||
executeCommand(coll.s.db, queryObject, finalOptions, (err, result) => {
|
||||
if (err) return handleCallback(callback, err, null);
|
||||
|
||||
return handleCallback(callback, null, result);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves this collections index info.
|
||||
*
|
||||
* @method
|
||||
* @param {Db} db The Db instance on which to retrieve the index info.
|
||||
* @param {string} name The name of the collection.
|
||||
* @param {object} [options] Optional settings. See Db.prototype.indexInformation for a list of options.
|
||||
* @param {Db~resultCallback} [callback] The command result callback
|
||||
*/
|
||||
function indexInformation(db, name, options, callback) {
|
||||
// If we specified full information
|
||||
const full = options['full'] == null ? false : options['full'];
|
||||
|
||||
// Did the user destroy the topology
|
||||
if (db.serverConfig && db.serverConfig.isDestroyed())
|
||||
return callback(new MongoError('topology was destroyed'));
|
||||
// Process all the results from the index command and collection
|
||||
function processResults(indexes) {
|
||||
// Contains all the information
|
||||
let info = {};
|
||||
// Process all the indexes
|
||||
for (let i = 0; i < indexes.length; i++) {
|
||||
const index = indexes[i];
|
||||
// Let's unpack the object
|
||||
info[index.name] = [];
|
||||
for (let name in index.key) {
|
||||
info[index.name].push([name, index.key[name]]);
|
||||
}
|
||||
}
|
||||
|
||||
return info;
|
||||
}
|
||||
|
||||
// Get the list of indexes of the specified collection
|
||||
db.collection(name)
|
||||
.listIndexes(options)
|
||||
.toArray((err, indexes) => {
|
||||
if (err) return callback(toError(err));
|
||||
if (!Array.isArray(indexes)) return handleCallback(callback, null, []);
|
||||
if (full) return handleCallback(callback, null, indexes);
|
||||
handleCallback(callback, null, processResults(indexes));
|
||||
});
|
||||
}
|
||||
|
||||
function prepareDocs(coll, docs, options) {
|
||||
const forceServerObjectId =
|
||||
typeof options.forceServerObjectId === 'boolean'
|
||||
? options.forceServerObjectId
|
||||
: coll.s.db.options.forceServerObjectId;
|
||||
|
||||
// no need to modify the docs if server sets the ObjectId
|
||||
if (forceServerObjectId === true) {
|
||||
return docs;
|
||||
}
|
||||
|
||||
return docs.map(doc => {
|
||||
if (forceServerObjectId !== true && doc._id == null) {
|
||||
doc._id = coll.s.pkFactory.createPk();
|
||||
}
|
||||
|
||||
return doc;
|
||||
});
|
||||
}
|
||||
|
||||
// Get the next available document from the cursor, returns null if no more documents are available.
|
||||
function nextObject(cursor, callback) {
|
||||
if (cursor.s.state === CursorState.CLOSED || (cursor.isDead && cursor.isDead())) {
|
||||
return handleCallback(
|
||||
callback,
|
||||
MongoError.create({ message: 'Cursor is closed', driver: true })
|
||||
);
|
||||
}
|
||||
|
||||
if (cursor.s.state === CursorState.INIT && cursor.cmd && cursor.cmd.sort) {
|
||||
try {
|
||||
cursor.cmd.sort = formattedOrderClause(cursor.cmd.sort);
|
||||
} catch (err) {
|
||||
return handleCallback(callback, err);
|
||||
}
|
||||
}
|
||||
|
||||
// Get the next object
|
||||
cursor._next((err, doc) => {
|
||||
cursor.s.state = CursorState.OPEN;
|
||||
if (err) return handleCallback(callback, err);
|
||||
handleCallback(callback, null, doc);
|
||||
});
|
||||
}
|
||||
|
||||
function insertDocuments(coll, docs, options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
options = options || {};
|
||||
// Ensure we are operating on an array op docs
|
||||
docs = Array.isArray(docs) ? docs : [docs];
|
||||
|
||||
// Final options for retryable writes and write concern
|
||||
let finalOptions = Object.assign({}, options);
|
||||
finalOptions = applyRetryableWrites(finalOptions, coll.s.db);
|
||||
finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options);
|
||||
|
||||
// If keep going set unordered
|
||||
if (finalOptions.keepGoing === true) finalOptions.ordered = false;
|
||||
finalOptions.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions;
|
||||
|
||||
docs = prepareDocs(coll, docs, options);
|
||||
|
||||
// File inserts
|
||||
coll.s.topology.insert(coll.s.namespace, docs, finalOptions, (err, result) => {
|
||||
if (callback == null) return;
|
||||
if (err) return handleCallback(callback, err);
|
||||
if (result == null) return handleCallback(callback, null, null);
|
||||
if (result.result.code) return handleCallback(callback, toError(result.result));
|
||||
if (result.result.writeErrors)
|
||||
return handleCallback(callback, toError(result.result.writeErrors[0]));
|
||||
// Add docs to the list
|
||||
result.ops = docs;
|
||||
// Return the results
|
||||
handleCallback(callback, null, result);
|
||||
});
|
||||
}
|
||||
|
||||
function removeDocuments(coll, selector, options, callback) {
|
||||
if (typeof options === 'function') {
|
||||
(callback = options), (options = {});
|
||||
} else if (typeof selector === 'function') {
|
||||
callback = selector;
|
||||
options = {};
|
||||
selector = {};
|
||||
}
|
||||
|
||||
// Create an empty options object if the provided one is null
|
||||
options = options || {};
|
||||
|
||||
// Final options for retryable writes and write concern
|
||||
let finalOptions = Object.assign({}, options);
|
||||
finalOptions = applyRetryableWrites(finalOptions, coll.s.db);
|
||||
finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options);
|
||||
|
||||
// If selector is null set empty
|
||||
if (selector == null) selector = {};
|
||||
|
||||
// Build the op
|
||||
const op = { q: selector, limit: 0 };
|
||||
if (options.single) {
|
||||
op.limit = 1;
|
||||
} else if (finalOptions.retryWrites) {
|
||||
finalOptions.retryWrites = false;
|
||||
}
|
||||
if (options.hint) {
|
||||
op.hint = options.hint;
|
||||
}
|
||||
|
||||
// Have we specified collation
|
||||
try {
|
||||
decorateWithCollation(finalOptions, coll, options);
|
||||
} catch (err) {
|
||||
return callback(err, null);
|
||||
}
|
||||
|
||||
// Execute the remove
|
||||
coll.s.topology.remove(coll.s.namespace, [op], finalOptions, (err, result) => {
|
||||
if (callback == null) return;
|
||||
if (err) return handleCallback(callback, err, null);
|
||||
if (result == null) return handleCallback(callback, null, null);
|
||||
if (result.result.code) return handleCallback(callback, toError(result.result));
|
||||
if (result.result.writeErrors) {
|
||||
return handleCallback(callback, toError(result.result.writeErrors[0]));
|
||||
}
|
||||
|
||||
// Return the results
|
||||
handleCallback(callback, null, result);
|
||||
});
|
||||
}
|
||||
|
||||
function updateDocuments(coll, selector, document, options, callback) {
|
||||
if ('function' === typeof options) (callback = options), (options = null);
|
||||
if (options == null) options = {};
|
||||
if (!('function' === typeof callback)) callback = null;
|
||||
|
||||
// If we are not providing a selector or document throw
|
||||
if (selector == null || typeof selector !== 'object')
|
||||
return callback(toError('selector must be a valid JavaScript object'));
|
||||
if (document == null || typeof document !== 'object')
|
||||
return callback(toError('document must be a valid JavaScript object'));
|
||||
|
||||
// Final options for retryable writes and write concern
|
||||
let finalOptions = Object.assign({}, options);
|
||||
finalOptions = applyRetryableWrites(finalOptions, coll.s.db);
|
||||
finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options);
|
||||
|
||||
// Do we return the actual result document
|
||||
// Either use override on the function, or go back to default on either the collection
|
||||
// level or db
|
||||
finalOptions.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions;
|
||||
|
||||
// Execute the operation
|
||||
const op = { q: selector, u: document };
|
||||
op.upsert = options.upsert !== void 0 ? !!options.upsert : false;
|
||||
op.multi = options.multi !== void 0 ? !!options.multi : false;
|
||||
|
||||
if (options.hint) {
|
||||
op.hint = options.hint;
|
||||
}
|
||||
|
||||
if (finalOptions.arrayFilters) {
|
||||
op.arrayFilters = finalOptions.arrayFilters;
|
||||
delete finalOptions.arrayFilters;
|
||||
}
|
||||
|
||||
if (finalOptions.retryWrites && op.multi) {
|
||||
finalOptions.retryWrites = false;
|
||||
}
|
||||
|
||||
// Have we specified collation
|
||||
try {
|
||||
decorateWithCollation(finalOptions, coll, options);
|
||||
} catch (err) {
|
||||
return callback(err, null);
|
||||
}
|
||||
|
||||
// Update options
|
||||
coll.s.topology.update(coll.s.namespace, [op], finalOptions, (err, result) => {
|
||||
if (callback == null) return;
|
||||
if (err) return handleCallback(callback, err, null);
|
||||
if (result == null) return handleCallback(callback, null, null);
|
||||
if (result.result.code) return handleCallback(callback, toError(result.result));
|
||||
if (result.result.writeErrors)
|
||||
return handleCallback(callback, toError(result.result.writeErrors[0]));
|
||||
// Return the results
|
||||
handleCallback(callback, null, result);
|
||||
});
|
||||
}
|
||||
|
||||
function updateCallback(err, r, callback) {
|
||||
if (callback == null) return;
|
||||
if (err) return callback(err);
|
||||
if (r == null) return callback(null, { result: { ok: 1 } });
|
||||
r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n;
|
||||
r.upsertedId =
|
||||
Array.isArray(r.result.upserted) && r.result.upserted.length > 0
|
||||
? r.result.upserted[0] // FIXME(major): should be `r.result.upserted[0]._id`
|
||||
: null;
|
||||
r.upsertedCount =
|
||||
Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0;
|
||||
r.matchedCount =
|
||||
Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n;
|
||||
callback(null, r);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
buildCountCommand,
|
||||
deleteCallback,
|
||||
findAndModify,
|
||||
indexInformation,
|
||||
nextObject,
|
||||
prepareDocs,
|
||||
insertDocuments,
|
||||
removeDocuments,
|
||||
updateDocuments,
|
||||
updateCallback
|
||||
};
|
||||
806
node_modules/mongodb/lib/operations/connect.js
generated
vendored
Normal file
806
node_modules/mongodb/lib/operations/connect.js
generated
vendored
Normal file
@@ -0,0 +1,806 @@
|
||||
'use strict';
|
||||
|
||||
const deprecate = require('util').deprecate;
|
||||
const Logger = require('../core').Logger;
|
||||
const MongoCredentials = require('../core').MongoCredentials;
|
||||
const MongoError = require('../core').MongoError;
|
||||
const Mongos = require('../topologies/mongos');
|
||||
const NativeTopology = require('../topologies/native_topology');
|
||||
const parse = require('../core').parseConnectionString;
|
||||
const ReadConcern = require('../read_concern');
|
||||
const ReadPreference = require('../core').ReadPreference;
|
||||
const ReplSet = require('../topologies/replset');
|
||||
const Server = require('../topologies/server');
|
||||
const ServerSessionPool = require('../core').Sessions.ServerSessionPool;
|
||||
const emitDeprecationWarning = require('../utils').emitDeprecationWarning;
|
||||
const fs = require('fs');
|
||||
const BSON = require('../core/connection/utils').retrieveBSON();
|
||||
const CMAP_EVENT_NAMES = require('../cmap/events').CMAP_EVENT_NAMES;
|
||||
|
||||
let client;
|
||||
function loadClient() {
|
||||
if (!client) {
|
||||
client = require('../mongo_client');
|
||||
}
|
||||
return client;
|
||||
}
|
||||
|
||||
const legacyParse = deprecate(
|
||||
require('../url_parser'),
|
||||
'current URL string parser is deprecated, and will be removed in a future version. ' +
|
||||
'To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.'
|
||||
);
|
||||
|
||||
const AUTH_MECHANISM_INTERNAL_MAP = {
|
||||
DEFAULT: 'default',
|
||||
PLAIN: 'plain',
|
||||
GSSAPI: 'gssapi',
|
||||
'MONGODB-CR': 'mongocr',
|
||||
'MONGODB-X509': 'x509',
|
||||
'MONGODB-AWS': 'mongodb-aws',
|
||||
'SCRAM-SHA-1': 'scram-sha-1',
|
||||
'SCRAM-SHA-256': 'scram-sha-256'
|
||||
};
|
||||
|
||||
const monitoringEvents = [
|
||||
'timeout',
|
||||
'close',
|
||||
'serverOpening',
|
||||
'serverDescriptionChanged',
|
||||
'serverHeartbeatStarted',
|
||||
'serverHeartbeatSucceeded',
|
||||
'serverHeartbeatFailed',
|
||||
'serverClosed',
|
||||
'topologyOpening',
|
||||
'topologyClosed',
|
||||
'topologyDescriptionChanged',
|
||||
'commandStarted',
|
||||
'commandSucceeded',
|
||||
'commandFailed',
|
||||
'joined',
|
||||
'left',
|
||||
'ping',
|
||||
'ha',
|
||||
'all',
|
||||
'fullsetup',
|
||||
'open'
|
||||
];
|
||||
|
||||
const VALID_AUTH_MECHANISMS = new Set([
|
||||
'DEFAULT',
|
||||
'PLAIN',
|
||||
'GSSAPI',
|
||||
'MONGODB-CR',
|
||||
'MONGODB-X509',
|
||||
'MONGODB-AWS',
|
||||
'SCRAM-SHA-1',
|
||||
'SCRAM-SHA-256'
|
||||
]);
|
||||
|
||||
const validOptionNames = [
|
||||
'poolSize',
|
||||
'ssl',
|
||||
'sslValidate',
|
||||
'sslCA',
|
||||
'sslCert',
|
||||
'sslKey',
|
||||
'sslPass',
|
||||
'sslCRL',
|
||||
'autoReconnect',
|
||||
'noDelay',
|
||||
'keepAlive',
|
||||
'keepAliveInitialDelay',
|
||||
'connectTimeoutMS',
|
||||
'family',
|
||||
'socketTimeoutMS',
|
||||
'reconnectTries',
|
||||
'reconnectInterval',
|
||||
'ha',
|
||||
'haInterval',
|
||||
'replicaSet',
|
||||
'secondaryAcceptableLatencyMS',
|
||||
'acceptableLatencyMS',
|
||||
'connectWithNoPrimary',
|
||||
'authSource',
|
||||
'w',
|
||||
'wtimeout',
|
||||
'j',
|
||||
'forceServerObjectId',
|
||||
'serializeFunctions',
|
||||
'ignoreUndefined',
|
||||
'raw',
|
||||
'bufferMaxEntries',
|
||||
'readPreference',
|
||||
'pkFactory',
|
||||
'promiseLibrary',
|
||||
'readConcern',
|
||||
'maxStalenessSeconds',
|
||||
'loggerLevel',
|
||||
'logger',
|
||||
'promoteValues',
|
||||
'promoteBuffers',
|
||||
'promoteLongs',
|
||||
'domainsEnabled',
|
||||
'checkServerIdentity',
|
||||
'validateOptions',
|
||||
'appname',
|
||||
'auth',
|
||||
'user',
|
||||
'password',
|
||||
'authMechanism',
|
||||
'compression',
|
||||
'fsync',
|
||||
'readPreferenceTags',
|
||||
'numberOfRetries',
|
||||
'auto_reconnect',
|
||||
'minSize',
|
||||
'monitorCommands',
|
||||
'retryWrites',
|
||||
'retryReads',
|
||||
'useNewUrlParser',
|
||||
'useUnifiedTopology',
|
||||
'serverSelectionTimeoutMS',
|
||||
'useRecoveryToken',
|
||||
'autoEncryption',
|
||||
'driverInfo',
|
||||
'tls',
|
||||
'tlsInsecure',
|
||||
'tlsinsecure',
|
||||
'tlsAllowInvalidCertificates',
|
||||
'tlsAllowInvalidHostnames',
|
||||
'tlsCAFile',
|
||||
'tlsCertificateFile',
|
||||
'tlsCertificateKeyFile',
|
||||
'tlsCertificateKeyFilePassword',
|
||||
'minHeartbeatFrequencyMS',
|
||||
'heartbeatFrequencyMS',
|
||||
'directConnection',
|
||||
'appName',
|
||||
|
||||
// CMAP options
|
||||
'maxPoolSize',
|
||||
'minPoolSize',
|
||||
'maxIdleTimeMS',
|
||||
'waitQueueTimeoutMS'
|
||||
];
|
||||
|
||||
const ignoreOptionNames = ['native_parser'];
|
||||
const legacyOptionNames = ['server', 'replset', 'replSet', 'mongos', 'db'];
|
||||
|
||||
// Validate options object
|
||||
function validOptions(options) {
|
||||
const _validOptions = validOptionNames.concat(legacyOptionNames);
|
||||
|
||||
for (const name in options) {
|
||||
if (ignoreOptionNames.indexOf(name) !== -1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (_validOptions.indexOf(name) === -1) {
|
||||
if (options.validateOptions) {
|
||||
return new MongoError(`option ${name} is not supported`);
|
||||
} else {
|
||||
console.warn(`the options [${name}] is not supported`);
|
||||
}
|
||||
}
|
||||
|
||||
if (legacyOptionNames.indexOf(name) !== -1) {
|
||||
console.warn(
|
||||
`the server/replset/mongos/db options are deprecated, ` +
|
||||
`all their options are supported at the top level of the options object [${validOptionNames}]`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const LEGACY_OPTIONS_MAP = validOptionNames.reduce((obj, name) => {
|
||||
obj[name.toLowerCase()] = name;
|
||||
return obj;
|
||||
}, {});
|
||||
|
||||
function addListeners(mongoClient, topology) {
|
||||
topology.on('authenticated', createListener(mongoClient, 'authenticated'));
|
||||
topology.on('error', createListener(mongoClient, 'error'));
|
||||
topology.on('timeout', createListener(mongoClient, 'timeout'));
|
||||
topology.on('close', createListener(mongoClient, 'close'));
|
||||
topology.on('parseError', createListener(mongoClient, 'parseError'));
|
||||
topology.once('open', createListener(mongoClient, 'open'));
|
||||
topology.once('fullsetup', createListener(mongoClient, 'fullsetup'));
|
||||
topology.once('all', createListener(mongoClient, 'all'));
|
||||
topology.on('reconnect', createListener(mongoClient, 'reconnect'));
|
||||
}
|
||||
|
||||
function assignTopology(client, topology) {
|
||||
client.topology = topology;
|
||||
|
||||
if (!(topology instanceof NativeTopology)) {
|
||||
topology.s.sessionPool = new ServerSessionPool(topology.s.coreTopology);
|
||||
}
|
||||
}
|
||||
|
||||
// Clear out all events
|
||||
function clearAllEvents(topology) {
|
||||
monitoringEvents.forEach(event => topology.removeAllListeners(event));
|
||||
}
|
||||
|
||||
// Collect all events in order from SDAM
|
||||
function collectEvents(mongoClient, topology) {
|
||||
let MongoClient = loadClient();
|
||||
const collectedEvents = [];
|
||||
|
||||
if (mongoClient instanceof MongoClient) {
|
||||
monitoringEvents.forEach(event => {
|
||||
topology.on(event, (object1, object2) => {
|
||||
if (event === 'open') {
|
||||
collectedEvents.push({ event: event, object1: mongoClient });
|
||||
} else {
|
||||
collectedEvents.push({ event: event, object1: object1, object2: object2 });
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
return collectedEvents;
|
||||
}
|
||||
|
||||
function resolveTLSOptions(options) {
|
||||
if (options.tls == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
['sslCA', 'sslKey', 'sslCert'].forEach(optionName => {
|
||||
if (options[optionName]) {
|
||||
options[optionName] = fs.readFileSync(options[optionName]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const emitDeprecationForNonUnifiedTopology = deprecate(() => {},
|
||||
'current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. ' + 'To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.');
|
||||
|
||||
function connect(mongoClient, url, options, callback) {
|
||||
options = Object.assign({}, options);
|
||||
|
||||
// If callback is null throw an exception
|
||||
if (callback == null) {
|
||||
throw new Error('no callback function provided');
|
||||
}
|
||||
|
||||
let didRequestAuthentication = false;
|
||||
const logger = Logger('MongoClient', options);
|
||||
|
||||
// Did we pass in a Server/ReplSet/Mongos
|
||||
if (url instanceof Server || url instanceof ReplSet || url instanceof Mongos) {
|
||||
return connectWithUrl(mongoClient, url, options, connectCallback);
|
||||
}
|
||||
|
||||
const useNewUrlParser = options.useNewUrlParser !== false;
|
||||
|
||||
const parseFn = useNewUrlParser ? parse : legacyParse;
|
||||
const transform = useNewUrlParser ? transformUrlOptions : legacyTransformUrlOptions;
|
||||
|
||||
parseFn(url, options, (err, _object) => {
|
||||
// Do not attempt to connect if parsing error
|
||||
if (err) return callback(err);
|
||||
|
||||
// Flatten
|
||||
const object = transform(_object);
|
||||
|
||||
// Parse the string
|
||||
const _finalOptions = createUnifiedOptions(object, options);
|
||||
|
||||
// Check if we have connection and socket timeout set
|
||||
if (_finalOptions.socketTimeoutMS == null) _finalOptions.socketTimeoutMS = 360000;
|
||||
if (_finalOptions.connectTimeoutMS == null) _finalOptions.connectTimeoutMS = 10000;
|
||||
if (_finalOptions.retryWrites == null) _finalOptions.retryWrites = true;
|
||||
if (_finalOptions.useRecoveryToken == null) _finalOptions.useRecoveryToken = true;
|
||||
if (_finalOptions.readPreference == null) _finalOptions.readPreference = 'primary';
|
||||
|
||||
if (_finalOptions.db_options && _finalOptions.db_options.auth) {
|
||||
delete _finalOptions.db_options.auth;
|
||||
}
|
||||
|
||||
// `journal` should be translated to `j` for the driver
|
||||
if (_finalOptions.journal != null) {
|
||||
_finalOptions.j = _finalOptions.journal;
|
||||
_finalOptions.journal = undefined;
|
||||
}
|
||||
|
||||
// resolve tls options if needed
|
||||
resolveTLSOptions(_finalOptions);
|
||||
|
||||
// Store the merged options object
|
||||
mongoClient.s.options = _finalOptions;
|
||||
|
||||
// Failure modes
|
||||
if (object.servers.length === 0) {
|
||||
return callback(new Error('connection string must contain at least one seed host'));
|
||||
}
|
||||
|
||||
if (_finalOptions.auth && !_finalOptions.credentials) {
|
||||
try {
|
||||
didRequestAuthentication = true;
|
||||
_finalOptions.credentials = generateCredentials(
|
||||
mongoClient,
|
||||
_finalOptions.auth.user,
|
||||
_finalOptions.auth.password,
|
||||
_finalOptions
|
||||
);
|
||||
} catch (err) {
|
||||
return callback(err);
|
||||
}
|
||||
}
|
||||
|
||||
if (_finalOptions.useUnifiedTopology) {
|
||||
return createTopology(mongoClient, 'unified', _finalOptions, connectCallback);
|
||||
}
|
||||
|
||||
emitDeprecationForNonUnifiedTopology();
|
||||
|
||||
// Do we have a replicaset then skip discovery and go straight to connectivity
|
||||
if (_finalOptions.replicaSet || _finalOptions.rs_name) {
|
||||
return createTopology(mongoClient, 'replicaset', _finalOptions, connectCallback);
|
||||
} else if (object.servers.length > 1) {
|
||||
return createTopology(mongoClient, 'mongos', _finalOptions, connectCallback);
|
||||
} else {
|
||||
return createServer(mongoClient, _finalOptions, connectCallback);
|
||||
}
|
||||
});
|
||||
|
||||
function connectCallback(err, topology) {
|
||||
const warningMessage = `seed list contains no mongos proxies, replicaset connections requires the parameter replicaSet to be supplied in the URI or options object, mongodb://server:port/db?replicaSet=name`;
|
||||
if (err && err.message === 'no mongos proxies found in seed list') {
|
||||
if (logger.isWarn()) {
|
||||
logger.warn(warningMessage);
|
||||
}
|
||||
|
||||
// Return a more specific error message for MongoClient.connect
|
||||
return callback(new MongoError(warningMessage));
|
||||
}
|
||||
|
||||
if (didRequestAuthentication) {
|
||||
mongoClient.emit('authenticated', null, true);
|
||||
}
|
||||
|
||||
// Return the error and db instance
|
||||
callback(err, topology);
|
||||
}
|
||||
}
|
||||
|
||||
function connectWithUrl(mongoClient, url, options, connectCallback) {
|
||||
// Set the topology
|
||||
assignTopology(mongoClient, url);
|
||||
|
||||
// Add listeners
|
||||
addListeners(mongoClient, url);
|
||||
|
||||
// Propagate the events to the client
|
||||
relayEvents(mongoClient, url);
|
||||
|
||||
let finalOptions = Object.assign({}, options);
|
||||
|
||||
// If we have a readPreference passed in by the db options, convert it from a string
|
||||
if (typeof options.readPreference === 'string' || typeof options.read_preference === 'string') {
|
||||
finalOptions.readPreference = new ReadPreference(
|
||||
options.readPreference || options.read_preference
|
||||
);
|
||||
}
|
||||
|
||||
const isDoingAuth = finalOptions.user || finalOptions.password || finalOptions.authMechanism;
|
||||
if (isDoingAuth && !finalOptions.credentials) {
|
||||
try {
|
||||
finalOptions.credentials = generateCredentials(
|
||||
mongoClient,
|
||||
finalOptions.user,
|
||||
finalOptions.password,
|
||||
finalOptions
|
||||
);
|
||||
} catch (err) {
|
||||
return connectCallback(err, url);
|
||||
}
|
||||
}
|
||||
|
||||
return url.connect(finalOptions, connectCallback);
|
||||
}
|
||||
|
||||
function createListener(mongoClient, event) {
|
||||
const eventSet = new Set(['all', 'fullsetup', 'open', 'reconnect']);
|
||||
return (v1, v2) => {
|
||||
if (eventSet.has(event)) {
|
||||
return mongoClient.emit(event, mongoClient);
|
||||
}
|
||||
|
||||
mongoClient.emit(event, v1, v2);
|
||||
};
|
||||
}
|
||||
|
||||
function createServer(mongoClient, options, callback) {
|
||||
// Pass in the promise library
|
||||
options.promiseLibrary = mongoClient.s.promiseLibrary;
|
||||
|
||||
// Set default options
|
||||
const servers = translateOptions(options);
|
||||
|
||||
const server = servers[0];
|
||||
|
||||
// Propagate the events to the client
|
||||
const collectedEvents = collectEvents(mongoClient, server);
|
||||
|
||||
// Connect to topology
|
||||
server.connect(options, (err, topology) => {
|
||||
if (err) {
|
||||
server.close(true);
|
||||
return callback(err);
|
||||
}
|
||||
// Clear out all the collected event listeners
|
||||
clearAllEvents(server);
|
||||
|
||||
// Relay all the events
|
||||
relayEvents(mongoClient, server);
|
||||
// Add listeners
|
||||
addListeners(mongoClient, server);
|
||||
// Check if we are really speaking to a mongos
|
||||
const ismaster = topology.lastIsMaster();
|
||||
|
||||
// Set the topology
|
||||
assignTopology(mongoClient, topology);
|
||||
|
||||
// Do we actually have a mongos
|
||||
if (ismaster && ismaster.msg === 'isdbgrid') {
|
||||
// Destroy the current connection
|
||||
topology.close();
|
||||
// Create mongos connection instead
|
||||
return createTopology(mongoClient, 'mongos', options, callback);
|
||||
}
|
||||
|
||||
// Fire all the events
|
||||
replayEvents(mongoClient, collectedEvents);
|
||||
// Otherwise callback
|
||||
callback(err, topology);
|
||||
});
|
||||
}
|
||||
|
||||
const DEPRECATED_UNIFIED_EVENTS = new Set([
|
||||
'reconnect',
|
||||
'reconnectFailed',
|
||||
'attemptReconnect',
|
||||
'joined',
|
||||
'left',
|
||||
'ping',
|
||||
'ha',
|
||||
'all',
|
||||
'fullsetup',
|
||||
'open'
|
||||
]);
|
||||
|
||||
function registerDeprecatedEventNotifiers(client) {
|
||||
client.on('newListener', eventName => {
|
||||
if (DEPRECATED_UNIFIED_EVENTS.has(eventName)) {
|
||||
emitDeprecationWarning(
|
||||
`The \`${eventName}\` event is no longer supported by the unified topology, please read more by visiting http://bit.ly/2D8WfT6`,
|
||||
'DeprecationWarning'
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function createTopology(mongoClient, topologyType, options, callback) {
|
||||
// Pass in the promise library
|
||||
options.promiseLibrary = mongoClient.s.promiseLibrary;
|
||||
|
||||
const translationOptions = {};
|
||||
if (topologyType === 'unified') translationOptions.createServers = false;
|
||||
|
||||
// Set default options
|
||||
const servers = translateOptions(options, translationOptions);
|
||||
|
||||
// determine CSFLE support
|
||||
if (options.autoEncryption != null) {
|
||||
let AutoEncrypter;
|
||||
try {
|
||||
require.resolve('mongodb-client-encryption');
|
||||
} catch (err) {
|
||||
callback(
|
||||
new MongoError(
|
||||
'Auto-encryption requested, but the module is not installed. Please add `mongodb-client-encryption` as a dependency of your project'
|
||||
)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
let mongodbClientEncryption = require('mongodb-client-encryption');
|
||||
if (typeof mongodbClientEncryption.extension !== 'function') {
|
||||
callback(
|
||||
new MongoError(
|
||||
'loaded version of `mongodb-client-encryption` does not have property `extension`. Please make sure you are loading the correct version of `mongodb-client-encryption`'
|
||||
)
|
||||
);
|
||||
}
|
||||
AutoEncrypter = mongodbClientEncryption.extension(require('../../index')).AutoEncrypter;
|
||||
} catch (err) {
|
||||
callback(err);
|
||||
return;
|
||||
}
|
||||
|
||||
const mongoCryptOptions = Object.assign(
|
||||
{
|
||||
bson:
|
||||
options.bson ||
|
||||
new BSON([
|
||||
BSON.Binary,
|
||||
BSON.Code,
|
||||
BSON.DBRef,
|
||||
BSON.Decimal128,
|
||||
BSON.Double,
|
||||
BSON.Int32,
|
||||
BSON.Long,
|
||||
BSON.Map,
|
||||
BSON.MaxKey,
|
||||
BSON.MinKey,
|
||||
BSON.ObjectId,
|
||||
BSON.BSONRegExp,
|
||||
BSON.Symbol,
|
||||
BSON.Timestamp
|
||||
])
|
||||
},
|
||||
options.autoEncryption
|
||||
);
|
||||
|
||||
options.autoEncrypter = new AutoEncrypter(mongoClient, mongoCryptOptions);
|
||||
}
|
||||
|
||||
// Create the topology
|
||||
let topology;
|
||||
if (topologyType === 'mongos') {
|
||||
topology = new Mongos(servers, options);
|
||||
} else if (topologyType === 'replicaset') {
|
||||
topology = new ReplSet(servers, options);
|
||||
} else if (topologyType === 'unified') {
|
||||
topology = new NativeTopology(options.servers, options);
|
||||
registerDeprecatedEventNotifiers(mongoClient);
|
||||
}
|
||||
|
||||
// Add listeners
|
||||
addListeners(mongoClient, topology);
|
||||
|
||||
// Propagate the events to the client
|
||||
relayEvents(mongoClient, topology);
|
||||
|
||||
// Open the connection
|
||||
assignTopology(mongoClient, topology);
|
||||
|
||||
// initialize CSFLE if requested
|
||||
if (options.autoEncrypter) {
|
||||
options.autoEncrypter.init(err => {
|
||||
if (err) {
|
||||
callback(err);
|
||||
return;
|
||||
}
|
||||
|
||||
topology.connect(options, err => {
|
||||
if (err) {
|
||||
topology.close(true);
|
||||
callback(err);
|
||||
return;
|
||||
}
|
||||
|
||||
callback(undefined, topology);
|
||||
});
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// otherwise connect normally
|
||||
topology.connect(options, err => {
|
||||
if (err) {
|
||||
topology.close(true);
|
||||
return callback(err);
|
||||
}
|
||||
|
||||
callback(undefined, topology);
|
||||
return;
|
||||
});
|
||||
}
|
||||
|
||||
function createUnifiedOptions(finalOptions, options) {
|
||||
const childOptions = [
|
||||
'mongos',
|
||||
'server',
|
||||
'db',
|
||||
'replset',
|
||||
'db_options',
|
||||
'server_options',
|
||||
'rs_options',
|
||||
'mongos_options'
|
||||
];
|
||||
const noMerge = ['readconcern', 'compression', 'autoencryption'];
|
||||
|
||||
for (const name in options) {
|
||||
if (noMerge.indexOf(name.toLowerCase()) !== -1) {
|
||||
finalOptions[name] = options[name];
|
||||
} else if (childOptions.indexOf(name.toLowerCase()) !== -1) {
|
||||
finalOptions = mergeOptions(finalOptions, options[name], false);
|
||||
} else {
|
||||
if (
|
||||
options[name] &&
|
||||
typeof options[name] === 'object' &&
|
||||
!Buffer.isBuffer(options[name]) &&
|
||||
!Array.isArray(options[name])
|
||||
) {
|
||||
finalOptions = mergeOptions(finalOptions, options[name], true);
|
||||
} else {
|
||||
finalOptions[name] = options[name];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return finalOptions;
|
||||
}
|
||||
|
||||
function generateCredentials(client, username, password, options) {
|
||||
options = Object.assign({}, options);
|
||||
|
||||
// the default db to authenticate against is 'self'
|
||||
// if authententicate is called from a retry context, it may be another one, like admin
|
||||
const source = options.authSource || options.authdb || options.dbName;
|
||||
|
||||
// authMechanism
|
||||
const authMechanismRaw = options.authMechanism || 'DEFAULT';
|
||||
const authMechanism = authMechanismRaw.toUpperCase();
|
||||
const mechanismProperties = options.authMechanismProperties;
|
||||
|
||||
if (!VALID_AUTH_MECHANISMS.has(authMechanism)) {
|
||||
throw MongoError.create({
|
||||
message: `authentication mechanism ${authMechanismRaw} not supported', options.authMechanism`,
|
||||
driver: true
|
||||
});
|
||||
}
|
||||
|
||||
return new MongoCredentials({
|
||||
mechanism: AUTH_MECHANISM_INTERNAL_MAP[authMechanism],
|
||||
mechanismProperties,
|
||||
source,
|
||||
username,
|
||||
password
|
||||
});
|
||||
}
|
||||
|
||||
function legacyTransformUrlOptions(object) {
|
||||
return mergeOptions(createUnifiedOptions({}, object), object, false);
|
||||
}
|
||||
|
||||
function mergeOptions(target, source, flatten) {
|
||||
for (const name in source) {
|
||||
if (source[name] && typeof source[name] === 'object' && flatten) {
|
||||
target = mergeOptions(target, source[name], flatten);
|
||||
} else {
|
||||
target[name] = source[name];
|
||||
}
|
||||
}
|
||||
|
||||
return target;
|
||||
}
|
||||
|
||||
function relayEvents(mongoClient, topology) {
|
||||
const serverOrCommandEvents = [
|
||||
// APM
|
||||
'commandStarted',
|
||||
'commandSucceeded',
|
||||
'commandFailed',
|
||||
|
||||
// SDAM
|
||||
'serverOpening',
|
||||
'serverClosed',
|
||||
'serverDescriptionChanged',
|
||||
'serverHeartbeatStarted',
|
||||
'serverHeartbeatSucceeded',
|
||||
'serverHeartbeatFailed',
|
||||
'topologyOpening',
|
||||
'topologyClosed',
|
||||
'topologyDescriptionChanged',
|
||||
|
||||
// Legacy
|
||||
'joined',
|
||||
'left',
|
||||
'ping',
|
||||
'ha'
|
||||
].concat(CMAP_EVENT_NAMES);
|
||||
|
||||
serverOrCommandEvents.forEach(event => {
|
||||
topology.on(event, (object1, object2) => {
|
||||
mongoClient.emit(event, object1, object2);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
//
|
||||
// Replay any events due to single server connection switching to Mongos
|
||||
//
|
||||
function replayEvents(mongoClient, events) {
|
||||
for (let i = 0; i < events.length; i++) {
|
||||
mongoClient.emit(events[i].event, events[i].object1, events[i].object2);
|
||||
}
|
||||
}
|
||||
|
||||
function transformUrlOptions(_object) {
|
||||
let object = Object.assign({ servers: _object.hosts }, _object.options);
|
||||
for (let name in object) {
|
||||
const camelCaseName = LEGACY_OPTIONS_MAP[name];
|
||||
if (camelCaseName) {
|
||||
object[camelCaseName] = object[name];
|
||||
}
|
||||
}
|
||||
|
||||
const hasUsername = _object.auth && _object.auth.username;
|
||||
const hasAuthMechanism = _object.options && _object.options.authMechanism;
|
||||
if (hasUsername || hasAuthMechanism) {
|
||||
object.auth = Object.assign({}, _object.auth);
|
||||
if (object.auth.db) {
|
||||
object.authSource = object.authSource || object.auth.db;
|
||||
}
|
||||
|
||||
if (object.auth.username) {
|
||||
object.auth.user = object.auth.username;
|
||||
}
|
||||
}
|
||||
|
||||
if (_object.defaultDatabase) {
|
||||
object.dbName = _object.defaultDatabase;
|
||||
}
|
||||
|
||||
if (object.maxPoolSize) {
|
||||
object.poolSize = object.maxPoolSize;
|
||||
}
|
||||
|
||||
if (object.readConcernLevel) {
|
||||
object.readConcern = new ReadConcern(object.readConcernLevel);
|
||||
}
|
||||
|
||||
if (object.wTimeoutMS) {
|
||||
object.wtimeout = object.wTimeoutMS;
|
||||
}
|
||||
|
||||
if (_object.srvHost) {
|
||||
object.srvHost = _object.srvHost;
|
||||
}
|
||||
|
||||
return object;
|
||||
}
|
||||
|
||||
function translateOptions(options, translationOptions) {
|
||||
translationOptions = Object.assign({}, { createServers: true }, translationOptions);
|
||||
|
||||
// If we have a readPreference passed in by the db options
|
||||
if (typeof options.readPreference === 'string' || typeof options.read_preference === 'string') {
|
||||
options.readPreference = new ReadPreference(options.readPreference || options.read_preference);
|
||||
}
|
||||
|
||||
// Do we have readPreference tags, add them
|
||||
if (options.readPreference && (options.readPreferenceTags || options.read_preference_tags)) {
|
||||
options.readPreference.tags = options.readPreferenceTags || options.read_preference_tags;
|
||||
}
|
||||
|
||||
// Do we have maxStalenessSeconds
|
||||
if (options.maxStalenessSeconds) {
|
||||
options.readPreference.maxStalenessSeconds = options.maxStalenessSeconds;
|
||||
}
|
||||
|
||||
// Set the socket and connection timeouts
|
||||
if (options.socketTimeoutMS == null) options.socketTimeoutMS = 360000;
|
||||
if (options.connectTimeoutMS == null) options.connectTimeoutMS = 10000;
|
||||
|
||||
if (!translationOptions.createServers) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Create server instances
|
||||
return options.servers.map(serverObj => {
|
||||
return serverObj.domain_socket
|
||||
? new Server(serverObj.domain_socket, 27017, options)
|
||||
: new Server(serverObj.host, serverObj.port, options);
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { validOptions, connect };
|
||||
68
node_modules/mongodb/lib/operations/count.js
generated
vendored
Normal file
68
node_modules/mongodb/lib/operations/count.js
generated
vendored
Normal file
@@ -0,0 +1,68 @@
|
||||
'use strict';
|
||||
|
||||
const buildCountCommand = require('./common_functions').buildCountCommand;
|
||||
const OperationBase = require('./operation').OperationBase;
|
||||
|
||||
class CountOperation extends OperationBase {
|
||||
constructor(cursor, applySkipLimit, options) {
|
||||
super(options);
|
||||
|
||||
this.cursor = cursor;
|
||||
this.applySkipLimit = applySkipLimit;
|
||||
}
|
||||
|
||||
execute(callback) {
|
||||
const cursor = this.cursor;
|
||||
const applySkipLimit = this.applySkipLimit;
|
||||
const options = this.options;
|
||||
|
||||
if (applySkipLimit) {
|
||||
if (typeof cursor.cursorSkip() === 'number') options.skip = cursor.cursorSkip();
|
||||
if (typeof cursor.cursorLimit() === 'number') options.limit = cursor.cursorLimit();
|
||||
}
|
||||
|
||||
// Ensure we have the right read preference inheritance
|
||||
if (options.readPreference) {
|
||||
cursor.setReadPreference(options.readPreference);
|
||||
}
|
||||
|
||||
if (
|
||||
typeof options.maxTimeMS !== 'number' &&
|
||||
cursor.cmd &&
|
||||
typeof cursor.cmd.maxTimeMS === 'number'
|
||||
) {
|
||||
options.maxTimeMS = cursor.cmd.maxTimeMS;
|
||||
}
|
||||
|
||||
let finalOptions = {};
|
||||
finalOptions.skip = options.skip;
|
||||
finalOptions.limit = options.limit;
|
||||
finalOptions.hint = options.hint;
|
||||
finalOptions.maxTimeMS = options.maxTimeMS;
|
||||
|
||||
// Command
|
||||
finalOptions.collectionName = cursor.namespace.collection;
|
||||
|
||||
let command;
|
||||
try {
|
||||
command = buildCountCommand(cursor, cursor.cmd.query, finalOptions);
|
||||
} catch (err) {
|
||||
return callback(err);
|
||||
}
|
||||
|
||||
// Set cursor server to the same as the topology
|
||||
cursor.server = cursor.topology.s.coreTopology;
|
||||
|
||||
// Execute the command
|
||||
cursor.topology.command(
|
||||
cursor.namespace.withCollection('$cmd'),
|
||||
command,
|
||||
cursor.options,
|
||||
(err, result) => {
|
||||
callback(err, result ? result.result.n : null);
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = CountOperation;
|
||||
41
node_modules/mongodb/lib/operations/count_documents.js
generated
vendored
Normal file
41
node_modules/mongodb/lib/operations/count_documents.js
generated
vendored
Normal file
@@ -0,0 +1,41 @@
|
||||
'use strict';
|
||||
|
||||
const AggregateOperation = require('./aggregate');
|
||||
|
||||
class CountDocumentsOperation extends AggregateOperation {
|
||||
constructor(collection, query, options) {
|
||||
const pipeline = [{ $match: query }];
|
||||
if (typeof options.skip === 'number') {
|
||||
pipeline.push({ $skip: options.skip });
|
||||
}
|
||||
|
||||
if (typeof options.limit === 'number') {
|
||||
pipeline.push({ $limit: options.limit });
|
||||
}
|
||||
|
||||
pipeline.push({ $group: { _id: 1, n: { $sum: 1 } } });
|
||||
|
||||
super(collection, pipeline, options);
|
||||
}
|
||||
|
||||
execute(server, callback) {
|
||||
super.execute(server, (err, result) => {
|
||||
if (err) {
|
||||
callback(err, null);
|
||||
return;
|
||||
}
|
||||
|
||||
// NOTE: We're avoiding creating a cursor here to reduce the callstack.
|
||||
const response = result.result;
|
||||
if (response.cursor == null || response.cursor.firstBatch == null) {
|
||||
callback(null, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
const docs = response.cursor.firstBatch;
|
||||
callback(null, docs.length ? docs[0].n : 0);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = CountDocumentsOperation;
|
||||
102
node_modules/mongodb/lib/operations/create_collection.js
generated
vendored
Normal file
102
node_modules/mongodb/lib/operations/create_collection.js
generated
vendored
Normal file
@@ -0,0 +1,102 @@
|
||||
'use strict';
|
||||
|
||||
const Aspect = require('./operation').Aspect;
|
||||
const defineAspects = require('./operation').defineAspects;
|
||||
const CommandOperation = require('./command');
|
||||
const applyWriteConcern = require('../utils').applyWriteConcern;
|
||||
const loadCollection = require('../dynamic_loaders').loadCollection;
|
||||
const MongoError = require('../core').MongoError;
|
||||
const ReadPreference = require('../core').ReadPreference;
|
||||
|
||||
const ILLEGAL_COMMAND_FIELDS = new Set([
|
||||
'w',
|
||||
'wtimeout',
|
||||
'j',
|
||||
'fsync',
|
||||
'autoIndexId',
|
||||
'strict',
|
||||
'serializeFunctions',
|
||||
'pkFactory',
|
||||
'raw',
|
||||
'readPreference',
|
||||
'session',
|
||||
'readConcern',
|
||||
'writeConcern'
|
||||
]);
|
||||
|
||||
class CreateCollectionOperation extends CommandOperation {
|
||||
constructor(db, name, options) {
|
||||
super(db, options);
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
_buildCommand() {
|
||||
const name = this.name;
|
||||
const options = this.options;
|
||||
|
||||
const cmd = { create: name };
|
||||
for (let n in options) {
|
||||
if (
|
||||
options[n] != null &&
|
||||
typeof options[n] !== 'function' &&
|
||||
!ILLEGAL_COMMAND_FIELDS.has(n)
|
||||
) {
|
||||
cmd[n] = options[n];
|
||||
}
|
||||
}
|
||||
|
||||
return cmd;
|
||||
}
|
||||
|
||||
execute(callback) {
|
||||
const db = this.db;
|
||||
const name = this.name;
|
||||
const options = this.options;
|
||||
const Collection = loadCollection();
|
||||
|
||||
let listCollectionOptions = Object.assign({ nameOnly: true, strict: false }, options);
|
||||
listCollectionOptions = applyWriteConcern(listCollectionOptions, { db }, listCollectionOptions);
|
||||
|
||||
function done(err) {
|
||||
if (err) {
|
||||
return callback(err);
|
||||
}
|
||||
|
||||
try {
|
||||
callback(
|
||||
null,
|
||||
new Collection(db, db.s.topology, db.databaseName, name, db.s.pkFactory, options)
|
||||
);
|
||||
} catch (err) {
|
||||
callback(err);
|
||||
}
|
||||
}
|
||||
|
||||
const strictMode = listCollectionOptions.strict;
|
||||
if (strictMode) {
|
||||
db.listCollections({ name }, listCollectionOptions)
|
||||
.setReadPreference(ReadPreference.PRIMARY)
|
||||
.toArray((err, collections) => {
|
||||
if (err) {
|
||||
return callback(err);
|
||||
}
|
||||
|
||||
if (collections.length > 0) {
|
||||
return callback(
|
||||
new MongoError(`Collection ${name} already exists. Currently in strict mode.`)
|
||||
);
|
||||
}
|
||||
|
||||
super.execute(done);
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// otherwise just execute the command
|
||||
super.execute(done);
|
||||
}
|
||||
}
|
||||
|
||||
defineAspects(CreateCollectionOperation, Aspect.WRITE_OPERATION);
|
||||
module.exports = CreateCollectionOperation;
|
||||
137
node_modules/mongodb/lib/operations/create_indexes.js
generated
vendored
Normal file
137
node_modules/mongodb/lib/operations/create_indexes.js
generated
vendored
Normal file
@@ -0,0 +1,137 @@
|
||||
'use strict';
|
||||
|
||||
const Aspect = require('./operation').Aspect;
|
||||
const defineAspects = require('./operation').defineAspects;
|
||||
const CommandOperationV2 = require('./command_v2');
|
||||
const MongoError = require('../core').MongoError;
|
||||
const parseIndexOptions = require('../utils').parseIndexOptions;
|
||||
const maxWireVersion = require('../core/utils').maxWireVersion;
|
||||
|
||||
const VALID_INDEX_OPTIONS = new Set([
|
||||
'background',
|
||||
'unique',
|
||||
'name',
|
||||
'partialFilterExpression',
|
||||
'sparse',
|
||||
'expireAfterSeconds',
|
||||
'storageEngine',
|
||||
'collation',
|
||||
|
||||
// text indexes
|
||||
'weights',
|
||||
'default_language',
|
||||
'language_override',
|
||||
'textIndexVersion',
|
||||
|
||||
// 2d-sphere indexes
|
||||
'2dsphereIndexVersion',
|
||||
|
||||
// 2d indexes
|
||||
'bits',
|
||||
'min',
|
||||
'max',
|
||||
|
||||
// geoHaystack Indexes
|
||||
'bucketSize',
|
||||
|
||||
// wildcard indexes
|
||||
'wildcardProjection'
|
||||
]);
|
||||
|
||||
class CreateIndexesOperation extends CommandOperationV2 {
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
constructor(parent, collection, indexes, options) {
|
||||
super(parent, options);
|
||||
this.collection = collection;
|
||||
|
||||
// createIndex can be called with a variety of styles:
|
||||
// coll.createIndex('a');
|
||||
// coll.createIndex({ a: 1 });
|
||||
// coll.createIndex([['a', 1]]);
|
||||
// createIndexes is always called with an array of index spec objects
|
||||
if (!Array.isArray(indexes) || Array.isArray(indexes[0])) {
|
||||
this.onlyReturnNameOfCreatedIndex = true;
|
||||
// TODO: remove in v4 (breaking change); make createIndex return full response as createIndexes does
|
||||
|
||||
const indexParameters = parseIndexOptions(indexes);
|
||||
// Generate the index name
|
||||
const name = typeof options.name === 'string' ? options.name : indexParameters.name;
|
||||
// Set up the index
|
||||
const indexSpec = { name, key: indexParameters.fieldHash };
|
||||
// merge valid index options into the index spec
|
||||
for (let optionName in options) {
|
||||
if (VALID_INDEX_OPTIONS.has(optionName)) {
|
||||
indexSpec[optionName] = options[optionName];
|
||||
}
|
||||
}
|
||||
this.indexes = [indexSpec];
|
||||
return;
|
||||
}
|
||||
|
||||
this.indexes = indexes;
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
execute(server, callback) {
|
||||
const options = this.options;
|
||||
const indexes = this.indexes;
|
||||
|
||||
const serverWireVersion = maxWireVersion(server);
|
||||
|
||||
// Ensure we generate the correct name if the parameter is not set
|
||||
for (let i = 0; i < indexes.length; i++) {
|
||||
// Did the user pass in a collation, check if our write server supports it
|
||||
if (indexes[i].collation && serverWireVersion < 5) {
|
||||
callback(
|
||||
new MongoError(
|
||||
`Server ${server.name}, which reports wire version ${serverWireVersion}, does not support collation`
|
||||
)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (indexes[i].name == null) {
|
||||
const keys = [];
|
||||
|
||||
for (let name in indexes[i].key) {
|
||||
keys.push(`${name}_${indexes[i].key[name]}`);
|
||||
}
|
||||
|
||||
// Set the name
|
||||
indexes[i].name = keys.join('_');
|
||||
}
|
||||
}
|
||||
|
||||
const cmd = { createIndexes: this.collection, indexes };
|
||||
|
||||
if (options.commitQuorum != null) {
|
||||
if (serverWireVersion < 9) {
|
||||
callback(
|
||||
new MongoError('`commitQuorum` option for `createIndexes` not supported on servers < 4.4')
|
||||
);
|
||||
return;
|
||||
}
|
||||
cmd.commitQuorum = options.commitQuorum;
|
||||
}
|
||||
|
||||
// collation is set on each index, it should not be defined at the root
|
||||
this.options.collation = undefined;
|
||||
|
||||
super.executeCommand(server, cmd, (err, result) => {
|
||||
if (err) {
|
||||
callback(err);
|
||||
return;
|
||||
}
|
||||
|
||||
callback(null, this.onlyReturnNameOfCreatedIndex ? indexes[0].name : result);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
defineAspects(CreateIndexesOperation, [Aspect.WRITE_OPERATION, Aspect.EXECUTE_WITH_SELECTION]);
|
||||
|
||||
module.exports = CreateIndexesOperation;
|
||||
167
node_modules/mongodb/lib/operations/cursor_ops.js
generated
vendored
Normal file
167
node_modules/mongodb/lib/operations/cursor_ops.js
generated
vendored
Normal file
@@ -0,0 +1,167 @@
|
||||
'use strict';
|
||||
|
||||
const buildCountCommand = require('./collection_ops').buildCountCommand;
|
||||
const handleCallback = require('../utils').handleCallback;
|
||||
const MongoError = require('../core').MongoError;
|
||||
const push = Array.prototype.push;
|
||||
const CursorState = require('../core/cursor').CursorState;
|
||||
|
||||
/**
|
||||
* Get the count of documents for this cursor.
|
||||
*
|
||||
* @method
|
||||
* @param {Cursor} cursor The Cursor instance on which to count.
|
||||
* @param {boolean} [applySkipLimit=true] Specifies whether the count command apply limit and skip settings should be applied on the cursor or in the provided options.
|
||||
* @param {object} [options] Optional settings. See Cursor.prototype.count for a list of options.
|
||||
* @param {Cursor~countResultCallback} [callback] The result callback.
|
||||
*/
|
||||
function count(cursor, applySkipLimit, opts, callback) {
|
||||
if (applySkipLimit) {
|
||||
if (typeof cursor.cursorSkip() === 'number') opts.skip = cursor.cursorSkip();
|
||||
if (typeof cursor.cursorLimit() === 'number') opts.limit = cursor.cursorLimit();
|
||||
}
|
||||
|
||||
// Ensure we have the right read preference inheritance
|
||||
if (opts.readPreference) {
|
||||
cursor.setReadPreference(opts.readPreference);
|
||||
}
|
||||
|
||||
if (
|
||||
typeof opts.maxTimeMS !== 'number' &&
|
||||
cursor.cmd &&
|
||||
typeof cursor.cmd.maxTimeMS === 'number'
|
||||
) {
|
||||
opts.maxTimeMS = cursor.cmd.maxTimeMS;
|
||||
}
|
||||
|
||||
let options = {};
|
||||
options.skip = opts.skip;
|
||||
options.limit = opts.limit;
|
||||
options.hint = opts.hint;
|
||||
options.maxTimeMS = opts.maxTimeMS;
|
||||
|
||||
// Command
|
||||
options.collectionName = cursor.namespace.collection;
|
||||
|
||||
let command;
|
||||
try {
|
||||
command = buildCountCommand(cursor, cursor.cmd.query, options);
|
||||
} catch (err) {
|
||||
return callback(err);
|
||||
}
|
||||
|
||||
// Set cursor server to the same as the topology
|
||||
cursor.server = cursor.topology.s.coreTopology;
|
||||
|
||||
// Execute the command
|
||||
cursor.topology.command(
|
||||
cursor.namespace.withCollection('$cmd'),
|
||||
command,
|
||||
cursor.options,
|
||||
(err, result) => {
|
||||
callback(err, result ? result.result.n : null);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterates over all the documents for this cursor. See Cursor.prototype.each for more information.
|
||||
*
|
||||
* @method
|
||||
* @deprecated
|
||||
* @param {Cursor} cursor The Cursor instance on which to run.
|
||||
* @param {Cursor~resultCallback} callback The result callback.
|
||||
*/
|
||||
function each(cursor, callback) {
|
||||
if (!callback) throw MongoError.create({ message: 'callback is mandatory', driver: true });
|
||||
if (cursor.isNotified()) return;
|
||||
if (cursor.s.state === CursorState.CLOSED || cursor.isDead()) {
|
||||
return handleCallback(
|
||||
callback,
|
||||
MongoError.create({ message: 'Cursor is closed', driver: true })
|
||||
);
|
||||
}
|
||||
|
||||
if (cursor.s.state === CursorState.INIT) {
|
||||
cursor.s.state = CursorState.OPEN;
|
||||
}
|
||||
|
||||
// Define function to avoid global scope escape
|
||||
let fn = null;
|
||||
// Trampoline all the entries
|
||||
if (cursor.bufferedCount() > 0) {
|
||||
while ((fn = loop(cursor, callback))) fn(cursor, callback);
|
||||
each(cursor, callback);
|
||||
} else {
|
||||
cursor.next((err, item) => {
|
||||
if (err) return handleCallback(callback, err);
|
||||
if (item == null) {
|
||||
return cursor.close({ skipKillCursors: true }, () => handleCallback(callback, null, null));
|
||||
}
|
||||
|
||||
if (handleCallback(callback, null, item) === false) return;
|
||||
each(cursor, callback);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Trampoline emptying the number of retrieved items
|
||||
// without incurring a nextTick operation
|
||||
function loop(cursor, callback) {
|
||||
// No more items we are done
|
||||
if (cursor.bufferedCount() === 0) return;
|
||||
// Get the next document
|
||||
cursor._next(callback);
|
||||
// Loop
|
||||
return loop;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of documents. See Cursor.prototype.toArray for more information.
|
||||
*
|
||||
* @method
|
||||
* @param {Cursor} cursor The Cursor instance from which to get the next document.
|
||||
* @param {Cursor~toArrayResultCallback} [callback] The result callback.
|
||||
*/
|
||||
function toArray(cursor, callback) {
|
||||
const items = [];
|
||||
|
||||
// Reset cursor
|
||||
cursor.rewind();
|
||||
cursor.s.state = CursorState.INIT;
|
||||
|
||||
// Fetch all the documents
|
||||
const fetchDocs = () => {
|
||||
cursor._next((err, doc) => {
|
||||
if (err) {
|
||||
return handleCallback(callback, err);
|
||||
}
|
||||
|
||||
if (doc == null) {
|
||||
return cursor.close({ skipKillCursors: true }, () => handleCallback(callback, null, items));
|
||||
}
|
||||
|
||||
// Add doc to items
|
||||
items.push(doc);
|
||||
|
||||
// Get all buffered objects
|
||||
if (cursor.bufferedCount() > 0) {
|
||||
let docs = cursor.readBufferedDocuments(cursor.bufferedCount());
|
||||
|
||||
// Transform the doc if transform method added
|
||||
if (cursor.s.transforms && typeof cursor.s.transforms.doc === 'function') {
|
||||
docs = docs.map(cursor.s.transforms.doc);
|
||||
}
|
||||
|
||||
push.apply(items, docs);
|
||||
}
|
||||
|
||||
// Attempt a fetch
|
||||
fetchDocs();
|
||||
});
|
||||
};
|
||||
|
||||
fetchDocs();
|
||||
}
|
||||
|
||||
module.exports = { count, each, toArray };
|
||||
467
node_modules/mongodb/lib/operations/db_ops.js
generated
vendored
Normal file
467
node_modules/mongodb/lib/operations/db_ops.js
generated
vendored
Normal file
@@ -0,0 +1,467 @@
|
||||
'use strict';
|
||||
|
||||
const applyWriteConcern = require('../utils').applyWriteConcern;
|
||||
const Code = require('../core').BSON.Code;
|
||||
const debugOptions = require('../utils').debugOptions;
|
||||
const handleCallback = require('../utils').handleCallback;
|
||||
const MongoError = require('../core').MongoError;
|
||||
const parseIndexOptions = require('../utils').parseIndexOptions;
|
||||
const ReadPreference = require('../core').ReadPreference;
|
||||
const toError = require('../utils').toError;
|
||||
const CONSTANTS = require('../constants');
|
||||
const MongoDBNamespace = require('../utils').MongoDBNamespace;
|
||||
|
||||
const debugFields = [
|
||||
'authSource',
|
||||
'w',
|
||||
'wtimeout',
|
||||
'j',
|
||||
'native_parser',
|
||||
'forceServerObjectId',
|
||||
'serializeFunctions',
|
||||
'raw',
|
||||
'promoteLongs',
|
||||
'promoteValues',
|
||||
'promoteBuffers',
|
||||
'bufferMaxEntries',
|
||||
'numberOfRetries',
|
||||
'retryMiliSeconds',
|
||||
'readPreference',
|
||||
'pkFactory',
|
||||
'parentDb',
|
||||
'promiseLibrary',
|
||||
'noListener'
|
||||
];
|
||||
|
||||
/**
|
||||
* Creates an index on the db and collection.
|
||||
* @method
|
||||
* @param {Db} db The Db instance on which to create an index.
|
||||
* @param {string} name Name of the collection to create the index on.
|
||||
* @param {(string|object)} fieldOrSpec Defines the index.
|
||||
* @param {object} [options] Optional settings. See Db.prototype.createIndex for a list of options.
|
||||
* @param {Db~resultCallback} [callback] The command result callback
|
||||
*/
|
||||
function createIndex(db, name, fieldOrSpec, options, callback) {
|
||||
// Get the write concern options
|
||||
let finalOptions = Object.assign({}, { readPreference: ReadPreference.PRIMARY }, options);
|
||||
finalOptions = applyWriteConcern(finalOptions, { db }, options);
|
||||
|
||||
// Ensure we have a callback
|
||||
if (finalOptions.writeConcern && typeof callback !== 'function') {
|
||||
throw MongoError.create({
|
||||
message: 'Cannot use a writeConcern without a provided callback',
|
||||
driver: true
|
||||
});
|
||||
}
|
||||
|
||||
// Did the user destroy the topology
|
||||
if (db.serverConfig && db.serverConfig.isDestroyed())
|
||||
return callback(new MongoError('topology was destroyed'));
|
||||
|
||||
// Attempt to run using createIndexes command
|
||||
createIndexUsingCreateIndexes(db, name, fieldOrSpec, finalOptions, (err, result) => {
|
||||
if (err == null) return handleCallback(callback, err, result);
|
||||
|
||||
/**
|
||||
* The following errors mean that the server recognized `createIndex` as a command so we don't need to fallback to an insert:
|
||||
* 67 = 'CannotCreateIndex' (malformed index options)
|
||||
* 85 = 'IndexOptionsConflict' (index already exists with different options)
|
||||
* 86 = 'IndexKeySpecsConflict' (index already exists with the same name)
|
||||
* 11000 = 'DuplicateKey' (couldn't build unique index because of dupes)
|
||||
* 11600 = 'InterruptedAtShutdown' (interrupted at shutdown)
|
||||
* 197 = 'InvalidIndexSpecificationOption' (`_id` with `background: true`)
|
||||
*/
|
||||
if (
|
||||
err.code === 67 ||
|
||||
err.code === 11000 ||
|
||||
err.code === 85 ||
|
||||
err.code === 86 ||
|
||||
err.code === 11600 ||
|
||||
err.code === 197
|
||||
) {
|
||||
return handleCallback(callback, err, result);
|
||||
}
|
||||
|
||||
// Create command
|
||||
const doc = createCreateIndexCommand(db, name, fieldOrSpec, options);
|
||||
// Set no key checking
|
||||
finalOptions.checkKeys = false;
|
||||
// Insert document
|
||||
db.s.topology.insert(
|
||||
db.s.namespace.withCollection(CONSTANTS.SYSTEM_INDEX_COLLECTION),
|
||||
doc,
|
||||
finalOptions,
|
||||
(err, result) => {
|
||||
if (callback == null) return;
|
||||
if (err) return handleCallback(callback, err);
|
||||
if (result == null) return handleCallback(callback, null, null);
|
||||
if (result.result.writeErrors)
|
||||
return handleCallback(callback, MongoError.create(result.result.writeErrors[0]), null);
|
||||
handleCallback(callback, null, doc.name);
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// Add listeners to topology
|
||||
function createListener(db, e, object) {
|
||||
function listener(err) {
|
||||
if (object.listeners(e).length > 0) {
|
||||
object.emit(e, err, db);
|
||||
|
||||
// Emit on all associated db's if available
|
||||
for (let i = 0; i < db.s.children.length; i++) {
|
||||
db.s.children[i].emit(e, err, db.s.children[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return listener;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures that an index exists. If it does not, creates it.
|
||||
*
|
||||
* @method
|
||||
* @param {Db} db The Db instance on which to ensure the index.
|
||||
* @param {string} name The index name
|
||||
* @param {(string|object)} fieldOrSpec Defines the index.
|
||||
* @param {object} [options] Optional settings. See Db.prototype.ensureIndex for a list of options.
|
||||
* @param {Db~resultCallback} [callback] The command result callback
|
||||
*/
|
||||
function ensureIndex(db, name, fieldOrSpec, options, callback) {
|
||||
// Get the write concern options
|
||||
const finalOptions = applyWriteConcern({}, { db }, options);
|
||||
// Create command
|
||||
const selector = createCreateIndexCommand(db, name, fieldOrSpec, options);
|
||||
const index_name = selector.name;
|
||||
|
||||
// Did the user destroy the topology
|
||||
if (db.serverConfig && db.serverConfig.isDestroyed())
|
||||
return callback(new MongoError('topology was destroyed'));
|
||||
|
||||
// Merge primary readPreference
|
||||
finalOptions.readPreference = ReadPreference.PRIMARY;
|
||||
|
||||
// Check if the index already exists
|
||||
indexInformation(db, name, finalOptions, (err, indexInformation) => {
|
||||
if (err != null && err.code !== 26) return handleCallback(callback, err, null);
|
||||
// If the index does not exist, create it
|
||||
if (indexInformation == null || !indexInformation[index_name]) {
|
||||
createIndex(db, name, fieldOrSpec, options, callback);
|
||||
} else {
|
||||
if (typeof callback === 'function') return handleCallback(callback, null, index_name);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluate JavaScript on the server
|
||||
*
|
||||
* @method
|
||||
* @param {Db} db The Db instance.
|
||||
* @param {Code} code JavaScript to execute on server.
|
||||
* @param {(object|array)} parameters The parameters for the call.
|
||||
* @param {object} [options] Optional settings. See Db.prototype.eval for a list of options.
|
||||
* @param {Db~resultCallback} [callback] The results callback
|
||||
* @deprecated Eval is deprecated on MongoDB 3.2 and forward
|
||||
*/
|
||||
function evaluate(db, code, parameters, options, callback) {
|
||||
let finalCode = code;
|
||||
let finalParameters = [];
|
||||
|
||||
// Did the user destroy the topology
|
||||
if (db.serverConfig && db.serverConfig.isDestroyed())
|
||||
return callback(new MongoError('topology was destroyed'));
|
||||
|
||||
// If not a code object translate to one
|
||||
if (!(finalCode && finalCode._bsontype === 'Code')) finalCode = new Code(finalCode);
|
||||
// Ensure the parameters are correct
|
||||
if (parameters != null && !Array.isArray(parameters) && typeof parameters !== 'function') {
|
||||
finalParameters = [parameters];
|
||||
} else if (parameters != null && Array.isArray(parameters) && typeof parameters !== 'function') {
|
||||
finalParameters = parameters;
|
||||
}
|
||||
|
||||
// Create execution selector
|
||||
let cmd = { $eval: finalCode, args: finalParameters };
|
||||
// Check if the nolock parameter is passed in
|
||||
if (options['nolock']) {
|
||||
cmd['nolock'] = options['nolock'];
|
||||
}
|
||||
|
||||
// Set primary read preference
|
||||
options.readPreference = new ReadPreference(ReadPreference.PRIMARY);
|
||||
|
||||
// Execute the command
|
||||
executeCommand(db, cmd, options, (err, result) => {
|
||||
if (err) return handleCallback(callback, err, null);
|
||||
if (result && result.ok === 1) return handleCallback(callback, null, result.retval);
|
||||
if (result)
|
||||
return handleCallback(
|
||||
callback,
|
||||
MongoError.create({ message: `eval failed: ${result.errmsg}`, driver: true }),
|
||||
null
|
||||
);
|
||||
handleCallback(callback, err, result);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a command
|
||||
*
|
||||
* @method
|
||||
* @param {Db} db The Db instance on which to execute the command.
|
||||
* @param {object} command The command hash
|
||||
* @param {object} [options] Optional settings. See Db.prototype.command for a list of options.
|
||||
* @param {Db~resultCallback} [callback] The command result callback
|
||||
*/
|
||||
function executeCommand(db, command, options, callback) {
|
||||
// Did the user destroy the topology
|
||||
if (db.serverConfig && db.serverConfig.isDestroyed())
|
||||
return callback(new MongoError('topology was destroyed'));
|
||||
// Get the db name we are executing against
|
||||
const dbName = options.dbName || options.authdb || db.databaseName;
|
||||
|
||||
// Convert the readPreference if its not a write
|
||||
options.readPreference = ReadPreference.resolve(db, options);
|
||||
|
||||
// Debug information
|
||||
if (db.s.logger.isDebug())
|
||||
db.s.logger.debug(
|
||||
`executing command ${JSON.stringify(
|
||||
command
|
||||
)} against ${dbName}.$cmd with options [${JSON.stringify(
|
||||
debugOptions(debugFields, options)
|
||||
)}]`
|
||||
);
|
||||
|
||||
// Execute command
|
||||
db.s.topology.command(db.s.namespace.withCollection('$cmd'), command, options, (err, result) => {
|
||||
if (err) return handleCallback(callback, err);
|
||||
if (options.full) return handleCallback(callback, null, result);
|
||||
handleCallback(callback, null, result.result);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a command on the database as admin.
|
||||
*
|
||||
* @method
|
||||
* @param {Db} db The Db instance on which to execute the command.
|
||||
* @param {object} command The command hash
|
||||
* @param {object} [options] Optional settings. See Db.prototype.executeDbAdminCommand for a list of options.
|
||||
* @param {Db~resultCallback} [callback] The command result callback
|
||||
*/
|
||||
function executeDbAdminCommand(db, command, options, callback) {
|
||||
const namespace = new MongoDBNamespace('admin', '$cmd');
|
||||
|
||||
db.s.topology.command(namespace, command, options, (err, result) => {
|
||||
// Did the user destroy the topology
|
||||
if (db.serverConfig && db.serverConfig.isDestroyed()) {
|
||||
return callback(new MongoError('topology was destroyed'));
|
||||
}
|
||||
|
||||
if (err) return handleCallback(callback, err);
|
||||
handleCallback(callback, null, result.result);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves this collections index info.
|
||||
*
|
||||
* @method
|
||||
* @param {Db} db The Db instance on which to retrieve the index info.
|
||||
* @param {string} name The name of the collection.
|
||||
* @param {object} [options] Optional settings. See Db.prototype.indexInformation for a list of options.
|
||||
* @param {Db~resultCallback} [callback] The command result callback
|
||||
*/
|
||||
function indexInformation(db, name, options, callback) {
|
||||
// If we specified full information
|
||||
const full = options['full'] == null ? false : options['full'];
|
||||
|
||||
// Did the user destroy the topology
|
||||
if (db.serverConfig && db.serverConfig.isDestroyed())
|
||||
return callback(new MongoError('topology was destroyed'));
|
||||
// Process all the results from the index command and collection
|
||||
function processResults(indexes) {
|
||||
// Contains all the information
|
||||
let info = {};
|
||||
// Process all the indexes
|
||||
for (let i = 0; i < indexes.length; i++) {
|
||||
const index = indexes[i];
|
||||
// Let's unpack the object
|
||||
info[index.name] = [];
|
||||
for (let name in index.key) {
|
||||
info[index.name].push([name, index.key[name]]);
|
||||
}
|
||||
}
|
||||
|
||||
return info;
|
||||
}
|
||||
|
||||
// Get the list of indexes of the specified collection
|
||||
db.collection(name)
|
||||
.listIndexes(options)
|
||||
.toArray((err, indexes) => {
|
||||
if (err) return callback(toError(err));
|
||||
if (!Array.isArray(indexes)) return handleCallback(callback, null, []);
|
||||
if (full) return handleCallback(callback, null, indexes);
|
||||
handleCallback(callback, null, processResults(indexes));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the current profiling information for MongoDB
|
||||
*
|
||||
* @method
|
||||
* @param {Db} db The Db instance on which to retrieve the profiling info.
|
||||
* @param {Object} [options] Optional settings. See Db.protoype.profilingInfo for a list of options.
|
||||
* @param {Db~resultCallback} [callback] The command result callback.
|
||||
* @deprecated Query the system.profile collection directly.
|
||||
*/
|
||||
function profilingInfo(db, options, callback) {
|
||||
try {
|
||||
db.collection('system.profile')
|
||||
.find({}, options)
|
||||
.toArray(callback);
|
||||
} catch (err) {
|
||||
return callback(err, null);
|
||||
}
|
||||
}
|
||||
|
||||
// Validate the database name
|
||||
function validateDatabaseName(databaseName) {
|
||||
if (typeof databaseName !== 'string')
|
||||
throw MongoError.create({ message: 'database name must be a string', driver: true });
|
||||
if (databaseName.length === 0)
|
||||
throw MongoError.create({ message: 'database name cannot be the empty string', driver: true });
|
||||
if (databaseName === '$external') return;
|
||||
|
||||
const invalidChars = [' ', '.', '$', '/', '\\'];
|
||||
for (let i = 0; i < invalidChars.length; i++) {
|
||||
if (databaseName.indexOf(invalidChars[i]) !== -1)
|
||||
throw MongoError.create({
|
||||
message: "database names cannot contain the character '" + invalidChars[i] + "'",
|
||||
driver: true
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the command object for Db.prototype.createIndex.
|
||||
*
|
||||
* @param {Db} db The Db instance on which to create the command.
|
||||
* @param {string} name Name of the collection to create the index on.
|
||||
* @param {(string|object)} fieldOrSpec Defines the index.
|
||||
* @param {Object} [options] Optional settings. See Db.prototype.createIndex for a list of options.
|
||||
* @return {Object} The insert command object.
|
||||
*/
|
||||
function createCreateIndexCommand(db, name, fieldOrSpec, options) {
|
||||
const indexParameters = parseIndexOptions(fieldOrSpec);
|
||||
const fieldHash = indexParameters.fieldHash;
|
||||
|
||||
// Generate the index name
|
||||
const indexName = typeof options.name === 'string' ? options.name : indexParameters.name;
|
||||
const selector = {
|
||||
ns: db.s.namespace.withCollection(name).toString(),
|
||||
key: fieldHash,
|
||||
name: indexName
|
||||
};
|
||||
|
||||
// Ensure we have a correct finalUnique
|
||||
const finalUnique = options == null || 'object' === typeof options ? false : options;
|
||||
// Set up options
|
||||
options = options == null || typeof options === 'boolean' ? {} : options;
|
||||
|
||||
// Add all the options
|
||||
const keysToOmit = Object.keys(selector);
|
||||
for (let optionName in options) {
|
||||
if (keysToOmit.indexOf(optionName) === -1) {
|
||||
selector[optionName] = options[optionName];
|
||||
}
|
||||
}
|
||||
|
||||
if (selector['unique'] == null) selector['unique'] = finalUnique;
|
||||
|
||||
// Remove any write concern operations
|
||||
const removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference', 'session'];
|
||||
for (let i = 0; i < removeKeys.length; i++) {
|
||||
delete selector[removeKeys[i]];
|
||||
}
|
||||
|
||||
// Return the command creation selector
|
||||
return selector;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create index using the createIndexes command.
|
||||
*
|
||||
* @param {Db} db The Db instance on which to execute the command.
|
||||
* @param {string} name Name of the collection to create the index on.
|
||||
* @param {(string|object)} fieldOrSpec Defines the index.
|
||||
* @param {Object} [options] Optional settings. See Db.prototype.createIndex for a list of options.
|
||||
* @param {Db~resultCallback} [callback] The command result callback.
|
||||
*/
|
||||
function createIndexUsingCreateIndexes(db, name, fieldOrSpec, options, callback) {
|
||||
// Build the index
|
||||
const indexParameters = parseIndexOptions(fieldOrSpec);
|
||||
// Generate the index name
|
||||
const indexName = typeof options.name === 'string' ? options.name : indexParameters.name;
|
||||
// Set up the index
|
||||
const indexes = [{ name: indexName, key: indexParameters.fieldHash }];
|
||||
// merge all the options
|
||||
const keysToOmit = Object.keys(indexes[0]).concat([
|
||||
'writeConcern',
|
||||
'w',
|
||||
'wtimeout',
|
||||
'j',
|
||||
'fsync',
|
||||
'readPreference',
|
||||
'session'
|
||||
]);
|
||||
|
||||
for (let optionName in options) {
|
||||
if (keysToOmit.indexOf(optionName) === -1) {
|
||||
indexes[0][optionName] = options[optionName];
|
||||
}
|
||||
}
|
||||
|
||||
// Get capabilities
|
||||
const capabilities = db.s.topology.capabilities();
|
||||
|
||||
// Did the user pass in a collation, check if our write server supports it
|
||||
if (indexes[0].collation && capabilities && !capabilities.commandsTakeCollation) {
|
||||
// Create a new error
|
||||
const error = new MongoError('server/primary/mongos does not support collation');
|
||||
error.code = 67;
|
||||
// Return the error
|
||||
return callback(error);
|
||||
}
|
||||
|
||||
// Create command, apply write concern to command
|
||||
const cmd = applyWriteConcern({ createIndexes: name, indexes }, { db }, options);
|
||||
|
||||
// ReadPreference primary
|
||||
options.readPreference = ReadPreference.PRIMARY;
|
||||
|
||||
// Build the command
|
||||
executeCommand(db, cmd, options, (err, result) => {
|
||||
if (err) return handleCallback(callback, err, null);
|
||||
if (result.ok === 0) return handleCallback(callback, toError(result), null);
|
||||
// Return the indexName for backward compatibility
|
||||
handleCallback(callback, null, indexName);
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
createListener,
|
||||
createIndex,
|
||||
ensureIndex,
|
||||
evaluate,
|
||||
executeCommand,
|
||||
executeDbAdminCommand,
|
||||
indexInformation,
|
||||
profilingInfo,
|
||||
validateDatabaseName
|
||||
};
|
||||
25
node_modules/mongodb/lib/operations/delete_many.js
generated
vendored
Normal file
25
node_modules/mongodb/lib/operations/delete_many.js
generated
vendored
Normal file
@@ -0,0 +1,25 @@
|
||||
'use strict';
|
||||
|
||||
const OperationBase = require('./operation').OperationBase;
|
||||
const deleteCallback = require('./common_functions').deleteCallback;
|
||||
const removeDocuments = require('./common_functions').removeDocuments;
|
||||
|
||||
class DeleteManyOperation extends OperationBase {
|
||||
constructor(collection, filter, options) {
|
||||
super(options);
|
||||
|
||||
this.collection = collection;
|
||||
this.filter = filter;
|
||||
}
|
||||
|
||||
execute(callback) {
|
||||
const coll = this.collection;
|
||||
const filter = this.filter;
|
||||
const options = this.options;
|
||||
|
||||
options.single = false;
|
||||
removeDocuments(coll, filter, options, (err, r) => deleteCallback(err, r, callback));
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = DeleteManyOperation;
|
||||
25
node_modules/mongodb/lib/operations/delete_one.js
generated
vendored
Normal file
25
node_modules/mongodb/lib/operations/delete_one.js
generated
vendored
Normal file
@@ -0,0 +1,25 @@
|
||||
'use strict';
|
||||
|
||||
const OperationBase = require('./operation').OperationBase;
|
||||
const deleteCallback = require('./common_functions').deleteCallback;
|
||||
const removeDocuments = require('./common_functions').removeDocuments;
|
||||
|
||||
class DeleteOneOperation extends OperationBase {
|
||||
constructor(collection, filter, options) {
|
||||
super(options);
|
||||
|
||||
this.collection = collection;
|
||||
this.filter = filter;
|
||||
}
|
||||
|
||||
execute(callback) {
|
||||
const coll = this.collection;
|
||||
const filter = this.filter;
|
||||
const options = this.options;
|
||||
|
||||
options.single = true;
|
||||
removeDocuments(coll, filter, options, (err, r) => deleteCallback(err, r, callback));
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = DeleteOneOperation;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user