4 * Acts as a bridge to retrieve messages from Google PubSub (with longpolling
5 * to traverse NAT) and forward messages over UDP.
7 * Sends UDP to host ::1 by default, can be overriden with the first command
8 * line argument. No legacy IP support.
10 * Uses the port number indicated as an attribute (with the name "port") to the
11 * pubsub messages, for ingestion of data from multiple bodet.js instances to
14 * See README for required credential setup.
18 const {PubSub} = require('@google-cloud/pubsub');
19 const dgram = require('dgram');
21 const host = process.argv[2] || '::1';
22 const subscriptionName = 'projects/plastkast/subscriptions/client';
24 const sock = dgram.createSocket('udp6');
26 // PubSub pull, but with longpolling
27 function listenWithRestart() {
28 const pubsub = new PubSub();
29 const subscription = pubsub.subscription(subscriptionName);
30 console.log('waiting for PubSub messages');
31 subscription.on('message', messageHandler);
32 subscription.on('error', (err) => {
33 console.error('subscription error: ' + err);
36 const t = setTimeout(() => {
37 console.log('restarting in case we got disconnected');
38 return subscription.close().then(() => {
39 return listenWithRestart();
46 function messageHandler(message) {
47 console.log(`PubSub message received, ID ${message.id}: ${message.data}`);
48 const data = new Buffer(message.data);
49 const port = message.attributes.port || 0;
50 sock.send(data, 0, data.length, port, host);