-
Notifications
You must be signed in to change notification settings - Fork 36
/
Cluster.scala
453 lines (420 loc) · 19 KB
/
Cluster.scala
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
/*
* Copyright (c) 2019 Couchbase, Inc.
*
* 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.
*/
package com.couchbase.client.scala
import com.couchbase.client.core.annotation.Stability
import com.couchbase.client.core.annotation.Stability.Uncommitted
import com.couchbase.client.core.diagnostics._
import com.couchbase.client.core.env.{Authenticator, PasswordAuthenticator}
import com.couchbase.client.core.transaction.CoreTransactionsReactive
import com.couchbase.client.core.util.ConnectionString
import com.couchbase.client.core.util.ConnectionStringUtil.asConnectionString
import com.couchbase.client.scala.analytics.{AnalyticsOptions, AnalyticsParameters, AnalyticsResult}
import com.couchbase.client.scala.diagnostics.{
DiagnosticsOptions,
PingOptions,
WaitUntilReadyOptions
}
import com.couchbase.client.scala.env.{ClusterEnvironment, SeedNode}
import com.couchbase.client.scala.manager.analytics.AnalyticsIndexManager
import com.couchbase.client.scala.manager.bucket.BucketManager
import com.couchbase.client.scala.manager.eventing.EventingFunctionManager
import com.couchbase.client.scala.manager.query.QueryIndexManager
import com.couchbase.client.scala.manager.search.SearchIndexManager
import com.couchbase.client.scala.manager.user.UserManager
import com.couchbase.client.scala.query.{QueryOptions, QueryParameters, QueryResult}
import com.couchbase.client.scala.search.SearchOptions
import com.couchbase.client.scala.search.queries.SearchQuery
import com.couchbase.client.scala.search.result.SearchResult
import com.couchbase.client.scala.search.vector.SearchRequest
import com.couchbase.client.scala.transactions.Transactions
import com.couchbase.client.scala.transactions.config.TransactionsConfig
import com.couchbase.client.scala.util.AsyncUtils
import com.couchbase.client.scala.util.CoreCommonConverters.convert
import java.util.UUID
import scala.concurrent.ExecutionContext
import scala.concurrent.duration.Duration
import scala.jdk.CollectionConverters._
import scala.util.Try
/** Represents a connection to a Couchbase cluster.
*
* These can be created through the functions in the companion object.
*
* @param _env the environment used to create this
* @param ec an ExecutionContext to use for any Future. Will be supplied automatically as long as resources are
* opened in the normal way, starting from functions in [[Cluster]]
*
* @author Graham Pople
* @since 1.0.0
*/
class Cluster private[scala] (
_env: => ClusterEnvironment,
authenticator: Authenticator,
connectionString: ConnectionString
) {
private[scala] implicit val ec: ExecutionContext = _env.ec
/** Access an asynchronous version of this API. */
val async = new AsyncCluster(_env, authenticator, connectionString)
/** Access a reactive version of this API. */
lazy val reactive = new ReactiveCluster(async)
/** The UserManager provides programmatic access to and creation of users and groups. */
lazy val users = new UserManager(async.users)
/** The BucketManager provides access to creating and getting buckets. */
lazy val buckets = new BucketManager(async.buckets)
lazy val queryIndexes = new QueryIndexManager(async.queryIndexes)
lazy val searchIndexes = new SearchIndexManager(async.searchIndexes)
lazy val analyticsIndexes =
new AnalyticsIndexManager(async.analyticsIndexes, reactive.analyticsIndexes)
@Stability.Uncommitted
lazy val eventingFunctions = new EventingFunctionManager(async.eventingFunctions)
@Stability.Uncommitted
lazy val transactions = new Transactions(
new CoreTransactionsReactive(
async.core,
_env.transactionsConfig.map(v => v.toCore).getOrElse(TransactionsConfig().toCore)
)
)
/** The environment used to create this cluster */
def env: ClusterEnvironment = _env
/** Opens and returns a Couchbase bucket resource that exists on this cluster.
*
* @param bucketName the name of the bucket to open
*/
def bucket(bucketName: String): Bucket = {
new Bucket(async.bucket(bucketName))
}
import com.couchbase.client.scala.util.DurationConversions._
/** Performs a N1QL query against the cluster.
*
* This is blocking. See [[Cluster.reactive]] for a reactive streaming version of this API, and
* [[Cluster.async]] for an asynchronous version.
*
* @param statement the N1QL statement to execute
* @param options any query options - see [[com.couchbase.client.scala.query.QueryOptions]] for documentation
*
* @return a `Try` containing a `Success(QueryResult)` (which includes any returned rows) if successful, else a
* `Failure`
*/
def query(statement: String, options: QueryOptions): Try[QueryResult] = {
Try(async.queryOps.queryBlocking(statement, options.toCore, null, null, null))
.map(result => convert(result))
}
/** Performs a N1QL query against the cluster.
*
* This is blocking. See [[Cluster.reactive]] for a reactive streaming version of this API, and
* [[Cluster.async]] for an asynchronous version.
*
* This overload provides only the most commonly used options. If you need to configure something more
* esoteric, use the overload that takes a [[com.couchbase.client.scala.query.QueryOptions]] instead, which supports all available options.
*
* @param statement the N1QL statement to execute
* @param parameters provides named or positional parameters for queries parameterised that way.
* @param timeout sets a maximum timeout for processing.
* @param adhoc if true (the default), adhoc mode is enabled: queries are just run. If false, adhoc mode is disabled
* and transparent prepared statement mode is enabled: queries are first prepared so they can be executed
* more efficiently in the future.
*
* @return a `Try` containing a `Success(QueryResult)` (which includes any returned rows) if successful, else a
* `Failure`
*/
def query(
statement: String,
parameters: QueryParameters = QueryParameters.None,
timeout: Duration = _env.timeoutConfig.queryTimeout(),
adhoc: Boolean = true
): Try[QueryResult] = {
Try(
async.queryOps.queryBlocking(
statement,
QueryOptions()
.adhoc(adhoc)
.timeout(timeout)
.parameters(parameters)
.toCore,
null,
null,
null
)
).map(result => convert(result))
}
/** Performs an Analytics query against the cluster.
*
* This is blocking. See [[Cluster.reactive]] for a reactive streaming version of this API, and
* [[Cluster.async]] for an asynchronous version.
*
* @param statement the Analytics query to execute
* @param options any query options - see [[com.couchbase.client.scala.analytics.AnalyticsOptions]] for documentation
*
* @return a `Try` containing a `Success(AnalyticsResult)` (which includes any returned rows) if successful, else a
* `Failure`
*/
def analyticsQuery(
statement: String,
options: AnalyticsOptions
): Try[AnalyticsResult] = {
AsyncUtils.block(async.analyticsQuery(statement, options))
}
/** Performs an Analytics query against the cluster.
*
* This is blocking. See [[Cluster.reactive]] for a reactive streaming version of this API, and
* [[Cluster.async]] for an asynchronous version.
*
* This overload provides only the most commonly used options. If you need to configure something more
* esoteric, use the overload that takes a [[com.couchbase.client.scala.analytics.AnalyticsOptions]] instead, which supports all available options.
*
* @param statement the Analytics query to execute
* @param parameters provides named or positional parameters for queries parameterised that way.
* @param timeout sets a maximum timeout for processing.
*
* @return a `Future` containing a `Success(AnalyticsResult)` (which includes any returned rows) if successful,
* else a `Failure`
*/
def analyticsQuery(
statement: String,
parameters: AnalyticsParameters = AnalyticsParameters.None,
timeout: Duration = _env.timeoutConfig.queryTimeout()
): Try[AnalyticsResult] = {
AsyncUtils.block(
async.analyticsQuery(statement, parameters, timeout)
)
}
/** Performs a Full Text Search (FTS) query, using default options.
*
* This can be used to perform a traditional FTS query, and/or a vector search.
*
* Use this to access global FTS indexes, and [[Scope.search]] for scoped indexes.
*
* This is blocking. See [[Cluster.reactive]] for a reactive streaming version of this API, and
* [[Cluster.async]] for an asynchronous version.
*
* @param indexName the name of the search index to use
* @param request the request to send to the FTS service.
*
* @return a `Try` containing a `Success(SearchResult)` (which includes any returned rows) if successful,
* else a `Failure`
*/
@Uncommitted
def search(
indexName: String,
request: SearchRequest
): Try[SearchResult] = {
search(indexName, request, SearchOptions())
}
/** Performs a Full Text Search (FTS) query.
*
* This can be used to perform a traditional FTS query, and/or a vector search.
*
* Use this to access global FTS indexes, and [[Scope.search]] for scoped indexes.
*
* This is blocking. See [[Cluster.reactive]] for a reactive streaming version of this API, and
* [[Cluster.async]] for an asynchronous version.
*
* @param indexName the name of the search index to use
* @param request the request to send to the FTS service.
* @param options see [[com.couchbase.client.scala.search.SearchOptions]]
* @return a `Try` containing a `Success(SearchResult)` (which includes any returned rows) if successful,
* else a `Failure`
*/
@Uncommitted
def search(
indexName: String,
request: SearchRequest,
options: SearchOptions
): Try[SearchResult] = {
AsyncUtils.block(async.search(indexName, request, options))
}
/** Performs a Full Text Search (FTS) query against the cluster.
*
* This is blocking. See [[Cluster.reactive]] for a reactive streaming version of this API, and
* [[Cluster.async]] for an asynchronous version.
*
* New users should consider the newer `search(String, SearchRequest)` interface instead, which can do both the traditional FTS {@link SearchQuery} that this method performs,
* and/or can also be used to perform a [[com.couchbase.client.scala.search.vector.VectorSearch]].
*
* @param indexName the name of the search index to use
* @param query the FTS query to execute. See
* [[com.couchbase.client.scala.search.queries.SearchQuery]] for more
* @param options the FTS query to execute. See [[com.couchbase.client.scala.search.SearchOptions]] for how to construct
* @return a `Try` containing a `Success(SearchResult)` (which includes any returned rows) if successful,
* else a `Failure`
*/
def searchQuery(
indexName: String,
query: SearchQuery,
options: SearchOptions
): Try[SearchResult] = {
AsyncUtils.block(async.searchQuery(indexName, query, options))
}
/** Performs a Full Text Search (FTS) query against the cluster.
*
* This is blocking. See [[Cluster.reactive]] for a reactive streaming version of this API, and
* [[Cluster.async]] for an asynchronous version.
*
* This overload provides only the most commonly used options. If you need to configure something more
* esoteric, use the overload that takes a [[com.couchbase.client.scala.search.SearchOptions]] instead, which supports all available options.
*
* New users should consider the newer `search(String, SearchRequest)` interface instead, which can do both the traditional FTS {@link SearchQuery} that this method performs,
* and/or can also be used to perform a [[com.couchbase.client.scala.search.vector.VectorSearch]].
*
* @param indexName the name of the search index to use
* @param query the FTS query to execute. See
* [[com.couchbase.client.scala.search.queries.SearchQuery]] for more
* @param timeout how long the operation is allowed to take
* @return a `Try` containing a `Success(SearchResult)` (which includes any returned rows) if successful,
* else a `Failure`
*/
def searchQuery(
indexName: String,
query: SearchQuery,
timeout: Duration = async.env.timeoutConfig.searchTimeout()
): Try[SearchResult] = {
AsyncUtils.block(async.searchQuery(indexName, query, timeout))
}
/** Shutdown all cluster resources.
*
* This should be called before application exit.
*
* @param timeout how long the disconnect is allowed to take; defaults to `disconnectTimeout` on the environment
*/
def disconnect(timeout: Duration = _env.timeoutConfig.disconnectTimeout()): Unit = {
reactive.disconnect(timeout).block()
}
/** Returns a `DiagnosticsResult`, reflecting the SDK's current view of all its existing connections to the
* cluster.
*
* @param reportId this will be returned in the `DiagnosticsResult`. If not specified it defaults to a UUID.
*
* @return a `DiagnosticsResult`
*/
def diagnostics(reportId: String = UUID.randomUUID.toString): Try[DiagnosticsResult] = {
AsyncUtils.block(async.diagnostics(reportId))
}
/** Returns a `DiagnosticsResult`, reflecting the SDK's current view of all its existing connections to the
* cluster.
*
* @param options options to customize the report generation
*
* @return a `DiagnosticsResult`
*/
def diagnostics(options: DiagnosticsOptions): Try[DiagnosticsResult] = {
AsyncUtils.block(async.diagnostics(options))
}
/** Performs application-level ping requests with custom options against services in the Couchbase cluster.
*
* Note that this operation performs active I/O against services and endpoints to assess their health. If you do
* not wish to perform I/O, consider using `.diagnostics()` instead.
*
* This overload provides only the most commonly used options. If you need to configure something more
* esoteric, use the overload that takes a [[com.couchbase.client.scala.diagnostics.PingOptions]] instead, which supports all available options.
*
* @param timeout the timeout to use for the operation
*
* @return the `PingResult` once complete.
*/
def ping(
timeout: Option[Duration] = None
): Try[PingResult] = {
AsyncUtils.block(async.ping(timeout))
}
/** Performs application-level ping requests with custom options against services in the Couchbase cluster.
*
* Note that this operation performs active I/O against services and endpoints to assess their health. If you do
* not wish to perform I/O, consider using `.diagnostics()` instead.
*
* @param options options to customize the ping
*
* @return the `PingResult` once complete.
*/
def ping(options: PingOptions): Try[PingResult] = {
AsyncUtils.block(async.ping(options))
}
/** Waits until the desired `ClusterState` is reached.
*
* This method will wait until either the cluster state is "online", or the timeout is reached. Since the SDK is
* bootstrapping lazily, this method allows to eagerly check during bootstrap if all of the services are online
* and usable before moving on.
*
* This overload provides only the most commonly used options. If you need to configure something more
* esoteric, use the overload that takes a [[com.couchbase.client.scala.diagnostics.WaitUntilReadyOptions]] instead, which supports all available options.
*
* @param timeout the maximum time to wait until readiness.
*/
def waitUntilReady(timeout: Duration): Try[Unit] = {
AsyncUtils.block(async.waitUntilReady(timeout))
}
/** Waits until the desired `ClusterState` is reached.
*
* This method will wait until either the cluster state is "online", or the timeout is reached. Since the SDK is
* bootstrapping lazily, this method allows to eagerly check during bootstrap if all of the services are online
* and usable before moving on.
*
* @param timeout the maximum time to wait until readiness.
* @param options options to customize the wait
*/
def waitUntilReady(timeout: Duration, options: WaitUntilReadyOptions): Try[Unit] = {
AsyncUtils.block(async.waitUntilReady(timeout, options))
}
}
/** Functions to allow creating a `Cluster`, which represents a connection to a Couchbase cluster.
*
* @define DeferredErrors Note that during opening of resources, all errors will be deferred until the first
* attempted operation.
*/
object Cluster {
/** Connect to a Couchbase cluster with a username and a password as credentials.
*
* $DeferredErrors
*
* @param connectionString connection string used to locate the Couchbase cluster.
* @param username the name of a user with appropriate permissions on the cluster.
* @param password the password of a user with appropriate permissions on the cluster.
*
* @return a [[Cluster]] representing a connection to the cluster
*/
def connect(connectionString: String, username: String, password: String): Try[Cluster] = {
connect(connectionString, ClusterOptions(PasswordAuthenticator.create(username, password)))
}
/** Connect to a Couchbase cluster with custom `Authenticator`.
*
* $DeferredErrors
*
* @param connectionString connection string used to locate the Couchbase cluster.
* @param options custom options used when connecting to the cluster.
*
* @return a [[Cluster]] representing a connection to the cluster
*/
def connect(connectionString: String, options: ClusterOptions): Try[Cluster] = {
AsyncCluster
.extractClusterEnvironment(connectionString, options)
.map(ce => {
val connStr = ConnectionString.create(connectionString)
val cluster = new Cluster(ce, options.authenticator, connStr)
cluster.async.performGlobalConnect()
cluster
})
}
/** Connect to a Couchbase cluster with a custom Set of [[com.couchbase.client.scala.env.SeedNode]].
*
* $DeferredErrors
*
* @param seedNodes known nodes from the Couchbase cluster to use for bootstrapping.
* @param options custom options used when connecting to the cluster.
*
* @return a [[Cluster]] representing a connection to the cluster
*/
def connect(seedNodes: Set[SeedNode], options: ClusterOptions): Try[Cluster] = {
connect(asConnectionString(seedNodes.map(_.toCore).asJava).original(), options)
}
}