This repository has been archived by the owner on Feb 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
271 lines (233 loc) · 9.22 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
var gcloud = require('@google-cloud/pubsub');
var _ = require('lodash');
var nid = require('nid');
module.exports = function (options) {
var seneca = this;
var plugin = 'gcloudpubsub-transport';
var pubsub;
var so = seneca.options();
var tu = seneca.export('transport/utils');
options = seneca.util.deepextend({
gcloud: {
topicPrefix: '',
projectId: '',
keyFilename: ''
}
}, options);
var topicPrefix = options.gcloud.topicPrefix;
seneca.add('role:transport,hook:listen,type:gcloud', hook_listen_gcloud);
seneca.add('role:transport,hook:client,type:gcloud', hook_client_gcloud);
seneca.add('role:seneca,cmd:close', shutdown);
function make_error_handler(type, tag) {
return function (note, err) {
seneca.log.error(type, tag, note, err, 'CLOSED');
}
}
function init(opts) {
return new Promise(function (fulfill, reject) {
try {
// seneca.log.info('OPTIONS');
// seneca.log.info(options['gcloud']);
// var clientOpts = JSON.parse(options['gcloud']);
pubsub = new gcloud({
projectId: opts.projectId,
keyFilename: opts.keyFilename
});
topicPrefix = opts.topicPrefix;
seneca.log.info('Connected to GCloud PubSub');
// seneca.log.info(pubsub);
fulfill(pubsub);
}
catch (ex) {
reject(ex);
}
});
}
function createTopics(pubsub) {
// Validate the topic prefix
// seneca.log.info('OPTS: ' + opts);
function validatePrefix(topicPrefix) {
return new Promise(function (fulfill, reject) {
if (!_.isString(topicPrefix) || _.isEmpty(topicPrefix)
|| topicPrefix.length > 250) {
reject('topicPrefix must be a valid string 250 characters or less!');
}
else {
fulfill();
}
});
}
// Create the request and response topics
function topicCreator(topicName) {
return new Promise(function (fulfill, reject) {
pubsub.createTopic(topicName, function (err, topic) {
if (!err) {
seneca.log.info('Topic "' + topicName + '" created: ', topic);
fulfill(topic);
}
else if (err.code === 409) { // If the topic already exists, just return it
seneca.log.warn('Topic "' + topicName + '" already exists.');
fulfill(pubsub.topic(topicName));
}
else {
seneca.log.info('Failed to create topic: ', topicName);
reject(err);
}
});
});
}
return Promise.all([
validatePrefix(topicPrefix),
topicCreator(topicPrefix + '.act'),
topicCreator(topicPrefix + '.res')
]).then(function (results) {
return Promise.resolve({
act: results[1],
res: results[2]
});
});
}
// Subscribe to a topic object
function createSubscription(topic, kind) {
return new Promise(function (fulfill, reject) {
var subscriber_name = topicPrefix + '.' + kind;
var subs_options = {
autoAck: false,
ackDeadlineSeconds: 20,
interval: 30,
maxInProgress: 1
};
pubsub.subscribe(topic, subscriber_name, subs_options,
function (err, subscription) {
if (err) {
seneca.log.error('Failed to subscribe to "' + topic.name + '"');
reject(err);
}
else {
seneca.log.info('Created subscription to "' + topic.name
+ '", Subscription: ' + subscriber_name);
fulfill(subscription);
}
}
);
});
}
function hook_listen_gcloud(args, done) {
var type = args.type;
var listen_options = seneca.util.clean(_.extend({}, options[type], args));
topicPrefix = listen_options.topicPrefix;
init(listen_options)
.then(createTopics)
.then(subscribeTopics)
.then(function () {
done();
})
.catch(function (err) {
done(err);
});
function subscribeTopics(topics) {
var act_topic = topics.act; // The request topic
var res_topic = topics.res; // The response topic
return createSubscription(act_topic, 'act')
.then(attachHandler);
function attachHandler(subscription) {
return new Promise(function (fulfill, reject) {
seneca.log.info('Subscribing to ' + subscription.name);
subscription.on('message', onMessage);
fulfill();
});
function onMessage(message) {
// seneca.log.info('Got a request: ' + message.id);
var content = message.data//message.data ? message.data.toString() : undefined;
var data = tu.parseJSON(seneca, 'listen-' + type, content.data);
// Publish message
tu.handle_request(seneca, data, listen_options, function (out) {
if (out == null) return;
res_topic.publish({
data: tu.stringifyJSON(seneca, 'listen-' + type, out)
}, function (err) {
if (err)
seneca.log.error('Failed to send message: ' + err);
// Acknowledge the message
message.ack(function (err) {
if (err)
seneca.log.warn('Failed to ack message: ' + message.id);
});
});
});
}
}
}
}
function hook_client_gcloud(args, client_done) {
var seneca = this;
var type = args.type;
var client_options = seneca.util.clean(_.extend({}, options[type], args));
init(client_options)
.then(createTopics)
.then(subscribeTopics)
.then(createClient)
.then(function (client) {
client_done(null, client);
})
.catch(function (err) {
client_done(err);
});
function subscribeTopics(topics) {
var res_topic = topics.res; // The response topic
return createSubscription(res_topic, 'res')
.then(function (subscription) {
return Promise.resolve({
topics: topics,
subscription: subscription
});
});
}
function createClient(params) {
return new Promise(function (fulfill, reject) {
var act_topic = params.topics.act;
var subscription = params.subscription;
// Subscribe to the response topic
seneca.log.info('Subscribing to ' + subscription.name);
subscription.on('message', onMessage);
function onMessage(message) {
// seneca.log.info('Got a response: ' + message.id);
var content = message.data;//message.data ? message.data.toString() : undefined;
var input = tu.parseJSON(seneca, 'client-' + type, content.data);
// Acknowledge the message
message.ack(function (err) {
if (err)
seneca.log.warn('Failed to ack message: ' + message.id);
});
tu.handle_response(seneca, input, client_options);
}
var client = {
id: nid(),
toString: function () {
return 'any-' + this.id;
},
// TODO: is this used?
match: function (args) {
return !this.has(args);
},
send: function (args, done) {
var outmsg = tu.prepare_request(this, args, done);
act_topic.publish({
data: tu.stringifyJSON(seneca, 'client-' + type, outmsg)
}, function (err) {
if (err)
seneca.log.error('Failed to send message: ' + err);
});
}
};
fulfill(client);
});
}
}
function shutdown(args, done) {
done();
}
return {
name: plugin
};
};