@bitfinex/bfx-facs-grc 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,2 @@
1
+ # bfx-facs-grc
2
+
package/index.js ADDED
@@ -0,0 +1,362 @@
1
+ 'use strict'
2
+
3
+ const async = require('async')
4
+ const GrLink = require('grenache-nodejs-link')
5
+ const GrHttp = require('grenache-nodejs-http')
6
+ const Base = require('@bitfinex/bfx-facs-base')
7
+ const fs = require('fs')
8
+ const { cloneDeep, difference, union } = require('@bitfinexcom/lib-js-util-base')
9
+
10
+ const { buildErr } = require('./lib/utils')
11
+
12
+ class Grc extends Base {
13
+ constructor (caller, opts, ctx) {
14
+ super(caller, opts, ctx)
15
+
16
+ this.name = 'grc'
17
+ this._hasConf = true
18
+
19
+ if (!this.opts.tickInterval) {
20
+ this.opts.tickInterval = 45000
21
+ }
22
+
23
+ if (!this.opts.secPortOffset) {
24
+ this.opts.secPortOffset = 2000
25
+ }
26
+
27
+ caller.on('started', () => {
28
+ this._tickItv = setInterval(() => {
29
+ this.tick()
30
+ }, this.opts.tickInterval)
31
+
32
+ this.tick()
33
+ })
34
+
35
+ this.init()
36
+ }
37
+
38
+ onPreparse (service, req, res, meta, handler) {
39
+ const api = this.api
40
+
41
+ // stream
42
+ const action = api.getStreamHandler(meta.action)
43
+ if (api && action) {
44
+ const rid = meta.infoHeaders[0]
45
+ const service = meta.infoHeaders[1]
46
+
47
+ if (meta.cert) {
48
+ meta._isSecure = true
49
+ meta._auth = {
50
+ fingerprint: meta.cert.fingerprint.toString('hex')
51
+ }
52
+ }
53
+
54
+ api.handleStream(service, action, req, res, meta, (err, res) => {
55
+ handler.reply(rid, buildErr(err), res)
56
+ })
57
+ return
58
+ }
59
+
60
+ service.handleBufferedRequest(req, res, meta)
61
+ }
62
+
63
+ onRequest (rid, service, payload, handler, cert) {
64
+ const api = this.api
65
+
66
+ if (api) {
67
+ if (cert) {
68
+ payload._isSecure = true
69
+ payload._auth = {
70
+ fingerprint: cert.fingerprint.toString('hex')
71
+ }
72
+ }
73
+
74
+ api.handle(service, payload, (err, res) => {
75
+ handler.reply(buildErr(err), res)
76
+ })
77
+ } else {
78
+ this.emit('request', rid, service, payload, handler)
79
+ }
80
+ }
81
+
82
+ setupPeers () {
83
+ if (!this.conf.protos) {
84
+ this.conf.protos = ['gen', 'sec']
85
+ }
86
+
87
+ const protos = this.conf.protos
88
+
89
+ if (protos.indexOf('gen') > -1) {
90
+ this.peer = new GrHttp.PeerRPCClient(this.link, {
91
+ maxActiveKeyDests: this.opts.maxActiveKeyDests
92
+ })
93
+
94
+ this.peerSrv = new GrHttp.PeerRPCServer(this.link, {
95
+ timeout: this.opts.server_timeout || 600000,
96
+ disableBuffered: true
97
+ })
98
+ }
99
+
100
+ if (protos.indexOf('sec') > -1) {
101
+ const secPath = `${this.opts.root}/sec`
102
+
103
+ if (fs.existsSync(secPath)) {
104
+ const sslConf = this.getSslConf(secPath)
105
+
106
+ this.peerSec = new GrHttp.PeerRPCClient(this.link, {
107
+ maxActiveKeyDests: this.opts.maxActiveKeyDests,
108
+ secure: sslConf.peer
109
+ })
110
+
111
+ this.peerSecSrv = new GrHttp.PeerRPCServer(this.link, {
112
+ timeout: this.opts.server_timeout || 600000,
113
+ secure: sslConf.srv,
114
+ disableBuffered: true
115
+ })
116
+ }
117
+ }
118
+ }
119
+
120
+ getSslConf (secPath) {
121
+ const peerSecOptsDefault = {
122
+ key: fs.readFileSync(`${secPath}/client-key.pem`),
123
+ cert: fs.readFileSync(`${secPath}/client-crt.pem`),
124
+ ca: fs.readFileSync(`${secPath}/ca-crt.pem`),
125
+ requestCert: true
126
+ }
127
+
128
+ const srvSecOptsDefault = {
129
+ key: fs.readFileSync(`${secPath}/server-key.pem`),
130
+ cert: fs.readFileSync(`${secPath}/server-crt.pem`),
131
+ ca: fs.readFileSync(`${secPath}/ca-crt.pem`),
132
+ requestCert: true
133
+ }
134
+
135
+ if (!this.conf.ssl) {
136
+ return { peer: peerSecOptsDefault, srv: srvSecOptsDefault }
137
+ }
138
+
139
+ let peer = peerSecOptsDefault
140
+ if (this.conf.ssl.peer) {
141
+ peer = { ...peerSecOptsDefault, ...this.conf.ssl.peer }
142
+ }
143
+
144
+ const srv = srvSecOptsDefault
145
+ if (this.conf.ssl.srv) {
146
+ peer = { ...srvSecOptsDefault, ...this.conf.ssl.srv }
147
+ }
148
+
149
+ return { peer, srv }
150
+ }
151
+
152
+ _start (cb) {
153
+ async.series([
154
+ next => { super._start(next) },
155
+ next => {
156
+ this.link = new GrLink({
157
+ grape: this.opts.grape || this.conf.grape,
158
+ requestTimeout: this.opts.linkRequestTimeout || 2500,
159
+ lruMaxAgeLookup: this.opts.linkRruMaxAgeLookup || 10000
160
+ })
161
+
162
+ this.link.start()
163
+
164
+ switch (this.conf.transport) {
165
+ case 'http':
166
+ this.setupPeers()
167
+ break
168
+ }
169
+
170
+ if (this.peer) {
171
+ this.peer.init()
172
+ this.peerSrv.init()
173
+ }
174
+
175
+ if (this.peerSec) {
176
+ this.peerSec.init()
177
+ this.peerSecSrv.init()
178
+ }
179
+
180
+ next()
181
+ }
182
+ ], cb)
183
+ }
184
+
185
+ tick () {
186
+ let pubServices = cloneDeep(this.opts.services)
187
+ if (!Array.isArray(pubServices) || !pubServices.length) {
188
+ pubServices = null
189
+ }
190
+
191
+ if (!pubServices || !this.opts.svc_port) {
192
+ return
193
+ }
194
+
195
+ if (this.peerSec) {
196
+ for (const s of Object.values(pubServices)) {
197
+ pubServices.push(`sec:${s}`)
198
+ }
199
+ }
200
+
201
+ const port = this.opts.svc_port
202
+ if (!port) {
203
+ console.error('no port set')
204
+ console.error('set port via commandline (--apiPort=$PORT)')
205
+ throw new Error('ERR_NO_PORT')
206
+ }
207
+
208
+ if (!this.service && this.peerSrv) {
209
+ this.service = this.peerSrv.transport('server')
210
+ this.service.listen(port)
211
+ this.service.on('stream', this.onPreparse.bind(this, this.service))
212
+ this.service.on('request', this.onRequest.bind(this))
213
+ }
214
+
215
+ if (!this.serviceSec && this.peerSec) {
216
+ this.serviceSec = this.peerSecSrv.transport('server')
217
+ this.serviceSec.listen(port + this.opts.secPortOffset)
218
+ this.serviceSec.on('stream', this.onPreparse.bind(this, this.serviceSec))
219
+ this.serviceSec.on('request', this.onRequest.bind(this))
220
+ }
221
+
222
+ async.auto({
223
+ announce: next => {
224
+ async.eachSeries(pubServices, (srv, next) => {
225
+ const tPort = srv.indexOf('sec:') === 0 ? port + this.opts.secPortOffset : port
226
+ this.link.announce(srv, tPort, {}, (err) => {
227
+ if (err) console.error(err)
228
+ next()
229
+ })
230
+ }, next)
231
+ }
232
+ }, (err) => {
233
+ if (err) console.error(err)
234
+ })
235
+ }
236
+
237
+ _stop (cb) {
238
+ async.series([
239
+ next => { super._stop(next) },
240
+ next => {
241
+ clearInterval(this._announceItv)
242
+ clearInterval(this._tickItv)
243
+
244
+ this.link.stop()
245
+
246
+ if (this.peerSec) {
247
+ this.peerSec.stop()
248
+ }
249
+
250
+ if (this.peer) {
251
+ this.peer.stop()
252
+ }
253
+
254
+ if (this.service) {
255
+ this.service.stop()
256
+ this.service.removeListener('request', this.onRequest.bind(this))
257
+ this.service.removeListener('stream', this.onPreparse.bind(this, this.service))
258
+ }
259
+
260
+ if (this.serviceSec) {
261
+ this.serviceSec.stop()
262
+ this.serviceSec.removeListener('request', this.onRequest.bind(this))
263
+ this.serviceSec.removeListener('stream', this.onPreparse.bind(this, this.service))
264
+ }
265
+
266
+ next()
267
+ }
268
+ ], cb)
269
+ }
270
+
271
+ setServices (ss) {
272
+ this.opts.services = ss
273
+ }
274
+
275
+ addServices (ss) {
276
+ if (!Array.isArray(this.opts.services)) {
277
+ this.opts.services = []
278
+ }
279
+
280
+ this.opts.services = union(this.opts.services, ss)
281
+ }
282
+
283
+ delServices (ss) {
284
+ if (!Array.isArray(this.opts.services)) {
285
+ this.opts.servies = []
286
+ }
287
+
288
+ this.opts.services = difference(this.opts.services, ss)
289
+ }
290
+
291
+ req (service, action, args, _opts = {}, _cb) {
292
+ return this._doReq('request', service, action, args, _opts, _cb)
293
+ }
294
+
295
+ map (service, action, args, _opts = {}, _cb) {
296
+ return this._doReq('map', service, action, args, _opts, _cb)
297
+ }
298
+
299
+ _doReq (reqType, service, action, args, _opts = {}, _cb) {
300
+ if (typeof _opts === 'function') {
301
+ _cb = _opts
302
+ _opts = {}
303
+ }
304
+ const isPromise = typeof _cb !== 'function'
305
+
306
+ if (typeof action !== 'string') {
307
+ const err = new Error('ERR_GRC_REQ_ACTION_INVALID')
308
+ return isPromise ? Promise.reject(err) : _cb(err)
309
+ }
310
+
311
+ if (!Array.isArray(args)) {
312
+ const err = new Error('ERR_GRC_REQ_ARGS_INVALID')
313
+ return isPromise ? Promise.reject(err) : _cb(err)
314
+ }
315
+
316
+ let isExecuted = false
317
+ let _resolve, _reject
318
+ const cb = (err, res) => {
319
+ if (err) {
320
+ if (err === 'ERR_TIMEOUT') {
321
+ console.error('ERR_TIMEOUT received', service, action, args)
322
+ } else {
323
+ console.error(service, action, args, err)
324
+ }
325
+ }
326
+
327
+ if (isExecuted) {
328
+ console.error('ERR_DOUBLE_CB', service, action, JSON.stringify(args))
329
+ return
330
+ }
331
+ isExecuted = true
332
+
333
+ if (isPromise) {
334
+ return err ? _reject(buildErr(err)) : _resolve(res)
335
+ } else {
336
+ return _cb(buildErr(err), res)
337
+ }
338
+ }
339
+
340
+ const peer = service.indexOf('sec:') === 0 ? this.peerSec : this.peer
341
+
342
+ const opts = { timeout: 120000, ..._opts }
343
+
344
+ if (isPromise) {
345
+ return new Promise((resolve, reject) => {
346
+ _resolve = resolve
347
+ _reject = reject
348
+ peer[reqType](service, {
349
+ action,
350
+ args
351
+ }, opts, cb)
352
+ })
353
+ }
354
+
355
+ peer[reqType](service, {
356
+ action,
357
+ args
358
+ }, opts, cb)
359
+ }
360
+ }
361
+
362
+ module.exports = Grc
package/lib/utils.js ADDED
@@ -0,0 +1,13 @@
1
+ 'use strict'
2
+
3
+ const buildErr = err => {
4
+ if (!err) {
5
+ return null
6
+ }
7
+
8
+ return err instanceof Error ? err : new Error(err.toString())
9
+ }
10
+
11
+ module.exports = {
12
+ buildErr
13
+ }
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@bitfinex/bfx-facs-grc",
3
+ "version": "1.0.0",
4
+ "private": false,
5
+ "description": "Bitfinex Grenache Facility",
6
+ "author": {
7
+ "name": "prdn",
8
+ "email": "paolo@bitfinex.com"
9
+ },
10
+ "main": "index.js",
11
+ "keywords": [
12
+ "bitfinex"
13
+ ],
14
+ "scripts": {
15
+ "lint": "standard",
16
+ "lint:fix": "standard --fix",
17
+ "test": "npm run lint && npm run unit",
18
+ "unit": "mocha"
19
+ },
20
+ "dependencies": {
21
+ "@bitfinex/bfx-facs-base": "git+https://github.com/bitfinexcom/bfx-facs-base.git",
22
+ "@bitfinexcom/lib-js-util-base": "git+https://github.com/bitfinexcom/lib-js-util-base#v1.20.0",
23
+ "async": "3.2.6",
24
+ "grenache-nodejs-http": "1.0.1",
25
+ "grenache-nodejs-link": "1.0.2"
26
+ },
27
+ "engines": {
28
+ "node": ">=16.0"
29
+ },
30
+ "license": "Apache-2.0",
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "git+https://github.com/bitfinexcom/bfx-facs-grc.git"
34
+ },
35
+ "maintainers": [
36
+ {
37
+ "name": "prdn",
38
+ "email": "paolo@bitfinex.com"
39
+ }
40
+ ],
41
+ "devDependencies": {
42
+ "bfx-svc-test-helper": "git+https://github.com/bitfinexcom/bfx-svc-test-helper.git",
43
+ "mocha": "11.2.2",
44
+ "standard": "17.1.2"
45
+ }
46
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "p0": {
3
+ "grape": "http://127.0.0.1:30001",
4
+ "transport": "http"
5
+ },
6
+ "p1": {
7
+ "grape": "http://127.0.0.1:30001",
8
+ "transport": "http"
9
+ }
10
+ }
@@ -0,0 +1,198 @@
1
+ /* eslint-env mocha */
2
+
3
+ 'use strict'
4
+
5
+ const assert = require('assert')
6
+ const { promisify } = require('util')
7
+
8
+ const createGrapes = require('bfx-svc-test-helper/grapes')
9
+ const createFxGrenache = require('bfx-svc-test-helper/fauxgrenache')
10
+
11
+ const Fac = require('..')
12
+
13
+ const stubs = {
14
+ 'rest:util:net': {
15
+ getIpInfo (space, ip, cb) {
16
+ const res = [ip, { country: 'US', region: 'CA' }]
17
+ return cb(null, res)
18
+ }
19
+ }
20
+ }
21
+
22
+ const grapes = createGrapes()
23
+ const caller = {
24
+ on: () => {},
25
+ ctx: { root: __dirname }
26
+ }
27
+
28
+ const fac = new Fac(caller, {}, { env: 'test' })
29
+ fac.tick = () => {}
30
+ fac.conf = { grape: 'http://127.0.0.1:30001', transport: 'http' }
31
+
32
+ let fxg1
33
+ let fxg2
34
+ describe('RPC integration: map', () => {
35
+ before(async function () {
36
+ this.timeout(20000)
37
+
38
+ grapes.onAnnounce()
39
+
40
+ await grapes.start()
41
+ fxg1 = createFxGrenache(stubs, grapes, { port: 1557 })
42
+ fxg2 = createFxGrenache(stubs, grapes, { port: 1558 })
43
+ await fxg1.start()
44
+ await fxg2.start()
45
+
46
+ const start = promisify(fac.start).bind(fac)
47
+ await start()
48
+ })
49
+
50
+ after(async function () {
51
+ this.timeout(5000)
52
+
53
+ await grapes.stop()
54
+ await fxg1.stop()
55
+ await fxg2.stop()
56
+ fac.stop()
57
+ })
58
+
59
+ describe('callback', () => {
60
+ it('options defaults', done => {
61
+ fac.map('rest:util:net', 'getIpInfo', ['8.8.8.8'], (_err, res) => {
62
+ assert.deepStrictEqual([
63
+ ['8.8.8.8', { country: 'US', region: 'CA' }],
64
+ ['8.8.8.8', { country: 'US', region: 'CA' }]
65
+ ], res)
66
+ done()
67
+ })
68
+ })
69
+
70
+ it('success', done => {
71
+ fac.map('rest:util:net', 'getIpInfo', ['8.8.8.8'], {}, (_err, res) => {
72
+ assert.deepStrictEqual([
73
+ ['8.8.8.8', { country: 'US', region: 'CA' }],
74
+ ['8.8.8.8', { country: 'US', region: 'CA' }]
75
+ ], res)
76
+ done()
77
+ })
78
+ })
79
+
80
+ it('lookup error', done => {
81
+ fac.map('foo:test:net', 'getIpInfo', [], {}, (err, res) => {
82
+ assert.strictEqual(err.message, 'ERR_GRAPE_LOOKUP_EMPTY')
83
+ done()
84
+ })
85
+ })
86
+
87
+ it('double cb error', done => {
88
+ const originalPeer = fac.peer
89
+ const originalConsoleError = console.error
90
+
91
+ let errorArgs
92
+ console.error = (...args) => {
93
+ if (errorArgs) {
94
+ done(new Error('Should have been called once'))
95
+ }
96
+ errorArgs = args
97
+ }
98
+
99
+ fac.peer = {
100
+ map (service, args, opts, cb) {
101
+ cb()
102
+ cb()
103
+ fac.peer = originalPeer
104
+ console.error = originalConsoleError
105
+ assert.strictEqual(errorArgs[0], 'ERR_DOUBLE_CB')
106
+ assert.strictEqual(errorArgs[1], 'rest:util:net')
107
+ assert.strictEqual(errorArgs[2], 'getIpInfo')
108
+ done()
109
+ }
110
+ }
111
+
112
+ fac.map('rest:util:net', 'getIpInfo', [], {}, () => {
113
+ assert.strictEqual(errorArgs, undefined)
114
+ })
115
+ })
116
+
117
+ it('invalid args', done => {
118
+ fac.map('rest:util:net', 'getIpInfo', {}, {}, (err, res) => {
119
+ assert.strictEqual(err.message, 'ERR_GRC_REQ_ARGS_INVALID')
120
+ done()
121
+ })
122
+ })
123
+
124
+ it('invalid action', done => {
125
+ fac.map('rest:util:net', {}, [], {}, (err, res) => {
126
+ assert.strictEqual(err.message, 'ERR_GRC_REQ_ACTION_INVALID')
127
+ done()
128
+ })
129
+ })
130
+ })
131
+
132
+ describe('promise', () => {
133
+ it('success', async () => {
134
+ const res = await fac.map('rest:util:net', 'getIpInfo', ['8.8.8.8'], {})
135
+ assert.deepStrictEqual([
136
+ ['8.8.8.8', { country: 'US', region: 'CA' }],
137
+ ['8.8.8.8', { country: 'US', region: 'CA' }]
138
+ ], res)
139
+ })
140
+
141
+ it('lookup error', async () => {
142
+ try {
143
+ await fac.map('foo:test:net', 'getIpInfo', [], {})
144
+ } catch (e) {
145
+ assert.strictEqual(e.message, 'ERR_GRAPE_LOOKUP_EMPTY')
146
+ return
147
+ }
148
+ throw new Error('Should have thrown')
149
+ })
150
+
151
+ it('double cb error', async () => {
152
+ const originalPeer = fac.peer
153
+ const originalConsoleError = console.error
154
+
155
+ fac.peer = {
156
+ map (service, args, opts, cb) {
157
+ cb()
158
+ cb()
159
+ assert.strictEqual(errorArgs[0], 'ERR_DOUBLE_CB')
160
+ assert.strictEqual(errorArgs[1], 'rest:util:net')
161
+ assert.strictEqual(errorArgs[2], 'getIpInfo')
162
+ fac.peer = originalPeer
163
+ console.error = originalConsoleError
164
+ }
165
+ }
166
+
167
+ let errorArgs
168
+ console.error = (...args) => {
169
+ if (errorArgs) {
170
+ throw new Error('Should have been called once')
171
+ }
172
+ errorArgs = args
173
+ }
174
+
175
+ await fac.map('rest:util:net', 'getIpInfo', [], {})
176
+ })
177
+
178
+ it('invalid args', async () => {
179
+ try {
180
+ await fac.map('rest:util:net', 'getIpInfo', {}, {})
181
+ } catch (e) {
182
+ assert.strictEqual(e.message, 'ERR_GRC_REQ_ARGS_INVALID')
183
+ return
184
+ }
185
+ throw new Error('Should have thrown')
186
+ })
187
+
188
+ it('invalid action', async () => {
189
+ try {
190
+ await fac.map('rest:util:net', {}, [], {})
191
+ } catch (e) {
192
+ assert.strictEqual(e.message, 'ERR_GRC_REQ_ACTION_INVALID')
193
+ return
194
+ }
195
+ throw new Error('Should have thrown')
196
+ })
197
+ })
198
+ })
@@ -0,0 +1,184 @@
1
+ /* eslint-env mocha */
2
+
3
+ 'use strict'
4
+
5
+ const assert = require('assert')
6
+ const { promisify } = require('util')
7
+
8
+ const createGrapes = require('bfx-svc-test-helper/grapes')
9
+ const createFxGrenache = require('bfx-svc-test-helper/fauxgrenache')
10
+
11
+ const Fac = require('..')
12
+
13
+ const stubs = {
14
+ 'rest:util:net': {
15
+ getIpInfo (space, ip, cb) {
16
+ const res = [ip, { country: 'US', region: 'CA' }]
17
+ return cb(null, res)
18
+ },
19
+ getTimeoutErr () {}
20
+ }
21
+ }
22
+
23
+ const grapes = createGrapes()
24
+ const caller = {
25
+ on: () => {},
26
+ ctx: { root: __dirname }
27
+ }
28
+
29
+ const fac = new Fac(caller, { requestTimeout: 5000 }, { env: 'test' })
30
+ fac.tick = () => {}
31
+ fac.conf = { grape: 'http://127.0.0.1:30001', transport: 'http' }
32
+
33
+ let fxg
34
+ describe('RPC integration: req', () => {
35
+ before(async function () {
36
+ this.timeout(20000)
37
+
38
+ await grapes.start()
39
+ fxg = createFxGrenache(stubs, grapes)
40
+ await fxg.start()
41
+
42
+ const start = promisify(fac.start).bind(fac)
43
+ await start()
44
+ })
45
+
46
+ after(async function () {
47
+ this.timeout(5000)
48
+
49
+ await grapes.stop()
50
+ await fxg.stop()
51
+ fac.stop()
52
+ })
53
+
54
+ describe('callback', () => {
55
+ it('options defaults', done => {
56
+ fac.req('rest:util:net', 'getIpInfo', ['8.8.8.8'], (_err, res) => {
57
+ assert.deepStrictEqual(['8.8.8.8', { country: 'US', region: 'CA' }], res)
58
+ done()
59
+ })
60
+ })
61
+
62
+ it('success', done => {
63
+ fac.req('rest:util:net', 'getIpInfo', ['8.8.8.8'], {}, (_err, res) => {
64
+ assert.deepStrictEqual(['8.8.8.8', { country: 'US', region: 'CA' }], res)
65
+ done()
66
+ })
67
+ })
68
+
69
+ it('lookup error', done => {
70
+ fac.req('foo:test:net', 'getIpInfo', ['8.8.8.8'], {}, (err) => {
71
+ assert.strictEqual(err.message, 'ERR_GRAPE_LOOKUP_EMPTY')
72
+ done()
73
+ })
74
+ })
75
+
76
+ it('double cb error', done => {
77
+ const originalPeer = fac.peer
78
+ const originalConsoleError = console.error
79
+
80
+ let errorArgs
81
+ console.error = (...args) => {
82
+ if (errorArgs) {
83
+ done(new Error('Should have been called once'))
84
+ }
85
+ errorArgs = args
86
+ }
87
+
88
+ fac.peer = {
89
+ request (service, args, opts, cb) {
90
+ cb()
91
+ cb()
92
+ fac.peer = originalPeer
93
+ console.error = originalConsoleError
94
+ assert.strictEqual(errorArgs[0], 'ERR_DOUBLE_CB')
95
+ assert.strictEqual(errorArgs[1], 'rest:util:net')
96
+ assert.strictEqual(errorArgs[2], 'getIpInfo')
97
+ done()
98
+ }
99
+ }
100
+
101
+ fac.req('rest:util:net', 'getIpInfo', [], {}, () => {
102
+ assert.strictEqual(errorArgs, undefined)
103
+ })
104
+ })
105
+
106
+ it('invalid args', done => {
107
+ fac.req('rest:util:net', 'getIpInfo', {}, {}, (err, res) => {
108
+ assert.strictEqual(err.message, 'ERR_GRC_REQ_ARGS_INVALID')
109
+ done()
110
+ })
111
+ })
112
+
113
+ it('invalid action', done => {
114
+ fac.req('rest:util:net', {}, [], {}, (err, res) => {
115
+ assert.strictEqual(err.message, 'ERR_GRC_REQ_ACTION_INVALID')
116
+ done()
117
+ })
118
+ })
119
+ })
120
+
121
+ describe('promise', () => {
122
+ it('success', async () => {
123
+ const res = await fac.req('rest:util:net', 'getIpInfo', ['8.8.8.8'], {})
124
+ assert.deepStrictEqual(['8.8.8.8', { country: 'US', region: 'CA' }], res)
125
+ })
126
+
127
+ it('lookup error', async () => {
128
+ try {
129
+ await fac.req('foo:test:net', 'getIpInfo', [], {})
130
+ } catch (e) {
131
+ assert.strictEqual(e.message, 'ERR_GRAPE_LOOKUP_EMPTY')
132
+ return
133
+ }
134
+ throw new Error('Should have thrown')
135
+ })
136
+
137
+ it('double cb error', async () => {
138
+ const originalPeer = fac.peer
139
+ const originalConsoleError = console.error
140
+
141
+ fac.peer = {
142
+ request (service, args, opts, cb) {
143
+ cb()
144
+ cb()
145
+ assert.strictEqual(errorArgs[0], 'ERR_DOUBLE_CB')
146
+ assert.strictEqual(errorArgs[1], 'rest:util:net')
147
+ assert.strictEqual(errorArgs[2], 'getIpInfo')
148
+ fac.peer = originalPeer
149
+ console.error = originalConsoleError
150
+ }
151
+ }
152
+
153
+ let errorArgs
154
+ console.error = (...args) => {
155
+ if (errorArgs) {
156
+ throw new Error('Should have been called once')
157
+ }
158
+ errorArgs = args
159
+ }
160
+
161
+ await fac.req('rest:util:net', 'getIpInfo', [], {})
162
+ })
163
+
164
+ it('invalid args', async () => {
165
+ try {
166
+ await fac.req('rest:util:net', 'getIpInfo', {}, {})
167
+ } catch (e) {
168
+ assert.strictEqual(e.message, 'ERR_GRC_REQ_ARGS_INVALID')
169
+ return
170
+ }
171
+ throw new Error('Should have thrown')
172
+ })
173
+
174
+ it('invalid action', async () => {
175
+ try {
176
+ await fac.req('rest:util:net', {}, [], {})
177
+ } catch (e) {
178
+ assert.strictEqual(e.message, 'ERR_GRC_REQ_ACTION_INVALID')
179
+ return
180
+ }
181
+ throw new Error('Should have thrown')
182
+ })
183
+ })
184
+ })
@@ -0,0 +1,2 @@
1
+ git fetch upstream
2
+ git merge upstream/master