This repository was archived by the owner on Feb 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathindex.js
163 lines (134 loc) · 4.48 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
'use strict'
const Hapi = require('@hapi/hapi')
const Pino = require('hapi-pino')
const H2o2 = require('@hapi/h2o2')
const debug = require('debug')
const multiaddr = require('multiaddr')
const toMultiaddr = require('uri-to-multiaddr')
const errorHandler = require('./error-handler')
const LOG = 'ipfs:http-api'
const LOG_ERROR = 'ipfs:http-api:error'
function hapiInfoToMultiaddr (info) {
let hostname = info.host
let uri = info.uri
// ipv6 fix
if (hostname.includes(':') && !hostname.startsWith('[')) {
// hapi 16 produces invalid URI for ipv6
// we fix it here by restoring missing square brackets
hostname = `[${hostname}]`
uri = uri.replace(`://${info.host}`, `://${hostname}`)
}
return toMultiaddr(uri)
}
function serverCreator (serverAddrs, createServer, ipfs) {
serverAddrs = serverAddrs || []
// just in case the address is just string
serverAddrs = Array.isArray(serverAddrs) ? serverAddrs : [serverAddrs]
const processServer = async address => {
const addrParts = address.split('/')
const server = await createServer(addrParts[2], addrParts[4], ipfs)
await server.start()
server.info.ma = hapiInfoToMultiaddr(server.info)
return server
}
return Promise.all(serverAddrs.map(processServer))
}
class HttpApi {
constructor (ipfs, options) {
this._ipfs = ipfs
this._options = options || {}
this._log = debug(LOG)
this._log.error = debug(LOG_ERROR)
if (process.env.IPFS_MONITORING) {
// Setup debug metrics collection
const prometheusClient = require('prom-client')
const prometheusGcStats = require('prometheus-gc-stats')
const collectDefaultMetrics = prometheusClient.collectDefaultMetrics
collectDefaultMetrics({ timeout: 5000 })
prometheusGcStats(prometheusClient.register)()
}
}
async start () {
this._log('starting')
const ipfs = this._ipfs
const config = await ipfs.config.get()
config.Addresses = config.Addresses || {}
const apiAddrs = config.Addresses.API
this._apiServers = await serverCreator(apiAddrs, this._createApiServer, ipfs)
const gatewayAddrs = config.Addresses.Gateway
this._gatewayServers = await serverCreator(gatewayAddrs, this._createGatewayServer, ipfs)
this._log('started')
return this
}
async _createApiServer (host, port, ipfs) {
const server = Hapi.server({
host,
port,
// CORS is enabled by default
// TODO: shouldn't, fix this
routes: {
cors: true
}
})
server.app.ipfs = ipfs
await server.register({
plugin: Pino,
options: {
prettyPrint: process.env.NODE_ENV !== 'production',
logEvents: ['onPostStart', 'onPostStop', 'response', 'request-error'],
level: debug.enabled(LOG) ? 'debug' : (debug.enabled(LOG_ERROR) ? 'error' : 'fatal')
}
})
const setHeader = (key, value) => {
server.ext('onPreResponse', (request, h) => {
const { response } = request
if (response.isBoom) {
response.output.headers[key] = value
} else {
response.header(key, value)
}
return h.continue
})
}
// Set default headers
setHeader('Access-Control-Allow-Headers',
'X-Stream-Output, X-Chunked-Output, X-Content-Length')
setHeader('Access-Control-Expose-Headers',
'X-Stream-Output, X-Chunked-Output, X-Content-Length')
server.route(require('./api/routes'))
errorHandler(server)
return server
}
async _createGatewayServer (host, port, ipfs) {
const server = Hapi.server({ host, port })
server.app.ipfs = ipfs
await server.register({
plugin: Pino,
options: {
prettyPrint: Boolean(debug.enabled(LOG)),
logEvents: ['onPostStart', 'onPostStop', 'response', 'request-error'],
level: debug.enabled(LOG) ? 'debug' : (debug.enabled(LOG_ERROR) ? 'error' : 'fatal')
}
})
await server.register(H2o2)
server.route(require('./gateway/routes'))
return server
}
get apiAddr () {
if (!this._apiServers || !this._apiServers.length) {
throw new Error('API address unavailable - server is not started')
}
return multiaddr('/ip4/127.0.0.1/tcp/' + this._apiServers[0].info.port)
}
async stop () {
this._log('stopping')
const stopServers = servers => Promise.all((servers || []).map(s => s.stop()))
await Promise.all([
stopServers(this._apiServers),
stopServers(this._gatewayServers)
])
this._log('stopped')
return this
}
}
module.exports = HttpApi