@hiero-ledger/sdk
Version:
3 lines (2 loc) • 7.78 kB
JavaScript
import t from"./grpc/GrpcServiceError.js";import e from"./grpc/GrpcStatus.js";import o from"./transaction/List.js";import{encode as n}from"./encoding/hex.js";import r from"./http/HttpError.js";import i from"./Status.js";import s from"./MaxAttemptsOrTimeoutError.js";const a={Finished:"Finished",Retry:"Retry",Error:"Error"},c=/\brst[^0-9a-zA-Z]stream\b/i,h=10;class d{constructor(){this._maxAttempts=10,this._nodeAccountIds=new o,this.transactionNodeIds=[],this._signOnDemand=!1,this._minBackoff=null,this._maxBackoff=8e3,this._operator=null,this._requestTimeout=null,this._grpcDeadline=null,this._logger=null}get nodeAccountIds(){return this._nodeAccountIds.isEmpty?null:(this._nodeAccountIds.setLocked(),this._nodeAccountIds.list)}setNodeAccountIds(t){return this._nodeAccountIds.setList(t).setLocked(),this}get maxRetries(){return console.warn("Deprecated: use maxAttempts instead"),this.maxAttempts}setMaxRetries(t){return console.warn("Deprecated: use setMaxAttempts() instead"),this.setMaxAttempts(t)}get maxAttempts(){return this._maxAttempts}setMaxAttempts(t){return this._maxAttempts=t,this}get grpcDeadline(){return this._grpcDeadline}setGrpcDeadline(t){return this._grpcDeadline=t,this}setMinBackoff(t){if(null==t)throw new Error("minBackoff cannot be null.");if(null!=this._maxBackoff&&t>this._maxBackoff)throw new Error("minBackoff cannot be larger than maxBackoff.");return this._minBackoff=t,this}get minBackoff(){return this._minBackoff}setMaxBackoff(t){if(null==t)throw new Error("maxBackoff cannot be null.");if(null!=this._minBackoff&&t<this._minBackoff)throw new Error("maxBackoff cannot be smaller than minBackoff.");return this._maxBackoff=t,this}get maxBackoff(){return this._maxBackoff}_beforeExecute(t){throw new Error("not implemented")}_makeRequestAsync(){throw new Error("not implemented")}_mapStatusError(t,e,o){throw new Error("not implemented")}_mapResponse(t,e,o){throw new Error("not implemented")}_execute(t,e){throw new Error("not implemented")}_getTransactionId(){throw new Error("not implemented")}_getLogId(){throw new Error("not implemented")}_requestToBytes(t){throw new Error("not implemented")}_responseToBytes(t){throw new Error("not implemented")}_shouldRetry(t,e){throw new Error("not implemented")}_shouldRetryExceptionally(o){return!(o instanceof t)||(o.status._code===e.Timeout._code||o.status._code===e.DeadlineExceeded._code||o.status._code===e.Unavailable._code||o.status._code===e.ResourceExhausted._code||o.status._code===e.GrpcWeb._code||o.status._code===e.Internal._code&&c.test(o.message))}_setOperatorWith(t,e,o){return this._operator={transactionSigner:o,accountId:t,publicKey:e},this}async executeWithSigner(t){return t.call(this)}isBatchedAndNotBatchTransaction(){return!1}async execute(o,c){const h=null!=o.network["127.0.0.1:50211"];if(this.isBatchedAndNotBatchTransaction())throw new Error("Cannot execute batchified transaction outside of BatchTransaction");this._logger=null==this._logger?null!=o._logger?o._logger:null:this._logger,null==this._requestTimeout&&(this._requestTimeout=null!=c?c:o.requestTimeout),null==this._grpcDeadline&&(this._grpcDeadline=o.grpcDeadline),await this._beforeExecute(o),null==this._maxBackoff&&(this._maxBackoff=o.maxBackoff),null==this._minBackoff&&(this._minBackoff=o.minBackoff);const d=Date.now();let g=null;const _=h?1e3:o._maxAttempts??this._maxAttempts;if(this.transactionNodeIds.length){const t=this._nodeAccountIds.list.map(t=>t.toString());if(!this.transactionNodeIds.some(e=>t.includes(e))){const e=t.length>2?`${t.slice(0,2).join(", ")} ...`:t.join(", "),o=1===t.length;throw new Error(`Attempting to execute a transaction against node${o?"":"s"} ${e}, which ${o?"is":"are"} not included in the Client's node list. Please review your Client configuration.`)}}for(let c=1;c<=_;c+=1){if(null!=this._requestTimeout&&d+this._requestTimeout<=Date.now())throw new s("timeout exceeded",this._nodeAccountIds.isEmpty?"No node account ID set":this._nodeAccountIds.current.toString());let m,f;if(this._nodeAccountIds.isEmpty?(f=o._network.getNode(),m=f.accountId,this._nodeAccountIds.setList([m])):(m=this._nodeAccountIds.current,f=o._network.getNode(m)),null==f)throw new Error(`NodeAccountId not recognized: ${m.toString()}`);if(this.transactionNodeIds.length){if(!this.transactionNodeIds.includes(m.toString())){console.error(`Attempting to execute a transaction against node ${m.toString()}, which is not included in the Client's node list. Please review your Client configuration.`),this._nodeAccountIds.advance();continue}}const p=this._getLogId();this._logger&&this._logger.debug(`[${p}] Node AccountID: ${f.accountId.toString()}, IP: ${f.address.toString()}`);const w=f.getChannel();null!=this._grpcDeadline&&w.setGrpcDeadline(this._grpcDeadline);const x=await this._makeRequestAsync();let k;if(!f.isHealthy()){const t=this._nodeAccountIds.index===this._nodeAccountIds.list.length-1;if(u(x)||h){await l(h,c,this._minBackoff,this._maxBackoff);continue}if(t||this._nodeAccountIds.length<=1)throw new Error(`Network connectivity issue: All nodes are unhealthy. Original node list: ${this._nodeAccountIds.list.join(", ")}`);this._logger&&this._logger.debug(`[${p}] Node is not healthy, trying the next node.`),this._nodeAccountIds.advance();continue}this._nodeAccountIds.advance();try{const o=[];null!=this._grpcDeadline&&o.push(new Promise((o,n)=>setTimeout(()=>n(new t(e.DeadlineExceeded)),this._grpcDeadline))),this._logger&&this._logger.trace(`[${this._getLogId()}] sending protobuf ${n(this._requestToBytes(x))}`),o.push(this._execute(w,x)),k=await Promise.race(o)}catch(e){const n=t._fromResponse(e);if(g=n,this._logger&&this._logger.debug(`[${p}] received error ${JSON.stringify(n)}`),(n instanceof t||n instanceof r)&&this._shouldRetryExceptionally(n)&&c<=_){this._logger&&this._logger.debug(`[${this._getLogId()}] node with accountId: ${f.accountId.toString()} and proxy IP: ${f.address.toString()} is unhealthy`),o._network.increaseBackoff(f);continue}throw e}this._logger&&this._logger.trace(`[${this._getLogId()}] sending protobuf ${n(this._responseToBytes(k))}`),o._network.decreaseBackoff(f);const[I,A]=this._shouldRetry(x,k);switch(I.toString()!==i.Ok.toString()&&I.toString()!==i.Success.toString()&&(g=I),A){case a.Retry:if(I===i.InvalidNodeAccount){this._logger&&this._logger.debug(`[${this._getLogId()}] node with accountId: ${f.accountId.toString()} and proxy IP: ${f.address.toString()} has invalid node account ID, marking as unhealthy and updating network`),o._network.increaseBackoff(f);try{o.mirrorNetwork.length>0?await o.updateNetwork():this._logger&&this._logger.warn("Cannot update address book: no mirror network configured. Retrying with existing network configuration.")}catch(t){if(this._logger){const e=t instanceof Error?t.message:String(t);this._logger.trace(`failed to update client address book after INVALID_NODE_ACCOUNT_ID: ${e}`)}}}await l(h,c,this._minBackoff,this._maxBackoff);continue;case a.Finished:return this._mapResponse(k,m,x);case a.Error:throw this._mapStatusError(x,k,m);default:throw new Error("(BUG) non-exhaustive switch statement for `ExecutionState`")}}throw new s(`max attempts of ${_.toString()} was reached for request with last error being: ${null!=g?g.toString():""}`,this._nodeAccountIds.current.toString())}toBytes(){throw new Error("not implemented")}setLogger(t){return this._logger=t,this}get logger(){return this._logger}}function u(t){return"object"==typeof t&&null!==t&&("transactionGetReceipt"in t||"transactionGetRecord"in t)}function l(t,e,o,n){if(t)return new Promise(t=>setTimeout(t,o));const r=Math.min(Math.floor(o*Math.pow(2,e)),n);return new Promise(t=>setTimeout(t,r))}export{h as DEFAULT_MAX_ATTEMPTS,a as ExecutionState,c as RST_STREAM,d as default};
//# sourceMappingURL=Executable.js.map