@ragestudio/scylla-odm 0.22.0 → 0.22.2
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 +19 -21
- package/batch/index.d.ts.map +1 -0
- package/batch/index.js +37 -1
- package/batch/index.js.map +1 -0
- package/client.d.ts +24 -27
- package/client.d.ts.map +1 -0
- package/client.js +190 -1
- package/client.js.map +1 -0
- package/cql_gen/create_keyspace.d.ts +8 -9
- package/cql_gen/create_keyspace.d.ts.map +1 -0
- package/cql_gen/create_keyspace.js +14 -1
- package/cql_gen/create_keyspace.js.map +1 -0
- package/cql_gen/create_table.d.ts +3 -6
- package/cql_gen/create_table.d.ts.map +1 -0
- package/cql_gen/create_table.js +51 -1
- package/cql_gen/create_table.js.map +1 -0
- package/document/index.d.ts +11 -14
- package/document/index.d.ts.map +1 -0
- package/document/index.js +76 -1
- package/document/index.js.map +1 -0
- package/global.d.ts +6 -0
- package/global.d.ts.map +1 -0
- package/global.js +2 -0
- package/global.js.map +1 -0
- package/index.d.ts +9 -7
- package/index.d.ts.map +1 -0
- package/index.js +9 -1
- package/index.js.map +1 -0
- package/logger/index.d.ts +7 -8
- package/logger/index.d.ts.map +1 -0
- package/logger/index.js +14 -1
- package/logger/index.js.map +1 -0
- package/migrate/index.d.ts +12 -14
- package/migrate/index.d.ts.map +1 -0
- package/migrate/index.js +254 -4
- package/migrate/index.js.map +1 -0
- package/model/index.d.ts +64 -67
- package/model/index.d.ts.map +1 -0
- package/model/index.js +71 -1
- package/model/index.js.map +1 -0
- package/operations/countAll.d.ts +3 -6
- package/operations/countAll.d.ts.map +1 -0
- package/operations/countAll.js +13 -1
- package/operations/countAll.js.map +1 -0
- package/operations/delete.d.ts +5 -8
- package/operations/delete.d.ts.map +1 -0
- package/operations/delete.js +23 -1
- package/operations/delete.js.map +1 -0
- package/operations/find.d.ts +4 -7
- package/operations/find.d.ts.map +1 -0
- package/operations/find.js +19 -1
- package/operations/find.js.map +1 -0
- package/operations/findOne.d.ts +4 -7
- package/operations/findOne.d.ts.map +1 -0
- package/operations/findOne.js +21 -1
- package/operations/findOne.js.map +1 -0
- package/operations/insert.d.ts +5 -8
- package/operations/insert.d.ts.map +1 -0
- package/operations/insert.js +24 -1
- package/operations/insert.js.map +1 -0
- package/operations/sync.d.ts +3 -6
- package/operations/sync.d.ts.map +1 -0
- package/operations/sync.js +16 -1
- package/operations/sync.js.map +1 -0
- package/operations/tableExists.d.ts +3 -6
- package/operations/tableExists.d.ts.map +1 -0
- package/operations/tableExists.js +15 -2
- package/operations/tableExists.js.map +1 -0
- package/operations/update.d.ts +5 -8
- package/operations/update.d.ts.map +1 -0
- package/operations/update.js +35 -1
- package/operations/update.js.map +1 -0
- package/package.json +13 -3
- package/schema/index.d.ts +13 -15
- package/schema/index.d.ts.map +1 -0
- package/schema/index.js +23 -1
- package/schema/index.js.map +1 -0
- package/types.d.ts +98 -84
- package/types.d.ts.map +1 -0
- package/types.js +33 -1
- package/types.js.map +1 -0
- package/utils/buildMapper.d.ts +12 -4
- package/utils/buildMapper.d.ts.map +1 -0
- package/utils/buildMapper.js +11 -1
- package/utils/buildMapper.js.map +1 -0
- package/utils/delay.d.ts +3 -4
- package/utils/delay.d.ts.map +1 -0
- package/utils/delay.js +5 -1
- package/utils/delay.js.map +1 -0
- package/utils/fillDefaults.d.ts +2 -4
- package/utils/fillDefaults.d.ts.map +1 -0
- package/utils/fillDefaults.js +24 -1
- package/utils/fillDefaults.js.map +1 -0
- package/utils/isPlainObject.d.ts +3 -4
- package/utils/isPlainObject.d.ts.map +1 -0
- package/utils/isPlainObject.js +11 -1
- package/utils/isPlainObject.js.map +1 -0
- package/utils/loadModels.d.ts +3 -4
- package/utils/loadModels.d.ts.map +1 -0
- package/utils/loadModels.js +29 -1
- package/utils/loadModels.js.map +1 -0
- package/utils/queryParser.d.ts +5 -8
- package/utils/queryParser.d.ts.map +1 -0
- package/utils/queryParser.js +102 -1
- package/utils/queryParser.js.map +1 -0
- package/utils/typeChecker.d.ts +3 -6
- package/utils/typeChecker.d.ts.map +1 -0
- package/utils/typeChecker.js +90 -1
- package/utils/typeChecker.js.map +1 -0
- package/driver/auth/index.d.ts +0 -34
- package/driver/auth/index.js +0 -1
- package/driver/auth/no-auth-provider.js +0 -1
- package/driver/auth/plain-text-auth-provider.js +0 -1
- package/driver/auth/provider.js +0 -1
- package/driver/client-options.js +0 -1
- package/driver/client.js +0 -1
- package/driver/concurrent/index.d.ts +0 -1
- package/driver/concurrent/index.js +0 -1
- package/driver/connection.js +0 -1
- package/driver/control-connection.js +0 -1
- package/driver/encoder.js +0 -1
- package/driver/errors.js +0 -1
- package/driver/execution-options.js +0 -1
- package/driver/execution-profile.js +0 -1
- package/driver/host-connection-pool.js +0 -1
- package/driver/host.js +0 -1
- package/driver/index.d.ts +0 -212
- package/driver/index.js +0 -1
- package/driver/mapping/cache.js +0 -1
- package/driver/mapping/doc-info-adapter.js +0 -1
- package/driver/mapping/index.d.ts +0 -142
- package/driver/mapping/index.js +0 -1
- package/driver/mapping/mapper.js +0 -1
- package/driver/mapping/mapping-handler.js +0 -1
- package/driver/mapping/model-batch-item.js +0 -1
- package/driver/mapping/model-batch-mapper.js +0 -1
- package/driver/mapping/model-mapper.js +0 -1
- package/driver/mapping/model-mapping-info.js +0 -1
- package/driver/mapping/object-selector.js +0 -1
- package/driver/mapping/q.js +0 -1
- package/driver/mapping/query-generator.js +0 -9
- package/driver/mapping/result-mapper.js +0 -4
- package/driver/mapping/result.js +0 -1
- package/driver/mapping/table-mappings.js +0 -1
- package/driver/mapping/tree.js +0 -1
- package/driver/metadata/aggregate.js +0 -1
- package/driver/metadata/client-state.js +0 -1
- package/driver/metadata/data-collection.js +0 -1
- package/driver/metadata/event-debouncer.js +0 -1
- package/driver/metadata/index.d.ts +0 -184
- package/driver/metadata/index.js +0 -1
- package/driver/metadata/materialized-view.js +0 -1
- package/driver/metadata/schema-function.js +0 -1
- package/driver/metadata/schema-index.js +0 -1
- package/driver/metadata/schema-parser.js +0 -1
- package/driver/metadata/table-metadata.js +0 -1
- package/driver/operation-state.js +0 -1
- package/driver/policies/address-resolution.js +0 -1
- package/driver/policies/index.d.ts +0 -135
- package/driver/policies/index.js +0 -1
- package/driver/policies/load-balancing.js +0 -1
- package/driver/policies/reconnection.js +0 -1
- package/driver/policies/retry.js +0 -1
- package/driver/policies/speculative-execution.js +0 -1
- package/driver/policies/timestamp-generation.js +0 -1
- package/driver/prepare-handler.js +0 -1
- package/driver/promise-utils.js +0 -1
- package/driver/readers.js +0 -1
- package/driver/request-execution.js +0 -1
- package/driver/request-handler.js +0 -1
- package/driver/requests.js +0 -1
- package/driver/stream-id-stack.js +0 -1
- package/driver/streams.js +0 -1
- package/driver/token.js +0 -1
- package/driver/tokenizer.js +0 -1
- package/driver/types/big-decimal.js +0 -1
- package/driver/types/duration.js +0 -1
- package/driver/types/index.d.ts +0 -320
- package/driver/types/index.js +0 -1
- package/driver/types/inet-address.js +0 -1
- package/driver/types/integer.js +0 -1
- package/driver/types/local-date.js +0 -1
- package/driver/types/local-time.js +0 -1
- package/driver/types/mutable-long.js +0 -1
- package/driver/types/protocol-version.js +0 -1
- package/driver/types/result-set.js +0 -1
- package/driver/types/result-stream.js +0 -1
- package/driver/types/row.js +0 -1
- package/driver/types/time-uuid.js +0 -1
- package/driver/types/tuple.js +0 -1
- package/driver/types/uuid.js +0 -1
- package/driver/types/vector.js +0 -1
- package/driver/types/version-number.js +0 -1
- package/driver/utils.js +0 -4
- package/driver/writers.js +0 -1
- package/package.js +0 -1
|
@@ -1,135 +0,0 @@
|
|
|
1
|
-
import { types } from "../types/index.js";
|
|
2
|
-
import { Client, EmptyCallback, ExecutionOptions, Host, HostMap } from "../index.js";
|
|
3
|
-
|
|
4
|
-
//#region src/driver/policies/index.d.ts
|
|
5
|
-
declare namespace policies {
|
|
6
|
-
function defaultAddressTranslator(): addressResolution.AddressTranslator;
|
|
7
|
-
function defaultLoadBalancingPolicy(localDc?: string): loadBalancing.LoadBalancingPolicy;
|
|
8
|
-
function defaultReconnectionPolicy(): reconnection.ReconnectionPolicy;
|
|
9
|
-
function defaultRetryPolicy(): retry.RetryPolicy;
|
|
10
|
-
function defaultSpeculativeExecutionPolicy(): speculativeExecution.SpeculativeExecutionPolicy;
|
|
11
|
-
function defaultTimestampGenerator(): timestampGeneration.TimestampGenerator;
|
|
12
|
-
namespace addressResolution {
|
|
13
|
-
interface AddressTranslator {
|
|
14
|
-
translate(address: string, port: number, callback: Function): void;
|
|
15
|
-
}
|
|
16
|
-
class EC2MultiRegionTranslator implements AddressTranslator {
|
|
17
|
-
translate(address: string, port: number, callback: Function): void;
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
namespace loadBalancing {
|
|
21
|
-
abstract class LoadBalancingPolicy {
|
|
22
|
-
init(client: Client, hosts: HostMap, callback: EmptyCallback): void;
|
|
23
|
-
getDistance(host: Host): types.distance;
|
|
24
|
-
newQueryPlan(keyspace: string, executionOptions: ExecutionOptions, callback: (error: Error, iterator: Iterator<Host>) => void): void;
|
|
25
|
-
getOptions(): Map<string, object>;
|
|
26
|
-
}
|
|
27
|
-
class DCAwareRoundRobinPolicy extends LoadBalancingPolicy {
|
|
28
|
-
constructor(localDc: string);
|
|
29
|
-
}
|
|
30
|
-
class TokenAwarePolicy extends LoadBalancingPolicy {
|
|
31
|
-
constructor(childPolicy: LoadBalancingPolicy);
|
|
32
|
-
}
|
|
33
|
-
class AllowListPolicy extends LoadBalancingPolicy {
|
|
34
|
-
constructor(childPolicy: LoadBalancingPolicy, allowList: string[]);
|
|
35
|
-
}
|
|
36
|
-
class WhiteListPolicy extends AllowListPolicy {}
|
|
37
|
-
class RoundRobinPolicy extends LoadBalancingPolicy {
|
|
38
|
-
constructor();
|
|
39
|
-
}
|
|
40
|
-
class DefaultLoadBalancingPolicy extends LoadBalancingPolicy {
|
|
41
|
-
constructor(options?: {
|
|
42
|
-
localDc?: string;
|
|
43
|
-
filter?: (host: Host) => boolean;
|
|
44
|
-
});
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
namespace reconnection {
|
|
48
|
-
class ConstantReconnectionPolicy implements ReconnectionPolicy {
|
|
49
|
-
constructor(delay: number);
|
|
50
|
-
getOptions(): Map<string, object>;
|
|
51
|
-
newSchedule(): Iterator<number>;
|
|
52
|
-
}
|
|
53
|
-
class ExponentialReconnectionPolicy implements ReconnectionPolicy {
|
|
54
|
-
constructor(baseDelay: number, maxDelay: number, startWithNoDelay?: boolean);
|
|
55
|
-
getOptions(): Map<string, object>;
|
|
56
|
-
newSchedule(): Iterator<number>;
|
|
57
|
-
}
|
|
58
|
-
interface ReconnectionPolicy {
|
|
59
|
-
getOptions(): Map<string, object>;
|
|
60
|
-
newSchedule(): Iterator<number>;
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
namespace retry {
|
|
64
|
-
class DecisionInfo {
|
|
65
|
-
decision: number;
|
|
66
|
-
consistency: types.consistencies;
|
|
67
|
-
}
|
|
68
|
-
class OperationInfo {
|
|
69
|
-
query: string;
|
|
70
|
-
executionOptions: ExecutionOptions;
|
|
71
|
-
nbRetry: number;
|
|
72
|
-
}
|
|
73
|
-
class IdempotenceAwareRetryPolicy extends RetryPolicy {
|
|
74
|
-
constructor(childPolicy: RetryPolicy);
|
|
75
|
-
}
|
|
76
|
-
class FallthroughRetryPolicy extends RetryPolicy {
|
|
77
|
-
constructor();
|
|
78
|
-
}
|
|
79
|
-
class RetryPolicy {
|
|
80
|
-
onReadTimeout(info: OperationInfo, consistency: types.consistencies, received: number, blockFor: number, isDataPresent: boolean): DecisionInfo;
|
|
81
|
-
onRequestError(info: OperationInfo, consistency: types.consistencies, err: Error): DecisionInfo;
|
|
82
|
-
onUnavailable(info: OperationInfo, consistency: types.consistencies, required: number, alive: boolean): DecisionInfo;
|
|
83
|
-
onWriteTimeout(info: OperationInfo, consistency: types.consistencies, received: number, blockFor: number, writeType: string): DecisionInfo;
|
|
84
|
-
rethrowResult(): DecisionInfo;
|
|
85
|
-
retryResult(consistency: types.consistencies, useCurrentHost?: boolean): DecisionInfo;
|
|
86
|
-
}
|
|
87
|
-
namespace RetryDecision {
|
|
88
|
-
enum retryDecision {
|
|
89
|
-
ignore,
|
|
90
|
-
rethrow,
|
|
91
|
-
retry
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
namespace speculativeExecution {
|
|
96
|
-
class ConstantSpeculativeExecutionPolicy implements SpeculativeExecutionPolicy {
|
|
97
|
-
constructor(delay: number, maxSpeculativeExecutions: number);
|
|
98
|
-
getOptions(): Map<string, object>;
|
|
99
|
-
init(client: Client): void;
|
|
100
|
-
newPlan(keyspace: string, queryInfo: string | Array<object>): {
|
|
101
|
-
nextExecution: Function;
|
|
102
|
-
};
|
|
103
|
-
shutdown(): void;
|
|
104
|
-
}
|
|
105
|
-
class NoSpeculativeExecutionPolicy implements SpeculativeExecutionPolicy {
|
|
106
|
-
constructor();
|
|
107
|
-
getOptions(): Map<string, object>;
|
|
108
|
-
init(client: Client): void;
|
|
109
|
-
newPlan(keyspace: string, queryInfo: string | Array<object>): {
|
|
110
|
-
nextExecution: Function;
|
|
111
|
-
};
|
|
112
|
-
shutdown(): void;
|
|
113
|
-
}
|
|
114
|
-
interface SpeculativeExecutionPolicy {
|
|
115
|
-
getOptions(): Map<string, object>;
|
|
116
|
-
init(client: Client): void;
|
|
117
|
-
newPlan(keyspace: string, queryInfo: string | Array<object>): {
|
|
118
|
-
nextExecution: Function;
|
|
119
|
-
};
|
|
120
|
-
shutdown(): void;
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
namespace timestampGeneration {
|
|
124
|
-
class MonotonicTimestampGenerator implements TimestampGenerator {
|
|
125
|
-
constructor(warningThreshold: number, minLogInterval: number);
|
|
126
|
-
getDate(): number;
|
|
127
|
-
next(client: Client): types.Long | number;
|
|
128
|
-
}
|
|
129
|
-
interface TimestampGenerator {
|
|
130
|
-
next(client: Client): types.Long | number;
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
//#endregion
|
|
135
|
-
export { policies };
|
package/driver/policies/index.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import e from"./address-resolution.js";import t from"./load-balancing.js";import n from"./reconnection.js";import r from"./retry.js";import i from"./speculative-execution.js";import a from"./timestamp-generation.js";var o={addressResolution:e,loadBalancing:t,reconnection:n,retry:r,speculativeExecution:i,timestampGeneration:a,defaultAddressTranslator,defaultLoadBalancingPolicy,defaultRetryPolicy,defaultReconnectionPolicy,defaultSpeculativeExecutionPolicy,defaultTimestampGenerator};function defaultAddressTranslator(){return new e.AddressTranslator}function defaultLoadBalancingPolicy(e){return new t.DefaultLoadBalancingPolicy(e)}function defaultRetryPolicy(){return new r.RetryPolicy}function defaultReconnectionPolicy(){return new n.ExponentialReconnectionPolicy(1e3,600*1e3,!1)}function defaultSpeculativeExecutionPolicy(){return new i.NoSpeculativeExecutionPolicy}function defaultTimestampGenerator(){return new a.MonotonicTimestampGenerator}export{o as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import e from"../errors.js";import t from"../utils.js";import n from"../types/index.js";import r from"util";const i=Object.freeze({done:!0});function LoadBalancingPolicy(){}LoadBalancingPolicy.prototype.init=function(e,t,n){this.client=e,this.hosts=t,n()},LoadBalancingPolicy.prototype.getDistance=function(e){return n.distance.local},LoadBalancingPolicy.prototype.newQueryPlan=function(e,t,n){n(Error(`You must implement a query plan for the LoadBalancingPolicy class`))},LoadBalancingPolicy.prototype.getOptions=function(){return new Map};function RoundRobinPolicy(){this.index=0}r.inherits(RoundRobinPolicy,LoadBalancingPolicy),RoundRobinPolicy.prototype.newQueryPlan=function(e,n,r){if(!this.hosts)return r(Error(`Load balancing policy not initialized`));let a=this.hosts.values(),o=this,s=0,c=o.index%a.length;o.index+=1,o.index>=t.maxInt&&(o.index=0),r(null,{next:function(){return++s>a.length?i:{value:a[c++%a.length],done:!1}}})};function DCAwareRoundRobinPolicy(e){this.localDc=e,this.index=0,this.localHostsArray=null}r.inherits(DCAwareRoundRobinPolicy,LoadBalancingPolicy),DCAwareRoundRobinPolicy.prototype.init=function(e,t,n){this.client=e,this.hosts=t,t.on(`add`,this._cleanHostCache.bind(this)),t.on(`remove`,this._cleanHostCache.bind(this));try{setLocalDc(this,e,this.hosts)}catch(e){return n(e)}n()},DCAwareRoundRobinPolicy.prototype.getDistance=function(e){return e.datacenter===this.localDc?n.distance.local:n.distance.ignored},DCAwareRoundRobinPolicy.prototype._cleanHostCache=function(){this.localHostsArray=null},DCAwareRoundRobinPolicy.prototype._resolveLocalHosts=function(){let e=this.hosts.values();this.localHostsArray||(this.localHostsArray=[],e.forEach(function(e){e.datacenter&&e.datacenter===this.localDc&&this.localHostsArray.push(e)},this))},DCAwareRoundRobinPolicy.prototype.newQueryPlan=function(e,n,r){if(!this.hosts)return r(Error(`Load balancing policy not initialized`));this.index+=1,this.index>=t.maxInt&&(this.index=0),this._resolveLocalHosts();let a=this.localHostsArray,o=this.index,s=0;r(null,{next:function(){let e;return s++<a.length?(e=a[o++%a.length],{value:e,done:!1}):i}})},DCAwareRoundRobinPolicy.prototype.getOptions=function(){return new Map([[`localDataCenter`,this.localDc]])};function TokenAwarePolicy(e){if(!e)throw Error(`You must specify a child load balancing policy`);this.childPolicy=e}r.inherits(TokenAwarePolicy,LoadBalancingPolicy),TokenAwarePolicy.prototype.init=function(e,t,n){this.client=e,this.hosts=t,this.childPolicy.init(e,t,n)},TokenAwarePolicy.prototype.getDistance=function(e){return this.childPolicy.getDistance(e)},TokenAwarePolicy.prototype.newQueryPlan=function(e,t,n){let r;t&&(r=t.getRoutingKey(),t.getKeyspace()&&(e=t.getKeyspace()));let i;if(r&&(i=this.client.getReplicas(e,r)),!r||!i)return this.childPolicy.newQueryPlan(e,t,n);new TokenAwareIterator(e,t,i,this.childPolicy).iterate(n)};function TokenAwareIterator(e,t,r,i){this.keyspace=e,this.childPolicy=i,this.options=t,this.localReplicas=[],this.replicaIndex=0,this.replicaMap={},this.childIterator=null;for(let e=0;e<r.length;e++){let t=r[e];this.childPolicy.getDistance(t)===n.distance.local&&(this.replicaMap[t.address]=!0,this.localReplicas.push(t))}this.startIndex=Math.floor(Math.random()*this.localReplicas.length)}TokenAwareIterator.prototype.iterate=function(e){let t=this;this.childPolicy.newQueryPlan(this.keyspace,this.options,function(n,r){if(n)return e(n);t.childIterator=r,e(null,{next:function(){return t.computeNext()}})})},TokenAwareIterator.prototype.computeNext=function(){let e;if(this.replicaIndex<this.localReplicas.length)return e=this.localReplicas[(this.startIndex+ this.replicaIndex++)%this.localReplicas.length],{value:e,done:!1};let t;for(;(t=this.childIterator.next())&&!t.done;)if(!this.replicaMap[t.value.address])return t;return i},TokenAwarePolicy.prototype.getOptions=function(){let e=new Map([[`childPolicy`,this.childPolicy.constructor===void 0?null:this.childPolicy.constructor.name]]);return this.childPolicy instanceof DCAwareRoundRobinPolicy&&e.set(`localDataCenter`,this.childPolicy.localDc),e};function AllowListPolicy(e,t){if(!e)throw Error(`You must specify a child load balancing policy`);if(!Array.isArray(t))throw Error(`You must provide the list of allowed host addresses`);this.childPolicy=e,this.allowList=new Map(t.map(e=>[e,!0]))}r.inherits(AllowListPolicy,LoadBalancingPolicy),AllowListPolicy.prototype.init=function(e,t,n){this.childPolicy.init(e,t,n)},AllowListPolicy.prototype.getDistance=function(e){return this._contains(e)?this.childPolicy.getDistance(e):n.distance.ignored},AllowListPolicy.prototype._contains=function(e){return!!this.allowList.get(e.address)},AllowListPolicy.prototype.newQueryPlan=function(e,t,n){let r=this;this.childPolicy.newQueryPlan(e,t,function(e,t){if(e)return n(e);n(null,r._filter(t))})},AllowListPolicy.prototype._filter=function(e){let t=this;return{next:function(){let n=e.next();return!n.done&&!t._contains(n.value)?this.next():n}}},AllowListPolicy.prototype.getOptions=function(){return new Map([[`childPolicy`,this.childPolicy.constructor===void 0?null:this.childPolicy.constructor.name],[`allowList`,Array.from(this.allowList.keys())]])};function WhiteListPolicy(e,t){AllowListPolicy.call(this,e,t)}r.inherits(WhiteListPolicy,AllowListPolicy);var a=class DefaultLoadBalancingPolicy extends LoadBalancingPolicy{constructor(e){super(),typeof e==`string`?e={localDc:e}:e||=t.emptyObject,this._client=null,this._hosts=null,this._filteredHosts=null,this._preferredHost=null,this._index=0,this.localDc=e.localDc,this._filter=e.filter||this._defaultFilter,e.isHostNewlyUp&&(this._isHostNewlyUp=e.isHostNewlyUp),e.healthCheck&&(this._healthCheck=e.healthCheck),e.compare&&(this._compare=e.compare),e.getReplicas&&(this._getReplicas=e.getReplicas)}init(e,t,n){this._client=e,this._hosts=t,this._hosts.on(`add`,()=>this._filteredHosts=null),this._hosts.on(`remove`,()=>this._filteredHosts=null);try{setLocalDc(this,e,this._hosts)}catch(e){return n(e)}n()}getDistance(e){return this._preferredHost!==null&&e===this._preferredHost||this._filter(e)&&e.datacenter===this.localDc?n.distance.local:n.distance.ignored}newQueryPlan(e,t,n){let r,i;t&&(r=t.getRoutingKey(),t.getKeyspace()&&(e=t.getKeyspace()),i=t.getPreferredHost());let a;return a=!e||!r?this._getLocalHosts():this._getReplicasAndLocalHosts(e,r),i&&(this._preferredHost=i,a=DefaultLoadBalancingPolicy._getPreferredHostFirst(i,a)),n(null,a)}static*_getPreferredHostFirst(e,t){yield e;for(let n of t)n!==e&&(yield n)}*_getLocalHosts(e){let t=this._getFilteredLocalHosts(),n=this._getIndex(),r=e?t=>e.indexOf(t)===-1:e=>!0;for(let e=0;e<t.length;e++){let i=t[(e+n)%t.length];r(i)&&i.isUp()&&(yield i)}}_getReplicasAndLocalHosts(e,n){let r=this._getReplicas(e,n);if(r===null)return this._getLocalHosts();let i=[],a=null,o=-(2**53-1),s=0;for(let e=0;e<r.length;e++){let t=r[e];if(!this._filter(t)||t.datacenter!==this.localDc||!t.isUp())continue;let n=this._isHostNewlyUp(t);n!==null&&n>o&&(a=t,o=n),a===null&&!this._healthCheck(t)&&s++,i.push(t)}if(r=i,t.shuffleArray(r),r.length<3)return this.yieldReplicasFirst(r);let c;if(a===null)s>0&&s<Math.floor(r.length/2+1)&&this._sendUnhealthyToTheBack(r,s);else if((a===r[0]||a===r[1])&&Math.random()*4>=1){let e=a===r[0]?0:1;c=r[r.length-1],r[r.length-1]=r[e],r[e]=c}return this._compare(r[1],r[0])>0&&(c=r[0],r[0]=r[1],r[1]=c),this.yieldReplicasFirst(r)}*yieldReplicasFirst(e){for(let t=0;t<e.length;t++)yield e[t];yield*this._getLocalHosts(e)}_isHostNewlyUp(e){return e.isUpSince!==null&&Date.now()-e.isUpSince<6e4?e.isUpSince:null}_healthCheck(e){return!(e.getInFlight()>=10&&e.getResponseCount()<=1)}_compare(e,t){return e.getInFlight()<t.getInFlight()?1:-1}_getReplicas(e,t){return this._client.getReplicas(e,t)}_getFilteredLocalHosts(){return this._filteredHosts===null&&(this._filteredHosts=this._hosts.values().filter(e=>this._filter(e)&&e.datacenter===this.localDc)),this._filteredHosts}_getIndex(){let e=this._index++;return this._index===2147483647&&(this._index=0),e}_sendUnhealthyToTheBack(e,t){let n=0;for(let r=e.length-1;r>=0&&n<t;r--){let t=e[r];if(this._healthCheck(t))continue;let i=e.length-1-n;if(i!==r){let n=e[i];e[i]=t,e[r]=n}n++}}_defaultFilter(){return!0}getOptions(){return new Map([[`localDataCenter`,this.localDc],[`filterFunction`,this._filter!==this._defaultFilter]])}};function setLocalDc(t,n,r){if(!(t instanceof LoadBalancingPolicy))throw new e.DriverInternalError(`LoadBalancingPolicy instance was not provided`);n&&n.options&&(t.localDc&&!n.options.localDataCenter&&n.log(`info`,`Local data center '${t.localDc}' was provided as an argument to the load-balancing policy. It is preferable to specify the local data center using 'localDataCenter' in Client options instead when your application is targeting a single data center.`),t.localDc=t.localDc||n.options.localDataCenter);let i=getDataCenters(r);if(!t.localDc)throw new e.ArgumentError(`'localDataCenter' is not defined in Client options and also was not specified in constructor. At least one is required. Available DCs are: [${Array.from(i)}]`);if(!i.has(t.localDc))throw new e.ArgumentError(`Datacenter ${t.localDc} was not found. Available DCs are: [${Array.from(i)}]`)}function getDataCenters(e){return new Set(e.values().map(e=>e.datacenter))}var o={AllowListPolicy,DCAwareRoundRobinPolicy,DefaultLoadBalancingPolicy:a,LoadBalancingPolicy,RoundRobinPolicy,TokenAwarePolicy,WhiteListPolicy};export{o as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import e from"util";function ReconnectionPolicy(){}ReconnectionPolicy.prototype.newSchedule=function(){throw Error(`You must implement a new schedule for the Reconnection class`)},ReconnectionPolicy.prototype.getOptions=function(){return new Map};function ConstantReconnectionPolicy(e){this.delay=e}e.inherits(ConstantReconnectionPolicy,ReconnectionPolicy),ConstantReconnectionPolicy.prototype.newSchedule=function(){let e=this;return{next:function(){return{value:e.delay,done:!1}}}},ConstantReconnectionPolicy.prototype.getOptions=function(){return new Map([[`delay`,this.delay]])};function ExponentialReconnectionPolicy(e,t,n){this.baseDelay=e,this.maxDelay=t,this.startWithNoDelay=n}e.inherits(ExponentialReconnectionPolicy,ReconnectionPolicy),ExponentialReconnectionPolicy.prototype.newSchedule=function*(){let e=this.startWithNoDelay?-1:0;for(;;){let t=0;e>=64?t=this.maxDelay:e!==-1&&(t=Math.min(2**e*this.baseDelay,this.maxDelay)),e++,yield this._addJitter(t)}},ExponentialReconnectionPolicy.prototype._addJitter=function(e){if(e===0)return e;let t=.85,n=.3;return!this.startWithNoDelay&&e===this.baseDelay?(t=1,n=.15):e===this.maxDelay&&(n=.15),Math.floor(e*(Math.random()*n+t))},ExponentialReconnectionPolicy.prototype.getOptions=function(){return new Map([[`baseDelay`,this.baseDelay],[`maxDelay`,this.maxDelay],[`startWithNoDelay`,this.startWithNoDelay]])};var t={ReconnectionPolicy,ConstantReconnectionPolicy,ExponentialReconnectionPolicy};export{t as default};
|
package/driver/policies/retry.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import e from"util";function RetryPolicy(){}RetryPolicy.prototype.onUnavailable=function(e,t,n,r){return e.nbRetry>0?this.rethrowResult():this.retryResult(void 0,!1)},RetryPolicy.prototype.onReadTimeout=function(e,t,n,r,i){return e.nbRetry>0?this.rethrowResult():n>=r&&!i?this.retryResult():this.rethrowResult()},RetryPolicy.prototype.onWriteTimeout=function(e,t,n,r,i){return e.nbRetry>0?this.rethrowResult():i===`BATCH_LOG`?this.retryResult():this.rethrowResult()},RetryPolicy.prototype.onRequestError=function(e,t,n){return this.retryResult(void 0,!1)},RetryPolicy.prototype.retryResult=function(e,t){return{decision:RetryPolicy.retryDecision.retry,consistency:e,useCurrentHost:t!==!1}},RetryPolicy.prototype.rethrowResult=function(){return{decision:RetryPolicy.retryDecision.rethrow}},RetryPolicy.retryDecision={rethrow:0,retry:1,ignore:2};function IdempotenceAwareRetryPolicy(e){this._childPolicy=e||new RetryPolicy}e.inherits(IdempotenceAwareRetryPolicy,RetryPolicy),IdempotenceAwareRetryPolicy.prototype.onReadTimeout=function(e,t,n,r,i){return this._childPolicy.onReadTimeout(e,t,n,r,i)},IdempotenceAwareRetryPolicy.prototype.onRequestError=function(e,t,n){return e.executionOptions.isIdempotent()?this._childPolicy.onRequestError(e,t,n):this.rethrowResult()},IdempotenceAwareRetryPolicy.prototype.onUnavailable=function(e,t,n,r){return this._childPolicy.onUnavailable(e,t,n,r)},IdempotenceAwareRetryPolicy.prototype.onWriteTimeout=function(e,t,n,r,i){return e.executionOptions.isIdempotent()?this._childPolicy.onWriteTimeout(e,t,n,r,i):this.rethrowResult()};function FallthroughRetryPolicy(){}e.inherits(FallthroughRetryPolicy,RetryPolicy),FallthroughRetryPolicy.prototype.onReadTimeout=function(){return this.rethrowResult()},FallthroughRetryPolicy.prototype.onRequestError=function(){return this.rethrowResult()},FallthroughRetryPolicy.prototype.onUnavailable=function(){return this.rethrowResult()},FallthroughRetryPolicy.prototype.onWriteTimeout=function(){return this.rethrowResult()};var t={IdempotenceAwareRetryPolicy,FallthroughRetryPolicy,RetryPolicy};export{t as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import e from"../errors.js";import t from"util";function SpeculativeExecutionPolicy(){}SpeculativeExecutionPolicy.prototype.init=function(e){},SpeculativeExecutionPolicy.prototype.shutdown=function(){},SpeculativeExecutionPolicy.prototype.newPlan=function(e,t){throw Error(`You must implement newPlan() method in the SpeculativeExecutionPolicy`)},SpeculativeExecutionPolicy.prototype.getOptions=function(){return new Map};function NoSpeculativeExecutionPolicy(){this._plan={nextExecution:function(){return-1}}}t.inherits(NoSpeculativeExecutionPolicy,SpeculativeExecutionPolicy),NoSpeculativeExecutionPolicy.prototype.newPlan=function(){return this._plan};function ConstantSpeculativeExecutionPolicy(t,n){if(!(t>=0))throw new e.ArgumentError(`delay must be a positive number or zero`);if(!(n>0))throw new e.ArgumentError(`maxSpeculativeExecutions must be a positive number`);this._delay=t,this._maxSpeculativeExecutions=n}t.inherits(ConstantSpeculativeExecutionPolicy,SpeculativeExecutionPolicy),ConstantSpeculativeExecutionPolicy.prototype.newPlan=function(){let e=0,t=this;return{nextExecution:function(){return e++<t._maxSpeculativeExecutions?t._delay:-1}}},ConstantSpeculativeExecutionPolicy.prototype.getOptions=function(){return new Map([[`delay`,this._delay],[`maxSpeculativeExecutions`,this._maxSpeculativeExecutions]])};var n={NoSpeculativeExecutionPolicy,SpeculativeExecutionPolicy,ConstantSpeculativeExecutionPolicy};export{n as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import e from"../errors.js";import{Long as t}from"../types/index.js";import n from"util";const r=t.fromInt(1e3);function TimestampGenerator(){}TimestampGenerator.prototype.next=function(e){throw Error(`next() must be implemented`)};function MonotonicTimestampGenerator(t,n){if(t<0)throw new e.ArgumentError(`warningThreshold can not be lower than 0`);this._warningThreshold=t||1e3,this._minLogInterval=1e3,typeof n==`number`&&(this._minLogInterval=n),this._micros=-1,this._lastDate=0,this._lastLogDate=0}n.inherits(MonotonicTimestampGenerator,TimestampGenerator),MonotonicTimestampGenerator.prototype.getDate=function(){return Date.now()},MonotonicTimestampGenerator.prototype.next=function(e){let t=this.getDate(),r=0;if(t>this._lastDate)return this._micros=0,this._lastDate=t,this._generateMicroseconds();t<this._lastDate&&(r=this._lastDate-t,t=this._lastDate),++this._micros===1e3&&(this._micros=0,t===this._lastDate&&(t++,r++));let i=this._lastDate;this._lastDate=t;let a=this._generateMicroseconds();if(r>=this._warningThreshold){let t=Date.now();if(this._minLogInterval>0&&this._lastLogDate+this._minLogInterval<=t){let o=n.format(`Timestamp generated using current date was %d milliseconds behind the last generated timestamp (which millisecond portion was %d), the returned value (%s) is being artificially incremented to guarantee monotonicity.`,r,i,a);this._lastLogDate=t,e.log(`warning`,o)}}return a},MonotonicTimestampGenerator.prototype._generateMicroseconds=function(){return this._lastDate<9007199254740?this._lastDate*1e3+this._micros:t.fromNumber(this._lastDate).multiply(r).add(t.fromInt(this._micros))};var i={TimestampGenerator,MonotonicTimestampGenerator};export{i as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import e from"./errors.js";import t from"./promise-utils.js";import n from"./utils.js";import r from"./types/index.js";var i=class PrepareHandler{constructor(e,t){this._client=e,this._loadBalancing=t,this.logEmitter=e.options.logEmitter,this.log=n.log}static async getPrepared(e,n,r,i){let a=e.metadata.getPreparedInfo(i,r);return a.queryId?a:a.preparing?await t.fromEvent(a,`prepared`):await new PrepareHandler(e,n)._prepare(a,r,i)}static async getPreparedMultiple(t,r,i,a){let o=[];for(let s of i){let i;if(s&&(i=typeof s==`string`?s:s.query),typeof i!=`string`)throw new e.ArgumentError(`Query item should be a string`);let{queryId:c,meta:l}=await PrepareHandler.getPrepared(t,r,i,a);o.push({query:i,params:n.adaptNamedParamsPrepared(s.params,l.columns),queryId:c,meta:l})}return o}async _prepare(e,n,r){e.preparing=!0;let i;try{return i=await t.newQueryPlan(this._loadBalancing,r,null),await this._prepareWithQueryPlan(e,i,n,r)}catch(t){throw e.preparing=!1,t.query=n,e.emit(`prepared`,t),t}}async _prepareWithQueryPlan(t,n,r,i){let a={};for(;;){let o=PrepareHandler.getNextHost(n,this._client.profileManager,a);if(o===null)throw new e.NoHostAvailableError(a);try{let e=await(await PrepareHandler._borrowWithKeyspace(o,i)).prepareOnceAsync(r,i);return this._client.options.prepareOnAllHosts&&await this._prepareOnAllHosts(n,r,i),t.preparing=!1,t.queryId=e.id,t.meta=e.meta,this._client.metadata.setPreparedById(t),t.emit(`prepared`,null,t),t}catch(t){if(a[o.address]=t,!t.isSocketError&&!(t instanceof e.OperationTimedOutError))throw t}}}static getNextHost(e,t,n){let i;for(;;){let a=e.next();if(a.done)return null;if(i=a.value,t.getDistance(i)!==r.distance.ignored){if(i.isUp())break;n&&(n[i.address]=`Host considered as DOWN`)}}return i}static async prepareAllQueries(e,t){let n=[],r=new Map;t.forEach(e=>{let t;e.keyspace?(t=r.get(e.keyspace),t||(t=[],r.set(e.keyspace,t))):t=n,t.push(e.query)});for(let[t,n]of r)await PrepareHandler._borrowAndPrepare(e,t,n);await PrepareHandler._borrowAndPrepare(e,null,n)}static async _borrowAndPrepare(e,t,n){if(n.length===0)return;let r=await PrepareHandler._borrowWithKeyspace(e,t);for(let e of n)await r.prepareOnceAsync(e,t)}static async _borrowWithKeyspace(e,t){let n=e.borrowConnection();return t&&n.keyspace!==t&&await n.changeKeyspace(t),n}_prepareOnAllHosts(e,t,n){let r=[t],i,a=[];for(;(i=PrepareHandler.getNextHost(e,this._client.profileManager))!==null;)a.push(i);return Promise.all(a.map(e=>PrepareHandler._borrowAndPrepare(e,n,r).catch(n=>this.log(`verbose`,`Unexpected error while preparing query (${t}) on ${e.address}`,n))))}};export{i as default};
|
package/driver/promise-utils.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function delay(e){return new Promise(t=>setTimeout(t,e||0))}function fromEvent(e,t){return new Promise((n,r)=>e.once(t,(e,t)=>{e?r(e):n(t)}))}function fromCallback(e){return new Promise((t,n)=>e((e,r)=>{e?n(e):t(r)}))}function getCallback(e,t){return function(n,r){n?t(n):e(r)}}async function invokeSequentially(e,t,n){let r;for(;(r=e.counter++)<t;)await n(r)}function newQueryPlan(e,t,n){return new Promise((r,i)=>{e.newQueryPlan(t,n,(e,t)=>{e?i(e):r(t)})})}function optionalCallback(e,t){if(!t)return e;toCallback(e,t)}function times(e,t,n){t>e&&(t=e);let r=Array(t),i={counter:0};for(let a=0;a<t;a++)r[a]=invokeSequentially(i,e,n);return Promise.all(r)}function toBackground(e){e.catch(()=>{})}function toCallback(e,t){e.then(e=>process.nextTick(()=>t(null,e)),e=>process.nextTick(()=>t(e)))}var e={delay,fromCallback,fromEvent,getCallback,newQueryPlan,optionalCallback,times,toBackground,toCallback};export{e as default};
|
package/driver/readers.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import e from"./errors.js";import t from"./utils.js";import n from"./types/index.js";import r from"util";const i={globalTablesSpec:1,hasMorePages:2,noMetadata:4,metadataChanged:8,continuousPaging:1073741824,lastContinuousPage:2147483648};var FrameReader=class{constructor(e,t,n){this.header=e,this.opcode=e.opcode,this.offset=n||0,this.buf=t}remainingLength(){return this.buf.length-this.offset}getBuffer(){return this.buf}slice(e,t){return t===void 0&&(t=this.buf.length),this.buf.slice(e,t)}unshift(e){if(this.offset>0)throw Error(`Can not modify the underlying buffer if already read`);this.buf=Buffer.concat([e,this.buf],e.length+this.buf.length)}read(e){let t=this.buf.length;e!==void 0&&this.offset+e<this.buf.length&&(t=this.offset+e);let n=this.slice(this.offset,t);return this.offset=t,n}toEnd(){this.offset=this.buf.length}readInt(){let e=this.buf.readInt32BE(this.offset);return this.offset+=4,e}readShort(){let e=this.buf.readUInt16BE(this.offset);return this.offset+=2,e}readByte(){let e=this.buf.readUInt8(this.offset);return this.offset+=1,e}readString(){let e=this.readShort();this.checkOffset(e);let t=this.buf.toString(`utf8`,this.offset,this.offset+e);return this.offset+=e,t}checkOffset(e){if(this.offset+e>this.buf.length){let t=RangeError(`Trying to access beyond buffer length`);throw t.expectedLength=e,t}}readStringList(){let e=this.readShort(),t=Array(e);for(let n=0;n<e;n++)t[n]=this.readString();return t}readBytes(){let e=this.readInt();return e<0?null:(this.checkOffset(e),this.read(e))}readShortBytes(){let e=this.readShort();return e<0?null:(this.checkOffset(e),this.read(e))}readMap(e,t,n){if(e<0)return null;let r={};for(let i=0;i<e;i++)r[t.call(this)]=n.call(this);return r}readStringMultiMap(){let e=this.readShort();if(e<0)return null;let t={};for(let n=0;n<e;n++)t[this.readString()]=this.readStringList();return t}readType(){let e,t={code:this.readShort(),type:null};switch(t.code){case n.dataTypes.custom:t.info=this.readString();break;case n.dataTypes.list:case n.dataTypes.set:t.info=this.readType();break;case n.dataTypes.map:t.info=[this.readType(),this.readType()];break;case n.dataTypes.udt:for(t.info={keyspace:this.readString(),name:this.readString(),fields:Array(this.readShort())},e=0;e<t.info.fields.length;e++)t.info.fields[e]={name:this.readString(),type:this.readType()};break;case n.dataTypes.tuple:for(t.info=Array(this.readShort()),e=0;e<t.info.length;e++)t.info[e]=this.readType();break}return t}readInet(){let e=this.readByte(),t=this.read(e);return{address:new n.InetAddress(t),port:this.readInt()}}readInetAddress(){let e=this.readByte();return new n.InetAddress(this.read(e))}readFlagsInfo(){if(this.header.flags===0)return t.emptyObject;let e={};return this.header.flags&n.frameFlags.tracing&&(this.checkOffset(16),e.traceId=new n.Uuid(t.copyBuffer(this.read(16)))),this.header.flags&n.frameFlags.warning&&(e.warnings=this.readStringList()),this.header.flags&n.frameFlags.customPayload&&(e.customPayload=this.readMap(this.readShort(),this.readString,this.readBytes)),e}readMetadata(e){let r,a=e===n.resultKind.prepared,o={};n.protocolVersion.supportsResultMetadataId(this.header.version)&&a&&(o.resultId=t.copyBuffer(this.readShortBytes()));let s=this.readInt(),c=this.readInt();if(n.protocolVersion.supportsPreparedPartitionKey(this.header.version)&&a)for(o.partitionKeys=Array(this.readInt()),r=0;r<o.partitionKeys.length;r++)o.partitionKeys[r]=this.readShort();for(s&i.hasMorePages&&(o.pageState=t.copyBuffer(this.readBytes())),s&i.metadataChanged&&(o.newResultId=t.copyBuffer(this.readShortBytes())),s&i.continuousPaging&&(o.continuousPageIndex=this.readInt(),o.lastContinuousPage=!!(s&i.lastContinuousPage)),s&i.globalTablesSpec&&(o.global_tables_spec=!0,o.keyspace=this.readString(),o.table=this.readString()),o.columns=Array(c),o.columnsByName=t.emptyObject,a&&(o.columnsByName={}),r=0;r<c;r++){let e={};o.global_tables_spec||(e.ksname=this.readString(),e.tablename=this.readString()),e.name=this.readString(),e.type=this.readType(),o.columns[r]=e,a&&(o.columnsByName[e.name]=r)}return o}readError(){let i=this.readInt(),a=this.readString(),o=new e.ResponseError(i,a);switch(i){case n.responseErrorCodes.unavailableException:o.consistencies=this.readShort(),o.required=this.readInt(),o.alive=this.readInt(),o.message=r.format(`Not enough replicas available for query at consistency %s (%d required but only %d alive)`,n.consistencyToString[o.consistencies],o.required,o.alive);break;case n.responseErrorCodes.readTimeout:case n.responseErrorCodes.readFailure:if(o.consistencies=this.readShort(),o.received=this.readInt(),o.blockFor=this.readInt(),i===n.responseErrorCodes.readFailure&&(n.protocolVersion.supportsFailureReasonMap(this.header.version)?(o.failures=this.readInt(),o.reasons=this.readMap(o.failures,this.readInetAddress,this.readShort)):o.failures=this.readInt()),o.isDataPresent=this.readByte(),i===n.responseErrorCodes.readTimeout){let e;e=o.received<o.blockFor?r.format(`%d replica(s) responded over %d required`,o.received,o.blockFor):o.isDataPresent?`timeout while waiting for repair of inconsistent replica`:`the replica queried for the data didn't respond`,o.message=r.format(`Server timeout during read query at consistency %s (%s)`,n.consistencyToString[o.consistencies],e)}else o.message=r.format(`Server failure during read query at consistency %s (%d responses were required but only %d replicas responded, %d failed)`,n.consistencyToString[o.consistencies],o.blockFor,o.received,o.failures);break;case n.responseErrorCodes.writeTimeout:case n.responseErrorCodes.writeFailure:if(o.consistencies=this.readShort(),o.received=this.readInt(),o.blockFor=this.readInt(),i===n.responseErrorCodes.writeFailure&&(n.protocolVersion.supportsFailureReasonMap(this.header.version)?(o.failures=this.readInt(),o.reasons=this.readMap(o.failures,this.readInetAddress,this.readShort)):o.failures=this.readInt()),o.writeType=this.readString(),i===n.responseErrorCodes.writeTimeout){let e=o.writeType===`BATCH_LOG`?`Server timeout during batchlog write at consistency %s (%d peer(s) acknowledged the write over %d required)`:`Server timeout during write query at consistency %s (%d peer(s) acknowledged the write over %d required)`;o.message=r.format(e,n.consistencyToString[o.consistencies],o.received,o.blockFor)}else o.message=r.format(`Server failure during write query at consistency %s (%d responses were required but only %d replicas responded, %d failed)`,n.consistencyToString[o.consistencies],o.blockFor,o.received,o.failures);break;case n.responseErrorCodes.unprepared:o.queryId=t.copyBuffer(this.readShortBytes());break;case n.responseErrorCodes.functionFailure:o.keyspace=this.readString(),o.functionName=this.readString(),o.argTypes=this.readStringList();break;case n.responseErrorCodes.alreadyExists:{o.keyspace=this.readString();let e=this.readString();e.length>0&&(o.table=e);break}}return o}readEvent(){let e=this.readString();switch(e){case n.protocolEvents.topologyChange:return{added:this.readString()===`NEW_NODE`,inet:this.readInet(),eventType:e};case n.protocolEvents.statusChange:return{up:this.readString()===`UP`,inet:this.readInet(),eventType:e};case n.protocolEvents.schemaChange:return this.parseSchemaChange()}return{eventType:e}}parseSchemaChange(){let e;if(!n.protocolVersion.supportsSchemaChangeFullMetadata(this.header.version))return e={eventType:n.protocolEvents.schemaChange,schemaChangeType:this.readString(),keyspace:this.readString(),table:this.readString()},e.isKeyspace=!e.table,e;switch(e={eventType:n.protocolEvents.schemaChange,schemaChangeType:this.readString(),target:this.readString(),keyspace:this.readString(),table:null,udt:null,signature:null},e.isKeyspace=e.target===`KEYSPACE`,e.target){case`TABLE`:e.table=this.readString();break;case`TYPE`:e.udt=this.readString();break;case`FUNCTION`:e.functionName=this.readString(),e.signature=this.readStringList();break;case`AGGREGATE`:e.aggregate=this.readString(),e.signature=this.readStringList()}return e}};export{FrameReader};
|
|
@@ -1 +0,0 @@
|
|
|
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"./policies/retry.js";import a from"./requests.js";const o=Object.freeze({decision:i.RetryPolicy.retryDecision.retry,useCurrentHost:!0,consistency:void 0}),s=Object.freeze({decision:i.RetryPolicy.retryDecision.rethrow}),c={none:0,socketError:1,socketErrorBeforeRequestWritten:2,clientTimeout:3,serverErrorUnprepared:4,serverErrorOverloaded:5,serverErrorReadTimeout:6,serverErrorUnavailable:7,serverErrorWriteTimeout:8,serverErrorOther:9},l=new Map([[c.none,(e,t,n)=>e.onSuccessfulResponse(n)],[c.socketError,(e,t)=>e.onConnectionError(t)],[c.clientTimeout,(e,t)=>e.onClientTimeoutError(t)],[c.serverErrorOverloaded,(e,t)=>e.onOtherError(t)],[c.serverErrorReadTimeout,(e,t)=>e.onReadTimeoutError(t)],[c.serverErrorUnavailable,(e,t)=>e.onUnavailableError(t)],[c.serverErrorWriteTimeout,(e,t)=>e.onWriteTimeoutError(t)],[c.serverErrorOther,(e,t)=>e.onOtherError(t)]]),u=new Map([[c.socketError,(e,t)=>e.onOtherErrorRetry(t)],[c.clientTimeout,(e,t)=>e.onClientTimeoutRetry(t)],[c.serverErrorOverloaded,(e,t)=>e.onOtherErrorRetry(t)],[c.serverErrorReadTimeout,(e,t)=>e.onReadTimeoutRetry(t)],[c.serverErrorUnavailable,(e,t)=>e.onUnavailableRetry(t)],[c.serverErrorWriteTimeout,(e,t)=>e.onWriteTimeoutRetry(t)],[c.serverErrorOther,(e,t)=>e.onOtherErrorRetry(t)]]);var d=class RequestExecution{constructor(e,t,n){this._parent=e,this._operation=null,this._host=t,this._connection=n,this._cancelled=!1,this._startTime=null,this._retryCount=0,this._request=this._parent.request,e.speculativeExecutions++}start(){this._sendOnConnection()}async restart(){try{let{host:e,connection:t}=this._parent.getNextConnection();this._connection=t,this._host=e}catch(e){return this._parent.handleNoHostAvailable(e,this)}let e=this._parent.client.keyspace;if(e&&e!==this._connection.keyspace)try{await this._connection.changeKeyspace(e)}catch(e){return this._handleError(RequestExecution._getErrorCode(e),e)}this._cancelled||this._sendOnConnection()}_sendOnConnection(){this._startTime=process.hrtime(),this._operation=this._connection.sendStream(this._request,this._parent.executionOptions,(e,n,r)=>{let i=RequestExecution._getErrorCode(e);if(this._trackResponse(process.hrtime(this._startTime),i,e,r),!this._cancelled){if(i!==c.none)return this._handleError(i,e);if(n.schemaChange)return t.toBackground(this._parent.client.handleSchemaAgreementAndRefresh(this._connection,n.schemaChange).then(e=>{this._cancelled||this._parent.setCompleted(null,this._getResultSet(n,e))}));if(n.keyspaceSet&&(this._parent.client.keyspace=n.keyspaceSet),n.meta&&n.meta.newResultId&&this._request.queryId){let e=this._parent.client.metadata.getPreparedById(this._request.queryId);e.meta.resultId=n.meta.newResultId}this._parent.setCompleted(null,this._getResultSet(n))}})}_trackResponse(e,t,n,r){RequestExecution._invokeMetricsHandler(t,this._parent.client.metrics,n,e);let i=this._parent.client.options.requestTracker;if(i===null)return;let a=this._request.query||this._request.queries,o=this._request.params,s=this._request.length;n?i.onError(this._host,a,o,this._parent.executionOptions,s,n,e):i.onSuccess(this._host,a,o,this._parent.executionOptions,s,r,e)}_getResultSet(e,t){let n=new r.ResultSet(e,this._host.address,this._parent.triedHosts,this._parent.speculativeExecutions,this._request.consistency,t===void 0||t);return n.rawPageState&&(n.nextPageAsync=this._parent.getNextPageHandler()),n}static _invokeMetricsHandler(t,n,r,i){let a=l.get(t);a!==void 0&&a(n,r,i),(!r||r instanceof e.ResponseError)&&n.onResponse(i)}static _invokeMetricsHandlerForRetry(e,t,n){let r=u.get(e);r!==void 0&&r(t,n)}cancel(){this._cancelled=!0,this._operation!==null&&this._operation.cancel()}wasCancelled(){return this._cancelled}_handleError(e,t){if(this._parent.triedHosts[this._host.address]=t,t.coordinator=this._host.address,e===c.serverErrorUnprepared)return this._prepareAndRetry(t.queryId);e===c.socketError||e===c.socketErrorBeforeRequestWritten?this._host.removeFromPool(this._connection):e===c.clientTimeout&&(this._parent.log(`warning`,t.message),this._host.checkHealth(this._connection));let r=this._getDecision(e,t);if(!r||r.decision===i.RetryPolicy.retryDecision.rethrow)return(this._request instanceof a.QueryRequest||this._request instanceof a.ExecuteRequest)&&(t.query=this._request.query),this._parent.setCompleted(t);let o=this._parent.client.metrics;return r.decision===i.RetryPolicy.retryDecision.ignore?(o.onIgnoreError(t),this._parent.setCompleted(null,this._getResultSet(n.emptyObject))):(RequestExecution._invokeMetricsHandlerForRetry(e,o,t),this._retry(r.consistency,r.useCurrentHost))}_getDecision(e,t){let n={query:this._request&&this._request.query,executionOptions:this._parent.executionOptions,nbRetry:this._retryCount},r=n.executionOptions.getRetryPolicy();switch(e){case c.socketErrorBeforeRequestWritten:return o;case c.socketError:case c.clientTimeout:case c.serverErrorOverloaded:return n.executionOptions.isIdempotent()?r.onRequestError(n,this._request.consistency,t):s;case c.serverErrorUnavailable:return r.onUnavailable(n,t.consistencies,t.required,t.alive);case c.serverErrorReadTimeout:return r.onReadTimeout(n,t.consistencies,t.received,t.blockFor,t.isDataPresent);case c.serverErrorWriteTimeout:return n.executionOptions.isIdempotent()?r.onWriteTimeout(n,t.consistencies,t.received,t.blockFor,t.writeType):s;default:return s}}static _getErrorCode(t){if(!t)return c.none;if(t.isSocketError)return t.requestNotWritten?c.socketErrorBeforeRequestWritten:c.socketError;if(t instanceof e.OperationTimedOutError)return c.clientTimeout;if(t instanceof e.ResponseError)switch(t.code){case r.responseErrorCodes.overloaded:case r.responseErrorCodes.isBootstrapping:case r.responseErrorCodes.truncateError:return c.serverErrorOverloaded;case r.responseErrorCodes.unavailableException:return c.serverErrorUnavailable;case r.responseErrorCodes.readTimeout:return c.serverErrorReadTimeout;case r.responseErrorCodes.writeTimeout:return c.serverErrorWriteTimeout;case r.responseErrorCodes.unprepared:return c.serverErrorUnprepared}return c.serverErrorOther}_retry(e,n,r){if(!this._cancelled){if(this._parent.log(`info`,`Retrying request`),this._retryCount++,(r||typeof e==`number`&&this._request.consistency!==e)&&(this._request=this._request.clone(),typeof e==`number`&&(this._request.consistency=e),r&&(this._request.meta=r)),n!==!1){try{this._connection=this._host.borrowConnection(this._connection)}catch{return t.toBackground(this.restart())}return this._sendOnConnection()}t.toBackground(this.restart())}}_prepareAndRetry(t){let n=this._connection;this._parent.log(`info`,`Query 0x${t.toString(`hex`)} not prepared on host ${n.endpointFriendlyName}, preparing and retrying`);let i=this._parent.client.metadata.getPreparedById(t);if(!i)return this._parent.setCompleted(new e.DriverInternalError(`Unprepared response invalid, id: 0x${t.toString(`hex`)}`));let a=this._connection.protocolVersion;if(!r.protocolVersion.supportsKeyspaceInRequest(a)&&i.keyspace&&i.keyspace!==n.keyspace)return this._parent.setCompleted(Error(`Query was prepared on keyspace ${i.keyspace}, can't execute it on ${n.keyspace} (${i.query})`));let o=this;this._connection.prepareOnce(i.query,i.keyspace,function(t,r){if(t)return!t.isSocketError&&t instanceof e.OperationTimedOutError&&o._parent.log(`warning`,`Unexpected timeout error when re-preparing query on host ${n.endpointFriendlyName}`),o._retry(void 0,!1);i.meta=r.meta,o._retry(void 0,!0,r.meta)})}};export{d as default};
|
|
@@ -1 +0,0 @@
|
|
|
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"./request-execution.js";import a from"util";var o=class RequestHandler{constructor(e,t,r){this.client=r,this._speculativeExecutionPlan=r.options.policies.speculativeExecution.newPlan(r.keyspace,e.query||e.queries),this.logEmitter=r.options.logEmitter,this.log=n.log,this.request=e,this.executionOptions=t,this.stackContainer=null,this.triedHosts={},this.speculativeExecutions=-1,this._hostIterator=null,this._resolveCallback=null,this._rejectCallback=null,this._newExecutionTimeout=null,this._executions=[]}static send(e,t,n){return new RequestHandler(e,t,n).send()}getNextConnection(){let t,n,i=this._hostIterator;for(;;){let a=i.next();if(a.done)throw new e.NoHostAvailableError(this.triedHosts);if(t=a.value,this.client.profileManager.getDistance(t)!==r.distance.ignored){if(!t.isUp()){this.triedHosts[t.address]=`Host considered as DOWN`;continue}try{n=t.borrowConnection(),this.triedHosts[t.address]=null;break}catch(e){this.triedHosts[t.address]=e}}}return{connection:n,host:t}}send(){return this.executionOptions.getCaptureStackTrace()&&Error.captureStackTrace(this.stackContainer={}),new Promise((e,r)=>{this._resolveCallback=e,this._rejectCallback=r;let i=this.executionOptions.getLoadBalancingPolicy(),a=this.executionOptions.getFixedHost();a?(this._hostIterator=n.arrayIterator([a]),t.toBackground(this._startNewExecution())):i.newQueryPlan(this.client.keyspace,this.executionOptions,(e,n)=>{if(e)return r(e);this._hostIterator=n,t.toBackground(this._startNewExecution())})})}async _startNewExecution(e){e&&this.client.metrics.onSpeculativeExecution();let t,n;try{({host:t,connection:n}=this.getNextConnection())}catch(e){return this.handleNoHostAvailable(e,null)}if(e&&this._executions.length>=0&&this._executions[0].wasCancelled())return;if(this.client.keyspace&&this.client.keyspace!==n.keyspace)try{await n.changeKeyspace(this.client.keyspace)}catch(n){return this.triedHosts[t.address]=n,this._startNewExecution(e)}let r=new i(this,t,n);this._executions.push(r),r.start(),this.executionOptions.isIdempotent()&&this._scheduleSpeculativeExecution(t)}_scheduleSpeculativeExecution(e){let n=this._speculativeExecutionPlan.nextExecution(e);if(!(typeof n!=`number`||n<0)){if(n===0)return process.nextTick(()=>{t.toBackground(this._startNewExecution(!0))});this._newExecutionTimeout=setTimeout(()=>t.toBackground(this._startNewExecution(!0)),n)}}static setKeyspace(t){let n;for(let e of t.hosts.values())if(n=e.getActiveConnection(),n)break;if(!n)throw new e.DriverInternalError(`No active connection found`);return n.changeKeyspace(t.keyspace)}setCompleted(e,t){this._newExecutionTimeout!==null&&clearTimeout(this._newExecutionTimeout);for(let e of this._executions)e.cancel();if(e)return this.executionOptions.getCaptureStackTrace()&&n.fixStack(this.stackContainer.stack,e),this._rejectCallback(e);t.info.warnings&&t.info.warnings.forEach(function(e,t,n){this.log(`warning`,a.format(`Received warning (%d of %d) "%s" for "%s"`,t+1,n.length,e,this.request.query||`batch`))},this),this._resolveCallback(t)}handleNoHostAvailable(e,t){if(t!==null){let e=this._executions.indexOf(t);this._executions.splice(e,1)}this._executions.length===0&&this.setCompleted(e)}getNextPageHandler(){let e=this.request,t=this.executionOptions,n=this.client;return function(r){return t.setPageState(r),new RequestHandler(e,t,n).send()}}};export{o as default};
|
package/driver/requests.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import e from"./utils.js";import t from"./types/index.js";import{FrameWriter as n}from"./writers.js";import{ExecutionOptions as r}from"./execution-options.js";import{description as i,version as a}from"../package.js";import o from"util";const s={values:1,skipMetadata:2,pageSize:4,withPagingState:8,withSerialConsistency:16,withDefaultTimestamp:32,withNameForValues:64,withKeyspace:128,withPageSizeBytes:1073741824,withContinuousPaging:2147483648},c={withSerialConsistency:16,withDefaultTimestamp:32,withNameForValues:64,withKeyspace:128},l={withKeyspace:1},u={logged:0,unlogged:1,counter:2};var Request=class{constructor(){this.length=0}write(e,t){throw Error(`Method must be implemented`)}clone(){let e=new this.constructor,t=Object.keys(this);for(let n=0;n<t.length;n++){let r=t[n];e[r]=this[r]}return e}},ExecuteRequest=class extends Request{constructor(e,n,i,a,o){super(),this.query=e,this.queryId=n,this.params=i,this.meta=o,this.options=a||r.empty(),this.timestamp=this.options.getOrGenerateTimestamp(),this.consistency=this.options.getConsistency()||t.consistencies.one,this.namedParameters=!1}getParamType(e){let t=this.meta.columns[e];return t?t.type:null}write(e,r){let i=new n(t.opcodes.execute),a=this.options.isQueryTracing()?t.frameFlags.tracing:0;return this.options.getCustomPayload()&&(a|=t.frameFlags.customPayload,i.writeCustomPayload(this.options.getCustomPayload())),i.writeShortBytes(this.queryId),t.protocolVersion.supportsResultMetadataId(e.protocolVersion)&&i.writeShortBytes(this.meta.resultId),this.writeQueryParameters(i,e),this.length=i.bodyLength,i.write(e.protocolVersion,r,a)}writeQueryParameters(e,n,r){let i=0,a=this.timestamp;if(t.protocolVersion.supportsPaging(n.protocolVersion)){i|=this.params&&this.params.length?s.values:0,i|=this.options.getFetchSize()>0?s.pageSize:0,i|=this.options.getPageState()?s.withPagingState:0,i|=this.options.getSerialConsistency()?s.withSerialConsistency:0,i|=a==null?0:s.withDefaultTimestamp,i|=this.namedParameters?s.withNameForValues:0;let o=r&&t.protocolVersion.supportsKeyspaceInRequest(n.protocolVersion);i|=o&&this.options.getKeyspace()?s.withKeyspace:0,e.writeShort(this.consistency),t.protocolVersion.uses4BytesQueryFlags(n.protocolVersion)?e.writeInt(i):e.writeByte(i)}if(this.params&&this.params.length){e.writeShort(this.params.length);for(let t=0;t<this.params.length;t++){let r=this.params[t];i&s.withNameForValues&&(e.writeString(r.name),r=r.value),e.writeBytes(n.encode(r,this.getParamType(t)))}}if(!t.protocolVersion.supportsPaging(n.protocolVersion)){(!this.params||!this.params.length)&&e.writeShort(0),e.writeShort(this.consistency);return}i&s.pageSize&&e.writeInt(this.options.getFetchSize()),i&s.withPagingState&&e.writeBytes(this.options.getPageState()),i&s.withSerialConsistency&&e.writeShort(this.options.getSerialConsistency()),i&s.withDefaultTimestamp&&e.writeLong(a),i&s.withKeyspace&&e.writeString(this.options.getKeyspace())}},QueryRequest=class extends ExecuteRequest{constructor(t,n,r,i){super(t,null,n,r,null),this.hints=this.options.getHints()||e.emptyArray,this.namedParameters=i}getParamType(e){return this.hints[e]}write(e,r){let i=new n(t.opcodes.query),a=this.options.isQueryTracing()?t.frameFlags.tracing:0;return this.options.getCustomPayload()&&(a|=t.frameFlags.customPayload,i.writeCustomPayload(this.options.getCustomPayload())),i.writeLString(this.query),t.protocolVersion.supportsPaging(e.protocolVersion)?this.writeQueryParameters(i,e,!0):i.writeShort(this.consistency),this.length=i.bodyLength,i.write(e.protocolVersion,r,a)}},PrepareRequest=class extends Request{constructor(e,t){super(),this.query=e,this.keyspace=t}write(e,r){let i=new n(t.opcodes.prepare);if(i.writeLString(this.query),t.protocolVersion.supportsPrepareFlags(e.protocolVersion)){let n=this.keyspace&&t.protocolVersion.supportsKeyspaceInRequest(e.protocolVersion)?l.withKeyspace:0;i.writeInt(n),n&l.withKeyspace&&i.writeString(this.keyspace)}return i.write(e.protocolVersion,r)}},StartupRequest=class extends Request{constructor(e){super(),this.options=e||{}}write(e,r){let o=new n(t.opcodes.startup),s={CQL_VERSION:this.options.cqlVersion||`3.0.0`,DRIVER_NAME:i,DRIVER_VERSION:a};return this.options.noCompact&&(s.NO_COMPACT=`true`),this.options.clientId&&(s.CLIENT_ID=this.options.clientId.toString()),this.options.applicationName&&(s.APPLICATION_NAME=this.options.applicationName),this.options.applicationVersion&&(s.APPLICATION_VERSION=this.options.applicationVersion),o.writeStringMap(s),o.write(e.protocolVersion,r)}},RegisterRequest=class extends Request{constructor(e){super(),this.events=e}write(e,r){let i=new n(t.opcodes.register);return i.writeStringList(this.events),i.write(e.protocolVersion,r)}},AuthResponseRequest=class extends Request{constructor(e){super(),this.token=e}write(e,r){let i=new n(t.opcodes.authResponse);return i.writeBytes(this.token),i.write(e.protocolVersion,r)}},CredentialsRequest=class extends Request{constructor(e,t){super(),this.username=e,this.password=t}write(e,r){let i=new n(t.opcodes.credentials);return i.writeStringMap({username:this.username,password:this.password}),i.write(e.protocolVersion,r)}},d=class BatchRequest extends Request{constructor(t,n){super(),this.queries=t,this.options=n,this.timestamp=this.options.getOrGenerateTimestamp(),this.hints=n.getHints()||e.emptyArray,this.type=u.logged,n.isBatchCounter()?this.type=u.counter:n.isBatchLogged()||(this.type=u.unlogged)}write(r,i){if(!this.queries||!(this.queries.length>0))throw TypeError(o.format(`Invalid queries provided %s`,this.queries));let a=new n(t.opcodes.batch),s=this.options.isQueryTracing()?t.frameFlags.tracing:0;this.options.getCustomPayload()&&(s|=t.frameFlags.customPayload,a.writeCustomPayload(this.options.getCustomPayload())),a.writeByte(this.type),a.writeShort(this.queries.length);let l=this;if(this.queries.forEach(function(t,n){let i=l.hints[n],o=t.params||e.emptyArray,getParamType;t.queryId?(a.writeByte(1),a.writeShortBytes(t.queryId),getParamType=e=>t.meta.columns[e].type):(a.writeByte(0),a.writeLString(t.query),getParamType=i?e=>i[e]:()=>null),a.writeShort(o.length),o.forEach((e,t)=>a.writeBytes(r.encode(e,getParamType(t))))},this),a.writeShort(this.options.getConsistency()),t.protocolVersion.supportsTimestamp(r.protocolVersion)){let e=this.options.getSerialConsistency()?c.withSerialConsistency:0,n=this.timestamp;e|=n==null?0:c.withDefaultTimestamp,e|=this.options.getKeyspace()&&t.protocolVersion.supportsKeyspaceInRequest(r.protocolVersion)?c.withKeyspace:0,t.protocolVersion.uses4BytesQueryFlags(r.protocolVersion)?a.writeInt(e):a.writeByte(e),e&c.withSerialConsistency&&a.writeShort(this.options.getSerialConsistency()),e&c.withDefaultTimestamp&&a.writeLong(n),e&c.withKeyspace&&a.writeString(this.options.getKeyspace())}return this.length=a.bodyLength,a.write(r.protocolVersion,i,s)}clone(){return new BatchRequest(this.queries,this.options)}};function CancelRequest(e){this.streamId=null,this.operationId=e}o.inherits(CancelRequest,Request),CancelRequest.prototype.write=function(e,r){let i=new n(t.opcodes.cancel);return i.writeInt(1),i.writeInt(this.operationId),i.write(e.protocolVersion,r)};var f={AuthResponseRequest,BatchRequest:d,CancelRequest,CredentialsRequest,ExecuteRequest,options:new class extends Request{write(e,r){return new n(t.opcodes.options).write(e.protocolVersion,r,0)}clone(){return this}},PrepareRequest,QueryRequest,RegisterRequest,Request,StartupRequest};export{ExecuteRequest,QueryRequest,f as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import e from"./types/index.js";var StreamIdStack=class{constructor(e){this.currentGroup=generateGroup(0),this.groupIndex=0,this.groups=[this.currentGroup],this.releaseTimeout=null,this.setVersion(e),this.inUse=0,this.releaseDelay=5e3}setVersion(t){this.maxGroups=e.protocolVersion.uses2BytesStreamIds(t)?256:1}pop(){let e=this.currentGroup.pop();if(e!==void 0)return this.inUse++,e;for(;this.groupIndex<this.groups.length-1;)if(this.currentGroup=this.groups[++this.groupIndex],e=this.currentGroup.pop(),e!==void 0)return this.inUse++,e;return this._tryCreateGroup()}push(e){this.inUse--;let t=e>>7,n=this.groups[t];n.push(e),t<this.groupIndex&&(this.groupIndex=t,this.currentGroup=n),this._tryIssueRelease()}clear(){this.releaseTimeout&&=(clearTimeout(this.releaseTimeout),null)}_tryCreateGroup(){return this.groups.length===this.maxGroups?null:(this.groupIndex=this.groups.length,this.currentGroup=generateGroup(this.groupIndex<<7),this.groups.push(this.currentGroup),this.inUse++,this.currentGroup.pop())}_tryIssueRelease(){this.releaseTimeout||this.groups.length<=4||(this.releaseTimeout=setTimeout(()=>this._releaseGroups(),this.releaseDelay))}_releaseGroups(){let e=0,t=this.groups.length-1;for(;e++<4&&this.groups.length>4&&t>this.groupIndex&&this.groups[t].length===128;)this.groups.pop(),t--;this.releaseTimeout=null,this._tryIssueRelease()}};function generateGroup(e){let t=Array(128),n=e+128-1;for(let e=0;e<128;e++)t[e]=n-e;return t}export{StreamIdStack as default};
|
package/driver/streams.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import e from"./errors.js";import t from"./utils.js";import n from"./types/index.js";import{FrameReader as r}from"./readers.js";import i from"util";import{Transform as a,Writable as o}from"stream";const{FrameHeader:s}=n,c=new Set([0,1,3,10,13]);function Protocol(e){a.call(this,e),this.header=null,this.bodyLength=0,this.clearHeaderChunks(),this.version=0,this.headerSize=0}i.inherits(Protocol,a),Protocol.prototype._transform=function(e,t,n){let r=null;try{this.readItems(e)}catch(e){r=e}n(r)},Protocol.prototype.readItems=function(e){if(!e||e.length===0)return;this.version===0&&(this.version=s.getProtocolVersion(e),this.headerSize=s.size(this.version));let t=0,n=this.header;if(this.header=null,this.headerChunks.byteLength!==0){if(this.headerChunks.parts.push(e),this.headerChunks.byteLength+e.length<this.headerSize){this.headerChunks.byteLength+=e.length;return}n=s.fromBuffer(Buffer.concat(this.headerChunks.parts,this.headerSize)),t=this.headerSize-this.headerChunks.byteLength,this.clearHeaderChunks()}let r=[];for(;;){if(!n){if(this.headerSize>e.length-t){if(e.length-t<=0)break;let n=e.slice(t,e.length);this.headerChunks.parts.push(n),this.headerChunks.byteLength=n.length;break}n=s.fromBuffer(e,t),t+=this.headerSize}let i=e.length-t;if(n.bodyLength<=i+this.bodyLength)r.push({header:n,chunk:e,offset:t,frameEnded:!0}),t+=n.bodyLength-this.bodyLength,this.bodyLength=0;else if(i>=0){this.header=n,this.bodyLength+=i,i>0&&r.push({header:n,chunk:e,offset:t,frameEnded:!1});break}n=null}for(let e=0;e<r.length;e++)this.push(r[e])},Protocol.prototype.clearHeaderChunks=function(){this.headerChunks={byteLength:0,parts:[]}};function Parser(e,t){a.call(this,e),this.frames={},this.encoder=t}i.inherits(Parser,a),Parser.prototype._transform=function(t,n,r){let i=this.frameState(t),a=null;try{this.parseBody(i,t)}catch(e){a=e}r(a),t.frameEnded&&(i.cellBuffer&&this.push({header:i.header,error:new e.DriverInternalError(`There was an problem while parsing streaming frame, opcode `+i.header.opcode)}),this.push({header:i.header,frameEnded:!0}))},Parser.prototype.parseBody=function(e,t){if(e.isStreaming=e.byRow&&t.header.opcode===n.opcodes.result,!this.handleFrameBuffers(e,t))return;let i=new r(t.header,t.chunk,t.offset);if(e.flagsInfo===void 0){let t=i.offset;try{e.flagsInfo=i.readFlagsInfo()}catch(n){return this.handleParsingError(n,e,i,t)}}switch(t.header.opcode){case n.opcodes.result:return this.parseResult(e,i);case n.opcodes.ready:case n.opcodes.authSuccess:return this.push({header:e.header,ready:!0});case n.opcodes.authChallenge:return this.push({header:e.header,authChallenge:!0,token:i.readBytes()});case n.opcodes.authenticate:return this.push({header:e.header,mustAuthenticate:!0,authenticatorName:i.readString()});case n.opcodes.error:return this.push({header:e.header,error:i.readError()});case n.opcodes.supported:return this.push({header:e.header,supported:i.readStringMultiMap()});case n.opcodes.event:return this.push({header:e.header,event:i.readEvent()});default:return this.push({header:e.header,error:Error(`Received invalid opcode: `+t.header.opcode)})}},Parser.prototype.handleFrameBuffers=function(t,n){if(!t.isStreaming)return(t.bufferLength||0)+n.chunk.length-n.offset<n.header.bodyLength?(this.addFrameBuffer(t,n),!1):(t.buffers&&(n.chunk=this.getFrameBuffer(t,n),n.offset=0),!0);if(t.cellBuffer){if(n.offset!==0)throw new e.DriverInternalError(`Following chunks can not have an offset greater than zero`);if(t.cellBuffer.parts.push(n.chunk),!t.cellBuffer.expectedLength){if(t.cellBuffer.parts.length!==2)throw new e.DriverInternalError(`Buffer for streaming frame can not contain more than 1 item`);return n.chunk=Buffer.concat(t.cellBuffer.parts,t.cellBuffer.byteLength+n.chunk.length),t.cellBuffer=null,!0}if(t.cellBuffer.expectedLength>t.cellBuffer.byteLength+n.chunk.length)return t.cellBuffer.byteLength+=n.chunk.length,!1;n.chunk=Buffer.concat(t.cellBuffer.parts,t.cellBuffer.byteLength+n.chunk.length),t.cellBuffer=null}return!0},Parser.prototype.addFrameBuffer=function(t,n){if(!t.buffers){t.buffers=[n.chunk.slice(n.offset)],t.bufferLength=n.chunk.length-n.offset;return}if(n.offset>0)throw new e.DriverInternalError(`Following chunks can not have an offset greater than zero`);t.buffers.push(n.chunk),t.bufferLength+=n.chunk.length},Parser.prototype.getFrameBuffer=function(e,t){e.buffers.push(t.chunk);let n=Buffer.concat(e.buffers,e.bodyLength);return e.buffers=null,n},Parser.prototype.parseResult=function(r,i){let a,o=i.offset;try{if(!r.meta)switch(r.kind=i.readInt(),r.kind){case n.resultKind.voidResult:a={header:r.header,flags:r.flagsInfo};break;case n.resultKind.rows:r.meta=i.readMetadata(r.kind);break;case n.resultKind.setKeyspace:a={header:r.header,keyspaceSet:i.readString(),flags:r.flagsInfo};break;case n.resultKind.prepared:{let e=t.copyBuffer(i.readShortBytes());r.meta=i.readMetadata(r.kind),a={header:r.header,id:e,meta:r.meta,flags:r.flagsInfo};break}case n.resultKind.schemaChange:a={header:r.header,schemaChange:i.parseSchemaChange(),flags:r.flagsInfo};break;default:throw e.DriverInternalError(`Unexpected result kind: `+r.kind)}}catch(e){return this.handleParsingError(e,r,i,o)}if(a)return r.emitted?void 0:(r.emitted=!0,this.push(a));i.remainingLength()>0&&this.parseRows(r,i)},Parser.prototype.parseRows=function(e,r){if(e.parsingError)return;if(e.rowLength===void 0)try{e.rowLength=r.readInt()}catch(t){return this.handleParsingError(t,e,r)}if(e.rowLength===0)return this.push({header:e.header,result:{rows:t.emptyArray,meta:e.meta,flags:e.flagsInfo}});let i=e.meta;if(e.rowIndex=e.rowIndex||0,!e._colDecoders){let t=Array(i.columns.length);for(let e=0;e<i.columns.length;e++){let n=i.columns[e].type.code;t[e]=this.encoder.decoders[n]}e._colDecoders=t}let a=e._colDecoders,o=i.columns,s=Math.min(e.rowIndex+100,e.rowLength);for(let t=e.rowIndex;t<s;t++){let s=r.offset,l=new n.Row(i.columns),u;for(let n=0;n<o.length;n++){let i=o[n];try{u=r.readBytes()}catch(n){return this.handleParsingError(n,e,r,s,t)}try{u===null||u.length===0&&!c.has(i.type.code)?l[i.name]=null:l[i.name]=a[n].call(this.encoder,u,i.type)}catch(t){return this.handleParsingError(t,e,null)}}this.push({header:e.header,row:l,meta:e.meta,byRow:e.byRow,length:e.rowLength,flags:e.flagsInfo})}if(e.rowIndex=s,s<e.rowLength){e._reader=r;let t=this;setImmediate(()=>t.parseRows(e,e._reader));return}e._colDecoders=null,e._reader=null,e.byRow&&this.push({header:e.header,byRowCompleted:!0,meta:e.meta,length:e.rowLength,flags:e.flagsInfo})},Parser.prototype.setOptions=function(e,t){if(this.frames[e.toString()])throw new n.DriverError(`There was already state for this frame`);this.frames[e.toString()]=t},Parser.prototype.clearOptions=function(e){delete this.frames[e.toString()]},Parser.prototype.frameState=function(e){let t=this.frames[e.header.streamId];return t?e.frameEnded&&delete this.frames[e.header.streamId]:(t={},e.frameEnded||(this.frames[e.header.streamId]=t)),t.header=e.header,t},Parser.prototype.handleParsingError=function(e,t,n,r,i){if(n&&t.isStreaming&&e instanceof RangeError)return this.bufferResultCell(t,n,r,i,e.expectedLength);t.parsingError=!0,t.cellBuffer=null,this.push({header:t.header,error:e})},Parser.prototype.bufferResultCell=function(e,t,n,r,i){!n&&n!==0&&(n=t.offset),e.rowIndex=r;let a=t.slice(n);e.cellBuffer={parts:[a],byteLength:a.length,expectedLength:i}};function ResultEmitter(e){o.call(this,e),this.rowBuffer={}}i.inherits(ResultEmitter,o),ResultEmitter.prototype._write=function(e,t,n){let r=null;try{this.each(e)}catch(e){r=e}n(r)},ResultEmitter.prototype.each=function(e){return e.error||e.result?this.emit(`result`,e.header,e.error,e.result):e.frameEnded?this.emit(`frameEnded`,e.header):e.lastContinuousPage?this.emit(`lastContinuousPage`,e.header):e.byRowCompleted?this.emit(`byRowCompleted`,e.header,e.row,e.meta,e.flags):e.byRow?this.emit(`row`,e.header,e.row,e.meta,e.length,e.flags):e.row?this.bufferAndEmit(e):e.event?this.emit(`nodeEvent`,e.header,e.event):this.emit(`result`,e.header,null,e)},ResultEmitter.prototype.bufferAndEmit=function(e){let t=this.rowBuffer[e.header.streamId];t||=this.rowBuffer[e.header.streamId]=[],t.push(e.row),t.length===e.length&&(this.emit(`result`,e.header,null,{rows:t,meta:e.meta,flags:e.flags}),delete this.rowBuffer[e.header.streamId])};var l={Protocol,Parser,ResultEmitter};export{l as default};
|
package/driver/token.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import e from"./types/index.js";import t from"util";const n=e.dataTypes.getByName(`bigint`),r=e.dataTypes.getByName(`varint`),i=e.dataTypes.getByName(`blob`);var Token=class{constructor(e){this._value=e}getType(){throw Error(`You must implement a getType function for this Token instance`)}getValue(){return this._value}toString(){return this._value.toString()}compare(e){return this._value.compare(e._value)}equals(e){return this.compare(e)===0}inspect(){return this.constructor.name+` { `+this.toString()+` }`}},Murmur3Token=class extends Token{constructor(e){super(e)}getType(){return n}},RandomToken=class extends Token{constructor(e){super(e)}getType(){return r}},ByteOrderedToken=class extends Token{constructor(e){super(e)}getType(){return i}toString(){return this._value.toString(`hex`).toUpperCase()}},a=class TokenRange{constructor(e,t,n){this.start=e,this.end=t,Object.defineProperty(this,`_tokenizer`,{value:n,enumerable:!1})}splitEvenly(e){if(e<1)throw Error(t.format(`numberOfSplits (%d) must be greater than 0.`,e));if(this.isEmpty())throw Error(`Can't split empty range `+this.toString());let n=[],r=this._tokenizer.split(this.start,this.end,e),i=this.start,a;for(let e=0;e<r.length;e++)a=r[e],n.push(new TokenRange(i,a,this._tokenizer)),i=a;return n.push(new TokenRange(i,this.end,this._tokenizer)),n}isEmpty(){return this.start.equals(this.end)&&!this.start.equals(this._tokenizer.minToken())}isWrappedAround(){return this.start.compare(this.end)>0&&!this.end.equals(this._tokenizer.minToken())}unwrap(){return this.isWrappedAround()?[new TokenRange(this.start,this._tokenizer.minToken(),this._tokenizer),new TokenRange(this._tokenizer.minToken(),this.end,this._tokenizer)]:[this]}contains(e){if(this.isEmpty())return!1;let t=this._tokenizer.minToken();if(this.end.equals(t))return this.start.equals(t)||e.equals(t)?!0:e.compare(this.start)>0;let n=e.compare(this.start)>0,r=e.compare(this.end)<=0;return this.isWrappedAround()?n||r:n&&r}equals(e){return e===this?!0:e instanceof TokenRange?this.compare(e)===0:!1}compare(e){let t=this.start.compare(e.start);return t===0?this.end.compare(e.end):t}toString(){return t.format(`]%s, %s]`,this.start.toString(),this.end.toString())}},o={Token,TokenRange:a,ByteOrderedToken,Murmur3Token,RandomToken};export{Token,a as TokenRange,o as default};
|
package/driver/tokenizer.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import e from"./utils.js";import t from"./types/index.js";import n from"./types/mutable-long.js";import r from"./token.js";import i from"crypto";const{Integer:a}=t,o=new n(21461,4418,31633,34755),s=new n(37759,10053,44355,19701),c=n.fromNumber(5),l=new n(36045,60757,45015,65361),u=new n(60499,6789,47614,50382),d=n.fromNumber(1390208809),f=n.fromNumber(944331445);var Tokenizer=class{constructor(){}hash(e){throw Error(`You must implement a hash function for the tokenizer`)}parse(e){throw Error(`You must implement a parse function for the tokenizer`)}minToken(){throw Error(`You must implement a minToken function for the tokenizer`)}split(e,t,n){throw Error(`You must implement a split function for the tokenizer`)}splitBase(e,t,n,r,i){let o=a.fromInt(i),s=t.divide(o),c=t.modulo(o),l=[],u=e,d=s.add(a.ONE);for(let e=1;e<i;e++)u=c.greaterThan(a.ZERO)?u.add(d):u.add(s),r&&u.greaterThan(n)&&(u=u.subtract(r)),l.push(u),c=c.subtract(a.ONE);return l}stringify(e){return e.getValue().toString()}},Murmur3Tokenizer=class extends Tokenizer{constructor(){super()}hash(e){let t=e,i=0,a=t.length,l=a>>4,u=new n,p=new n,m=new n,h=new n;for(let e=0;e<l;e++)m=this.getBlock(t,i,e*2),h=this.getBlock(t,i,e*2+1),m.multiply(o),this.rotl64(m,31),m.multiply(s),u.xor(m),this.rotl64(u,27),u.add(p),u.multiply(c).add(d),h.multiply(s),this.rotl64(h,33),h.multiply(o),p.xor(h),this.rotl64(p,31),p.add(u),p.multiply(c).add(f);switch(i+=l*16,m=new n,h=new n,a&15){case 15:h.xor(fromSignedByte(t[i+14]).shiftLeft(48));case 14:h.xor(fromSignedByte(t[i+13]).shiftLeft(40));case 13:h.xor(fromSignedByte(t[i+12]).shiftLeft(32));case 12:h.xor(fromSignedByte(t[i+11]).shiftLeft(24));case 11:h.xor(fromSignedByte(t[i+10]).shiftLeft(16));case 10:h.xor(fromSignedByte(t[i+9]).shiftLeft(8));case 9:h.xor(fromSignedByte(t[i+8])),h.multiply(s),this.rotl64(h,33),h.multiply(o),p.xor(h);case 8:m.xor(fromSignedByte(t[i+7]).shiftLeft(56));case 7:m.xor(fromSignedByte(t[i+6]).shiftLeft(48));case 6:m.xor(fromSignedByte(t[i+5]).shiftLeft(40));case 5:m.xor(fromSignedByte(t[i+4]).shiftLeft(32));case 4:m.xor(fromSignedByte(t[i+3]).shiftLeft(24));case 3:m.xor(fromSignedByte(t[i+2]).shiftLeft(16));case 2:m.xor(fromSignedByte(t[i+1]).shiftLeft(8));case 1:m.xor(fromSignedByte(t[i])),m.multiply(o),this.rotl64(m,31),m.multiply(s),u.xor(m)}return u.xor(n.fromNumber(a)),p.xor(n.fromNumber(a)),u.add(p),p.add(u),this.fmix(u),this.fmix(p),u.add(p),new r.Murmur3Token(u)}getBlock(e,t,r){let i=t+(r<<3);return new n(e[i]|e[i+1]<<8,e[i+2]|e[i+3]<<8,e[i+4]|e[i+5]<<8,e[i+6]|e[i+7]<<8)}rotl64(e,t){let n=e.clone().shiftLeft(t);e.shiftRightUnsigned(64-t).or(n)}fmix(e){e.xor(new n(e.getUint16(2)>>>1|e.getUint16(3)<<15&65535,e.getUint16(3)>>>1,0,0)),e.multiply(l);let t=new n(e.getUint16(2)>>>1|e.getUint16(3)<<15&65535,e.getUint16(3)>>>1,0,0);e.xor(t),e.multiply(u),e.xor(new n(e.getUint16(2)>>>1|e.getUint16(3)<<15&65535,e.getUint16(3)>>>1,0,0))}parse(e){return new r.Murmur3Token(n.fromString(e))}minToken(){return this._minToken||=this.parse(`-9223372036854775808`),this._minToken}maxToken(){return this._maxToken||=this.parse(`9223372036854775807`),this._maxToken}maxValue(){return this._maxValue||=a.fromString(`9223372036854775807`),this._maxValue}minValue(){return this._minValue||=a.fromString(`-9223372036854775808`),this._minValue}ringLength(){return this._ringLength||=this.maxValue().subtract(this.minValue()),this._ringLength}split(e,t,n){e.equals(t)&&e.equals(this.minToken())&&(t=this.maxToken());let r=a.fromString(e.getValue().toString()),i=a.fromString(t.getValue().toString()).subtract(r);return i.isNegative()&&(i=i.add(this.ringLength())),this.splitBase(r,i,this.maxValue(),this.ringLength(),n).map(e=>this.parse(e.toString()))}stringify(e){let t=e.getValue();return t.getUint16(0)+`,`+t.getUint16(1)+`,`+t.getUint16(2)+`,`+t.getUint16(3)}},RandomTokenizer=class extends Tokenizer{constructor(){super(),this._crypto=i}hash(t){Array.isArray(t)&&(t=e.allocBufferFromArray(t));let n=this._crypto.createHash(`md5`).update(t).digest();return new r.RandomToken(a.fromBuffer(n).abs())}parse(e){return new r.RandomToken(a.fromString(e))}minToken(){return this._minToken||=this.parse(`-1`),this._minToken}maxValue(){return this._maxValue||=a.fromNumber(2**127),this._maxValue}maxToken(){return this._maxToken||=new r.RandomToken(this.maxValue()),this._maxToken}ringLength(){return this._ringLength||=this.maxValue().add(a.ONE),this._ringLength}split(e,t,n){e.equals(t)&&e.equals(this.minToken())&&(t=this.maxToken());let i=e.getValue(),o=t.getValue().subtract(i);return o.lessThan(a.ZERO)&&(o=o.add(this.ringLength())),this.splitBase(i,o,this.maxValue(),this.ringLength(),n).map(e=>new r.RandomToken(e))}},ByteOrderedTokenizer=class extends Tokenizer{constructor(){super()}hash(t){Array.isArray(t)&&(t=e.allocBufferFromArray(t));let n=t.length;for(let e=t.length-1;e>0&&t[e]===0;e--)n=e;return new r.ByteOrderedToken(t.slice(0,n))}stringify(e){return e.getValue().toString(`hex`)}parse(t){return this.hash(e.allocBufferFromString(t,`hex`))}minToken(){return this._minToken||=this.hash([]),this._minToken}_toNumber(e,t){let n=e;e.length!==t&&(n=Buffer.alloc(t),e.copy(n));let r=Array(Math.ceil(n.length/4));for(let e=0;e<r.length;e++){let t=n.length-(e+1)*4,i;if(t<0){t+=4,i=0;for(let e=0;e<t;e++){let r=n[e];i|=r<<(t-e-1)*8}}else i=n.readInt32BE(t);r[e]=i}return new a(r,0)}_toBuffer(e,t){let n=a.toBuffer(e);if(n.length===t)return n;let r,i;n[0]===0?(r=1,i=n.length-1):(r=0,i=n.length);let o=Buffer.alloc(t);return n.copy(o,t-i,r,i+r),o}split(e,t,n){let i=e.compare(t);if(i===0&&e.equals(this.minToken()))throw Error(`Cannot split whole ring with ordered partitioner`);let o,s,c,l,u,d=a.fromNumber(n),f=Math.max(e.getValue().length,t.getValue().length);if(i<0){let n=0;for(;o=this._toNumber(e.getValue(),f),s=this._toNumber(t.getValue(),f),c=s.subtract(o),!(n===4||c.compare(d)>=0);)f+=1,n+=1}else{let n=0;for(;o=this._toNumber(e.getValue(),f),s=this._toNumber(t.getValue(),f),l=a.fromNumber(2**(f*8)),u=l.subtract(a.ONE),c=s.subtract(o).add(l),!(n===4||c.compare(d)>=0);)f+=1,n+=1}return this.splitBase(o,c,u,l,n).map(e=>new r.ByteOrderedToken(this._toBuffer(e,f)))}};function fromSignedByte(e){return e<128?new n(e,0,0,0):new n(e-256&65535,65535,65535,65535)}var p={Murmur3Tokenizer,RandomTokenizer,ByteOrderedTokenizer};export{p as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import e from"../utils.js";import t from"./integer.js";function BigDecimal(e,n){typeof e==`number`&&(e=t.fromNumber(e)),this._intVal=e,this._scale=n}BigDecimal.fromBuffer=function(e){let n=e.readInt32BE(0);return new BigDecimal(t.fromBuffer(e.slice(4)),n)},BigDecimal.toBuffer=function(n){let r=t.toBuffer(n._intVal),i=e.allocBufferUnsafe(4);return i.writeInt32BE(n._scale,0),Buffer.concat([i,r],i.length+r.length)},BigDecimal.fromString=function(e){if(!e)throw TypeError(`Invalid null or undefined value`);e=e.trim();let n=e.indexOf(`.`),r=0;return n>=0&&(r=e.length-1-n,e=e.substr(0,n)+e.substr(n+1)),new BigDecimal(t.fromString(e),r)},BigDecimal.fromNumber=function(e){if(isNaN(e))return new BigDecimal(t.ZERO,0);let n=e.toString();return n.indexOf(`e`)>=0&&(n=e.toFixed(20)),BigDecimal.fromString(n)},BigDecimal.prototype.equals=function(e){return e instanceof BigDecimal&&this.compare(e)===0},BigDecimal.prototype.inspect=function(){return this.constructor.name+`: `+this.toString()},BigDecimal.prototype.notEquals=function(e){return!this.equals(e)},BigDecimal.prototype.compare=function(e){let t=this.subtract(e);return t.isNegative()?-1:+!t.isZero()},BigDecimal.prototype.subtract=function(e){let n=this;if(n._scale===e._scale)return new BigDecimal(n._intVal.subtract(e._intVal),n._scale);let r,i;return n._scale<e._scale?(r=e._scale-n._scale,i=n._intVal.multiply(t.fromNumber(10**r)).subtract(e._intVal),new BigDecimal(i,e._scale)):(r=n._scale-e._scale,i=n._intVal.subtract(e._intVal.multiply(t.fromNumber(10**r))),new BigDecimal(i,n._scale))},BigDecimal.prototype.add=function(e){let n=this;if(n._scale===e._scale)return new BigDecimal(n._intVal.add(e._intVal),n._scale);let r,i;return n._scale<e._scale?(r=e._scale-n._scale,i=n._intVal.multiply(t.fromNumber(10**r)).add(e._intVal),new BigDecimal(i,e._scale)):(r=n._scale-e._scale,i=n._intVal.add(e._intVal.multiply(t.fromNumber(10**r))),new BigDecimal(i,n._scale))},BigDecimal.prototype.greaterThan=function(e){return this.compare(e)===1},BigDecimal.prototype.isNegative=function(){return this._intVal.isNegative()},BigDecimal.prototype.isZero=function(){return this._intVal.isZero()},BigDecimal.prototype.toString=function(){let t=this._intVal.toString();if(this._scale===0)return t;let n=``;t.charAt(0)===`-`&&(n=`-`,t=t.substr(1));let r=t.length-this._scale;return r<=0&&(t=e.stringRepeat(`0`,-r+1)+t,r=t.length-this._scale),n+t.substr(0,r)+`.`+t.substr(r)},BigDecimal.prototype.toNumber=function(){return parseFloat(this.toString())},BigDecimal.prototype.toJSON=function(){return this.toString()};export{BigDecimal as default};
|
package/driver/types/duration.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import e from"../utils.js";import t from"util";import n from"long";const r=e.VIntCoding,i={months:e.allocBuffer(9),days:e.allocBuffer(9),nanoseconds:e.allocBuffer(9)},a=2147483647,o=n.fromInt(1e3),s=o,c=o.multiply(s),l=o.multiply(c),u=n.fromInt(60).multiply(l),d=n.fromInt(60).multiply(u),f=/(\d+)(y|mo|w|d|h|s|ms|us|µs|ns|m)/gi,p=/P((\d+)Y)?((\d+)M)?((\d+)D)?(T((\d+)H)?((\d+)M)?((\d+)S)?)?/,m=/P(\d+)W/,h=/P(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})/;function Duration(e,t,r){this.months=e,this.days=t,this.nanoseconds=typeof r==`number`?n.fromNumber(r):r}Duration.prototype.equals=function(e){return e instanceof Duration?this.months===e.months&&this.days===e.days&&this.nanoseconds.equals(e.nanoseconds):!1},Duration.prototype.toBuffer=function(){let t=r.writeVInt(n.fromNumber(this.months),i.months),a=r.writeVInt(n.fromNumber(this.days),i.days),o=r.writeVInt(this.nanoseconds,i.nanoseconds),s=e.allocBufferUnsafe(t+a+o);i.months.copy(s,0,0,t);let c=t;return i.days.copy(s,c,0,a),c+=a,i.nanoseconds.copy(s,c,0,o),s},Duration.prototype.toString=function(){let e=``;function append(t,n,r){return t===0||t<n?t:(e+=(t/n).toFixed(0)+r,t%n)}function append64(t,r,i){return t.equals(n.ZERO)||t.lessThan(r)?t:(e+=t.divide(r).toString()+i,t.modulo(r))}(this.months<0||this.days<0||this.nanoseconds.isNegative())&&(e=`-`);let t=append(Math.abs(this.months),12,`y`);return append(t,1,`mo`),append(Math.abs(this.days),1,`d`),this.nanoseconds.equals(n.ZERO)||(t=append64(this.nanoseconds.isNegative()?this.nanoseconds.negate():this.nanoseconds,d,`h`),t=append64(t,u,`m`),t=append64(t,l,`s`),t=append64(t,c,`ms`),t=append64(t,s,`us`),append64(t,n.ONE,`ns`)),e},Duration.fromBuffer=function(e){let t={value:0};return new Duration(r.readVInt(e,t).toNumber(),r.readVInt(e,t).toNumber(),r.readVInt(e,t))},Duration.fromString=function(e){let t=e.charAt(0)===`-`,n=t?e.substr(1):e;return n.charAt(0)===`P`?n.charAt(n.length-1)===`W`?parseIso8601WeekFormat(t,n):n.indexOf(`-`)>0?parseIso8601AlternativeFormat(t,n):parseIso8601Format(t,n):parseStandardFormat(t,n)};function parseStandardFormat(e,t){let n=new Builder(e);f.lastIndex=0;let r;for(;(r=f.exec(t))&&r.length<=3;)n.add(r[1],r[2]);return n.build()}function parseIso8601Format(e,n){let r=p.exec(n);if(!r||r[0]!==n)throw TypeError(t.format(`Unable to convert '%s' to a duration`,n));let i=new Builder(e);return r[1]&&i.addYears(r[2]),r[3]&&i.addMonths(r[4]),r[5]&&i.addDays(r[6]),r[7]&&(r[8]&&i.addHours(r[9]),r[10]&&i.addMinutes(r[11]),r[12]&&i.addSeconds(r[13])),i.build()}function parseIso8601WeekFormat(e,n){let r=m.exec(n);if(!r||r[0]!==n)throw TypeError(t.format(`Unable to convert '%s' to a duration`,n));return new Builder(e).addWeeks(r[1]).build()}function parseIso8601AlternativeFormat(e,n){let r=h.exec(n);if(!r||r[0]!==n)throw TypeError(t.format(`Unable to convert '%s' to a duration`,n));return new Builder(e).addYears(r[1]).addMonths(r[2]).addDays(r[3]).addHours(r[4]).addMinutes(r[5]).addSeconds(r[6]).build()}function Builder(e){this._isNegative=e,this._unitIndex=0,this._months=0,this._days=0,this._nanoseconds=n.ZERO,this._addMethods={y:this.addYears,mo:this.addMonths,w:this.addWeeks,d:this.addDays,h:this.addHours,m:this.addMinutes,s:this.addSeconds,ms:this.addMillis,µs:this.addMicros,us:this.addMicros,ns:this.addNanos},this._unitByIndex=[null,`years`,`months`,`weeks`,`days`,`hours`,`minutes`,`seconds`,`milliseconds`,`microseconds`,`nanoseconds`]}Builder.prototype._validateOrder=function(e){if(e===this._unitIndex)throw TypeError(t.format(`Invalid duration. The %s are specified multiple times`,this._getUnitName(e)));if(e<=this._unitIndex)throw TypeError(t.format(`Invalid duration. The %s should be after %s`,this._getUnitName(this._unitIndex),this._getUnitName(e)));this._unitIndex=e},Builder.prototype._validateMonths=function(e,t){this._validate32(e,(a-this._months)/t,`months`)},Builder.prototype._validateDays=function(e,t){this._validate32(e,(a-this._days)/t,`days`)},Builder.prototype._validateNanos=function(e,t){this._validate64(e,n.MAX_VALUE.subtract(this._nanoseconds).divide(t),`nanoseconds`)},Builder.prototype._validate32=function(e,n,r){if(e>n)throw TypeError(t.format(`Invalid duration. The total number of %s must be less or equal to %s`,r,a))},Builder.prototype._validate64=function(e,r,i){if(e.greaterThan(r))throw TypeError(t.format(`Invalid duration. The total number of %s must be less or equal to %s`,i,n.MAX_VALUE.toString()))},Builder.prototype._getUnitName=function(e){let t=this._unitByIndex[+e];if(!t)throw Error(`unknown unit index: `+e);return t},Builder.prototype.add=function(e,n){let r=this._addMethods[n.toLowerCase()];if(!r)throw TypeError(t.format(`Unknown duration symbol '%s'`,n));return r.call(this,e)},Builder.prototype.addYears=function(e){let t=+e;return this._validateOrder(1),this._validateMonths(t,12),this._months+=t*12,this},Builder.prototype.addMonths=function(e){let t=+e;return this._validateOrder(2),this._validateMonths(t,1),this._months+=t,this},Builder.prototype.addWeeks=function(e){let t=+e;return this._validateOrder(3),this._validateDays(t,7),this._days+=t*7,this},Builder.prototype.addDays=function(e){let t=+e;return this._validateOrder(4),this._validateDays(t,1),this._days+=t,this},Builder.prototype.addHours=function(e){let t=typeof e==`string`?n.fromString(e):e;return this._validateOrder(5),this._validateNanos(t,d),this._nanoseconds=this._nanoseconds.add(t.multiply(d)),this},Builder.prototype.addMinutes=function(e){let t=typeof e==`string`?n.fromString(e):e;return this._validateOrder(6),this._validateNanos(t,u),this._nanoseconds=this._nanoseconds.add(t.multiply(u)),this},Builder.prototype.addSeconds=function(e){let t=typeof e==`string`?n.fromString(e):e;return this._validateOrder(7),this._validateNanos(t,l),this._nanoseconds=this._nanoseconds.add(t.multiply(l)),this},Builder.prototype.addMillis=function(e){let t=typeof e==`string`?n.fromString(e):e;return this._validateOrder(8),this._validateNanos(t,c),this._nanoseconds=this._nanoseconds.add(t.multiply(c)),this},Builder.prototype.addMicros=function(e){let t=typeof e==`string`?n.fromString(e):e;return this._validateOrder(9),this._validateNanos(t,s),this._nanoseconds=this._nanoseconds.add(t.multiply(s)),this},Builder.prototype.addNanos=function(e){let t=typeof e==`string`?n.fromString(e):e;return this._validateOrder(10),this._validateNanos(t,n.ONE),this._nanoseconds=this._nanoseconds.add(t),this},Builder.prototype.build=function(){return this._isNegative?new Duration(-this._months,-this._days,this._nanoseconds.negate()):new Duration(this._months,this._days,this._nanoseconds)};export{Duration as default};
|