-
Notifications
You must be signed in to change notification settings - Fork 32
/
http.js
81 lines (70 loc) · 2.45 KB
/
http.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
/*
* raft.js: Raft consensus algorithm in JavaScript
* Copyright (C) 2013 Joel Martin
* Licensed under MPL 2.0 (see LICENSE.txt)
*
* See README.md for description and usage instructions.
*/
"use strict"
var RaftServerLocal = require("./local").RaftServerLocal,
url = require("url"),
http = require("http")
// RaftServer that uses HTTP communication for RPC
function RaftServerHttp(id, opts) {
if (!(this instanceof RaftServerHttp)) {
// Handle instantiation without "new"
return new RaftServerHttp(id, opts)
}
// Call the superclass
RaftServerLocal.call(this, id, opts)
if (!opts.listenAddress) {
throw new Error("opts.listenAddress is required")
}
// TODO: better way to track server addresses
if (!opts.serverAddress) {
throw new Error("opts.serverAddress is required")
}
// start listening server
var httpServer = http.createServer(function(request, response) {
var dstr = ""
request.on('data', function (chunk) {
dstr += chunk
})
request.on('error', function(error) {
this.error("got error:", error, targetId, rpcName)
}.bind(this))
request.on('end', function(){
var data = JSON.parse(dstr),
rpcName = data[0],
args = data[1]
this.dbg("Got RPC " + rpcName)
response.end()
this[rpcName](args)
}.bind(this))
}.bind(this))
httpServer.on('close', function() {
this.warn("Server closed")
}.bind(this))
var parts = opts.listenAddress.split(/:/),
port = parts[parts.length-1],
host = parts[parts.length-2]
httpServer.listen(port, host)
}
RaftServerHttp.prototype = Object.create(RaftServerLocal.prototype)
RaftServerHttp.prototype.constructor = RaftServerHttp
RaftServerHttp.prototype.sendRPC = function(targetId, rpcName, args) {
var saddr = this._opts.serverAddress[targetId],
ropts = url.parse("http://" + saddr)
ropts.method = 'POST'
this.dbg("Send RPC to " + targetId + " [" + saddr + "]: " + rpcName)
var req = http.request(ropts, function (response) {
response.on('data', function (chunk) {})
response.on('end', function (chunk) {})
})
req.on('error', function(error) {
this.info("got error:", error, targetId, rpcName)
}.bind(this))
req.write(JSON.stringify([rpcName, args]))
req.end()
}
exports.RaftServerHttp = RaftServerHttp