servers.mjs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. import fs from 'node:fs/promises'
  2. import http from 'node:http'
  3. import https from 'node:https'
  4. import { ApolloServer } from '@apollo/server'
  5. import { expressMiddleware } from '@apollo/server/express4'
  6. import { isEmpty } from 'lodash-es'
  7. import { Server as IoServer } from 'socket.io'
  8. import { ApolloServerPluginLandingPageLocalDefault, ApolloServerPluginLandingPageProductionDefault } from '@apollo/server/plugin/landingPage/default'
  9. import graphqlUploadExpress from 'graphql-upload/graphqlUploadExpress.mjs'
  10. import { initSchema } from '../graph/index.mjs'
  11. export default {
  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 : await fs.readFile(WIKI.config.ssl.key, 'utf-8')
  69. tlsOpts.cert = WIKI.config.ssl.inline ? WIKI.config.ssl.cert : await fs.readFile(WIKI.config.ssl.cert, 'utf-8')
  70. } else {
  71. tlsOpts.pfx = WIKI.config.ssl.inline ? WIKI.config.ssl.pfx : await fs.readFile(WIKI.config.ssl.pfx, 'utf-8')
  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 = await initSchema()
  123. this.graph = new ApolloServer({
  124. schema: graphqlSchema,
  125. allowBatchedHttpRequests: true,
  126. csrfPrevention: true,
  127. cache: 'bounded',
  128. plugins: [
  129. process.env.NODE_ENV === 'production' ? ApolloServerPluginLandingPageProductionDefault({
  130. footer: false
  131. }) : ApolloServerPluginLandingPageLocalDefault({
  132. footer: false,
  133. embed: {
  134. endpointIsEditable: false,
  135. runTelemetry: false
  136. }
  137. })
  138. // ApolloServerPluginDrainHttpServer({ httpServer: this.http })
  139. // ...(this.https && ApolloServerPluginDrainHttpServer({ httpServer: this.https }))
  140. ]
  141. })
  142. await this.graph.start()
  143. WIKI.app.use(graphqlUploadExpress({
  144. maxFileSize: WIKI.config.security.uploadMaxFileSize,
  145. maxFiles: WIKI.config.security.uploadMaxFiles
  146. }))
  147. WIKI.app.use('/_graphql', expressMiddleware(this.graph, {
  148. context: ({ req, res }) => ({ req, res })
  149. }))
  150. },
  151. /**
  152. * Start Socket.io WebSocket Server
  153. */
  154. async initWebSocket() {
  155. if (this.https) {
  156. this.ws = new IoServer(this.https, {
  157. path: '/_ws/',
  158. serveClient: false
  159. })
  160. WIKI.logger.info(`WebSocket Server attached to HTTPS Server [ OK ]`)
  161. } else {
  162. this.ws = new IoServer(this.http, {
  163. path: '/_ws/',
  164. serveClient: false,
  165. cors: true // TODO: dev only, replace with app settings once stable
  166. })
  167. WIKI.logger.info(`WebSocket Server attached to HTTP Server [ OK ]`)
  168. }
  169. },
  170. /**
  171. * Close all active connections
  172. */
  173. closeConnections (mode = 'all') {
  174. for (const [key, conn] of this.connections) {
  175. if (mode !== `all` && key.indexOf(`${mode}:`) !== 0) {
  176. continue
  177. }
  178. conn.destroy()
  179. this.connections.delete(key)
  180. }
  181. if (mode === 'all') {
  182. this.connections.clear()
  183. }
  184. },
  185. /**
  186. * Stop all servers
  187. */
  188. async stopServers () {
  189. this.closeConnections()
  190. if (this.http) {
  191. await new Promise(resolve => this.http.close(resolve))
  192. this.http = null
  193. }
  194. if (this.https) {
  195. await new Promise(resolve => this.https.close(resolve))
  196. this.https = null
  197. }
  198. this.graph = null
  199. },
  200. /**
  201. * Restart Server
  202. */
  203. async restartServer (srv = 'https') {
  204. this.closeConnections(srv)
  205. switch (srv) {
  206. case 'http':
  207. if (this.http) {
  208. await new Promise(resolve => this.http.close(resolve))
  209. this.http = null
  210. }
  211. this.initHTTP()
  212. this.startHTTP()
  213. break
  214. case 'https':
  215. if (this.https) {
  216. await new Promise(resolve => this.https.close(resolve))
  217. this.https = null
  218. }
  219. this.initHTTPS()
  220. this.startHTTPS()
  221. break
  222. default:
  223. throw new Error('Cannot restart server: Invalid designation')
  224. }
  225. }
  226. }