-
Notifications
You must be signed in to change notification settings - Fork 503
/
pathfind.js
90 lines (73 loc) · 2.53 KB
/
pathfind.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
'use strict';
const EventEmitter = require('events').EventEmitter;
const util = require('util');
const Amount = require('./amount').Amount;
/**
* Represents a persistent path finding request.
*
* Only one path find request is allowed per connection, so when another path
* find request is triggered it will supercede the existing one, making it emit
* the 'end' and 'superceded' events.
*/
function PathFind(remote, src_account, dst_account, dst_amount, src_currencies
) {
EventEmitter.call(this);
this.remote = remote;
this.src_account = src_account;
this.dst_account = dst_account;
this.dst_amount = dst_amount;
this.src_currencies = src_currencies;
}
util.inherits(PathFind, EventEmitter);
/**
* Submits a path_find_create request to the network.
*
* This starts a path find request, superceding all previous path finds.
*
* This will be called automatically by Remote when this object is instantiated,
* so you should only have to call it if the path find was closed or superceded
* and you wish to restart it.
*/
PathFind.prototype.create = function() {
const self = this;
const req = this.remote.requestPathFindCreate({
source_account: this.src_account,
destination_account: this.dst_account,
destination_amount: this.dst_amount,
source_currencies: this.src_currencies
});
req.once('error', function(err) {
self.emit('error', err);
});
req.once('success', function(msg) {
self.notify_update(msg);
});
// XXX We should add ourselves to prepare_subscribe or a similar mechanism so
// that we can resubscribe after a reconnection.
req.broadcast().request();
};
PathFind.prototype.close = function() {
this.removeAllListeners('update');
this.remote.requestPathFindClose().broadcast().request();
this.emit('end');
this.emit('close');
};
PathFind.prototype.notify_update = function(message) {
const src_account = message.source_account;
const dst_account = message.destination_account;
const dst_amount = Amount.from_json(message.destination_amount);
// Only pass the event along if this path find response matches what we were
// looking for.
if (this.src_account === src_account &&
this.dst_account === dst_account &&
dst_amount.equals(this.dst_amount)) {
this.emit('update', message);
}
};
PathFind.prototype.notify_superceded = function() {
// XXX If we're set to re-subscribe whenever we connect to a new server, then
// we should cancel that behavior here. See PathFind#create.
this.emit('end');
this.emit('superceded');
};
exports.PathFind = PathFind;