npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

instant-relay

v1.0.0

Published

An opinionated library for asynchronous communication between nodes. Focuses on backpressure management, simplicity, performance.

Downloads

11

Readme

instant-relay

instant-relay is an opinionated library for asynchronous communication between nodes in non-hierarchical sets. Each registered node can send (one-to-one) or broadcast (one-to-many). It is written in TypeScript for Node.js, with the following priorities in mind:

  1. Backpressure management and prevention of accidental blocking behavior, addressed by decoupling message delivery from message handling and managing backpressure upon delivery.
  2. Simplicity and ease of debugging, addressed by a small codebase (~ 300 LoCs in total) and few dependencies (1 direct, 2 in total).
  3. Performance, addressed by selecting fast data structure implementations and reducing the overall number of allocations per handled message.

instant-relay was born out of the convergence of previous projects in the space of multi-protocol gateways for the IoT sector.

How to use

A new relay is created through the InstantRelay class, which requires a union of possible message types as a type argument.

New nodes can be added to an instance of the InstantRelay class by providing dedicated factory functions implementing the NodeFactory interface.

import { uid } from 'uid';
import { InstantRelay, NodeFactory } from 'instant-relay';

// Message types
interface Request { id: string; type: 'req'; }
interface Response { type: 'res'; reqId: string; }

// Union of all possible message types
type Message = Request | Response;

// Promisified setTimeout()
const wait = (delay: number) => {
  return new Promise((resolve) => {
    setTimeout(resolve, delay);
  });
};

// Main instance
const relay = new InstantRelay<Message>();

// Factory function for "server" nodes
const serverFactory: NodeFactory<Message, {}> = (send, broadcast, opts) => {
  return async (message) => {
    switch (message.type) {
      case 'req':
        console.log(`server received request ${message.id}`);
        await wait(Math.random() * 1000);
        await send('client', { type: 'res', reqId: message.id });
        break;
      default:
    }
  };
};

// Add one "server" node with custom options
relay.addNode('server', serverFactory, {
  concurrency: 2,                             // How many messages may be processed in parallel
  highWaterMark: 2,                           // Threshold above which throttling starts
  throttle: queueLength => queueLength * 10,  // Set throttling delay based on queue length
});

// Factory function for "client" nodes
const clientFactory: NodeFactory<Message, {}> = (send, broadcast, opts) => {
  // Send loop w/ backpressure support
  const loop = () => {
    const now = Date.now();
    send('server', { id: uid(), type: 'req' }).then(() => {
      console.log('client loop lag', Date.now() - now);
      setImmediate(loop);
    });
  };
  setImmediate(loop);
  return async (message) => {
    switch (message.type) {
      case 'res':
        console.log(`client received a response for request ${message.reqId}`);
        break;
      default:
    }
  };
};

relay.addNode('client', clientFactory, {});

Due to backpressure support, the loop that sends requests to the server node will quickly slow down to a rate compatible with the artificial latency.

License

Licensed under MIT.