forked from olegabu/fabric-starter-rest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rest-socket-server.js
84 lines (74 loc) · 3.01 KB
/
rest-socket-server.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
const SocketServer = require('socket.io');
const logger = require('log4js').getLogger('RestSocketServer');
const _ = require('lodash');
const cfg = require('./config.js');
class RestSocketServer {
constructor(fabricStarterClient) {
if(!fabricStarterClient) {
const FabricStarterClient = require('./fabric-starter-client');
fabricStarterClient = new FabricStarterClient();
}
this.listOfChannels = [];
this.fabricStarterClient = fabricStarterClient;
}
async startSocketServer(server, opts) {
const self = this;
this.io = new SocketServer(server, {origins: '*:*'});
const channels = await this.fabricStarterClient.queryChannels();
this.opts = opts;
for (const channelId of channels.map(c => {
return c.channel_id;
})) {
await this.registerChannelChainblockListener(channelId);
}
this.startSocketServerTimer();
}
startSocketServerTimer() {
const fabricStarter = this.fabricStarterClient;
const self = this;
let channelList = {};
setInterval(async () => {
const channels = await fabricStarter.queryChannels();
_.forEach(channels, async channel => {
let channelId = channel.channel_id;
let peers = await fabricStarter.getPeersForOrgOnChannel(channelId);
let newPeersFound = false;
_.forEach(peers, peerName => {
if (!_.get(channelList, `${channelId}["${peerName}"]`)) {
_.set(channelList, `${channelId}["${peerName}"]`, true);
logger.debug(`Found new peer ${peerName} on channel ${channelId}`);
newPeersFound = true;
}
});
if (newPeersFound && self.listOfChannels.find(i => i === channelId)) {
await self.sendRepeatableBlock(channelId);
}
if (!self.listOfChannels.find(i => i === channelId)) {
logger.debug(`Found new channel ${channelId}`);
await self.registerChannelChainblockListener(channelId);
}
});
}, cfg.CHANNEL_LISTENER_UPDATE_TIMEOUT);
}
async registerChannelChainblockListener(channel) {
await this.fabricStarterClient.registerBlockEvent(channel, block => {
let blockNumber = block.number || _.get(block, "header.number");
logger.debug(`fabricStarterClient hase recived block ${blockNumber} on ${block.channel_id}`);
logger.debug(block);
this.io.emit('chainblock', block);
}, e => {
logger.error('registerBlockEvent error:', e);
return false;
}, this.opts);
logger.debug(`registered for block event on ${channel}`);
this.listOfChannels.push(channel);
return true;
}
async sendRepeatableBlock(channel) {
let info = await this.fabricStarterClient.queryInfo(channel);
let number = info.height.low-1;
let block = await this.fabricStarterClient.queryBlock(channel, number, true);
this.io.emit('chainblock', block)
}
}
module.exports = RestSocketServer;