├── event-simulator ├── xs-security.json ├── package.json ├── config.js ├── README.md ├── default-env.json ├── manifest.yml └── main.js ├── .gitignore ├── .gitattributes ├── CREDITS.txt ├── xb-msg-amqp-v100-samples ├── package.json ├── config │ └── cf-sample-config.js ├── README.md └── src │ ├── producer.js │ ├── consumer.js │ └── tools.js ├── .reuse └── dep5 ├── xb-msg-amqp-v100-doc ├── examples │ ├── counter.js │ ├── producer.js │ ├── consumer.js │ ├── gateway.js │ └── tools.js └── README.md ├── README.md ├── LICENSES └── Apache-2.0.txt └── LICENSE /event-simulator/xs-security.json: -------------------------------------------------------------------------------- 1 | { 2 | "xsappname" : "xb-msg-sample-stream-logger" 3 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | _* 2 | build/ 3 | node_modules/ 4 | _gen/ 5 | gen/ 6 | .metadata 7 | .idea 8 | npm-debug.log 9 | package-lock.json 10 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text eol=lf 2 | 3 | *.md text 4 | *.js text 5 | 6 | *.pdf binary 7 | *.pptx binary 8 | *.jar binary 9 | *.png binary 10 | *.jpg binary 11 | *.PNG binary 12 | *.JPG binary 13 | *.so binary 14 | *.dll binary 15 | *.node binary 16 | *.exe binary 17 | -------------------------------------------------------------------------------- /CREDITS.txt: -------------------------------------------------------------------------------- 1 | This program references the following third party open source or other free download components. 2 | The third party licensors of these components may provide additional license rights, 3 | terms and conditions and/or require certain notices as described below. 4 | -------------------------------------------------------------------------------- /event-simulator/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@sap/xb-msg-samples-simple-logger", 3 | "version": "0.0.1", 4 | "description": "xb messaging simple logger", 5 | "keywords": [ 6 | "messaging", 7 | "application" 8 | ], 9 | "engines": { 10 | "node": ">=6.9.1" 11 | }, 12 | "dependencies": { 13 | "@sap/xsenv": "1.2.8", 14 | "@sap/xb-msg": ">=0.2.4", 15 | "@sap/xb-msg-env": ">=0.2.1" 16 | }, 17 | "scripts": { 18 | "start": "node main.js" 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /event-simulator/config.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * timerMin (seconds) - the minimum time interval to produce a message 5 | * timerMax (seconds) - the maximum time interval to produce a message 6 | */ 7 | 8 | const service = 'myrabbitmq'; 9 | const taskList = { 10 | myOutA : { topic: 'Sales/Order/Created' , timerMin: 1, timerMax: 11 }, 11 | myOutB : { topic: 'Outbound/Delivery/Released' , timerMin: 5, timerMax: 8 } 12 | }; 13 | 14 | module.exports.taskList = taskList; 15 | module.exports.service= service; 16 | 17 | -------------------------------------------------------------------------------- /xb-msg-amqp-v100-samples/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@sap/xb-msg-amqp-v100-samples", 3 | "version": "1.0.0", 4 | "description": "xb-msg-amqp-v100-samples", 5 | "keywords": [ 6 | "messaging", 7 | "application", 8 | "sample" 9 | ], 10 | "engines": { 11 | "node": ">=6.9.1" 12 | }, 13 | "dependencies": { 14 | "@sap/xb-msg-amqp-v100": "^0.3.5" 15 | }, 16 | "scripts": { 17 | "consumer": "node src/consumer.js ../config/cf-sample-config.js", 18 | "producer": "node src/producer.js ../config/cf-sample-config.js" 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /xb-msg-amqp-v100-samples/config/cf-sample-config.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const fs = require('fs'); 4 | 5 | module.exports = { 6 | uri : 'wss://em.cfapps..ondemand.com/protocols/amqp10ws', 7 | oa2 :{ 8 | endpoint : 'https://authentication..ondemand.com/oauth/token', 9 | client : '', 10 | secret : '' 11 | }, 12 | credentials: { 13 | mechanism : '', 14 | user : '', 15 | password : '' 16 | }, 17 | data: { 18 | source : 'queue:SampleForAQueue', 19 | target : 'topic:sample/for/a/topic', 20 | payload : new Buffer.allocUnsafe(20), 21 | maxCount : 100, 22 | logCount : 10 23 | } 24 | }; 25 | 26 | -------------------------------------------------------------------------------- /event-simulator/README.md: -------------------------------------------------------------------------------- 1 | # Event Simulator 2 | 3 | Simulates events/messages and logs them via console. 4 | 5 | ## Prerequisites 6 | In case you want to run the example application locally you need to install a RabbitMQ. 7 | 8 | ## Installation 9 | ```` 10 | npm install 11 | ```` 12 | 13 | ## Run Locally 14 | ```` 15 | npm start 16 | ```` 17 | 18 | ## Run in Cloud Foundry 19 | Please adjust the [manifest.yml](manifest.yml) 20 | ```` 21 | cf push 22 | ```` 23 | You may check the logs via: 24 | ```` 25 | cf logs msg-event-simulator --recent 26 | ```` 27 | 28 | 29 | ## License 30 | Copyright (c) 2017 SAP SE or an SAP affiliate company. All rights reserved. 31 | This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the [LICENSE file](../LICENSE.txt). -------------------------------------------------------------------------------- /event-simulator/default-env.json: -------------------------------------------------------------------------------- 1 | { 2 | "PORT": 9001, 3 | "VCAP_SERVICES": { 4 | "rabbitmq": [ 5 | { 6 | "credentials": { 7 | "uri": "amqp://guest:guest@localhost:5672" 8 | }, 9 | "label": "rabbitmq", 10 | "name": "myrabbitmq", 11 | "tags": [ 12 | "rabbitmq", 13 | "amqp" 14 | ] 15 | } 16 | ] 17 | }, 18 | "SAP_XBEM_BINDINGS": { 19 | "inputs": { 20 | }, 21 | "outputs": { 22 | "myOutA" : { 23 | "service": "myrabbitmq", 24 | "address": "topic:erp/event", 25 | "reliable": false 26 | }, 27 | "myOutB" : { 28 | "service": "myrabbitmq", 29 | "address": "topic:erp/event", 30 | "reliable": false 31 | } 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /event-simulator/manifest.yml: -------------------------------------------------------------------------------- 1 | #--- 2 | #applications: 3 | #- name: msg-event-simulator 4 | # host: [prefix]-msg-event-simulator 5 | # domain: cfapps.sap.hana.ondemand.com 6 | # buildpack: https://github.com/cloudfoundry/nodejs-buildpack 7 | # memory: 256M 8 | # command: node main.js 9 | # services: 10 | # - myrabbitmq 11 | --- 12 | applications: 13 | - name: msg-event-simulator 14 | buildpack: https://github.com/cloudfoundry/nodejs-buildpack 15 | command: node main.js 16 | memory: 1024M 17 | services: 18 | - myrabbitmq 19 | health-check-type: none 20 | env: 21 | SAP_JWT_TRUST_ACL: "[{\"clientid\":\"*\",\"identityzone\":\"*\"}]" 22 | SAP_XBEM_BINDINGS: > 23 | { 24 | "inputs": {}, 25 | "outputs": { 26 | "myOutA" : { 27 | "service": "myrabbitmq", 28 | "address": "topic:erp/event", 29 | "reliable": false 30 | }, 31 | "myOutB" : { 32 | "service": "myrabbitmq", 33 | "address": "topic:erp/event", 34 | "reliable": false 35 | } 36 | } 37 | } 38 | path: . 39 | 40 | -------------------------------------------------------------------------------- /xb-msg-amqp-v100-samples/README.md: -------------------------------------------------------------------------------- 1 | # Sample application for Messaging Client Node.js 2 | 3 | ## Description 4 | Sample application (plain Node.js) of how to use the _Event Mesh Client_ to send and receive messages via _SAP Event Mesh_. 5 | 6 | ## How To run 7 | This section includes the _Prerequisite_, describe _how to install_ and _how to configure_ this basic sample. 8 | 9 | 1. Prerequisite: Enable Event Mesh on _SAP BTP_ 10 | 1. Create required _Event Mesh_ service via e.g. `cf cs enterprise-messaging dev event-mesh-service-instance-name -c '{"emname":"sample_application"}'` 11 | 1. Create service key via e.g. `cf csk event-mesh-service-instance-name key-name -c '{"emname":"sample_application"}'` 12 | 1. Get key via e.g. `cf service-key event-mesh-service-instance-name key-name` 13 | 1. Update the `config/cf-sample-config.js` with information of the _service key_ 14 | 1. Install required dependencies via `npm install` 15 | 1. Run sample application 16 | 1. Start producer via `npm run-script producer` (default) or via `node src/producer.js ../config/cf-sample-config.js` (with given config file) 17 | 1. Start consumer via `npm run-script consumer` (default) or via `node src/consumer.js ../config/cf-sample-config.js` (with given config file) 18 | 19 | ## Support 20 | This project is _'as-is'_ with no support, no changes being made. 21 | You are welcome to make changes to improve it but we are not available for questions or support of any kind. 22 | 23 | ## License 24 | Copyright (c) 2017 SAP SE or an SAP affiliate company. All rights reserved. 25 | This file is licensed under the _SAP SAMPLE CODE LICENSE AGREEMENT, v1.0-071618_ except as noted otherwise in the [LICENSE file](../LICENSE.txt). 26 | -------------------------------------------------------------------------------- /.reuse/dep5: -------------------------------------------------------------------------------- 1 | Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ 2 | Upstream-Name: enterprise-messaging-client-nodejs-samples 3 | Upstream-Contact: Christoph Scheiber 4 | Source: https://github.com/SAP-samples/enterprise-messaging-client-nodejs-samples 5 | Disclaimer: The code in this project may include calls to APIs (“API Calls”) of 6 | SAP or third-party products or services developed outside of this project 7 | (“External Products”). 8 | “APIs” means application programming interfaces, as well as their respective 9 | specifications and implementing code that allows software to communicate with 10 | other software. 11 | API Calls to External Products are not licensed under the open source license 12 | that governs this project. The use of such API Calls and related External 13 | Products are subject to applicable additional agreements with the relevant 14 | provider of the External Products. In no event shall the open source license 15 | that governs this project grant any rights in or to any External Products,or 16 | alter, expand or supersede any terms of the applicable additional agreements. 17 | If you have a valid license agreement with SAP for the use of a particular SAP 18 | External Product, then you may make use of any API Calls included in this 19 | project’s code for that SAP External Product, subject to the terms of such 20 | license agreement. If you do not have a valid license agreement for the use of 21 | a particular SAP External Product, then you may only make use of any API Calls 22 | in this project for that SAP External Product for your internal, non-productive 23 | and non-commercial test and evaluation of such API Calls. Nothing herein grants 24 | you any rights to use or access any SAP External Product, or provide any third 25 | parties the right to use of access any SAP External Product, through API Calls. 26 | 27 | Files: * 28 | Copyright: 2018 SAP SE or an SAP affiliate company and enterprise-messaging-client-nodejs-samples 29 | License: Apache-2.0 30 | -------------------------------------------------------------------------------- /event-simulator/main.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const msg = require('@sap/xb-msg'); 4 | const config = require('./config'); 5 | 6 | const env = require('@sap/xb-msg-env'); 7 | const xsenv = require('@sap/xsenv'); 8 | 9 | xsenv.loadEnv(); 10 | const client = new msg.Client(env.msgClientOptions(config.service, [], ['myOutA', 'myOutB'])); 11 | 12 | function setupOptions(tasks, options) { 13 | Object.getOwnPropertyNames(tasks).forEach((id) => { 14 | const task = tasks[id]; 15 | options.destinations[0].ostreams[id] = { 16 | channel: 1, 17 | exchange: 'amq.topic', 18 | routingKey: task.topic 19 | }; 20 | }); 21 | return options; 22 | } 23 | 24 | function getRandomInt(min, max) { 25 | min = Math.ceil(min); 26 | max = Math.floor(max); 27 | return (Math.floor(Math.random() * (max - min + 1)) + min) * 1000; 28 | } 29 | 30 | function initTasks(tasks, client) { 31 | Object.getOwnPropertyNames(tasks).forEach((id) => { 32 | const task = tasks[id]; 33 | const stream = client.ostream(id); 34 | 35 | const handler = () => { 36 | console.log('publishing ' + task.topic); 37 | 38 | const message = { 39 | target: { address: 'topic:' + task.topic }, 40 | payload: Buffer.allocUnsafe(50).fill('X') 41 | }; 42 | if (!stream.write(message)) { 43 | console.log('wait'); 44 | return; 45 | } 46 | setTimeout(handler, getRandomInt(task.timerMin, task.timerMax)); 47 | }; 48 | 49 | stream.on('drain', () => { 50 | setTimeout(handler, getRandomInt(task.timerMin, task.timerMax)); 51 | }); 52 | 53 | setTimeout(handler, getRandomInt(task.timerMin, task.timerMax)); 54 | }); 55 | } 56 | 57 | client 58 | .on('connected', () => { 59 | console.log('connected'); 60 | initTasks(config.taskList, client); 61 | }) 62 | .on('drain', () => { 63 | console.log('continue'); 64 | }) 65 | .on('error', (error) => { 66 | console.log(error); 67 | }); 68 | 69 | client.connect(); 70 | 71 | -------------------------------------------------------------------------------- /xb-msg-amqp-v100-doc/examples/counter.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const data = { source : { address:'/topic/a.b.#', expires : 'connection-close', timeout : 0 }, logCount : 10000, slowWork : false }; 4 | const options = Object.assign({ 5 | // tls : { host : 'localhost', port: 5671 } 6 | // net : { host : 'localhost', port: 5672 } 7 | // wss : { host : 'localhost', port: 433, path: '/' } 8 | // ws : { host : 'localhost', port: 80, path: '/' } 9 | // sasl: { user : 'guest', password : 'guest' }, 10 | }, (process.argv.length > 2) ? require(process.argv[2]) : {}); options.data = Object.assign(data, options.data); 11 | 12 | const { Client } = require('../index'); 13 | const client = new Client(options); 14 | const stream = client.receiver('InputA').attach(options.data); 15 | let msgCount = 0, logCount = options.data.logCount; 16 | 17 | stream 18 | .on('subscribed', () => { 19 | console.log('subscribed'); 20 | if (options.data.slowWork) wait(1000, 250); 21 | }) 22 | .on('error', (error) => { 23 | console.log(error); 24 | }) 25 | .on('data', (message) => { 26 | message.done(); 27 | if (++msgCount % logCount === 0) console.log(msgCount); 28 | }); 29 | 30 | client 31 | .on('connected',(destination, peerInfo) => { 32 | console.log('connected', peerInfo.description); 33 | }) 34 | .on('idle', (local) => { 35 | console.log(local ? 'idle' : 'heartbeat'); 36 | }) 37 | .on('assert', (error) => { 38 | console.log(error.message); 39 | }) 40 | .on('error', (error) => { 41 | console.log(error); 42 | }) 43 | .on('disconnected', (hadError, byBroker, statistics) => { 44 | console.log('disconnected'); 45 | setTimeout(() => client.connect(), 1000); 46 | }); 47 | 48 | client.connect(); 49 | 50 | // wait and work to simulate slow processing 51 | 52 | function wait(waitTime, workTime) { 53 | console.log('wait for', waitTime, 'ms'); 54 | setTimeout(work, waitTime, waitTime, workTime); 55 | stream.pause(); 56 | } 57 | 58 | function work(waitTime, workTime) { 59 | console.log('work for', workTime, 'ms'); 60 | setTimeout(wait, workTime, waitTime, workTime); 61 | stream.resume(); 62 | } 63 | 64 | -------------------------------------------------------------------------------- /xb-msg-amqp-v100-doc/examples/producer.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const data = { target: '/topic/a.b.c', payload: new Buffer.allocUnsafe(50).fill('X'), maxCount: 100000, logCount: 10000 }; 4 | const options = Object.assign({ 5 | // tls : { host : '127.0.0.1', port: 5671 } 6 | // net : { host : '127.0.0.1', port: 5672 } 7 | // wss : { host : 'localhost', port: 433, path: '/' } 8 | // ws : { host : 'localhost', port: 80, path: '/' } 9 | // sasl: { user: 'guest', password: 'guest' }, 10 | }, (process.argv.length > 2) ? require(process.argv[2]) : {}); options.data = Object.assign(data, options.data); 11 | 12 | const { Client } = require('../index'); 13 | const { ProduceStatistics } = require('./tools'); 14 | const stats = new ProduceStatistics(true, options.data.maxCount, options.data.logCount); 15 | const message = { payload : options.data.payload, done : stats.onDone, failed : stats.onFailed }; 16 | 17 | const client = new Client(options); 18 | const stream = client.sender('out').attach(options.data.target, '', options.data.maxCount); 19 | 20 | function send() { 21 | stats.onSend(); 22 | 23 | let noPause = true; 24 | while (noPause && stats.countMessage()) { 25 | noPause = stream.write(message); 26 | } 27 | 28 | if (noPause) { 29 | stats.onStop(); 30 | } else { 31 | stats.onWait(); 32 | } 33 | } 34 | 35 | stats 36 | .on('info', (count) => { 37 | console.log(count); 38 | }) 39 | .on('error', (error) => { 40 | console.log(error.message); 41 | }) 42 | .on('done', () => { 43 | stream.end(); 44 | }); 45 | 46 | stream 47 | .on('ready', () => { 48 | send(); 49 | }) 50 | .on('drain', () => { 51 | send(); 52 | }) 53 | .on('finish', () => { 54 | client.disconnect(); 55 | }); 56 | 57 | client 58 | .on('connected',(destination, peerInfo) => { 59 | console.log('connected', peerInfo.description); 60 | }) 61 | .on('assert', (error) => { 62 | console.log(error.message); 63 | }) 64 | .on('error', (error) => { 65 | console.log(error.message); 66 | }) 67 | .on('reconnecting', (destination) => { 68 | console.log('reconnecting, using destination ' + destination); 69 | }) 70 | .on('disconnected', (hadError, byBroker, statistics) => { 71 | console.log('disconnected'); 72 | stats.print(statistics); 73 | }); 74 | 75 | client.connect(); 76 | 77 | -------------------------------------------------------------------------------- /xb-msg-amqp-v100-samples/src/producer.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const data = { target: '/topic/a.b.c', payload: new Buffer.allocUnsafe(50).fill('X'), maxCount: 100000, logCount: 10000 }; 4 | const options = Object.assign({ 5 | // tls : { host : '127.0.0.1', port: 5671 } 6 | // net : { host : '127.0.0.1', port: 5672 } 7 | // wss : { host : 'localhost', port: 433, path: '/' } 8 | // ws : { host : 'localhost', port: 80, path: '/' } 9 | // sasl: { user: 'guest', password: 'guest' }, 10 | }, (process.argv.length > 2) ? require(process.argv[2]) : {}); options.data = Object.assign(data, options.data); 11 | 12 | const { Client } = require('@sap/xb-msg-amqp-v100'); 13 | const { ProduceStatistics } = require('./tools'); 14 | const stats = new ProduceStatistics(true, options.data.maxCount, options.data.logCount); 15 | const message = { payload : options.data.payload, done : stats.onDone, failed : stats.onFailed }; 16 | 17 | const client = new Client(options); 18 | const stream = client.sender('out').attach(options.data.target, '', options.data.maxCount); 19 | 20 | function send() { 21 | stats.onSend(); 22 | 23 | let noPause = true; 24 | while (noPause && stats.countMessage()) { 25 | noPause = stream.write(message); 26 | } 27 | 28 | if (noPause) { 29 | stats.onStop(); 30 | } else { 31 | stats.onWait(); 32 | } 33 | } 34 | 35 | stats 36 | .on('info', (count) => { 37 | console.log(count); 38 | }) 39 | .on('error', (error) => { 40 | console.log(error.message); 41 | }) 42 | .on('done', () => { 43 | stream.end(); 44 | }); 45 | 46 | stream 47 | .on('ready', () => { 48 | send(); 49 | }) 50 | .on('drain', () => { 51 | send(); 52 | }) 53 | .on('finish', () => { 54 | client.disconnect(); 55 | }); 56 | 57 | client 58 | .on('connected',(destination, peerInfo) => { 59 | console.log('connected', peerInfo.description); 60 | }) 61 | .on('assert', (error) => { 62 | console.log(error.message); 63 | }) 64 | .on('error', (error) => { 65 | console.log(error.message); 66 | }) 67 | .on('reconnecting', (destination) => { 68 | console.log('reconnecting, using destination ' + destination); 69 | }) 70 | .on('disconnected', (hadError, byBroker, statistics) => { 71 | console.log('disconnected'); 72 | stats.print(statistics); 73 | }); 74 | 75 | client.connect(); 76 | 77 | -------------------------------------------------------------------------------- /xb-msg-amqp-v100-samples/src/consumer.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // module.exports = require('@sap/xb-msg'); 4 | // module.exports = require('@sap/xb-msg-env'); 5 | // module.exports = require('@sap/xsenv'); 6 | 7 | const data = { source : '/topic/a.b.#', maxCount : 100000, logCount : 1000 }; 8 | const options = Object.assign({ 9 | // tls : { host : 'localhost', port: 5671 } 10 | // net : { host : 'localhost', port: 5672 } 11 | // wss : { host : 'localhost', port: 433, path: '/' } 12 | // ws : { host : 'localhost', port: 80, path: '/' } 13 | // sasl: { user : 'guest', password : 'guest' }, 14 | }, (process.argv.length > 2) ? require(process.argv[2]) : {}); options.data = Object.assign(data, options.data); 15 | 16 | options.destinations = [ { sample: 'test'} ] 17 | console.log(options) 18 | 19 | const { Client } = require('@sap/xb-msg-amqp-v100'); 20 | const { ConsumeStatistics } = require('./tools'); 21 | const stats = new ConsumeStatistics(options.data.maxCount, options.data.logCount); 22 | 23 | const client = new Client(options); 24 | // const msg = require('@sap/xb-msg'); 25 | // const client = new msg.Client(options); 26 | const stream = client.receiver('InputA').attach(options.data.source); 27 | 28 | stream 29 | .on('ready', () => { 30 | console.log('ready'); 31 | }) 32 | .on('data', (message) => { 33 | switch (stats.onReceive()) { 34 | case stats.COUNT: 35 | message.done(); 36 | return; 37 | case stats.COUNT_LOG: 38 | console.log(stats.count()); 39 | message.done(); 40 | return; 41 | case stats.UNSUBSCRIBE: 42 | console.log(stats.count()); 43 | message.done(); 44 | client.disconnect(); 45 | return; 46 | case stats.COOLDOWN: 47 | message.done(); 48 | return; 49 | } 50 | }) 51 | .on('finish', () => { 52 | console.log('finish'); 53 | client.disconnect(); 54 | }); 55 | 56 | client 57 | .on('connected',(destination, peerInfo) => { 58 | console.log('connected', peerInfo.description); 59 | }) 60 | .on('assert', (error) => { 61 | console.log(error.message); 62 | }) 63 | .on('error', (error) => { 64 | console.log(error); 65 | }) 66 | .on('reconnecting', (destination) => { 67 | console.log('reconnecting, using destination ' + destination); 68 | }) 69 | .on('disconnected', (hadError, byBroker, statistics) => { 70 | console.log('disconnected'); 71 | stats.print(statistics); 72 | }); 73 | 74 | client.connect(); 75 | 76 | -------------------------------------------------------------------------------- /xb-msg-amqp-v100-doc/examples/consumer.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const data = { source : '/topic/a.b.#', maxCount : 100000, logCount : 10000, slowWork : false }; 4 | const options = Object.assign({ 5 | // tls : { host : 'localhost', port: 5671 } 6 | // net : { host : 'localhost', port: 5672 } 7 | // wss : { host : 'localhost', port: 433, path: '/' } 8 | // ws : { host : 'localhost', port: 80, path: '/' } 9 | // sasl: { user : 'guest', password : 'guest' }, 10 | }, (process.argv.length > 2) ? require(process.argv[2]) : {}); options.data = Object.assign(data, options.data); 11 | 12 | const { Client } = require('../index'); 13 | const { ConsumeStatistics } = require('./tools'); 14 | const stats = new ConsumeStatistics(options.data.maxCount, options.data.logCount); 15 | 16 | const client = new Client(options); 17 | const stream = client.receiver('InputA').attach(options.data.source); 18 | 19 | stats 20 | .on('info', (count) => { 21 | console.log(count); 22 | }) 23 | .on('done', () => { 24 | client.disconnect(); 25 | }); 26 | 27 | stream 28 | .on('subscribed', () => { 29 | console.log('attached'); 30 | if (options.data.slowWork) wait(1000, 250); 31 | }) 32 | .on('error', (error) => { 33 | console.log(error.message); 34 | }) 35 | .on('data', (message) => { 36 | stats.onReceive(); 37 | message.done(); 38 | }); 39 | 40 | client 41 | .on('connected',(destination, peerInfo) => { 42 | console.log('connected', peerInfo.description); 43 | }) 44 | .on('idle', (local) => { 45 | console.log(local ? 'idle' : 'heartbeat'); 46 | }) 47 | .on('assert', (error) => { 48 | console.log(error.message); 49 | }) 50 | .on('error', (error) => { 51 | console.log(error.message); 52 | }) 53 | .on('reconnecting', (destination) => { 54 | console.log('reconnecting, using destination ' + destination); 55 | }) 56 | .on('disconnected', (hadError, byBroker, statistics) => { 57 | console.log('disconnected'); 58 | stats.print(statistics); 59 | }); 60 | 61 | client.connect(); 62 | 63 | // wait and work to simulate slow processing 64 | 65 | function wait(waitTime, workTime) { 66 | if (stats.ready()) return; 67 | console.log('wait for', waitTime, 'ms'); 68 | setTimeout(work, waitTime, waitTime, workTime); 69 | stream.pause(); 70 | } 71 | 72 | function work(waitTime, workTime) { 73 | if (stats.ready()) return; 74 | console.log('work for', workTime, 'ms'); 75 | setTimeout(wait, workTime, waitTime, workTime); 76 | stream.resume(); 77 | } 78 | 79 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Messaging Client Node.js - Samples for SAP Event Mesh 2 | [![REUSE status](https://api.reuse.software/badge/github.com/SAP-samples/event-mesh-client-nodejs-samples)](https://api.reuse.software/info/github.com/SAP-samples/event-mesh-client-nodejs-samples) 3 | 4 | ## Note 5 | The SAP Cloud Platform Enterprise Messaging service has been renamed to SAP Event Mesh - find more information in this [blog article](https://blogs.sap.com/2021/02/22/please-welcome-sap-event-mesh-new-name-for-sap-cloud-platform-enterprise-messaging) 6 | 7 | ## Description 8 | SAP Event Mesh provides a cloud-based messaging framework for the development of decoupled and resilient services and integration flows (using SAP Cloud Integration) to support asynchronous communication principles. 9 | Direct integration with SAP S/4HANA Business Event Handling allows efficient development of innovative and scaling extensions. 10 | 11 | This repository provides documentation and samples of how to use the Messaging Client (Node.js) for messaging via SAP Event Mesh in the Cloud Foundry environment. Details on each sample application and the covered scenario are described in the table _List of content and sample projects_ below. 12 | 13 | For more details of **SAP Event Mesh** take a look at the [Event Mesh - Messaging Clients landing page](https://www.npmjs.com/package/@sap/xb-msg-amqp-v100) and [SAP Event Mesh on SAP Help portal](https://help.sap.com/viewer/product/SAP_ENTERPRISE_MESSAGING/Cloud/en-US). 14 | 15 | This repository provides samples of how to use the Messaging Client (Node.js) for messaging via SAP Event Mesh in the Cloud Foundry environment. 16 | 17 | ## List of content and sample projects 18 | 19 | |Sample/Content|Scenario|Scenario Description| 20 | |---|---|---| 21 | |[xb-msg-amqp-v100-doc](xb-msg-amqp-v100-doc)|Node.js Messaging Client documentation (includes basic sample)|Documentation and related samples which shows hot this library provides a messaging client as well as classes to realize a server for `AMQP 1.0`| 22 | |[xb-msg-amqp-v100-samples](xb-msg-amqp-v100-samples)|Basic Messaging Sample which runs locally|This sample demonstrates how each application (plain Node.js, non SAP BTP) can use the _Event Mesh Client_ to send and receive messages via _SAP Event Mesh_. Therefore the messaging sample consists of a `consumer.js` and a `producer.js` which provides the corresponding functionality for send/receive (and the `config/cf-sample-config.js` to configure the sample)| 23 | |[event-simulator](event-simulator)|Event Simulator for SAP BTP deployment|The Event Simulator application demonstrates a scenario where events are emitted and send as messages via SAP Event Mesh which were consumed and further processed (i.e. logged via console). Therefore the messaging sample consists of a `main.js` which provides the corresponding functionality and start the simulation (and a `config.js` to configure the sample)| 24 | 25 | ## Requirements 26 | To run the samples a running `Event Mesh Service @SAP BTP` is required. 27 | Further necessary configuration and settings are dependent on the specific sample and are documented there. 28 | 29 | ## Download and Installation 30 | To download and install the samples just clone this repository via `git clone` 31 | 32 | For details on how to configure and run the samples please take a look into the README in the corresponding samples directory. 33 | 34 | 35 | ## Contributing 36 | This project is _'as-is'_ with no support, no changes being made. 37 | You are welcome to make changes to improve it but we are not available for questions or support of any kind. 38 | 39 | ## Licensing 40 | Copyright (c) 2024 SAP SE or an SAP affiliate company. All rights reserved. 41 | This project is licensed under the Apache Software License, version 2.0 except as noted otherwise in the [LICENSE file](./LICENSES/Apache-2.0.txt). 42 | -------------------------------------------------------------------------------- /xb-msg-amqp-v100-doc/examples/gateway.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const data = { logCount : 1000, verbose: false }; 4 | const options = Object.assign({ 5 | // tls : { host : '0.0.0.0', port: 5671 } 6 | // net : { host : '0.0.0.0', port: 5672 } 7 | // wss : { host : '0.0.0.0', port: 433, path: '/', backlog: 511 } 8 | // ws : { host : '0.0.0.0', port: 80, path: '/', backlog: 511 } 9 | // sasl: { mechanism: 'ANONYMOUS PLAIN EXTERNAL' } 10 | }, (process.argv.length > 2) ? require(process.argv[2]) : {}); options.data = Object.assign(data, options.data); 11 | 12 | const AMQP = require('../index'); 13 | const server = new AMQP.Server(options); 14 | 15 | server 16 | .on('listening', (type, host, port) => { 17 | console.log('%s server listening at port %d host %s', type, port, host); 18 | }) 19 | .on('authenticate', (type, data, request, callback) => { 20 | if (options.data.verbose) console.log('ws upgrade request'); 21 | callback(); // approve ws upgrade, type: 'Basic' or 'Bearer' 22 | }) 23 | .on('error', (error) => { 24 | console.log(error.message); 25 | }) 26 | .on('close', () => { 27 | console.log('server close'); 28 | }) 29 | .on('connection', (connection) => { 30 | 31 | connection 32 | .on('authenticate', (mechanism, data, callback) => { 33 | if (options.data.verbose) 34 | console.log('authenticate "%s" for "%s"', mechanism, data.user ? data.user : data.identity ); 35 | callback(); // approve client SASL request 36 | }) 37 | .on('valid', () => { 38 | if (options.data.verbose) 39 | console.log('authenticated'); 40 | }) 41 | .on('ready', (peerInfo) => { 42 | console.log('ready', peerInfo.description); 43 | }) 44 | .on('idle', (local) => { // idle state, local socket timeout or incoming empty frame or ws ping 45 | console.log(local ? 'idle' : 'heartbeat'); 46 | }) 47 | .on('final', (hadAssert, closeTimeout) => { 48 | console.log('final'); // ending without immediate close, server can set individual close timer 49 | }) 50 | .on('assert', (error) => { 51 | console.log(error.message); // peer protocol error, container close with error, connection is ending 52 | }) 53 | .on('error', (error) => { 54 | console.log(error.message); // any error occurred, but no assert (if assert event is handled) 55 | }) 56 | .on('abort', (hadError) => { 57 | console.log('abort'); // closed while authentication 58 | }) 59 | .on('close', (hadError) => { 60 | console.log('close'); // closed after authentication 61 | }) 62 | .on('session', (endpoint) => { 63 | if (options.data.verbose) 64 | console.log('session'); // new session opened the very first time, on client request 65 | }) 66 | .on('sender', (endpoint) => { 67 | if (options.data.verbose) 68 | console.log('sender'); // new outgoing link opened the very first time, on client request 69 | }) 70 | .on('receiver', (endpoint) => { 71 | if (options.data.verbose) 72 | console.log('receiver'); // new incoming link opened the very first time, on client request 73 | 74 | let cnt = 0; 75 | endpoint.stream().on('data', (message) => { 76 | message.done(); 77 | if (++cnt % options.data.logCount === 0) console.log(cnt); 78 | }); 79 | }) 80 | ; 81 | 82 | }) 83 | ; 84 | 85 | server.listen(); 86 | 87 | -------------------------------------------------------------------------------- /xb-msg-amqp-v100-doc/examples/tools.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const EventEmitter = require('events'); 4 | const Transform = require('stream').Transform; 5 | 6 | /** 7 | * @private 8 | */ 9 | class ProduceStatistics extends EventEmitter { 10 | 11 | constructor(confirms, maxCount, logCount) { 12 | 13 | super(); 14 | 15 | this._countTodo = maxCount; 16 | this._countDone = 0; 17 | this._countLog = logCount; 18 | this._countAckTodo = confirms ? maxCount : 0; 19 | this._countAckDone = 0; 20 | this._countPause = 0; 21 | this._durationInit = 0; 22 | this._durationWork = 0; 23 | this._durationWait = 0; 24 | this.timeBase = Date.now(); 25 | 26 | if (this._countAckTodo) { 27 | this.onDone = () => { 28 | if (++this._countAckDone === this._countAckTodo) { 29 | this.emit('done'); 30 | } 31 | }; 32 | this.onFailed = (error) => { 33 | if (error) this.emit('error', error); 34 | if (++this._countAckDone === this._countAckTodo) { 35 | this.emit('done'); 36 | } 37 | }; 38 | } else { 39 | this.onDone = () => { 40 | 41 | }; 42 | } 43 | 44 | } 45 | 46 | countMessage() { 47 | if(this._countDone < this._countTodo) { 48 | ++this._countDone; 49 | if (this._countDone % this._countLog === 0) this.emit('info', this._countDone); 50 | return true; 51 | } 52 | return false; 53 | } 54 | 55 | onSend() { 56 | if (this._durationInit) { 57 | this._durationWait += this._duration(); 58 | } else { 59 | this._durationInit += this._duration(); 60 | } 61 | } 62 | 63 | onWait() { 64 | ++this._countPause; 65 | this._durationWork += this._duration(); 66 | } 67 | 68 | onStop() { 69 | this._durationWork += this._duration(); 70 | if (this._countAckTodo === 0) this.emit('done'); 71 | } 72 | 73 | _duration() { 74 | const now = Date.now(); 75 | const duration = now - this.timeBase; 76 | this.timeBase = now; 77 | return duration; 78 | } 79 | 80 | print(info) { 81 | const overallTime = (this._durationWait + this._durationWork); 82 | console.log(); 83 | console.log('messages published : ' + this._countDone); 84 | if (this._countAckDone) { 85 | console.log('messages acknowledged : ' + this._countAckDone); 86 | } 87 | if (info) { 88 | if (info.ws) { 89 | console.log('websocket incoming : ' + (info.ws.inboundFrames125 + info.ws.inboundFramesL16 + info.ws.inboundFramesL64) + ' frames ( small ' + info.ws.inboundFrames125 + ' / medium '+ info.ws.inboundFramesL16 + ' / large ' + info.ws.inboundFramesL64 + ' )'); 90 | console.log('websocket outgoing : ' + (info.ws.outboundFrames125 + info.ws.outboundFramesL16 + info.ws.outboundFramesL64) + ' frames ( small ' + info.ws.outboundFrames125 + ' / medium '+ info.ws.outboundFramesL16 + ' / large ' + info.ws.outboundFramesL64 + ' )'); 91 | } 92 | console.log('protocol incoming : ' + info.inboundFrames + ' frames, ' + info.inboundBytes + ' bytes, ' + info.inboundChunks + ' chunks'); 93 | console.log('protocol outgoing : ' + info.outboundFrames + ' frames, ' + info.outboundBytes + ' bytes, ' + info.outboundChunks + ' chunks ( reuse ' + info.outboundChunksRecycled + ' / alloc ' + info.outboundChunksDefAlloc + ' )'); 94 | console.log('drain events incoming : ' + info.inboundDrains); 95 | console.log('drain events outgoing : ' + info.outboundDrains); 96 | } 97 | console.log('socket wait time[ms] : ' + this._durationWait); 98 | console.log('socket init time[ms] : ' + this._durationInit); 99 | console.log('sender work time[ms] : ' + this._durationWork); 100 | console.log('overall run time[ms] : ' + (this._durationWait + this._durationWork)); 101 | if(overallTime > 10) { 102 | console.log('overall rate [msg/s] : ' + Math.trunc(this._countDone * 1000 / overallTime)); 103 | } 104 | } 105 | 106 | } 107 | 108 | /** 109 | * @private 110 | */ 111 | class ConsumeStatistics extends EventEmitter { 112 | 113 | constructor(maxCount, logCount) { 114 | super(); 115 | 116 | this._countTodo = maxCount; 117 | this._countDone = 0; 118 | this._countLog = logCount; 119 | this._timeStart = 0; 120 | this._timeFinish = 0; 121 | 122 | } 123 | 124 | onReceive() { 125 | if (this._countDone === 0) { 126 | this._timeStart = Date.now(); 127 | } 128 | 129 | ++this._countDone; 130 | 131 | if (this._countDone < this._countTodo) { 132 | if (this._countDone % this._countLog === 0) this.emit('info', this._countDone); 133 | } else if (this._countDone === this._countTodo) { 134 | this._timeFinish = Date.now(); 135 | this.emit('done'); 136 | } else { 137 | --this._countDone; 138 | } 139 | } 140 | 141 | count() { 142 | return this._countDone; 143 | } 144 | 145 | ready() { 146 | return this._countDone >= this._countTodo; 147 | } 148 | 149 | print(info) { 150 | const overallTime = this._timeFinish - this._timeStart; 151 | console.log(); 152 | console.log('messages received : ' + this._countDone); 153 | if (info) { 154 | if (info.ws) { 155 | console.log('websocket incoming : ' + (info.ws.inboundFrames125 + info.ws.inboundFramesL16 + info.ws.inboundFramesL64) + ' frames ( small ' + info.ws.inboundFrames125 + ' / medium '+ info.ws.inboundFramesL16 + ' / large ' + info.ws.inboundFramesL64 + ' )'); 156 | console.log('websocket outgoing : ' + (info.ws.outboundFrames125 + info.ws.outboundFramesL16 + info.ws.outboundFramesL64) + ' frames ( small ' + info.ws.outboundFrames125 + ' / medium '+ info.ws.outboundFramesL16 + ' / large ' + info.ws.outboundFramesL64 + ' )'); 157 | } 158 | console.log('protocol incoming : ' + info.inboundFrames + ' frames, ' + info.inboundBytes + ' bytes, ' + info.inboundChunks + ' chunks'); 159 | console.log('protocol outgoing : ' + info.outboundFrames + ' frames, ' + info.outboundBytes + ' bytes, ' + info.outboundChunks + ' chunks ( reuse ' + info.outboundChunksRecycled + ' / alloc ' + info.outboundChunksDefAlloc + ' )'); 160 | console.log('drain events incoming : ' + info.inboundDrains); 161 | console.log('drain events outgoing : ' + info.outboundDrains); 162 | } 163 | if(overallTime > 10) { 164 | console.log('overall rate [msg/s] : ' + Math.trunc(this._countDone * 1000 / overallTime)); 165 | } 166 | } 167 | 168 | } 169 | 170 | /** 171 | * @private 172 | */ 173 | class JSONValidator extends Transform { 174 | 175 | constructor(valueStream, setupStream) { 176 | super(Object.create({ 177 | highWaterMark: 500, 178 | decodeStrings: false, 179 | allowHalfOpen: false, 180 | readableObjectMode: true, 181 | writableObjectMode: true 182 | })); 183 | 184 | this._valueStream = valueStream; 185 | 186 | this._setupStream = setupStream; 187 | } 188 | 189 | /** 190 | * @param {!{}} message 191 | * @param {!string} encoding 192 | * @param {!function(error=, message=)} callback 193 | * @protected 194 | * @override 195 | */ 196 | _transform(message, encoding, callback) { 197 | try { 198 | switch(message.stream) { 199 | case this._valueStream: { 200 | JSON.parse(message.payload.toString('utf8')); 201 | this.push(message); 202 | break; 203 | } 204 | case this._setupStream: { 205 | // follow up master data changes, change behavior 206 | break; 207 | } 208 | default: { 209 | // ignore 210 | } 211 | } 212 | callback(); 213 | } catch (e) { 214 | callback(e, message); 215 | } 216 | } 217 | 218 | } 219 | 220 | module.exports.ProduceStatistics = ProduceStatistics; 221 | module.exports.ConsumeStatistics = ConsumeStatistics; 222 | module.exports.JSONValidator = JSONValidator; 223 | module.exports.jsonPayload = Buffer.from('{"a1":10,"a2":"42","a3":"test","a4":{"b":42}}'); 224 | module.exports.dataPayload = Buffer.from('aaaaaaaaaa.aaaaaaaaaa.aaaaaaaaaa.aaaaaaaaaa'); 225 | 226 | 227 | -------------------------------------------------------------------------------- /xb-msg-amqp-v100-samples/src/tools.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const EventEmitter = require('events'); 4 | const Transform = require('stream').Transform; 5 | 6 | /** 7 | * @private 8 | */ 9 | class ProduceStatistics extends EventEmitter { 10 | 11 | constructor(confirms, maxCount, logCount) { 12 | 13 | super(); 14 | 15 | this._countTodo = maxCount; 16 | this._countDone = 0; 17 | this._countLog = logCount; 18 | this._countAckTodo = confirms ? maxCount : 0; 19 | this._countAckDone = 0; 20 | this._countPause = 0; 21 | this._durationInit = 0; 22 | this._durationWork = 0; 23 | this._durationWait = 0; 24 | this.timeBase = Date.now(); 25 | 26 | if (this._countAckTodo) { 27 | this.onDone = () => { 28 | if (++this._countAckDone === this._countAckTodo) { 29 | this.emit('done'); 30 | } 31 | }; 32 | this.onFailed = (error) => { 33 | this.emit('error', error); 34 | if (++this._countAckDone === this._countAckTodo) { 35 | this.emit('done'); 36 | } 37 | }; 38 | } else { 39 | this.onDone = () => { 40 | 41 | }; 42 | } 43 | 44 | } 45 | 46 | countMessage() { 47 | if(this._countDone < this._countTodo) { 48 | ++this._countDone; 49 | if (this._countDone % this._countLog === 0) this.emit('info', this._countDone); 50 | return true; 51 | } 52 | return false; 53 | } 54 | 55 | onSend() { 56 | if (this._durationInit) { 57 | this._durationWait += this._duration(); 58 | } else { 59 | this._durationInit += this._duration(); 60 | } 61 | } 62 | 63 | onWait() { 64 | ++this._countPause; 65 | this._durationWork += this._duration(); 66 | } 67 | 68 | onStop() { 69 | this._durationWork += this._duration(); 70 | if (this._countAckTodo === 0) this.emit('done'); 71 | } 72 | 73 | _duration() { 74 | const now = Date.now(); 75 | const duration = now - this.timeBase; 76 | this.timeBase = now; 77 | return duration; 78 | } 79 | 80 | print(info) { 81 | const overallTime = (this._durationWait + this._durationWork); 82 | console.log(); 83 | console.log('messages published : ' + this._countDone); 84 | if (this._countAckDone) { 85 | console.log('messages acknowledged : ' + this._countAckDone); 86 | } 87 | if (info) { 88 | if (info.ws) { 89 | console.log('websocket incoming : ' + (info.ws.inboundFrames125 + info.ws.inboundFramesL16 + info.ws.inboundFramesL64) + ' frames ( small ' + info.ws.inboundFrames125 + ' / medium '+ info.ws.inboundFramesL16 + ' / large ' + info.ws.inboundFramesL64 + ' )'); 90 | console.log('websocket outgoing : ' + (info.ws.outboundFrames125 + info.ws.outboundFramesL16 + info.ws.outboundFramesL64) + ' frames ( small ' + info.ws.outboundFrames125 + ' / medium '+ info.ws.outboundFramesL16 + ' / large ' + info.ws.outboundFramesL64 + ' )'); 91 | } 92 | console.log('protocol incoming : ' + info.inboundFrames + ' frames, ' + info.inboundBytes + ' bytes, ' + info.inboundChunks + ' chunks'); 93 | console.log('protocol outgoing : ' + info.outboundFrames + ' frames, ' + info.outboundBytes + ' bytes, ' + info.outboundChunks + ' chunks ( reuse ' + info.outboundChunksRecycled + ' / alloc ' + info.outboundChunksDefAlloc + ' )'); 94 | console.log('drain events incoming : ' + info.inboundDrains); 95 | console.log('drain events outgoing : ' + info.outboundDrains); 96 | } 97 | console.log('socket wait time[ms] : ' + this._durationWait); 98 | console.log('socket init time[ms] : ' + this._durationInit); 99 | console.log('sender work time[ms] : ' + this._durationWork); 100 | console.log('overall run time[ms] : ' + (this._durationWait + this._durationWork)); 101 | if(overallTime > 10) { 102 | console.log('overall rate [msg/s] : ' + Math.trunc(this._countDone * 1000 / overallTime)); 103 | } 104 | } 105 | 106 | } 107 | 108 | /** 109 | * @private 110 | */ 111 | class ConsumeStatistics { 112 | 113 | constructor(maxCount, logCount) { 114 | 115 | this.COUNT = 1; 116 | this.COUNT_LOG = 2; 117 | this.UNSUBSCRIBE = 3; 118 | this.COOLDOWN = 4; 119 | 120 | this._countTodo = maxCount; 121 | this._countDone = 0; 122 | this._countLog = logCount; 123 | this._timeStart = 0; 124 | this._timeFinish = 0; 125 | this.timeBase = Date.now(); 126 | 127 | } 128 | 129 | onReceive() { 130 | if (this._countDone === 0) { 131 | this._timeStart = Date.now(); 132 | } 133 | 134 | ++this._countDone; 135 | 136 | if (this._countDone < this._countTodo) { 137 | return this._countDone % this._countLog === 0 ? this.COUNT_LOG : this.COUNT; 138 | } else if (this._countDone === this._countTodo) { 139 | this._timeFinish = Date.now(); 140 | return this.UNSUBSCRIBE; 141 | } else { 142 | --this._countDone; 143 | return this.COOLDOWN; 144 | } 145 | } 146 | 147 | count() { 148 | return this._countDone; 149 | } 150 | 151 | print(info) { 152 | const overallTime = this._timeFinish - this._timeStart; 153 | console.log(); 154 | console.log('messages published : ' + this._countDone); 155 | if (this._countAckDone) { 156 | console.log('messages received : ' + this._countDone); 157 | } 158 | if (info) { 159 | if (info.ws) { 160 | console.log('websocket incoming : ' + (info.ws.inboundFrames125 + info.ws.inboundFramesL16 + info.ws.inboundFramesL64) + ' frames ( small ' + info.ws.inboundFrames125 + ' / medium '+ info.ws.inboundFramesL16 + ' / large ' + info.ws.inboundFramesL64 + ' )'); 161 | console.log('websocket outgoing : ' + (info.ws.outboundFrames125 + info.ws.outboundFramesL16 + info.ws.outboundFramesL64) + ' frames ( small ' + info.ws.outboundFrames125 + ' / medium '+ info.ws.outboundFramesL16 + ' / large ' + info.ws.outboundFramesL64 + ' )'); 162 | } 163 | console.log('protocol incoming : ' + info.inboundFrames + ' frames, ' + info.inboundBytes + ' bytes, ' + info.inboundChunks + ' chunks'); 164 | console.log('protocol outgoing : ' + info.outboundFrames + ' frames, ' + info.outboundBytes + ' bytes, ' + info.outboundChunks + ' chunks ( reuse ' + info.outboundChunksRecycled + ' / alloc ' + info.outboundChunksDefAlloc + ' )'); 165 | console.log('drain events incoming : ' + info.inboundDrains); 166 | console.log('drain events outgoing : ' + info.outboundDrains); 167 | } 168 | if(overallTime > 10) { 169 | console.log('overall rate [msg/s] : ' + Math.trunc(this._countDone * 1000 / overallTime)); 170 | } 171 | } 172 | 173 | } 174 | 175 | /** 176 | * @private 177 | */ 178 | class JSONValidator extends Transform { 179 | 180 | constructor(valueStream, setupStream) { 181 | super(Object.create({ 182 | highWaterMark: 500, 183 | decodeStrings: false, 184 | allowHalfOpen: false, 185 | readableObjectMode: true, 186 | writableObjectMode: true 187 | })); 188 | 189 | this._valueStream = valueStream; 190 | 191 | this._setupStream = setupStream; 192 | } 193 | 194 | /** 195 | * @param {!{}} message 196 | * @param {!string} encoding 197 | * @param {!function(error=, message=)} callback 198 | * @protected 199 | * @override 200 | */ 201 | _transform(message, encoding, callback) { 202 | try { 203 | switch(message.stream) { 204 | case this._valueStream: { 205 | JSON.parse(message.payload.toString('utf8')); 206 | this.push(message); 207 | break; 208 | } 209 | case this._setupStream: { 210 | // follow up master data changes, change behavior 211 | break; 212 | } 213 | default: { 214 | // ignore 215 | } 216 | } 217 | callback(); 218 | } catch (e) { 219 | callback(e, message); 220 | } 221 | } 222 | 223 | } 224 | 225 | module.exports.ProduceStatistics = ProduceStatistics; 226 | module.exports.ConsumeStatistics = ConsumeStatistics; 227 | module.exports.JSONValidator = JSONValidator; 228 | module.exports.jsonPayload = Buffer.from('{"a1":10,"a2":"42","a3":"test","a4":{"b":42}}'); 229 | module.exports.dataPayload = Buffer.from('aaaaaaaaaa.aaaaaaaaaa.aaaaaaaaaa.aaaaaaaaaa'); 230 | 231 | 232 | -------------------------------------------------------------------------------- /LICENSES/Apache-2.0.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. 9 | 10 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. 11 | 12 | "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. 13 | 14 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. 15 | 16 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. 17 | 18 | "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. 19 | 20 | "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). 21 | 22 | "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. 23 | 24 | "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." 25 | 26 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 27 | 28 | 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 29 | 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 30 | 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: 31 | (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and 32 | (b) You must cause any modified files to carry prominent notices stating that You changed the files; and 33 | (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and 34 | (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. 35 | You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 36 | 37 | 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 38 | 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 39 | 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 40 | 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 41 | 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. 42 | END OF TERMS AND CONDITIONS 43 | 44 | APPENDIX: How to apply the Apache License to your work. 45 | 46 | To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. 47 | 48 | Copyright [yyyy] [name of copyright owner] 49 | 50 | Licensed under the Apache License, Version 2.0 (the "License"); 51 | you may not use this file except in compliance with the License. 52 | You may obtain a copy of the License at 53 | 54 | http://www.apache.org/licenses/LICENSE-2.0 55 | 56 | Unless required by applicable law or agreed to in writing, software 57 | distributed under the License is distributed on an "AS IS" BASIS, 58 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 59 | See the License for the specific language governing permissions and 60 | limitations under the License. 61 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /xb-msg-amqp-v100-doc/README.md: -------------------------------------------------------------------------------- 1 | # @sap/xb-msg-amqp-v100 2 | Provides a protocol implementation for [AMQP 1.0](http://www.amqp.org/specification/1.0/amqp-org-download). 3 | 4 | ## Table of contents 5 | 6 | * [Prerequisites](#prerequisites) 7 | * [Install](#install) 8 | * [Overview](#overview) 9 | * [Getting started](#getting-started) 10 | * [API](#api) 11 | * [Client Options](#client-options) 12 | * [Server Options](#server-options) 13 | * [Endpoints](#endpoints) 14 | * [Dynamic Endpoints](#dynamic-endpoints) 15 | * [Common Behavior](#common-endpoint-behavior) 16 | * [Session](#session) 17 | * [Sender](#sender) 18 | * [Outgoing Stream](#outgoing-stream) 19 | * [Delivery Tags](#delivery-tags) 20 | * [Receiver](#receiver) 21 | * [Incoming Stream](#incoming-stream) 22 | * [Message Delivery](#message-delivery) 23 | * [Streams](#message-streams) 24 | * [Piped Streams](#piped-message-streams) 25 | * [Message Source and Target](#message-source-and-target) 26 | * [Convert Source and Target](#convert-source-and-target) 27 | * [Variable Message Routing](#variable-message-routing) 28 | * [Quality of Service](#quality-of-service) 29 | * [Mixed Quality of Service](#mixed-quality-of-service) 30 | * [Flow Control](#flow-control) 31 | * [Payload](#message-payload) 32 | * [Payload and AMQP values](#message-payload-and-amqp-values) 33 | * [Payload and Websocket Data Masking](#message-payload-and-websocket-data-masking) 34 | * [Constraints](#constraints) 35 | * [Further Links](#further-links) 36 | 37 | ## Prerequisites 38 | 39 | Make sure to have a message broker available for testing, e.g. [RabbitMQ](https://www.rabbitmq.com/download.html) with enabled AMQP 1.0 plugin. 40 | 41 | ## Install 42 | 43 | Add the SAP NPM Registry to your npm configuration for all `@sap` scoped modules. 44 | 45 | ```bash 46 | npm config set @sap:registry https://npm.sap.com 47 | ``` 48 | 49 | Add the dependency in applications `package.json` and run npm for it: 50 | 51 | ```bash 52 | npm install 53 | ``` 54 | 55 | To generate complete API documentation run inside the library package folder 56 | 57 | ```bash 58 | npm run doc 59 | ``` 60 | 61 | ## Overview 62 | 63 | This library provides a messaging client as well as classes to realize a server for [AMQP 1.0](http://www.amqp.org/specification/1.0/amqp-org-download). 64 | 65 | Either TLS or NET socket is used, depending on the defined client options. 66 | Besides plain TCP/IP also WebSocket is supported, with and without [OAuth 2.0](https://oauth.net/2/), grant flows [ClientCredentialsFlow](https://tools.ietf.org/html/rfc6749#section-4.4) and [ResourceOwnerPasswordCredentialsFlow](https://tools.ietf.org/html/rfc6749#section-4.3). 67 | 68 | The API works completely asynchronous based on callbacks, typically providing done (resolve) and failed (reject) callbacks. 69 | Hence, it will be simple to use Promise objects in the application even if this library does not use it so far. 70 | 71 | ## Getting started 72 | 73 | There are test programs in the package folder `./examples` to demonstrate: 74 | * How to use a client as [producer](examples/producer.js), [consumer](examples/consumer.js) or [counter](examples/counter.js) 75 | * How to realize a server, here first basics for a protocol [gateway](examples/gateway.js) 76 | 77 | All client examples shall run with provided defaults immediately if e.g. RabbitMQ is installed at localhost:5672 with user guest/guest, having the AMQP 1.0 plugin enabled. 78 | Alternatively, the producer may run in combination with the gateway example. 79 | 80 | The library has been tested successfully in combination with: 81 | * RabbitMQ, version `3.6.6`, 82 | * Solace VMR, as of version `8.5.0.1008`, 83 | * AMQPNetLite, version `2.1.1`, 84 | * Apache Qpid Proton-J, version `0.23.0` 85 | 86 | All examples accept individual settings, e.g. to use a remote host or to try different stream settings. 87 | It can be provided with a js-file given as command line parameter. The file shall just export the options. 88 | Run it like this if the file is stored in folder ```config```, same level as ```examples```. 89 | 90 | ```bash 91 | node .\examples\producer.js ..\config\my-options.js 92 | ``` 93 | 94 | Feel free to start testing with the following file content: 95 | 96 | ```bash 97 | 'use strict'; 98 | 99 | module.exports = { 100 | net: { 101 | host : '127.0.0.1', 102 | port : 5672 103 | }, 104 | sasl: { 105 | mechanism : '', 106 | user : 'guest', 107 | password : 'guest' 108 | }, 109 | data: { 110 | source : 'q001', // a queue name, source address for a receiver 111 | target : 'q002', // a queue name, target address for a sender 112 | payload : new Buffer.allocUnsafe(50).fill('X'), 113 | maxCount : 10000, 114 | logCount : 1000 115 | } 116 | }; 117 | ``` 118 | 119 | The `data` section is ignored by the client, it is just used by the example programs. 120 | 121 | ## API 122 | 123 | First, the library provides a `Client` class. It represents one AMQP container and is able to manage one connection. 124 | `Session`, `Sender` and `Receiver` are provided as endpoints. 125 | Readable/Writable streams are used to consume/produce messages. 126 | 127 | For the server implementation a basic `Server` class is provided. 128 | Like `Client` it supports connections running plain TCP (net/tls) as well as WebSocket (http/https). 129 | 130 | Incoming connections are represented as instances of the `Connection` class. 131 | `Connection` instances can also be created by an application-specific, more specialized server class. 132 | It could for example support different connection types or WebSocket sub-protocols in parallel or could apply more strict validation rules. 133 | 134 | ### Client Options 135 | 136 | Client instances are created directly, just providing options to the constructor: 137 | 138 | ```bash 139 | const AMQP = require('@sap/xb-msg-amqp-v100'); 140 | 141 | ... 142 | const client = new AMQP.Client(options); 143 | ... 144 | ``` 145 | 146 | Options for a plain TCP connection, authenticating with user/password only: 147 | 148 | ```bash 149 | const options = { 150 | net: { 151 | host: 'localhost', 152 | port: 5672, 153 | }, 154 | sasl: { 155 | mechanism: 'PLAIN', 156 | user: 'guest', 157 | password: 'guest' 158 | } 159 | }; 160 | ``` 161 | 162 | Options for a plain TCP connection, using TLS and special trusts: 163 | 164 | ```bash 165 | const options = { 166 | tls: { 167 | host: 'localhost', 168 | port: 5671, 169 | ca: [ 170 | fs.readFileSync('../truststore/cacert.pem'), 171 | fs.readFileSync('../truststore/cert.pem') 172 | ] 173 | }, 174 | sasl: { 175 | mechanism: 'PLAIN', 176 | user: 'guest', 177 | password: 'guest' 178 | } 179 | }; 180 | ``` 181 | 182 | Options to run AMQP over WebSocket (HTTP): 183 | 184 | ```bash 185 | const options = { 186 | ws: { 187 | host: 'localhost', 188 | port: 80, 189 | path: '/' 190 | auth: 'webUser:webPass' 191 | } 192 | sasl: { 193 | mechanism: 'PLAIN', 194 | user: 'guest', 195 | password: 'guest' 196 | } 197 | }; 198 | ``` 199 | 200 | Options to run AMQP over WebSocket, using TLS (HTTPS) with well-known CA: 201 | 202 | ```bash 203 | const options = { 204 | wss: { 205 | host: 'localhost', 206 | port: 443, 207 | path: '/' 208 | }, 209 | sasl: { 210 | user: 'guest', 211 | password: 'guest' 212 | } 213 | }; 214 | ``` 215 | 216 | Either 'tls' [attributes](https://nodejs.org/api/tls.html#tls_tls_connect_options_callback), 'net' [attributes](https://nodejs.org/api/net.html#net_socket_connect_options_connectlistener), wss [attributes](https://nodejs.org/api/https.html#https_https_request_options_callback) or ws [attributes](https://nodejs.org/api/http.html#http_http_request_options_callback) must be provided. 217 | If more than one is defined the preference is as follows: preferred 'tls' then 'net' then 'wss' then finally 'ws'. 218 | 219 | In case of WebSocket options the client will overwrite the HTTP method (with GET) and all web-socket relevant header fields. 220 | Everything else is given to `http.request()` or `https.request()`. 221 | 222 | Hence, you could for example use a specialized https agent: 223 | 224 | ```bash 225 | const HttpsProxyAgent = require('https-proxy-agent'); 226 | 227 | ... 228 | const options = { 229 | wss: { 230 | host : 'my.host.behind.proxy', 231 | port : 443, 232 | path: '/', 233 | agent: new HttpsProxyAgent('http://proxy:8080') 234 | }, 235 | sasl: { 236 | user: 'guest', 237 | password: 'guest' 238 | } 239 | }; 240 | ``` 241 | 242 | It is also possible to provide connection data as URI. 243 | 244 | ```bash 245 | const options = { 246 | uri: 'amqp://user:pass@localhost:5672/?container=myAMQPContainerID' 247 | }; 248 | ``` 249 | 250 | To use 'tls' again with own trust: 251 | 252 | ```bash 253 | const options = { 254 | uri: 'amqps://user:pass@localhost:5671?cacertfile=cacert.pem&cacertfile=cert.pem' 255 | }; 256 | ``` 257 | 258 | Finally, also an array of URIs can be provided: 259 | 260 | ```bash 261 | const options = { 262 | uri: [ 263 | 'amqp://user11:pass11@host11:7777/?container=ABC123', 264 | 'amqp://user22:pass22@host22:9999/?container=XYZ789' 265 | ] 266 | }; 267 | ``` 268 | 269 | The client will start using the first URI and will try further URIs automatically in the given sequence until the connection can be established. 270 | If the client fails with all URIs then it stops and waits for another explicit call to connect. 271 | At this point an event `'disconnected'` is raised. 272 | 273 | An application that requires a continuously opened connection shall always handle the `'disconnect'` event by calling `client.connect()` again, of course after a given delay time. 274 | Timers or other mechanisms may be used, depending on the application design. 275 | But keep in mind that NodeJS runtime does not guarantee precise timer execution. The scheduling depends on the event queue load. 276 | 277 | Finally, URIs can also be combined with all other settings. URI data (as far as provided) will just overwrite the corresponding fields. 278 | A typical example: 279 | 280 | ```bash 281 | const options = { 282 | uri: [ 283 | 'amqp://user11:pass11@host11:7777', 284 | 'amqp://user22:pass22@host22:9999' 285 | ] 286 | amqp: { 287 | containerID: '', // auto-generated by client 288 | maxMessageSize: 1000000 // bytes 289 | autoDeliveryTagPrefix: 'tag-', 290 | outgoingSessionWindow: 1000, 291 | incomingSessionWindow: 1000, 292 | maxReceiverLinkCredit: 255, 293 | minReceiverLinkCredit: 200 294 | } 295 | }; 296 | ``` 297 | 298 | WebSocket connections may require the use of [OAuth 2.0](https://oauth.net/2/) as well, for example a local application connecting to SAP cloud. 299 | Relevant grant flows are: [ClientCredentialsFlow](https://tools.ietf.org/html/rfc6749#section-4.4) and [ResourceOwnerPasswordCredentialsFlow](https://tools.ietf.org/html/rfc6749#section-4.3). 300 | 301 | ```bash 302 | const options = { 303 | wss: { 304 | host: 'myapp.cfapps.sap.hana.ondemand.com', 305 | port: 443, 306 | path: '/' 307 | }, 308 | oa2: { 309 | endpoint: 'https://myzone.authentication.sap.hana.ondemand.com/oauth/token', 310 | client: 'myclientid', 311 | secret: 'myclientsecret', 312 | }, 313 | sasl: { 314 | mechanism: 'ANONYMOUS', 315 | identity: 'test.user@sap.com' 316 | } 317 | }; 318 | ``` 319 | 320 | Further settings for the OAuth token request, for example a special agent: 321 | 322 | ```bash 323 | const options = { 324 | wss: { 325 | host: 'myapp.cfapps.sap.hana.ondemand.com', 326 | port: 443, 327 | path: '/' 328 | agent: new HttpsProxyAgent('http://proxy:8080') 329 | }, 330 | oa2: { 331 | endpoint: 'https://myzone.authentication.sap.hana.ondemand.com/oauth/token', 332 | client: 'myclientid', 333 | secret: 'myclientsecret', 334 | request: { 335 | agent: new HttpsProxyAgent('http://proxy:8080') 336 | } 337 | }, 338 | sasl: { 339 | mechanism: 'ANONYMOUS', 340 | identity: 'test.user@sap.com' 341 | } 342 | }; 343 | ``` 344 | 345 | ### Server Options 346 | 347 | Similar to `Client` new server instances are created, using the constructor: 348 | 349 | ```bash 350 | const AMQP = require('@sap/xb-msg-amqp-v100'); 351 | 352 | ... 353 | const server = new AMQP.Server(options); 354 | ... 355 | server.listen(); 356 | ``` 357 | 358 | Options for plain TCP connections, accepting two SASL mechanisms (validation triggered by event): 359 | 360 | ```bash 361 | const options = { 362 | net: { 363 | port: 9999, 364 | }, 365 | sasl: { 366 | mechanism: 'ANONYMOUS PLAIN', 367 | } 368 | }; 369 | ``` 370 | 371 | To use WebSocket with or without SASL processing, both possible in parallel: 372 | 373 | ```bash 374 | const options = { 375 | ws: { 376 | port: 8888, 377 | }, 378 | sasl: { 379 | mechanism: 'ANONYMOUS PLAIN', 380 | mandatory: false 381 | } 382 | }; 383 | ``` 384 | 385 | Secure plain TCP connections and more restrictive protocol settings: 386 | 387 | ```bash 388 | const options = { 389 | tls: { 390 | port: 5671, 391 | }, 392 | sasl: { 393 | mechanism: 'PLAIN EXTERNAL', 394 | }, 395 | amqp: { 396 | outgoingSessionWindow: 100, 397 | incomingSessionWindow: 100, 398 | maxReceiverLinkCredit: 10, 399 | minReceiverLinkCredit: 5 400 | maxMessageSize: 10000 // bytes 401 | } 402 | } 403 | ``` 404 | 405 | The server will create one `Connection` instance for each incoming client connection. 406 | When running an own (more specialized) server similar instances can be created. 407 | 408 | The AMQP protocol is completely handled by the `Connection` class. It requires the same options as the `Server` class, but uses only the sections `sasl`, `amqp` and `tune`. 409 | 410 | ```bash 411 | const AMQP = require('@sap/xb-msg-amqp-v100'); 412 | 413 | const options = { 414 | sasl: { 415 | mechanism: 'PLAIN EXTERNAL', 416 | mandatory: true 417 | }, 418 | amqp: { 419 | outgoingSessionWindow: 100, 420 | incomingSessionWindow: 100, 421 | maxReceiverLinkCredit: 10, 422 | minReceiverLinkCredit: 5 423 | maxMessageSize: 10000 // bytes 424 | } 425 | tune: { 426 | ostreamPayloadCopyLimit: 1024 // bytes 427 | } 428 | } 429 | 430 | function init(socket) { 431 | try { 432 | const connection = new Connection(socket, 'net', options); 433 | ... 434 | connection 435 | .once('authenticate', (mechanism, data, callback) => {...} 436 | .once('ready', (peerInfo) => {...} 437 | .once('abort', (hadError) => {...} 438 | .once('close', (hadError) => {...} 439 | .on('error', (error) => {...} 440 | .on('sender', (endpoint) => {...} 441 | .on('receiver', (endpoint) => {...} 442 | ; 443 | ... 444 | } catch(e) { 445 | socket.destroy(e); // if e.g. options were not accepted 446 | } 447 | } 448 | ``` 449 | 450 | The [gateway](examples/gateway.js) example uses all of the defined events, you may compare it as check list. 451 | More details can also be found in JSDoc. 452 | 453 | `Connection` instances behave always the same, independent from the used server class. 454 | Each instance offers the expected endpoints: `Session`, `Sender`, `Receiver`. 455 | 456 | ### Endpoints 457 | 458 | Once a connection has been established its usage is quite symmetric for both peers. 459 | At least foreseen by the specification client and server both can begin and end sessions as well as attach and detach incoming or outgoing links. 460 | 461 | For example, a server may wait for clients to connect and may afterwards immediately begin a session, attach an outgoing link and may finally start sending messages (that the client has never asked for). 462 | 463 | However, in typical scenarios the client takes the active role and the server will wait for client requests. 464 | In particular, if the server is actually a message broker this is the expected behavior. 465 | 466 | #### Dynamic Endpoints 467 | 468 | The boolean endpoint property _dynamic_ indicates whether or not an endpoint was created on peers request. 469 | `Session`, `Sender` and `Receiver` provide a common getter for it. 470 | The property is not covered by the specification, it is just used by this API as part of the endpoint lifecycle control. 471 | 472 | `Client` and `Connection` both support _dynamic_ endpoints as follows: 473 | 474 | * raise an event each time a dynamic endpoint was created and opened the very first time, 475 | * destroy it immediately if the event is not handled to avoid uncontrolled resource consumption, 476 | * destroy it automatically latest on connection close, 477 | * allow the application to destroy it at any earlier point in time. 478 | 479 | In addition the `Client` allows to create _non-dynamic_ endpoints, which stay registered by `name` or `id` until the application destroys it explicitly. 480 | Those endpoints can be used at any point in time, with or without an opened connection. 481 | 482 | #### Common Endpoint Behavior 483 | 484 | Overview on common methods for `Session`, `Sender` and `Receiver` (check JSDoc for details): 485 | 486 | * `dynamic()`: returns `true` if the endpoint was created on peers request, 487 | * `active()`: returns `true` if the endpoint gets opened automatically once `Client` is connected, 488 | * `opened()`: returns `true` if local and remote endpoint are interactive, 489 | * `closed()`: returns `true` if local and remote endpoint are neither opened nor on the way to open, 490 | * `destroyed()`: returns true if the endpoint was destroyed; it is not registered anymore, 491 | * `destroy()`: will immediately destroy the endpoint and cancel all of its messages in transit. 492 | 493 | Overview on common events for `Session`, `Sender` and `Receiver` (check JSDoc for details): 494 | 495 | * `opened`: raised if the local and the remote endpoint are both opened, 496 | * `closed`: raised if the local and the remote endpoint are both not opened, 497 | * `destroy`: raised before the local endpoint is destroyed, application shall release any reference. 498 | 499 | Further methods and events depend on the specific endpoint type and applicable performatives. 500 | 501 | #### Session 502 | 503 | Each [session](http://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-transport-v1.0-os.html#section-sessions) groups multiple [links](http://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-transport-v1.0-os.html#section-links) and provides a higher-level flow control. 504 | For a single connection multiple sessions can be used, but one session is usually sufficient. 505 | 506 | A stable session identifier (comparable to a link name) is not defined by the specification. 507 | That's why, the library introduces an identifier (a simple string) just for local usage and applications convenience. 508 | It is never visible to the peer. 509 | 510 | There is one default session in use, identified with an empty string: 511 | 512 | ```bash 513 | const defSession = client.session(''); 514 | ... 515 | const anySession = client.session('anyLocalID'); 516 | ``` 517 | 518 | Overview on `Session` specific methods (check JSDoc for details): 519 | 520 | * all [common endpoint methods](#common-endpoint-behavior) and 521 | * `begin(outgoing, incoming, options)`: _begin_ session, all parameters optional and defaulted by client options, 522 | * `flow(outgoing, incoming)`: change current incoming and outgoing window size, 523 | * `end()`: _end_ the session, no messages will be sent or received, attached outgoing streams will wait based on flow control. 524 | 525 | Overview on `Session` specific events (check JSDoc for details): 526 | 527 | * all [common endpoint events](#common-endpoint-behavior) and 528 | * `flow`: flow settings were updated by the corresponding remote endpoint. 529 | 530 | A session will automatically _begin_ if at least one active link endpoint is assigned to it. 531 | However, this can also be triggered explicitly. 532 | 533 | ```bash 534 | client.session('').begin(200, 200); 535 | ``` 536 | 537 | The inherited method `destroy()` will first destroy all currently attached links before destroying itself. 538 | 539 | #### Sender 540 | 541 | Each `Sender` offers an `OutgoingStream` which extends the NodeJS stream class `Writable`. 542 | The stream runs in object mode and expects plain message objects (see also [Message Streams](#message-streams)). 543 | 544 | Overview on `Sender` methods (check JSDoc for details): 545 | 546 | * all [common endpoint methods](#common-endpoint-behavior) and 547 | * `session()`: returns the currently assigned session endpoint, 548 | * `name()`: returns the link name, 549 | * `options()`: returns current settings as plain object, 550 | * `stream()`: returns the currently associated stream, 551 | * `attach()`: update settings, create the stream, _attach_ the link and return the stream, 552 | * `detach()`: destroy the stream and _detach_ the link, 553 | 554 | A `Sender` provides only the [common endpoint events](#common-endpoint-behavior) (check JSDoc for details): 555 | 556 | Method `attach()` may also be called if the client is not connected. 557 | This will switch the endpoint in active mode and it will automatically _attach_ whenever a connection is opened successfully. 558 | 559 | Immediately after calling `attach()` the application may also start using the stream. 560 | In any case flow control must be handled correctly, based on the standard NodeJS stream API. 561 | 562 | As long as the endpoint is `active()` it will try to send all queued messages. 563 | Even if the connection is interrupted the endpoint will resume its work as soon as the connection is opened again. 564 | 565 | The inherited method `destroy()` will first _detach_ the endpoint before destroying its stream and finally itself. 566 | Destroying the stream means all queued messages including those that are already in transit will be cancelled. 567 | The message `failed` callback is used to notify the application. 568 | 569 | The application may also call `stream.end()` to indicate end of usage. 570 | New messages are not accepted anymore, but all queued messages will be processed before the link is detached. 571 | 572 | A `Sender` manages one instance of an `OutgoingStream`. 573 | 574 | #### Outgoing Stream 575 | 576 | Overview on `OutgoingStream` methods (check JSDoc for details): 577 | 578 | * all methods of `Writable` and 579 | * `sender(): Sender`: returns the associated sender endpoint, 580 | * `newDeliveryTag():string`: returns a new delivery tag that can be registered by application before usage, 581 | * `flow(available)`: send the amount of locally available messages, 582 | * `delivered():UInt`: returns the amount of delivered messages, 583 | * `available():UInt`: returns the amount of available messages, 584 | * `credit():UInt`: returns the remaining message transfer credit, 585 | 586 | Overview on `OutgoingStream` events (check JSDoc for details): 587 | * all events of `Writable` and 588 | * `ready`: indicates the stream is attached and messages will now really be sent, not only queued. 589 | 590 | ```bash 591 | stream 592 | .on('ready', () => { 593 | send(); 594 | }) 595 | .on('drain', () => { 596 | send(); 597 | }) 598 | .on('finish', () => { 599 | client.disconnect(); 600 | }); 601 | ``` 602 | 603 | #### Delivery Tags 604 | 605 | If the application writes a message without a deliveryTag to an outgoing stream then this tag will be generated automatically. 606 | The result will be the same as if the application would have called `stream.newDeliveryTag()`, but the application was not able to register the tag for any kind of message correlation later on. 607 | 608 | Generated delivery tags will start with `options.amqp.autoDeliveryTagPrefix`, by default 'tag-'. 609 | Hence, the application may also use own delivery tags in parallel with generated tags, easily avoiding duplicate tags being used. 610 | 611 | See also the [producer](examples/producer.js) example. 612 | 613 | #### Receiver 614 | 615 | Each `Receiver` offers an `IncomingStream` which extends the NodeJS stream class `Readable`. 616 | The stream runs in object mode and manages plain message objects (see also [Message Streams](#message-streams)). 617 | 618 | Overview on `Receiver` methods (check JSDoc for details): 619 | 620 | * all [common endpoint methods](#common-endpoint-behavior) and 621 | * `session()`: returns the currently assigned session endpoint, 622 | * `name()`: returns the link name, 623 | * `options()`: returns current settings as plain object, 624 | * `stream()`: returns the currently associated stream, 625 | * `attach()`: update settings, create the stream, _attach_ the link and return the stream, 626 | * `detach()`: destroy the stream and _detach_ the link, 627 | 628 | A `Receiver` provides only the [common endpoint events](#common-endpoint-behavior) (check JSDoc for details): 629 | 630 | Method `attach()` may also be called if the client is not connected and it will return the stream already. 631 | The endpoint is switched into active mode and will automatically _attach_ whenever a connection is opened successfully. 632 | 633 | The inherited method `destroy()` will first _detach_ before destroying its stream and finally itself. 634 | Destroying the stream means: 635 | 636 | * all queued messages will be deleted immediately; it will not reach the application anymore, 637 | * for messages in transit (already provided to the application, but not yet done) a following `done()` callback is ignored, 638 | 639 | A `Receiver` manages one instance of an `IncomingStream`. 640 | 641 | #### Incoming Stream 642 | 643 | The IncomingSteam handles also flow control for the application. 644 | It can renew the transfer credit after it was consumed and it can reduce the credit if application has to consume slower as the sender can send. 645 | 646 | Overview on `IncomingStream` methods (check JSDoc for details): 647 | 648 | * all methods of `Readable` and 649 | * `receiver(): Receiver`: returns the associated receiver endpoint, 650 | * `flow(maxCredit, minCredit)`: updates message transfer credit settings, 651 | * `delivered():UInt`: returns the amount of messages received by this stream, 652 | * `available():UInt`: returns the amount of available messages from the remote endpoint, 653 | * `credit():UInt`: returns the remaining message transfer credit, 654 | 655 | Overview on `IncomingStream` events (check JSDoc for details): 656 | * all events of `Readable` and 657 | * `subscribed`: indicates the stream is attached and messages could be received now. 658 | 659 | ```bash 660 | stream 661 | .on('subscribed', () => { 662 | console.log('attached'); 663 | }) 664 | .on('data', (message) => { 665 | ... 666 | message.done(); 667 | ... 668 | }); 669 | ``` 670 | 671 | As soon as the current credit reaches `minCredit`, the incoming stream will renew the credit with maxCredit automatically. 672 | If the application decides to set `minCredit = -1` then the application will have to renew the credit explicitly using method `stream.flow(maxCredit, minCredit)`. 673 | 674 | The application must always call `message.done()`, independent from chosen settle mode. 675 | 676 | See also the [consumer](examples/consumer.js) example. 677 | 678 | ### Message Delivery 679 | 680 | Messages are transferred as soon as a link between a `Sender` and a `Receiver` is attached. 681 | 682 | #### Message Streams 683 | 684 | As mentioned earlier `Writable` and `Readable` streams are provided to handle outgoing and incoming messages. 685 | These streams always run in object mode using `options.amqp.linkHighWaterMsgCount`. 686 | 687 | Here, a single message is represented as a plain object with the following attributes: 688 | * `source`: defined by the incoming stream, providing transfer attributes as well as the message header, annotations and properties, 689 | * `target`: defined optionally by the application, similar to the source, accepted by the outgoing stream, 690 | * `payload`: message data to transfer, see next chapter for details, 691 | * `done`: a callback function to confirm final message processing, 692 | * `failed`: a callback function to indicate processing failure. 693 | 694 | A receiving application is expected to call either `done` or `failed` for each single message, exactly one time (maybe asynchronously) and independent from the used link settings. 695 | 696 | If a transfer was received unsettled then `done` will send a disposition with outcome [DeliveryAccepted](http://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-messaging-v1.0-os.html#type-accepted). 697 | 698 | In the case of a processing error, `failed` will either send outcome [DeliveryRejected](http://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-messaging-v1.0-os.html#type-rejected) (if an error object is provided) or [DeliveryReleased](http://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-messaging-v1.0-os.html#type-released) otherwise. 699 | 700 | ```bash 701 | stream.on('data', (message) => { 702 | try { 703 | JSON.parse(message.payload.toString('utf8')); 704 | ... 705 | message.done(); 706 | } catch (e) { 707 | message.failed(e); 708 | } 709 | }; 710 | ``` 711 | 712 | A sending application can define the callbacks to get notified about the transfer result. 713 | 714 | ```bash 715 | const message = { 716 | payload : Buffer.from('test'), 717 | done : () => this._onSendDone(message), 718 | failed : (error) => this._onSendFailed(error, message) 719 | }; 720 | const noPause = stream.write(message); 721 | ``` 722 | 723 | #### Piped Message Streams 724 | 725 | An application may also pass trough (or transform) a received message from an incoming stream to an outgoing stream. 726 | In this case both streams would directly handle `done` and `failed` correctly. 727 | 728 | ```bash 729 | class Processor extends Transform { 730 | super({ 731 | writableObjectMode: true, 732 | writableHighWaterMark: 16 733 | readableObjectMode: true, 734 | readableHighWaterMark: 16 735 | }); 736 | 737 | _transform(message, encoding, callback) { 738 | try { 739 | JSON.parse(message.payload.toString('utf8')); 740 | ... 741 | this.push(message); 742 | callback(); 743 | } catch (e) { 744 | callback(e); 745 | } 746 | } 747 | } 748 | ... 749 | const istream = client.receiver('inp').attach('queue:q001'); 750 | const ostream = client.sender('out').attach('topic:a/b/c'); 751 | ... 752 | istream.pipe(new Processor()).pipe(ostream); 753 | ... 754 | client.connect(); 755 | ``` 756 | 757 | #### Message Source and Target 758 | 759 | Both, `message.source`and `message.target` provide the same fields (check JSDoc for details): 760 | 761 | * `deliveryTag`: an application tag to identify (and correlate) the message, 762 | * `batchable`: true if a disposition can be delayed in order to optimize processing, 763 | * `settled`: true if the sender has already settled, 764 | * `rcvSettleMode`: senders requested receiver settle mode, 765 | * `header`: plain object with header data ([see specification](http://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-messaging-v1.0-os.html#type-header)), 766 | * `annotations`: map with message annotations ([see specification](http://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-messaging-v1.0-os.html#type-message-annotations)), 767 | * `properties`: plain object with message properties ([see specification](http://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-messaging-v1.0-os.html#type-properties)). 768 | 769 | All target data are optional, defaults originate from the link definition that the message is sent over. 770 | 771 | #### Convert Source and Target 772 | 773 | Two fields of the `Client` and the `Connection` options allow the registration of conversion exits: 774 | * `options.amqp.mapIncomingMsgSource` 775 | * `options.amqp.mapOutgoingMsgTarget` 776 | 777 | The application or any other library could replace the default functions (check JSDoc for parameters). 778 | For example, @sap/xb-msg-env uses this mechanism to assure that a unified message source is provided and a unified target can be used by application. 779 | 780 | #### Variable Message Routing 781 | 782 | Using `message.target` the application can select dynamically the address that the message is sent to: 783 | 784 | ```bash 785 | let id = '42'; 786 | ... 787 | message.target = { 788 | properties : { 789 | to: 'topic/order/' + id 790 | } 791 | }; 792 | ... 793 | ``` 794 | 795 | This allows to: 796 | * add message-related data as topic segment, e.g. an object identifier, 797 | * forward messages with variable target address over one single link. 798 | 799 | Please note, the specification defines only an [address string](http://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-messaging-v1.0-os.html#type-address-string). 800 | The address syntax depends on the connected service. For example, RabbitMQ, SolaceVMR or SAP Event Mesh support different address expressions. 801 | And even more unexpected, RabbitMQ uses `properties.subject` instead of `properties.to`. 802 | However, package @sap/xb-msg-env would enable a unified processing here, if really needed. 803 | 804 | #### Quality of Service 805 | 806 | Chapter [2.6.12.](http://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-transport-v1.0-os.html#doc-idp438000) of the protocol specification describes how to handle message transfers. 807 | With different combinations of sender and receiver settle mode the usual qualities can be realized. 808 | 809 | | quality | [sndSettleMode](http://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-transport-v1.0-os.html#type-sender-settle-mode) | [rcvSettleMode](http://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-transport-v1.0-os.html#type-receiver-settle-mode) | 810 | | :---: | :---: | :---: | 811 | | at-most-once | 1 | 1 | 812 | | at-least-once | 0 | 0 | 813 | | exactly-once | 0 | 1 | 814 | 815 | Sender and receiver will agree on its settle modes when the link is attached: 816 | ```bash 817 | sender.attach({ 818 | sndSettleMode: 0, 819 | rcvSettleMode: 0, 820 | target: { 821 | address: 'topic:a/b/c' 822 | } 823 | }); 824 | ``` 825 | 826 | ```bash 827 | receiver.attach({ 828 | sndSettleMode: 0, 829 | rcvSettleMode: 0, 830 | source: { 831 | address: 'queue:q001' 832 | } 833 | }); 834 | ``` 835 | 836 | In any case the application has just to select the settle mode, usually at the client side. 837 | The library will assure correct handling of messages in transit, delivery states and message settlement. 838 | 839 | #### Mixed Quality of Service 840 | 841 | A sender may decide dynamically (per single message) on the settle mode. 842 | First, it would define sndSettleMode `mixed` while attaching the link. 843 | 844 | ```bash 845 | sender.attach({ 846 | sndSettleMode: 2, 847 | rcvSettleMode: 0, 848 | target: { 849 | address: 'topic:a/b/c' 850 | } 851 | }); 852 | ``` 853 | 854 | Later it would define the quality of service using the message target. 855 | 856 | ```bash 857 | ... 858 | message.target = { 859 | settled: false, // not yet settled by sender 860 | rcvSettleMode: 0 // receiver settles first 861 | }; 862 | ... 863 | ``` 864 | 865 | #### Flow Control 866 | 867 | There are actually 3 layers of flow control: 868 | * network socket and amount of bytes that is sent or received before the connection is throttled, 869 | * session layer with an incoming and outgoing message transfer window, 870 | * link layer with message transfer credits provided by the receiver to the sender. 871 | 872 | The library handles flow control on all layers automatically to protect the process in which it resides. 873 | The application just has to define the limits for each layer as part of the client or server options: 874 | 875 | * section `options.tune` for the network layer and 876 | * section `options.amqp` for the session and link layer. 877 | 878 | #### Message Payload 879 | 880 | The application may provide the message payload for an outgoing message as follows: 881 | 882 | * a `Buffer` object, 883 | * an `Array` of `Buffer` objects, 884 | * a `Payload` object or a plain object with same properties as `Payload`. 885 | 886 | Properties of a `Payload` object: 887 | * `chunks`: an Array of Buffer objects, 888 | * `type`: an optional string providing the content type, 889 | * `encoding`: an optional string providing the content encoding, 890 | * `data`: any optional data to be sent either as [AMQP sequence](http://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-messaging-v1.0-os.html#type-amqp-sequence) or as [AMQP value](http://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-messaging-v1.0-os.html#type-amqp-value), 891 | * `properties`: [application properties](http://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-messaging-v1.0-os.html#type-application-properties). 892 | 893 | After the payload was given to a sender it must not be modified by the application anymore. 894 | And as soon as a single buffers size exceeds `options.tune.ostreamPayloadCopyLimit` (default 1024 bytes, minimum 128 bytes) it will not be copied anymore, but will be pushed to the network socket directly. 895 | 896 | Incoming messages will always provide a `Payload` object, just for application convenience. 897 | 898 | #### Message Payload and AMQP values 899 | 900 | Usually, the message payload will consist of binary data, an opaque array of bytes from the protocol libraries perspective. 901 | However, AMQP 1.0 allows also a single [AMQP value](http://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-messaging-v1.0-os.html#type-amqp-value) or an [AMQP sequence](http://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-messaging-v1.0-os.html#type-amqp-sequence) alternatively. 902 | 903 | If a received message payload consists of such values then the decoded values are provided as `payload.data` and in addition the corresponding parsed raw bytes as `payload.chunks`. 904 | The field `payload.type` will then have the special value `'amqp-1.0'`, which is not a real mime type and in consequence not in danger to clash with such. 905 | Please note, `'amqp-1.0'` is only a local API convention, not standardized. 906 | However, it has already been introduced by [RabbitMQ AMQP 1.0 plugin](https://github.com/rabbitmq/rabbitmq-amqp1.0). 907 | 908 | For an outgoing message payload with special type `'amqp-1.0'` the encoder will either write `payload.chunks` (if provided) directly without any validation or it will encode the given `payload.data` as AMQP value or AMQP sequence. 909 | 910 | #### Message Payload and WebSocket Data Masking 911 | 912 | Using a plain TCP connection the payload data will be sent unchanged. It may only be split into multiple transfers. 913 | But running a WebSocket connection the encoder will have to mask (means to modify) all data before sending. 914 | 915 | Hence, if (and only if) an application 916 | 917 | * uses WebSocket connections and 918 | * uses payload `Buffer` objects larger than the defined payload copy limit and 919 | * re-uses the same buffer instance(s) for multiple messages then 920 | 921 | it must take a copy of those buffers by itself before writing to an outgoing stream. 922 | 923 | Typically, the payload is created per message and released by application already after calling the client to publish. 924 | In this case do not copy anything. 925 | 926 | ## Constraints 927 | Similar to other libraries not the full scope of AMQP 1.0 could be implemented so far: 928 | * Only the following SASL mechanisms are supported: ANONYMOUS, PLAIN, EXTERNAL, 929 | * Deliveries cannot be resumed; once reconnected those messages are sent again with a new delivery, 930 | * Delivery state [Received](http://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-messaging-v1.0-os.html#type-received) is not used, 931 | * Delivery state [Modified](http://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-messaging-v1.0-os.html#type-modified) is not supported, 932 | * Multiple Transfer Frames for one delivery are collected until the whole message can be provided to the application, 933 | * Message Footer is not supported, received but not exposed at the API, 934 | * Message Delivery Annotations are not supported, received, but not exposed at the API, 935 | * Transactions are not supported, 936 | * Incoming streams handle Quality of Service _Exactly Once_ with one single callback to the application only, 937 | * Source filters are not supported, 938 | * Several fine-grained settings for endpoint lifecycle control may be ignored. 939 | 940 | ## Further Links 941 | 942 | Protocol Specification: 943 | 944 | * [AMQP 1.0, Part 1: Types](http://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-types-v1.0-os.html#toc) 945 | * [AMQP 1.0, Part 2: Transport](http://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-transport-v1.0-os.html#toc) 946 | * [AMQP 1.0, Part 3: Messaging](http://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-messaging-v1.0-os.html#toc) 947 | * [AMQP 1.0, Part 4: Transactions](http://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-transactions-v1.0-os.html#toc) 948 | * [AMQP 1.0, Part 5: Security](http://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-security-v1.0-os.html#toc) 949 | 950 | SASL and supported mechanisms: 951 | 952 | * [SASL Protocol](https://tools.ietf.org/html/rfc4422) 953 | * [SASL Mechanisms](https://www.iana.org/assignments/sasl-mechanisms/sasl-mechanisms.xhtml#sasl-mechanisms-1) 954 | * [SASL Mechanism ANONYMOUS](https://tools.ietf.org/html/rfc4505) 955 | * [SASL Mechanism PLAIN](https://tools.ietf.org/html/rfc4616) 956 | * [SASL Mechanism EXTERNAL](https://tools.ietf.org/html/rfc4422#page-29) 957 | 958 | AMQP and WebSocket: 959 | 960 | * [AMQP WebSocketBinding](http://docs.oasis-open.org/amqp-bindmap/amqp-wsb/v1.0/amqp-wsb-v1.0.html) 961 | * [WebSocket Protocol](https://tools.ietf.org/html/rfc6455) 962 | * [Http User Agent Header](https://tools.ietf.org/html/rfc2616#section-14.43) 963 | * [OAuth 2.0](https://oauth.net/2/) 964 | * [OAuth 2.0, Client Credentials Grant](https://tools.ietf.org/html/rfc6749#section-4.4) 965 | * [OAuth 2.0, Resource Owner Password Credentials Grant](https://tools.ietf.org/html/rfc6749#section-4.3) 966 | 967 | Protocol Support by others: 968 | 969 | * [Rabbit MQ AMQP 1.0 plugin](https://github.com/rabbitmq/rabbitmq-amqp1.0) 970 | * [AMQP 1.0 in Azure Service Bus and Event Hubs protocol guide](https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-amqp-protocol-guide) 971 | * [Solace: Using AMQP 1.0](https://docs.solace.com/Open-APIs-Protocols/Using-AMQP.htm) 972 | * [Solace: AMQP 1.0 Protocol Conformance](https://docs.solace.com/Open-APIs-Protocols/AMQP-Protocol-Conformance.htm) 973 | * [Qpid Proton Overview](https://qpid.apache.org/proton/index.html) 974 | * [Qpid Proton C++ API](https://qpid.apache.org/releases/qpid-proton-0.22.0/proton/cpp/api/index.html) 975 | * [Qpid Proton-J API](https://qpid.apache.org/releases/qpid-proton-j-0.26.0/api/index.html) 976 | * [Qpid JMS](https://qpid.apache.org/components/jms/index.html) 977 | * [Qpid Proton github repository](https://github.com/apache/qpid-proton) 978 | * [.Net Library: AMQP.Net Lite](https://github.com/Azure/amqpnetlite) 979 | * [Node Library: Rhea](https://github.com/amqp/rhea) 980 | * [Node Library: AMQP 1.0](https://github.com/noodlefrenzy/node-amqp10) 981 | 982 | Others: 983 | * [Introduction to AMQP 1.0](https://de.slideshare.net/ClemensVasters/amqp-10-introduction) 984 | * [Node: Backpressuring in Streams](https://nodejs.org/en/docs/guides/backpressuring-in-streams/) 985 | 986 | ## Support 987 | This project is _'as-is'_ with no support, no changes being made. + 988 | You are welcome to make changes to improve it but we are not available for questions or support of any kind. 989 | 990 | ## License 991 | Copyright (c) 2017 SAP SE or an SAP affiliate company. All rights reserved. 992 | This file is licensed under the _SAP SAMPLE CODE LICENSE AGREEMENT, v1.0-071618_ except as noted otherwise in the [LICENSE file](../LICENSE.txt). 993 | --------------------------------------------------------------------------------