Class NodeConnectionManager

Hierarchy

  • StartStop
    • NodeConnectionManager

Constructors

Properties

Accessors

Methods

Constructors

  • Constructs the NodeConnectionManager.

    Parameters

    • __namedParameters: {
          authenticateNetworkForwardCallback?: AuthenticateNetworkForwardCallback;
          authenticateNetworkReverseCallback?: AuthenticateNetworkReverseCallback;
          connectionConnectTimeoutTime?: number;
          connectionFindConcurrencyLimit?: number;
          connectionFindLocalTimeoutTime?: number;
          connectionGetClosestLimit?: number;
          connectionHolePunchIntervalTime?: number;
          connectionIdleTimeoutTimeMin?: number;
          connectionIdleTimeoutTimeScale?: number;
          connectionInitialMaxStreamsBidi?: number;
          connectionInitialMaxStreamsUni?: number;
          connectionKeepAliveIntervalTime?: number;
          connectionKeepAliveTimeoutTime?: number;
          keyRing: KeyRing;
          logger?: Logger;
          rpcCallTimeoutTime?: number;
          rpcParserBufferSize?: number;
          tlsConfig: TLSConfig;
      }
      • Optional authenticateNetworkForwardCallback?: AuthenticateNetworkForwardCallback
      • Optional authenticateNetworkReverseCallback?: AuthenticateNetworkReverseCallback
      • Optional connectionConnectTimeoutTime?: number
      • Optional connectionFindConcurrencyLimit?: number
      • Optional connectionFindLocalTimeoutTime?: number
      • Optional connectionGetClosestLimit?: number
      • Optional connectionHolePunchIntervalTime?: number
      • Optional connectionIdleTimeoutTimeMin?: number
      • Optional connectionIdleTimeoutTimeScale?: number
      • Optional connectionInitialMaxStreamsBidi?: number
      • Optional connectionInitialMaxStreamsUni?: number
      • Optional connectionKeepAliveIntervalTime?: number
      • Optional connectionKeepAliveTimeoutTime?: number
      • keyRing: KeyRing
      • Optional logger?: Logger
      • Optional rpcCallTimeoutTime?: number
      • Optional rpcParserBufferSize?: number
      • tlsConfig: TLSConfig

    Returns NodeConnectionManager

Properties

[initLock]: RWLockWriter
activeForwardAuthenticateCalls: Map<string, PromiseCancellable<void>> = ...

Used to track the active authentication RPC calls

activeHolePunchAddresses: Map<string, Semaphore> = ...

Used to rate limit hole punch attempts per IP Address. We use a semaphore to track the number of active hole punch attempts to that address. We Use a semaphore here to allow a limit of 3 attempts per host. To allow concurrent attempts to the same host while limiting the number of different ports. This is mainly used to limit requests to a single target host.

activeHolePunchPs: Map<string, PromiseCancellable<void>> = ...

Used to track active hole punching attempts. Attempts are mapped by a string of ${host}:${port}. This is used to coalesce attempts to a target host and port. Used to cancel and await punch attempts when stopping to prevent orphaned promises.

activeSignalFinalPs: Set<Promise<void>> = ...

Used track the active nodesConnectionSignalFinal attempts and prevent orphaned promises. Used to cancel and await the active nodesConnectionSignalFinal when stopping.

authenticateNetworkForwardCallback: AuthenticateNetworkForwardCallback

Callback used to generate authentication data when making the authentication call

authenticateNetworkReverseCallback: AuthenticateNetworkReverseCallback

Callback used to authenticate the peer when processing an authentication request from the peer

connectionConnectTimeoutTime: number

Time used to establish NodeConnection

connectionFindConcurrencyLimit: number

Alpha constant for kademlia The number of the closest nodes to contact initially

connectionFindLocalTimeoutTime: number

Time used to find a node using findNodeLocal.

connectionGetClosestLimit: number

Default limit used when getting the closest active connections of a node. Defaults to the nodesGraphBucketLimit

connectionHolePunchIntervalTime: number

Initial delay between punch packets, delay doubles each attempt.

connectionIdleTimeoutTimeMin: number

Minimum time to wait to garbage collect un-used node connections.

connectionIdleTimeoutTimeScale: number

Scaling factor to apply to Idle timeout

connectionInitialMaxStreamsBidi: number

Total number of active bidirectional streams that can be created

connectionInitialMaxStreamsUni: number

Total number of active unidirectional streams that can be created

connectionKeepAliveIntervalTime: number

Time interval for sending keep alive messages.

connectionKeepAliveTimeoutTime: number

Time to keep alive node connection.

connections: Map<NodeIdString, ConnectionsEntry> = ...

Data structure to store all NodeConnections. If a connection to a node N does not exist, no entry for N will exist in the map. Alternatively, if a connection is currently being instantiated by some thread, an entry will exist in the map, but only with the lock (no connection object). Once a connection is instantiated, the entry in the map is updated to include the connection object. A nodeIdString is used for the key here since NodeIds can't be used to properly retrieve a value from the map.

