Installations
npm install node-nats-streaming
Developer Guide
Typescript
No
Module System
CommonJS
Min. Node Version
>= 8.0.0
Node Version
11.4.0
NPM Version
6.14.4
Score
64
Supply Chain
98.8
Quality
80
Maintenance
100
Vulnerability
99.6
License
Releases
Contributors
Unable to fetch Contributors
Languages
JavaScript (98.39%)
TypeScript (1.24%)
Makefile (0.37%)
Developer
nats-io
Download Statistics
Total Downloads
6,892,491
Last Day
1,047
Last Week
9,710
Last Month
48,920
Last Year
1,002,302
GitHub Statistics
293 Stars
132 Commits
49 Forks
20 Watching
6 Branches
24 Contributors
Bundle Size
351.02 kB
Minified
77.04 kB
Minified + Gzipped
Package Meta Information
Latest Version
0.3.2
Package Id
node-nats-streaming@0.3.2
Size
41.78 kB
NPM Version
6.14.4
Node Version
11.4.0
Publised On
12 May 2020
Total Downloads
Cumulative downloads
Total Downloads
6,892,491
Last day
-60.3%
1,047
Compared to previous day
Last week
-19.8%
9,710
Compared to previous week
Last month
-6.3%
48,920
Compared to previous month
Last year
-45.8%
1,002,302
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
3
Stan.js - Node.js client for NATS Streaming
NATS Streaming Server is an extremely performant, lightweight reliable streaming platform powered by NATS.
NATS streaming server provides the following high-level feature set:
- Log based persistence
- At-Least-Once Delivery model, giving reliable message delivery
- Rate matched on a per subscription basis
- Replay/Restart
- Last Value Semantics
Installation
1npm install node-nats-streaming 2 3# development versions of stan.js can be obtained by: 4npm install node-nats-streaming@next
Basic Usage
1#!/usr/bin/env node 2 3'use-strict' 4 5const sc = require('node-nats-streaming').connect('test-cluster', 'test') 6 7sc.on('connect', () => { 8 // Simple Publisher (all publishes are async in the node version of the client) 9 sc.publish('foo', 'Hello node-nats-streaming!', (err, guid) => { 10 if (err) { 11 console.log('publish failed: ' + err) 12 } else { 13 console.log('published message with guid: ' + guid) 14 } 15 }) 16 17 // Subscriber can specify how many existing messages to get. 18 const opts = sc.subscriptionOptions().setStartWithLastReceived() 19 const subscription = sc.subscribe('foo', opts) 20 subscription.on('message', (msg) => { 21 console.log('Received a message [' + msg.getSequence() + '] ' + msg.getData()) 22 }) 23 24 // After one second, unsubscribe, when that is done, close the connection 25 setTimeout(() => { 26 subscription.unsubscribe() 27 subscription.on('unsubscribed', () => { 28 sc.close() 29 }) 30 }, 1000) 31}) 32 33sc.on('close', () => { 34 process.exit() 35})
Subscription Start (i.e. Replay) Options
NATS streaming subscriptions are similar to NATS subscriptions, but clients may start their subscription at an earlier point in the message stream, allowing them to receive messages that were published before this client registered interest.
The options are described with examples below:
1// Subscribe starting with the most recently published value 2let opts = sc.subscriptionOptions() 3opts.setStartWithLastReceived() 4let subscription = sc.subscribe('foo', opts) 5 6// Receive all stored values in order 7opts = sc.subscriptionOptions() 8opts.setDeliverAllAvailable() 9subscription = sc.subscribe('foo', opts) 10 11// Receive all messages starting at a specific sequence number 12opts = sc.subscriptionOptions() 13opts.setStartAtSequence(22) 14subscription = sc.subscribe('foo', opts) 15 16// Subscribe starting at a specific time 17const d = new Date(2016, 7, 8) // August 8th, 2016 18opts = sc.subscriptionOptions() 19opts.setStartTime(d) 20subscription = sc.subscribe('foo', opts) 21 22// Subscribe starting at a specific amount of time in the past (e.g. 30 seconds ago) 23opts = sc.subscriptionOptions() 24opts.setStartAtTimeDelta(30 * 1000) // 30 seconds ago 25subscription = sc.subscribe('foo', opts)
Wildcard Subscriptions
NATS streaming subscriptions do not support wildcards.
Durable Subscriptions
Replay of messages offers great flexibility for clients wishing to begin processing at some earlier point in the data stream. However, some clients just need to pick up where they left off from an earlier session, without having to manually track their position in the stream of messages. Durable subscriptions allow clients to assign a durable name to a subscription when it is created. Doing this causes the NATS Streaming server to track the last acknowledged message for that clientID + durable name, so that only messages since the last acknowledged message will be delivered to the client.
1let sc = require('node-nats-streaming').connect('test-cluster', 'client-123') 2 3sc.on('connect', () => { 4 // Subscribe with durable name 5 const opts = sc.subscriptionOptions() 6 opts.setDeliverAllAvailable() 7 opts.setDurableName('my-durable') 8 9 let durableSub = sc.subscribe('foo', opts) 10 durableSub.on('message', (msg) => { 11 console.log('Received a message: ' + msg.getData()) 12 }) 13 14 // client suspends durable subscription 15 durableSub.close() 16 17 // client resumes durable subscription 18 durableSub = sc.subscribe('foo', opts) 19 durableSub.on('message', (msg) => { 20 console.log('Received a message: ' + msg.getData()) 21 }) 22 23 // ... 24 // client receives message sequence 1-40, and disconnects 25 sc.close() 26 27 // client reconnects in the future with same clientID 28 sc = require('node-nats-streaming').connect('test-cluster', 'client-123') 29 durableSub = sc.subscribe('foo', opts) 30 durableSub.on('message', (msg) => { 31 console.log('Received a message: ' + msg.getData()) 32 }) 33})
Queue Groups
Subscriptions with the same queue name will form a queue group. Each message is only delivered to a single subscriber per queue group. You can have as many queue groups as you wish. Normal subscribers are not affected by queue group semantics.
1const opts = sc.subscriptionOptions() 2opts.setStartWithLastReceived() 3sc.subscribe('foo', 'foo.workers', opts)
Asynchronous Publishing
For each message published, a NUID is generated for the message on creation. When the message is received by the server, the client library is notified on its optional callback:
1const guid = sc.publish('foo', 'Hello World!', (err, aGuid) => { 2 // err will be undefined if the message was accepted by the 3 // NATS streaming server 4 if (err) { 5 console.log('Error publishing: ' + aGuid + ' - ' + err) 6 } 7})
Message Acknowledgements and Redelivery
NATS streaming server offers At-Least-Once delivery semantics, meaning that once a message has been delivered to an eligible subscriber, if an acknowledgement is not received within the configured timeout interval, NATS streaming server will attempt redelivery of the message.
This timeout interval is specified by the subscription option SubscriptionOptions#setAckWait(millis)
, which defaults to 30 seconds.
By default, messages are automatically acknowledged by the stan.js library after the subscriber's message handler is invoked. However, there may be cases in which the subscribing client wishes to accelerate or defer acknowledgement of the message.
To do this, the client must set manual acknowledgement mode on the subscription, and invoke Message#ack()
on the Message
.
1const opts = sc.subscriptionOptions() 2opts.setManualAckMode(true) 3opts.setAckWait(60 * 1000) // 60s 4 5const sub = sc.subscribe('Foo', opts) 6 7sub.on('message', (msg) => { 8 // do something with the message 9 msg.ack() 10})
Synchronous Publishing
The stan.js client does not support synchronous publishing.
Rate limiting/matching
A classic problem of publish-subscribe messaging is matching the rate of message producers with the rate of message consumers. Message producers can often outpace the speed of the subscribers that are consuming their messages. This mismatch is commonly called a "fast producer/slow consumer" problem, and may result in dramatic resource utilization spikes in the underlying messaging system as it tries to buffer messages until the slow consumer(s) can catch up.
Under Nodejs, this is even more important, as in Nodejs is a single-threaded environment. This means that if your application is CPU bound, it is possible for your application to block the processing of outgoing or incoming messages.
Publisher rate limiting
NATS streaming server provides a connection option called maxPubAcksInflight
that effectively limits the number of unacknowledged messages that a publisher may have in-flight at any given time. When this maximum is reached, your publisher's callback will be invoked with an error. If not callback was defined, an error will be thrown until the number of unacknowledged messages fall below the specified limit.
Subscriber rate limiting
Rate limiting may also be accomplished on the subscriber side, on a per-subscription basis, using a subscription option called SubscriptionOptions#setMaxInFlight(number)
. This option specifies the maximum number of outstanding acknowledgements (messages that have been delivered but not acknowledged) that NATS streaming server will allow for a given subscription.
When this limit is reached, NATS streaming server will suspend delivery of messages to this subscription until the number of unacknowledged messages falls below the specified limit.
Connection Status
The fact that the NATS streaming server and clients are not directly connected poses a challenge when it comes to know if a client is still valid. When a client disconnects, the streaming server is not notified, hence the importance of calling stan#close()
. The server sends heartbeats to the client's private inbox and if it misses a certain number of responses, it will consider the client's connection lost and remove it from its state.
Before version 0.1.0
, the client library was not sending PINGs to the streaming server to detect connection failure. This was problematic especially if an application was never sending data (had only subscriptions for instance). Picture the case where a client connects to a NATS Server which has a route to a NATS streaming server (either connecting to a standalone NATS Server or the server it embeds). If the connection between the NATS streaming server and the client's NATS Server is broken, the client's NATS connection would still be ok, yet, no communication with the streaming server is possible.
Starting version 0.1.0
of this library and server 0.10.0
, the client library will now send PINGs at regular intervals (default is 5000
milliseconds) and will close the streaming connection after a certain number of PINGs have been sent without any response (default is 3
). When that happens, a callback - if one is registered - will be invoked to notify the user that the connection is permanently lost, and the reason for the failure.
Here is how you would specify your own PING values and the callback:
1const STAN = require('node-nats-streaming') 2const sc = STAN.connect('test-cluster', 'test', { 3 stanMaxPingOut: 3, 4 stanPingInterval: 1000 5}) 6 7sc.on('connect', () => { 8 sc.on('connection_lost', (error) => { 9 console.log('disconnected from stan', error) 10 }) 11...
Note that the only way to be notified is to set the callback. If the callback is not set, PINGs are still sent and the connection will be closed if needed, but the application won't know if it has only subscriptions.
When the connection is lost, your application would have to re-create it and all subscriptions if any.
When no NATS connection is provided via the connection options, the library creates its own NATS connection and will now set the reconnect attempts (maxReconnectAttempts
) to "infinite" (-1
), which was not the case before. It should therefore be possible for the library to always reconnect, but this does not mean that the streaming connection will not be closed, even if you set a very high threshold for the PINGs max out value. Keep in mind that while the client is disconnected, the server is sending heartbeats to the clients too, and when not getting any response, it will remove that client from its state. When the communication is restored, the PINGs sent to the server will allow to detect this condition and report to the client that the connection is now closed.
Also, while a client is "disconnected" from the server, another application with connectivity to the streaming server may connect and uses the same client ID. The server, when detecting the duplicate client ID, will try to contact the first client to know if it should reject the connect request of the second client. Since the communication between the server and the first client is broken, the server will not get a response and therefore will replace the first client with the second one.
Prior to client 0.1.0
and server 0.10.0
, if the communication between the first client and server were to be restored, and the application would send messages, the server would accept those because the published messages client ID would be valid, although the client is not. With client at 0.1.0
+ and server 0.10.0
+, additional information is sent with each message to allow the server to reject messages from a client that has been replaced by another client.
Supported Node Versions
Support policy for Nodejs versions follows Nodejs release support. We will support and build node-nats-streaming on even Nodejs versions that are current or in maintenance.
License
Unless otherwise noted, the NATS source files are distributed under the Apache Version 2.0 license found in the LICENSE file.
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: Apache License 2.0: LICENSE:0
Reason
Found 19/23 approved changesets -- score normalized to 8
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 27 are checked with a SAST tool
Reason
12 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-67hx-6x53-jw92
- Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-9c47-m6qq-7p4h
- Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv
- Warn: Project is vulnerable to: GHSA-f8q6-p94x-37v3
- Warn: Project is vulnerable to: GHSA-mwcw-c2x4-8c55
- Warn: Project is vulnerable to: GHSA-hrpp-h998-j3pp
- Warn: Project is vulnerable to: GHSA-p8p7-x288-28g6
- Warn: Project is vulnerable to: GHSA-c2qf-rxjj-qqgw
- Warn: Project is vulnerable to: GHSA-72xf-g2v4-qvf3
- Warn: Project is vulnerable to: GHSA-j8xg-fqg3-53r7
Score
2.8
/10
Last Scanned on 2024-12-16
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn MoreOther packages similar to node-nats-streaming
node-nats-streaming-buffered-client
[![npm version](https://badge.fury.io/js/node-nats-streaming-buffered-client.svg)](https://badge.fury.io/js/node-nats-streaming-buffered-client) [![Travis](https://travis-ci.com/SpringTree/node-nats-streaming-buffered-client.svg?branch=master)](https://tr
@egomobile/nats
Classes, functions and tools that help to connect and communicate to and with a NATS streaming server.
node-red-contrib-natsstreaming
NATS streaming with Node-RED
@brunomiketickets/common
Common contains a set of reusable middlewares, event related classes base of node-nats-streaming and pre-defined error classes.