/
cluster.ts
594 lines (519 loc) · 15.4 KB
/
cluster.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
import { AnalyticsExecutor } from './analyticsexecutor'
import { AnalyticsIndexManager } from './analyticsindexmanager'
import {
AnalyticsMetaData,
AnalyticsQueryOptions,
AnalyticsResult,
} from './analyticstypes'
import {
Authenticator,
PasswordAuthenticator,
CertificateAuthenticator,
} from './authenticators'
import { Bucket } from './bucket'
import { BucketManager } from './bucketmanager'
import { Connection, ConnectionOptions } from './connection'
import { DiagnoticsExecutor, PingExecutor } from './diagnosticsexecutor'
import {
DiagnosticsOptions,
DiagnosticsResult,
PingOptions,
PingResult,
} from './diagnosticstypes'
import { ClusterClosedError, NeedOpenBucketError } from './errors'
import { libLogger } from './logging'
import { LogFunc, defaultLogger } from './logging'
import { LoggingMeter, Meter } from './metrics'
import { QueryExecutor } from './queryexecutor'
import { QueryIndexManager } from './queryindexmanager'
import { QueryMetaData, QueryOptions, QueryResult } from './querytypes'
import { SearchExecutor } from './searchexecutor'
import { SearchIndexManager } from './searchindexmanager'
import { SearchQuery } from './searchquery'
import {
SearchMetaData,
SearchQueryOptions,
SearchResult,
SearchRow,
} from './searchtypes'
import { StreamableRowPromise } from './streamablepromises'
import { RequestTracer, ThresholdLoggingTracer } from './tracing'
import { Transcoder, DefaultTranscoder } from './transcoders'
import { UserManager } from './usermanager'
import { PromiseHelper, NodeCallback } from './utilities'
/**
* Specifies the options which can be specified when connecting
* to a cluster.
*
* @category Core
*/
export interface ConnectOptions {
/**
* Specifies a username to use for an implicitly created IPasswordAuthenticator
* used for authentication with the cluster.
*/
username?: string
/**
* Specifies a password to be used in concert with username for authentication.
*
* @see ConnectOptions.username
*/
password?: string
/**
* Specifies a specific authenticator to use when connecting to the cluster.
*/
authenticator?: Authenticator
/**
* Specifies the path to a trust store file to be used when validating the
* authenticity of the server when connecting over SSL.
*/
trustStorePath?: string
/**
* Specifies the default timeout for KV operations, specified in millseconds.
*/
kvTimeout?: number
/**
* Specifies the default timeout for durable KV operations, specified in millseconds.
*/
kvDurableTimeout?: number
/**
* Specifies the default timeout for views operations, specified in millseconds.
*/
viewTimeout?: number
/**
* Specifies the default timeout for query operations, specified in millseconds.
*/
queryTimeout?: number
/**
* Specifies the default timeout for analytics query operations, specified in millseconds.
*/
analyticsTimeout?: number
/**
* Specifies the default timeout for search query operations, specified in millseconds.
*/
searchTimeout?: number
/**
* Specifies the default timeout for management operations, specified in millseconds.
*/
managementTimeout?: number
/**
* Specifies the default transcoder to use when encoding or decoding document values.
*/
transcoder?: Transcoder
/**
* Specifies the tracer to use for diagnostics tracing.
*/
tracer?: RequestTracer
/**
* Specifies the meter to use for diagnostics metrics.
*/
meter?: Meter
/**
* Specifies a logging function to use when outputting logging.
*/
logFunc?: LogFunc
}
/**
* Exposes the operations which are available to be performed against a cluster.
* Namely the ability to access to Buckets as well as performing management
* operations against the cluster.
*
* @category Core
*/
export class Cluster {
private _connStr: string
private _trustStorePath: string
private _kvTimeout: number
private _kvDurableTimeout: number
private _viewTimeout: number
private _queryTimeout: number
private _analyticsTimeout: number
private _searchTimeout: number
private _managementTimeout: number
private _auth: Authenticator
private _closed: boolean
private _clusterConn: Connection | null
private _conns: { [key: string]: Connection }
private _transcoder: Transcoder
private _tracer: RequestTracer
private _meter: Meter
private _logFunc: LogFunc
/**
@internal
*/
get transcoder(): Transcoder {
return this._transcoder
}
/**
@internal
@deprecated Use the static sdk-level {@link connect} method instead.
*/
constructor(connStr: string, options?: ConnectOptions) {
if (!options) {
options = {}
}
this._connStr = connStr
this._trustStorePath = options.trustStorePath || ''
this._kvTimeout = options.kvTimeout || 0
this._kvDurableTimeout = options.kvDurableTimeout || 0
this._viewTimeout = options.viewTimeout || 0
this._queryTimeout = options.queryTimeout || 0
this._analyticsTimeout = options.analyticsTimeout || 0
this._searchTimeout = options.searchTimeout || 0
this._managementTimeout = options.managementTimeout || 0
if (options.transcoder) {
this._transcoder = options.transcoder
} else {
this._transcoder = new DefaultTranscoder()
}
if (options.tracer) {
this._tracer = options.tracer
} else {
this._tracer = new ThresholdLoggingTracer({})
}
if (options.meter) {
this._meter = options.meter
} else {
this._meter = new LoggingMeter({})
}
if (options.logFunc) {
this._logFunc = options.logFunc
} else {
this._logFunc = defaultLogger
}
if (options.username || options.password) {
if (options.authenticator) {
throw new Error(
'Cannot specify authenticator along with username/password.'
)
}
this._auth = {
username: options.username || '',
password: options.password || '',
}
} else if (options.authenticator) {
this._auth = options.authenticator
} else {
this._auth = {
username: '',
password: '',
}
}
this._closed = false
this._clusterConn = null
this._conns = {}
}
/**
@internal
*/
static async connect(
connStr: string,
options?: ConnectOptions,
callback?: NodeCallback<Cluster>
): Promise<Cluster> {
return PromiseHelper.wrapAsync(async () => {
const cluster = new Cluster(connStr, options)
await cluster._clusterConnect()
return cluster
}, callback)
}
/**
* Creates a Bucket object reference to a specific bucket.
*
* @param bucketName The name of the bucket to reference.
*/
bucket(bucketName: string): Bucket {
return new Bucket(this, bucketName)
}
/**
* Returns a UserManager which can be used to manage the users
* of this cluster.
*/
users(): UserManager {
return new UserManager(this)
}
/**
* Returns a BucketManager which can be used to manage the buckets
* of this cluster.
*/
buckets(): BucketManager {
return new BucketManager(this)
}
/**
* Returns a QueryIndexManager which can be used to manage the query indexes
* of this cluster.
*/
queryIndexes(): QueryIndexManager {
return new QueryIndexManager(this)
}
/**
* Returns a AnalyticsIndexManager which can be used to manage the analytics
* indexes of this cluster.
*/
analyticsIndexes(): AnalyticsIndexManager {
return new AnalyticsIndexManager(this)
}
/**
* Returns a SearchIndexManager which can be used to manage the search
* indexes of this cluster.
*/
searchIndexes(): SearchIndexManager {
return new SearchIndexManager(this)
}
/**
* Executes a N1QL query against the cluster.
*
* @param statement The N1QL statement to execute.
* @param options Optional parameters for this operation.
* @param callback A node-style callback to be invoked after execution.
*/
query<TRow = any>(
statement: string,
options?: QueryOptions,
callback?: NodeCallback<QueryResult<TRow>>
): StreamableRowPromise<QueryResult<TRow>, TRow, QueryMetaData> {
if (options instanceof Function) {
callback = arguments[0]
options = undefined
}
if (!options) {
options = {}
}
const conn = this._getClusterConn()
const exec = new QueryExecutor(conn)
const options_ = options
return PromiseHelper.wrapAsync(
() => exec.query<TRow>(statement, options_),
callback
)
}
/**
* Executes an analytics query against the cluster.
*
* @param statement The analytics statement to execute.
* @param options Optional parameters for this operation.
* @param callback A node-style callback to be invoked after execution.
*/
analyticsQuery<TRow = any>(
statement: string,
options?: AnalyticsQueryOptions,
callback?: NodeCallback<AnalyticsResult<TRow>>
): StreamableRowPromise<AnalyticsResult<TRow>, TRow, AnalyticsMetaData> {
if (options instanceof Function) {
callback = arguments[0]
options = undefined
}
if (!options) {
options = {}
}
const conn = this._getClusterConn()
const exec = new AnalyticsExecutor(conn)
const options_ = options
return PromiseHelper.wrapAsync(
() => exec.query<TRow>(statement, options_),
callback
)
}
/**
* Executes a search query against the cluster.
*
* @param indexName The name of the index to query.
* @param query The SearchQuery describing the query to execute.
* @param options Optional parameters for this operation.
* @param callback A node-style callback to be invoked after execution.
*/
searchQuery(
indexName: string,
query: SearchQuery,
options?: SearchQueryOptions,
callback?: NodeCallback<SearchResult>
): StreamableRowPromise<SearchResult, SearchRow, SearchMetaData> {
if (options instanceof Function) {
callback = arguments[0]
options = undefined
}
if (!options) {
options = {}
}
const conn = this._getClusterConn()
const exec = new SearchExecutor(conn)
const options_ = options
return PromiseHelper.wrapAsync(
() => exec.query(indexName, query, options_),
callback
)
}
/**
* Returns a diagnostics report about the currently active connections with the
* cluster. Includes information about remote and local addresses, last activity,
* and other diagnostics information.
*
* @param options Optional parameters for this operation.
* @param callback A node-style callback to be invoked after execution.
*/
diagnostics(
options?: DiagnosticsOptions,
callback?: NodeCallback<DiagnosticsResult>
): Promise<DiagnosticsResult> {
if (options instanceof Function) {
callback = arguments[0]
options = undefined
}
if (!options) {
options = {}
}
let conns = Object.values(this._conns)
if (this._clusterConn) {
conns = [...conns, this._clusterConn]
}
const exec = new DiagnoticsExecutor(conns)
const options_ = options
return PromiseHelper.wrapAsync(() => exec.diagnostics(options_), callback)
}
/**
* Performs a ping operation against the cluster. Pinging the services which
* are specified (or all services if none are specified). Returns a report
* which describes the outcome of the ping operations which were performed.
*
* @param options Optional parameters for this operation.
* @param callback A node-style callback to be invoked after execution.
*/
ping(
options?: PingOptions,
callback?: NodeCallback<PingResult>
): Promise<PingResult> {
if (options instanceof Function) {
callback = arguments[0]
options = undefined
}
if (!options) {
options = {}
}
const conn = this._getClusterConn()
const exec = new PingExecutor(conn)
const options_ = options
return PromiseHelper.wrapAsync(() => exec.ping(options_), callback)
}
/**
* Shuts down this cluster object. Cleaning up all resources associated with it.
*
* @param callback A node-style callback to be invoked after execution.
*/
close(callback?: NodeCallback<void>): Promise<void> {
return PromiseHelper.wrapAsync(async () => {
const closeOneConn = async (conn: Connection) => {
return PromiseHelper.wrap<void>((wrapCallback) => {
conn.close(wrapCallback)
})
}
let allConns = Object.values(this._conns)
this._conns = {}
if (this._clusterConn) {
allConns = [...allConns, this._clusterConn]
this._clusterConn = null
}
this._closed = true
await Promise.all(allConns.map((conn) => closeOneConn(conn)))
}, callback)
}
private _buildConnOpts(
extraOpts: Partial<ConnectionOptions>
): ConnectionOptions {
const connOpts = {
connStr: this._connStr,
trustStorePath: this._trustStorePath,
tracer: this._tracer,
meter: this._meter,
logFunc: this._logFunc,
kvTimeout: this._kvTimeout,
kvDurableTimeout: this._kvDurableTimeout,
viewTimeout: this._viewTimeout,
queryTimeout: this._queryTimeout,
analyticsTimeout: this._analyticsTimeout,
searchTimeout: this._searchTimeout,
managementTimeout: this._managementTimeout,
...extraOpts,
}
if (this._auth) {
const passAuth = this._auth as PasswordAuthenticator
if (passAuth.username || passAuth.password) {
connOpts.username = passAuth.username
connOpts.password = passAuth.password
}
const certAuth = this._auth as CertificateAuthenticator
if (certAuth.certificatePath || certAuth.keyPath) {
connOpts.certificatePath = certAuth.certificatePath
connOpts.keyPath = certAuth.keyPath
}
}
return connOpts
}
private async _clusterConnect() {
return new Promise((resolve, reject) => {
const connOpts = this._buildConnOpts({})
const conn = new Connection(connOpts)
conn.connect((err) => {
if (err) {
return reject(err)
}
this._clusterConn = conn
resolve(null)
})
})
}
/**
@internal
*/
_getClusterConn(): Connection {
if (this._closed) {
throw new ClusterClosedError()
}
if (this._clusterConn) {
return this._clusterConn
}
const conns = Object.values(this._conns)
if (conns.length === 0) {
throw new NeedOpenBucketError()
}
return conns[0]
}
/**
* @internal
*/
_getConn(options: { bucketName: string }): Connection {
if (this._closed) {
throw new ClusterClosedError()
}
// Hijack the cluster-level connection if it is available
if (this._clusterConn) {
this._clusterConn.close(() => {
// TODO(brett19): Handle the close error here...
})
this._clusterConn = null
/*
let conn = this._clusterConn;
this._clusterConn = null;
conn.selectBucket(opts.bucketName);
this._conns[bucketName] = conn;
return conn;
*/
}
// Build a new connection for this, since there is no
// cluster-level connection available.
const connOpts = this._buildConnOpts({
bucketName: options.bucketName,
})
let conn = this._conns[options.bucketName]
if (!conn) {
conn = new Connection(connOpts)
conn.connect((err: Error | null) => {
if (err) {
libLogger('failed to connect to bucket: %O', err)
conn.close(() => undefined)
}
})
this._conns[options.bucketName] = conn
}
return conn
}
}