@opensearch-project/opensearch 1.0.2 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/ADMINS.md CHANGED
@@ -1,3 +1,9 @@
1
+ - [Overview](#overview)
2
+ - [Current Admins](#current-admins)
3
+ - [Admin Responsibilities](#admin-responsibilities)
4
+ - [Prioritize Security](#prioritize-security)
5
+ - [Enforce Code of Conduct](#enforce-code-of-conduct)
6
+ - [Adopt Organizational Best Practices](#adopt-organizational-best-practices)
1
7
  ## Overview
2
8
 
3
9
  This document explains who the admins are (see below), what they do in this repo, and how they should be doing it. If you're interested in becoming a maintainer, see [MAINTAINERS](MAINTAINERS.md). If you're interested in contributing, see [CONTRIBUTING](CONTRIBUTING.md).
@@ -0,0 +1,18 @@
1
+ - [Compatibility with OpenSearch](#compatibility-with-opensearch)
2
+
3
+ ## Compatibility with OpenSearch
4
+
5
+ The below matrix shows the compatibility of the [`opensearch-js`](https://www.npmjs.com/package/@opensearch-project/opensearch) with versions of [`OpenSearch`](https://opensearch.org/downloads.html#opensearch).
6
+
7
+ | OpenSearch Version | Client Version |
8
+ | --- | --- |
9
+ | 1.0.0 | 1.0.0 |
10
+ | 1.0.1 | 1.0.0 |
11
+ | 1.1.0 | 1.1.0 |
12
+ | 1.2.0 | 1.1.0 |
13
+ | 1.2.1 | 1.1.0 |
14
+ | 1.2.2 | 1.1.0 |
15
+ | 1.2.3 | 1.1.0 |
16
+ | 1.2.4 | 1.1.0 |
17
+ | 1.3.0 | 1.1.0 |
18
+ | 1.3.1 | 1.1.0 |
@@ -1,3 +1,12 @@
1
+ - [Developer Guide](#developer-guide)
2
+ - [Getting Started](#getting-started)
3
+ - [Git Clone OpenSearch Node.js Client Repository](#git-clone-opensearch-nodejs-client-repository)
4
+ - [Install Prerequisites](#install-prerequisites)
5
+ - [Node.js](#nodejs)
6
+ - [Docker](#docker)
7
+ - [Unit Testing](#unit-testing)
8
+ - [Integration Testing](#integration-testing)
9
+ - [Execute integration tests from your terminal](#execute-integration-tests-from-your-terminal)
1
10
  # Developer Guide
2
11
 
3
12
  So you want to contribute code to the OpenSearch Node.js Client? Excellent! We're glad you're here. Here's what you need to do:
package/MAINTAINERS.md CHANGED
@@ -1,15 +1,16 @@
1
1
  - [Overview](#overview)
2
2
  - [Current Maintainers](#current-maintainers)
3
3
  - [Maintainer Responsibilities](#maintainer-responsibilities)
4
- - [Uphold Code of Conduct](#uphold-code-of-conduct)
5
- - [Prioritize Security](#prioritize-security)
6
- - [Review Pull Requests](#review-pull-requests)
7
- - [Triage Open Issues](#triage-open-issues)
8
- - [Be Responsive](#be-responsive)
9
- - [Maintain Overall Health of the Repo](#maintain-overall-health-of-the-repo)
10
- - [Use Semver](#use-semver)
11
- - [Release Frequently](#release-frequently)
12
- - [Promote Other Maintainers](#promote-other-maintainers)
4
+ - [Uphold Code of Conduct](#uphold-code-of-conduct)
5
+ - [Prioritize Security](#prioritize-security)
6
+ - [Review Pull Requests](#review-pull-requests)
7
+ - [Triage Open Issues](#triage-open-issues)
8
+ - [Backports](#backports)
9
+ - [Be Responsive](#be-responsive)
10
+ - [Maintain Overall Health of the Repo](#maintain-overall-health-of-the-repo)
11
+ - [Use Semver](#use-semver)
12
+ - [Release Frequently](#release-frequently)
13
+ - [Promote Other Maintainers](#promote-other-maintainers)
13
14
 
14
15
  ## Overview
15
16
 
@@ -52,6 +53,10 @@ All repositories in this organization have a standard set of labels, including `
52
53
 
53
54
  Use labels to target an issue or a PR for a given release, add `help wanted` to good issues for new community members, and `blocker` for issues that scare you or need immediate attention. Request for more information from a submitter if an issue is not clear. Create new labels as needed by the project.
54
55
 
56
+ ### Backports
57
+
58
+ The Github workflow in [backport.yml](.github/workflows/backport.yml) creates backport PRs automatically when the original PR with an appropriate label `backport <backport-branch-name>` is merged to main. To backport a PR to `1.x`, add a label `backport 1.x` to the PR, once this PR is merged to main, the workflow will create a backport PR to the `1.x` branch.
59
+
55
60
  ### Be Responsive
56
61
 
57
62
  Respond to enhancement requests, and forum posts. Allocate time to reviewing and commenting on issues and conversations as they come in.
package/README.md CHANGED
@@ -10,24 +10,26 @@
10
10
  OpenSearch Node.js client
11
11
 
12
12
  - [Welcome!](#welcome)
13
+ - [Example use](#example-use)
14
+ - [Setup](#setup)
15
+ - [Sample code](#sample-code)
13
16
  - [Project Resources](#project-resources)
14
17
  - [Code of Conduct](#code-of-conduct)
15
18
  - [License](#license)
16
19
  - [Copyright](#copyright)
17
-
18
20
  ## Welcome!
19
21
 
20
22
  **[opensearch-js](https://www.npmjs.com/package/@opensearch-project/opensearch)** is [a community-driven, open source fork](https://aws.amazon.com/blogs/opensource/introducing-opensearch/) of elasticsearch-js licensed under the [Apache v2.0 License](LICENSE.txt). For more information, see [opensearch.org](https://opensearch.org/).
21
23
 
22
24
  ## Example use
25
+
23
26
  The OpenSearch JavaScript client provides a safer and easier way to interact with your OpenSearch cluster. Rather than using OpenSearch from the browser and potentially exposing your data to the public, you can build an OpenSearch client that takes care of sending requests to your cluster.
24
27
 
25
28
  The client contains a library of APIs that let you perform different operations on your cluster and return a standard response body. The example here demonstrates some basic operations like creating an index, adding documents, and searching your data.
26
29
 
27
-
28
30
  ### Setup
29
31
 
30
- # To add the client to your project, install it with npm:
32
+ To add the client to your project, install it with npm:
31
33
 
32
34
  ```bash
33
35
  npm i @opensearch-project/opensearch
@@ -41,115 +43,10 @@ Then require the client:
41
43
  const { Client } = require('@opensearch-project/opensearch')
42
44
  ```
43
45
 
46
+ ## Sample code
44
47
 
45
- ### Sample code
48
+ Please see the [USER_GUIDE](USER_GUIDE.md) for code snippets.
46
49
 
47
- ```javascript
48
- 'use strict';
49
-
50
- var host = 'localhost';
51
- var protocol = 'https';
52
- var port = 9200;
53
- var auth = 'admin:admin'; // For testing only. Don't store credentials in code.
54
- var ca_certs_path = '/full/path/to/root-ca.pem';
55
-
56
- // Optional client certificates if you don't want to use HTTP basic authentication.
57
- // var client_cert_path = '/full/path/to/client.pem'
58
- // var client_key_path = '/full/path/to/client-key.pem'
59
-
60
- // Create a client with SSL/TLS enabled.
61
- var { Client } = require('@opensearch-project/opensearch');
62
- var fs = require('fs');
63
- var client = new Client({
64
- node: protocol + '://' + auth + '@' + host + ':' + port,
65
- ssl: {
66
- ca: fs.readFileSync(ca_certs_path),
67
- // You can turn off certificate verification (rejectUnauthorized: false) if you're using self-signed certificates with a hostname mismatch.
68
- // cert: fs.readFileSync(client_cert_path),
69
- // key: fs.readFileSync(client_key_path)
70
- }
71
- })
72
-
73
- async function search() {
74
-
75
- // Create an index with non-default settings.
76
- var index_name = 'books'
77
- var settings = {
78
- 'settings': {
79
- 'index': {
80
- 'number_of_shards': 4,
81
- 'number_of_replicas': 3
82
- }
83
- }
84
- }
85
-
86
- var response = await client.indices.create({
87
- index: index_name,
88
- body: settings
89
- })
90
-
91
- console.log('Creating index:')
92
- console.log(response.body)
93
-
94
- // Add a document to the index.
95
- var document = {
96
- 'title': 'The Outsider',
97
- 'author': 'Stephen King',
98
- 'year': '2018',
99
- 'genre': 'Crime fiction'
100
- }
101
-
102
- var id = '1'
103
-
104
- var response = await client.index({
105
- id: id,
106
- index: index_name,
107
- body: document,
108
- refresh: true
109
- })
110
-
111
- console.log('Adding document:')
112
- console.log(response.body)
113
-
114
- // Search for the document.
115
- var query = {
116
- 'query': {
117
- 'match': {
118
- 'title': {
119
- 'query': 'The Outsider'
120
- }
121
- }
122
- }
123
- }
124
-
125
- var response = await client.search({
126
- index: index_name,
127
- body: query
128
- })
129
-
130
- console.log('Search results:')
131
- console.log(response.body.hits)
132
-
133
- // Delete the document.
134
- var response = await client.delete({
135
- index: index_name,
136
- id: id
137
- })
138
-
139
- console.log('Deleting document:')
140
- console.log(response.body)
141
-
142
- // Delete the index.
143
- var response = await client.indices.delete({
144
- index: index_name
145
- })
146
-
147
- console.log('Deleting index:')
148
- console.log(response.body)
149
- }
150
-
151
- search().catch(console.log)
152
- ```
153
50
 
154
51
  ## Project Resources
155
52
 
package/RELEASING.md CHANGED
@@ -31,4 +31,10 @@ Repositories create consistent release labels, such as `v1.0.0`, `v1.1.0` and `v
31
31
 
32
32
  ## Releasing
33
33
 
34
- The release process is standard across repositories in this org and is run by a release manager volunteering from amongst [MAINTAINERS](MAINTAINERS.md).
34
+ The release process is standard across repositories in this org and is run by a release manager volunteering from amongst [maintainers](MAINTAINERS.md).
35
+
36
+ 1. Create a tag, e.g. v2.1.0, and push it to the GitHub repo.
37
+ 1. The [release-drafter.yml](.github/workflows/release-drafter.yml) will be automatically kicked off and a draft release will be created.
38
+ 1. This draft release triggers the [jenkins release workflow](https://build.ci.opensearch.org/job/opensearch-js-release/) as a result of which opensearch-js client is released on [npmjs](https://www.npmjs.com/package/@opensearch-project/opensearch).
39
+ 1. Once the above release workflow is successful, the drafted release on GitHub is published automatically.
40
+ 1. Increment "version" in package.json to the next patch release, e.g. v2.1.1. See [example](https://github.com/opensearch-project/opensearch-js/pull/318)
package/USER_GUIDE.md ADDED
@@ -0,0 +1,201 @@
1
+ # User Guide
2
+
3
+ - [User Guide](#user-guide)
4
+ - [Initializing a Client](#initializing-a-client)
5
+ - [Authenticate with Amazon OpenSearch Service](#authenticate-with-amazon-opensearch-service)
6
+ - [Using AWS V2 SDK](#using-aws-v2-sdk)
7
+ - [Using AWS V3 SDK](#using-aws-v3-sdk)
8
+ - [Create an Index](#create-an-index)
9
+ - [Add a Document to the Index](#add-a-document-to-the-index)
10
+ - [Search for the Document](#search-for-the-document)
11
+ - [Delete the document](#delete-the-document)
12
+ - [Delete the index](#delete-the-index)
13
+
14
+ ## Initializing a Client
15
+ ```javascript
16
+ 'use strict';
17
+
18
+ var host = 'localhost';
19
+ var protocol = 'https';
20
+ var port = 9200;
21
+ var auth = 'admin:admin'; // For testing only. Don't store credentials in code.
22
+ var ca_certs_path = '/full/path/to/root-ca.pem';
23
+
24
+ // Optional client certificates if you don't want to use HTTP basic authentication.
25
+ // var client_cert_path = '/full/path/to/client.pem'
26
+ // var client_key_path = '/full/path/to/client-key.pem'
27
+
28
+ // Create a client with SSL/TLS enabled.
29
+ var { Client } = require('@opensearch-project/opensearch');
30
+ var fs = require('fs');
31
+ var client = new Client({
32
+ node: protocol + '://' + auth + '@' + host + ':' + port,
33
+ ssl: {
34
+ ca: fs.readFileSync(ca_certs_path),
35
+ // You can turn off certificate verification (rejectUnauthorized: false) if you're using self-signed certificates with a hostname mismatch.
36
+ // cert: fs.readFileSync(client_cert_path),
37
+ // key: fs.readFileSync(client_key_path)
38
+ },
39
+ });
40
+ ```
41
+
42
+ ### Authenticate with Amazon OpenSearch Service
43
+
44
+ #### Using AWS V2 SDK
45
+
46
+ ```javascript
47
+ const AWS = require('aws-sdk'); // V2 SDK.
48
+ const { Client } = require('@opensearch-project/opensearch');
49
+ const { AwsSigv4Signer } = require('@opensearch-project/opensearch/aws');
50
+
51
+ const client = new Client({
52
+ ...AwsSigv4Signer({
53
+ region: 'us-west-2',
54
+ service: 'es', // 'aoss' for OpenSearch Serverless
55
+ // Must return a Promise that resolve to an AWS.Credentials object.
56
+ // This function is used to acquire the credentials when the client start and
57
+ // when the credentials are expired.
58
+ // The Client will refresh the Credentials only when they are expired.
59
+ // With AWS SDK V2, Credentials.refreshPromise is used when available to refresh the credentials.
60
+
61
+ // Example with AWS SDK V2:
62
+ getCredentials: () =>
63
+ new Promise((resolve, reject) => {
64
+ // Any other method to acquire a new Credentials object can be used.
65
+ AWS.config.getCredentials((err, credentials) => {
66
+ if (err) {
67
+ reject(err);
68
+ } else {
69
+ resolve(credentials);
70
+ }
71
+ });
72
+ }),
73
+ }),
74
+ node: 'https://search-xxx.region.es.amazonaws.com', // OpenSearch domain URL
75
+ // node: "https://xxx.region.aoss.amazonaws.com" for OpenSearch Serverless
76
+ });
77
+ ```
78
+
79
+ #### Using AWS V3 SDK
80
+
81
+ ```javascript
82
+ const { defaultProvider } = require("@aws-sdk/credential-provider-node"); // V3 SDK.
83
+ const { Client } = require('@opensearch-project/opensearch');
84
+ const { AwsSigv4Signer } = require('@opensearch-project/opensearch/aws');
85
+
86
+ const client = new Client({
87
+ ...AwsSigv4Signer({
88
+ region: 'us-east-1',
89
+ service: 'es', // 'aoss' for OpenSearch Serverless
90
+ // Must return a Promise that resolve to an AWS.Credentials object.
91
+ // This function is used to acquire the credentials when the client start and
92
+ // when the credentials are expired.
93
+ // The Client will refresh the Credentials only when they are expired.
94
+ // With AWS SDK V2, Credentials.refreshPromise is used when available to refresh the credentials.
95
+
96
+ // Example with AWS SDK V3:
97
+ getCredentials: () => {
98
+ // Any other method to acquire a new Credentials object can be used.
99
+ const credentialsProvider = defaultProvider();
100
+ return credentialsProvider();
101
+ },
102
+ }),
103
+ node: 'https://search-xxx.region.es.amazonaws.com', // OpenSearch domain URL
104
+ // node: "https://xxx.region.aoss.amazonaws.com" for OpenSearch Serverless
105
+ });
106
+ ```
107
+
108
+ ## Create an Index
109
+
110
+ ```javascript
111
+ console.log('Creating index:');
112
+
113
+ var index_name = 'books';
114
+ var settings = {
115
+ settings: {
116
+ index: {
117
+ number_of_shards: 4,
118
+ number_of_replicas: 3,
119
+ },
120
+ },
121
+ };
122
+
123
+ var response = await client.indices.create({
124
+ index: index_name,
125
+ body: settings,
126
+ });
127
+
128
+ console.log(response.body);
129
+ ```
130
+
131
+ ## Add a Document to the Index
132
+
133
+ ```javascript
134
+ console.log('Adding document:');
135
+
136
+ var document = {
137
+ title: 'The Outsider',
138
+ author: 'Stephen King',
139
+ year: '2018',
140
+ genre: 'Crime fiction',
141
+ };
142
+
143
+ var id = '1';
144
+
145
+ var response = await client.index({
146
+ id: id,
147
+ index: index_name,
148
+ body: document,
149
+ refresh: true,
150
+ });
151
+
152
+ console.log(response.body);
153
+ ```
154
+
155
+ ## Search for the Document
156
+
157
+ ```javascript
158
+ console.log('Search results:');
159
+
160
+ var query = {
161
+ query: {
162
+ match: {
163
+ title: {
164
+ query: 'The Outsider',
165
+ },
166
+ },
167
+ },
168
+ };
169
+
170
+ var response = await client.search({
171
+ index: index_name,
172
+ body: query,
173
+ });
174
+
175
+ console.log(response.body.hits);
176
+ ```
177
+
178
+ ## Delete the document
179
+
180
+ ```javascript
181
+ console.log('Deleting document:');
182
+
183
+ var response = await client.delete({
184
+ index: index_name,
185
+ id: id,
186
+ });
187
+
188
+ console.log(response.body);
189
+ ```
190
+
191
+ ## Delete the index
192
+
193
+ ```javascript
194
+ console.log('Deleting index:');
195
+
196
+ var response = await client.indices.delete({
197
+ index: index_name,
198
+ });
199
+
200
+ console.log(response.body);
201
+ ```
package/index.d.ts CHANGED
@@ -126,6 +126,10 @@ interface ClientOptions {
126
126
  password?: string;
127
127
  };
128
128
  disablePrototypePoisoningProtection?: boolean | 'proto' | 'constructor';
129
+ memoryCircuitBreaker?: {
130
+ enabled: boolean;
131
+ maxPercentage: number;
132
+ }
129
133
  }
130
134
 
131
135
  declare class Client {
package/index.js CHANGED
@@ -178,7 +178,8 @@ class Client extends OpenSearchAPI {
178
178
  generateRequestId: options.generateRequestId,
179
179
  name: options.name,
180
180
  opaqueIdPrefix: options.opaqueIdPrefix,
181
- context: options.context
181
+ context: options.context,
182
+ memoryCircuitBreaker: options.memoryCircuitBreaker
182
183
  })
183
184
 
184
185
  this.helpers = new Helpers({
@@ -0,0 +1,11 @@
1
+ lib = library(identifier: 'jenkins@1.1.1', retriever: modernSCM([
2
+ $class: 'GitSCMSource',
3
+ remote: 'https://github.com/opensearch-project/opensearch-build-libraries.git',
4
+ ]))
5
+
6
+ standardReleasePipelineWithGenericTrigger(
7
+ tokenIdCredential: 'jenkins-opensearch-js-generic-webhook-token',
8
+ causeString: 'A tag was cut on opensearch-project/opensearch-js repository causing this workflow to run',
9
+ publishRelease: true) {
10
+ publishToNpm(repository: 'https://github.com/opensearch-project/opensearch-js', tag: "$tag")
11
+ }
package/lib/Helpers.d.ts CHANGED
@@ -115,6 +115,7 @@ export interface OnDropDocument<TDocument = unknown> {
115
115
  reason: string
116
116
  }
117
117
  }
118
+ operation: Action
118
119
  document: TDocument
119
120
  retried: boolean
120
121
  }
package/lib/Helpers.js CHANGED
@@ -732,7 +732,7 @@ class Helpers {
732
732
  }
733
733
  } else {
734
734
  onDrop({
735
- status: status,
735
+ status,
736
736
  error: action[operation].error,
737
737
  operation: serializer.deserialize(bulkBody[indexSlice]),
738
738
  document: operation !== 'delete'
package/lib/Transport.js CHANGED
@@ -51,6 +51,7 @@ const clientVersion = require('../package.json').version
51
51
  const userAgent = `opensearch-js/${clientVersion} (${os.platform()} ${os.release()}-${os.arch()}; Node.js ${process.version})`
52
52
  const MAX_BUFFER_LENGTH = buffer.constants.MAX_LENGTH
53
53
  const MAX_STRING_LENGTH = buffer.constants.MAX_STRING_LENGTH
54
+ const HEAP_SIZE_LIMIT = require('v8').getHeapStatistics().heap_size_limit
54
55
  const kCompatibleCheck = Symbol('compatible check')
55
56
  const kApiVersioning = Symbol('api versioning')
56
57
 
@@ -81,6 +82,7 @@ class Transport {
81
82
  this.opaqueIdPrefix = opts.opaqueIdPrefix
82
83
  this[kCompatibleCheck] = 0 // 0 = to be checked, 1 = checking, 2 = checked-ok, 3 checked-notok
83
84
  this[kApiVersioning] = process.env.OPENSEARCH_CLIENT_APIVERSIONING === 'true'
85
+ this.memoryCircuitBreaker = opts.memoryCircuitBreaker
84
86
 
85
87
  this.nodeFilter = opts.nodeFilter || defaultNodeFilter
86
88
  if (typeof opts.nodeSelector === 'function') {
@@ -247,10 +249,10 @@ class Transport {
247
249
 
248
250
  const contentEncoding = (result.headers['content-encoding'] || '').toLowerCase()
249
251
  const isCompressed = contentEncoding.indexOf('gzip') > -1 || contentEncoding.indexOf('deflate') > -1
250
-
251
252
  /* istanbul ignore else */
252
253
  if (result.headers['content-length'] !== undefined) {
253
254
  const contentLength = Number(result.headers['content-length'])
255
+ // nodeJS data type limit check
254
256
  if (isCompressed && contentLength > MAX_BUFFER_LENGTH) {
255
257
  response.destroy()
256
258
  return onConnectionError(
@@ -261,6 +263,12 @@ class Transport {
261
263
  return onConnectionError(
262
264
  new RequestAbortedError(`The content length (${contentLength}) is bigger than the maximum allowed string (${MAX_STRING_LENGTH})`, result)
263
265
  )
266
+ } else if (shouldApplyCircuitBreaker(contentLength)) {
267
+ // Abort this response to avoid OOM crash of dashboards.
268
+ response.destroy()
269
+ return onConnectionError(
270
+ new RequestAbortedError(`The content length (${contentLength}) is bigger than the maximum allowed heap memory limit.`, result)
271
+ )
264
272
  }
265
273
  }
266
274
  // if the response is compressed, we must handle it
@@ -301,6 +309,13 @@ class Transport {
301
309
  response.on('end', onEnd)
302
310
  response.on('aborted', onAbort)
303
311
  }
312
+ // Helper function to check if memory circuit breaker enabled and the response payload is too large to fit into available heap memory.
313
+ const shouldApplyCircuitBreaker = (contentLength) => {
314
+ if (!this.memoryCircuitBreaker || !this.memoryCircuitBreaker.enabled) return false
315
+ const maxPercentage = validateMemoryPercentage(this.memoryCircuitBreaker.maxPercentage)
316
+ const heapUsed = process.memoryUsage().heapUsed
317
+ return contentLength + heapUsed > HEAP_SIZE_LIMIT * maxPercentage
318
+ }
304
319
 
305
320
  const onBody = (err, payload) => {
306
321
  if (err) {
@@ -636,6 +651,11 @@ function lowerCaseHeaders (oldHeaders) {
636
651
  return newHeaders
637
652
  }
638
653
 
654
+ function validateMemoryPercentage (percentage) {
655
+ if (percentage < 0 || percentage > 1) return 1.0
656
+ return percentage
657
+ }
658
+
639
659
  module.exports = Transport
640
660
  module.exports.internals = {
641
661
  defaultNodeFilter,
@@ -0,0 +1,173 @@
1
+ /*
2
+ * SPDX-License-Identifier: Apache-2.0
3
+ *
4
+ * The OpenSearch Contributors require contributions made to
5
+ * this file be licensed under the Apache-2.0 license or a
6
+ * compatible open source license.
7
+ *
8
+ * Modifications Copyright OpenSearch Contributors. See
9
+ * GitHub history for details.
10
+ */
11
+
12
+ 'use strict'
13
+ const Connection = require('../Connection')
14
+ const Transport = require('../Transport')
15
+ const aws4 = require('aws4')
16
+ const AwsSigv4SignerError = require('./errors')
17
+ const crypto = require('crypto')
18
+
19
+ const getAwsSDKCredentialsProvider = async () => {
20
+ // First try V3
21
+ try {
22
+ const awsV3 = await import('@aws-sdk/credential-provider-node')
23
+ if (typeof awsV3.defaultProvider === 'function') {
24
+ return awsV3.defaultProvider()
25
+ }
26
+ } catch (err) {
27
+ // Ignore
28
+ }
29
+ try {
30
+ const awsV2 = await import('aws-sdk')
31
+ if (awsV2.default && typeof awsV2.default.config.getCredentials === 'function') {
32
+ return () =>
33
+ new Promise((resolve, reject) => {
34
+ awsV2.default.config.getCredentials((err, credentials) => {
35
+ if (err) {
36
+ reject(err)
37
+ } else {
38
+ resolve(credentials)
39
+ }
40
+ })
41
+ })
42
+ }
43
+ } catch (err) {
44
+ // Ignore
45
+ }
46
+
47
+ throw new AwsSigv4SignerError(
48
+ 'Unable to find a valid AWS SDK, please provide a valid getCredentials function to AwsSigv4Signer options.'
49
+ )
50
+ }
51
+
52
+ const awsDefaultCredentialsProvider = () =>
53
+ new Promise((resolve, reject) => {
54
+ getAwsSDKCredentialsProvider()
55
+ .then((provider) => {
56
+ provider().then(resolve).catch(reject)
57
+ })
58
+ .catch((err) => {
59
+ reject(err)
60
+ })
61
+ })
62
+
63
+ function AwsSigv4Signer (opts = {}) {
64
+ const credentialsState = {
65
+ credentials: null
66
+ }
67
+ if (!opts.region) {
68
+ throw new AwsSigv4SignerError('Region cannot be empty')
69
+ }
70
+ if (!opts.service) {
71
+ opts.service = 'es'
72
+ }
73
+ if (typeof opts.getCredentials !== 'function') {
74
+ opts.getCredentials = awsDefaultCredentialsProvider
75
+ }
76
+
77
+ function buildSignedRequestObject (request = {}) {
78
+ request.service = opts.service
79
+ request.region = opts.region
80
+ request.headers = request.headers || {}
81
+ request.headers.host = request.hostname
82
+ const signed = aws4.sign(request, credentialsState.credentials)
83
+ signed.headers['x-amz-content-sha256'] = crypto
84
+ .createHash('sha256')
85
+ .update(request.body || '', 'utf8')
86
+ .digest('hex')
87
+ return signed
88
+ }
89
+
90
+ class AwsSigv4SignerConnection extends Connection {
91
+ buildRequestObject (params) {
92
+ const request = super.buildRequestObject(params)
93
+ return buildSignedRequestObject(request)
94
+ }
95
+ }
96
+
97
+ class AwsSigv4SignerTransport extends Transport {
98
+ request (params, options = {}, callback = undefined) {
99
+ // options is optional so if options is a function, it's the callback.
100
+ if (typeof options === 'function') {
101
+ callback = options
102
+ options = {}
103
+ }
104
+
105
+ const currentCredentials = credentialsState.credentials
106
+ let expired = false
107
+ if (!currentCredentials) {
108
+ // Credentials haven't been acquired yet.
109
+ expired = true
110
+ } else if (typeof currentCredentials.needsRefresh === 'function') {
111
+ // AWS SDK V2, needsRefresh should be available.
112
+ expired = currentCredentials.needsRefresh()
113
+ } else if (currentCredentials.expired === true) {
114
+ // AWS SDK V2, alternative to needsRefresh.
115
+ expired = true
116
+ } else if (currentCredentials.expireTime && currentCredentials.expireTime < new Date()) {
117
+ // AWS SDK V2, alternative to needsRefresh and expired.
118
+ expired = true
119
+ } else if (currentCredentials.expiration && currentCredentials.expiration < new Date()) {
120
+ // AWS SDK V3, Credentials.expiration is a Date object
121
+ expired = true
122
+ }
123
+
124
+ if (!expired) {
125
+ if (typeof callback === 'undefined') {
126
+ return super.request(params, options)
127
+ }
128
+ super.request(params, options, callback)
129
+ return
130
+ }
131
+
132
+ // In AWS SDK V2 Credentials.refreshPromise should be available.
133
+ if (currentCredentials && typeof currentCredentials.refreshPromise === 'function') {
134
+ if (typeof callback === 'undefined') {
135
+ return currentCredentials.refreshPromise().then(() => {
136
+ return super.request(params, options)
137
+ })
138
+ } else {
139
+ currentCredentials
140
+ .refreshPromise()
141
+ .then(() => {
142
+ super.request(params, options, callback)
143
+ })
144
+ .catch(callback)
145
+ return
146
+ }
147
+ }
148
+
149
+ // For AWS SDK V3 or when the client has not acquired credentials yet.
150
+ if (typeof callback === 'undefined') {
151
+ return opts.getCredentials().then((credentials) => {
152
+ credentialsState.credentials = credentials
153
+ return super.request(params, options)
154
+ })
155
+ } else {
156
+ opts
157
+ .getCredentials()
158
+ .then((credentials) => {
159
+ credentialsState.credentials = credentials
160
+ super.request(params, options, callback)
161
+ })
162
+ .catch(callback)
163
+ }
164
+ }
165
+ }
166
+
167
+ return {
168
+ Transport: AwsSigv4SignerTransport,
169
+ Connection: AwsSigv4SignerConnection,
170
+ buildSignedRequestObject
171
+ }
172
+ }
173
+ module.exports = AwsSigv4Signer
@@ -0,0 +1,25 @@
1
+ /*
2
+ * SPDX-License-Identifier: Apache-2.0
3
+ *
4
+ * The OpenSearch Contributors require contributions made to
5
+ * this file be licensed under the Apache-2.0 license or a
6
+ * compatible open source license.
7
+ *
8
+ * Modifications Copyright OpenSearch Contributors. See
9
+ * GitHub history for details.
10
+ */
11
+
12
+ 'use strict'
13
+ const { OpenSearchClientError } = require('../errors')
14
+
15
+ class AwsSigv4SignerError extends OpenSearchClientError {
16
+ constructor (message, data) {
17
+ super(message, data)
18
+ Error.captureStackTrace(this, AwsSigv4SignerError)
19
+ this.name = 'AwsSigv4SignerError'
20
+ this.message = message || 'AwsSigv4Signer Error'
21
+ this.data = data
22
+ }
23
+ }
24
+
25
+ module.exports = AwsSigv4SignerError
@@ -0,0 +1,41 @@
1
+ /*
2
+ * SPDX-License-Identifier: Apache-2.0
3
+ *
4
+ * The OpenSearch Contributors require contributions made to
5
+ * this file be licensed under the Apache-2.0 license or a
6
+ * compatible open source license.
7
+ *
8
+ * Modifications Copyright OpenSearch Contributors. See
9
+ * GitHub history for details.
10
+ */
11
+
12
+ /// <reference types="node" />
13
+
14
+ import { Credentials } from '@aws-sdk/types';
15
+ import Connection from '../Connection';
16
+ import Transport from '../Transport';
17
+ import * as http from 'http';
18
+ import { OpenSearchClientError } from '../errors';
19
+
20
+ interface AwsSigv4SignerOptions {
21
+ getCredentials: () => Promise<Credentials>;
22
+ region: string;
23
+ service?: 'es' | 'aoss';
24
+ }
25
+
26
+ interface AwsSigv4SignerResponse {
27
+ Connection: typeof Connection;
28
+ Transport: typeof Transport;
29
+ buildSignedRequestObject(request: any): http.ClientRequestArgs;
30
+ }
31
+
32
+ declare function AwsSigv4Signer (opts: AwsSigv4SignerOptions): AwsSigv4SignerResponse;
33
+
34
+ declare class AwsSigv4SignerError extends OpenSearchClientError {
35
+ name: string;
36
+ message: string;
37
+ data: any;
38
+ constructor(message: string, data: any);
39
+ }
40
+
41
+ export { AwsSigv4Signer, AwsSigv4SignerOptions, AwsSigv4SignerResponse, AwsSigv4SignerError };
@@ -0,0 +1,20 @@
1
+ /*
2
+ * SPDX-License-Identifier: Apache-2.0
3
+ *
4
+ * The OpenSearch Contributors require contributions made to
5
+ * this file be licensed under the Apache-2.0 license or a
6
+ * compatible open source license.
7
+ *
8
+ * Modifications Copyright OpenSearch Contributors. See
9
+ * GitHub history for details.
10
+ */
11
+
12
+ 'use strict'
13
+
14
+ const AwsSigv4Signer = require('./AwsSigv4Signer')
15
+ const AwsSigv4SignerError = require('./errors')
16
+
17
+ module.exports = {
18
+ AwsSigv4Signer,
19
+ AwsSigv4SignerError
20
+ }
package/lib/errors.js CHANGED
@@ -69,7 +69,7 @@ class NoLivingConnectionsError extends OpenSearchClientError {
69
69
 
70
70
  class SerializationError extends OpenSearchClientError {
71
71
  constructor (message, data) {
72
- super(message, data)
72
+ super(message)
73
73
  Error.captureStackTrace(this, SerializationError)
74
74
  this.name = 'SerializationError'
75
75
  this.message = message || 'Serialization Error'
@@ -79,7 +79,7 @@ class SerializationError extends OpenSearchClientError {
79
79
 
80
80
  class DeserializationError extends OpenSearchClientError {
81
81
  constructor (message, data) {
82
- super(message, data)
82
+ super(message)
83
83
  Error.captureStackTrace(this, DeserializationError)
84
84
  this.name = 'DeserializationError'
85
85
  this.message = message || 'Deserialization Error'
package/package.json CHANGED
@@ -8,10 +8,21 @@
8
8
  "require": "./index.js",
9
9
  "import": "./index.mjs"
10
10
  },
11
+ "./aws": "./lib/aws/index.js",
11
12
  "./": "./"
12
13
  },
14
+ "typesVersions": {
15
+ "*": {
16
+ ".": [
17
+ "index.d.ts"
18
+ ],
19
+ "aws": [
20
+ "./lib/aws/index.d.ts"
21
+ ]
22
+ }
23
+ },
13
24
  "homepage": "https://www.opensearch.org/",
14
- "version": "1.0.2",
25
+ "version": "1.2.0",
15
26
  "versionCanary": "7.10.0-canary.6",
16
27
  "keywords": [
17
28
  "opensearch",
@@ -44,8 +55,9 @@
44
55
  "company": "Elasticsearch BV"
45
56
  },
46
57
  "devDependencies": {
58
+ "@aws-sdk/types": "^3.272.0",
47
59
  "@sinonjs/fake-timers": "github:sinonjs/fake-timers#0bfffc1",
48
- "@types/node": "^15.3.1",
60
+ "@types/node": "^17.0.45",
49
61
  "convert-hrtime": "^5.0.0",
50
62
  "cross-zip": "^4.0.0",
51
63
  "dedent": "^0.7.0",
@@ -62,17 +74,18 @@
62
74
  "proxy": "^1.0.2",
63
75
  "rimraf": "^3.0.2",
64
76
  "semver": "^7.3.5",
65
- "simple-git": "^2.39.0",
77
+ "simple-git": "^3.5.0",
66
78
  "simple-statistics": "^7.7.0",
67
79
  "split2": "^3.2.2",
68
80
  "standard": "^16.0.3",
69
81
  "stoppable": "^1.1.0",
70
- "tap": "^15.0.9",
82
+ "tap": "^15.2.0",
71
83
  "tsd": "^0.15.1",
72
84
  "workq": "^3.0.0",
73
85
  "xmlbuilder2": "^2.4.1"
74
86
  },
75
87
  "dependencies": {
88
+ "aws4": "^1.11.0",
76
89
  "debug": "^4.3.1",
77
90
  "hpagent": "^0.1.1",
78
91
  "ms": "^2.1.3",