@opensearch-project/opensearch 1.0.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.
Files changed (84) hide show
  1. package/.dockerignore +5 -0
  2. package/ADMINS.md +34 -0
  3. package/DEVELOPER_GUIDE.md +60 -0
  4. package/LICENSE.txt +201 -0
  5. package/MAINTAINERS.md +73 -0
  6. package/Makefile +27 -0
  7. package/NOTICE.txt +8 -0
  8. package/README.md +183 -0
  9. package/RELEASING.md +34 -0
  10. package/SECURITY.md +3 -0
  11. package/api/api/bulk.js +81 -0
  12. package/api/api/cat.js +525 -0
  13. package/api/api/clear_scroll.js +66 -0
  14. package/api/api/cluster.js +431 -0
  15. package/api/api/count.js +75 -0
  16. package/api/api/create.js +80 -0
  17. package/api/api/dangling_indices.js +126 -0
  18. package/api/api/delete.js +76 -0
  19. package/api/api/delete_by_query.js +82 -0
  20. package/api/api/delete_by_query_rethrottle.js +71 -0
  21. package/api/api/delete_script.js +67 -0
  22. package/api/api/exists.js +76 -0
  23. package/api/api/exists_source.js +85 -0
  24. package/api/api/explain.js +76 -0
  25. package/api/api/features.js +92 -0
  26. package/api/api/field_caps.js +66 -0
  27. package/api/api/get.js +76 -0
  28. package/api/api/get_script.js +67 -0
  29. package/api/api/get_script_context.js +61 -0
  30. package/api/api/get_script_languages.js +61 -0
  31. package/api/api/get_source.js +76 -0
  32. package/api/api/index.js +82 -0
  33. package/api/api/indices.js +1516 -0
  34. package/api/api/info.js +61 -0
  35. package/api/api/ingest.js +211 -0
  36. package/api/api/mget.js +81 -0
  37. package/api/api/msearch.js +81 -0
  38. package/api/api/msearch_template.js +81 -0
  39. package/api/api/mtermvectors.js +75 -0
  40. package/api/api/nodes.js +279 -0
  41. package/api/api/ping.js +61 -0
  42. package/api/api/put_script.js +82 -0
  43. package/api/api/rank_eval.js +72 -0
  44. package/api/api/reindex.js +67 -0
  45. package/api/api/reindex_rethrottle.js +71 -0
  46. package/api/api/render_search_template.js +66 -0
  47. package/api/api/scripts_painless_execute.js +61 -0
  48. package/api/api/scroll.js +66 -0
  49. package/api/api/search.js +75 -0
  50. package/api/api/search_shards.js +66 -0
  51. package/api/api/search_template.js +81 -0
  52. package/api/api/shutdown.js +135 -0
  53. package/api/api/snapshot.js +450 -0
  54. package/api/api/tasks.js +119 -0
  55. package/api/api/terms_enum.js +67 -0
  56. package/api/api/termvectors.js +78 -0
  57. package/api/api/update.js +80 -0
  58. package/api/api/update_by_query.js +78 -0
  59. package/api/api/update_by_query_rethrottle.js +71 -0
  60. package/api/index.js +254 -0
  61. package/api/new.d.ts +716 -0
  62. package/api/requestParams.d.ts +1583 -0
  63. package/api/types.d.ts +9481 -0
  64. package/api/utils.js +69 -0
  65. package/codecov.yml +14 -0
  66. package/index.d.ts +1210 -0
  67. package/index.js +338 -0
  68. package/index.mjs +40 -0
  69. package/lib/Connection.d.ts +107 -0
  70. package/lib/Connection.js +345 -0
  71. package/lib/Helpers.d.ts +135 -0
  72. package/lib/Helpers.js +779 -0
  73. package/lib/Serializer.d.ts +41 -0
  74. package/lib/Serializer.js +105 -0
  75. package/lib/Transport.d.ts +173 -0
  76. package/lib/Transport.js +646 -0
  77. package/lib/errors.d.ts +101 -0
  78. package/lib/errors.js +168 -0
  79. package/lib/pool/BaseConnectionPool.js +269 -0
  80. package/lib/pool/CloudConnectionPool.js +75 -0
  81. package/lib/pool/ConnectionPool.js +257 -0
  82. package/lib/pool/index.d.ts +215 -0
  83. package/lib/pool/index.js +41 -0
  84. package/package.json +102 -0
