@ragestudio/scylla-odm 0.19.0 → 0.20.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/batch/index.d.ts +24 -0
- package/batch/index.js +1 -0
- package/client.d.ts +3 -1
- package/client.js +1 -1
- package/cql_gen/create_keyspace.js +1 -1
- package/cql_gen/create_table.js +1 -1
- package/document/index.d.ts +2 -3
- package/document/index.js +1 -1
- package/driver/{lib/auth → auth}/index.d.ts +1 -13
- package/driver/auth/index.js +1 -0
- package/driver/auth/no-auth-provider.js +1 -0
- package/driver/auth/plain-text-auth-provider.js +1 -0
- package/driver/auth/provider.js +1 -0
- package/driver/client-options.js +1 -0
- package/driver/client.js +1 -0
- package/driver/concurrent/index.d.ts +1 -0
- package/driver/concurrent/index.js +1 -0
- package/driver/connection.js +1 -0
- package/driver/control-connection.js +1 -0
- package/driver/encoder.js +1 -0
- package/driver/errors.js +1 -0
- package/driver/execution-options.js +1 -0
- package/driver/execution-profile.js +1 -0
- package/driver/host-connection-pool.js +1 -0
- package/driver/host.js +1 -0
- package/driver/index.d.ts +8 -100
- package/driver/index.js +1 -1
- package/driver/mapping/cache.js +1 -0
- package/driver/mapping/doc-info-adapter.js +1 -0
- package/driver/{lib/mapping → mapping}/index.d.ts +2 -2
- package/driver/mapping/mapper.js +1 -0
- package/driver/mapping/mapping-handler.js +1 -0
- package/driver/mapping/model-batch-item.js +1 -0
- package/driver/mapping/model-batch-mapper.js +1 -0
- package/driver/mapping/model-mapper.js +1 -0
- package/driver/mapping/model-mapping-info.js +1 -0
- package/driver/mapping/object-selector.js +1 -0
- package/driver/mapping/q.js +1 -0
- package/driver/mapping/query-generator.js +9 -0
- package/driver/mapping/result-mapper.js +4 -0
- package/driver/mapping/result.js +1 -0
- package/driver/mapping/table-mappings.js +1 -0
- package/driver/mapping/tree.js +1 -0
- package/driver/metadata/aggregate.js +1 -0
- package/driver/metadata/client-state.js +1 -0
- package/driver/metadata/data-collection.js +1 -0
- package/driver/metadata/event-debouncer.js +1 -0
- package/driver/{lib/metadata → metadata}/index.d.ts +2 -2
- package/driver/metadata/index.js +1 -0
- package/driver/metadata/materialized-view.js +1 -0
- package/driver/metadata/schema-function.js +1 -0
- package/driver/metadata/schema-index.js +1 -0
- package/driver/metadata/schema-parser.js +1 -0
- package/driver/metadata/table-metadata.js +1 -0
- package/driver/operation-state.js +1 -0
- package/driver/policies/address-resolution.js +1 -0
- package/driver/{lib/policies → policies}/index.d.ts +2 -2
- package/driver/policies/index.js +1 -0
- package/driver/policies/load-balancing.js +1 -0
- package/driver/policies/reconnection.js +1 -0
- package/driver/policies/retry.js +1 -0
- package/driver/policies/speculative-execution.js +1 -0
- package/driver/policies/timestamp-generation.js +1 -0
- package/driver/prepare-handler.js +1 -0
- package/driver/promise-utils.js +1 -0
- package/driver/readers.js +1 -0
- package/driver/request-execution.js +1 -0
- package/driver/request-handler.js +1 -0
- package/driver/requests.js +1 -0
- package/driver/stream-id-stack.js +1 -0
- package/driver/streams.js +1 -0
- package/driver/token.js +1 -0
- package/driver/tokenizer.js +1 -0
- package/driver/types/big-decimal.js +1 -0
- package/driver/types/duration.js +1 -0
- package/driver/{lib/types → types}/index.d.ts +2 -2
- package/driver/types/index.js +1 -0
- package/driver/types/inet-address.js +1 -0
- package/driver/types/integer.js +1 -0
- package/driver/types/local-date.js +1 -0
- package/driver/types/local-time.js +1 -0
- package/driver/types/mutable-long.js +1 -0
- package/driver/types/result-set.js +1 -0
- package/driver/types/result-stream.js +1 -0
- package/driver/types/row.js +1 -0
- package/driver/types/time-uuid.js +1 -0
- package/driver/types/tuple.js +1 -0
- package/driver/types/uuid.js +1 -0
- package/driver/types/vector.js +1 -0
- package/driver/types/version-number.js +1 -0
- package/driver/utils.js +4 -0
- package/driver/writers.js +1 -0
- package/index.d.ts +2 -1
- package/index.js +1 -1
- package/logger/index.js +1 -1
- package/model/index.d.ts +37 -6
- package/model/index.js +1 -1
- package/operations/countAll.js +1 -1
- package/operations/delete.d.ts +4 -3
- package/operations/delete.js +1 -1
- package/operations/find.js +1 -1
- package/operations/findOne.js +1 -1
- package/operations/insert.d.ts +8 -0
- package/operations/insert.js +1 -0
- package/operations/sync.js +1 -1
- package/operations/tableExists.js +2 -2
- package/operations/update.d.ts +3 -2
- package/operations/update.js +1 -1
- package/package.js +1 -1
- package/package.json +1 -1
- package/schema/index.js +1 -1
- package/types.d.ts +18 -2
- package/utils/buildMapper.js +1 -1
- package/utils/delay.js +1 -1
- package/utils/fillDefaults.js +1 -1
- package/utils/isPlainObject.js +1 -1
- package/utils/loadModels.js +1 -1
- package/utils/queryParser.js +1 -1
- package/utils/typeChecker.js +1 -1
- package/_virtual/_rolldown/runtime.js +0 -1
- package/driver/lib/auth/base-dse-authenticator.js +0 -1
- package/driver/lib/auth/dse-gssapi-auth-provider.js +0 -1
- package/driver/lib/auth/dse-plain-text-auth-provider.js +0 -1
- package/driver/lib/auth/gssapi-client.js +0 -1
- package/driver/lib/auth/index.js +0 -1
- package/driver/lib/auth/no-auth-provider.js +0 -1
- package/driver/lib/auth/plain-text-auth-provider.js +0 -1
- package/driver/lib/auth/provider.js +0 -1
- package/driver/lib/client-options.js +0 -1
- package/driver/lib/client.js +0 -1
- package/driver/lib/concurrent/index.d.ts +0 -25
- package/driver/lib/concurrent/index.js +0 -1
- package/driver/lib/connection.js +0 -1
- package/driver/lib/control-connection.js +0 -1
- package/driver/lib/datastax/graph/complex-type-helper.js +0 -1
- package/driver/lib/datastax/graph/custom-type-serializers.js +0 -1
- package/driver/lib/datastax/graph/graph-executor.js +0 -1
- package/driver/lib/datastax/graph/graph-serializer.js +0 -1
- package/driver/lib/datastax/graph/index.d.ts +0 -63
- package/driver/lib/datastax/graph/index.js +0 -1
- package/driver/lib/datastax/graph/options.js +0 -1
- package/driver/lib/datastax/graph/result-set.js +0 -1
- package/driver/lib/datastax/graph/structure.js +0 -1
- package/driver/lib/datastax/graph/type-serializers.js +0 -1
- package/driver/lib/datastax/graph/wrappers.js +0 -1
- package/driver/lib/datastax/index.d.ts +0 -7
- package/driver/lib/datastax/search/date-range.js +0 -1
- package/driver/lib/datastax/search/index.d.ts +0 -49
- package/driver/lib/datastax/search/index.js +0 -1
- package/driver/lib/encoder.js +0 -1
- package/driver/lib/errors.js +0 -1
- package/driver/lib/execution-options.js +0 -1
- package/driver/lib/execution-profile.js +0 -1
- package/driver/lib/geometry/geometry.js +0 -1
- package/driver/lib/geometry/index.d.ts +0 -49
- package/driver/lib/geometry/index.js +0 -1
- package/driver/lib/geometry/line-string.js +0 -1
- package/driver/lib/geometry/point.js +0 -1
- package/driver/lib/geometry/polygon.js +0 -1
- package/driver/lib/host-connection-pool.js +0 -1
- package/driver/lib/host.js +0 -1
- package/driver/lib/insights-client.js +0 -1
- package/driver/lib/mapping/cache.js +0 -1
- package/driver/lib/mapping/doc-info-adapter.js +0 -1
- package/driver/lib/mapping/mapper.js +0 -1
- package/driver/lib/mapping/mapping-handler.js +0 -1
- package/driver/lib/mapping/model-batch-item.js +0 -1
- package/driver/lib/mapping/model-batch-mapper.js +0 -1
- package/driver/lib/mapping/model-mapper.js +0 -1
- package/driver/lib/mapping/model-mapping-info.js +0 -1
- package/driver/lib/mapping/object-selector.js +0 -1
- package/driver/lib/mapping/q.js +0 -1
- package/driver/lib/mapping/query-generator.js +0 -9
- package/driver/lib/mapping/result-mapper.js +0 -4
- package/driver/lib/mapping/result.js +0 -1
- package/driver/lib/mapping/table-mappings.js +0 -1
- package/driver/lib/mapping/tree.js +0 -1
- package/driver/lib/metadata/aggregate.js +0 -1
- package/driver/lib/metadata/client-state.js +0 -1
- package/driver/lib/metadata/data-collection.js +0 -1
- package/driver/lib/metadata/event-debouncer.js +0 -1
- package/driver/lib/metadata/index.js +0 -1
- package/driver/lib/metadata/materialized-view.js +0 -1
- package/driver/lib/metadata/schema-function.js +0 -1
- package/driver/lib/metadata/schema-index.js +0 -1
- package/driver/lib/metadata/schema-parser.js +0 -1
- package/driver/lib/metadata/table-metadata.js +0 -1
- package/driver/lib/metrics/client-metrics.js +0 -1
- package/driver/lib/metrics/default-metrics.js +0 -1
- package/driver/lib/metrics/index.d.ts +0 -44
- package/driver/lib/metrics/index.js +0 -1
- package/driver/lib/operation-state.js +0 -1
- package/driver/lib/policies/address-resolution.js +0 -1
- package/driver/lib/policies/index.js +0 -1
- package/driver/lib/policies/load-balancing.js +0 -1
- package/driver/lib/policies/reconnection.js +0 -1
- package/driver/lib/policies/retry.js +0 -1
- package/driver/lib/policies/speculative-execution.js +0 -1
- package/driver/lib/policies/timestamp-generation.js +0 -1
- package/driver/lib/prepare-handler.js +0 -1
- package/driver/lib/promise-utils.js +0 -1
- package/driver/lib/readers.js +0 -1
- package/driver/lib/request-execution.js +0 -1
- package/driver/lib/request-handler.js +0 -1
- package/driver/lib/requests.js +0 -1
- package/driver/lib/stream-id-stack.js +0 -1
- package/driver/lib/streams.js +0 -1
- package/driver/lib/token.js +0 -1
- package/driver/lib/tokenizer.js +0 -1
- package/driver/lib/tracker/index.d.ts +0 -45
- package/driver/lib/tracker/index.js +0 -1
- package/driver/lib/tracker/request-logger.js +0 -1
- package/driver/lib/tracker/request-tracker.js +0 -1
- package/driver/lib/types/big-decimal.js +0 -1
- package/driver/lib/types/duration.js +0 -1
- package/driver/lib/types/index.js +0 -1
- package/driver/lib/types/inet-address.js +0 -1
- package/driver/lib/types/integer.js +0 -1
- package/driver/lib/types/local-date.js +0 -1
- package/driver/lib/types/local-time.js +0 -1
- package/driver/lib/types/mutable-long.js +0 -1
- package/driver/lib/types/result-set.js +0 -1
- package/driver/lib/types/result-stream.js +0 -1
- package/driver/lib/types/row.js +0 -1
- package/driver/lib/types/time-uuid.js +0 -1
- package/driver/lib/types/tuple.js +0 -1
- package/driver/lib/types/uuid.js +0 -1
- package/driver/lib/types/vector.js +0 -1
- package/driver/lib/types/version-number.js +0 -1
- package/driver/lib/utils.js +0 -4
- package/driver/lib/writers.js +0 -1
- /package/driver/{lib/mapping → mapping}/index.js +0 -0
- /package/driver/{lib/types → types}/protocol-version.js +0 -0
package/batch/index.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { types } from "../driver/types/index.js";
|
|
2
|
+
import { mapping } from "../driver/mapping/index.js";
|
|
3
|
+
import { Client } from "../client.js";
|
|
4
|
+
|
|
5
|
+
//#region src/batch/index.d.ts
|
|
6
|
+
type Long = types.Long;
|
|
7
|
+
type BatchExecutionOptions = {
|
|
8
|
+
logged?: boolean;
|
|
9
|
+
timestamp?: number | Long;
|
|
10
|
+
executionProfile?: string;
|
|
11
|
+
};
|
|
12
|
+
declare class Batch {
|
|
13
|
+
private _items;
|
|
14
|
+
private _client;
|
|
15
|
+
private _logged;
|
|
16
|
+
constructor(client: Client, logged?: boolean);
|
|
17
|
+
add(item: mapping.ModelBatchItem): this;
|
|
18
|
+
execute(options?: BatchExecutionOptions): Promise<mapping.Result>;
|
|
19
|
+
get size(): number;
|
|
20
|
+
clear(): void;
|
|
21
|
+
logged(value: boolean): this;
|
|
22
|
+
}
|
|
23
|
+
//#endregion
|
|
24
|
+
export { Batch, Batch as default, BatchExecutionOptions };
|
package/batch/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var Batch=class{_items=[];_client;_logged;constructor(e,t=!0){this._client=e,this._logged=t}add(e){return this._items.push(e),this}async execute(e){if(this._items.length===0)throw Error(`Cannot execute an empty batch`);let t=this._items;this._items=[];let n={logged:this._logged,...e};return this._client.executeWithRetry(async()=>await this._client.mapper.batch(t,n),`batch`)}get size(){return this._items.length}clear(){this._items=[]}logged(e){return this._logged=e,this}};export{Batch,Batch as default};
|
package/client.d.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { mapping } from "./driver/
|
|
1
|
+
import { mapping } from "./driver/mapping/index.js";
|
|
2
2
|
import { Client as Client$1 } from "./driver/index.js";
|
|
3
3
|
import { Model } from "./model/index.js";
|
|
4
4
|
import { ClientConfig } from "./types.js";
|
|
5
5
|
import { Logger } from "./logger/index.js";
|
|
6
|
+
import { Batch } from "./batch/index.js";
|
|
6
7
|
|
|
7
8
|
//#region src/client.d.ts
|
|
8
9
|
declare class Client {
|
|
@@ -16,6 +17,7 @@ declare class Client {
|
|
|
16
17
|
initialize(options?: {
|
|
17
18
|
sync?: boolean;
|
|
18
19
|
}): Promise<void>;
|
|
20
|
+
batch(logged?: boolean): Batch;
|
|
19
21
|
shutdown(): Promise<void>;
|
|
20
22
|
private connectWithRetry;
|
|
21
23
|
executeWithRetry<T>(operation: () => Promise<T>, operationName?: string): Promise<T>;
|
package/client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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:
|
|
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{Batch as o}from"./batch/index.js";import s from"node:path";const{SCYLLA_CONTACT_POINTS:c,SCYLLA_LOCAL_DATA_CENTER:l,SCYLLA_KEYSPACE:u}=process.env;var Client=class{constructor(t={}){if(globalThis.__scylla_client)throw Error(`An instance of Scylla Client is already initialized`);this.config={modelsPath:s.resolve(process.cwd(),`db`),contactPoints:t.contactPoints??c?.split(`,`)??[`127.0.0.1`],localDataCenter:t.localDataCenter??l??`datacenter1`,keyspace:t.keyspace??u??`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()}batch(e=!0){return new o(this,e)}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{Client,Client as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function
|
|
1
|
+
function createKeyspace(e){let t={};return t=e.replication?e.replication:{strategy:`SimpleStrategy`,options:{replication_factor:`1`}},`CREATE KEYSPACE IF NOT EXISTS ${e.keyspace} WITH REPLICATION = ${JSON.stringify(t)};`}export{createKeyspace as default};
|
package/cql_gen/create_table.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function
|
|
1
|
+
function create_table_default(e){let t=e.schema,n=t.table_name,r=e.client.config.keyspace,i=t.fields,a=t.keys,o=t.clustering_order,s=``;for(let e in i){let t=i[e],r=typeof t==`string`?t:t?.type;if(!r)throw Error(`Invalid field type for "${e}" in model "${n}"`);s+=`"${e}" ${r.toUpperCase()}, `}let c=``;if(typeof a==`string`)c=`"${a}"`;else if(Array.isArray(a)&&a.length>0){let e=a[0];c=Array.isArray(e)?`(${e.map(e=>`"${e}"`).join(`, `)})`:`"${e}"`;for(let e=1;e<a.length;e++)c+=`, "${a[e]}"`}else throw Error(`Missing or invalid primary key in model "${n}"`);let l=``;if(o){let e=``;for(let t in o)e!==``&&(e+=`, `),e+=`"${t}" ${o[t].toUpperCase()}`;e!==``&&(l=` WITH CLUSTERING ORDER BY (${e})`)}return`CREATE TABLE IF NOT EXISTS ${r}.${n} (${s}PRIMARY KEY (${c}))${l}`}export{create_table_default as default};
|
package/document/index.d.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { mapping } from "../driver/lib/mapping/index.js";
|
|
2
1
|
import { Model } from "../model/index.js";
|
|
3
2
|
import { Doc } from "../types.js";
|
|
4
3
|
|
|
@@ -6,8 +5,8 @@ import { Doc } from "../types.js";
|
|
|
6
5
|
declare class Document<TDoc = any> {
|
|
7
6
|
constructor(data: TDoc, model: Model<any, TDoc>);
|
|
8
7
|
_model: Model<any, TDoc>;
|
|
9
|
-
save(): Promise<Doc<TDoc
|
|
10
|
-
delete(): Promise<
|
|
8
|
+
save(): Promise<Doc<TDoc>[]>;
|
|
9
|
+
delete(): Promise<Doc<TDoc>[]>;
|
|
11
10
|
toRaw(): TDoc;
|
|
12
11
|
isValid(): boolean;
|
|
13
12
|
getChangedFields(original: Partial<TDoc>): (keyof TDoc)[];
|
package/document/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Document=class{constructor(e,t){if(e==null)throw Error(`Cannot create Document with null or undefined data`);if(typeof e!=`object`||Array.isArray(e))throw Error(`Document data must be an object`);Object.assign(this,e),Object.defineProperty(this,`_model`,{value:t,enumerable:!1,writable:!1,configurable:!1})}_model;async save(){try{let e=this.toRaw();return await this._model.update(e)}catch(e){throw Error(`Failed to save document: ${e.message}`)}}async delete(){try{return await this._model.delete(this.toRaw())}catch(e){throw Error(`Failed to delete document: ${e.message}`)}}toRaw(){let e={};for(let t in this)if(t!==`_model`&&this.propertyIsEnumerable(t)){let n=this[t];try{JSON.stringify(n),e[t]=n}catch{e[t]=String(n)}}return e}isValid(){try{return!0}catch{return!1}}getChangedFields(e){let t=this.toRaw(),n=[];for(let r in t)(!(r in e)||t[r]!==e[r])&&n.push(r);return n}};export{Document,Document as default};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//#region src/driver/
|
|
1
|
+
//#region src/driver/auth/index.d.ts
|
|
2
2
|
/*
|
|
3
3
|
* Licensed to the Apache Software Foundation (ASF) under one
|
|
4
4
|
* or more contributor license agreements. See the NOTICE file
|
|
@@ -29,18 +29,6 @@ declare namespace auth {
|
|
|
29
29
|
constructor(username: string, password: string);
|
|
30
30
|
newAuthenticator(endpoint: string, name: string): Authenticator;
|
|
31
31
|
}
|
|
32
|
-
class DsePlainTextAuthProvider implements AuthProvider {
|
|
33
|
-
constructor(username: string, password: string, authorizationId?: string);
|
|
34
|
-
newAuthenticator(endpoint: string, name: string): Authenticator;
|
|
35
|
-
}
|
|
36
|
-
class DseGssapiAuthProvider implements AuthProvider {
|
|
37
|
-
constructor(gssOptions?: {
|
|
38
|
-
authorizationId?: string;
|
|
39
|
-
service?: string;
|
|
40
|
-
hostNameResolver?: Function;
|
|
41
|
-
});
|
|
42
|
-
newAuthenticator(endpoint: string, name: string): Authenticator;
|
|
43
|
-
}
|
|
44
32
|
}
|
|
45
33
|
//#endregion
|
|
46
34
|
export { auth };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{AuthProvider as e,Authenticator as t}from"./provider.js";import{PlainTextAuthProvider as n}from"./plain-text-auth-provider.js";import r from"./no-auth-provider.js";var i={Authenticator:t,AuthProvider:e,NoAuthProvider:r,PlainTextAuthProvider:n};export{i as default};
|
|
@@ -0,0 +1 @@
|
|
|
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 NoAuthProvider=class extends t{newAuthenticator(e,t){return t===`com.datastax.bdp.cassandra.auth.DseAuthenticator`?new TransitionalModePlainTextAuthenticator:new NoAuthAuthenticator(e)}},NoAuthAuthenticator=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`))}},TransitionalModePlainTextAuthenticator=class extends r{constructor(){super(``,``)}};export{NoAuthProvider as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import e from"../utils.js";import{AuthProvider as t,Authenticator as n}from"./provider.js";import r from"util";function PlainTextAuthProvider(e,t){this.username=e,this.password=t}r.inherits(PlainTextAuthProvider,t),PlainTextAuthProvider.prototype.newAuthenticator=function(){return new PlainTextAuthenticator(this.username,this.password)};function PlainTextAuthenticator(e,t){this.username=e,this.password=t}r.inherits(PlainTextAuthenticator,n),PlainTextAuthenticator.prototype.initialResponse=function(t){t(null,Buffer.concat([e.allocBufferFromArray([0]),e.allocBufferFromString(this.username,`utf8`),e.allocBufferFromArray([0]),e.allocBufferFromString(this.password,`utf8`)]))},PlainTextAuthenticator.prototype.evaluateChallenge=function(e,t){t()};export{PlainTextAuthProvider,PlainTextAuthenticator};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function AuthProvider(){}AuthProvider.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 Authenticator(){}Authenticator.prototype.initialResponse=function(e){e(Error(`Not implemented`))},Authenticator.prototype.evaluateChallenge=function(e,t){t(Error(`Not implemented`))},Authenticator.prototype.onAuthenticationSuccess=function(e){};export{AuthProvider,Authenticator};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import e from"./utils.js";import t from"./types/index.js";import n from"./policies/index.js";import r from"./auth/index.js";import i from"util";const a={onSuccessfulResponse(){},onConnectionError(){},onClientTimeoutError(){},onOtherError(){},onReadTimeoutError(){},onUnavailableError(){},onWriteTimeoutError(){},onOtherErrorRetry(){},onClientTimeoutRetry(){},onReadTimeoutRetry(){},onUnavailableRetry(){},onWriteTimeoutRetry(){},onResponse(){},onIgnoreError(){},onSpeculativeExecution(){},onAuthenticationError(){}},o={0:2,1:1,2:0},s={0:1,1:1,2:0},c=2048;function defaultOptions(){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:a,maxPrepared:500,refreshSchemaDelay:1e3,isMetadataSyncEnabled:!0,prepareOnAllHosts:!0,rePrepareOnUp:!0,encoding:{copyBuffer:!0,useUndefinedAsUnset:!0},monitorReporting:{enabled:!0}}}function extend(t,n){arguments.length===1&&(n=arguments[0],t={});let r=e.deepExtend(t,defaultOptions(),n);if(!Array.isArray(r.contactPoints)||r.contactPoints.length===0)throw TypeError(`Contacts points are not defined.`);for(let e=0;e<r.contactPoints.length;e++){let t=r.contactPoints[e];if(!t)throw TypeError(i.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(r.sni=void 0,r.logEmitter||=function(){},!r.queryOptions)throw TypeError(`queryOptions not defined in options`);if(validatePoliciesOptions(r.policies),validateProtocolOptions(r.protocolOptions),validateSocketOptions(r.socketOptions),validateAuthenticationOptions(r),r.encoding=r.encoding||{},validateEncodingOptions(r.encoding),r.profiles&&!Array.isArray(r.profiles))throw TypeError(`profiles must be an Array of ExecutionProfile instances`);return validateApplicationInfo(r),validateMonitorReporting(r),r}function validatePoliciesOptions(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 validateProtocolOptions(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(i.format(`protocolOptions.maxVersion provided (%s) is invalid`,n))}function validateSocketOptions(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 validateAuthenticationOptions(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 r.PlainTextAuthProvider(t.username,t.password)}else e.authProvider=new r.NoAuthProvider}else if(!(e.authProvider instanceof r.AuthProvider))throw TypeError(`options.authProvider must be an instance of AuthProvider`)}function validateEncodingOptions(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 validateApplicationInfo(e){function validateString(t){let n=e[t];if(n!=null&&typeof n!=`string`)throw TypeError(`${t} should be a String`)}if(validateString(`applicationName`),validateString(`applicationVersion`),e.id!==null&&e.id!==void 0&&!(e.id instanceof t.Uuid))throw TypeError(`Client id must be a Uuid`)}function validateMonitorReporting(e){let t=e.monitorReporting;if(typeof t!=`object`||!t)throw TypeError(`Monitor reporting must be an object, obtained: ${t}`)}function setMetadataDependent(n){let r=n.controlConnection.protocolVersion,i=s,a=c;t.protocolVersion.uses2BytesStreamIds(r)||(i=o,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 l={extend,defaultOptions,coreConnectionsPerHostV2:o,coreConnectionsPerHostV3:s,maxRequestsPerConnectionV2:128,maxRequestsPerConnectionV3:c,setMetadataDependent,continuousPageUnitBytes:`bytes`,continuousPageDefaultSize:5e3,continuousPageDefaultHighWaterMark:1e4};export{l as default};
|
package/driver/client.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
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"util";import h from"events";function Client(e){h.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}),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}m.inherits(Client,h.EventEmitter),Client.prototype.connect=function(e){return this.connected&&e?e():t.optionalCallback(this._connect(),e)},Client.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`,m.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.connected=!0,this.connecting=!1,this.emit(`connected`)}},Client.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)}},Client.prototype.executeGraph=function(){throw Error(`Graph queries are not supported in this build`)},Client.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,nextPage=()=>t.toCallback(this._execute(e,r,c),pageCallback);function pageCallback(e,t){if(e)return s(e);if(l+=t.rowLength,t.rawPageState!==void 0){if(c.setPageState(t.rawPageState),c.isAutoPage())return nextPage();t.nextPage=nextPage}t.rowLength=l,s(null,t)}t.toCallback(this._execute(e,r,c),pageCallback)},Client.prototype.stream=function(e,t,i,a){a||=n.noop;let o=new r.ResultStream({objectMode:1});function onFinish(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 s=!0;return this.eachRow(e,t,i,function(e,t){o.add(t)},function(e,t){if(s)return setImmediate(function(){onFinish(e,t)});onFinish(e,t)}),s=!1,o},Client.prototype.batch=function(e,n,r){return!r&&typeof n==`function`&&(r=n,n=null),t.optionalCallback(this._batch(e,n),r)},Client.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)},Client.prototype.getReplicas=function(e,t){return this.metadata.getReplicas(e,t)},Client.prototype.getState=function(){return u.from(this)},Client.prototype.log=n.log,Client.prototype.shutdown=function(e){return t.optionalCallback(this._shutdown(),e)},Client.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.controlConnection.shutdown(),this.options.policies.speculativeExecution.shutdown(),this.options.requestTracker&&this.options.requestTracker.shutdown(),await Promise.all(e.map(e=>e.shutdown(!1)))},Client.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},Client.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},Client.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)},Client.prototype._setHostListeners=function(){function getHostUpListener(e,t){return()=>e.emit(`hostUp`,t)}function getHostDownListener(e,t){return()=>e.emit(`hostDown`,t)}let e=this;this.hosts.on(`add`,function(t){t.on(`up`,getHostUpListener(e,t)),t.on(`down`,getHostDownListener(e,t)),e.emit(`hostAdd`,t)}),this.hosts.on(`remove`,function(t){t.removeAllListeners(),e.emit(`hostRemove`,t)}),this.hosts.forEach(function(t){t.on(`up`,getHostUpListener(e,t)),t.on(`down`,getHostDownListener(e,t))})},Client.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()})},Client.prototype._getEncoder=function(){let t=this.controlConnection.getEncoder();if(!t)throw new e.DriverInternalError(`Encoder is not defined`);return t},Client.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)},Client.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)},Client.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)},Client.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`,m.format(`Table %s.%s metadata could not be retrieved`,n.keyspace,n.table))}};export{Client as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import { Readable } from "stream";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import e from"../utils.js";import{Stream as t}from"stream";function executeConcurrent(e,n,r,i){if(!e)throw TypeError(`Client instance is not defined`);if(typeof n==`string`){if(Array.isArray(r))return new ArrayBasedExecutor(e,n,r,i).execute();if(r instanceof t)return new StreamBasedExecutor(e,n,r,i).execute();throw TypeError(`parameters should be an Array or a Stream instance`)}if(Array.isArray(n))return i=r,new ArrayBasedExecutor(e,null,n,i).execute();throw TypeError(`A string query or query and parameters array should be provided`)}var ArrayBasedExecutor=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 ResultSetGroup(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}},StreamBasedExecutor=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 ResultSetGroup(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))}},ResultSetGroup=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)}},n={executeConcurrent,ResultSetGroup};export{n as default};
|
|
@@ -0,0 +1 @@
|
|
|
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 Connection=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,a){if(i&&n._checkingVersion){let a=i instanceof e.ResponseError&&i.code===r.responseErrorCodes.protocolError&&i.message.indexOf(`Invalid or unsupported protocol version`)>=0;if(!a&&r.protocolVersion.canStartupResponseErrorBeWrapped(n.protocolVersion)&&(a=i instanceof e.ResponseError&&i.code===r.responseErrorCodes.serverError&&i.message.indexOf(`ProtocolException: Invalid or unsupported protocol version`)>0),a){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 startupCallback(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(a&&a.mustAuthenticate)return n.startAuthenticating(a.authenticatorName,startupCallback);startupCallback(i)});function startupCallback(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{Connection as default};
|
|
@@ -0,0 +1 @@
|
|
|
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 ControlConnection=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 removeListeners(){e.removeListener(`down`,downOrIgnoredHandler),e.removeListener(`ignore`,downOrIgnoredHandler),n.removeListener(`socketClose`,socketClosedHandler)}function startReconnecting(a){i++===0&&(removeListeners(),!r._isShuttingDown&&(a?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 downOrIgnoredHandler(){startReconnecting(!0)}function socketClosedHandler(){startReconnecting(!1)}e.once(`down`,downOrIgnoredHandler),e.once(`ignore`,downOrIgnoredHandler),n.once(`socketClose`,socketClosedHandler)}_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,handler,r;if(e.isKeyspace)return e.schemaChangeType===g.dropped?(handler=function(){delete n.metadata.keyspaces[e.keyspace]},this._scheduleObjectRefresh(handler,e.keyspace,null,t)):this._scheduleKeyspaceRefresh(e.keyspace,t);let i=this.metadata.keyspaces[e.keyspace];return!i||(e.table?(r=e.table,handler=function(){delete i.tables[e.table],delete i.views[e.table]}):e.udt?(r=e.udt,handler=function(){delete i.udts[e.udt]}):e.functionName?(r=e.functionName,handler=function(){delete i.functions[e.functionName]}):e.aggregate&&(r=e.aggregate,handler=function(){delete i.aggregates[e.aggregate]}),!handler)?Promise.resolve():this._scheduleObjectRefresh(handler,e.keyspace,r,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,setDseParameters(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,setDseParameters(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 newConnectionListener(e){clearTimeout(a),i(e)}this.once(`newConnection`,newConnectionListener),a=setTimeout(()=>{this.removeListener(`newConnection`,newConnectionListener),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 setDseParameters(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{ControlConnection as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import e from"./utils.js";import t from"./types/vector.js";import n from"./types/index.js";import r from"./types/mutable-long.js";import i from"./token.js";import a from"util";const o=n.dataTypes,s=n.Long,c=n.Integer,l=n.BigDecimal,u=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,d={int16Zero:e.allocBufferFromArray([0,0]),int32Zero:e.allocBufferFromArray([0,0,0,0]),int8Zero:e.allocBufferFromArray([0]),int8One:e.allocBufferFromArray([1]),int8MaxValue:e.allocBufferFromArray([255])},f=typeof BigInt<`u`,p=f?BigInt(32):null,m=f?BigInt(8):null,h=f?BigInt(0):null,g=f?BigInt(-1):null,_=f?BigInt(4294967295):null,v=f?BigInt(255):null,y=Object.freeze({list:`org.apache.cassandra.db.marshal.ListType`,set:`org.apache.cassandra.db.marshal.SetType`,map:`org.apache.cassandra.db.marshal.MapType`,udt:`org.apache.cassandra.db.marshal.UserType`,tuple:`org.apache.cassandra.db.marshal.TupleType`,frozen:`org.apache.cassandra.db.marshal.FrozenType`,reversed:`org.apache.cassandra.db.marshal.ReversedType`,composite:`org.apache.cassandra.db.marshal.CompositeType`,empty:`org.apache.cassandra.db.marshal.EmptyType`,collection:`org.apache.cassandra.db.marshal.ColumnToCollectionType`}),b=Object.freeze({frozen:`frozen`,list:`list`,set:`set`,map:`map`,tuple:`tuple`,empty:`empty`,duration:`duration`,vector:`vector`}),x=Object.freeze({"org.apache.cassandra.db.marshal.UTF8Type":o.varchar,"org.apache.cassandra.db.marshal.AsciiType":o.ascii,"org.apache.cassandra.db.marshal.UUIDType":o.uuid,"org.apache.cassandra.db.marshal.TimeUUIDType":o.timeuuid,"org.apache.cassandra.db.marshal.Int32Type":o.int,"org.apache.cassandra.db.marshal.BytesType":o.blob,"org.apache.cassandra.db.marshal.FloatType":o.float,"org.apache.cassandra.db.marshal.DoubleType":o.double,"org.apache.cassandra.db.marshal.BooleanType":o.boolean,"org.apache.cassandra.db.marshal.InetAddressType":o.inet,"org.apache.cassandra.db.marshal.SimpleDateType":o.date,"org.apache.cassandra.db.marshal.TimeType":o.time,"org.apache.cassandra.db.marshal.ShortType":o.smallint,"org.apache.cassandra.db.marshal.ByteType":o.tinyint,"org.apache.cassandra.db.marshal.DateType":o.timestamp,"org.apache.cassandra.db.marshal.TimestampType":o.timestamp,"org.apache.cassandra.db.marshal.LongType":o.bigint,"org.apache.cassandra.db.marshal.DecimalType":o.decimal,"org.apache.cassandra.db.marshal.IntegerType":o.varint,"org.apache.cassandra.db.marshal.CounterColumnType":o.counter});invertObject(x);const S=Object.keys(x).reduce(function(e,t){return t.length>e?t.length:e},0),C=Object.freeze({duration:`org.apache.cassandra.db.marshal.DurationType`,vector:`org.apache.cassandra.db.marshal.VectorType`}),w=e.allocBufferFromArray([255,255,255,255]),T=e.allocBufferFromArray([255,255,255,254]),E=new Set([o.text,o.ascii,o.varchar,o.custom,o.blob]);function Encoder(t,n){this.encodingOptions=n.encoding||e.emptyObject,defineInstanceMembers.call(this),this.setProtocolVersion(t),setEncoders.call(this),this.encodingOptions.copyBuffer?this.handleBuffer=handleBufferCopy:this.handleBuffer=handleBufferRef}function defineInstanceMembers(){this.setProtocolVersion=function(e){this.protocolVersion=e,this.decodeCollectionLength=decodeCollectionLengthV3,this.getLengthBuffer=getLengthBufferV3,this.collectionLengthSize=4,n.protocolVersion.uses4BytesCollectionLength(this.protocolVersion)||(this.decodeCollectionLength=decodeCollectionLengthV2,this.getLengthBuffer=getLengthBufferV2,this.collectionLengthSize=2)};let u={[C.duration]:decodeDuration},f={[C.duration]:encodeDuration};this.decodeBlob=function(e){return this.handleBuffer(e)},this.decodeCustom=function(e,t){if(!t)return this.handleBuffer(e);if(`customTypeName`in t&&t.customTypeName===`vector`)return this.decodeVector(e,t);if(typeof t.info==`string`&&t.info.startsWith(C.vector)){let n=this.parseFqTypeName(t.info);return this.decodeVector(e,n)}let n=u[t.info];return n?n.call(this,e):this.handleBuffer(e)},this.decodeUtf8String=function(e){return e.toString(`utf8`)},this.decodeAsciiString=function(e){return e.toString(`ascii`)},this.decodeBoolean=function(e){return!!e.readUInt8(0)},this.decodeDouble=function(e){return e.readDoubleBE(0)},this.decodeFloat=function(e){return e.readFloatBE(0)},this.decodeInt=function(e){return e.readInt32BE(0)},this.decodeSmallint=function(e){return e.readInt16BE(0)},this.decodeTinyint=function(e){return e.readInt8(0)},this._decodeCqlLongAsLong=function(e){return s.fromBuffer(e)},this._decodeCqlLongAsBigInt=function(e){return BigInt.asIntN(64,BigInt(e.readUInt32BE(0))<<p|BigInt(e.readUInt32BE(4)))},this.decodeLong=this.encodingOptions.useBigIntAsLong?this._decodeCqlLongAsBigInt:this._decodeCqlLongAsLong,this._decodeVarintAsInteger=function(e){return c.fromBuffer(e)},this._decodeVarintAsBigInt=function(e){let t=h;if(e[0]<=127)for(let n=0;n<e.length;n++){let r=BigInt(e[e.length-1-n]);t|=r<<BigInt(n*8)}else{for(let n=0;n<e.length;n++){let r=BigInt(e[e.length-1-n]);t|=(~r&v)<<BigInt(n*8)}t=~t}return t},this.decodeVarint=this.encodingOptions.useBigIntAsVarint?this._decodeVarintAsBigInt:this._decodeVarintAsInteger,this.decodeDecimal=function(e){return l.fromBuffer(e)},this.decodeTimestamp=function(e){return new Date(this._decodeCqlLongAsLong(e).toNumber())},this.decodeDate=function(e){return n.LocalDate.fromBuffer(e)},this.decodeTime=function(e){return n.LocalTime.fromBuffer(e)},this.decodeList=function(e,t){let n=t.info,r=this.decodeCollectionLength(e,0),i=this.collectionLengthSize,a=Array(r);for(let t=0;t<r;t++){let r=this.decodeCollectionLength(e,i);i+=this.collectionLengthSize,a[t]=this.decode(e.slice(i,i+r),n),i+=r}return a},this.decodeSet=function(e,t){let n=this.decodeList(e,t);if(this.encodingOptions.set){let e=this.encodingOptions.set;return new e(n)}return n},this.decodeMap=function(e,t){let n=t.info,r,i=this.decodeCollectionLength(e,0),a=this.collectionLengthSize,o=this;function readValues(t,r){for(let s=0;s<i;s++){let i=o.decodeCollectionLength(e,a);a+=o.collectionLengthSize;let s=o.decode(e.slice(a,a+i),n[0]);a+=i;let c=o.decodeCollectionLength(e,a);if(a+=o.collectionLengthSize,c<0){t.call(r,s,null);continue}let l=o.decode(e.slice(a,a+c),n[1]);a+=c,t.call(r,s,l)}}if(this.encodingOptions.map){let e=this.encodingOptions.map;r=new e,readValues(r.set,r)}else r={},readValues(function(e,t){r[e]=t});return r},this.decodeUuid=function(e){return new n.Uuid(this.handleBuffer(e))},this.decodeTimeUuid=function(e){return new n.TimeUuid(this.handleBuffer(e))},this.decodeInet=function(e){return new n.InetAddress(this.handleBuffer(e))},this.decodeUdt=function(e,t){let n=t.info,r={},i=0;for(let t=0;t<n.fields.length&&i<e.length;t++){let a=e.readInt32BE(i);i+=4;let o=n.fields[t];if(a<0){r[o.name]=null;continue}r[o.name]=this.decode(e.slice(i,i+a),o.type),i+=a}return r},this.decodeTuple=function(e,t){let r=t.info,i=Array(r.length),a=0;for(let t=0;t<r.length&&a<e.length;t++){let n=e.readInt32BE(a);if(a+=4,n<0){i[t]=null;continue}i[t]=this.decode(e.slice(a,a+n),r[t]),a+=n}return n.Tuple.fromArray(i)},this.encodeFloat=function(t){if(typeof t==`string`&&(t=parseFloat(t),Number.isNaN(t)))throw TypeError(`Expected string representation of a number, obtained ${a.inspect(t)}`);if(typeof t!=`number`)throw TypeError(`Expected Number, obtained `+a.inspect(t));let n=e.allocBufferUnsafe(4);return n.writeFloatBE(t,0),n},this.encodeDouble=function(t){if(typeof t==`string`&&(t=parseFloat(t),Number.isNaN(t)))throw TypeError(`Expected string representation of a number, obtained ${a.inspect(t)}`);if(typeof t!=`number`)throw TypeError(`Expected Number, obtained `+a.inspect(t));let n=e.allocBufferUnsafe(8);return n.writeDoubleBE(t,0),n},this.encodeTimestamp=function(e){let t=e;if(typeof e==`string`&&(e=new Date(e)),e instanceof Date&&(e=e.getTime(),isNaN(e)))throw TypeError(`Invalid date: `+t);return this.encodingOptions.useBigIntAsLong&&(e=BigInt(e)),this.encodeLong(e)},this.encodeDate=function(e){let t=e;try{typeof e==`string`&&(e=n.LocalDate.fromString(e)),e instanceof Date&&(e=n.LocalDate.fromDate(e))}catch(e){throw TypeError(`LocalDate could not be parsed `+e)}if(!(e instanceof n.LocalDate))throw TypeError(`Expected Date/String/LocalDate, obtained `+a.inspect(t));return e.toBuffer()},this.encodeTime=function(e){let t=e;try{typeof e==`string`&&(e=n.LocalTime.fromString(e))}catch(e){throw TypeError(`LocalTime could not be parsed `+e)}if(!(e instanceof n.LocalTime))throw TypeError(`Expected String/LocalTime, obtained `+a.inspect(t));return e.toBuffer()},this.encodeUuid=function(e){if(typeof e==`string`)try{e=n.Uuid.fromString(e).getBuffer()}catch(e){throw TypeError(e.message)}else if(e instanceof n.Uuid)e=e.getBuffer();else throw TypeError(`Not a valid Uuid, expected Uuid/String/Buffer, obtained `+a.inspect(e));return e},this.encodeInet=function(e){if(typeof e==`string`&&(e=n.InetAddress.fromString(e)),e instanceof n.InetAddress&&(e=e.getBuffer()),!(e instanceof Buffer))throw TypeError(`Not a valid Inet, expected InetAddress/Buffer, obtained `+a.inspect(e));return e},this._encodeBigIntFromLong=function(e){typeof e==`number`?e=s.fromNumber(e):typeof e==`string`&&(e=s.fromString(e));let t=null;if(e instanceof s?t=s.toBuffer(e):e instanceof r&&(t=s.toBuffer(e.toImmutable())),t===null)throw TypeError(`Not a valid bigint, expected Long/Number/String/Buffer, obtained `+a.inspect(e));return t},this._encodeBigIntFromBigInt=function(t){if(typeof t==`string`&&(t=BigInt(t)),typeof t!=`bigint`)throw TypeError(`Not a valid BigInt value, obtained `+a.inspect(t));let n=e.allocBufferUnsafe(8);return n.writeUInt32BE(Number(t>>p)>>>0,0),n.writeUInt32BE(Number(t&_),4),n},this.encodeLong=this.encodingOptions.useBigIntAsLong?this._encodeBigIntFromBigInt:this._encodeBigIntFromLong,this._encodeVarintFromInteger=function(e){typeof e==`number`&&(e=c.fromNumber(e)),typeof e==`string`&&(e=c.fromString(e));let t=null;if(e instanceof Buffer&&(t=e),e instanceof c&&(t=c.toBuffer(e)),t===null)throw TypeError(`Not a valid varint, expected Integer/Number/String/Buffer, obtained `+a.inspect(e));return t},this._encodeVarintFromBigInt=function(t){if(typeof t==`string`&&(t=BigInt(t)),typeof t!=`bigint`)throw TypeError(`Not a valid varint, expected BigInt, obtained `+a.inspect(t));if(t===h)return d.int8Zero;if(t===g)return d.int8MaxValue;let n=[];if(t>h){for(;t!==h;)n.unshift(Number(t&v)),t>>=m;n[0]>127&&n.unshift(0)}else{for(;t!==g;)n.unshift(Number(t&v)),t>>=m;n[0]<=127&&n.unshift(255)}return e.allocBufferFromArray(n)},this.encodeVarint=this.encodingOptions.useBigIntAsVarint?this._encodeVarintFromBigInt:this._encodeVarintFromInteger,this.encodeDecimal=function(e){typeof e==`number`?e=l.fromNumber(e):typeof e==`string`&&(e=l.fromString(e));let t=null;if(e instanceof l)t=l.toBuffer(e);else throw TypeError(`Not a valid varint, expected BigDecimal/Number/String/Buffer, obtained `+a.inspect(e));return t},this.encodeString=function(t,n){if(typeof t!=`string`)throw TypeError(`Not a valid text value, expected String obtained `+a.inspect(t));return e.allocBufferFromString(t,n)},this.encodeUtf8String=function(e){return this.encodeString(e,`utf8`)},this.encodeAsciiString=function(e){return this.encodeString(e,`ascii`)},this.encodeBlob=function(e){if(!(e instanceof Buffer))throw TypeError(`Not a valid blob, expected Buffer obtained `+a.inspect(e));return e},this.encodeCustom=function(e,t){if(`customTypeName`in t&&t.customTypeName===`vector`)return this.encodeVector(e,t);if(typeof t.info==`string`&&t.info.startsWith(C.vector)){let n=this.parseFqTypeName(t.info);return this.encodeVector(e,n)}let n=f[t.info];if(n)return n.call(this,e);throw TypeError(`No encoding handler found for type `+t)},this.encodeBoolean=function(e){return e?d.int8One:d.int8Zero},this.encodeInt=function(t){if(isNaN(t))throw TypeError(`Expected Number, obtained `+a.inspect(t));let n=e.allocBufferUnsafe(4);return n.writeInt32BE(t,0),n},this.encodeSmallint=function(t){if(isNaN(t))throw TypeError(`Expected Number, obtained `+a.inspect(t));let n=e.allocBufferUnsafe(2);return n.writeInt16BE(t,0),n},this.encodeTinyint=function(t){if(isNaN(t))throw TypeError(`Expected Number, obtained `+a.inspect(t));let n=e.allocBufferUnsafe(1);return n.writeInt8(t,0),n},this.encodeList=function(e,t){let r=t.info;if(!Array.isArray(e))throw TypeError(`Not a valid list value, expected Array obtained `+a.inspect(e));if(e.length===0)return null;let i=[];i.push(this.getLengthBuffer(e));for(let t=0;t<e.length;t++){let a=e[t];if(a==null||a===n.unset)throw TypeError(`A collection can't contain null or unset values`);let o=this.encode(a,r);i.push(this.getLengthBuffer(o)),i.push(o)}return Buffer.concat(i)},this.encodeSet=function(e,t){if(this.encodingOptions.set&&e instanceof this.encodingOptions.set){let n=[];return e.forEach(function(e){n.push(e)}),this.encodeList(n,t)}return this.encodeList(e,t)},this.encodeMap=function(e,t){let r=t.info,i=[],a=0,o=null,s=null,c=this;r&&(o=r[0],s=r[1]);function addItem(e,t){if(t==null||t===n.unset)throw TypeError(`A map can't contain null or unset keys`);if(e==null||e===n.unset)throw TypeError(`A map can't contain null or unset values`);let r=c.encode(t,o);i.push(c.getLengthBuffer(r)),i.push(r);let l=c.encode(e,s);i.push(c.getLengthBuffer(l)),l!==null&&i.push(l),a++}if(this.encodingOptions.map&&e instanceof this.encodingOptions.map)e.forEach(addItem);else for(let t in e){if(!e.hasOwnProperty(t))continue;let n=e[t];addItem(n,t)}return i.unshift(this.getLengthBuffer(a)),Buffer.concat(i)},this.encodeUdt=function(t,r){let i=r.info,a=[],o=0;for(let r=0;r<i.fields.length;r++){let s=i.fields[r],c=this.encode(t[s.name],s.type);if(!c){a.push(w),o+=4;continue}if(c===n.unset){a.push(T),o+=4;continue}let l=e.allocBufferUnsafe(4);l.writeInt32BE(c.length,0),a.push(l),a.push(c),o+=c.length+4}return Buffer.concat(a,o)},this.encodeTuple=function(t,r){let i=r.info,a=[],o=0,s=Math.min(i.length,t.length);for(let r=0;r<s;r++){let s=i[r],c=this.encode(t.get(r),s);if(!c){a.push(w),o+=4;continue}if(c===n.unset){a.push(T),o+=4;continue}let l=e.allocBufferUnsafe(4);l.writeInt32BE(c.length,0),a.push(l),a.push(c),o+=c.length+4}return Buffer.concat(a,o)},this.decodeVector=function(r,i){let a=i.info[0],o=i.info[1],s=this.serializationSizeIfFixed(a),c=[],l=0;for(let t=0;t<o;t++)if(s===-1){let[n,i]=e.VIntCoding.uvintUnpack(r.subarray(l));if(l+=i,l+n>r.length)throw TypeError(`Not enough bytes to decode the vector`);c[t]=this.decode(r.subarray(l,l+n),a),l+=n}else{if(l+s>r.length)throw TypeError(`Not enough bytes to decode the vector`);c[t]=this.decode(r.subarray(l,l+s),a),l+=s}if(l!==r.length)throw TypeError(`Extra bytes found after decoding the vector`);return new t(c,n.getDataTypeNameByCode(a))},this.serializationSizeIfFixed=function(e){switch(e.code){case o.bigint:return 8;case o.boolean:return 1;case o.timestamp:return 8;case o.double:return 8;case o.float:return 4;case o.int:return 4;case o.timeuuid:return 16;case o.uuid:return 16;case o.custom:if(`customTypeName`in e&&e.customTypeName===`vector`){let t=this.serializationSizeIfFixed(e.info[0]);return t===-1?-1:t*e.info[1]}return-1;default:return-1}},this.encodeVector=function(n,r){if(!(n instanceof t))throw TypeError(`Driver only supports Vector type when encoding a vector`);let i=r.info[1];if(n.length!==i)throw TypeError(`Expected vector with ${i} dimensions, observed size of ${n.length}`);if(n.length===0)throw TypeError(`Cannot encode empty array as vector`);let a=this.serializationSizeIfFixed(r.info[0]),o=[];for(let t of n){let n=this.encode(t,r.info[0]);a===-1&&o.push(e.VIntCoding.uvintPack(n.length)),o.push(n)}return Buffer.concat(o)},this.parseVectorTypeArgs=function(e,t,n){let r=parseParams(e,t.length+1,e.length-(t.length+2));if(r.length===2)return{code:o.custom,info:[n.bind(this)(r[0].trim()),parseInt(r[1].trim(),10)],customTypeName:`vector`};throw TypeError(`Not a valid type `+e)},this.setRoutingKeyFromUser=function(t,n,r){let o=0,s=n.getRoutingKey();if(Array.isArray(s)){if(s.length===1){n.setRoutingKey(s[0]);return}o=0;for(let e=0;e<s.length;e++){let t=s[e];if(!t){n.setRoutingKey(null);return}o+=t.length+3}n.setRoutingKey(concatRoutingKey(s,o));return}if(s){if(s instanceof Buffer||s instanceof i.Token||s instanceof i.TokenRange)return;throw TypeError(`Unexpected routingKey '${a.inspect(s)}' provided. Expected Buffer, Array<Buffer>, Token, or TokenRange.`)}if(!t||t.length===0)return;let c=n.getRoutingIndexes();if(n.getRoutingNames()&&(c=n.getRoutingNames().map(e=>r[e])),!c)return;let l=[],u=n.getHints()||e.emptyArray,d=r?e=>this.encode(t[e].value,u[e]):e=>this.encode(t[e],u[e]);try{o=this._encodeRoutingKeyParts(l,c,d)}catch{}o!==0&&n.setRoutingKey(concatRoutingKey(l,o))},this.setRoutingKeyFromMeta=function(e,t,n){let r=n.getRoutingIndexes();if(!r)return;let i=Array(r.length),encodeParam=n=>{let r=e.columns[n];return this.encode(t[n],r?r.type:null)},a=0;try{a=this._encodeRoutingKeyParts(i,r,encodeParam)}catch{}a!==0&&n.setRoutingKey(concatRoutingKey(i,a))},this._encodeRoutingKeyParts=function(e,t,r){let i=0;for(let a=0;a<t.length;a++){let o=t[a];if(o===void 0)return 0;let s=r(o);if(s==null||s===n.unset)return 0;i+=s.length+3,e[a]=s}return i},this.parseTypeName=async function(e,t,n,r,i){n||=0,r||=t.length;let a,s=!1;if(t.indexOf(`'`,n)===n){let e=t.substr(n+1,r-2);return{code:o.custom,info:e}}if(r||=t.length,t.indexOf(b.frozen,n)===n&&(n+=b.frozen.length+1,r-=b.frozen.length+2,s=!0),t.indexOf(b.list,n)===n){if(n+=b.list.length+1,r-=b.list.length+2,a=parseParams(t,n,r,`<`,`>`),a.length!==1)throw TypeError(`Not a valid type `+t);let c=await this.parseTypeName(e,a[0],0,null,i);return{code:o.list,info:c,options:{frozen:s}}}if(t.indexOf(b.set,n)===n){if(n+=b.set.length+1,r-=b.set.length+2,a=parseParams(t,n,r,`<`,`>`),a.length!==1)throw TypeError(`Not a valid type `+t);let c=await this.parseTypeName(e,a[0],0,null,i);return{code:o.set,info:c,options:{frozen:s}}}if(t.indexOf(b.map,n)===n){if(n+=b.map.length+1,r-=b.map.length+2,a=parseParams(t,n,r,`<`,`>`),a.length!==2)throw TypeError(`Not a valid type `+t);let c=await this._parseChildTypes(e,a,i);return{code:o.map,info:c,options:{frozen:s}}}if(t.indexOf(b.tuple,n)===n){if(n+=b.tuple.length+1,r-=b.tuple.length+2,a=parseParams(t,n,r,`<`,`>`),a.length<1)throw TypeError(`Not a valid type `+t);let c=await this._parseChildTypes(e,a,i);return{code:o.tuple,info:c,options:{frozen:s}}}if(t.indexOf(b.vector,n)===n){let n=this.parseVectorTypeArgs.bind(this)(t,b.vector,e=>e);return n.info[0]=await this.parseTypeName(e,n.info[0]),n}let c=t.indexOf(`"`,n)===n;c&&(n++,r-=2),n>0&&(t=t.substr(n,r)),c&&(t=t.replace(`""`,`"`));let l=o[t];if(typeof l==`number`)return{code:l,info:null};if(t===b.duration)return{code:o.custom,info:C.duration};if(t===b.empty)return{code:o.custom,info:`empty`};let u=await i(e,t);if(u)return{code:o.udt,info:u,options:{frozen:s}};throw TypeError(`Not a valid type "`+t+`"`)},this._parseChildTypes=function(e,t,n){return Promise.all(t.map(t=>this.parseTypeName(e,t.trim(),0,null,n)))},this.parseFqTypeName=function(e,t,n){let r=!1,i=!1;t||=0;let a;n||=e.length,n>y.reversed.length&&e.indexOf(y.reversed)===t&&(t+=y.reversed.length+1,n-=y.reversed.length+2,i=!0),n>y.frozen.length&&e.indexOf(y.frozen,t)===t&&(t+=y.frozen.length+1,n-=y.frozen.length+2,r=!0);let s={frozen:r,reversed:i};if(e===y.empty)return{code:o.custom,info:`empty`,options:s};if(n<=S){t>0&&(e=e.substr(t,n));let r=x[e];if(typeof r==`number`)return{code:r,info:null,options:s};if(e===C.duration)return{code:o.duration,options:s};throw TypeError(`Not a valid type "`+e+`"`)}if(e.indexOf(y.list,t)===t){if(t+=y.list.length+1,n-=y.list.length+2,a=parseParams(e,t,n),a.length!==1)throw TypeError(`Not a valid type `+e);let r=this.parseFqTypeName(a[0]);return{code:o.list,info:r,options:s}}if(e.indexOf(y.set,t)===t){if(t+=y.set.length+1,n-=y.set.length+2,a=parseParams(e,t,n),a.length!==1)throw TypeError(`Not a valid type `+e);let r=this.parseFqTypeName(a[0]);return{code:o.set,info:r,options:s}}if(e.indexOf(y.map,t)===t){if(t+=y.map.length+1,n-=y.map.length+2,a=parseParams(e,t,n),a.length!==2)throw TypeError(`Not a valid type `+e);let r=this.parseFqTypeName(a[0]),i=this.parseFqTypeName(a[1]);return{code:o.map,info:[r,i],options:s}}if(e.indexOf(y.udt,t)===t){t+=y.udt.length+1,n-=y.udt.length+2;let r=this._parseUdtName(e,t,n);return r.options=s,r}if(e.indexOf(y.tuple,t)===t){if(t+=y.tuple.length+1,n-=y.tuple.length+2,a=parseParams(e,t,n),a.length<1)throw TypeError(`Not a valid type `+e);let r=a.map(e=>this.parseFqTypeName(e));return{code:o.tuple,info:r,options:s}}if(e.indexOf(C.vector,t)===t){let t=this.parseVectorTypeArgs.bind(this)(e,C.vector,this.parseFqTypeName);return t.options=s,t}let c=e.substr(t,n);return{code:o.custom,info:c,options:s}},this.parseKeyTypes=function(e){let t=0,n=e.length,r=e.indexOf(y.composite)===0;r&&(t=y.composite.length+1,n--);let i=[],a=t,o=0,s=!1,c=!1;for(;++t<n;)switch(e[t]){case`,`:if(o>0)break;s&&(a=e.indexOf(`:`,a)+1),i.push(e.substring(a,t)),a=t+1;break;case`(`:if(o===0&&e.indexOf(y.collection,a)===a){s=!0,c=!0,t++,a=t;break}o++;break;case`)`:if(s&&o===0){i.push(e.substring(e.indexOf(`:`,a)+1,t)),a=t+1;break}o--;break}return a<n&&i.push(e.substring(a,n)),{types:i.map(e=>this.parseFqTypeName(e)),hasCollections:c,isComposite:r}},this._parseUdtName=function(t,n,r){let i=parseParams(t,n,r);if(i.length<2)throw TypeError(`Not a valid type `+t);let a={keyspace:i[0],name:e.allocBufferFromString(i[1],`hex`).toString(),fields:[]};for(let t=2;t<i.length;t++){let n=i[t],r=n.indexOf(`:`),o=this.parseFqTypeName(n,r+1,n.length-(r+1));a.fields.push({name:e.allocBufferFromString(n.substr(0,r),`hex`).toString(),type:o})}return{code:o.udt,info:a}}}function setEncoders(){this.decoders={[o.custom]:this.decodeCustom,[o.ascii]:this.decodeAsciiString,[o.bigint]:this.decodeLong,[o.blob]:this.decodeBlob,[o.boolean]:this.decodeBoolean,[o.counter]:this.decodeLong,[o.decimal]:this.decodeDecimal,[o.double]:this.decodeDouble,[o.float]:this.decodeFloat,[o.int]:this.decodeInt,[o.text]:this.decodeUtf8String,[o.timestamp]:this.decodeTimestamp,[o.uuid]:this.decodeUuid,[o.varchar]:this.decodeUtf8String,[o.varint]:this.decodeVarint,[o.timeuuid]:this.decodeTimeUuid,[o.inet]:this.decodeInet,[o.date]:this.decodeDate,[o.time]:this.decodeTime,[o.smallint]:this.decodeSmallint,[o.tinyint]:this.decodeTinyint,[o.duration]:decodeDuration,[o.list]:this.decodeList,[o.map]:this.decodeMap,[o.set]:this.decodeSet,[o.udt]:this.decodeUdt,[o.tuple]:this.decodeTuple},this.encoders={[o.custom]:this.encodeCustom,[o.ascii]:this.encodeAsciiString,[o.bigint]:this.encodeLong,[o.blob]:this.encodeBlob,[o.boolean]:this.encodeBoolean,[o.counter]:this.encodeLong,[o.decimal]:this.encodeDecimal,[o.double]:this.encodeDouble,[o.float]:this.encodeFloat,[o.int]:this.encodeInt,[o.text]:this.encodeUtf8String,[o.timestamp]:this.encodeTimestamp,[o.uuid]:this.encodeUuid,[o.varchar]:this.encodeUtf8String,[o.varint]:this.encodeVarint,[o.timeuuid]:this.encodeUuid,[o.inet]:this.encodeInet,[o.date]:this.encodeDate,[o.time]:this.encodeTime,[o.smallint]:this.encodeSmallint,[o.tinyint]:this.encodeTinyint,[o.duration]:encodeDuration,[o.list]:this.encodeList,[o.map]:this.encodeMap,[o.set]:this.encodeSet,[o.udt]:this.encodeUdt,[o.tuple]:this.encodeTuple}}Encoder.prototype.decode=function(e,t){if(e===null||e.length===0&&!E.has(t.code))return null;let n=this.decoders[t.code];if(!n)throw Error(`Unknown data type: `+t.code);return n.call(this,e,t)},Encoder.prototype.encode=function(e,t){if(e===void 0&&(e=this.encodingOptions.useUndefinedAsUnset&&this.protocolVersion>=4?n.unset:null),e===n.unset){if(!n.protocolVersion.supportsUnset(this.protocolVersion))throw TypeError(`Unset value can not be used for this version of Cassandra, protocol version: `+this.protocolVersion);return e}if(e===null||e instanceof Buffer)return e;let r=null;if(t){if(typeof t==`number`?r={code:t}:typeof t==`string`?r=o.getByName(t):typeof t.code==`number`&&(r=t),r==null||typeof r.code!=`number`)throw TypeError(`Type information not valid, only String and Number values are valid hints`)}else if(r=Encoder.guessDataType(e),!r)throw TypeError(`Target data type could not be guessed, you should use prepared statements for accurate type mapping. Value: `+a.inspect(e));let i=this.encoders[r.code];if(!i)throw Error(`Type not supported `+r.code);return i.call(this,e,r)},Encoder.guessDataType=function(e){let t=typeof e;if(t===`number`)return{code:o.double};if(t===`string`)return e.length===36&&u.test(e)?{code:o.uuid}:{code:o.text};if(t===`boolean`)return{code:o.boolean};if(e instanceof Buffer)return{code:o.blob};if(e instanceof Date)return{code:o.timestamp};if(e instanceof s)return{code:o.bigint};if(e instanceof c)return{code:o.varint};if(e instanceof l)return{code:o.decimal};if(e instanceof n.Uuid)return{code:o.uuid};if(e instanceof n.InetAddress)return{code:o.inet};if(e instanceof n.Tuple)return{code:o.tuple};if(e instanceof n.LocalDate)return{code:o.date};if(e instanceof n.LocalTime)return{code:o.time};if(e instanceof n.Duration)return{code:o.custom,info:C.duration};if(e instanceof n.Vector)if(e&&e.length>0){if(e instanceof Float32Array)return{code:o.custom,customTypeName:`vector`,info:[{code:o.float},e.length]};let t=null;if(e.subtype)try{t=o.getByName(e.subtype)}catch{}if(t??=this.guessDataType(e[0]),t!=null)return{code:o.custom,customTypeName:`vector`,info:[t,e.length]};throw TypeError(`Cannot guess subtype from element `+e[0])}else throw TypeError(`Cannot guess subtype of empty vector`);else if(Array.isArray(e))return{code:o.list};return null};function getLengthBufferV2(t){if(!t)return d.int16Zero;let n=e.allocBufferUnsafe(2);return typeof t==`number`?n.writeUInt16BE(t,0):n.writeUInt16BE(t.length,0),n}function getLengthBufferV3(t){if(!t)return d.int32Zero;let n=e.allocBufferUnsafe(4);return typeof t==`number`?n.writeInt32BE(t,0):n.writeInt32BE(t.length,0),n}function handleBufferCopy(t){return t===null?null:e.copyBuffer(t)}function handleBufferRef(e){return e}function decodeCollectionLengthV3(e,t){return e.readInt32BE(t)}function decodeCollectionLengthV2(e,t){return e.readUInt16BE(t)}function decodeDuration(e){return n.Duration.fromBuffer(e)}function encodeDuration(e){if(!(e instanceof n.Duration))throw TypeError(`Not a valid duration, expected Duration/Buffer obtained `+a.inspect(e));return e.toBuffer()}function parseParams(e,t,n,r,i){r||=`(`,i||=`)`;let a=[],o=t,s=0;for(let c=t;c<t+n;c++){let t=e[c];t===r&&s++,t===i&&s--,s===0&&t===`,`&&(a.push(e.substr(o,c-o)),o=c+1)}return a.push(e.substr(o,n-(o-t))),a}function concatRoutingKey(t,n){if(n===0)return null;if(t.length===1)return t[0];let r=e.allocBufferUnsafe(n),i=0;for(let e=0;e<t.length;e++){let n=t[e];r.writeUInt16BE(n.length,i),i+=2,n.copy(r,i),i+=n.length,r[i]=0,i++}return r}function invertObject(e){let t={};for(let n in e)e.hasOwnProperty(n)&&(t[e[n]]=n);return t}Encoder.isTypedArray=function(e){return e instanceof Object.getPrototypeOf(Uint8Array)};export{Encoder as default};
|
package/driver/errors.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import e from"util";function DriverError(e){Error.call(this,e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.info=`Cassandra Driver Error`,this.message=e}e.inherits(DriverError,Error);function NoHostAvailableError(t,n){if(DriverError.call(this,n),this.innerErrors=t,this.info=`Represents an error when a query cannot be performed because no host is available or could be reached by the driver.`,!n&&(this.message=`All host(s) tried for query failed.`,t)){let n=Object.keys(t);if(n.length>0){let r=n[0];this.message+=e.format(` First host tried, %s: %s. See innerErrors.`,r,t[r])}}}e.inherits(NoHostAvailableError,DriverError);function ResponseError(e,t){DriverError.call(this,t),this.code=e,this.info=`Represents an error message from the server`}e.inherits(ResponseError,DriverError);function DriverInternalError(e){DriverError.call(this,e),this.info=`Represents a bug inside the driver or in a Cassandra host.`}e.inherits(DriverInternalError,DriverError);function AuthenticationError(e){DriverError.call(this,e),this.info=`Represents an authentication error from the driver or from a Cassandra node.`}e.inherits(AuthenticationError,DriverError);function ArgumentError(e){DriverError.call(this,e),this.info=`Represents an error that is raised when one of the arguments provided to a method is not valid.`}e.inherits(ArgumentError,DriverError);function OperationTimedOutError(e,t){DriverError.call(this,e,this.constructor),this.info=`Represents a client-side error that is raised when the client did not hear back from the server within socketOptions.readTimeout`,this.host=t}e.inherits(OperationTimedOutError,DriverError);function NotSupportedError(e){DriverError.call(this,e,this.constructor),this.info=`Represents a feature that is not supported in the driver or in the Cassandra version.`}e.inherits(NotSupportedError,DriverError);function BusyConnectionError(t,n,r){let i=e.format(`All connections to host %s are busy, %d requests are in-flight on %s`,t,n,r===1?`a single connection`:`each connection`);DriverError.call(this,i,this.constructor),this.info=`Represents a client-side error indicating that all connections to a certain host have reached the maximum amount of in-flight requests supported (pooling.maxRequestsPerConnection)`}e.inherits(BusyConnectionError,DriverError);function VIntOutOfRangeException(e){let t=`Value ${e.toString} is out of range for a JavaScript Number`;DriverError.call(this,t,this.constructor),this.info=`Represents a run-time exception when attempting to decode a vint and the JavaScript Number doesn't have enough space to fit the value that was decoded`}e.inherits(VIntOutOfRangeException,DriverError);var t={ArgumentError,AuthenticationError,BusyConnectionError,DriverError,OperationTimedOutError,DriverInternalError,NoHostAvailableError,NotSupportedError,ResponseError,VIntOutOfRangeException};export{t as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import e from"./errors.js";import t from"./utils.js";import n from"./types/index.js";const r=`ProxyExecute`;var i=class ExecutionOptions{constructor(){}static empty(){return new ExecutionOptions}getCaptureStackTrace(){}getConsistency(){}getCustomPayload(){}getFetchSize(){}getFixedHost(){}getHints(){}isAutoPage(){}isBatchCounter(){}isBatchLogged(){}isIdempotent(){}isPrepared(){}isQueryTracing(){}getKeyspace(){}getLoadBalancingPolicy(){}getPageState(){}getPreferredHost(){}getRawQueryOptions(){}getReadTimeout(){}getRetryPolicy(){}getRowCallback(){}getOrGenerateTimestamp(){}getRoutingIndexes(){}getRoutingKey(){}getRoutingNames(){}getSerialConsistency(){}getTimestamp(){}setHints(e){}setKeyspace(e){}setPageState(){}setPreferredHost(){}setRoutingIndexes(e){}setRoutingKey(e){}},a=class DefaultExecutionOptions extends i{constructor(n,r,i){if(super(),this._queryOptions=n,this._rowCallback=i,this._routingKey=this._queryOptions.routingKey,this._hints=this._queryOptions.hints,this._keyspace=this._queryOptions.keyspace,this._routingIndexes=this._queryOptions.routingIndexes,this._pageState=typeof this._queryOptions.pageState==`string`?t.allocBufferFromString(this._queryOptions.pageState,`hex`):this._queryOptions.pageState,this._preferredHost=null,this._client=r,this._defaultQueryOptions=r.options.queryOptions,this._profile=r.profileManager.getProfile(this._queryOptions.executionProfile),this._customPayload=DefaultExecutionOptions.createCustomPayload(this._queryOptions,this._defaultQueryOptions),!this._profile)throw new e.ArgumentError(`Execution profile "${this._queryOptions.executionProfile}" not found`)}static createCustomPayload(e,n){let i=e.customPayload||n.customPayload,a=e.executeAs||n.executeAs;return a&&(i?i.ProxyExecute||(i=t.extend({},i),i[r]=t.allocBufferFromString(a)):(i={},i[r]=t.allocBufferFromString(a))),i}static create(e,n,r){return(!e||typeof e==`function`)&&(e=t.emptyObject),new DefaultExecutionOptions(e,n,r)}getCaptureStackTrace(){return ifUndefined(this._queryOptions.captureStackTrace,this._defaultQueryOptions.captureStackTrace)}getConsistency(){return ifUndefined3(this._queryOptions.consistency,this._profile.consistency,this._defaultQueryOptions.consistency)}getCustomPayload(){return this._customPayload}getFetchSize(){return ifUndefined(this._queryOptions.fetchSize,this._defaultQueryOptions.fetchSize)}getFixedHost(){return this._queryOptions.host}getHints(){return this._hints}isAutoPage(){return ifUndefined(this._queryOptions.autoPage,this._defaultQueryOptions.autoPage)}isBatchCounter(){return ifUndefined(this._queryOptions.counter,!1)}isBatchLogged(){return ifUndefined3(this._queryOptions.logged,this._defaultQueryOptions.logged,!0)}isIdempotent(){return ifUndefined(this._queryOptions.isIdempotent,this._defaultQueryOptions.isIdempotent)}isPrepared(){return ifUndefined(this._queryOptions.prepare,this._defaultQueryOptions.prepare)}isQueryTracing(){return ifUndefined(this._queryOptions.traceQuery,this._defaultQueryOptions.traceQuery)}getKeyspace(){return this._keyspace}getLoadBalancingPolicy(){return this._profile.loadBalancing}getOrGenerateTimestamp(){let e=this.getTimestamp();if(e===void 0){let t=this._client.options.policies.timestampGeneration;e=n.protocolVersion.supportsTimestamp(this._client.controlConnection.protocolVersion)&&t?t.next(this._client):null}return typeof e==`number`?n.Long.fromNumber(e):e}getPageState(){return this._pageState}getProfile(){return this._profile}getRawQueryOptions(){return this._queryOptions}getReadTimeout(){return ifUndefined3(this._queryOptions.readTimeout,this._profile.readTimeout,this._client.options.socketOptions.readTimeout)}getRetryPolicy(){return ifUndefined3(this._queryOptions.retry,this._profile.retry,this._client.options.policies.retry)}getRoutingIndexes(){return this._routingIndexes}getRoutingKey(){return this._routingKey}getRoutingNames(){return this._queryOptions.routingNames}getRowCallback(){return this._rowCallback}getSerialConsistency(){return ifUndefined3(this._queryOptions.serialConsistency,this._profile.serialConsistency,this._defaultQueryOptions.serialConsistency)}getTimestamp(){return this._queryOptions.timestamp}setCustomPayload(e){this._customPayload=e}setHints(e){this._hints=e}setKeyspace(e){this._keyspace=e}setPageState(e){this._pageState=e}setRoutingIndexes(e){this._routingIndexes=e}setRoutingKey(e){this._routingKey=e}};function ifUndefined(e,t){return e===void 0?t:e}function ifUndefined3(e,t,n){return e===void 0?t===void 0?n:t:e}export{a as DefaultExecutionOptions,i as ExecutionOptions};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import e from"./promise-utils.js";import t from"./utils.js";import n from"./types/index.js";function ExecutionProfile(e,n){if(typeof e!=`string`)throw TypeError(`Execution profile name must be a string`);n||=t.emptyObject;let r=n.graphOptions||t.emptyObject;this.name=e,this.consistency=n.consistency,this.loadBalancing=n.loadBalancing,this.readTimeout=n.readTimeout,this.retry=n.retry,this.serialConsistency=n.serialConsistency,this.graphOptions={language:r.language,results:r.results,name:r.name,readConsistency:r.readConsistency,source:r.source,writeConsistency:r.writeConsistency}}var ProfileManager=class{constructor(e){this._profiles=e.profiles||[],this._defaultConfiguredRetryPolicy=void 0,this._setDefault(e),this._loadBalancingPolicies=[],this._profilesMap={},this._customPayloadCache={},this._graphOptionsCache={},this._profiles.forEach(function(e){return this._profilesMap[e.name]=e,e.loadBalancing=e.loadBalancing||this._defaultProfile.loadBalancing,this._loadBalancingPolicies.indexOf(e.loadBalancing)===-1&&this._loadBalancingPolicies.push(e.loadBalancing),e},this)}async init(t,n){for(let r of this._loadBalancingPolicies)await e.fromCallback(e=>r.init(t,n,e))}getDistance(e){let t=n.distance.ignored;for(let r=0;r<this._loadBalancingPolicies.length;r++){let i=this._loadBalancingPolicies[r].getDistance(e);if(i<t&&(t=i,t===n.distance.local))break}return e.setDistance(t),t}getProfile(e){return e instanceof ExecutionProfile?e:this._profilesMap[e||`default`]}getDefault(){return this._defaultProfile}getDefaultLoadBalancing(){return this._defaultProfile.loadBalancing}getOrCreateGraphOptions(e,t){let n=this._graphOptionsCache[e.name];return n||=this._graphOptionsCache[e.name]=t(),n}_setDefault(e){this._defaultProfile=this._profiles.filter(function(e){return e.name===`default`})[0],this._defaultProfile||this._profiles.push(this._defaultProfile=new ExecutionProfile(`default`)),this._defaultConfiguredRetryPolicy=this._defaultProfile.retry,this._defaultProfile.loadBalancing=this._defaultProfile.loadBalancing||e.policies.loadBalancing,this._defaultProfile.retry=this._defaultProfile.retry||e.policies.retry}getAll(){return this._profiles}getDefaultConfiguredRetryPolicy(){return this._defaultConfiguredRetryPolicy}};export{ExecutionProfile,ProfileManager};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import e from"./errors.js";import t from"./promise-utils.js";import n from"./utils.js";import r from"./client-options.js";import i from"./connection.js";import a from"util";import o from"events";let s=0;const c=2**15;let l;const u={initial:0,closing:1,shuttingDown:2,shutDown:4};var d=class HostConnectionPool extends o.EventEmitter{constructor(e,t){super(),this._address=e.address,this._newConnectionTimeout=null,this._state=u.initial,this._opening=!1,this._host=e,this.responseCounter=0,this.options=e.options,this.protocolVersion=t,this.coreConnectionsLength=1,this.connections=n.emptyArray,this.setMaxListeners(0),this.log=n.log}getInFlight(){let e=this.connections.length;if(e===1)return this.connections[0].getInFlight();let t=0;for(let n=0;n<e;n++)t+=this.connections[n].getInFlight();return t}borrowConnection(t){if(this.connections.length===0)throw Error(`No connection available`);let n=this.options.pooling.maxRequestsPerConnection,r=HostConnectionPool.minInFlight(this.connections,n,t);if(r.getInFlight()>=n)throw new e.BusyConnectionError(this._address,n,this.connections.length);return r}static minInFlight(e,t,n){let r=e.length;if(r===1)return e[0];s++,s>=c&&(s=0);let i;for(let a=s;a<s+r;a++){i=e[a%r],i===n&&(i=e[++a%r]);let o=e[(a+1)%r];if(o===n&&(o=e[(a+2)%r]),o.getInFlight()<i.getInFlight()&&(i=o),i.getInFlight()<t)break}return i}async warmup(e){if(this.connections.length<this.coreConnectionsLength){for(;this.connections.length<this.coreConnectionsLength;)await this._attemptNewConnection();this.log(`info`,`Connection pool to host ${this._address} created with ${this.connections.length} connection(s)`)}else this.log(`info`,`Connection pool to host ${this._address} contains ${this.connections.length} connection(s)`);if(e)try{for(let t of this.connections)await t.changeKeyspace(e)}catch{this.log(`warning`,`Connection(s) to host ${this._address} could not be switched to keyspace ${e}`)}}_createConnection(){let e=new i(this.options.sni?this._host.hostId.toString():this._address,this.protocolVersion,this.options);return this._addListeners(e),e}_addListeners(e){e.on(`responseDequeued`,()=>this.responseCounter++);let t=this;function connectionErrorCallback(){t.remove(e)}e.on(`idleRequestError`,connectionErrorCallback),e.on(`socketClose`,connectionErrorCallback)}addExistingConnection(e){this._addListeners(e),this.connections=this.connections.slice(0),this.connections.push(e)}clearNewConnectionAttempt(){this._newConnectionTimeout&&=(clearTimeout(this._newConnectionTimeout),null)}async _attemptNewConnection(){if(this._opening)return await t.fromEvent(this,`open`);this._opening=!0;let e=this._createConnection(),n;try{await e.openAsync()}catch(e){n=e,this.log(`warning`,`Connection to ${this._address} could not be created: ${n}`,n)}if(this.isClosing()&&(this.log(`info`,`Connection to ${this._address} opened successfully but pool was being closed`),n=Error(`Connection closed`)),n)t.toBackground(e.closeAsync());else{let t=this.connections.slice(0);t.push(e),this.connections=t,this.log(`info`,`Connection to ${this._address} opened successfully`)}if(this._opening=!1,this.emit(`open`,n,e),n)throw n}attemptNewConnectionImmediate(){let e=this;function openConnection(){e.clearNewConnectionAttempt(),e.scheduleNewConnectionAttempt(0)}if(this._state===u.initial)return openConnection();if(this._state===u.closing)return this.once(`close`,openConnection)}remove(e){let t=this.connections.indexOf(e);if(t<0)return;let n=this.connections.slice(0);n.splice(t,1),this.connections=n,setImmediate(function(){e.close()}),this.emit(`remove`)}scheduleNewConnectionAttempt(e){if(this.isClosing())return;let n=this;this._newConnectionTimeout=setTimeout(function(){if(n._newConnectionTimeout=null,!(n.connections.length>=n.coreConnectionsLength)){if(e>0&&n.options.sni){t.toBackground(n.options.sni.addressResolver.refresh().then(()=>n._attemptNewConnection()));return}t.toBackground(n._attemptNewConnection())}},e)}hasScheduledNewConnection(){return!!this._newConnectionTimeout||this._opening}increaseSize(){this.connections.length<this.coreConnectionsLength&&!this.hasScheduledNewConnection()&&this.scheduleNewConnectionAttempt(0)}getAndResetResponseCounter(){let e=this.responseCounter;return this.responseCounter=0,e}isClosing(){return this._state!==u.initial}drainAndShutdown(){if(this.isClosing())return;if(this._state=u.closing,this.clearNewConnectionAttempt(),this.connections.length===0)return this._afterClosing();let e=this,t=this.connections;this.connections=n.emptyArray;let r=0;this.log(`info`,a.format(`Draining and closing %d connections to %s`,t.length,this._address));let i=!1,o;for(let e=0;e<t.length;e++){let n=t[e];if(n.getInFlight()===0){getDelayedClose(n)();continue}n.emitDrain=!0,n.once(`drain`,getDelayedClose(n))}function getDelayedClose(n){return function(){n.close(),!(++r<t.length)&&(i||(i=!0,o&&clearTimeout(o),e._afterClosing()))}}let s=(this.options.socketOptions.readTimeout||getDefaultOptions().socketOptions.readTimeout)+100;o=setTimeout(function(){i=!0,t.forEach(function(e){e.close()}),e._afterClosing()},s)}_afterClosing(){let e=this;function resetState(){e._state===u.shuttingDown?e._state=u.shutDown:e._state=u.initial,e.emit(`close`),e._state===u.shutDown&&e.emit(`shutdown`)}if(this._opening)return this.once(`open`,resetState);resetState()}async shutdown(){if(this.clearNewConnectionAttempt(),!this.connections.length){this._state=u.shutDown;return}let e=this._state;if(this._state=u.shuttingDown,e===u.closing||e===u.shuttingDown)return t.fromEvent(this,`shutdown`);await this._closeAllConnections(),this._state=u.shutDown,this.emit(`shutdown`)}async _closeAllConnections(){let e=this.connections;this.connections=n.emptyArray,e.length!==0&&(this.log(`info`,a.format(`Closing %d connections to %s`,e.length,this._address)),await Promise.all(e.map(e=>e.closeAsync())))}};function getDefaultOptions(){return l===void 0&&(l=r.defaultOptions()),l}export{d as default};
|
package/driver/host.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import e from"./promise-utils.js";import t from"./utils.js";import n from"./types/index.js";import r from"./host-connection-pool.js";import i from"./prepare-handler.js";import a from"events";var Host=class extends a.EventEmitter{constructor(i,a,o,s){super(),this.address=i,this.setDownAt=0,this.log=t.log,this.isUpSince=null,Object.defineProperty(this,`options`,{value:o,enumerable:!1,writable:!1}),Object.defineProperty(this,`pool`,{value:new r(this,a),enumerable:!1}),this.pool.on(`open`,t=>e.toBackground(this._onNewConnectionOpen(t))),this.pool.on(`remove`,()=>this._checkPoolState()),this.cassandraVersion=null,this.datacenter=null,this.rack=null,this.tokens=null,this.hostId=null,this.dseVersion=null,this.workloads=t.emptyArray,this._distance=n.distance.ignored,this._healthResponseCounter=0,Object.defineProperty(this,`_metadata`,{value:s,enumerable:!1}),Object.defineProperty(this,`_healthResponseCountTimer`,{value:null,enumerable:!1,writable:!0}),this.reconnectionSchedule=this.options.policies.reconnection.newSchedule(),this.reconnectionDelay=0}setDown(){this.setDownAt===0&&(this.pool.isClosing()||(this.setDownAt=Date.now(),this.pool.coreConnectionsLength>0?this.log(`warning`,`Host ${this.address} considered as DOWN. Reconnection delay ${this.reconnectionDelay}ms.`):this.log(`info`,`Host ${this.address} considered as DOWN.`),this.emit(`down`),this._checkPoolState()))}setUp(e){this.setDownAt&&(this.log(`info`,`Setting host ${this.address} as UP`),this.setDownAt=0,this.isUpSince=Date.now(),this.reconnectionSchedule=this.options.policies.reconnection.newSchedule(),e&&this.pool.clearNewConnectionAttempt(),this.emit(`up`))}checkIsUp(){this.isUp()||(this.reconnectionSchedule=this.options.policies.reconnection.newSchedule(),this.reconnectionDelay=0,this.pool.attemptNewConnectionImmediate())}shutdown(e){return this._healthResponseCountTimer&&clearInterval(this._healthResponseCountTimer),e?(this.pool.drainAndShutdown(),Promise.resolve()):this.pool.shutdown()}isUp(){return!this.setDownAt}canBeConsideredAsUp(){let e=this;function hasTimePassed(){return new Date().getTime()-e.setDownAt>=e.reconnectionDelay}return!this.setDownAt||hasTimePassed()}setDistance(e){let t=this._distance;return this._distance=e||n.distance.local,this.options.pooling.coreConnectionsPerHost?this.pool.coreConnectionsLength=this.options.pooling.coreConnectionsPerHost[this._distance]||0:this.pool.coreConnectionsLength=1,this._distance===t?this._distance:(this._healthResponseCountTimer&&clearInterval(this._healthResponseCountTimer),this._distance===n.distance.ignored?(this.emit(`ignore`),this.pool.drainAndShutdown()):(this.isUp()||this.checkIsUp(),this._healthResponseCountTimer=setInterval(()=>{this._healthResponseCounter=this.pool.getAndResetResponseCounter()},200)),this._distance)}setProtocolVersion(e){this.pool.protocolVersion=e}borrowConnection(e){return this.pool.borrowConnection(e)}warmupPool(e){return this.pool.warmup(e)}initializePool(){this.pool.increaseSize()}getActiveConnection(){return!this.isUp()||!this.pool.connections.length?null:this.pool.connections[0]}getResponseCount(){return this._healthResponseCounter+this.pool.responseCounter}checkHealth(e){e.timedOutOperations<=this.options.socketOptions.defunctReadTimeoutThreshold||this.removeFromPool(e)}removeFromPool(e){this.pool.remove(e),this._checkPoolState()}getInFlight(){return this.pool.getInFlight()}_checkPoolState(){this.pool.isClosing()||(this.pool.connections.length<this.pool.coreConnectionsLength&&(this.pool.hasScheduledNewConnection()||(this.reconnectionDelay=this.reconnectionSchedule.next().value,this.pool.scheduleNewConnectionAttempt(this.reconnectionDelay))),this._distance!==n.distance.ignored&&this.pool.coreConnectionsLength>0&&this.pool.connections.length===0&&this.setDown())}async _onNewConnectionOpen(e){if(e){this._checkPoolState();return}if(!this.isUp()&&this.options.rePrepareOnUp){this.log(`info`,`Re-preparing all queries on host ${this.address} before setting it as UP`);let e=this._metadata.getAllPrepared();try{await i.prepareAllQueries(this,e)}catch(e){this.log(`warning`,`Failed re-preparing on host ${this.address}: ${e}`,e)}}this.setUp(),this.pool.increaseSize()}getCassandraVersion(){return this.cassandraVersion?this.cassandraVersion.split(`-`)[0].split(`.`).map(e=>parseInt(e,10)):t.emptyArray}getDseVersion(){return this.dseVersion?this.dseVersion.split(`-`)[0].split(`.`).map(e=>parseInt(e,10)):t.emptyArray}},HostMap=class extends a.EventEmitter{constructor(){super(),this._items=new Map,this._values=null,Object.defineProperty(this,`length`,{get:()=>this.values().length,enumerable:!0})}forEach(e){let t=this._items;for(let[n,r]of t)e(r,n)}get(e){return this._items.get(e)}keys(){return Array.from(this._items.keys())}remove(e){let t=this._items.get(e);if(t===void 0)return;this._values=null;let n=new Map(this._items);n.delete(e),this._items=n,this.emit(`remove`,t)}removeMultiple(e){this._values=null;let t=new Map(this._items),n=[];for(let r of e){let e=t.get(r);e&&(n.push(e),t.delete(r))}this._items=t,n.forEach(e=>this.emit(`remove`,e))}set(e,t){this._values=null;let n=this._items.get(e);if(n){this._items.set(e,t),this.emit(`remove`,n),this.emit(`add`,t);return}let r=new Map(this._items);return r.set(e,t),this._items=r,this.emit(`add`,t),t}slice(e,t){return!e&&!t?this.values():this.values().slice(e||0,t)}push(e,t){this.set(e,t)}values(){return this._values||=Object.freeze(Array.from(this._items.values())),this._values}clear(){let e=this.values();return this._values=null,this._items=new Map,e.forEach(e=>this.emit(`remove`,e)),e}inspect(){return this._items}toJSON(){if(Object.fromEntries)return Object.fromEntries(this._items);let e={};for(let[t,n]of this._items)e[t]=n;return e}};export{Host,HostMap};
|
package/driver/index.d.ts
CHANGED
|
@@ -1,18 +1,12 @@
|
|
|
1
|
-
import { auth } from "./
|
|
2
|
-
import { types } from "./
|
|
3
|
-
import { policies } from "./
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import { metadata } from "./lib/metadata/index.js";
|
|
7
|
-
import { concurrent } from "./lib/concurrent/index.js";
|
|
8
|
-
import { mapping } from "./lib/mapping/index.js";
|
|
9
|
-
import { geometry } from "./lib/geometry/index.js";
|
|
1
|
+
import { auth } from "./auth/index.js";
|
|
2
|
+
import { types } from "./types/index.js";
|
|
3
|
+
import { policies } from "./policies/index.js";
|
|
4
|
+
import { metadata } from "./metadata/index.js";
|
|
5
|
+
import { mapping } from "./mapping/index.js";
|
|
10
6
|
import * as events$1 from "events";
|
|
11
7
|
import * as tls$1 from "tls";
|
|
12
8
|
|
|
13
9
|
//#region src/driver/index.d.ts
|
|
14
|
-
declare const version: number;
|
|
15
|
-
declare function defaultOptions(): ClientOptions;
|
|
16
10
|
type ValueCallback<T> = (err: Error, val: T) => void;
|
|
17
11
|
type EmptyCallback = (err: Error) => void;
|
|
18
12
|
type ArrayOrObject = any[] | {
|
|
@@ -22,24 +16,14 @@ declare class Client extends events$1.EventEmitter {
|
|
|
22
16
|
hosts: HostMap;
|
|
23
17
|
keyspace: string;
|
|
24
18
|
metadata: metadata.Metadata;
|
|
25
|
-
metrics:
|
|
26
|
-
constructor(options:
|
|
19
|
+
metrics: null;
|
|
20
|
+
constructor(options: ClientOptions);
|
|
27
21
|
connect(): Promise<void>;
|
|
28
22
|
connect(callback: EmptyCallback): void;
|
|
29
23
|
execute(query: string, params?: ArrayOrObject, options?: QueryOptions): Promise<types.ResultSet>;
|
|
30
24
|
execute(query: string, params: ArrayOrObject, options: QueryOptions, callback: ValueCallback<types.ResultSet>): void;
|
|
31
25
|
execute(query: string, params: ArrayOrObject, callback: ValueCallback<types.ResultSet>): void;
|
|
32
26
|
execute(query: string, callback: ValueCallback<types.ResultSet>): void;
|
|
33
|
-
executeGraph(traversal: string, parameters: {
|
|
34
|
-
[name: string]: any;
|
|
35
|
-
} | undefined, options: GraphQueryOptions, callback: ValueCallback<graph.GraphResultSet>): void;
|
|
36
|
-
executeGraph(traversal: string, parameters: {
|
|
37
|
-
[name: string]: any;
|
|
38
|
-
} | undefined, callback: ValueCallback<graph.GraphResultSet>): void;
|
|
39
|
-
executeGraph(traversal: string, callback: ValueCallback<graph.GraphResultSet>): void;
|
|
40
|
-
executeGraph(traversal: string, parameters?: {
|
|
41
|
-
[name: string]: any;
|
|
42
|
-
}, options?: GraphQueryOptions): Promise<graph.GraphResultSet>;
|
|
43
27
|
eachRow(query: string, params: ArrayOrObject, options: QueryOptions, rowCallback: (n: number, row: types.Row) => void, callback?: ValueCallback<types.ResultSet>): void;
|
|
44
28
|
eachRow(query: string, params: ArrayOrObject, rowCallback: (n: number, row: types.Row) => void, callback?: ValueCallback<types.ResultSet>): void;
|
|
45
29
|
eachRow(query: string, rowCallback: (n: number, row: types.Row) => void): void;
|
|
@@ -124,7 +108,6 @@ interface ClientOptions {
|
|
|
124
108
|
};
|
|
125
109
|
isMetadataSyncEnabled?: boolean;
|
|
126
110
|
maxPrepared?: number;
|
|
127
|
-
metrics?: metrics.ClientMetrics;
|
|
128
111
|
policies?: {
|
|
129
112
|
addressResolution?: policies.addressResolution.AddressTranslator;
|
|
130
113
|
loadBalancing?: policies.loadBalancing.LoadBalancingPolicy;
|
|
@@ -153,7 +136,6 @@ interface ClientOptions {
|
|
|
153
136
|
queryOptions?: QueryOptions;
|
|
154
137
|
refreshSchemaDelay?: number;
|
|
155
138
|
rePrepareOnUp?: boolean;
|
|
156
|
-
requestTracker?: tracker.RequestTracker;
|
|
157
139
|
socketOptions?: {
|
|
158
140
|
coalescingThreshold?: number;
|
|
159
141
|
connectTimeout?: number;
|
|
@@ -189,30 +171,6 @@ interface QueryOptions {
|
|
|
189
171
|
timestamp?: number | Long;
|
|
190
172
|
traceQuery?: boolean;
|
|
191
173
|
}
|
|
192
|
-
interface DseClientOptions extends ClientOptions {
|
|
193
|
-
id?: Uuid;
|
|
194
|
-
applicationName?: string;
|
|
195
|
-
applicationVersion?: string;
|
|
196
|
-
monitorReporting?: {
|
|
197
|
-
enabled?: boolean;
|
|
198
|
-
};
|
|
199
|
-
graphOptions?: GraphOptions;
|
|
200
|
-
}
|
|
201
|
-
interface GraphQueryOptions extends QueryOptions {
|
|
202
|
-
graphLanguage?: string;
|
|
203
|
-
graphName?: string;
|
|
204
|
-
graphReadConsistency?: types.consistencies;
|
|
205
|
-
graphSource?: string;
|
|
206
|
-
graphWriteConsistency?: types.consistencies;
|
|
207
|
-
}
|
|
208
|
-
type GraphOptions = {
|
|
209
|
-
language?: string;
|
|
210
|
-
name?: string;
|
|
211
|
-
readConsistency?: types.consistencies;
|
|
212
|
-
readTimeout?: number;
|
|
213
|
-
source?: string;
|
|
214
|
-
writeConsistency?: types.consistencies;
|
|
215
|
-
};
|
|
216
174
|
declare class ExecutionProfile {
|
|
217
175
|
consistency?: types.consistencies;
|
|
218
176
|
loadBalancing?: policies.loadBalancing.LoadBalancingPolicy;
|
|
@@ -220,64 +178,14 @@ declare class ExecutionProfile {
|
|
|
220
178
|
readTimeout?: number;
|
|
221
179
|
retry?: policies.retry.RetryPolicy;
|
|
222
180
|
serialConsistency?: types.consistencies;
|
|
223
|
-
graphOptions?: {
|
|
224
|
-
name?: string;
|
|
225
|
-
language?: string;
|
|
226
|
-
source?: string;
|
|
227
|
-
readConsistency?: types.consistencies;
|
|
228
|
-
writeConsistency?: types.consistencies;
|
|
229
|
-
};
|
|
230
181
|
constructor(name: string, options: {
|
|
231
182
|
consistency?: types.consistencies;
|
|
232
183
|
loadBalancing?: policies.loadBalancing.LoadBalancingPolicy;
|
|
233
184
|
readTimeout?: number;
|
|
234
185
|
retry?: policies.retry.RetryPolicy;
|
|
235
186
|
serialConsistency?: types.consistencies;
|
|
236
|
-
graphOptions?: {
|
|
237
|
-
name?: string;
|
|
238
|
-
language?: string;
|
|
239
|
-
source?: string;
|
|
240
|
-
readConsistency?: types.consistencies;
|
|
241
|
-
writeConsistency?: types.consistencies;
|
|
242
|
-
};
|
|
243
187
|
});
|
|
244
188
|
}
|
|
245
|
-
declare namespace errors {
|
|
246
|
-
class ArgumentError extends DriverError {
|
|
247
|
-
constructor(message: string);
|
|
248
|
-
}
|
|
249
|
-
class AuthenticationError extends DriverError {
|
|
250
|
-
constructor(message: string);
|
|
251
|
-
}
|
|
252
|
-
class BusyConnectionError extends DriverError {
|
|
253
|
-
constructor(address: string, maxRequestsPerConnection: number, connectionLength: number);
|
|
254
|
-
}
|
|
255
|
-
class VIntOutOfRangeException extends DriverError {
|
|
256
|
-
constructor(long: Long);
|
|
257
|
-
}
|
|
258
|
-
abstract class DriverError extends Error {
|
|
259
|
-
info: string;
|
|
260
|
-
constructor(message: string, constructor?: any);
|
|
261
|
-
}
|
|
262
|
-
class DriverInternalError extends DriverError {
|
|
263
|
-
constructor(message: string);
|
|
264
|
-
}
|
|
265
|
-
class NoHostAvailableError extends DriverError {
|
|
266
|
-
innerErrors: any;
|
|
267
|
-
constructor(innerErrors: any, message?: string);
|
|
268
|
-
}
|
|
269
|
-
class NotSupportedError extends DriverError {
|
|
270
|
-
constructor(message: string);
|
|
271
|
-
}
|
|
272
|
-
class OperationTimedOutError extends DriverError {
|
|
273
|
-
host?: string;
|
|
274
|
-
constructor(message: string, host?: string);
|
|
275
|
-
}
|
|
276
|
-
class ResponseError extends DriverError {
|
|
277
|
-
code: number;
|
|
278
|
-
constructor(code: number, message: string);
|
|
279
|
-
}
|
|
280
|
-
}
|
|
281
189
|
declare namespace token {
|
|
282
190
|
interface Token {
|
|
283
191
|
compare(other: Token): number;
|
|
@@ -301,4 +209,4 @@ declare namespace token {
|
|
|
301
209
|
}
|
|
302
210
|
}
|
|
303
211
|
//#endregion
|
|
304
|
-
export {
|
|
212
|
+
export { Client, ClientOptions, EmptyCallback, ExecutionOptions, Host, HostMap, ValueCallback, token };
|
package/driver/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"./
|
|
1
|
+
import e from"./errors.js";import t from"./types/index.js";import n from"./policies/index.js";import r from"./auth/index.js";import i from"./client-options.js";import{ExecutionProfile as a}from"./execution-profile.js";import{ExecutionOptions as o}from"./execution-options.js";import{version as s}from"../package.js";import{Token as c,TokenRange as l}from"./token.js";import u from"./encoder.js";import d from"./metadata/index.js";import f from"./client.js";import p from"./mapping/index.js";import m from"./concurrent/index.js";const h={Token:c,TokenRange:l},g={Metadata:d};function defaultOptions(){return i.defaultOptions()}const _={Client:f,ExecutionProfile:a,ExecutionOptions:o,types:t,errors:e,policies:n,auth:r,mapping:p,concurrent:m,token:h,metadata:g,Encoder:u,defaultOptions,version:s};export{_ as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{QueryAssignment as e,QueryOperator as t}from"./q.js";var n=class Cache{static*getSelectKey(e,t,n){yield*Cache._yieldKeyAndOperators(e,t),yield*Cache._getSelectDocInfo(n)}static*getSelectAllKey(e){yield`root`,yield*Cache._getSelectDocInfo(e)}static*_getSelectDocInfo(e){if(e&&(e.fields&&e.fields.length>0&&(yield`|f|`,yield*e.fields),typeof e.limit==`number`&&(yield`|l|`),e.orderBy)){yield`|o|`;let t=Object.keys(e.orderBy);for(let n=0;n<t.length;n++){let r=t[n];yield r,yield e.orderBy[r]}}}static*getInsertKey(e,t){yield*e,t&&(t.fields&&t.fields.length>0&&(yield`|f|`,yield*t.fields),typeof t.ttl==`number`&&(yield`|t|`),t.ifNotExists&&(yield`|e|`))}static*getUpdateKey(e,t,n){yield*Cache._yieldKeyAndAllQs(e,t),n&&(n.fields&&n.fields.length>0&&(yield`|f|`,yield*n.fields),typeof n.ttl==`number`&&(yield`|t|`),n.ifExists&&(yield`|e|`),n.when&&(yield*Cache._yieldKeyAndOperators(Object.keys(n.when),n.when)))}static*getRemoveKey(e,t,n){yield*Cache._yieldKeyAndOperators(e,t),n&&(n.fields&&n.fields.length>0&&(yield`|f|`,yield*n.fields),n.ifExists&&(yield`|e|`),n.deleteOnlyColumns&&(yield`|dc|`),n.when&&(yield*Cache._yieldKeyAndOperators(Object.keys(n.when),n.when)))}static*_yieldKeyAndOperators(e,t){for(let n=0;n<e.length;n++){let r=e[n];yield r,yield*Cache._yieldOperators(t[r])}}static*_yieldOperators(e){e!=null&&e instanceof t&&(yield e.key,e.hasChildValues&&(yield*Cache._yieldOperators(e.value[0]),yield`|/|`,yield*Cache._yieldOperators(e.value[1])))}static*_yieldKeyAndAllQs(n,r){for(let i=0;i<n.length;i++){let a=n[i];yield a;let o=r[a];o!=null&&(o instanceof t?yield*Cache._yieldOperators(o):o instanceof e&&(yield o.sign,yield o.inverted))}}};export{n as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import e from"../errors.js";import t from"../utils.js";var DocInfoAdapter=class{static getPropertiesInfo(e,t,n,r){let i=e;return t&&t.fields&&t.fields.length>0&&(i=t.fields),i.map(e=>({propertyName:e,columnName:r.getColumnName(e),value:n[e],fromModel:r.getFromModelFn(e)}))}static adaptOrderBy(n,r){return!n||!n.orderBy?t.emptyArray:Object.keys(n.orderBy).map(t=>{let i=n.orderBy[t],a=typeof i==`string`?i.toUpperCase():i;if(a!==`ASC`&&a!==`DESC`)throw new e.ArgumentError(`Order must be either "ASC" or "DESC", obtained: `+i);return[r.getColumnName(t),a]})}static adaptOptions(e,t){let n={prepare:!0,executionProfile:void 0,timestamp:void 0,isIdempotent:t};return typeof e==`string`?n.executionProfile=e:e!=null&&(n.executionProfile=e.executionProfile,n.timestamp=e.timestamp,e.isIdempotent!==void 0&&(n.isIdempotent=e.isIdempotent)),n}static adaptAllOptions(e,t){let n={prepare:!0,executionProfile:void 0,fetchSize:void 0,pageState:void 0,timestamp:void 0,isIdempotent:void 0};return typeof e==`string`?n.executionProfile=e:e!=null&&(n.executionProfile=e.executionProfile,n.fetchSize=e.fetchSize,n.pageState=e.pageState,n.timestamp=e.timestamp,n.isIdempotent=e.isIdempotent),t&&(n.isIdempotent=!0),n}static adaptBatchOptions(e,t,n){let r={prepare:!0,executionProfile:void 0,timestamp:void 0,logged:void 0,isIdempotent:t,counter:n};return typeof e==`string`?r.executionProfile=e:e!=null&&(r.executionProfile=e.executionProfile,r.timestamp=e.timestamp,r.logged=e.logged!==!1,e.isIdempotent!==void 0&&(r.isIdempotent=e.isIdempotent)),r}};export{DocInfoAdapter as default};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { types } from "../types/index.js";
|
|
2
|
-
import { Client } from "
|
|
2
|
+
import { Client } from "../index.js";
|
|
3
3
|
|
|
4
|
-
//#region src/driver/
|
|
4
|
+
//#region src/driver/mapping/index.d.ts
|
|
5
5
|
declare namespace mapping {
|
|
6
6
|
interface TableMappings {
|
|
7
7
|
getColumnName(propName: string): string;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import e from"../errors.js";import{ModelBatchItem as t}from"./model-batch-item.js";import n from"./model-mapper.js";import r from"./result-mapper.js";import i from"./result.js";import a from"./doc-info-adapter.js";import o from"./mapping-handler.js";import s from"./model-mapping-info.js";var Mapper=class{constructor(e,t){if(!e)throw Error(`client must be defined`);this.client=e,this._modelMappingInfos=s.parse(t,e.keyspace),this._modelMappers=new Map}forModel(e){let t=this._modelMappers.get(e);if(t===void 0){let r=this._modelMappingInfos.get(e);if(r===void 0){if(!this.client.keyspace)throw Error(`No mapping information found for model '${e}'. Mapper is unable to create default mappings without setting the keyspace`);r=s.createDefault(e,this.client.keyspace),this.client.log(`info`,`Mapping information for model '${e}' not found, creating default mapping. Keyspace: ${r.keyspace}; Table: ${r.tables[0].name}.`)}else this.client.log(`info`,`Creating model mapper for '${e}' using mapping information. Keyspace: ${r.keyspace}; Table${r.tables.length>1?`s`:``}: ${r.tables.map(e=>e.name)}.`);t=new n(e,new o(this.client,r)),this._modelMappers.set(e,t)}return t}batch(n,o){if(!Array.isArray(n)||!(n.length>0))return Promise.reject(new e.ArgumentError(`First parameter items should be an Array with 1 or more ModelBatchItem instances`));let s=[],c=!0,l;return Promise.all(n.map(e=>e instanceof t?e.pushQueries(s).then(e=>{c&&=e.isIdempotent,l=e.isCounter}):Promise.reject(Error(`Batch items must be instances of ModelBatchItem, use modelMapper.batching object to create each item`)))).then(()=>this.client.batch(s,a.adaptBatchOptions(o,c,l))).then(e=>new i(e,n[0].getMappingInfo(),r.getMutationAdapter(e)))}};export{Mapper as default};
|