@ragestudio/scylla-odm 0.15.1 → 0.16.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/_virtual/_rolldown/runtime.js +1 -1
- package/client.js +1 -1
- package/driver/index.d.ts +7 -7
- package/driver/index.js +1 -1
- package/driver/lib/auth/base-dse-authenticator.js +1 -1
- package/driver/lib/auth/dse-gssapi-auth-provider.js +1 -1
- package/driver/lib/auth/dse-plain-text-auth-provider.js +1 -1
- package/driver/lib/auth/gssapi-client.js +1 -1
- package/driver/lib/auth/index.js +1 -1
- package/driver/lib/auth/no-auth-provider.js +1 -1
- package/driver/lib/auth/plain-text-auth-provider.js +1 -1
- package/driver/lib/auth/provider.js +1 -1
- package/driver/lib/client-options.js +1 -1
- package/driver/lib/client.js +1 -1
- package/driver/lib/concurrent/index.js +1 -1
- package/driver/lib/connection.js +1 -1
- package/driver/lib/control-connection.js +1 -1
- package/driver/lib/datastax/graph/complex-type-helper.js +1 -1
- package/driver/lib/datastax/graph/custom-type-serializers.js +1 -1
- package/driver/lib/datastax/graph/graph-executor.js +1 -1
- package/driver/lib/datastax/graph/graph-serializer.js +1 -1
- package/driver/lib/datastax/graph/index.js +1 -1
- package/driver/lib/datastax/graph/options.js +1 -1
- package/driver/lib/datastax/graph/result-set.js +1 -1
- package/driver/lib/datastax/graph/structure.js +1 -1
- package/driver/lib/datastax/graph/type-serializers.js +1 -1
- package/driver/lib/datastax/graph/wrappers.js +1 -1
- package/driver/lib/datastax/search/date-range.js +1 -1
- package/driver/lib/datastax/search/index.js +1 -1
- package/driver/lib/encoder.js +1 -1
- package/driver/lib/errors.js +1 -1
- package/driver/lib/execution-options.js +1 -1
- package/driver/lib/execution-profile.js +1 -1
- package/driver/lib/geometry/geometry.js +1 -1
- package/driver/lib/geometry/index.js +1 -1
- package/driver/lib/geometry/line-string.js +1 -1
- package/driver/lib/geometry/point.js +1 -1
- package/driver/lib/geometry/polygon.js +1 -1
- package/driver/lib/host-connection-pool.js +1 -1
- package/driver/lib/host.js +1 -1
- package/driver/lib/insights-client.js +1 -1
- package/driver/lib/mapping/cache.js +1 -1
- package/driver/lib/mapping/doc-info-adapter.js +1 -1
- package/driver/lib/mapping/index.js +1 -1
- package/driver/lib/mapping/mapper.js +1 -1
- package/driver/lib/mapping/mapping-handler.js +1 -1
- package/driver/lib/mapping/model-batch-item.js +1 -1
- package/driver/lib/mapping/model-batch-mapper.js +1 -1
- package/driver/lib/mapping/model-mapper.js +1 -1
- package/driver/lib/mapping/model-mapping-info.js +1 -1
- package/driver/lib/mapping/object-selector.js +1 -1
- package/driver/lib/mapping/q.js +1 -1
- package/driver/lib/mapping/query-generator.js +9 -9
- package/driver/lib/mapping/result-mapper.js +3 -3
- package/driver/lib/mapping/result.js +1 -1
- package/driver/lib/mapping/table-mappings.js +1 -1
- package/driver/lib/mapping/tree.js +1 -1
- package/driver/lib/metadata/aggregate.js +1 -1
- package/driver/lib/metadata/client-state.js +1 -1
- package/driver/lib/metadata/data-collection.js +1 -1
- package/driver/lib/metadata/event-debouncer.js +1 -1
- package/driver/lib/metadata/index.js +1 -1
- package/driver/lib/metadata/materialized-view.js +1 -1
- package/driver/lib/metadata/schema-function.js +1 -1
- package/driver/lib/metadata/schema-index.js +1 -1
- package/driver/lib/metadata/schema-parser.js +1 -1
- package/driver/lib/metadata/table-metadata.js +1 -1
- package/driver/lib/metrics/client-metrics.js +1 -1
- package/driver/lib/metrics/default-metrics.js +1 -1
- package/driver/lib/metrics/index.js +1 -1
- package/driver/lib/operation-state.js +1 -1
- package/driver/lib/policies/address-resolution.js +1 -1
- package/driver/lib/policies/index.js +1 -1
- package/driver/lib/policies/load-balancing.js +1 -1
- package/driver/lib/policies/reconnection.js +1 -1
- package/driver/lib/policies/retry.js +1 -1
- package/driver/lib/policies/speculative-execution.js +1 -1
- package/driver/lib/policies/timestamp-generation.js +1 -1
- package/driver/lib/prepare-handler.js +1 -1
- package/driver/lib/promise-utils.js +1 -1
- package/driver/lib/readers.js +1 -1
- package/driver/lib/request-execution.js +1 -1
- package/driver/lib/request-handler.js +1 -1
- package/driver/lib/requests.js +1 -1
- package/driver/lib/stream-id-stack.js +1 -1
- package/driver/lib/streams.js +1 -1
- package/driver/lib/token.js +1 -1
- package/driver/lib/tokenizer.js +1 -1
- package/driver/lib/tracker/index.js +1 -1
- package/driver/lib/tracker/request-logger.js +1 -1
- package/driver/lib/tracker/request-tracker.js +1 -1
- package/driver/lib/types/big-decimal.js +1 -1
- package/driver/lib/types/duration.js +1 -1
- package/driver/lib/types/index.js +1 -1
- package/driver/lib/types/inet-address.js +1 -1
- package/driver/lib/types/integer.js +1 -1
- package/driver/lib/types/local-date.js +1 -1
- package/driver/lib/types/local-time.js +1 -1
- package/driver/lib/types/mutable-long.js +1 -1
- package/driver/lib/types/protocol-version.js +1 -1
- package/driver/lib/types/result-set.js +1 -1
- package/driver/lib/types/result-stream.js +1 -1
- package/driver/lib/types/row.js +1 -1
- package/driver/lib/types/time-uuid.js +1 -1
- package/driver/lib/types/tuple.js +1 -1
- package/driver/lib/types/uuid.js +1 -1
- package/driver/lib/types/vector.js +1 -1
- package/driver/lib/types/version-number.js +1 -1
- package/driver/lib/utils.js +2 -2
- package/driver/lib/writers.js +1 -1
- package/package.js +1 -1
- package/package.json +1 -1
- package/utils/queryParser.js +1 -1
- package/utils/typeChecker.js +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r};export{t as __exportAll};
|
package/client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import e from"./driver/index.js";import{Model as t}from"./model/index.js";import{Logger as n}from"./logger/index.js";import r from"./utils/loadModels.js";import i from"./utils/buildMapper.js";import a from"./utils/delay.js";import o from"node:path";const{SCYLLA_CONTACT_POINTS:s,SCYLLA_LOCAL_DATA_CENTER:c,SCYLLA_KEYSPACE:l}=process.env;var u=class{constructor(t={}){if(globalThis.__scylla_client)throw Error(`An instance of Scylla Client is already initialized`);this.config={modelsPath:o.resolve(process.cwd(),`db`),contactPoints:t.contactPoints??s?.split(`,`)??[`127.0.0.1`],localDataCenter:t.localDataCenter??c??`datacenter1`,keyspace:t.keyspace??l??`default_keyspace`,port:9042,maxRetries:3,retryDelay:1e3,...t};let n={contactPoints:this.config.contactPoints,localDataCenter:this.config.localDataCenter,keyspace:this.config.keyspace,protocolOptions:{port:this.config.port}};this.config.pooling&&(n.pooling=this.config.pooling),this.driver=new e.Client(n)}config;driver;mapper;models=new Map;model(e){return this.models.get(e)}logger=new n;async initialize(n={}){let a;try{a=await r(this.config.modelsPath)}catch(e){throw Error(`Failed to load models: ${e.message}`)}a=a.filter(e=>e instanceof t),this.mapper=new e.mapping.Mapper(this.driver,{models:i(a)}),globalThis.__scylla_client=this,this.logger.log(`Connecting...`),await this.connectWithRetry(),this.logger.log(`Connected`);for(let e of a)this.models.set(e.name,e),n?.sync===!0&&await e._sync()}async shutdown(){try{await this.driver.shutdown(),this.logger.log(`connection closed`),delete globalThis.__scylla_client}catch(e){throw this.logger.error(`error shutting down connection:`,e),e}}async connectWithRetry(){let e=null;for(let t=1;t<=this.config.maxRetries;t++)try{await this.driver.connect();return}catch(n){e=n,this.logger.warn(`Connection attempt ${t} failed: ${n.message}`),t<this.config.maxRetries&&(this.logger.log(`Retrying in ${this.config.retryDelay}ms...`),await a(this.config.retryDelay))}throw Error(`Failed to connect to ScyllaDB after ${this.config.maxRetries} attempts: ${e?.message}`)}async executeWithRetry(e,t=`operation`){let n=null;for(let r=1;r<=this.config.maxRetries;r++)try{return await e()}catch(e){if(n=e,this.isRetryableError(e)&&r<this.config.maxRetries){this.logger.warn(`Operation ${t} attempt ${r} failed: ${e.message}`),this.logger.log(`Retrying in ${this.config.retryDelay}ms...`),await a(this.config.retryDelay);continue}throw e}throw Error(`Operation ${t} failed after ${this.config.maxRetries} attempts: ${n?.message}`)}isRetryableError(e){let t=[`timeout`,`connection`,`network`,`unavailable`,`overloaded`,`no hosts available`],n=e.message?.toLowerCase()||``;return t.some(e=>n.includes(e))}};export{u as Client,u as default};
|
package/driver/index.d.ts
CHANGED
|
@@ -7,8 +7,8 @@ import { metadata } from "./lib/metadata/index.js";
|
|
|
7
7
|
import { concurrent } from "./lib/concurrent/index.js";
|
|
8
8
|
import { mapping } from "./lib/mapping/index.js";
|
|
9
9
|
import { geometry } from "./lib/geometry/index.js";
|
|
10
|
-
import * as events from "events";
|
|
11
|
-
import * as tls from "tls";
|
|
10
|
+
import * as events$1 from "events";
|
|
11
|
+
import * as tls$1 from "tls";
|
|
12
12
|
|
|
13
13
|
//#region src/driver/index.d.ts
|
|
14
14
|
declare const version: number;
|
|
@@ -18,7 +18,7 @@ type EmptyCallback = (err: Error) => void;
|
|
|
18
18
|
type ArrayOrObject = any[] | {
|
|
19
19
|
[key: string]: any;
|
|
20
20
|
};
|
|
21
|
-
declare class Client extends events.EventEmitter {
|
|
21
|
+
declare class Client extends events$1.EventEmitter {
|
|
22
22
|
hosts: HostMap;
|
|
23
23
|
keyspace: string;
|
|
24
24
|
metadata: metadata.Metadata;
|
|
@@ -43,7 +43,7 @@ declare class Client extends events.EventEmitter {
|
|
|
43
43
|
eachRow(query: string, params: ArrayOrObject, options: QueryOptions, rowCallback: (n: number, row: types.Row) => void, callback?: ValueCallback<types.ResultSet>): void;
|
|
44
44
|
eachRow(query: string, params: ArrayOrObject, rowCallback: (n: number, row: types.Row) => void, callback?: ValueCallback<types.ResultSet>): void;
|
|
45
45
|
eachRow(query: string, rowCallback: (n: number, row: types.Row) => void): void;
|
|
46
|
-
stream(query: string, params?: ArrayOrObject, options?: QueryOptions, callback?: EmptyCallback): events.EventEmitter;
|
|
46
|
+
stream(query: string, params?: ArrayOrObject, options?: QueryOptions, callback?: EmptyCallback): events$1.EventEmitter;
|
|
47
47
|
batch(queries: Array<string | {
|
|
48
48
|
query: string;
|
|
49
49
|
params?: ArrayOrObject;
|
|
@@ -61,14 +61,14 @@ declare class Client extends events.EventEmitter {
|
|
|
61
61
|
getReplicas(keyspace: string, token: Buffer): Host[];
|
|
62
62
|
getState(): metadata.ClientState;
|
|
63
63
|
}
|
|
64
|
-
interface HostMap extends events.EventEmitter {
|
|
64
|
+
interface HostMap extends events$1.EventEmitter {
|
|
65
65
|
length: number;
|
|
66
66
|
forEach(callback: (value: Host, key: string) => void): void;
|
|
67
67
|
get(key: string): Host;
|
|
68
68
|
keys(): string[];
|
|
69
69
|
values(): Host[];
|
|
70
70
|
}
|
|
71
|
-
interface Host extends events.EventEmitter {
|
|
71
|
+
interface Host extends events$1.EventEmitter {
|
|
72
72
|
address: string;
|
|
73
73
|
cassandraVersion: string;
|
|
74
74
|
datacenter: string;
|
|
@@ -163,7 +163,7 @@ interface ClientOptions {
|
|
|
163
163
|
readTimeout?: number;
|
|
164
164
|
tcpNoDelay?: boolean;
|
|
165
165
|
};
|
|
166
|
-
sslOptions?: tls.ConnectionOptions;
|
|
166
|
+
sslOptions?: tls$1.ConnectionOptions;
|
|
167
167
|
}
|
|
168
168
|
interface QueryOptions {
|
|
169
169
|
autoPage?: boolean;
|
package/driver/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import e from"./lib/errors.js";import t from"./lib/types/index.js";import n from"./lib/policies/index.js";import r from"./lib/tracker/index.js";import i from"./lib/metrics/index.js";import a from"./lib/auth/index.js";import o from"./lib/client-options.js";import{ExecutionProfile as s}from"./lib/execution-profile.js";import{ExecutionOptions as c}from"./lib/execution-options.js";import{version as l}from"../package.js";import{Token as u,TokenRange as d}from"./lib/token.js";import f from"./lib/geometry/index.js";import p from"./lib/encoder.js";import m from"./lib/metadata/index.js";import h from"./lib/client.js";import g from"./lib/mapping/index.js";import _ from"./lib/concurrent/index.js";const v={Token:u,TokenRange:d},y={Metadata:m};function b(){return o.defaultOptions()}const x={Client:h,ExecutionProfile:s,ExecutionOptions:c,types:t,errors:e,policies:n,auth:a,mapping:g,tracker:r,metrics:i,concurrent:_,token:v,metadata:y,Encoder:p,geometry:f,defaultOptions:b,version:l};export{x as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Authenticator as e}from"./provider.js";import t from"util";function n(e){this.authenticatorName=e}t.inherits(n,e),n.prototype.getMechanism=function(){throw Error(`Not implemented`)},n.prototype.getInitialServerChallenge=function(){throw Error(`Not implemented`)},n.prototype.initialResponse=function(e){if(!this._isDseAuthenticator())return this.evaluateChallenge(this.getInitialServerChallenge(),e);e(null,this.getMechanism())},n.prototype._isDseAuthenticator=function(){return this.authenticatorName===`com.datastax.bdp.cassandra.auth.DseAuthenticator`};export{n as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import e from"../utils.js";import{AuthProvider as t}from"./provider.js";import n from"./base-dse-authenticator.js";import r from"./gssapi-client.js";import i from"util";import a from"dns";import{createRequire as o}from"module";const s=o(import.meta.url),c=e.allocBufferFromString(`GSSAPI`),l=`GSSAPI-START`,u=e.allocBuffer(0);function d(t){try{this._kerberos=s(`kerberos`)}catch(e){if(e.code===`MODULE_NOT_FOUND`){let t=Error(`You must install module "kerberos" to use GSSAPI auth provider: https://www.npmjs.com/package/kerberos`);throw t.code=e.code,t}throw e}t||=e.emptyObject,this.authorizationId=t.authorizationId||t.user,this.service=t.service,this.hostNameResolver=t.hostNameResolver||d.lookupServiceResolver}i.inherits(d,t),d.prototype.newAuthenticator=function(e,t){let n=e;return e.indexOf(`:`)>0&&(n=e.split(`:`)[0]),new f(this._kerberos,n,t,this.authorizationId,this.service,this.hostNameResolver)},d.lookupServiceResolver=function(e,t){if(!a.lookupService)return d.reverseDnsResolver(e,t);a.lookupService(e,0,function(n,r){if(n)return t(n);if(!r)return t(null,e);t(null,r)})},d.reverseDnsResolver=function(e,t){a.reverse(e,function(n,r){if(n)return t(n);if(!r||!r.length)return t(null,e);t(null,r[0])})},d.useIpResolver=function(e,t){t(null,e)};function f(e,t,i,a,o,s){n.call(this,i),this.authorizationId=a,this.address=t,this.client=r.createNew(e,a,o),this.hostNameResolver=s}i.inherits(f,n),f.prototype.getMechanism=function(){return c},f.prototype.getInitialServerChallenge=function(){return e.allocBufferFromString(l)},f.prototype.initialResponse=function(t){let n=this,r=this.address;e.series([function(e){n.hostNameResolver(n.address,function(t,n){!t&&n&&(r=n),e()})},function(e){n.client.init(r,function(t){if(t)return e(t);if(!n._isDseAuthenticator())return n.evaluateChallenge(n.getInitialServerChallenge(),e);e(null,n.getMechanism())})}],t)},f.prototype.evaluateChallenge=function(e,t){(!e||e.toString()===l)&&(e=u),this.client.evaluateChallenge(e,t)},f.prototype.onAuthenticationSuccess=function(e){this.client.shutdown(function(){})};export{d as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import e from"../utils.js";import{AuthProvider as t}from"./provider.js";import n from"./base-dse-authenticator.js";import r from"util";const i=e.allocBufferFromString(`PLAIN`),a=e.allocBufferFromArray([0]),o=`PLAIN-START`;function s(e,t,n){if(typeof e!=`string`||typeof t!=`string`)throw TypeError(`Username and password must be a string`);this.username=e,this.password=t,this.authorizationId=n}r.inherits(s,t),s.prototype.newAuthenticator=function(e,t){return new c(t,this.username,this.password,this.authorizationId)};function c(t,r,i,a){n.call(this,t),this.authenticatorId=e.allocBufferFromString(r),this.password=e.allocBufferFromString(i),this.authorizationId=e.allocBufferFromString(a||``)}r.inherits(c,n),c.prototype.getMechanism=function(){return i},c.prototype.getInitialServerChallenge=function(){return e.allocBufferFromString(o)},c.prototype.evaluateChallenge=function(e,t){if(!e||e.toString()!==o)return t(Error(`Incorrect SASL challenge from server`));t(null,Buffer.concat([this.authorizationId,a,this.authenticatorId,a,this.password]))};export{s as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import e from"../utils.js";import t from"util";var n=class{constructor(e,t){this.authorizationId=e,this.service=t===void 0?`dse`:t}init(e,t){throw Error(`Not implemented`)}evaluateChallenge(e,t){throw Error(`Not implemented`)}shutdown(e){throw Error(`Not implemented`)}static createNew(e,t,n){return new r(e,t,n)}},r=class extends n{constructor(e,t,n){if(typeof e.initializeClient!=`function`)throw Error(`The driver expects version 1.x of the kerberos library`);super(t,n),this.kerberos=e,this.transitionIndex=0}init(e,n){this.host=e;let r=this.service;this.host&&(r=t.format(`%s@%s`,this.service,this.host));let i={gssFlags:this.kerberos.GSS_C_MUTUAL_FLAG};this.kerberos.initializeClient(r,i,(e,t)=>{if(e)return n(e);this.kerberosClient=t,n()})}evaluateChallenge(t,n){this[`transition`+this.transitionIndex](t,(t,r)=>{if(t)return n(t);this.transitionIndex++,n(null,r?e.allocBufferFromString(r,`base64`):e.allocBuffer(0))})}transition0(e,t){this.kerberosClient.step(``,t)}transition1(e,t){let n=e.toString(`base64`);this.kerberosClient.step(n,t)}transition2(e,t){this.kerberosClient.unwrap(e.toString(`base64`),(e,n)=>{if(e)return t(e,!1);let r=function(e,n){if(e)return t(e);t(null,n)};this.authorizationId===void 0?this.kerberosClient.wrap(n,null,r):this.kerberosClient.wrap(n,{user:this.authorizationId},r)})}shutdown(e){this.kerberosClient=null,e()}};export{n as default};
|
package/driver/lib/auth/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{AuthProvider as e,Authenticator as t}from"./provider.js";import{PlainTextAuthProvider as n}from"./plain-text-auth-provider.js";import r from"./dse-gssapi-auth-provider.js";import i from"./dse-plain-text-auth-provider.js";import a from"./no-auth-provider.js";var o={Authenticator:t,AuthProvider:e,DseGssapiAuthProvider:r,DsePlainTextAuthProvider:i,NoAuthProvider:a,PlainTextAuthProvider:n};export{o as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import e from"../errors.js";import{AuthProvider as t,Authenticator as n}from"./provider.js";import{PlainTextAuthenticator as r}from"./plain-text-auth-provider.js";var i=class extends t{newAuthenticator(e,t){return t===`com.datastax.bdp.cassandra.auth.DseAuthenticator`?new o:new a(e)}},a=class extends n{constructor(e){super(),this.endpoint=e}initialResponse(t){t(new e.AuthenticationError(`Host ${this.endpoint} requires authentication, but no authenticator found in the options`))}},o=class extends r{constructor(){super(``,``)}};export{i as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import e from"../utils.js";import{AuthProvider as t,Authenticator as n}from"./provider.js";import r from"util";function i(e,t){this.username=e,this.password=t}r.inherits(i,t),i.prototype.newAuthenticator=function(){return new a(this.username,this.password)};function a(e,t){this.username=e,this.password=t}r.inherits(a,n),a.prototype.initialResponse=function(t){t(null,Buffer.concat([e.allocBufferFromArray([0]),e.allocBufferFromString(this.username,`utf8`),e.allocBufferFromArray([0]),e.allocBufferFromString(this.password,`utf8`)]))},a.prototype.evaluateChallenge=function(e,t){t()};export{i as PlainTextAuthProvider,a as PlainTextAuthenticator};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
function e(){}e.prototype.newAuthenticator=function(e,t){throw Error(`This is an abstract class, you must implement newAuthenticator method or use another auth provider that inherits from this class`)};function t(){}t.prototype.initialResponse=function(e){e(Error(`Not implemented`))},t.prototype.evaluateChallenge=function(e,t){t(Error(`Not implemented`))},t.prototype.onAuthenticationSuccess=function(e){};export{e as AuthProvider,t as Authenticator};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import e from"./utils.js";import t from"./types/index.js";import n from"./policies/index.js";import r from"./tracker/index.js";import i from"./metrics/index.js";import a from"./auth/index.js";import o from"util";const s={0:2,1:1,2:0},c={0:1,1:1,2:0},l=2048;function u(){return{policies:{addressResolution:n.defaultAddressTranslator(),loadBalancing:n.defaultLoadBalancingPolicy(),reconnection:n.defaultReconnectionPolicy(),retry:n.defaultRetryPolicy(),speculativeExecution:n.defaultSpeculativeExecutionPolicy(),timestampGeneration:n.defaultTimestampGenerator()},queryOptions:{fetchSize:5e3,prepare:!1,captureStackTrace:!1},protocolOptions:{port:9042,maxSchemaAgreementWaitSeconds:10,maxVersion:0,noCompact:!1},pooling:{heartBeatInterval:3e4,warmup:!0},socketOptions:{connectTimeout:5e3,defunctReadTimeoutThreshold:64,keepAlive:!0,keepAliveDelay:0,readTimeout:12e3,tcpNoDelay:!0,coalescingThreshold:65536},authProvider:null,requestTracker:null,metrics:new i.DefaultMetrics,maxPrepared:500,refreshSchemaDelay:1e3,isMetadataSyncEnabled:!0,prepareOnAllHosts:!0,rePrepareOnUp:!0,encoding:{copyBuffer:!0,useUndefinedAsUnset:!0},monitorReporting:{enabled:!0}}}function d(t,n){arguments.length===1&&(n=arguments[0],t={});let a=e.deepExtend(t,u(),n);if(!Array.isArray(a.contactPoints)||a.contactPoints.length===0)throw TypeError(`Contacts points are not defined.`);for(let e=0;e<a.contactPoints.length;e++){let t=a.contactPoints[e];if(!t)throw TypeError(o.format(`Contact point %s (%s) is not a valid host name, the following values are valid contact points: ipAddress, hostName or ipAddress:port`,e,t))}if(a.sni=void 0,a.logEmitter||=function(){},!a.queryOptions)throw TypeError(`queryOptions not defined in options`);if(a.requestTracker!==null&&!(a.requestTracker instanceof r.RequestTracker))throw TypeError(`requestTracker must be an instance of RequestTracker`);if(!(a.metrics instanceof i.ClientMetrics))throw TypeError(`metrics must be an instance of ClientMetrics`);if(f(a.policies),p(a.protocolOptions),m(a.socketOptions),h(a),a.encoding=a.encoding||{},g(a.encoding),a.profiles&&!Array.isArray(a.profiles))throw TypeError(`profiles must be an Array of ExecutionProfile instances`);return _(a),v(a),a}function f(e){if(!e)throw TypeError(`policies not defined in options`);if(!(e.loadBalancing instanceof n.loadBalancing.LoadBalancingPolicy))throw TypeError(`Load balancing policy must be an instance of LoadBalancingPolicy`);if(!(e.reconnection instanceof n.reconnection.ReconnectionPolicy))throw TypeError(`Reconnection policy must be an instance of ReconnectionPolicy`);if(!(e.retry instanceof n.retry.RetryPolicy))throw TypeError(`Retry policy must be an instance of RetryPolicy`);if(!(e.addressResolution instanceof n.addressResolution.AddressTranslator))throw TypeError(`Address resolution policy must be an instance of AddressTranslator`);if(e.timestampGeneration!==null&&!(e.timestampGeneration instanceof n.timestampGeneration.TimestampGenerator))throw TypeError(`Timestamp generation policy must be an instance of TimestampGenerator`)}function p(e){if(!e)throw TypeError(`protocolOptions not defined in options`);let n=e.maxVersion;if(n&&(typeof n!=`number`||!t.protocolVersion.isSupported(n)))throw TypeError(o.format(`protocolOptions.maxVersion provided (%s) is invalid`,n))}function m(e){if(!e)throw TypeError(`socketOptions not defined in options`);if(typeof e.readTimeout!=`number`)throw TypeError(`socketOptions.readTimeout must be a Number`);if(typeof e.coalescingThreshold!=`number`||e.coalescingThreshold<=0)throw TypeError(`socketOptions.coalescingThreshold must be a positive Number`)}function h(e){if(!e.authProvider){let t=e.credentials;if(t){if(typeof t.username!=`string`||typeof t.password!=`string`)throw TypeError(`credentials username and password must be a string`);e.authProvider=new a.PlainTextAuthProvider(t.username,t.password)}else e.authProvider=new a.NoAuthProvider}else if(!(e.authProvider instanceof a.AuthProvider))throw TypeError(`options.authProvider must be an instance of AuthProvider`)}function g(e){if(e.map){let t=e.map;if(typeof t!=`function`||typeof t.prototype.forEach!=`function`||typeof t.prototype.set!=`function`)throw TypeError(`Map constructor not valid`)}if(e.set){let t=e.set;if(typeof t!=`function`||typeof t.prototype.forEach!=`function`||typeof t.prototype.add!=`function`)throw TypeError(`Set constructor not valid`)}if((e.useBigIntAsLong||e.useBigIntAsVarint)&&typeof BigInt>`u`)throw TypeError(`BigInt is not supported by the JavaScript engine`)}function _(e){function n(t){let n=e[t];if(n!=null&&typeof n!=`string`)throw TypeError(`${t} should be a String`)}if(n(`applicationName`),n(`applicationVersion`),e.id!==null&&e.id!==void 0&&!(e.id instanceof t.Uuid))throw TypeError(`Client id must be a Uuid`)}function v(e){let t=e.monitorReporting;if(typeof t!=`object`||!t)throw TypeError(`Monitor reporting must be an object, obtained: ${t}`)}function y(n){let r=n.controlConnection.protocolVersion,i=c,a=l;t.protocolVersion.uses2BytesStreamIds(r)||(i=s,a=128),n.options.queryOptions.consistency===void 0&&(n.options.queryOptions.consistency=n.metadata.isDbaas()?t.consistencies.localQuorum:t.consistencies.localOne),n.options.pooling=e.deepExtend({},{coreConnectionsPerHost:i,maxRequestsPerConnection:a},n.options.pooling)}var b={extend:d,defaultOptions:u,coreConnectionsPerHostV2:s,coreConnectionsPerHostV3:c,maxRequestsPerConnectionV2:128,maxRequestsPerConnectionV3:l,setMetadataDependent:y,continuousPageUnitBytes:`bytes`,continuousPageDefaultSize:5e3,continuousPageDefaultHighWaterMark:1e4};export{b as default};
|
package/driver/lib/client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import e from"./errors.js";import t from"./promise-utils.js";import n from"./utils.js";import r from"./types/index.js";import i from"./client-options.js";import{ProfileManager as a}from"./execution-profile.js";import{DefaultExecutionOptions as o}from"./execution-options.js";import{description as s,version as c}from"../../package.js";import l from"./requests.js";import u from"./metadata/client-state.js";import d from"./prepare-handler.js";import f from"./control-connection.js";import p from"./request-handler.js";import m from"./insights-client.js";import h from"./datastax/graph/graph-executor.js";import g from"util";import _ from"events";function v(e){_.EventEmitter.call(this),this.options=i.extend({logEmitter:this.emit.bind(this),id:r.Uuid.random()},e),Object.defineProperty(this,`profileManager`,{value:new a(this.options)}),Object.defineProperty(this,`controlConnection`,{value:new f(this.options,this.profileManager),writable:!0}),Object.defineProperty(this,`insightsClient`,{value:new m(this)}),this.setMaxListeners(0),this.connected=!1,this.isShuttingDown=!1,this.keyspace=e.keyspace,this.metadata=this.controlConnection.metadata,this.hosts=this.controlConnection.hosts,this.metrics=this.options.metrics,this._graphExecutor=new h(this,e,this._execute)}g.inherits(v,_.EventEmitter),v.prototype.connect=function(e){return this.connected&&e?e():t.optionalCallback(this._connect(),e)},v.prototype._connect=async function(){if(!this.connected){if(this.isShuttingDown)throw new e.NoHostAvailableError(null,`Connecting after shutdown is not supported`);if(this.connecting)return t.fromEvent(this,`connected`);this.connecting=!0,this.log(`info`,g.format(`Connecting to cluster using '%s' version %s`,s,c));try{await this.controlConnection.init(),this.hosts=this.controlConnection.hosts,await this.profileManager.init(this,this.hosts),this.keyspace&&await p.setKeyspace(this),i.setMetadataDependent(this),await this._warmup()}catch(e){throw await this.controlConnection.reset(),this.connected=!1,this.connecting=!1,this.emit(`connected`,e),e}this._setHostListeners(),this.profileManager.getDistance(this.controlConnection.host),this.insightsClient.init(),this.connected=!0,this.connecting=!1,this.emit(`connected`)}},v.prototype.execute=function(e,n,r,i){i||(typeof r==`function`?(i=r,r=null):typeof n==`function`&&(i=n,n=null));try{let a=o.create(r,this);return t.optionalCallback(this._execute(e,n,a),i)}catch(e){return i?i(e):Promise.reject(e)}},v.prototype.executeGraph=function(e,n,r,i){return i=i||r||n,typeof i==`function`?(n=typeof n==`function`?null:n,t.toCallback(this._graphExecutor.send(e,n,r),i)):this._graphExecutor.send(e,n,r)},v.prototype.eachRow=function(e,r,i,a,s){!s&&a&&typeof i==`function`?(s=n.validateFn(a,`rowCallback`),a=i):(s||=n.noop,a=n.validateFn(a||i||r,`rowCallback`)),r=typeof r==`function`?null:r;let c;try{c=o.create(i,this,a)}catch(e){return s(e)}let l=0,u=()=>t.toCallback(this._execute(e,r,c),d);function d(e,t){if(e)return s(e);if(l+=t.rowLength,t.rawPageState!==void 0){if(c.setPageState(t.rawPageState),c.isAutoPage())return u();t.nextPage=u}t.rowLength=l,s(null,t)}t.toCallback(this._execute(e,r,c),d)},v.prototype.stream=function(e,t,i,a){a||=n.noop;let o=new r.ResultStream({objectMode:1});function s(e,t){if(e&&o.emit(`error`,e),t&&t.nextPage){o._valve(function(){try{t.nextPage()}catch(e){o.emit(`error`,e)}});return}o._valve(null),o.add(null),a(e)}let c=!0;return this.eachRow(e,t,i,function(e,t){o.add(t)},function(e,t){if(c)return setImmediate(function(){s(e,t)});s(e,t)}),c=!1,o},v.prototype.batch=function(e,n,r){return!r&&typeof n==`function`&&(r=n,n=null),t.optionalCallback(this._batch(e,n),r)},v.prototype._batch=async function(t,n){if(!Array.isArray(t))throw new e.ArgumentError(`Queries should be an Array`);if(t.length===0)throw new e.ArgumentError(`Queries array should not be empty`);await this._connect();let i=o.create(n,this),a;if(i.isPrepared()){let e=this.controlConnection.protocolVersion,o=r.protocolVersion.supportsKeyspaceInRequest(e)&&n.keyspace||this.keyspace;a=await d.getPreparedMultiple(this,i.getLoadBalancingPolicy(),t,o)}else{a=Array(t.length);for(let n=0;n<t.length;n++){let r=t[n];if(!r)throw new e.ArgumentError(`Invalid query at index ${n}`);let i=typeof r==`string`?r:r.query;if(!i)throw new e.ArgumentError(`Invalid query at index ${n}`);a[n]={query:i,params:r.params}}}let s=await this._createBatchRequest(a,i);return await p.send(s,i,this)},v.prototype.getReplicas=function(e,t){return this.metadata.getReplicas(e,t)},v.prototype.getState=function(){return u.from(this)},v.prototype.log=n.log,v.prototype.shutdown=function(e){return t.optionalCallback(this._shutdown(),e)},v.prototype._shutdown=async function(){if(this.log(`info`,`Shutting down`),!this.hosts||!this.connected){this.connected=!1;return}this.connecting&&(this.log(`warning`,`Shutting down while connecting`),await t.fromEvent(this,`connected`)),this.connected=!1,this.isShuttingDown=!0;let e=this.hosts.values();this.insightsClient.shutdown(),this.controlConnection.shutdown(),this.options.policies.speculativeExecution.shutdown(),this.options.requestTracker&&this.options.requestTracker.shutdown(),await Promise.all(e.map(e=>e.shutdown(!1)))},v.prototype._waitForSchemaAgreement=async function(e){if(this.hosts.length===1)return!0;let n=process.hrtime(),r=this.options.protocolOptions.maxSchemaAgreementWaitSeconds;this.log(`info`,`Waiting for schema agreement`);let i;for(;!i&&process.hrtime(n)[0]<r;){if(i=await this.metadata.compareSchemaVersions(e),i){this.log(`info`,`Schema versions match`);break}await t.delay(500)}return i},v.prototype.handleSchemaAgreementAndRefresh=async function(e,t){let n=!1;try{n=await this._waitForSchemaAgreement(e)}catch(e){this.log(`warning`,`There was an error while waiting for the schema agreement between nodes`,e)}if(!this.options.isMetadataSyncEnabled)return n;try{await this.controlConnection.handleSchemaChange(t,!0)}catch(e){this.log(`warning`,`There was an error while handling schema change`,e)}return n},v.prototype._execute=async function(t,n,i){let a=this.controlConnection.protocolVersion;if(!i.isPrepared()&&n&&!Array.isArray(n)&&!r.protocolVersion.supportsNamedParameters(a))throw new e.ArgumentError(`Named parameters for simple statements are not supported, use prepare flag`);let o;if(this.connected||await this._connect(),!i.isPrepared())o=await this._createQueryRequest(t,i,n);else{let e=i.getLoadBalancingPolicy(),s=r.protocolVersion.supportsKeyspaceInRequest(a)&&i.getKeyspace()||this.keyspace,{queryId:c,meta:l}=await d.getPrepared(this,e,t,s);o=await this._createExecuteRequest(t,c,i,n,l)}return await p.send(o,i,this)},v.prototype._setHostListeners=function(){function e(e,t){return()=>e.emit(`hostUp`,t)}function t(e,t){return()=>e.emit(`hostDown`,t)}let n=this;this.hosts.on(`add`,function(r){r.on(`up`,e(n,r)),r.on(`down`,t(n,r)),n.emit(`hostAdd`,r)}),this.hosts.on(`remove`,function(e){e.removeAllListeners(),n.emit(`hostRemove`,e)}),this.hosts.forEach(function(r){r.on(`up`,e(n,r)),r.on(`down`,t(n,r))})},v.prototype._warmup=function(){let e=this.hosts.values();return t.times(e.length,32,async t=>{let n=e[t],i=this.profileManager.getDistance(n);if(i!==r.distance.ignored)if(this.options.pooling.warmup&&i===r.distance.local)try{await n.warmupPool(this.keyspace)}catch(e){this.log(`warning`,`Connection pool to host ${n.address} could not be created: ${e}`,e)}else n.initializePool()})},v.prototype._getEncoder=function(){let t=this.controlConnection.getEncoder();if(!t)throw new e.DriverInternalError(`Encoder is not defined`);return t},v.prototype._createBatchRequest=async function(e,t){let n=e[0];return n.meta&&await this._setRoutingInfo(t,n.params,n.meta),new l.BatchRequest(e,t)},v.prototype._createExecuteRequest=async function(e,t,r,i,a){return i=n.adaptNamedParamsPrepared(i,a.columns),await this._setRoutingInfo(r,i,a),new l.ExecuteRequest(e,t,i,r,a)},v.prototype._createQueryRequest=async function(e,t,r){await this.metadata.adaptUserHints(this.keyspace,t.getHints());let i=n.adaptNamedParamsWithHints(r,t);return this._getEncoder().setRoutingKeyFromUser(i.params,t,i.keyIndexes),new l.QueryRequest(e,i.params,t,i.namedParameters)},v.prototype._setRoutingInfo=async function(e,t,n){let r=this._getEncoder();if(!e.getKeyspace()&&n.keyspace&&e.setKeyspace(n.keyspace),e.getRoutingKey())return r.setRoutingKeyFromUser(t,e);if(Array.isArray(n.partitionKeys))return e.setRoutingIndexes(n.partitionKeys),r.setRoutingKeyFromMeta(n,t,e);try{let i=await this.metadata.getTable(n.keyspace,n.table);if(!i)return;e.setRoutingIndexes(i.partitionKeys.map(e=>n.columnsByName[e.name])),n.partitionKeys=e.getRoutingIndexes(),r.setRoutingKeyFromMeta(n,t,e)}catch{this.log(`warning`,g.format(`Table %s.%s metadata could not be retrieved`,n.keyspace,n.table))}};export{v as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import e from"../utils.js";import{Stream as t}from"stream";function n(e,n,a,o){if(!e)throw TypeError(`Client instance is not defined`);if(typeof n==`string`){if(Array.isArray(a))return new r(e,n,a,o).execute();if(a instanceof t)return new i(e,n,a,o).execute();throw TypeError(`parameters should be an Array or a Stream instance`)}if(Array.isArray(n))return o=a,new r(e,null,n,o).execute();throw TypeError(`A string query or query and parameters array should be provided`)}var r=class{constructor(t,n,r,i){this._client=t,this._query=n,this._parameters=r,i||=e.emptyObject,this._raiseOnFirstError=i.raiseOnFirstError!==!1,this._concurrencyLevel=Math.min(i.concurrencyLevel||100,this._parameters.length),this._queryOptions={prepare:!0,executionProfile:i.executionProfile},this._result=new a(i),this._stop=!1}execute(){let e=Array(this._concurrencyLevel);for(let t=0;t<this._concurrencyLevel;t++)e[t]=this._executeOneAtATime(t,0);return Promise.all(e).then(()=>this._result)}_executeOneAtATime(e,t){let n=e+this._concurrencyLevel*t;if(n>=this._parameters.length||this._stop)return Promise.resolve();let r=this._parameters[n],i,a;return this._query===null?(i=r.query,a=r.params):(i=this._query,a=r),this._client.execute(i,a,this._queryOptions).then(e=>this._result.setResultItem(n,e)).catch(e=>this._setError(n,e)).then(()=>this._executeOneAtATime(e,t+1))}_setError(e,t){if(this._result.setError(e,t),this._raiseOnFirstError)throw this._stop=!0,t}},i=class{constructor(t,n,r,i){this._client=t,this._query=n,this._stream=r,i||=e.emptyObject,this._raiseOnFirstError=i.raiseOnFirstError!==!1,this._concurrencyLevel=i.concurrencyLevel||100,this._queryOptions={prepare:!0,executionProfile:i.executionProfile},this._inFlight=0,this._index=0,this._result=new a(i),this._resolveCallback=null,this._rejectCallback=null,this._readEnded=!1}execute(){return new Promise((e,t)=>{this._resolveCallback=e,this._rejectCallback=t,this._stream.on(`data`,e=>this._executeOne(e)).on(`error`,e=>this._setReadEnded(e)).on(`end`,()=>this._setReadEnded())})}_executeOne(e){if(!Array.isArray(e))return this._setReadEnded(TypeError(`Stream should be in objectMode and should emit Array instances`));if(this._readEnded)return;let t=this._index++;this._inFlight++,this._client.execute(this._query,e,this._queryOptions).then(e=>{this._result.setResultItem(t,e),this._inFlight--}).catch(e=>{this._inFlight--,this._setError(t,e)}).then(()=>{this._stream.isPaused()&&this._stream.resume(),this._readEnded&&this._inFlight===0&&this._resolveCallback(this._result)}),this._inFlight>=this._concurrencyLevel&&this._stream.pause()}_setReadEnded(e){this._readEnded||(this._readEnded=!0,e?this._rejectCallback(e):this._inFlight===0&&this._resolveCallback(this._result))}_setError(e,t){this._result.setError(e,t),this._raiseOnFirstError&&(this._readEnded=!0,this._rejectCallback(t))}},a=class{constructor(e){this._collectResults=e.collectResults,this._maxErrors=e.maxErrors||100,this.totalExecuted=0,this.errors=[],this._collectResults?this.resultItems=[]:Object.defineProperty(this,`resultItems`,{enumerable:!1,get:()=>{throw Error(`Property resultItems can not be accessed when collectResults is set to false`)}})}setResultItem(e,t){this.totalExecuted++,this._collectResults&&(this.resultItems[e]=t)}setError(e,t){this.totalExecuted++,this.errors.length<this._maxErrors&&this.errors.push(t),this._collectResults&&(this.resultItems[e]=t)}},o={executeConcurrent:n,ResultSetGroup:a};export{o as default};
|
package/driver/lib/connection.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__commonJSMin as e,__require as t}from"../../_virtual/_rolldown/runtime.js";import{require_errors as n}from"./errors.js";import{require_promise_utils as r}from"./promise-utils.js";import{require_utils as i}from"./utils.js";import{require_types as a}from"./types/index.js";import{require_writers as o}from"./writers.js";import{require_execution_options as s}from"./execution-options.js";import{require_requests as c}from"./requests.js";import{require_encoder as l}from"./encoder.js";import{require_streams as u}from"./streams.js";import{require_stream_id_stack as d}from"./stream-id-stack.js";import{require_operation_state as f}from"./operation-state.js";var p=e(((e,p)=>{let m=t(`events`),h=t(`util`),g=t(`tls`),_=t(`net`),v=l(),{WriteQueue:y}=o(),b=c(),x=u(),S=i(),C=a(),w=n(),T=d(),E=f(),D=r(),{ExecutionOptions:O}=s();p.exports=class extends m.EventEmitter{constructor(e,t,n){if(super(),this.setMaxListeners(0),!n)throw Error(`options is not defined`);if(this.endpoint=e,this.endpointFriendlyName=this.endpoint,n.sni&&(this._serverName=e,this.endpoint=`${n.sni.addressResolver.getIp()}:${n.sni.port}`,this.endpointFriendlyName=`${this.endpoint} (${this._serverName})`),!this.endpoint||this.endpoint.indexOf(`:`)<0)throw Error(`EndPoint must contain the ip address and port separated by : symbol`);let r=this.endpoint.lastIndexOf(`:`);this.address=this.endpoint.substr(0,r),this.port=this.endpoint.substr(r+1),Object.defineProperty(this,`options`,{value:n,enumerable:!1,writable:!1}),t===null&&(t=C.protocolVersion.maxSupported,n.protocolOptions.maxVersion&&(t=n.protocolOptions.maxVersion),this._checkingVersion=!0),this.log=S.log,this.protocolVersion=t,this._operations=new Map,this._pendingWrites=[],this._preparing=new Map,this._idleTimeout=null,this._requestTimeoutTimer=null,this.timedOutOperations=0,this._streamIds=new T(this.protocolVersion),this._metrics=n.metrics,this.encoder=new v(t,n),this.keyspace=null,this.emitDrain=!1,this.connected=!1,this.isSocketOpen=!1,this.send=h.promisify(this.sendStream),this.closeAsync=h.promisify(this.close),this.openAsync=h.promisify(this.open),this.prepareOnceAsync=h.promisify(this.prepareOnce)}bindSocketListeners(){this.netClient.removeAllListeners(`connect`),this.netClient.removeAllListeners(`timeout`),this.isSocketOpen=!0,this.netClient.on(`close`,()=>{this.log(`info`,`Connection to ${this.endpointFriendlyName} closed`),this.isSocketOpen=!1;let e=this.connected;this.close(),e&&this.emit(`socketClose`)}),this.protocol=new x.Protocol({objectMode:!0}),this.parser=new x.Parser({objectMode:!0},this.encoder);let e=new x.ResultEmitter({objectMode:!0});e.on(`result`,this.handleResult.bind(this)),e.on(`row`,this.handleRow.bind(this)),e.on(`frameEnded`,this.freeStreamId.bind(this)),e.on(`nodeEvent`,this.handleNodeEvent.bind(this)),this.netClient.pipe(this.protocol).pipe(this.parser).pipe(e),this.writeQueue=new y(this.netClient,this.encoder,this.options)}open(e){let t=this;if(this.log(`info`,`Connecting to ${this.endpointFriendlyName}`),!this.options.sslOptions)this.netClient=new _.Socket({highWaterMark:this.options.socketOptions.coalescingThreshold}),this.netClient.connect(this.port,this.address,function(){t.log(`verbose`,`Socket connected to ${t.endpointFriendlyName}`),t.bindSocketListeners(),t.startup(e)});else{let n=S.extend({rejectUnauthorized:!1},this.options.sslOptions);this.options.sni&&(n.servername=this._serverName),this.netClient=g.connect(this.port,this.address,n,function(){t.log(`verbose`,`Secure socket connected to ${t.endpointFriendlyName} with protocol ${t.netClient.getProtocol()}`),t.bindSocketListeners(),t.startup(e)}),this.netClient.setMaxSendFragment(this.options.socketOptions.coalescingThreshold)}this.netClient.once(`error`,function(n){t.errorConnecting(n,!1,e)}),this.netClient.once(`timeout`,function(){let n=new C.DriverError(`Connection timeout`);t.errorConnecting(n,!0,e)}),this.netClient.setTimeout(this.options.socketOptions.connectTimeout),this.options.socketOptions.keepAlive&&this.netClient.setKeepAlive(!0,this.options.socketOptions.keepAliveDelay),this.netClient.setNoDelay(!!this.options.socketOptions.tcpNoDelay)}startup(e){this._checkingVersion&&this.log(`info`,`Trying to use protocol version 0x`+this.protocolVersion.toString(16));let t=this,n=new b.StartupRequest({noCompact:this.options.protocolOptions.noCompact,clientId:this.options.id,applicationName:this.options.applicationName,applicationVersion:this.options.applicationVersion});this.sendStream(n,null,function(n,i){if(n&&t._checkingVersion){let i=n instanceof w.ResponseError&&n.code===C.responseErrorCodes.protocolError&&n.message.indexOf(`Invalid or unsupported protocol version`)>=0;if(!i&&C.protocolVersion.canStartupResponseErrorBeWrapped(t.protocolVersion)&&(i=n instanceof w.ResponseError&&n.code===C.responseErrorCodes.serverError&&n.message.indexOf(`ProtocolException: Invalid or unsupported protocol version`)>0),i){let n=t.protocol.version;if(n===t.protocolVersion?n=C.protocolVersion.getLowerSupported(t.protocolVersion):C.protocolVersion.isSupported(t.protocol.version)||(t.log(`info`,`Protocol version ${t.protocol.version} not supported by this driver, downgrading`),n=C.protocolVersion.getLowerSupported(t.protocol.version)),!n)return r(Error(`Connection was unable to STARTUP using protocol version `+t.protocolVersion));t.log(`info`,`Protocol 0x`+t.protocolVersion.toString(16)+` not supported, using 0x`+n.toString(16)),t.decreaseVersion(n),setImmediate(function(){t.close(function(){t.open(e)})});return}}if(i&&i.mustAuthenticate)return t.startAuthenticating(i.authenticatorName,r);r(n)});function r(n){return n?t.errorConnecting(n,!1,e):t.connectionReady(e)}}errorConnecting(e,t,n){this.log(`warning`,`There was an error when trying to connect to the host ${this.endpointFriendlyName}`,e),t&&this.netClient.destroy(),this._metrics.onConnectionError(e),n(e)}connectionReady(e){this.emit(`connected`),this.connected=!0,this.netClient.removeAllListeners(`error`),this.netClient.on(`error`,this.handleSocketError.bind(this)),e()}decreaseVersion(e){this.protocolVersion=e,this.encoder.setProtocolVersion(e),this._streamIds.setVersion(e)}handleSocketError(e){this._metrics.onConnectionError(e),this.clearAndInvokePending(e)}clearAndInvokePending(e){this._idleTimeout&&=(clearTimeout(this._idleTimeout),null),this._requestTimeoutTimer&&=(clearTimeout(this._requestTimeoutTimer),null),this._streamIds.clear(),this.emitDrain&&this.emit(`drain`);let t=new C.DriverError(`Socket was closed`);t.isSocketError=!0,e&&(t.innerError=e);let n=Array.from(this._operations.values());this._operations=new Map,n.length>0&&this.log(`info`,`Invoking `+n.length+` pending callbacks`),S.each(n,function(e,n){e.setResult(t),n()});let r=this._pendingWrites;this._pendingWrites=[],S.each(r,function(e,n){e.setResult(t),n()})}startAuthenticating(e,t){if(!this.options.authProvider)return t(new w.AuthenticationError(`Authentication provider not set`));let n=this.options.authProvider.newAuthenticator(this.endpoint,e),r=this;n.initialResponse(function(e,i){if(e)return r.onAuthenticationError(t,e);r.authenticate(n,i,t)})}authenticate(e,t,n){let r=this,i=new b.AuthResponseRequest(t);if(this.protocolVersion===1){if(!e.username)return r.onAuthenticationError(n,new w.AuthenticationError(`Only plain text authenticator providers allowed under protocol v1`));i=new b.CredentialsRequest(e.username,e.password)}this.sendStream(i,null,function(t,i){if(t){if(t instanceof w.ResponseError&&t.code===C.responseErrorCodes.badCredentials){let e=new w.AuthenticationError(t.message);e.additionalInfo=t,t=e}return r.onAuthenticationError(n,t)}if(i.ready)return e.onAuthenticationSuccess(),n();if(i.authChallenge)return e.evaluateChallenge(i.token,function(t,i){if(t)return r.onAuthenticationError(n,t);r.authenticate(e,i,n)});n(new w.DriverInternalError(`Unexpected response from Cassandra: `+h.inspect(i)))})}onAuthenticationError(e,t){this._metrics.onAuthenticationError(t),e(t)}async changeKeyspace(e){if(!e||this.keyspace===e)return;if(this.toBeKeyspace===e)return D.fromEvent(this,`keyspaceChanged`);this.toBeKeyspace=e;let t=`USE "${e}"`;try{await this.send(new b.QueryRequest(t,null,null),null),this.keyspace=e,this.emit(`keyspaceChanged`,null,e)}catch(e){throw this.log(`error`,`Connection to ${this.endpointFriendlyName} could not switch active keyspace: ${e}`,e),this.emit(`keyspaceChanged`,e),e}finally{this.toBeKeyspace=null}}prepareOnce(e,t,n){let r=(t||``)+e,i=this._preparing.get(r);if(i)return i.once(`prepared`,n);i=new m.EventEmitter,i.setMaxListeners(0),i.once(`prepared`,n),this._preparing.set(r,i),this.sendStream(new b.PrepareRequest(e,t),null,(e,t)=>{i.emit(`prepared`,e,t),this._preparing.delete(r)})}sendStream(e,t,n){t||=O.empty();let r=new E(e,t.getRowCallback(),(e,t,r)=>{(!e||!e.isSocketError)&&this.emit(`responseDequeued`),n(e,t,r)}),i=this._getStreamId();return r.setRequestTimeout(t,this.options.socketOptions.readTimeout,this.endpoint,()=>this.timedOutOperations++,()=>this.timedOutOperations--),this._scheduleRequestTimeout(),i===null?(this.log(`info`,`Enqueuing `+this._pendingWrites.length+`, if this message is recurrent consider configuring more connections per host or lowering the pressure`),this._pendingWrites.push(r),r):(this._write(r,i),r)}_write(e,t){e.streamId=t;let n=this;this.writeQueue.push(e,function(r){if(r)return n._streamIds.push(t),e.setResult(r);n.log(`verbose`,`Sent stream #`+t+` to `+n.endpointFriendlyName),e.isByRow()&&n.parser.setOptions(t,{byRow:!0}),n._setIdleTimeout(),n._operations.set(t,e)})}_setIdleTimeout(){if(!this.options.pooling.heartBeatInterval)return;let e=this,t=this._idleTimeout;e._idleTimeout=setTimeout(()=>e._idleTimeoutHandler(),e.options.pooling.heartBeatInterval),t&&clearTimeout(t)}_idleTimeoutHandler(){if(this.sendingIdleQuery){this._idleTimeout=setTimeout(()=>this._idleTimeoutHandler(),this.options.pooling.heartBeatInterval);return}this.log(`verbose`,`Connection to ${this.endpointFriendlyName} idling, issuing a request to prevent disconnects`),this.sendingIdleQuery=!0,this.sendStream(b.options,null,e=>{this.sendingIdleQuery=!1,e&&(this.log(`warning`,`Received heartbeat request error`,e),this.emit(`idleRequestError`,e,this))})}_getStreamId(){return this._streamIds.pop()}_scheduleRequestTimeout(){this._requestTimeoutTimer&&=(clearTimeout(this._requestTimeoutTimer),null);let e=1/0;for(let t of this._operations.values())t._deadline&&t._deadline<e&&(e=t._deadline);if(e===1/0)return;let t=Math.max(0,e-Date.now());this._requestTimeoutTimer=setTimeout(()=>this._onRequestTimeout(),t)}_onRequestTimeout(){this._requestTimeoutTimer=null;let e=Date.now(),t=1/0;for(let[n,r]of this._operations)r._deadline&&(r._deadline<=e?r.checkTimeout(e):r._deadline<t&&(t=r._deadline));if(t!==1/0){let e=Math.max(0,t-Date.now());this._requestTimeoutTimer=setTimeout(()=>this._onRequestTimeout(),e)}}freeStreamId(e){let t=e.streamId;t<0||(this._operations.delete(t),this._streamIds.push(t),this.emitDrain&&this._streamIds.inUse===0&&this._pendingWrites.length===0&&this.emit(`drain`),this._writeNext())}_writeNext(){if(this._pendingWrites.length===0)return;let e=this._getStreamId();if(e===null)return;let t=this,n;for(;(n=this._pendingWrites.shift())&&!n.canBeWritten(););if(!n){this._streamIds.push(e);return}setImmediate(function(){t._write(n,e)})}getInFlight(){return this._streamIds.inUse}handleResult(e,t,n){let r=e.streamId;if(r<0)return this.log(`verbose`,`event received`,e);let i=this._operations.get(r);if(!i)return this.log(`error`,`The server replied with a wrong streamId #`+r);this.log(`verbose`,`Received frame #`+r+` from `+this.endpointFriendlyName),i.setResult(t,n,e.bodyLength)}handleNodeEvent(e,t){switch(t.eventType){case C.protocolEvents.schemaChange:this.emit(`nodeSchemaChange`,t);break;case C.protocolEvents.topologyChange:this.emit(`nodeTopologyChange`,t);break;case C.protocolEvents.statusChange:this.emit(`nodeStatusChange`,t);break}}handleRow(e,t,n,r,i){let a=e.streamId;if(a<0)return this.log(`verbose`,`Event received`,e);let o=this._operations.get(a);if(!o)return this.log(`error`,`The server replied with a wrong streamId #`+a);o.setResultRow(t,n,r,i,e)}close(e){if(e||=S.noop,!this.connected&&!this.isSocketOpen||(this.connected=!1,this.removeAllListeners(`drain`),this.clearAndInvokePending(),!this.isSocketOpen))return e();this.isSocketOpen=!1,this.log(`verbose`,`Closing connection to ${this.endpointFriendlyName}`);let t=this,n=setTimeout(()=>{this.log(`info`,`${this.endpointFriendlyName} did not respond to connection close within ${this.options.socketOptions.connectTimeout}ms, destroying connection`),this.netClient.destroy()},this.options.socketOptions.connectTimeout);this.netClient.once(`close`,function(r){clearTimeout(n),r&&t.log(`info`,`The socket closed with a transmission error`),setImmediate(e)}),this.netClient.removeAllListeners(`error`),this.netClient.on(`error`,e=>this.clearAndInvokePending(e)),this.netClient.end()}getLocalAddress(){if(this.netClient)return this.netClient.localAddress}}}));export default p();export{p as require_connection};
|
|
1
|
+
import e from"./errors.js";import t from"./promise-utils.js";import n from"./utils.js";import r from"./types/index.js";import{WriteQueue as i}from"./writers.js";import{ExecutionOptions as a}from"./execution-options.js";import o from"./requests.js";import s from"./encoder.js";import c from"./streams.js";import l from"./stream-id-stack.js";import u from"./operation-state.js";import d from"util";import f from"net";import p from"events";import m from"tls";var h=class extends p.EventEmitter{constructor(e,t,i){if(super(),this.setMaxListeners(0),!i)throw Error(`options is not defined`);if(this.endpoint=e,this.endpointFriendlyName=this.endpoint,i.sni&&(this._serverName=e,this.endpoint=`${i.sni.addressResolver.getIp()}:${i.sni.port}`,this.endpointFriendlyName=`${this.endpoint} (${this._serverName})`),!this.endpoint||this.endpoint.indexOf(`:`)<0)throw Error(`EndPoint must contain the ip address and port separated by : symbol`);let a=this.endpoint.lastIndexOf(`:`);this.address=this.endpoint.substr(0,a),this.port=this.endpoint.substr(a+1),Object.defineProperty(this,`options`,{value:i,enumerable:!1,writable:!1}),t===null&&(t=r.protocolVersion.maxSupported,i.protocolOptions.maxVersion&&(t=i.protocolOptions.maxVersion),this._checkingVersion=!0),this.log=n.log,this.protocolVersion=t,this._operations=new Map,this._pendingWrites=[],this._preparing=new Map,this._idleTimeout=null,this._requestTimeoutTimer=null,this.timedOutOperations=0,this._streamIds=new l(this.protocolVersion),this._metrics=i.metrics,this.encoder=new s(t,i),this.keyspace=null,this.emitDrain=!1,this.connected=!1,this.isSocketOpen=!1,this.send=d.promisify(this.sendStream),this.closeAsync=d.promisify(this.close),this.openAsync=d.promisify(this.open),this.prepareOnceAsync=d.promisify(this.prepareOnce)}bindSocketListeners(){this.netClient.removeAllListeners(`connect`),this.netClient.removeAllListeners(`timeout`),this.isSocketOpen=!0,this.netClient.on(`close`,()=>{this.log(`info`,`Connection to ${this.endpointFriendlyName} closed`),this.isSocketOpen=!1;let e=this.connected;this.close(),e&&this.emit(`socketClose`)}),this.protocol=new c.Protocol({objectMode:!0}),this.parser=new c.Parser({objectMode:!0},this.encoder);let e=new c.ResultEmitter({objectMode:!0});e.on(`result`,this.handleResult.bind(this)),e.on(`row`,this.handleRow.bind(this)),e.on(`frameEnded`,this.freeStreamId.bind(this)),e.on(`nodeEvent`,this.handleNodeEvent.bind(this)),this.netClient.pipe(this.protocol).pipe(this.parser).pipe(e),this.writeQueue=new i(this.netClient,this.encoder,this.options)}open(e){let t=this;if(this.log(`info`,`Connecting to ${this.endpointFriendlyName}`),!this.options.sslOptions)this.netClient=new f.Socket({highWaterMark:this.options.socketOptions.coalescingThreshold}),this.netClient.connect(this.port,this.address,function(){t.log(`verbose`,`Socket connected to ${t.endpointFriendlyName}`),t.bindSocketListeners(),t.startup(e)});else{let r=n.extend({rejectUnauthorized:!1},this.options.sslOptions);this.options.sni&&(r.servername=this._serverName),this.netClient=m.connect(this.port,this.address,r,function(){t.log(`verbose`,`Secure socket connected to ${t.endpointFriendlyName} with protocol ${t.netClient.getProtocol()}`),t.bindSocketListeners(),t.startup(e)}),this.netClient.setMaxSendFragment(this.options.socketOptions.coalescingThreshold)}this.netClient.once(`error`,function(n){t.errorConnecting(n,!1,e)}),this.netClient.once(`timeout`,function(){let n=new r.DriverError(`Connection timeout`);t.errorConnecting(n,!0,e)}),this.netClient.setTimeout(this.options.socketOptions.connectTimeout),this.options.socketOptions.keepAlive&&this.netClient.setKeepAlive(!0,this.options.socketOptions.keepAliveDelay),this.netClient.setNoDelay(!!this.options.socketOptions.tcpNoDelay)}startup(t){this._checkingVersion&&this.log(`info`,`Trying to use protocol version 0x`+this.protocolVersion.toString(16));let n=this,i=new o.StartupRequest({noCompact:this.options.protocolOptions.noCompact,clientId:this.options.id,applicationName:this.options.applicationName,applicationVersion:this.options.applicationVersion});this.sendStream(i,null,function(i,o){if(i&&n._checkingVersion){let o=i instanceof e.ResponseError&&i.code===r.responseErrorCodes.protocolError&&i.message.indexOf(`Invalid or unsupported protocol version`)>=0;if(!o&&r.protocolVersion.canStartupResponseErrorBeWrapped(n.protocolVersion)&&(o=i instanceof e.ResponseError&&i.code===r.responseErrorCodes.serverError&&i.message.indexOf(`ProtocolException: Invalid or unsupported protocol version`)>0),o){let e=n.protocol.version;if(e===n.protocolVersion?e=r.protocolVersion.getLowerSupported(n.protocolVersion):r.protocolVersion.isSupported(n.protocol.version)||(n.log(`info`,`Protocol version ${n.protocol.version} not supported by this driver, downgrading`),e=r.protocolVersion.getLowerSupported(n.protocol.version)),!e)return a(Error(`Connection was unable to STARTUP using protocol version `+n.protocolVersion));n.log(`info`,`Protocol 0x`+n.protocolVersion.toString(16)+` not supported, using 0x`+e.toString(16)),n.decreaseVersion(e),setImmediate(function(){n.close(function(){n.open(t)})});return}}if(o&&o.mustAuthenticate)return n.startAuthenticating(o.authenticatorName,a);a(i)});function a(e){return e?n.errorConnecting(e,!1,t):n.connectionReady(t)}}errorConnecting(e,t,n){this.log(`warning`,`There was an error when trying to connect to the host ${this.endpointFriendlyName}`,e),t&&this.netClient.destroy(),this._metrics.onConnectionError(e),n(e)}connectionReady(e){this.emit(`connected`),this.connected=!0,this.netClient.removeAllListeners(`error`),this.netClient.on(`error`,this.handleSocketError.bind(this)),e()}decreaseVersion(e){this.protocolVersion=e,this.encoder.setProtocolVersion(e),this._streamIds.setVersion(e)}handleSocketError(e){this._metrics.onConnectionError(e),this.clearAndInvokePending(e)}clearAndInvokePending(e){this._idleTimeout&&=(clearTimeout(this._idleTimeout),null),this._requestTimeoutTimer&&=(clearTimeout(this._requestTimeoutTimer),null),this._streamIds.clear(),this.emitDrain&&this.emit(`drain`);let t=new r.DriverError(`Socket was closed`);t.isSocketError=!0,e&&(t.innerError=e);let i=Array.from(this._operations.values());this._operations=new Map,i.length>0&&this.log(`info`,`Invoking `+i.length+` pending callbacks`),n.each(i,function(e,n){e.setResult(t),n()});let a=this._pendingWrites;this._pendingWrites=[],n.each(a,function(e,n){e.setResult(t),n()})}startAuthenticating(t,n){if(!this.options.authProvider)return n(new e.AuthenticationError(`Authentication provider not set`));let r=this.options.authProvider.newAuthenticator(this.endpoint,t),i=this;r.initialResponse(function(e,t){if(e)return i.onAuthenticationError(n,e);i.authenticate(r,t,n)})}authenticate(t,n,i){let a=this,s=new o.AuthResponseRequest(n);if(this.protocolVersion===1){if(!t.username)return a.onAuthenticationError(i,new e.AuthenticationError(`Only plain text authenticator providers allowed under protocol v1`));s=new o.CredentialsRequest(t.username,t.password)}this.sendStream(s,null,function(n,o){if(n){if(n instanceof e.ResponseError&&n.code===r.responseErrorCodes.badCredentials){let t=new e.AuthenticationError(n.message);t.additionalInfo=n,n=t}return a.onAuthenticationError(i,n)}if(o.ready)return t.onAuthenticationSuccess(),i();if(o.authChallenge)return t.evaluateChallenge(o.token,function(e,n){if(e)return a.onAuthenticationError(i,e);a.authenticate(t,n,i)});i(new e.DriverInternalError(`Unexpected response from Cassandra: `+d.inspect(o)))})}onAuthenticationError(e,t){this._metrics.onAuthenticationError(t),e(t)}async changeKeyspace(e){if(!e||this.keyspace===e)return;if(this.toBeKeyspace===e)return t.fromEvent(this,`keyspaceChanged`);this.toBeKeyspace=e;let n=`USE "${e}"`;try{await this.send(new o.QueryRequest(n,null,null),null),this.keyspace=e,this.emit(`keyspaceChanged`,null,e)}catch(e){throw this.log(`error`,`Connection to ${this.endpointFriendlyName} could not switch active keyspace: ${e}`,e),this.emit(`keyspaceChanged`,e),e}finally{this.toBeKeyspace=null}}prepareOnce(e,t,n){let r=(t||``)+e,i=this._preparing.get(r);if(i)return i.once(`prepared`,n);i=new p.EventEmitter,i.setMaxListeners(0),i.once(`prepared`,n),this._preparing.set(r,i),this.sendStream(new o.PrepareRequest(e,t),null,(e,t)=>{i.emit(`prepared`,e,t),this._preparing.delete(r)})}sendStream(e,t,n){t||=a.empty();let r=new u(e,t.getRowCallback(),(e,t,r)=>{(!e||!e.isSocketError)&&this.emit(`responseDequeued`),n(e,t,r)}),i=this._getStreamId();return r.setRequestTimeout(t,this.options.socketOptions.readTimeout,this.endpoint,()=>this.timedOutOperations++,()=>this.timedOutOperations--),this._scheduleRequestTimeout(),i===null?(this.log(`info`,`Enqueuing `+this._pendingWrites.length+`, if this message is recurrent consider configuring more connections per host or lowering the pressure`),this._pendingWrites.push(r),r):(this._write(r,i),r)}_write(e,t){e.streamId=t;let n=this;this.writeQueue.push(e,function(r){if(r)return n._streamIds.push(t),e.setResult(r);n.log(`verbose`,`Sent stream #`+t+` to `+n.endpointFriendlyName),e.isByRow()&&n.parser.setOptions(t,{byRow:!0}),n._setIdleTimeout(),n._operations.set(t,e)})}_setIdleTimeout(){if(!this.options.pooling.heartBeatInterval)return;let e=this,t=this._idleTimeout;e._idleTimeout=setTimeout(()=>e._idleTimeoutHandler(),e.options.pooling.heartBeatInterval),t&&clearTimeout(t)}_idleTimeoutHandler(){if(this.sendingIdleQuery){this._idleTimeout=setTimeout(()=>this._idleTimeoutHandler(),this.options.pooling.heartBeatInterval);return}this.log(`verbose`,`Connection to ${this.endpointFriendlyName} idling, issuing a request to prevent disconnects`),this.sendingIdleQuery=!0,this.sendStream(o.options,null,e=>{this.sendingIdleQuery=!1,e&&(this.log(`warning`,`Received heartbeat request error`,e),this.emit(`idleRequestError`,e,this))})}_getStreamId(){return this._streamIds.pop()}_scheduleRequestTimeout(){this._requestTimeoutTimer&&=(clearTimeout(this._requestTimeoutTimer),null);let e=1/0;for(let t of this._operations.values())t._deadline&&t._deadline<e&&(e=t._deadline);if(e===1/0)return;let t=Math.max(0,e-Date.now());this._requestTimeoutTimer=setTimeout(()=>this._onRequestTimeout(),t)}_onRequestTimeout(){this._requestTimeoutTimer=null;let e=Date.now(),t=1/0;for(let[n,r]of this._operations)r._deadline&&(r._deadline<=e?r.checkTimeout(e):r._deadline<t&&(t=r._deadline));if(t!==1/0){let e=Math.max(0,t-Date.now());this._requestTimeoutTimer=setTimeout(()=>this._onRequestTimeout(),e)}}freeStreamId(e){let t=e.streamId;t<0||(this._operations.delete(t),this._streamIds.push(t),this.emitDrain&&this._streamIds.inUse===0&&this._pendingWrites.length===0&&this.emit(`drain`),this._writeNext())}_writeNext(){if(this._pendingWrites.length===0)return;let e=this._getStreamId();if(e===null)return;let t=this,n;for(;(n=this._pendingWrites.shift())&&!n.canBeWritten(););if(!n){this._streamIds.push(e);return}setImmediate(function(){t._write(n,e)})}getInFlight(){return this._streamIds.inUse}handleResult(e,t,n){let r=e.streamId;if(r<0)return this.log(`verbose`,`event received`,e);let i=this._operations.get(r);if(!i)return this.log(`error`,`The server replied with a wrong streamId #`+r);this.log(`verbose`,`Received frame #`+r+` from `+this.endpointFriendlyName),i.setResult(t,n,e.bodyLength)}handleNodeEvent(e,t){switch(t.eventType){case r.protocolEvents.schemaChange:this.emit(`nodeSchemaChange`,t);break;case r.protocolEvents.topologyChange:this.emit(`nodeTopologyChange`,t);break;case r.protocolEvents.statusChange:this.emit(`nodeStatusChange`,t);break}}handleRow(e,t,n,r,i){let a=e.streamId;if(a<0)return this.log(`verbose`,`Event received`,e);let o=this._operations.get(a);if(!o)return this.log(`error`,`The server replied with a wrong streamId #`+a);o.setResultRow(t,n,r,i,e)}close(e){if(e||=n.noop,!this.connected&&!this.isSocketOpen||(this.connected=!1,this.removeAllListeners(`drain`),this.clearAndInvokePending(),!this.isSocketOpen))return e();this.isSocketOpen=!1,this.log(`verbose`,`Closing connection to ${this.endpointFriendlyName}`);let t=this,r=setTimeout(()=>{this.log(`info`,`${this.endpointFriendlyName} did not respond to connection close within ${this.options.socketOptions.connectTimeout}ms, destroying connection`),this.netClient.destroy()},this.options.socketOptions.connectTimeout);this.netClient.once(`close`,function(n){clearTimeout(r),n&&t.log(`info`,`The socket closed with a transmission error`),setImmediate(e)}),this.netClient.removeAllListeners(`error`),this.netClient.on(`error`,e=>this.clearAndInvokePending(e)),this.netClient.end()}getLocalAddress(){if(this.netClient)return this.netClient.localAddress}};export{h as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__commonJSMin as e,__require as t}from"../../_virtual/_rolldown/runtime.js";import{require_errors as n}from"./errors.js";import{require_promise_utils as r}from"./promise-utils.js";import{require_utils as i}from"./utils.js";import{require_types as a}from"./types/index.js";import{require_requests as o}from"./requests.js";import{require_connection as s}from"./connection.js";import{require_host as c}from"./host.js";import{require_metadata as l}from"./metadata/index.js";import{require_event_debouncer as u}from"./metadata/event-debouncer.js";var d=e(((e,d)=>{let f=t(`events`),p=t(`util`),m=t(`net`),h=t(`dns`),g=n(),{Host:_,HostMap:v}=c(),y=l(),b=u(),x=s(),S=o(),C=i(),w=a(),T=r(),E=p.format,D=1e3,O={created:`CREATED`,updated:`UPDATED`,dropped:`DROPPED`};var k=class extends f.EventEmitter{constructor(e,t,n){super(),this.protocolVersion=null,this.hosts=new v,this.setMaxListeners(0),this.log=C.log,Object.defineProperty(this,`options`,{value:e,enumerable:!1,writable:!1}),this.metadata=new y(this.options,this),this.initialized=!1,this.host=null,this.connection=null,this._addressTranslator=this.options.policies.addressResolution,this._reconnectionPolicy=this.options.policies.reconnection,this._reconnectionSchedule=this._reconnectionPolicy.newSchedule(),this._isShuttingDown=!1,this._encoder=null,this._debouncer=new b(e.refreshSchemaDelay,this.log.bind(this)),this._profileManager=t,this._triedHosts=null,this._resolvedContactPoints=new Map,this._contactPoints=new Set,this._topologyChangeTimeout=null,this._nodeStatusChangeTimeout=null,n&&n.borrowHostConnection&&(this._borrowHostConnection=n.borrowHostConnection),n&&n.createConnection&&(this._createConnection=n.createConnection)}_addContactPoint(e,t,n,r){if(e===null){this._resolvedContactPoints.set(n,C.emptyArray);return}let i=parseInt(t,10)||this.options.protocolOptions.port,a=`${e}:${i}`;this._contactPoints.add(a);let o=r?`[${e}]:${i}`:a,s=this._resolvedContactPoints.get(n);(s===void 0||s===C.emptyArray)&&(s=[],this._resolvedContactPoints.set(n,s)),s.push(o)}async _parseContactPoint(e){let t=e,n=null;if(e.indexOf(`[`)===0&&e.indexOf(`]:`)>1){let r=e.lastIndexOf(`]:`);t=e.substr(1,r-1),n=e.substr(r+2)}else if(e.indexOf(`:`)>0){let r=e.split(`:`);r.length===2&&(t=r[0],n=r[1])}if(m.isIP(t)){this._addContactPoint(t,n,e,m.isIPv6(t));return}let r=await this._resolveAll(t);r.length>0?r.forEach(t=>this._addContactPoint(t.address,n,e,t.isIPv6)):this._addContactPoint(null,null,e,!1)}async init(){if(!this.initialized){if(!this.options.sni)await Promise.all(this.options.contactPoints.map(e=>this._parseContactPoint(e)));else{this.options.contactPoints.forEach(e=>this._contactPoints.add(e));let e=this.options.sni.address,t=e.lastIndexOf(`:`);if(t===-1)throw new new g.DriverInternalError(`The SNI endpoint address should contain ip/name and port`);let n=e.substr(0,t);this.options.sni.port=e.substr(t+1),this.options.sni.addressResolver=new C.AddressResolver({nameOrIp:n,dns:h}),await this.options.sni.addressResolver.init()}if(this._contactPoints.size===0)throw new g.NoHostAvailableError({},`No host could be resolved`);await this._initializeConnection()}}_setHealthListeners(e,t){let n=this,r=0;function i(){e.removeListener(`down`,o),e.removeListener(`ignore`,o),t.removeListener(`socketClose`,s)}function a(a){r++===0&&(i(),!n._isShuttingDown&&(a?n.log(`warning`,`Host ${e.address} used by the ControlConnection DOWN, connection to ${t.endpointFriendlyName} will not longer be used`):n.log(`warning`,`Connection to ${t.endpointFriendlyName} used by the ControlConnection was closed`),T.toBackground(n._refresh())))}function o(){a(!0)}function s(){a(!1)}e.once(`down`,o),e.once(`ignore`,o),t.once(`socketClose`,s)}_borrowAConnection(e){let t=null;for(;!t;){let n=e.next(),r=n.value;if(n.done)throw new g.NoHostAvailableError(this._triedHosts);let i=this._profileManager.getDistance(r);if(!(!r.isUp()||i===w.distance.ignored))try{t=this._borrowHostConnection(r)}catch(e){this._triedHosts[r.address]=e}}return t}async _borrowFirstConnection(e){let t=null;for(;!t;){let n=e.next(),r=n.value;if(n.done)throw new g.NoHostAvailableError(this._triedHosts);try{t=await this._createConnection(r)}catch(e){this._triedHosts[r]=e}}if(!t){let e=new g.NoHostAvailableError(this._triedHosts);throw this.log(`error`,`ControlConnection failed to acquire a connection`),e}this.protocolVersion=t.protocolVersion,this._encoder=t.encoder,this.connection=t}_borrowHostConnection(e){return e.borrowConnection()}async _createConnection(e){let t=new x(e,null,this.options);try{await t.openAsync()}catch(e){throw T.toBackground(t.closeAsync()),e}return t}async _refreshHosts(e,t){let n=this.connection;if(!n){if(t)throw new g.DriverInternalError(`Connection reference has been lost when reconnecting`);return}this.log(`info`,`Refreshing local and peers info`);let r=await n.send(new S.QueryRequest(`SELECT * FROM system.local WHERE key='local'`),null);if(this._setLocalInfo(e,t,n,r),!this.host)throw new g.DriverInternalError(`Information from system.local could not be retrieved`);let i=await n.send(new S.QueryRequest(`SELECT * FROM system.peers`),null);if(await this.setPeersInfo(e,i),!this.initialized){let e=w.protocolVersion.getHighestCommon(n,this.hosts),t=e!==this.protocolVersion;if(this.protocolVersion=e,this.hosts.forEach(e=>e.setProtocolVersion(this.protocolVersion)),t){this.log(`info`,`Reconnecting since the protocol version changed to 0x${e.toString(16)}`),n.decreaseVersion(this.protocolVersion),await n.closeAsync();try{await n.openAsync()}catch(e){throw T.toBackground(n.closeAsync()),e}}if(this.metadata.setCassandraVersion(this.host.getCassandraVersion()),this.metadata.buildTokens(this.hosts),!this.options.isMetadataSyncEnabled){this.metadata.initialized=!0;return}await this.metadata.refreshKeyspacesInternal(!1),this.metadata.initialized=!0}}async _refreshControlConnection(e){if(this.options.sni)this.connection=this._borrowAConnection(e);else try{this.connection=this._borrowAConnection(e)}catch{this.log(`info`,`ControlConnection could not reconnect using existing connections. Refreshing contact points and retrying`),this._contactPoints.clear(),this._resolvedContactPoints.clear(),await Promise.all(this.options.contactPoints.map(e=>this._parseContactPoint(e)));let e=Array.from(this._contactPoints).join(`,`);this.log(`info`,`Refreshed contact points: ${e}`),await this._initializeConnection()}}async _refresh(e){if(this._isShuttingDown){this.log(`info`,`The ControlConnection will not be refreshed as the Client is being shutdown`);return}this.host=null,this.connection=null;try{e||=(this.log(`info`,`Trying to acquire a connection to a new host`),this._triedHosts={},await T.newQueryPlan(this._profileManager.getDefaultLoadBalancing(),null,null)),await this._refreshControlConnection(e)}catch(e){if(this.log(`error`,`ControlConnection failed to acquire a connection`,e),!this._isShuttingDown){let t=this._reconnectionSchedule.next().value;this.log(`warning`,`ControlConnection could not reconnect, scheduling reconnection in ${t}ms`),setTimeout(()=>this._refresh(),t),this.emit(`newConnection`,e)}return}this.log(`info`,`ControlConnection connected to ${this.connection.endpointFriendlyName}`);try{await this._refreshHosts(!1,!0),await this._registerToConnectionEvents()}catch(t){return this.log(`error`,`ControlConnection failed to retrieve topology and keyspaces information`,t),this._triedHosts[this.connection.endpoint]=t,t.isSocketError&&this.host&&this.host.removeFromPool(this.connection),await this._refresh(e)}this._reconnectionSchedule=this._reconnectionPolicy.newSchedule(),this._setHealthListeners(this.host,this.connection),this.emit(`newConnection`,null,this.connection,this.host),this.log(`info`,`ControlConnection connected to ${this.connection.endpointFriendlyName} and up to date`)}async _initializeConnection(){this.log(`info`,`Getting first connection`),this.host=null,this.connection=null,this._triedHosts={};let e=C.shuffleArray(Array.from(this._contactPoints))[Symbol.iterator]();for(;;){await this._borrowFirstConnection(e),this.log(`info`,`ControlConnection using protocol version 0x${this.protocolVersion.toString(16)}, connected to ${this.connection.endpointFriendlyName}`);try{await this._getSupportedOptions(),await this._refreshHosts(!0,!0),await this._registerToConnectionEvents();break}catch(e){this.log(`error`,`ControlConnection failed to retrieve topology and keyspaces information`,e),this._triedHosts[this.connection.endpoint]=e}}this.host.pool.addExistingConnection(this.connection),this.initialized=!0,this._setHealthListeners(this.host,this.connection),this.log(`info`,`ControlConnection connected to ${this.connection.endpointFriendlyName}`)}async _getSupportedOptions(){let e=await this.connection.send(S.options,null),t=e.supported&&e.supported.PRODUCT_TYPE;Array.isArray(t)&&t[0]===`DATASTAX_APOLLO`&&this.metadata.setProductTypeAsDbaas()}async _registerToConnectionEvents(){this.connection.on(`nodeTopologyChange`,this._nodeTopologyChangeHandler.bind(this)),this.connection.on(`nodeStatusChange`,this._nodeStatusChangeHandler.bind(this)),this.connection.on(`nodeSchemaChange`,this._nodeSchemaChangeHandler.bind(this));let e=new S.RegisterRequest([`TOPOLOGY_CHANGE`,`STATUS_CHANGE`,`SCHEMA_CHANGE`]);await this.connection.send(e,null)}_nodeTopologyChangeHandler(e){this.log(`info`,`Received topology change`,e),clearTimeout(this._topologyChangeTimeout),this._topologyChangeTimeout=setTimeout(()=>T.toBackground(this._scheduleRefreshHosts()),D)}_nodeStatusChangeHandler(e){let t=this,n=e.inet.address.toString(),r=this.options.protocolOptions.port;this._addressTranslator.translate(n,r,function(r){let i=t.hosts.get(r);if(!i){t.log(`warning`,`Received status change event but host was not found: `+n);return}let a=t._profileManager.getDistance(i);if(e.up){if(a===w.distance.ignored)return i.setUp(!0);clearTimeout(t._nodeStatusChangeTimeout),t._nodeStatusChangeTimeout=setTimeout(()=>i.checkIsUp(),D);return}if(a===w.distance.ignored)return i.setDown();t.log(`warning`,`Received status change to DOWN for host `+i.address)})}_nodeSchemaChangeHandler(e){this.log(`info`,`Schema change`,e),this.options.isMetadataSyncEnabled&&T.toBackground(this.handleSchemaChange(e,!1))}handleSchemaChange(e,t){let n=this,r,i;if(e.isKeyspace)return e.schemaChangeType===O.dropped?(r=function(){delete n.metadata.keyspaces[e.keyspace]},this._scheduleObjectRefresh(r,e.keyspace,null,t)):this._scheduleKeyspaceRefresh(e.keyspace,t);let a=this.metadata.keyspaces[e.keyspace];return!a||(e.table?(i=e.table,r=function(){delete a.tables[e.table],delete a.views[e.table]}):e.udt?(i=e.udt,r=function(){delete a.udts[e.udt]}):e.functionName?(i=e.functionName,r=function(){delete a.functions[e.functionName]}):e.aggregate&&(i=e.aggregate,r=function(){delete a.aggregates[e.aggregate]}),!r)?Promise.resolve():this._scheduleObjectRefresh(r,e.keyspace,i,t)}_scheduleObjectRefresh(e,t,n,r){return this._debouncer.eventReceived({handler:e,keyspace:t,cqlObject:n},r)}_scheduleKeyspaceRefresh(e,t){return this._debouncer.eventReceived({handler:()=>this.metadata.refreshKeyspace(e),keyspace:e},t)}_scheduleRefreshHosts(){return this._debouncer.eventReceived({handler:()=>this._refreshHosts(!1,!1),all:!0},!1)}_setLocalInfo(e,t,n,r){if(!r||!r.rows||!r.rows.length){this.log(`warning`,`No local info could be obtained`);return}let i=r.rows[0],a,o=this.options.sni?`${i.rpc_address}:${this.options.protocolOptions.port}`:n.endpoint;if(e)a=new _(o,this.protocolVersion,this.options,this.metadata),this.hosts.set(o,a),this.log(`info`,`Adding host ${o}`);else if(a=this.hosts.get(o),!a){this.log(`error`,`Localhost could not be found`);return}a.datacenter=i.data_center,a.rack=i.rack,a.tokens=i.tokens,a.hostId=i.host_id,a.cassandraVersion=i.release_version,A(a,i),this.metadata.setPartitioner(i.partitioner),this.log(`info`,`Local info retrieved`),t&&(this.host=a)}async setPeersInfo(e,t){if(!t||!t.rows)return;let n={},r=this.options.protocolOptions.port,i=new Set;this.host&&this.host.datacenter&&i.add(this.host.datacenter);for(let a of t.rows){let t=await this.getAddressForPeerHost(a,r);if(!t)continue;n[t]=!0;let o=this.hosts.get(t),s=!o;s&&=(o=new _(t,this.protocolVersion,this.options,this.metadata),this.log(`info`,`Adding host ${t}`),!0),o.datacenter=a.data_center,o.rack=a.rack,o.tokens=a.tokens,o.hostId=a.host_id,o.cassandraVersion=a.release_version,A(o,a),o.datacenter&&i.add(o.datacenter),s&&(this.hosts.set(t,o),e||(this._profileManager.getDistance(o),o.setDown()))}if(this.hosts.length>t.rows.length+1){this.log(`info`,`Removing nodes from the pool`);let e=[];this.hosts.forEach(t=>{!n[t.address]&&t!==this.host&&(this.log(`info`,`Removing host `+t.address),e.push(t.address),t.shutdown(!0))}),this.hosts.removeMultiple(e)}if(e&&this.options.localDataCenter){let e=this.options.localDataCenter;if(!i.has(e))throw new g.ArgumentError(`localDataCenter was configured as '${e}', but only found hosts in data centers: [${Array.from(i).join(`, `)}]`)}this.log(`info`,`Peers info retrieved`)}getAddressForPeerHost(e,t){return new Promise(n=>{let r=e.rpc_address,i=e.peer;if(!r)return this.log(`error`,E(`No rpc_address found for host %s in %s's peers system table. %s will be ignored.`,i,this.host.address,i)),n(null);r.toString()===`0.0.0.0`&&(this.log(`warning`,E(`Found host with 0.0.0.0 as rpc_address, using listen_address (%s) to contact it instead. If this is incorrect you should avoid the use of 0.0.0.0 server side.`,i)),r=i),this._addressTranslator.translate(r.toString(),t,n)})}async _resolveAll(e){let t=[],n=p.promisify(h.resolve4),r=p.promisify(h.resolve6),i=p.promisify(h.lookup),a=n(e).catch(()=>{}).then(e=>e||C.emptyArray),o=r(e).catch(()=>{}).then(e=>e||C.emptyArray),s;if(s=await a,s.forEach(e=>t.push({address:e,isIPv6:!1})),s=await o,s.forEach(e=>t.push({address:e,isIPv6:!0})),t.length===0)try{s=await i(e,{all:!0}),s.forEach(({address:e,family:n})=>t.push({address:e,isIPv6:n===6}))}catch(t){this.log(`error`,`Host with name ${e} could not be resolved`,t)}return t}_waitForReconnection(){return new Promise((e,t)=>{let n=T.getCallback(e,t),r;function i(e){clearTimeout(r),n(e)}this.once(`newConnection`,i),r=setTimeout(()=>{this.removeListener(`newConnection`,i),n(new g.OperationTimedOutError(`A connection could not be acquired before timeout.`))},2e3)})}async query(e,t=!0){return!this.connection&&t&&await this._waitForReconnection(),await(async()=>{if(!this.connection||this._isShuttingDown)throw new g.NoHostAvailableError({},`ControlConnection is not connected at the time`);let t=typeof e==`string`?new S.QueryRequest(e,null,null):e;return await this.connection.send(t,null)})()}getEncoder(){if(!this._encoder)throw new g.DriverInternalError(`Encoder is not defined`);return this._encoder}shutdown(){this._isShuttingDown=!0,this._debouncer.shutdown(),this.emit(`newConnection`,new g.DriverError(`ControlConnection is being shutdown`)),clearTimeout(this._topologyChangeTimeout),clearTimeout(this._nodeStatusChangeTimeout)}async reset(){let e=this.hosts.clear();this._isShuttingDown=!0,await Promise.all(e.map(e=>e.shutdown())),this.initialized=!1,this._isShuttingDown=!1}getResolvedContactPoints(){return this._resolvedContactPoints}getLocalAddress(){if(this.connection)return this.connection.getLocalAddress()}getEndpoint(){if(this.connection)return this.connection.endpoint}};function A(e,t){t.workloads===void 0?t.workload?e.workloads=[t.workload]:e.workloads=C.emptyArray:e.workloads=t.workloads,t.dse_version!==void 0&&(e.dseVersion=t.dse_version)}d.exports=k}));export default d();export{d as require_control_connection};
|
|
1
|
+
import e from"./errors.js";import t from"./promise-utils.js";import n from"./utils.js";import r from"./types/index.js";import i from"./requests.js";import a from"./connection.js";import{Host as o,HostMap as s}from"./host.js";import c from"./metadata/index.js";import l from"./metadata/event-debouncer.js";import u from"util";import d from"dns";import f from"net";import p from"events";const m=u.format,h=1e3,g={created:`CREATED`,updated:`UPDATED`,dropped:`DROPPED`};var _=class extends p.EventEmitter{constructor(e,t,r){super(),this.protocolVersion=null,this.hosts=new s,this.setMaxListeners(0),this.log=n.log,Object.defineProperty(this,`options`,{value:e,enumerable:!1,writable:!1}),this.metadata=new c(this.options,this),this.initialized=!1,this.host=null,this.connection=null,this._addressTranslator=this.options.policies.addressResolution,this._reconnectionPolicy=this.options.policies.reconnection,this._reconnectionSchedule=this._reconnectionPolicy.newSchedule(),this._isShuttingDown=!1,this._encoder=null,this._debouncer=new l(e.refreshSchemaDelay,this.log.bind(this)),this._profileManager=t,this._triedHosts=null,this._resolvedContactPoints=new Map,this._contactPoints=new Set,this._topologyChangeTimeout=null,this._nodeStatusChangeTimeout=null,r&&r.borrowHostConnection&&(this._borrowHostConnection=r.borrowHostConnection),r&&r.createConnection&&(this._createConnection=r.createConnection)}_addContactPoint(e,t,r,i){if(e===null){this._resolvedContactPoints.set(r,n.emptyArray);return}let a=parseInt(t,10)||this.options.protocolOptions.port,o=`${e}:${a}`;this._contactPoints.add(o);let s=i?`[${e}]:${a}`:o,c=this._resolvedContactPoints.get(r);(c===void 0||c===n.emptyArray)&&(c=[],this._resolvedContactPoints.set(r,c)),c.push(s)}async _parseContactPoint(e){let t=e,n=null;if(e.indexOf(`[`)===0&&e.indexOf(`]:`)>1){let r=e.lastIndexOf(`]:`);t=e.substr(1,r-1),n=e.substr(r+2)}else if(e.indexOf(`:`)>0){let r=e.split(`:`);r.length===2&&(t=r[0],n=r[1])}if(f.isIP(t)){this._addContactPoint(t,n,e,f.isIPv6(t));return}let r=await this._resolveAll(t);r.length>0?r.forEach(t=>this._addContactPoint(t.address,n,e,t.isIPv6)):this._addContactPoint(null,null,e,!1)}async init(){if(!this.initialized){if(!this.options.sni)await Promise.all(this.options.contactPoints.map(e=>this._parseContactPoint(e)));else{this.options.contactPoints.forEach(e=>this._contactPoints.add(e));let t=this.options.sni.address,r=t.lastIndexOf(`:`);if(r===-1)throw new new e.DriverInternalError(`The SNI endpoint address should contain ip/name and port`);let i=t.substr(0,r);this.options.sni.port=t.substr(r+1),this.options.sni.addressResolver=new n.AddressResolver({nameOrIp:i,dns:d}),await this.options.sni.addressResolver.init()}if(this._contactPoints.size===0)throw new e.NoHostAvailableError({},`No host could be resolved`);await this._initializeConnection()}}_setHealthListeners(e,n){let r=this,i=0;function a(){e.removeListener(`down`,s),e.removeListener(`ignore`,s),n.removeListener(`socketClose`,c)}function o(o){i++===0&&(a(),!r._isShuttingDown&&(o?r.log(`warning`,`Host ${e.address} used by the ControlConnection DOWN, connection to ${n.endpointFriendlyName} will not longer be used`):r.log(`warning`,`Connection to ${n.endpointFriendlyName} used by the ControlConnection was closed`),t.toBackground(r._refresh())))}function s(){o(!0)}function c(){o(!1)}e.once(`down`,s),e.once(`ignore`,s),n.once(`socketClose`,c)}_borrowAConnection(t){let n=null;for(;!n;){let i=t.next(),a=i.value;if(i.done)throw new e.NoHostAvailableError(this._triedHosts);let o=this._profileManager.getDistance(a);if(!(!a.isUp()||o===r.distance.ignored))try{n=this._borrowHostConnection(a)}catch(e){this._triedHosts[a.address]=e}}return n}async _borrowFirstConnection(t){let n=null;for(;!n;){let r=t.next(),i=r.value;if(r.done)throw new e.NoHostAvailableError(this._triedHosts);try{n=await this._createConnection(i)}catch(e){this._triedHosts[i]=e}}if(!n){let t=new e.NoHostAvailableError(this._triedHosts);throw this.log(`error`,`ControlConnection failed to acquire a connection`),t}this.protocolVersion=n.protocolVersion,this._encoder=n.encoder,this.connection=n}_borrowHostConnection(e){return e.borrowConnection()}async _createConnection(e){let n=new a(e,null,this.options);try{await n.openAsync()}catch(e){throw t.toBackground(n.closeAsync()),e}return n}async _refreshHosts(n,a){let o=this.connection;if(!o){if(a)throw new e.DriverInternalError(`Connection reference has been lost when reconnecting`);return}this.log(`info`,`Refreshing local and peers info`);let s=await o.send(new i.QueryRequest(`SELECT * FROM system.local WHERE key='local'`),null);if(this._setLocalInfo(n,a,o,s),!this.host)throw new e.DriverInternalError(`Information from system.local could not be retrieved`);let c=await o.send(new i.QueryRequest(`SELECT * FROM system.peers`),null);if(await this.setPeersInfo(n,c),!this.initialized){let e=r.protocolVersion.getHighestCommon(o,this.hosts),n=e!==this.protocolVersion;if(this.protocolVersion=e,this.hosts.forEach(e=>e.setProtocolVersion(this.protocolVersion)),n){this.log(`info`,`Reconnecting since the protocol version changed to 0x${e.toString(16)}`),o.decreaseVersion(this.protocolVersion),await o.closeAsync();try{await o.openAsync()}catch(e){throw t.toBackground(o.closeAsync()),e}}if(this.metadata.setCassandraVersion(this.host.getCassandraVersion()),this.metadata.buildTokens(this.hosts),!this.options.isMetadataSyncEnabled){this.metadata.initialized=!0;return}await this.metadata.refreshKeyspacesInternal(!1),this.metadata.initialized=!0}}async _refreshControlConnection(e){if(this.options.sni)this.connection=this._borrowAConnection(e);else try{this.connection=this._borrowAConnection(e)}catch{this.log(`info`,`ControlConnection could not reconnect using existing connections. Refreshing contact points and retrying`),this._contactPoints.clear(),this._resolvedContactPoints.clear(),await Promise.all(this.options.contactPoints.map(e=>this._parseContactPoint(e)));let e=Array.from(this._contactPoints).join(`,`);this.log(`info`,`Refreshed contact points: ${e}`),await this._initializeConnection()}}async _refresh(e){if(this._isShuttingDown){this.log(`info`,`The ControlConnection will not be refreshed as the Client is being shutdown`);return}this.host=null,this.connection=null;try{e||=(this.log(`info`,`Trying to acquire a connection to a new host`),this._triedHosts={},await t.newQueryPlan(this._profileManager.getDefaultLoadBalancing(),null,null)),await this._refreshControlConnection(e)}catch(e){if(this.log(`error`,`ControlConnection failed to acquire a connection`,e),!this._isShuttingDown){let t=this._reconnectionSchedule.next().value;this.log(`warning`,`ControlConnection could not reconnect, scheduling reconnection in ${t}ms`),setTimeout(()=>this._refresh(),t),this.emit(`newConnection`,e)}return}this.log(`info`,`ControlConnection connected to ${this.connection.endpointFriendlyName}`);try{await this._refreshHosts(!1,!0),await this._registerToConnectionEvents()}catch(t){return this.log(`error`,`ControlConnection failed to retrieve topology and keyspaces information`,t),this._triedHosts[this.connection.endpoint]=t,t.isSocketError&&this.host&&this.host.removeFromPool(this.connection),await this._refresh(e)}this._reconnectionSchedule=this._reconnectionPolicy.newSchedule(),this._setHealthListeners(this.host,this.connection),this.emit(`newConnection`,null,this.connection,this.host),this.log(`info`,`ControlConnection connected to ${this.connection.endpointFriendlyName} and up to date`)}async _initializeConnection(){this.log(`info`,`Getting first connection`),this.host=null,this.connection=null,this._triedHosts={};let e=n.shuffleArray(Array.from(this._contactPoints))[Symbol.iterator]();for(;;){await this._borrowFirstConnection(e),this.log(`info`,`ControlConnection using protocol version 0x${this.protocolVersion.toString(16)}, connected to ${this.connection.endpointFriendlyName}`);try{await this._getSupportedOptions(),await this._refreshHosts(!0,!0),await this._registerToConnectionEvents();break}catch(e){this.log(`error`,`ControlConnection failed to retrieve topology and keyspaces information`,e),this._triedHosts[this.connection.endpoint]=e}}this.host.pool.addExistingConnection(this.connection),this.initialized=!0,this._setHealthListeners(this.host,this.connection),this.log(`info`,`ControlConnection connected to ${this.connection.endpointFriendlyName}`)}async _getSupportedOptions(){let e=await this.connection.send(i.options,null),t=e.supported&&e.supported.PRODUCT_TYPE;Array.isArray(t)&&t[0]===`DATASTAX_APOLLO`&&this.metadata.setProductTypeAsDbaas()}async _registerToConnectionEvents(){this.connection.on(`nodeTopologyChange`,this._nodeTopologyChangeHandler.bind(this)),this.connection.on(`nodeStatusChange`,this._nodeStatusChangeHandler.bind(this)),this.connection.on(`nodeSchemaChange`,this._nodeSchemaChangeHandler.bind(this));let e=new i.RegisterRequest([`TOPOLOGY_CHANGE`,`STATUS_CHANGE`,`SCHEMA_CHANGE`]);await this.connection.send(e,null)}_nodeTopologyChangeHandler(e){this.log(`info`,`Received topology change`,e),clearTimeout(this._topologyChangeTimeout),this._topologyChangeTimeout=setTimeout(()=>t.toBackground(this._scheduleRefreshHosts()),h)}_nodeStatusChangeHandler(e){let t=this,n=e.inet.address.toString(),i=this.options.protocolOptions.port;this._addressTranslator.translate(n,i,function(i){let a=t.hosts.get(i);if(!a){t.log(`warning`,`Received status change event but host was not found: `+n);return}let o=t._profileManager.getDistance(a);if(e.up){if(o===r.distance.ignored)return a.setUp(!0);clearTimeout(t._nodeStatusChangeTimeout),t._nodeStatusChangeTimeout=setTimeout(()=>a.checkIsUp(),h);return}if(o===r.distance.ignored)return a.setDown();t.log(`warning`,`Received status change to DOWN for host `+a.address)})}_nodeSchemaChangeHandler(e){this.log(`info`,`Schema change`,e),this.options.isMetadataSyncEnabled&&t.toBackground(this.handleSchemaChange(e,!1))}handleSchemaChange(e,t){let n=this,r,i;if(e.isKeyspace)return e.schemaChangeType===g.dropped?(r=function(){delete n.metadata.keyspaces[e.keyspace]},this._scheduleObjectRefresh(r,e.keyspace,null,t)):this._scheduleKeyspaceRefresh(e.keyspace,t);let a=this.metadata.keyspaces[e.keyspace];return!a||(e.table?(i=e.table,r=function(){delete a.tables[e.table],delete a.views[e.table]}):e.udt?(i=e.udt,r=function(){delete a.udts[e.udt]}):e.functionName?(i=e.functionName,r=function(){delete a.functions[e.functionName]}):e.aggregate&&(i=e.aggregate,r=function(){delete a.aggregates[e.aggregate]}),!r)?Promise.resolve():this._scheduleObjectRefresh(r,e.keyspace,i,t)}_scheduleObjectRefresh(e,t,n,r){return this._debouncer.eventReceived({handler:e,keyspace:t,cqlObject:n},r)}_scheduleKeyspaceRefresh(e,t){return this._debouncer.eventReceived({handler:()=>this.metadata.refreshKeyspace(e),keyspace:e},t)}_scheduleRefreshHosts(){return this._debouncer.eventReceived({handler:()=>this._refreshHosts(!1,!1),all:!0},!1)}_setLocalInfo(e,t,n,r){if(!r||!r.rows||!r.rows.length){this.log(`warning`,`No local info could be obtained`);return}let i=r.rows[0],a,s=this.options.sni?`${i.rpc_address}:${this.options.protocolOptions.port}`:n.endpoint;if(e)a=new o(s,this.protocolVersion,this.options,this.metadata),this.hosts.set(s,a),this.log(`info`,`Adding host ${s}`);else if(a=this.hosts.get(s),!a){this.log(`error`,`Localhost could not be found`);return}a.datacenter=i.data_center,a.rack=i.rack,a.tokens=i.tokens,a.hostId=i.host_id,a.cassandraVersion=i.release_version,v(a,i),this.metadata.setPartitioner(i.partitioner),this.log(`info`,`Local info retrieved`),t&&(this.host=a)}async setPeersInfo(t,n){if(!n||!n.rows)return;let r={},i=this.options.protocolOptions.port,a=new Set;this.host&&this.host.datacenter&&a.add(this.host.datacenter);for(let e of n.rows){let n=await this.getAddressForPeerHost(e,i);if(!n)continue;r[n]=!0;let s=this.hosts.get(n),c=!s;c&&=(s=new o(n,this.protocolVersion,this.options,this.metadata),this.log(`info`,`Adding host ${n}`),!0),s.datacenter=e.data_center,s.rack=e.rack,s.tokens=e.tokens,s.hostId=e.host_id,s.cassandraVersion=e.release_version,v(s,e),s.datacenter&&a.add(s.datacenter),c&&(this.hosts.set(n,s),t||(this._profileManager.getDistance(s),s.setDown()))}if(this.hosts.length>n.rows.length+1){this.log(`info`,`Removing nodes from the pool`);let e=[];this.hosts.forEach(t=>{!r[t.address]&&t!==this.host&&(this.log(`info`,`Removing host `+t.address),e.push(t.address),t.shutdown(!0))}),this.hosts.removeMultiple(e)}if(t&&this.options.localDataCenter){let t=this.options.localDataCenter;if(!a.has(t))throw new e.ArgumentError(`localDataCenter was configured as '${t}', but only found hosts in data centers: [${Array.from(a).join(`, `)}]`)}this.log(`info`,`Peers info retrieved`)}getAddressForPeerHost(e,t){return new Promise(n=>{let r=e.rpc_address,i=e.peer;if(!r)return this.log(`error`,m(`No rpc_address found for host %s in %s's peers system table. %s will be ignored.`,i,this.host.address,i)),n(null);r.toString()===`0.0.0.0`&&(this.log(`warning`,m(`Found host with 0.0.0.0 as rpc_address, using listen_address (%s) to contact it instead. If this is incorrect you should avoid the use of 0.0.0.0 server side.`,i)),r=i),this._addressTranslator.translate(r.toString(),t,n)})}async _resolveAll(e){let t=[],r=u.promisify(d.resolve4),i=u.promisify(d.resolve6),a=u.promisify(d.lookup),o=r(e).catch(()=>{}).then(e=>e||n.emptyArray),s=i(e).catch(()=>{}).then(e=>e||n.emptyArray),c;if(c=await o,c.forEach(e=>t.push({address:e,isIPv6:!1})),c=await s,c.forEach(e=>t.push({address:e,isIPv6:!0})),t.length===0)try{c=await a(e,{all:!0}),c.forEach(({address:e,family:n})=>t.push({address:e,isIPv6:n===6}))}catch(t){this.log(`error`,`Host with name ${e} could not be resolved`,t)}return t}_waitForReconnection(){return new Promise((n,r)=>{let i=t.getCallback(n,r),a;function o(e){clearTimeout(a),i(e)}this.once(`newConnection`,o),a=setTimeout(()=>{this.removeListener(`newConnection`,o),i(new e.OperationTimedOutError(`A connection could not be acquired before timeout.`))},2e3)})}async query(t,n=!0){return!this.connection&&n&&await this._waitForReconnection(),await(async()=>{if(!this.connection||this._isShuttingDown)throw new e.NoHostAvailableError({},`ControlConnection is not connected at the time`);let n=typeof t==`string`?new i.QueryRequest(t,null,null):t;return await this.connection.send(n,null)})()}getEncoder(){if(!this._encoder)throw new e.DriverInternalError(`Encoder is not defined`);return this._encoder}shutdown(){this._isShuttingDown=!0,this._debouncer.shutdown(),this.emit(`newConnection`,new e.DriverError(`ControlConnection is being shutdown`)),clearTimeout(this._topologyChangeTimeout),clearTimeout(this._nodeStatusChangeTimeout)}async reset(){let e=this.hosts.clear();this._isShuttingDown=!0,await Promise.all(e.map(e=>e.shutdown())),this.initialized=!1,this._isShuttingDown=!1}getResolvedContactPoints(){return this._resolvedContactPoints}getLocalAddress(){if(this.connection)return this.connection.getLocalAddress()}getEndpoint(){if(this.connection)return this.connection.endpoint}};function v(e,t){t.workloads===void 0?t.workload?e.workloads=[t.workload]:e.workloads=n.emptyArray:e.workloads=t.workloads,t.dse_version!==void 0&&(e.dseVersion=t.dse_version)}export{_ as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import e from"../../types/tuple.js";import{getDataTypeNameByCode as t,types_exports as n}from"../../types/index.js";import r from"../../encoder.js";import{GraphTypeWrapper as i,UdtGraphWrapper as a}from"./wrappers.js";const{dataTypes:o}=n;function s(t){if(t instanceof e)return{cqlType:`tuple`,definition:t.elements.map(s)};if(t instanceof Map){let e={cqlType:`map`};return t.size>0&&(e.definition=t.entries().next().value.map(s)),e}if(t instanceof a)return u(t);let n;return n=t instanceof i?t.typeInfo:r.guessDataType(t),n?c(n):null}function c(e){return e.code===o.udt?l(e.info):e.code===o.tuple||e.code===o.map?{cqlType:t(e),definition:e.info.map(c)}:e.code===o.list||e.code===o.set?{cqlType:e.code===o.list?`list`:`set`,definition:[c(e.info)]}:{cqlType:t(e)}}function l(e){return{cqlType:`udt`,keyspace:e.keyspace,name:e.name,definition:e.fields.map(e=>Object.assign({fieldName:e.name},c(e.type)))}}function u(e){return l(e.udtInfo)}export{s as getTypeDefinitionByValue,u as getUdtTypeDefinitionByValue};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{allocBufferFromString as e}from"../../utils.js";import t from"../../types/uuid.js";import n from"../../types/integer.js";import r from"../../types/big-decimal.js";import i from"../../types/duration.js";import a from"../../types/inet-address.js";import o from"../../types/local-date.js";import s from"../../types/local-time.js";import{Long as c,types_exports as l}from"../../types/index.js";import u from"../../geometry/point.js";import d from"../../geometry/line-string.js";import f from"../../geometry/polygon.js";import"../../geometry/index.js";import{GraphTypeWrapper as p,UdtGraphWrapper as m}from"./wrappers.js";import{getTypeDefinitionByValue as h,getUdtTypeDefinitionByValue as g}from"./complex-type-helper.js";import{Edge as _}from"./structure.js";const{Tuple:v,dataTypes:y}=l,b=`@type`,x=`@value`;var S=class{constructor(){this.key=`g:Edge`}deserialize(e){let t=e[x];return new _(this.reader.read(t.id),this.reader.read(t.outV),t.outVLabel,t.label,this.reader.read(t.inV),t.inVLabel,this.reader.read(t.properties))}},C=class{constructor(e,t){if(!e)throw Error(`Deserializer must provide a type key`);if(!t)throw Error(`Deserializer must provide a target type`);this.key=e,this.targetType=t}deserialize(e){let t=e[x];return typeof t!=`string`&&(t=t.toString()),this.targetType.fromString(t)}serialize(e){return{[b]:this.key,[x]:e.toString()}}canBeUsedFor(e){return e instanceof this.targetType}},w=class extends C{constructor(){super(`g:UUID`,t)}},T=class extends C{constructor(){super(`g:Int64`,c)}},E=class extends C{constructor(){super(`gx:BigDecimal`,r)}},D=class extends C{constructor(){super(`gx:BigInteger`,n)}},O=class extends C{constructor(){super(`gx:InetAddress`,a)}},k=class extends C{constructor(){super(`gx:LocalDate`,o)}},A=class extends C{constructor(){super(`gx:LocalTime`,s)}},j=class extends C{constructor(){super(`gx:Instant`,Date)}serialize(e){return{[b]:this.key,[x]:e.toISOString()}}deserialize(e){return new Date(e[x])}},M=class extends C{constructor(){super(`dse:Blob`,Buffer)}deserialize(t){return e(t[x],`base64`)}serialize(e){return{[b]:this.key,[x]:e.toString(`base64`)}}},N=class extends C{constructor(){super(`dse:Point`,u)}},P=class extends C{constructor(){super(`dse:LineString`,d)}},F=class extends C{constructor(){super(`dse:Polygon`,f)}},I=class{constructor(){this.key=`dse:Tuple`}deserialize(e){let t=e[x].value;if(!Array.isArray(t))throw Error(`Expected Array, obtained: `+t);let n=[];for(let e of t)n.push(this.reader.read(e));return v.fromArray(n)}serialize(e){let t={cqlType:`tuple`,definition:e.elements.map(h),value:e.elements.map(e=>this.writer.adaptObject(e))};return{[b]:this.key,[x]:t}}canBeUsedFor(e){return e instanceof v}},L=class{constructor(){this.key=`dse:Duration`}deserialize(e){let t=e[x];return new i(this.reader.read(t.months),this.reader.read(t.days),this.reader.read(t.nanos))}serialize(e){return{[b]:this.key,[x]:{months:e.months,days:e.days,nanos:e.nanoseconds}}}canBeUsedFor(e){return e instanceof i}},R=class{constructor(){this.key=`dse:UDT`}deserialize(e){let t=e[x],n={},r=t.value;return t.definition.forEach((e,t)=>{n[e.fieldName]=this.reader.read(r[t])}),n}serialize(e){let t=g(e);return t.value=Object.entries(e.value).map(([e,t])=>this.writer.adaptObject(t)),{[b]:this.key,[x]:t}}canBeUsedFor(e){return e instanceof m}},z=class{constructor(e,t){this._name=e,this._transformFn=t||(e=>e)}serialize(e){return{[b]:this._name,[x]:this._transformFn(e)}}};const B={[y.int]:new z(`g:Int32`),[y.bigint]:new z(`g:Int64`),[y.double]:new z(`g:Double`),[y.float]:new z(`g:Float`),[y.timestamp]:new z(`g:Timestamp`,e=>e.getTime())},V=[S,w,T,E,D,O,k,A,j,M,N,P,F,I,R,class{constructor(){this.key=`client:wrapper`}serialize(e){let t=B[e.typeInfo.code];if(!t)throw Error(`No serializer found for wrapped value ${e}`);return t.serialize(e.value)}canBeUsedFor(e){return e instanceof p}},L];function H(){let e={};return V.forEach(t=>{let n=new t;if(!n.key)throw TypeError(`Key for ${t} instance not set`);e[n.key]=n}),e}export{H as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{emptyArray as e,extend as t}from"../../utils.js";import n from"../../policies/retry.js";import"../../policies/index.js";import r from"./result-set.js";import i from"./custom-type-serializers.js";import{GraphSON2Reader as a,GraphSON2Writer as o,GraphSON3Reader as s,GraphSON3Writer as c}from"./graph-serializer.js";import{GraphExecutionOptions as l,graphProtocol as u}from"./options.js";const d=`gremlin-groovy`,f=new a({serializers:i()}),p=new o({serializers:i()}),m=new s({serializers:i()}),h=new c({serializers:i()}),g=new Map([[u.graphson2,y(f)],[u.graphson3,y(m)]]),_=new Map([[u.graphson1,e=>JSON.stringify(e)],[u.graphson2,b(p)],[u.graphson3,b(h)]]);var v=class i{constructor(e,r,i){this._client=e,this._handler=i,this._defaultProfileRetryPolicy=e.profileManager.getDefaultConfiguredRetryPolicy(),this._graphBaseOptions=t({executeAs:e.options.queryOptions.executeAs,language:d,source:`g`,readTimeout:0,retry:new n.FallthroughRetryPolicy},r.graphOptions,e.profileManager.getDefault().graphOptions),this._graphBaseOptions.readTimeout===null&&(this._graphBaseOptions.readTimeout=e.options.socketOptions.readTimeout)}async send(e,t,n){if(Array.isArray(t))throw TypeError(`Parameters must be a Object instance as an associative array`);if(!e)throw TypeError(`Query must be defined`);let r=new l(n,this._client,this._graphBaseOptions,this._defaultProfileRetryPolicy);if(r.getGraphSource()===`a`){let e=await this._getAnalyticsMaster();r.setPreferredHost(e)}let a=typeof e==`object`&&e.graphLanguage&&e.value&&e.queryWriterFactory;if(a&&r.setGraphLanguage(e.graphLanguage),this._setGraphProtocol(r),r.setGraphPayload(),t=i._buildGraphParameters(t,r.getGraphSubProtocol()),typeof e!=`string`){let t=r.getQueryWriter();a?t=e.queryWriterFactory(r.getGraphSubProtocol()):t||=i._writerFactory(r.getGraphSubProtocol()),e=t(a?e.value:e)}return await this._executeGraphQuery(e,t,r)}async _executeGraphQuery(e,t,n){return new r(await this._handler.call(this._client,e,t,n),n.getRowParser()||i._rowParserFactory(n.getGraphSubProtocol()))}async _getAnalyticsMaster(){try{let t=await this._client.execute(`CALL DseClientTool.getAnalyticsGraphServer()`,e);if(t.rows.length===0)return this._client.log(`verbose`,`Empty response querying graph analytics server, query will not be routed optimally`),null;let n=t.rows[0].result;if(!n||!n.location)return this._client.log(`verbose`,`Unexpected response querying graph analytics server, query will not be routed optimally`,t.rows[0]),null;let r=n.location.substr(0,n.location.lastIndexOf(`:`)),i=this._client.options.policies.addressResolution;return await new Promise(e=>{i.translate(r,this._client.options.protocolOptions.port,t=>e(this._client.hosts.get(t)))})}catch(e){return this._client.log(`verbose`,`Error querying graph analytics server, query will not be routed optimally`,e),null}}_setGraphProtocol(e){let t=e.getGraphSubProtocol();if(!t){if(e.getGraphName()){let n=this._client.metadata.keyspaces[e.getGraphName()];n&&n.graphEngine===`Core`&&(t=u.graphson3)}t||=e.getGraphLanguage()===d?u.graphson1:u.graphson2,e.setGraphSubProtocol(t)}}static _buildGraphParameters(e,t){if(!e||typeof e!=`object`)return null;let n=i._writerFactory(t);return[t!==u.graphson1&&t!==u.graphson2?n(new Map(Object.entries(e))):n(e)]}static _rowParserFactory(e){return g.get(e)||null}static _writerFactory(e){let t=_.get(e);if(!t)throw Error(`No writer defined for protocol ${e}`);return t}};function y(e){return t=>{let n=e.read(JSON.parse(t.gremlin));return{object:n.result,bulk:n.bulk||1}}}function b(e){return t=>e.write(t)}export{v as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{BulkSetSerializer as e,BytecodeSerializer as t,DateSerializer as n,DirectionSerializer as r,EdgeSerializer as i,EnumSerializer as a,LambdaSerializer as o,ListSerializer as s,LongSerializer as c,MapSerializer as l,NumberSerializer as u,PSerializer as d,Path3Serializer as f,PropertySerializer as p,SetSerializer as m,TSerializer as h,TextPSerializer as g,TraversalStrategySerializer as _,TraverserSerializer as v,VertexPropertySerializer as y,VertexSerializer as b,typeKey as x,valueKey as S}from"./type-serializers.js";var C=class{constructor(e){this._options=e||{},this._serializers=this.getDefaultSerializers().map(e=>{let t=new e;return t.writer=this,t});let t=this._options.serializers||{};Object.keys(t).forEach(e=>{let n=t[e];n.serialize&&(n.writer=this,this._serializers.unshift(n))})}getDefaultSerializers(){return k}adaptObject(e){let t;for(let n=0;n<this._serializers.length;n++){let r=this._serializers[n];if(r.canBeUsedFor&&r.canBeUsedFor(e)){t=r;break}}return t?t.serialize(e):Array.isArray(e)?e.map(e=>this.adaptObject(e)):e}write(e){return JSON.stringify(this.adaptObject(e))}},w=class extends C{getDefaultSerializers(){return A}},T=class{constructor(e){this._options=e||{},this._deserializers={};let t=this.getDefaultDeserializers();if(Object.keys(t).forEach(e=>{let n=t[e],r=new n;r.reader=this,this._deserializers[e]=r}),this._options.serializers){let e=this._options.serializers||{};Object.keys(e).forEach(t=>{let n=e[t];n.deserialize&&(n.reader=this,this._deserializers[t]=n)})}}getDefaultDeserializers(){return D}read(e){if(e===void 0)return;if(e===null)return null;if(Array.isArray(e))return e.map(e=>this.read(e));let t=e[x];if(t){let n=this._deserializers[t];return n?n.deserialize(e):e[S]}return e&&typeof e==`object`&&e.constructor===Object?this._deserializeObject(e):e}_deserializeObject(e){let t=Object.keys(e),n={};for(let r=0;r<t.length;r++)n[t[r]]=this.read(e[t[r]]);return n}},E=class extends T{getDefaultDeserializers(){return O}};const D={"g:Traverser":v,"g:TraversalStrategy":_,"g:Int32":u,"g:Int64":u,"g:Float":u,"g:Double":u,"g:Date":n,"g:Direction":r,"g:Vertex":b,"g:Edge":i,"g:VertexProperty":y,"g:Property":p,"g:Path":f,"g:TextP":g,"g:T":h,"g:BulkSet":e},O=Object.assign({},D,{"g:List":s,"g:Set":m,"g:Map":l}),k=[u,n,t,v,_,d,g,o,a,b,i,c],A=k.concat([s,m,l]);export{T as GraphSON2Reader,C as GraphSON2Writer,E as GraphSON3Reader,w as GraphSON3Writer};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import"./result-set.js";import"./wrappers.js";import"./structure.js";import"./custom-type-serializers.js";var e=class{constructor(e,t){this.typeName=e,this.elementName=t}toString(){return this.elementName}};const t={id:new e(`T`,`id`),key:new e(`T`,`key`),label:new e(`T`,`label`),value:new e(`T`,`value`)},n={both:new e(`Direction`,`BOTH`),in:new e(`Direction`,`IN`),out:new e(`Direction`,`OUT`)};n.in_=n.in;export{n as direction,t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{allocBufferFromString as e,emptyObject as t,ifUndefined as n,ifUndefined3 as r}from"../../utils.js";import{Long as i,consistencies as a}from"../../types/index.js";import{DefaultExecutionOptions as o,proxyExecuteKey as s}from"../../execution-options.js";import c from"util";const l=i;let u;const d=Object.freeze({graphson1:`graphson-1.0`,graphson2:`graphson-2.0`,graphson3:`graphson-3.0`}),f=Object.freeze({language:`graph-language`,source:`graph-source`,name:`graph-name`,results:`graph-results`,writeConsistency:`graph-write-consistency`,readConsistency:`graph-read-consistency`,timeout:`request-timeout`});function p(i,a,o,c){return i.getOrCreateGraphOptions(c,function(){let l=c.graphOptions||t,u=i.getDefault(),d={customPayload:{[f.language]:e(l.language||a.language),[f.source]:e(l.source||a.source)},graphLanguage:l.language||a.language,graphResults:l.results||a.results,graphSource:l.source||a.source,graphName:n(l.name,a.name)};c===u?d.retry=o||a.retry:d.retry=c.retry||a.retry,a.executeAs&&(d.customPayload[s]=e(a.executeAs)),d.graphName&&(d.customPayload[f.name]=e(d.graphName));let p=n(l.results,a.graphResults);p!==void 0&&(d.customPayload[f.results]=e(p));let m=n(l.readConsistency,a.readConsistency);m!==void 0&&(d.customPayload[f.readConsistency]=e(g(m)));let _=n(l.writeConsistency,a.writeConsistency);return _!==void 0&&(d.customPayload[f.writeConsistency]=e(g(_))),d.readTimeout=r(c.readTimeout,u.readTimeout,a.readTimeout),d.readTimeout>0&&(d.customPayload[f.timeout]=h(d.readTimeout)),d})}function m(t,n,r,i,a){if(a||=e,i!==null){if(i!==void 0){t[r]=a(i);return}n.customPayload[r]&&(t[r]=n.customPayload[r])}}function h(e){return e=l.fromNumber(e),l.toBuffer(e)}function g(e){if(e==null)return;_();let t=u[e];if(!t)throw Error(c.format(`Consistency %s not found, use values defined as properties in types.consistencies object`,e));return t}function _(){if(u)return;u={};let e=Object.keys(a);for(let t=0;t<e.length;t++){let n=e[t];u[a[n]]=n.toUpperCase()}u[a.localQuorum]=`LOCAL_QUORUM`,u[a.eachQuorum]=`EACH_QUORUM`,u[a.localSerial]=`LOCAL_SERIAL`,u[a.localOne]=`LOCAL_ONE`}var v=class extends o{constructor(e,n,r,i){e||=t,super(e,n,null),this._defaultGraphOptions=p(n.profileManager,r,i,this.getProfile()),this._preferredHost=null,this._graphSubProtocol=e.graphResults||this._defaultGraphOptions.graphResults,this._graphLanguage=e.graphLanguage||this._defaultGraphOptions.graphLanguage}setPreferredHost(e){this._preferredHost=e}getPreferredHost(){return this._preferredHost}getGraphSource(){return this.getRawQueryOptions().graphSource||this._defaultGraphOptions.graphSource}getGraphLanguage(){return this._graphLanguage}setGraphLanguage(e){this._graphLanguage=e}getGraphName(){return n(this.getRawQueryOptions().graphName,this._defaultGraphOptions.graphName)}getGraphSubProtocol(){return this._graphSubProtocol}setGraphSubProtocol(e){this._graphSubProtocol=e}getReadTimeout(){return this.getRawQueryOptions().readTimeout||this._defaultGraphOptions.readTimeout}getRetryPolicy(){return this.getRawQueryOptions().retry||this._defaultGraphOptions.retry}getRowParser(){let e=this.getRawQueryOptions().rowParserFactory;return e?e(this.getGraphSubProtocol()):null}getQueryWriter(){let e=this.getRawQueryOptions().queryWriterFactory;return e?e(this.getGraphSubProtocol()):null}setGraphPayload(){let t=this.getRawQueryOptions(),n=this._defaultGraphOptions,r=Object.assign({},this.getCustomPayload());m(r,n,f.language,this.getGraphLanguage()===this._defaultGraphOptions.graphLanguage?void 0:this.getGraphLanguage()),m(r,n,f.source,t.graphSource),m(r,n,f.name,t.graphName),m(r,n,f.readConsistency,g(t.graphReadConsistency)),m(r,n,f.writeConsistency,g(t.graphWriteConsistency)),m(r,n,f.timeout,this.getReadTimeout()>0?this.getReadTimeout():null,h),r[f.results]=n.graphResults===this.getGraphSubProtocol()?n.customPayload[f.results]:e(this.getGraphSubProtocol()),this.setCustomPayload(r)}};export{v as GraphExecutionOptions,d as graphProtocol};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{emptyArray as e,iteratorToArray as t}from"../../utils.js";function n(n,i){this.info=n.info;let a=n.rows;i||=r,this.length=n.rowLength,this.pageState=n.pageState,this.first=function(){let e=this.values().next();return e.done?null:e.value},this.forEach=function(e,t){if(!a.length)return;let n=this.values(),r=n.next(),i=0;for(;!r.done;)e.call(t||this,r.value,i++),r=n.next()},this.toArray=function(){return a.length?t(this.values()):e},this.values=function*(){for(let e of this.getTraversers()){let t=e.bulk||1;for(let n=0;n<t;n++)yield e.object}},this.getTraversers=function*(){for(let e of a)yield i(e)}}typeof Symbol<`u`&&typeof Symbol.iterator==`symbol`&&(n.prototype[Symbol.iterator]=function(){return this.values()});function r(e){let t=JSON.parse(e.gremlin);return{object:t.result,bulk:t.bulk||1}}export{n as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import e from"util";function t(e,t){this.id=e,this.label=t}function n(e,n,r){t.call(this,e,n),this.properties=r}e.inherits(n,t);function r(e,n,r,i,a,o,s){t.call(this,e,i),this.outV=n,this.outVLabel=r,this.inV=a,this.inVLabel=o,this.properties={},(function(e){if(s){let t=Object.keys(s);for(let n=0;n<t.length;n++){let r=t[n];e.properties[r]=s[r].value}}})(this)}e.inherits(r,t);function i(e,n,r,i){t.call(this,e,n),this.value=r,this.key=this.label,this.properties=i}e.inherits(i,t);function a(e,t){this.key=e,this.value=t}function o(e,t){this.labels=e,this.objects=t}export{r as Edge,t as Element,o as Path,a as Property,n as Vertex,i as VertexProperty};
|