]> git.sesse.net Git - ultimatescore/blob - pubsub/ultimatescore.js
Add a comment about what “Mark game” means.
[ultimatescore] / pubsub / ultimatescore.js
1 /*
2  * ultimatescore.js
3  *
4  * Acts as a bridge to retrieve messages from Google PubSub (with longpolling
5  * to traverse NAT) and forward messages over UDP.
6  *
7  * Sends UDP to host ::1 by default, can be overriden with the first command
8  * line argument. No legacy IP support.
9  *
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
12  * ultimatescore.
13  *
14  * See README for required credential setup.
15  *
16  */
17
18 const {PubSub} = require('@google-cloud/pubsub');
19 const dgram = require('dgram');
20
21 const host = process.argv[2] || '::1';
22 const subscriptionName = 'projects/plastkast/subscriptions/client';
23
24 const sock = dgram.createSocket('udp6');
25
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);
34   });
35
36   const t = setTimeout(() => {
37     console.log('restarting in case we got disconnected');
38     return subscription.close().then(() => {
39       return listenWithRestart();
40     });
41   }, 60*1000);
42 }
43
44 listenWithRestart();
45
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);
51   message.ack();
52 };