keyRing: KeyRing
logger: Logger
quicServer: QUICServer
quicSocket: QUICSocket
rateLimiter: RateLimiter = ...

Used to limit signalling requests on a per-requester basis. This is mainly used to limit a single source node making too many requests through a relay.

rpcCallTimeoutTime: number

Default timeout for RPC handlers

rpcParserBufferSize: number

Max parse buffer size before RPC parser throws a parse error.

rpcServer: RPCServer
tlsConfig: TLSConfig

Accessors

  • get [eventHandled](): ReadonlyWeakSet<Event>
  • Returns ReadonlyWeakSet<Event>

  • get [eventHandlers](): ReadonlyMap<string, Set<EventHandlerInfo>>
  • Returns ReadonlyMap<string, Set<EventHandlerInfo>>

  • get [eventTarget](): EventTarget
  • Returns EventTarget

  • get [handleEventError](): ((evt) => void)
  • Returns ((evt) => void)

      • (evt): void
      • Parameters

        • evt: EventError

        Returns void

  • get [running](): boolean
  • Returns boolean

  • get [statusP](): Promise<Status>
  • Returns Promise<Status>

  • get [status](): Status
  • Returns Status

Methods

  • For usage with withF, to acquire a connection This unique acquire function structure of returning the ResourceAcquire itself is such that we can pass targetNodeId as a parameter (as opposed to an acquire function with no parameters).

    Parameters

    • targetNodeId: NodeId

      Id of target node to communicate with

    • ctx: ContextTimed

    Returns ResourceAcquire<NodeConnection>

    ResourceAcquire Resource API for use in with contexts

  • This is the internal acquireConnection for using connections without authentication. For usage with withF, to acquire a connection This unique acquire function structure of returning the ResourceAcquire itself is such that we can pass targetNodeId as a parameter (as opposed to an acquire function with no parameters).

    Parameters

    • targetNodeId: NodeId

      Id of target node to communicate with

    Returns ResourceAcquire<NodeConnection>

    ResourceAcquire Resource API for use in with contexts

  • Adds connection to the connections map. Preforms some checks and lifecycle hooks. This code is shared between the reverse and forward connection creation.

    Multiple connections can be added for a single NodeId, but the connection with the 'lowest' connectionId will be used. The remaining connections will be left to timeout gracefully.

    Parameters

    Returns ConnectionAndTimer

  • Parameters

    • type: string
    • callback: null | EventListenerOrEventListenerObject
    • Optional options: boolean | AddEventListenerOptions

    Returns void

  • Parameters

    • _ctx: ContextTimed
    • _cancel: ((reason?) => void)
        • (reason?): void
        • Parameters

          • Optional reason: any

          Returns void

    • meta: undefined | Record<string, JSONValue>

    Returns {
        forward: TransformStream<JSONRPCRequest, JSONRPCRequest>;
        reverse: TransformStream<JSONRPCResponse<JSONRPCResponse>, JSONRPCResponse<JSONRPCResponse>>;
    }

    • forward: TransformStream<JSONRPCRequest, JSONRPCRequest>
    • reverse: TransformStream<JSONRPCResponse<JSONRPCResponse>, JSONRPCResponse<JSONRPCResponse>>
  • Creates multiple connections looking for a single node. Once the connection has been established then all pending connections are cancelled. This will return the first connection made or timeout.

    Parameters

    • nodeIds: NodeId[]
    • addresses: [Host, Port][]
    • Optional ctx: Partial<ContextTimedInput>

    Returns PromiseCancellable<NodeConnection>

  • Removes the connection from the connection map and destroys it. If the connectionId is specified then just that connection is destroyed. If no connectionId is specified then all connections for that node are destroyed.

    Parameters

    • targetNodeId: NodeId

      Id of node we are destroying connection to

    • force: boolean

      if true force the connection to end with error.

    • Optional connectionIdTarget: string

      if specified destroys only the desired connection.

    Returns Promise<void>

  • Parameters

    • event: Event

    Returns boolean

  • Returns a list of active connections and their address information.

    Parameters

    • targetNodeId: NodeId
    • limit: number = ...

    Returns ActiveConnectionsInfo[]

  • Gets the existing active connection for the target node

    Parameters

    Returns undefined | ConnectionAndTimer

  • Will determine how long to keep a node around for.

    Timeout is scaled linearly from 1 min to 2 hours based on its bucket. The value will be symmetric for two nodes, they will assign the same timeout for each other.

    Parameters

    • nodeId: NodeId
    • primary: boolean

    Returns number

  • This takes a reverse initiated QUICConnection, wraps it as a NodeConnection and adds it to the connection map.

    Parameters

    • quicConnection: QUICConnection

    Returns void

  • Triggers the destruction of the NodeConnectionManager. Since this is only in response to an underlying problem or close it will force destroy. Dispatched by the EventNodeConnectionManagerError event as the EventNodeConnectionManagerError -> EventNodeConnectionManagerClose event path.

    Returns Promise<void>

  • Dispatches a EventNodeConnectionManagerClose in response to any NodeConnectionManager error event. Will trigger stop of the NodeConnectionManager via the EventNodeConnectionManagerError -> EventNodeConnectionManagerClose event path.

    Returns void

  • Redispatches QUICSocket or QUICServer error events as NodeConnectionManager error events. This should trigger the destruction of the NodeConnection through the EventNodeConnectionError -> EventNodeConnectionClose event path.

    Parameters

    • evt: EventQUICSocketError

    Returns void

  • Handles EventQUICServerConnection events. These are reverser or server peer initiated connections that needs to be handled and added to the connection map.

    Parameters

    • evt: EventQUICServerConnection

    Returns void

  • Handle unexpected stoppage of the QUICServer. Not expected to happen without error, but we have it just in case.

    Parameters

    • _evt: EventQUICServerStopped

    Returns void

  • Handle unexpected stoppage of the QUICSocket. Not expected to happen without error, but we have it just in case.

    Parameters

    • _evt: EventQUICSocketStopped

    Returns void

  • This is used by the NodesConnectionSignalFinal to initiate the hole punch procedure.

    Will validate the message, and initiate hole punching in the background and return immediately. Attempts to the same host and port are coalesced. Attempts to the same host are limited by a semaphore. Active attempts are tracked inside the activeHolePunchPs set and are cancelled and awaited when the NodeConnectionManager stops.

    Parameters

    Returns void

  • This is used by the NodesConnectionSignalInitial to initiate a relay request. Requests can only be relayed to nodes this node is currently connected to.

    Requests made by the same node are rate limited, when the limit has been exceeded the request throws an ErrorNodeConnectionManagerRequestRateExceeded error.

    Active relay attempts are tracked in activeSignalFinalPs and are cancelled and awaited when the NodeConnectionManager stops.

    Parameters

    • sourceNodeId: NodeId

      NodeId of the node making the request. Used for rate limiting.

    • targetNodeId: NodeId

      NodeId of the node that needs to initiate hole punching.

    • address: {
          host: Host;
          port: Port;
      }

      Address the target needs to punch to.

    • requestSignature: string

      base64url encoded signature

    • Optional ctx: Partial<ContextTimedInput>

    Returns Promise<{
        host: Host;
        port: Port;
    }>

  • Open up a port in the NAT by sending packets to the target address. The packets will be sent in an exponential backoff dialing pattern and contain random data.

    This is only ever done used in the reverse direction to open up the nat for the connection to establish from the forward direction.

    This can't know it succeeded, it will continue until timed out or cancelled.

    Parameters

    • host: Host

      host of the target client.

    • port: Port

      port of the target client.

    • Optional ctx: Partial<ContextTimedInput>

    Returns PromiseCancellable<void>

  • Returns a promise that resolves once the connection has authenticated, otherwise it rejects with the authentication failure

    Parameters

    • nodeId: NodeId
    • Optional ctx: Partial<ContextTimedInput>

    Returns Promise<void>

  • Returns {
        address: {
            host: Host;
            hostname: undefined | Hostname;
            port: Port;
        };
        connectionId: string;
        nodeId: NodeId;
        primary: boolean;
        timeout: undefined | number;
        usageCount: number;
    }[]

  • Parameters

    • type: string
    • callback: null | EventListenerOrEventListenerObject
    • Optional options: boolean | EventListenerOptions

    Returns void

  • What doe stop do with force? Figure it out.

    Parameters

    • __namedParameters: {
          force?: boolean;
      } = {}
      • Optional force?: boolean

    Returns Promise<void>

  • Perform some function on another node over the network with a connection. Will either retrieve an existing connection, or create a new one if it doesn't exist. for use with normal arrow function

    Type Parameters

    • T

    Parameters

    • targetNodeId: NodeId

      Id of target node to communicate with

    • ctx: undefined | Partial<ContextTimedInput>
    • f: ((conn) => Promise<T>)

      Function to handle communication

        • (conn): Promise<T>
        • Parameters

          Returns Promise<T>

    Returns Promise<T>

  • Perform some function on another node over the network with a connection. Will either retrieve an existing connection, or create a new one if it doesn't exist. for use with a generator function

    Type Parameters

    • T

    • TReturn

    • TNext

    Parameters

    • targetNodeId: NodeId

      Id of target node to communicate with

    • ctx: undefined | Partial<ContextTimedInput>
    • g: ((conn) => AsyncGenerator<T, TReturn, TNext>)

      Generator function to handle communication

        • (conn): AsyncGenerator<T, TReturn, TNext>
        • Parameters

          Returns AsyncGenerator<T, TReturn, TNext>

    Returns AsyncGenerator<T, TReturn, TNext>

Generated using TypeDoc