@libp2p/ping 2.0.1 → 2.0.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/dist/index.min.js +1 -1
- package/dist/src/ping.d.ts.map +1 -1
- package/dist/src/ping.js +22 -29
- package/dist/src/ping.js.map +1 -1
- package/package.json +7 -9
- package/src/ping.ts +24 -45
package/dist/index.min.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2PPing = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var Libp2PPing=(()=>{var A=Object.defineProperty;var W=Object.getOwnPropertyDescriptor;var H=Object.getOwnPropertyNames;var J=Object.prototype.hasOwnProperty;var Q=(e,t)=>{for(var r in t)A(e,r,{get:t[r],enumerable:!0})},Y=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of H(t))!J.call(e,o)&&o!==r&&A(e,o,{get:()=>t[o],enumerable:!(n=W(t,o))||n.enumerable});return e};var Z=e=>Y(A({},"__esModule",{value:!0}),e);var pt={};Q(pt,{PING_PROTOCOL:()=>j,ping:()=>lt});var b=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var g=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}};var E=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}},x=class extends Error{static name="ProtocolError";constructor(t="Protocol error"){super(t),this.name="ProtocolError"}},w=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}};function U(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}var d=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var bt=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var gt={}.toString;function k(e=32){if(d&&typeof d.getRandomValues=="function")return d.getRandomValues(new Uint8Array(e));if(d&&typeof d.randomBytes=="function")return d.randomBytes(e);throw new Error("crypto.getRandomValues must be defined")}function O(e){if(isNaN(e)||e<=0)throw new g("random bytes length must be a Number bigger than 0");return k(e)}function tt(e){return e[Symbol.asyncIterator]!=null}function et(e){if(tt(e))return(async()=>{for await(let t of e)return t})();for(let t of e)return t}var R=et;function I(){let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e}var L=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||t-1&t)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},h=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new L(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let r=this.head;this.head=r.next=new L(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var _=class extends Error{type;code;constructor(t,r){super(t??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function S(e={}){return rt(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},e)}function rt(e,t){t=t??{};let r=t.onEnd,n=new h,o,i,a,u=I(),c=async()=>{try{return n.isEmpty()?a?{done:!0}:await new Promise((s,p)=>{i=y=>{i=null,n.push(y);try{s(e(n))}catch(f){p(f)}return o}}):e(n)}finally{n.isEmpty()&&queueMicrotask(()=>{u.resolve(),u=I()})}},l=s=>i!=null?i(s):(n.push(s),o),T=s=>(n=new h,i!=null?i({error:s}):(n.push({error:s}),o)),N=s=>{if(a)return o;if(t?.objectMode!==!0&&s?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:s})},P=s=>a?o:(a=!0,s!=null?T(s):l({done:!0})),$=()=>(n=new h,P(),{done:!0}),q=s=>(P(s),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:$,throw:q,push:N,end:P,get readableLength(){return n.size},onEmpty:async s=>{let p=s?.signal;if(p?.throwIfAborted(),n.isEmpty())return;let y,f;p!=null&&(y=new Promise((dt,K)=>{f=()=>{K(new _)},p.addEventListener("abort",f)}));try{await Promise.race([u.promise,y])}finally{f!=null&&p!=null&&p?.removeEventListener("abort",f)}}},r==null)return o;let m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(s){return m.throw(s),r!=null&&(r(s),r=void 0),{done:!0}},return(){return m.return(),r!=null&&(r(),r=void 0),{done:!0}},push:N,end(s){return m.end(s),r!=null&&(r(s),r=void 0),o},get readableLength(){return m.readableLength},onEmpty:s=>m.onEmpty(s)},o}function nt(e){return e[Symbol.asyncIterator]!=null}function ot(...e){let t=[];for(let r of e)nt(r)||t.push(r);return t.length===e.length?function*(){for(let r of t)yield*r}():async function*(){let r=S({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(e.map(async n=>{for await(let o of n)r.push(o)})),r.end()}catch(n){r.end(n)}}),yield*r}()}var B=ot;function C(e,...t){if(e==null)throw new Error("Empty pipeline");if(M(e)){let n=e;e=()=>n.source}else if(z(e)||D(e)){let n=e;e=()=>n}let r=[e,...t];if(r.length>1&&M(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let n=1;n<r.length-1;n++)M(r[n])&&(r[n]=it(r[n]));return st(...r)}var st=(...e)=>{let t;for(;e.length>0;)t=e.shift()(t);return t},D=e=>e?.[Symbol.asyncIterator]!=null,z=e=>e?.[Symbol.iterator]!=null,M=e=>e==null?!1:e.sink!=null&&e.source!=null,it=e=>t=>{let r=e.sink(t);if(r?.then!=null){let n=S({objectMode:!0});r.then(()=>{n.end()},a=>{n.end(a)});let o,i=e.source;if(D(i))o=async function*(){yield*i,n.end()};else if(z(i))o=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return B(n,o())}return e.source};var j="/ipfs/ping/1.0.0";var F="1.0.0",V="ping",X="ipfs";var v=class{protocol;components;started;timeout;maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;log;constructor(t,r={}){this.components=t,this.log=t.logger.forComponent("libp2p:ping"),this.started=!1,this.protocol=`/${r.protocolPrefix??X}/${V}/${F}`,this.timeout=r.timeout??1e4,this.maxInboundStreams=r.maxInboundStreams??2,this.maxOutboundStreams=r.maxOutboundStreams??1,this.runOnLimitedConnection=r.runOnLimitedConnection??!0,this.handleMessage=this.handleMessage.bind(this)}[Symbol.toStringTag]="@libp2p/ping";async start(){await this.components.registrar.handle(this.protocol,this.handleMessage,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}isStarted(){return this.started}handleMessage(t){this.log("incoming ping from %p",t.connection.remotePeer);let{stream:r}=t,n=Date.now();AbortSignal.timeout(this.timeout).addEventListener("abort",()=>{r?.abort(new w("ping timeout"))}),C(r,async function*(i){let a=0;for await(let u of i){if(a+=u.byteLength,a>32){r?.abort(new E("Too much data received"));return}yield u}},r).catch(i=>{this.log.error("incoming ping from %p failed with error",t.connection.remotePeer,i),r?.abort(i)}).finally(()=>{let i=Date.now()-n;this.log("incoming ping from %p complete in %dms",t.connection.remotePeer,i)})}async ping(t,r={}){this.log("pinging %p",t);let n=Date.now(),o=O(32),i=await this.components.connectionManager.openConnection(t,r),a,u=()=>{};if(r.signal==null){let c=AbortSignal.timeout(this.timeout);r={...r,signal:c}}try{a=await i.newStream(this.protocol,{...r,runOnLimitedConnection:this.runOnLimitedConnection}),u=()=>{a?.abort(new b)},r.signal?.addEventListener("abort",u,{once:!0});let c=await C([o],a,async T=>R(T)),l=Date.now()-n;if(c==null)throw new x(`Did not receive a ping ack after ${l}ms`);if(!U(o,c.subarray()))throw new x(`Received wrong ping ack after ${l}ms`);return this.log("ping %p complete in %dms",i.remotePeer,l),l}catch(c){throw this.log.error("error while pinging %p",i.remotePeer,c),a?.abort(c),c}finally{r.signal?.removeEventListener("abort",u),a!=null&&await a.close()}}};function lt(e={}){return t=>new v(t,e)}return Z(pt);})();
|
|
2
|
+
"use strict";var Libp2PPing=(()=>{var S=Object.defineProperty;var G=Object.getOwnPropertyDescriptor;var $=Object.getOwnPropertyNames;var W=Object.prototype.hasOwnProperty;var H=(o,t)=>{for(var e in t)S(o,e,{get:t[e],enumerable:!0})},K=(o,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of $(t))!W.call(o,n)&&n!==e&&S(o,n,{get:()=>t[n],enumerable:!(r=G(t,n))||r.enumerable});return o};var z=o=>K(S({},"__esModule",{value:!0}),o);var tt={};H(tt,{PING_PROTOCOL:()=>F,ping:()=>Q});var y=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}};var g=class extends Error{static name="ProtocolError";constructor(t="Protocol error"){super(t),this.name="ProtocolError"}},x=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}};function E(o,t){if(o===t)return!0;if(o.byteLength!==t.byteLength)return!1;for(let e=0;e<o.byteLength;e++)if(o[e]!==t[e])return!1;return!0}var m=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var it=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var at={}.toString;function C(o=32){if(m&&typeof m.getRandomValues=="function")return m.getRandomValues(new Uint8Array(o));if(m&&typeof m.randomBytes=="function")return m.randomBytes(o);throw new Error("crypto.getRandomValues must be defined")}function p(o=0){return new Uint8Array(o)}function b(o=0){return new Uint8Array(o)}function L(o){if(isNaN(o)||o<=0)throw new y("random bytes length must be a Number bigger than 0");return C(o)}function I(o,t){t==null&&(t=o.reduce((n,s)=>n+s.length,0));let e=b(t),r=0;for(let n of o)e.set(n,r),r+=n.length;return e}function d(){let o={};return o.promise=new Promise((t,e)=>{o.resolve=t,o.reject=e}),o}var O=class extends Error{type;code;constructor(t,e,r){super(t??"The operation was aborted"),this.type="aborted",this.name=r??"AbortError",this.code=e??"ABORT_ERR"}};async function B(o,t,e){if(t==null)return o;if(t.aborted)return Promise.reject(new O(e?.errorMessage,e?.errorCode,e?.errorName));let r,n=new O(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([o,new Promise((s,i)=>{r=()=>{i(n)},t.addEventListener("abort",r)})])}finally{r!=null&&t.removeEventListener("abort",r)}}var T=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=d(),this.haveNext=d()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=d(),t}async throw(t){return this.ended=!0,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return await this._push(void 0),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=d(),await B(this.readNext.promise,e?.signal,e)}};function M(){return new T}var k=Symbol.for("@achingbrain/uint8arraylist");function V(o,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let r of o){let n=e+r.byteLength;if(t<n)return{buf:r,index:t-e};e=n}throw new RangeError("index is out of bounds")}function U(o){return!!o?.[k]}var w=class o{bufs;length;[k]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let r of t)if(r instanceof Uint8Array)e+=r.byteLength,this.bufs.push(r);else if(U(r))e+=r.byteLength,this.bufs.push(...r.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let r of t.reverse())if(r instanceof Uint8Array)e+=r.byteLength,this.bufs.unshift(r);else if(U(r))e+=r.byteLength,this.bufs.unshift(...r.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=V(this.bufs,t);return e.buf[e.index]}set(t,e){let r=V(this.bufs,t);r.buf[r.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let r=0;r<t.length;r++)this.set(e+r,t[r]);else if(U(t))for(let r=0;r<t.length;r++)this.set(e+r,t.get(r));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:r,length:n}=this._subList(t,e);return I(r,n)}subarray(t,e){let{bufs:r,length:n}=this._subList(t,e);return r.length===1?r[0]:I(r,n)}sublist(t,e){let{bufs:r,length:n}=this._subList(t,e),s=new o;return s.length=n,s.bufs=[...r],s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let r=[],n=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=n,c=a+i.byteLength;if(n=c,t>=c)continue;let f=t>=a&&t<c,l=e>a&&e<=c;if(f&&l){if(t===a&&e===c){r.push(i);break}let u=t-a;r.push(i.subarray(u,u+(e-t)));break}if(f){if(t===0){r.push(i);continue}r.push(i.subarray(t-a));continue}if(l){if(e===c){r.push(i);break}r.push(i.subarray(0,e-a));break}r.push(i)}return{bufs:r,length:e-t}}indexOf(t,e=0){if(!U(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let r=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let n=r.byteLength;if(n===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let u=0;u<s;u++)i[u]=-1;for(let u=0;u<n;u++)i[r[u]]=u;let a=i,c=this.byteLength-r.byteLength,f=r.byteLength-1,l;for(let u=e;u<=c;u+=l){l=0;for(let h=f;h>=0;h--){let D=this.get(u+h);if(r[h]!==D){l=Math.max(1,h-a[D]);break}}if(l===0)return u}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let r=b(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,e),this.write(r,t)}getInt16(t,e){let r=this.subarray(t,t+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,e)}setInt16(t,e,r){let n=p(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt16(0,e,r),this.write(n,t)}getInt32(t,e){let r=this.subarray(t,t+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,e)}setInt32(t,e,r){let n=p(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt32(0,e,r),this.write(n,t)}getBigInt64(t,e){let r=this.subarray(t,t+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,e)}setBigInt64(t,e,r){let n=p(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigInt64(0,e,r),this.write(n,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let r=b(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,e),this.write(r,t)}getUint16(t,e){let r=this.subarray(t,t+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,e)}setUint16(t,e,r){let n=p(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(0,e,r),this.write(n,t)}getUint32(t,e){let r=this.subarray(t,t+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,e)}setUint32(t,e,r){let n=p(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint32(0,e,r),this.write(n,t)}getBigUint64(t,e){let r=this.subarray(t,t+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,e)}setBigUint64(t,e,r){let n=p(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigUint64(0,e,r),this.write(n,t)}getFloat32(t,e){let r=this.subarray(t,t+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,e)}setFloat32(t,e,r){let n=p(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat32(0,e,r),this.write(n,t)}getFloat64(t,e){let r=this.subarray(t,t+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,e)}setFloat64(t,e,r){let n=p(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat64(0,e,r),this.write(n,t)}equals(t){if(t==null||!(t instanceof o)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!E(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let r=new o;return r.bufs=t,e==null&&(e=t.reduce((n,s)=>n+s.byteLength,0)),r.length=e,r}};var v=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var P=class extends Error{code;constructor(t,e){super(t),this.code=e}},N=class extends P{type;constructor(t){super(t,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function _(o,t){let e=M();o.sink(e).catch(async i=>{await e.end(i)}),o.sink=async i=>{for await(let a of i)await e.push(a);await e.end()};let r=o.source;o.source[Symbol.iterator]!=null?r=o.source[Symbol.iterator]():o.source[Symbol.asyncIterator]!=null&&(r=o.source[Symbol.asyncIterator]());let n=new w;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,f=new Promise((l,u)=>{c=()=>{u(new N("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:u,value:h}=await Promise.race([r.next(),f]);return u===!0?new w:h}for(;n.byteLength<i;){let{value:u,done:h}=await Promise.race([r.next(),f]);if(h===!0)throw new v("unexpected end of input");n.append(u)}let l=n.sublist(0,i);return n.consume(i),l}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await e.push(i,a):await e.push(i.subarray(),a)},unwrap:()=>{if(n.byteLength>0){let i=o.source;o.source=async function*(){t?.yieldBytes===!1?yield n:yield*n,yield*i}()}return o}}}var F="/ipfs/ping/1.0.0";var j="1.0.0",X="ping",q="ipfs";var A=class{protocol;components;started;timeout;maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;log;constructor(t,e={}){this.components=t,this.log=t.logger.forComponent("libp2p:ping"),this.started=!1,this.protocol=`/${e.protocolPrefix??q}/${X}/${j}`,this.timeout=e.timeout??1e4,this.maxInboundStreams=e.maxInboundStreams??2,this.maxOutboundStreams=e.maxOutboundStreams??1,this.runOnLimitedConnection=e.runOnLimitedConnection??!0,this.handleMessage=this.handleMessage.bind(this)}[Symbol.toStringTag]="@libp2p/ping";async start(){await this.components.registrar.handle(this.protocol,this.handleMessage,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}isStarted(){return this.started}handleMessage(t){this.log("incoming ping from %p",t.connection.remotePeer);let{stream:e}=t,r=Date.now(),n=_(e);Promise.resolve().then(async()=>{for(;;){let s=AbortSignal.timeout(this.timeout);s.addEventListener("abort",()=>{e?.abort(new x("ping timeout"))});let i=await n.read(32,{signal:s});await n.write(i,{signal:s})}}).catch(s=>{this.log.error("incoming ping from %p failed with error",t.connection.remotePeer,s),e?.abort(s)}).finally(()=>{let s=Date.now()-r;this.log("incoming ping from %p complete in %dms",t.connection.remotePeer,s)})}async ping(t,e={}){this.log("pinging %p",t);let r=Date.now(),n=L(32),s=await this.components.connectionManager.openConnection(t,e),i;if(e.signal==null){let a=AbortSignal.timeout(this.timeout);e={...e,signal:a}}try{i=await s.newStream(this.protocol,{...e,runOnLimitedConnection:this.runOnLimitedConnection});let a=_(i),[,c]=await Promise.all([a.write(n,e),a.read(32,e)]),f=Date.now()-r;if(!E(n,c.subarray()))throw new g(`Received wrong ping ack after ${f}ms`);return this.log("ping %p complete in %dms",s.remotePeer,f),f}catch(a){throw this.log.error("error while pinging %p",s.remotePeer,a),i?.abort(a),a}finally{i!=null&&await i.close(e)}}};function Q(o={}){return t=>new A(t,o)}return z(tt);})();
|
|
3
3
|
/*! Bundled license information:
|
|
4
4
|
|
|
5
5
|
@noble/hashes/esm/utils.js:
|
package/dist/src/ping.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ping.d.ts","sourceRoot":"","sources":["../../src/ping.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"ping.d.ts","sourceRoot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to';
|
|
2
|
-
import {
|
|
3
|
-
import
|
|
4
|
-
import { pipe } from 'it-pipe';
|
|
2
|
+
import { ProtocolError, TimeoutError } from '@libp2p/interface';
|
|
3
|
+
import { byteStream } from 'it-byte-stream';
|
|
5
4
|
import { equals as uint8ArrayEquals } from 'uint8arrays/equals';
|
|
6
5
|
import { PROTOCOL_PREFIX, PROTOCOL_NAME, PING_LENGTH, PROTOCOL_VERSION, TIMEOUT, MAX_INBOUND_STREAMS, MAX_OUTBOUND_STREAMS } from './constants.js';
|
|
7
6
|
export class PingService {
|
|
@@ -47,21 +46,21 @@ export class PingService {
|
|
|
47
46
|
this.log('incoming ping from %p', data.connection.remotePeer);
|
|
48
47
|
const { stream } = data;
|
|
49
48
|
const start = Date.now();
|
|
50
|
-
const
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
49
|
+
const bytes = byteStream(stream);
|
|
50
|
+
Promise.resolve().then(async () => {
|
|
51
|
+
while (true) {
|
|
52
|
+
const signal = AbortSignal.timeout(this.timeout);
|
|
53
|
+
signal.addEventListener('abort', () => {
|
|
54
|
+
stream?.abort(new TimeoutError('ping timeout'));
|
|
55
|
+
});
|
|
56
|
+
const buf = await bytes.read(PING_LENGTH, {
|
|
57
|
+
signal
|
|
58
|
+
});
|
|
59
|
+
await bytes.write(buf, {
|
|
60
|
+
signal
|
|
61
|
+
});
|
|
63
62
|
}
|
|
64
|
-
}
|
|
63
|
+
})
|
|
65
64
|
.catch(err => {
|
|
66
65
|
this.log.error('incoming ping from %p failed with error', data.connection.remotePeer, err);
|
|
67
66
|
stream?.abort(err);
|
|
@@ -80,7 +79,6 @@ export class PingService {
|
|
|
80
79
|
const data = randomBytes(PING_LENGTH);
|
|
81
80
|
const connection = await this.components.connectionManager.openConnection(peer, options);
|
|
82
81
|
let stream;
|
|
83
|
-
let onAbort = () => { };
|
|
84
82
|
if (options.signal == null) {
|
|
85
83
|
const signal = AbortSignal.timeout(this.timeout);
|
|
86
84
|
options = {
|
|
@@ -93,16 +91,12 @@ export class PingService {
|
|
|
93
91
|
...options,
|
|
94
92
|
runOnLimitedConnection: this.runOnLimitedConnection
|
|
95
93
|
});
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
const result = await pipe([data], stream, async (source) => first(source));
|
|
94
|
+
const bytes = byteStream(stream);
|
|
95
|
+
const [, result] = await Promise.all([
|
|
96
|
+
bytes.write(data, options),
|
|
97
|
+
bytes.read(PING_LENGTH, options)
|
|
98
|
+
]);
|
|
102
99
|
const ms = Date.now() - start;
|
|
103
|
-
if (result == null) {
|
|
104
|
-
throw new ProtocolError(`Did not receive a ping ack after ${ms}ms`);
|
|
105
|
-
}
|
|
106
100
|
if (!uint8ArrayEquals(data, result.subarray())) {
|
|
107
101
|
throw new ProtocolError(`Received wrong ping ack after ${ms}ms`);
|
|
108
102
|
}
|
|
@@ -115,9 +109,8 @@ export class PingService {
|
|
|
115
109
|
throw err;
|
|
116
110
|
}
|
|
117
111
|
finally {
|
|
118
|
-
options.signal?.removeEventListener('abort', onAbort);
|
|
119
112
|
if (stream != null) {
|
|
120
|
-
await stream.close();
|
|
113
|
+
await stream.close(options);
|
|
121
114
|
}
|
|
122
115
|
}
|
|
123
116
|
}
|
package/dist/src/ping.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ping.js","sourceRoot":"","sources":["../../src/ping.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAC5C,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"ping.js","sourceRoot":"","sources":["../../src/ping.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAC5C,OAAO,EAAE,aAAa,EA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
|
|
5
5
|
"license": "Apache-2.0 OR MIT",
|
|
6
6
|
"homepage": "https://github.com/libp2p/js-libp2p/tree/main/packages/protocol-ping#readme",
|
|
@@ -50,19 +50,17 @@
|
|
|
50
50
|
"doc-check": "aegir doc-check"
|
|
51
51
|
},
|
|
52
52
|
"dependencies": {
|
|
53
|
-
"@libp2p/crypto": "^5.0.
|
|
54
|
-
"@libp2p/interface": "^2.0
|
|
55
|
-
"@libp2p/interface-internal": "^2.0.
|
|
53
|
+
"@libp2p/crypto": "^5.0.2",
|
|
54
|
+
"@libp2p/interface": "^2.1.0",
|
|
55
|
+
"@libp2p/interface-internal": "^2.0.2",
|
|
56
56
|
"@multiformats/multiaddr": "^12.2.3",
|
|
57
|
-
"it-
|
|
58
|
-
"it-pipe": "^3.0.1",
|
|
57
|
+
"it-byte-stream": "^1.1.0",
|
|
59
58
|
"uint8arrays": "^5.1.0"
|
|
60
59
|
},
|
|
61
60
|
"devDependencies": {
|
|
62
|
-
"@libp2p/logger": "^5.0.
|
|
63
|
-
"@libp2p/peer-id": "^5.0.
|
|
61
|
+
"@libp2p/logger": "^5.0.2",
|
|
62
|
+
"@libp2p/peer-id": "^5.0.2",
|
|
64
63
|
"aegir": "^44.0.1",
|
|
65
|
-
"it-byte-stream": "^1.0.10",
|
|
66
64
|
"it-pair": "^2.0.6",
|
|
67
65
|
"p-defer": "^4.0.1",
|
|
68
66
|
"sinon-ts": "^2.0.0"
|
package/src/ping.ts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { randomBytes } from '@libp2p/crypto'
|
|
2
|
-
import {
|
|
3
|
-
import
|
|
4
|
-
import { pipe } from 'it-pipe'
|
|
2
|
+
import { ProtocolError, TimeoutError } from '@libp2p/interface'
|
|
3
|
+
import { byteStream } from 'it-byte-stream'
|
|
5
4
|
import { equals as uint8ArrayEquals } from 'uint8arrays/equals'
|
|
6
5
|
import { PROTOCOL_PREFIX, PROTOCOL_NAME, PING_LENGTH, PROTOCOL_VERSION, TIMEOUT, MAX_INBOUND_STREAMS, MAX_OUTBOUND_STREAMS } from './constants.js'
|
|
7
6
|
import type { PingServiceComponents, PingServiceInit, PingService as PingServiceInterface } from './index.js'
|
|
@@ -60,37 +59,29 @@ export class PingService implements Startable, PingServiceInterface {
|
|
|
60
59
|
|
|
61
60
|
const { stream } = data
|
|
62
61
|
const start = Date.now()
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
62
|
+
const bytes = byteStream(stream)
|
|
63
|
+
|
|
64
|
+
Promise.resolve().then(async () => {
|
|
65
|
+
while (true) {
|
|
66
|
+
const signal = AbortSignal.timeout(this.timeout)
|
|
67
|
+
signal.addEventListener('abort', () => {
|
|
68
|
+
stream?.abort(new TimeoutError('ping timeout'))
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
const buf = await bytes.read(PING_LENGTH, {
|
|
72
|
+
signal
|
|
73
|
+
})
|
|
74
|
+
await bytes.write(buf, {
|
|
75
|
+
signal
|
|
76
|
+
})
|
|
77
|
+
}
|
|
67
78
|
})
|
|
68
|
-
|
|
69
|
-
void pipe(
|
|
70
|
-
stream,
|
|
71
|
-
async function * (source) {
|
|
72
|
-
let received = 0
|
|
73
|
-
|
|
74
|
-
for await (const buf of source) {
|
|
75
|
-
received += buf.byteLength
|
|
76
|
-
|
|
77
|
-
if (received > PING_LENGTH) {
|
|
78
|
-
stream?.abort(new InvalidMessageError('Too much data received'))
|
|
79
|
-
return
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
yield buf
|
|
83
|
-
}
|
|
84
|
-
},
|
|
85
|
-
stream
|
|
86
|
-
)
|
|
87
79
|
.catch(err => {
|
|
88
80
|
this.log.error('incoming ping from %p failed with error', data.connection.remotePeer, err)
|
|
89
81
|
stream?.abort(err)
|
|
90
82
|
})
|
|
91
83
|
.finally(() => {
|
|
92
84
|
const ms = Date.now() - start
|
|
93
|
-
|
|
94
85
|
this.log('incoming ping from %p complete in %dms', data.connection.remotePeer, ms)
|
|
95
86
|
})
|
|
96
87
|
}
|
|
@@ -105,7 +96,6 @@ export class PingService implements Startable, PingServiceInterface {
|
|
|
105
96
|
const data = randomBytes(PING_LENGTH)
|
|
106
97
|
const connection = await this.components.connectionManager.openConnection(peer, options)
|
|
107
98
|
let stream: Stream | undefined
|
|
108
|
-
let onAbort = (): void => {}
|
|
109
99
|
|
|
110
100
|
if (options.signal == null) {
|
|
111
101
|
const signal = AbortSignal.timeout(this.timeout)
|
|
@@ -122,25 +112,15 @@ export class PingService implements Startable, PingServiceInterface {
|
|
|
122
112
|
runOnLimitedConnection: this.runOnLimitedConnection
|
|
123
113
|
})
|
|
124
114
|
|
|
125
|
-
|
|
126
|
-
stream?.abort(new AbortError())
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
// make stream abortable
|
|
130
|
-
options.signal?.addEventListener('abort', onAbort, { once: true })
|
|
115
|
+
const bytes = byteStream(stream)
|
|
131
116
|
|
|
132
|
-
const result = await
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
)
|
|
117
|
+
const [, result] = await Promise.all([
|
|
118
|
+
bytes.write(data, options),
|
|
119
|
+
bytes.read(PING_LENGTH, options)
|
|
120
|
+
])
|
|
137
121
|
|
|
138
122
|
const ms = Date.now() - start
|
|
139
123
|
|
|
140
|
-
if (result == null) {
|
|
141
|
-
throw new ProtocolError(`Did not receive a ping ack after ${ms}ms`)
|
|
142
|
-
}
|
|
143
|
-
|
|
144
124
|
if (!uint8ArrayEquals(data, result.subarray())) {
|
|
145
125
|
throw new ProtocolError(`Received wrong ping ack after ${ms}ms`)
|
|
146
126
|
}
|
|
@@ -155,9 +135,8 @@ export class PingService implements Startable, PingServiceInterface {
|
|
|
155
135
|
|
|
156
136
|
throw err
|
|
157
137
|
} finally {
|
|
158
|
-
options.signal?.removeEventListener('abort', onAbort)
|
|
159
138
|
if (stream != null) {
|
|
160
|
-
await stream.close()
|
|
139
|
+
await stream.close(options)
|
|
161
140
|
}
|
|
162
141
|
}
|
|
163
142
|
}
|