@@ -0,0 +1,345 @@
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
+ /*
13
+ * Licensed to Elasticsearch B.V. under one or more contributor
14
+ * license agreements. See the NOTICE file distributed with
15
+ * this work for additional information regarding copyright
16
+ * ownership. Elasticsearch B.V. licenses this file to you under
17
+ * the Apache License, Version 2.0 (the "License"); you may
18
+ * not use this file except in compliance with the License.
19
+ * You may obtain a copy of the License at
20
+ *
21
+ * http://www.apache.org/licenses/LICENSE-2.0
22
+ *
23
+ * Unless required by applicable law or agreed to in writing,
24
+ * software distributed under the License is distributed on an
25
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
26
+ * KIND, either express or implied. See the License for the
27
+ * specific language governing permissions and limitations
28
+ * under the License.
29
+ */
30
+
31
+ 'use strict'
32
+
33
+ const assert = require('assert')
34
+ const { inspect } = require('util')
35
+ const hpagent = require('hpagent')
36
+ const http = require('http')
37
+ const https = require('https')
38
+ const debug = require('debug')('opensearch')
39
+ const { pipeline } = require('stream')
40
+ const INVALID_PATH_REGEX = /[^\u0021-\u00ff]/
41
+ const {
42
+ ConnectionError,
43
+ RequestAbortedError,
44
+ TimeoutError,
45
+ ConfigurationError
46
+ } = require('./errors')
47
+
48
+ class Connection {
49
+ constructor (opts) {
50
+ this.url = opts.url
51
+ this.ssl = opts.ssl || null
52
+ this.id = opts.id || stripAuth(opts.url.href)
53
+ this.headers = prepareHeaders(opts.headers, opts.auth)
54
+ this.deadCount = 0
55
+ this.resurrectTimeout = 0
56
+
57
+ this._openRequests = 0
58
+ this._status = opts.status || Connection.statuses.ALIVE
59
+ this.roles = Object.assign({}, defaultRoles, opts.roles)
60
+
61
+ if (!['http:', 'https:'].includes(this.url.protocol)) {
62
+ throw new ConfigurationError(`Invalid protocol: '${this.url.protocol}'`)
63
+ }
64
+
65
+ if (typeof opts.agent === 'function') {
66
+ this.agent = opts.agent(opts)
67
+ } else if (opts.agent === false) {
68
+ this.agent = undefined
69
+ } else {
70
+ const agentOptions = Object.assign({}, {
71
+ keepAlive: true,
72
+ keepAliveMsecs: 1000,
73
+ maxSockets: 256,
74
+ maxFreeSockets: 256,
75
+ scheduling: 'lifo'
76
+ }, opts.agent)
77
+ if (opts.proxy) {
78
+ agentOptions.proxy = opts.proxy
79
+ this.agent = this.url.protocol === 'http:'
80
+ ? new hpagent.HttpProxyAgent(agentOptions)
81
+ : new hpagent.HttpsProxyAgent(Object.assign({}, agentOptions, this.ssl))
82
+ } else {
83
+ this.agent = this.url.protocol === 'http:'
84
+ ? new http.Agent(agentOptions)
85
+ : new https.Agent(Object.assign({}, agentOptions, this.ssl))
86
+ }
87
+ }
88
+
89
+ this.makeRequest = this.url.protocol === 'http:'
90
+ ? http.request
91
+ : https.request
92
+ }
93
+
94
+ request (params, callback) {
95
+ this._openRequests++
96
+ let cleanedListeners = false
97
+
98
+ const requestParams = this.buildRequestObject(params)
99
+ // https://github.com/nodejs/node/commit/b961d9fd83
100
+ if (INVALID_PATH_REGEX.test(requestParams.path) === true) {
101
+ callback(new TypeError(`ERR_UNESCAPED_CHARACTERS: ${requestParams.path}`), null)
102
+ /* istanbul ignore next */
103
+ return { abort: () => { } }
104
+ }
105
+
106
+ debug('Starting a new request', params)
107
+ const request = this.makeRequest(requestParams)
108
+
109
+ const onResponse = response => {
110
+ cleanListeners()
111
+ this._openRequests--
112
+ callback(null, response)
113
+ }
114
+
115
+ const onTimeout = () => {
116
+ cleanListeners()
117
+ this._openRequests--
118
+ request.once('error', () => { }) // we need to catch the request aborted error
119
+ request.abort()
120
+ callback(new TimeoutError('Request timed out', params), null)
121
+ }
122
+
123
+ const onError = err => {
124
+ cleanListeners()
125
+ this._openRequests--
126
+ callback(new ConnectionError(err.message), null)
127
+ }
128
+
129
+ const onAbort = () => {
130
+ cleanListeners()
131
+ request.once('error', () => { }) // we need to catch the request aborted error
132
+ debug('Request aborted', params)
133
+ this._openRequests--
134
+ callback(new RequestAbortedError(), null)
135
+ }
136
+
137
+ request.on('response', onResponse)
138
+ request.on('timeout', onTimeout)
139
+ request.on('error', onError)
140
+ request.on('abort', onAbort)
141
+
142
+ // Disables the Nagle algorithm
143
+ request.setNoDelay(true)
144
+
145
+ // starts the request
146
+ if (isStream(params.body) === true) {
147
+ pipeline(params.body, request, err => {
148
+ /* istanbul ignore if */
149
+ if (err != null && cleanedListeners === false) {
150
+ cleanListeners()
151
+ this._openRequests--
152
+ callback(err, null)
153
+ }
154
+ })
155
+ } else {
156
+ request.end(params.body)
157
+ }
158
+
159
+ return request
160
+
161
+ function cleanListeners () {
162
+ request.removeListener('response', onResponse)
163
+ request.removeListener('timeout', onTimeout)
164
+ request.removeListener('error', onError)
165
+ request.removeListener('abort', onAbort)
166
+ cleanedListeners = true
167
+ }
168
+ }
169
+
170
+ // TODO: write a better closing logic
171
+ close (callback = () => { }) {
172
+ debug('Closing connection', this.id)
173
+ if (this._openRequests > 0) {
174
+ setTimeout(() => this.close(callback), 1000)
175
+ } else {
176
+ if (this.agent !== undefined) {
177
+ this.agent.destroy()
178
+ }
179
+ callback()
180
+ }
181
+ }
182
+
183
+ setRole (role, enabled) {
184
+ if (validRoles.indexOf(role) === -1) {
185
+ throw new ConfigurationError(`Unsupported role: '${role}'`)
186
+ }
187
+ if (typeof enabled !== 'boolean') {
188
+ throw new ConfigurationError('enabled should be a boolean')
189
+ }
190
+
191
+ this.roles[role] = enabled
192
+ return this
193
+ }
194
+
195
+ get status () {
196
+ return this._status
197
+ }
198
+
199
+ set status (status) {
200
+ assert(
201
+ ~validStatuses.indexOf(status),
202
+ `Unsupported status: '${status}'`
203
+ )
204
+ this._status = status
205
+ }
206
+
207
+ buildRequestObject (params) {
208
+ const url = this.url
209
+ const request = {
210
+ protocol: url.protocol,
211
+ hostname: url.hostname[0] === '['
212
+ ? url.hostname.slice(1, -1)
213
+ : url.hostname,
214
+ hash: url.hash,
215
+ search: url.search,
216
+ pathname: url.pathname,
217
+ path: '',
218
+ href: url.href,
219
+ origin: url.origin,
220
+ // https://github.com/elastic/elasticsearch-js/issues/843
221
+ port: url.port !== '' ? url.port : undefined,
222
+ headers: this.headers,
223
+ agent: this.agent
224
+ }
225
+
226
+ const paramsKeys = Object.keys(params)
227
+ for (let i = 0, len = paramsKeys.length; i < len; i++) {
228
+ const key = paramsKeys[i]
229
+ if (key === 'path') {
230
+ request.pathname = resolve(request.pathname, params[key])
231
+ } else if (key === 'querystring' && !!params[key] === true) {
232
+ if (request.search === '') {
233
+ request.search = '?' + params[key]
234
+ } else {
235
+ request.search += '&' + params[key]
236
+ }
237
+ } else if (key === 'headers') {
238
+ request.headers = Object.assign({}, request.headers, params.headers)
239
+ } else {
240
+ request[key] = params[key]
241
+ }
242
+ }
243
+
244
+ request.path = request.pathname + request.search
245
+
246
+ return request
247
+ }
248
+
249
+ // Handles console.log and utils.inspect invocations.
250
+ // We want to hide `auth`, `agent` and `ssl` since they made
251
+ // the logs very hard to read. The user can still
252
+ // access them with `instance.agent` and `instance.ssl`.
253
+ [inspect.custom] (depth, options) {
254
+ const {
255
+ authorization,
256
+ ...headers
257
+ } = this.headers
258
+
259
+ return {
260
+ url: stripAuth(this.url.toString()),
261
+ id: this.id,
262
+ headers,
263
+ deadCount: this.deadCount,
264
+ resurrectTimeout: this.resurrectTimeout,
265
+ _openRequests: this._openRequests,
266
+ status: this.status,
267
+ roles: this.roles
268
+ }
269
+ }
270
+
271
+ toJSON () {
272
+ const {
273
+ authorization,
274
+ ...headers
275
+ } = this.headers
276
+
277
+ return {
278
+ url: stripAuth(this.url.toString()),
279
+ id: this.id,
280
+ headers,
281
+ deadCount: this.deadCount,
282
+ resurrectTimeout: this.resurrectTimeout,
283
+ _openRequests: this._openRequests,
284
+ status: this.status,
285
+ roles: this.roles
286
+ }
287
+ }
288
+ }
289
+
290
+ Connection.statuses = {
291
+ ALIVE: 'alive',
292
+ DEAD: 'dead'
293
+ }
294
+
295
+ Connection.roles = {
296
+ MASTER: 'master',
297
+ DATA: 'data',
298
+ INGEST: 'ingest'
299
+ }
300
+
301
+ const defaultRoles = {
302
+ [Connection.roles.MASTER]: true,
303
+ [Connection.roles.DATA]: true,
304
+ [Connection.roles.INGEST]: true
305
+ }
306
+
307
+ const validStatuses = Object.keys(Connection.statuses)
308
+ .map(k => Connection.statuses[k])
309
+ const validRoles = Object.keys(Connection.roles)
310
+ .map(k => Connection.roles[k])
311
+
312
+ function stripAuth (url) {
313
+ if (url.indexOf('@') === -1) return url
314
+ return url.slice(0, url.indexOf('//') + 2) + url.slice(url.indexOf('@') + 1)
315
+ }
316
+
317
+ function isStream (obj) {
318
+ return obj != null && typeof obj.pipe === 'function'
319
+ }
320
+
321
+ function resolve (host, path) {
322
+ const hostEndWithSlash = host[host.length - 1] === '/'
323
+ const pathStartsWithSlash = path[0] === '/'
324
+
325
+ if (hostEndWithSlash === true && pathStartsWithSlash === true) {
326
+ return host + path.slice(1)
327
+ } else if (hostEndWithSlash !== pathStartsWithSlash) {
328
+ return host + path
329
+ } else {
330
+ return host + '/' + path
331
+ }
332
+ }
333
+
334
+ function prepareHeaders (headers = {}, auth) {
335
+ if (auth != null && headers.authorization == null) {
336
+ /* istanbul ignore else */
337
+ if (auth.username && auth.password) {
338
+ headers.authorization = 'Basic ' + Buffer.from(`${auth.username}:${auth.password}`).toString('base64')
339
+ }
340
+ }
341
+ return headers
342
+ }
343
+
344
+ module.exports = Connection
345
+ module.exports.internals = { prepareHeaders }
@@ -0,0 +1,135 @@
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
+ /*
13
+ * Licensed to Elasticsearch B.V. under one or more contributor
14
+ * license agreements. See the NOTICE file distributed with
15
+ * this work for additional information regarding copyright
16
+ * ownership. Elasticsearch B.V. licenses this file to you under
17
+ * the Apache License, Version 2.0 (the "License"); you may
18
+ * not use this file except in compliance with the License.
19
+ * You may obtain a copy of the License at
20
+ *
21
+ * http://www.apache.org/licenses/LICENSE-2.0
22
+ *
23
+ * Unless required by applicable law or agreed to in writing,
24
+ * software distributed under the License is distributed on an
25
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
26
+ * KIND, either express or implied. See the License for the
27
+ * specific language governing permissions and limitations
28
+ * under the License.
29
+ */
30
+
31
+ import { Readable as ReadableStream } from 'stream'
32
+ import { TransportRequestOptions, ApiError, ApiResponse, RequestBody, Context } from './Transport'
33
+ import { Search, Msearch, Bulk } from '../api/requestParams'
34
+
35
+ export default class Helpers {
36
+ search<TDocument = unknown, TRequestBody extends RequestBody = Record<string, any>>(params: Search<TRequestBody>, options?: TransportRequestOptions): Promise<TDocument[]>
37
+ scrollSearch<TDocument = unknown, TResponse = Record<string, any>, TRequestBody extends RequestBody = Record<string, any>, TContext = Context>(params: Search<TRequestBody>, options?: TransportRequestOptions): AsyncIterable<ScrollSearchResponse<TDocument, TResponse, TContext>>
38
+ scrollDocuments<TDocument = unknown, TRequestBody extends RequestBody = Record<string, any>>(params: Search<TRequestBody>, options?: TransportRequestOptions): AsyncIterable<TDocument>
39
+ msearch(options?: MsearchHelperOptions, reqOptions?: TransportRequestOptions): MsearchHelper
40
+ bulk<TDocument = unknown>(options: BulkHelperOptions<TDocument>, reqOptions?: TransportRequestOptions): BulkHelper<BulkStats>
41
+ }
42
+
43
+ export interface ScrollSearchResponse<TDocument = unknown, TResponse = Record<string, any>, TContext = Context> extends ApiResponse<TResponse, TContext> {
44
+ clear: () => Promise<void>
45
+ documents: TDocument[]
46
+ }
47
+
48
+ export interface BulkHelper<T> extends Promise<T> {
49
+ abort: () => BulkHelper<T>
50
+ readonly stats: BulkStats
51
+ }
52
+
53
+ export interface BulkStats {
54
+ total: number
55
+ failed: number
56
+ retry: number
57
+ successful: number
58
+ noop: number
59
+ time: number
60
+ bytes: number
61
+ aborted: boolean
62
+ }
63
+
64
+ interface IndexAction {
65
+ index: {
66
+ _index: string
67
+ [key: string]: any
68
+ }
69
+ }
70
+
71
+ interface CreateAction {
72
+ create: {
73
+ _index: string
74
+ [key: string]: any
75
+ }
76
+ }
77
+
78
+ interface UpdateActionOperation {
79
+ update: {
80
+ _index: string
81
+ [key: string]: any
82
+ }
83
+ }
84
+
85
+ interface DeleteAction {
86
+ delete: {
87
+ _index: string
88
+ [key: string]: any
89
+ }
90
+ }
91
+
92
+ type UpdateAction = [UpdateActionOperation, Record<string, any>]
93
+ type Action = IndexAction | CreateAction | UpdateAction | DeleteAction
94
+ type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>
95
+
96
+ export interface BulkHelperOptions<TDocument = unknown> extends Omit<Bulk, 'body'> {
97
+ datasource: TDocument[] | Buffer | ReadableStream | AsyncIterator<TDocument>
98
+ onDocument: (doc: TDocument) => Action
99
+ flushBytes?: number
100
+ flushInterval?: number
101
+ concurrency?: number
102
+ retries?: number
103
+ wait?: number
104
+ onDrop?: (doc: OnDropDocument<TDocument>) => void
105
+ refreshOnCompletion?: boolean | string
106
+ }
107
+
108
+ export interface OnDropDocument<TDocument = unknown> {
109
+ status: number
110
+ error: {
111
+ type: string,
112
+ reason: string,
113
+ caused_by: {
114
+ type: string,
115
+ reason: string
116
+ }
117
+ }
118
+ document: TDocument
119
+ retried: boolean
120
+ }
121
+
122
+ export interface MsearchHelperOptions extends Omit<Msearch, 'body'> {
123
+ operations?: number
124
+ flushInterval?: number
125
+ concurrency?: number
126
+ retries?: number
127
+ wait?: number
128
+ }
129
+
130
+ declare type callbackFn<Response, Context> = (err: ApiError, result: ApiResponse<Response, Context>) => void;
131
+ export interface MsearchHelper extends Promise<void> {
132
+ stop(error?: Error): void
133
+ search<TResponse = Record<string, any>, TRequestBody extends RequestBody = Record<string, any>, TContext = Context>(header: Omit<Search, 'body'>, body: TRequestBody): Promise<ApiResponse<TResponse, TContext>>
134
+ search<TResponse = Record<string, any>, TRequestBody extends RequestBody = Record<string, any>, TContext = Context>(header: Omit<Search, 'body'>, body: TRequestBody, callback: callbackFn<TResponse, TContext>): void
135
+ }