-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
100 lines (84 loc) · 2.29 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
const axios = require('axios');
const _ = require('lodash');
const api = require('./api');
const chain = require('./chain');
const config = require('./config');
const { firebase, user, provider, frequency } = config;
const TIMEOUT = frequency * 1000;
let health;
let loadingHealth;
function openChannel(client) {
return client.openEthChannel('100', '100');
}
function getStat(client, role) {
api.getStat(client).then(data => {
console.log(role, data);
axios.put(`${firebase}/${role}.json`, data);
});
}
function resolveChannel(client, onSuccess = _.noop) {
console.log(`resolve payment at ${new Date()}`);
return api.resolveChannel(client).then(onSuccess);
}
function sendUserPay() {
console.log(`Send user payment at ${new Date()}`);
return api
.sendPay(user.client, provider.address, user.queryResult)
.then(() => {
setTimeout(() => {
resolveChannel(user.client, sendUserPay);
}, TIMEOUT);
});
}
function sendProviderPay() {
console.log(`Send provider payment at ${new Date()}`);
return api
.sendPay(provider.client, user.address, provider.queryResult)
.then(() => {
setTimeout(() => {
resolveChannel(provider.client, sendProviderPay);
}, TIMEOUT);
});
}
function checkHealth() {
if (loadingHealth) {
return;
}
if (_.isNil(health)) {
loadingHealth = true;
chain.uptime().then(res => {
loadingHealth = false;
health = res.toNumber();
axios.put(`${firebase}/uptime.json`, `${health}`);
axios.put(`${firebase}/health/running.json`, `${health}`);
});
return;
}
api.checkHealth().then(({ data }) => {
if (data.running !== health) {
health = data.running;
chain
.updateUptime()
.then(res => {
resolveChannel(user.client);
resolveChannel(provider.client);
axios.put(`${firebase}/uptime.json`, `${health}`);
})
.catch(console.log);
}
});
}
function main() {
Promise.all([openChannel(user.client), openChannel(provider.client)]).then(
() => {
sendUserPay();
setTimeout(() => sendProviderPay(), 1000);
setInterval(checkHealth, 1000);
setInterval(() => {
getStat(provider.client, 'provider');
getStat(user.client, 'user');
}, 2000);
}
);
}
main();