-
Notifications
You must be signed in to change notification settings - Fork 2
/
peer-pad-pinner
executable file
·112 lines (90 loc) · 2.63 KB
/
peer-pad-pinner
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
#!/usr/bin/env node
/* eslint no-console: "off" */
'use strict'
const http = require('http')
const httpProxy = require('http-proxy')
require('dotenv').config()
const createPinner = require('./index')
const defaultName = 'peer-pad/2'
const defaultSwarmAddress = '/dns4/ws-star1.par.dwebops.pub/tcp/443/wss/p2p-websocket-star'
const config = {
name: process.env.PEER_BASE_APP_NAME || process.env.PEER_STAR_APP_NAME || defaultName,
swarmAddress: process.env.PEER_BASE_SWARM_ADDRESS || process.env.PEER_STAR_SWARM_ADDRESS || defaultSwarmAddress
}
const options = {}
function log (...args) {
console.log('pinner:', ...args)
}
if (config.swarmAddress) {
log('using swarm address', config.swarmAddress)
options.ipfs = {
swarm: [config.swarmAddress]
}
}
log('pinning app', config.name)
process.on('unhandledRejection', (err) => {
console.error(err)
})
const pinner = createPinner(config.name, options)
setInterval(() => {}, 24 * 60 * 60 * 1000) // Keep pinner alive during startup
pinner.start().then(() => {
pinner.peerId().then(id => {
log('Pinner Peer Id:', id)
})
})
startHealthEndpointServer().catch((err) => {
console.error('error starting health endpoint:', err)
process.exit(1)
})
function startHealthEndpointServer () {
const metricsRegistry = require('./pinner-metrics')(pinner)
const proxy = httpProxy.createProxyServer({
target: 'ws://127.0.0.1:24002',
ws: true
})
proxy.on('error', e => {
console.error('Proxy error', e)
})
return new Promise((resolve, reject) => {
let started = false
const server = http.createServer(onRequest)
const port = process.env.PORT || 3001
const host = process.env.HOST || '0.0.0.0'
server.once('error', (err) => {
if (!started) {
reject(err)
}
})
if (process.env.WEBSOCKET_ANNOUNCE_HOST) {
server.on('upgrade', onUpgrade)
}
server.listen({ port, host }, () => {
log('Health endpoint listening on port', port)
started = true
resolve()
})
})
function onRequest (request, response) {
switch (request.url) {
case '/health':
pinner.ipfs.id().then((peer) => {
response.writeHead(200, { 'content-type': 'text/json' })
response.end(JSON.stringify({
app: config.name,
id: peer.id
}))
})
break
case '/prometheus':
response.writeHead(200, { 'content-type': 'text/plain' })
response.end(metricsRegistry.metrics())
break
default:
response.writeHead(404)
response.end('Not found')
}
}
function onUpgrade (req, socket, head) {
proxy.ws(req, socket, head)
}
}