servers.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. const fs = require('fs-extra')
  2. const http = require('http')
  3. const https = require('https')
  4. const { ApolloServer } = require('apollo-server-express')
  5. const Promise = require('bluebird')
  6. const _ = require('lodash')
  7. const io = require('socket.io')
  8. const { ApolloServerPluginLandingPageGraphQLPlayground, ApolloServerPluginLandingPageProductionDefault } = require('apollo-server-core')
  9. const { graphqlUploadExpress } = require('graphql-upload')
  10. /* global WIKI */
  11. module.exports = {
  12. graph: null,
  13. http: null,
  14. https: null,
  15. ws: null,
  16. connections: new Map(),
  17. le: null,
  18. /**
  19. * Initialize HTTP Server
  20. */
  21. async initHTTP () {
  22. WIKI.logger.info(`HTTP Server on port: [ ${WIKI.config.port} ]`)
  23. this.http = http.createServer(WIKI.app)
  24. this.http.on('error', (error) => {
  25. if (error.syscall !== 'listen') {
  26. throw error
  27. }
  28. switch (error.code) {
  29. case 'EACCES':
  30. WIKI.logger.error('Listening on port ' + WIKI.config.port + ' requires elevated privileges!')
  31. return process.exit(1)
  32. case 'EADDRINUSE':
  33. WIKI.logger.error('Port ' + WIKI.config.port + ' is already in use!')
  34. return process.exit(1)
  35. default:
  36. throw error
  37. }
  38. })
  39. this.http.on('listening', () => {
  40. WIKI.logger.info('HTTP Server: [ RUNNING ]')
  41. })
  42. this.http.on('connection', conn => {
  43. let connKey = `http:${conn.remoteAddress}:${conn.remotePort}`
  44. this.connections.set(connKey, conn)
  45. conn.on('close', () => {
  46. this.connections.delete(connKey)
  47. })
  48. })
  49. },
  50. /**
  51. * Start HTTP Server
  52. */
  53. async startHTTP () {
  54. this.http.listen(WIKI.config.port, WIKI.config.bindIP)
  55. },
  56. /**
  57. * Initialize HTTPS Server
  58. */
  59. async initHTTPS () {
  60. if (WIKI.config.ssl.provider === 'letsencrypt') {
  61. this.le = require('./letsencrypt')
  62. await this.le.init()
  63. }
  64. WIKI.logger.info(`HTTPS Server on port: [ ${WIKI.config.ssl.port} ]`)
  65. const tlsOpts = {}
  66. try {
  67. if (WIKI.config.ssl.format === 'pem') {
  68. tlsOpts.key = WIKI.config.ssl.inline ? WIKI.config.ssl.key : fs.readFileSync(WIKI.config.ssl.key)
  69. tlsOpts.cert = WIKI.config.ssl.inline ? WIKI.config.ssl.cert : fs.readFileSync(WIKI.config.ssl.cert)
  70. } else {
  71. tlsOpts.pfx = WIKI.config.ssl.inline ? WIKI.config.ssl.pfx : fs.readFileSync(WIKI.config.ssl.pfx)
  72. }
  73. if (!_.isEmpty(WIKI.config.ssl.passphrase)) {
  74. tlsOpts.passphrase = WIKI.config.ssl.passphrase
  75. }
  76. if (!_.isEmpty(WIKI.config.ssl.dhparam)) {
  77. tlsOpts.dhparam = WIKI.config.ssl.dhparam
  78. }
  79. } catch (err) {
  80. WIKI.logger.error('Failed to setup HTTPS server parameters:')
  81. WIKI.logger.error(err)
  82. return process.exit(1)
  83. }
  84. this.https = https.createServer(tlsOpts, WIKI.app)
  85. this.https.listen(WIKI.config.ssl.port, WIKI.config.bindIP)
  86. this.https.on('error', (error) => {
  87. if (error.syscall !== 'listen') {
  88. throw error
  89. }
  90. switch (error.code) {
  91. case 'EACCES':
  92. WIKI.logger.error('Listening on port ' + WIKI.config.ssl.port + ' requires elevated privileges!')
  93. return process.exit(1)
  94. case 'EADDRINUSE':
  95. WIKI.logger.error('Port ' + WIKI.config.ssl.port + ' is already in use!')
  96. return process.exit(1)
  97. default:
  98. throw error
  99. }
  100. })
  101. this.https.on('listening', () => {
  102. WIKI.logger.info('HTTPS Server: [ RUNNING ]')
  103. })
  104. this.https.on('connection', conn => {
  105. let connKey = `https:${conn.remoteAddress}:${conn.remotePort}`
  106. this.connections.set(connKey, conn)
  107. conn.on('close', () => {
  108. this.connections.delete(connKey)
  109. })
  110. })
  111. },
  112. /**
  113. * Start HTTPS Server
  114. */
  115. async startHTTPS () {
  116. this.https.listen(WIKI.config.ssl.port, WIKI.config.bindIP)
  117. },
  118. /**
  119. * Start GraphQL Server
  120. */
  121. async startGraphQL () {
  122. const graphqlSchema = require('../graph')
  123. this.graph = new ApolloServer({
  124. schema: graphqlSchema,
  125. csrfPrevention: true,
  126. cache: 'bounded',
  127. context: ({ req, res }) => ({ req, res }),
  128. plugins: [
  129. process.env.NODE_ENV === 'development' ? ApolloServerPluginLandingPageGraphQLPlayground({
  130. footer: false
  131. }) : ApolloServerPluginLandingPageProductionDefault({
  132. footer: false
  133. })
  134. // ApolloServerPluginDrainHttpServer({ httpServer: this.http })
  135. // ...(this.https && ApolloServerPluginDrainHttpServer({ httpServer: this.https }))
  136. ]
  137. })
  138. await this.graph.start()
  139. WIKI.app.use(graphqlUploadExpress())
  140. this.graph.applyMiddleware({ app: WIKI.app, cors: false, path: '/_graphql' })
  141. },
  142. /**
  143. * Start Socket.io WebSocket Server
  144. */
  145. async initWebSocket() {
  146. if (this.https) {
  147. this.ws = new io.Server(this.https, {
  148. path: '/_ws/',
  149. serveClient: false
  150. })
  151. WIKI.logger.info(`WebSocket Server attached to HTTPS Server [ OK ]`)
  152. } else {
  153. this.ws = new io.Server(this.http, {
  154. path: '/_ws/',
  155. serveClient: false,
  156. cors: true // TODO: dev only, replace with app settings once stable
  157. })
  158. WIKI.logger.info(`WebSocket Server attached to HTTP Server [ OK ]`)
  159. }
  160. },
  161. /**
  162. * Close all active connections
  163. */
  164. closeConnections (mode = 'all') {
  165. for (const [key, conn] of this.connections) {
  166. if (mode !== `all` && key.indexOf(`${mode}:`) !== 0) {
  167. continue
  168. }
  169. conn.destroy()
  170. this.connections.delete(key)
  171. }
  172. if (mode === 'all') {
  173. this.connections.clear()
  174. }
  175. },
  176. /**
  177. * Stop all servers
  178. */
  179. async stopServers () {
  180. this.closeConnections()
  181. if (this.http) {
  182. await Promise.fromCallback(cb => { this.http.close(cb) })
  183. this.http = null
  184. }
  185. if (this.https) {
  186. await Promise.fromCallback(cb => { this.https.close(cb) })
  187. this.https = null
  188. }
  189. this.graph = null
  190. },
  191. /**
  192. * Restart Server
  193. */
  194. async restartServer (srv = 'https') {
  195. this.closeConnections(srv)
  196. switch (srv) {
  197. case 'http':
  198. if (this.http) {
  199. await Promise.fromCallback(cb => { this.http.close(cb) })
  200. this.http = null
  201. }
  202. this.initHTTP()
  203. this.startHTTP()
  204. break
  205. case 'https':
  206. if (this.https) {
  207. await Promise.fromCallback(cb => { this.https.close(cb) })
  208. this.https = null
  209. }
  210. this.initHTTPS()
  211. this.startHTTPS()
  212. break
  213. default:
  214. throw new Error('Cannot restart server: Invalid designation')
  215. }
  216. }
  217. }