-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathindex.js
More file actions
90 lines (76 loc) · 2.36 KB
/
index.js
File metadata and controls
90 lines (76 loc) · 2.36 KB
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
// Copyright (c) Microsoft Corporation and others. Licensed under the MIT license.
// SPDX-License-Identifier: MIT
const config = require('painless-config')
const defaults = require(config.get('CRAWLER_OPTIONS') || './config/cdConfig')
const run = require('./ghcrawler').run
const www = require('./ghcrawler/bin/www')
const createInsights = require('./providers/logging/insightsConfig')
const createLogger = require('./providers/logging/logger')
const { withTimeout } = require('./lib/utils')
const searchPath = [require('./providers')]
const maps = require('./config/map')
const shutdownTimeoutMs = defaults.service?.shutdownTimeoutMs ?? 60000
const aiClient = createInsights(config)
const logger = createLogger({ aiClient })
const service = run(defaults, logger, searchPath, maps)
const { server, port } = www(service, logger, defaults.service?.port ?? '5000')
let shuttingDown = false
server.on('error', onError)
process.on('SIGTERM', onShutdown)
process.on('SIGINT', onShutdown)
process.on('SIGHUP', onShutdown)
function onError(error) {
if (error.syscall !== 'listen') {
throw error
}
const bind = typeof port === 'string' ? `Pipe ${port}` : `Port ${port}`
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(`${bind} requires elevated privileges`)
process.exit(1)
break
case 'EADDRINUSE':
console.error(`${bind} is already in use`)
process.exit(1)
break
default:
throw error
}
}
async function onShutdown(signal) {
if (shuttingDown) {
return
}
shuttingDown = true
console.log(`Received ${signal}`)
try {
await withTimeout(performShutdownCleanup, shutdownTimeoutMs)
console.log('Server closed.')
process.exit(0)
} catch (error) {
console.error(`Closing server: ${error}`)
process.exit(1)
}
}
async function performShutdownCleanup() {
await closeServer(server)
await service.stop()
try {
await aiClient.flush()
} catch (error) {
// Best effort to flush any remaining insights, but don't let it block shutdown.
console.error(`Flushing insights: ${error}`)
}
}
async function closeServer(httpServer) {
await new Promise((resolve, reject) => {
httpServer.close(error => {
if (error && error.code !== 'ERR_SERVER_NOT_RUNNING') {
reject(error)
return
}
resolve()
})
})
}