-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
198 lines (171 loc) · 4.59 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
#!/usr/bin/env node
"use strict";
import express from "express";
import bodyParser from "body-parser";
import { JSONRPCServer } from "json-rpc-2.0";
import { Fluence } from "@fluencelabs/js-client";
import {
quorumEth,
randomLoadBalancingEth,
roundRobinEth,
} from "../aqua-compiled/rpc.js";
import { registerLoggerSrv } from "../aqua-compiled/logger.js";
import { registerCounterSrv } from "../aqua-compiled/counter.js";
import { registerQuorumCheckerSrv } from "../aqua-compiled/quorum.js";
import { readArguments } from "./arguments.js";
import { readConfig } from "./config.js";
import { methods } from "./methods.js";
const args = readArguments(process.argv.slice(2));
if (args.errors.length > 0) {
console.log(args.help);
args.errors.forEach((err) => console.log(err));
process.exit(1);
}
const { config, errors, help } = readConfig(args.configPath);
if (errors.length > 0) {
errors.forEach((err) => console.log(err));
console.log(help);
process.exit(1);
}
console.log("Running server...");
const route = "/";
const server = new JSONRPCServer();
// initialize fluence client
await Fluence.connect(config.relay, {});
const peerId = (await Fluence.getClient()).getPeerId();
// handler for logger
registerLoggerSrv({
log: (s) => {
console.log("log: " + s);
},
logCall: (s) => {
console.log("Call will be to : " + s);
},
logWorker: (s) => {
console.log("Worker used: " + JSON.stringify(s));
},
logNum: (s) => {
console.log("Number: " + s);
},
});
let counter = 0;
registerCounterSrv("counter", {
incrementAndReturn: () => {
counter++;
console.log("Counter: " + counter);
return counter;
},
});
function findSameResults(results, minNum) {
const resultCounts = results
.filter((obj) => obj.success)
.map((obj) => obj.value)
.reduce(function (i, v) {
if (i[v] === undefined) {
i[v] = 1;
} else {
i[v] = i[v] + 1;
}
return i;
}, {});
const getMaxRepeated = Math.max(...Object.values(resultCounts));
if (getMaxRepeated >= minNum) {
console.log(resultCounts);
const max = Object.entries(resultCounts).find(
(kv) => kv[1] === getMaxRepeated,
);
return {
value: max[0],
results: [],
error: "",
};
} else {
return {
error: "No consensus in results",
results: results,
value: "",
};
}
}
registerQuorumCheckerSrv("quorum", {
check: (ethResults, minQuorum) => {
console.log("Check quorum for:");
console.log(ethResults);
return findSameResults(ethResults, minQuorum);
},
});
const counterServiceId = config.counterServiceId || "counter";
const counterPeerId = config.counterPeerId || peerId;
const quorumServiceId = config.quorumServiceId || "quorum";
const quorumPeerId = config.quorumPeerId || peerId;
const quorumNumber = config.quorumNumber || 2;
const mode = config.mode || "random";
console.log(`Using mode '${mode}'`);
async function methodHandler(reqRaw, method) {
const req = reqRaw.map((s) => JSON.stringify(s));
console.log(`Receiving request '${method}'`);
let result;
if (mode === "random") {
result = await randomLoadBalancingEth(config.providers, method, req);
} else if (mode === "round-robin") {
result = await roundRobinEth(
config.providers,
method,
req,
counterServiceId,
counterPeerId,
config.serviceId,
);
} else if (mode === "quorum") {
const quorumResult = await quorumEth(
config.providers,
quorumNumber,
10000,
method,
req,
quorumServiceId,
quorumPeerId,
{ ttl: 20000 },
);
if (quorumResult.error) {
console.error(
`quorum failed: ${quorumResult.error}\n${JSON.stringify(
quorumResult.results,
)}`,
);
result = { success: false, error: quorumResult.error };
} else {
result = {
success: true,
error: quorumResult.error,
value: quorumResult.value,
};
}
}
if (!result.success) {
throw new Error(result.error);
}
return JSON.parse(result.value || "{}");
}
function addMethod(op) {
server.addMethod(op, async (req) => methodHandler(req, op));
}
// register all eth methods
methods.forEach((m) => {
addMethod(m);
});
const app = express();
app.use(bodyParser.json());
// register JSON-RPC handler
app.post(route, (req, res) => {
const jsonRPCRequest = req.body;
server.receive(jsonRPCRequest).then((jsonRPCResponse) => {
if (jsonRPCResponse) {
res.json(jsonRPCResponse);
} else {
res.sendStatus(204);
}
});
});
app.listen(config.port);
console.log("Server was started on port " + config.port);