Security News
RubyGems.org Adds New Maintainer Role
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
nats-micro
Advanced tools
A convenient microservice library based on NATS and compatible with nats-go microservices
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
Starting a microservice is extremely simple:
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',
},
},
}
);
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);
@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);
You can easily stop a microservice
const ms = await Microservice.createFromClass(broker, echoMicroservice);
await ms.stop();
To start if again just use the same code as before:
await Microservice.createFromClass(broker, echoMicroservice);
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 BalanceDemoMicroservice {
@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';
}
}
If you call balance-demo.balanced
, having N instances of balance-demo
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.
If you send a call to balance-demo.all
however, it will be received and responded by every balance-demo
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.
As for the balance-demo.local
, there is no such subject any microservice is subcribed to. Instead instance ID
of the balance-demo
microservice will listen to balance-demo.<microservice ID>.local
only. You will need to use broker.request(..., { microservice: 'balance-demo', 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.
While you can use NATS native way to discover currently running microservices by sending messages to subject "$SRV.INFO" and collecting their responses, nats-micro
library provides an additional convenient way of doing this.
Every nats-micro microservice will announce itself at "$SRV.REG" subject, which you can listen either manually subscribing to the subject or using Monitor
class.
// create a new microservice monitor
// broker must be already connected by this moment
const monitor = new Monitor(broker);
// receive an event whenever a new service appears online
// or when you (re)discover it manually
monitor.on('added', (service) => console.log);
// receive an event whenever the list of services changes
monitor.on('change', (services) => console.log);
// manually discover all running microservices in background,
// giving them 10 seconds to respond
monitor.discover(10000);
// or wait for the 10 seconds in foreground
await monitor.discover(10000);
// access the list of services collected
const servicesRunning = monitor.services;
// note that discover() will abandon all previously collected services
// unless you instuct it explicitly
monitor.discover(10000, { doNotClear: true });
// start automatic discovery with 60 seconds interval
monitor.startPeriodicDiscovery(60000, 10000);
// and then stop it
monitor.stopPeriodicDiscovery();
Using Monitor
you can not only watch for microservices coming online, but also for disconnecting ones.
For this you need a NATS server with system account configured and create two separate connections from your code: one for a usual user and one for a system user:
// both brokers must be already connected by this moment
const monitor = new Monitor(userBroker, systemBroker);
// in addition to 'change' and 'added' events
// you can watch for microservices removed
monitor.on('removed', (service) => console.log);
This code will give Monitor
an ability to subscribe to "$SYS.ACCOUNT.*.DISCONNECT" subject and watch connections going offline.
As every microservice created with nats-micro
has a _nats.client.id
value in its metadata, this allows Monitor
to associate microservices with NATS connections and understand if they went offline when their parent broker is disconnects for whatever reason.
FAQs
NATS micro compatible extra-lightweight microservice library
The npm package nats-micro receives a total of 10 weekly downloads. As such, nats-micro popularity was classified as not popular.
We found that nats-micro demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
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.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.
Security News
Research
Socket's threat research team has detected five malicious npm packages targeting Roblox developers, deploying malware to steal credentials and personal data.