Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

nats-micro

Package Overview
Dependencies
Maintainers
1
Versions
38
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

nats-micro

NATS micro compatible extra-lightweight microservice library

  • 0.9.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
13
decreased by-88.18%
Maintainers
1
Weekly downloads
 
Created
Source

NATS Microservice Library

A convenient microservice library based on NATS and compatible with nats-go microservices

Description

This is a typescript-first library that provides a convinient (in 10 lines of code or less!) way to write microservises with out of the box auto discovery, observability and load balancing.

Full interoperability with to-be-released nastcli v0.0.36 that adds nats micro info, nats micro stats and nats micro ping commands

It also supports service schema discovery which is not (yet?) supported by nats micro

Limitations / TODO

  1. No multi-reply support yet. When you send a message you will be getting exactly one response (or a timeout error)

  2. Automatica typing and validation is inclomplete yet

Usage

It is extremely simple:

Functional way

const broker = await new Broker('echo' + process.pid).connect();

await Microservice.create(
  broker,
  {
    name: 'echo',
    description: 'Simple echo microservice',
    version: '0.0.1',
    methods: {
      say: {
        handler: (text) => text,
        // subject is autogenerated according to nats micro protocol
      },
      'config-change-event': {
        handler: console.log,
        // subject is manually specified which allows for broadcast
        // event bus
        subject: '$EVT.config.change',
      },
    },
  }
);

Declarative way

class EchoMicroservice {
  public get config(): MicroserviceConfig {
    return {
      name: 'echo',
      description: 'Simple echo microservice',
      version: '0.0.1',
      methods: {
        say: { handler: this.say },
        'config-change-event': { handler: this.onConfigChange },
      },
    };
  }

  private say(text: string): string {
    return text;
  }

  private onConfigChange(change: unknown): void {
    console.log(change);
  }
}

const echoMicroservice = new EchoMicroservice();

const broker = await new Broker('echo' + process.pid).connect();
await Microservice.create(broker, echoMicroservice.config);

Using decorators

@microservice({ name: 'echo', description: 'Decorated service' })
// @microservice() // as simple as this 
export default class EchoMicroservice {

  // name is manual, subject is autodetected
  @method({name: 'say'}) 
  private reply(text: string): string {
    return text;
  }
  
  // name is autodetected as 'config-change-event', subject is manual
  @method({ subject: '$EVT.config.change' }) 
  private configChangeEvent(change: unknown): void {
    console.log(change);
  }
}

const echoMicroservice = new EchoMicroservice();

const broker = await new Broker('echo' + process.pid).connect();
await Microservice.createFromClass(broker, echoMicroservice);

Load balancing

When you start a number of number of instances of the same microservice, normally, NATS will automatically balance any calls to the a method across all the microservice instances.

However, you can control his behavior:

@microservice()
export default class BalancedMicroservice {

  @method()
  public async balanced(): Promise<string> {
    return 'I will answer this if everyone else is slower than me';
  }

  @method({ unbalanced: true })
  public async all(): Promise<string> {
    return 'I will answer this no matter what. Get ready for multiple answers';
  }

  @method({ local: true })
  public async local(): Promise<string> {
    return 'You can reach me only at my local subject, no load balancing';
  }
}

Balanced behavior

If you call balanced.balanced, having N instances of balanced microservice, every one of them will receive and respond to every Nth call on average. The logic of load balancing is based on NATS internal "queue groups" functionality ans is described in its documentation.

Unbalanced behavior

If you send a call to balanced.all however, it will be received and responded by every balanced microservice that has the all method.

This is useful for broadcast event buses, when you want all microservices to receive an even no matter what and possibly respond to it.

Having this utilized be ready to receiving multiple responses to a request.

Local endpoint behavior

As for the balanced.local, there is no such subject any microservice is subcribed to. Instead instance ID of a microservice balanced will listen to balanced.<microservice ID>.local only. You will need to use broker.exec(..., { microservice: 'balanced', instance: '<microservice ID>', method: 'local' }, ...) for that.

This feature is useful for scenarios like when you have multiple instances of the same microservice, want to discover their IDs and then address specific ones of them.

Keywords

FAQs

Package last updated on 07 Sep 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc