-
Notifications
You must be signed in to change notification settings - Fork 5
/
run.ts
85 lines (77 loc) · 2.1 KB
/
run.ts
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
/*!
* Copyright © 2023 United States Government as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All Rights Reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
import { join } from 'node:path'
import waitPort from 'wait-port'
import { install } from './install.js'
import { mkdtemp } from 'node:fs/promises'
import { mkdirP, temp } from './paths.js'
import rimraf from 'rimraf'
import type { SandboxEngine } from './engines.js'
import { UnexpectedResolveError, neverResolve } from './promises.js'
import { launchBinary } from './runBinary.js'
import { launchDocker } from './runDocker.js'
export type SearchEngineLauncherFunction<T = object> = (
props: T & {
options: string[]
dataDir: string
logsDir: string
engine: SandboxEngine
port: number
}
) => Promise<{
kill: () => Promise<void>
waitUntilStopped: () => Promise<void>
}>
export async function launch({
port,
engine,
}: {
port?: number
engine: SandboxEngine
}) {
port ??= 9200
const url = `http://localhost:${port}`
const options = [
`http.port=${port}`,
'discovery.type=single-node',
engine === 'elasticsearch'
? 'xpack.security.enabled=false'
: 'plugins.security.disabled=true',
]
await mkdirP(temp)
const tempDir = await mkdtemp(join(temp, 'run-'))
const [dataDir, logsDir] = ['data', 'logs'].map((s) => join(tempDir, s))
await Promise.all([dataDir, logsDir].map(mkdirP))
const bin = await install(engine)
const props = { engine, dataDir, logsDir, options, port }
const { kill, waitUntilStopped } = await (bin
? launchBinary({ bin, ...props })
: launchDocker(props))
try {
await Promise.race([
waitPort({ port, protocol: 'http' }),
neverResolve(waitUntilStopped()),
])
} catch (e) {
if (e instanceof UnexpectedResolveError) {
throw new Error('Search engine terminated unexpectedly')
} else {
throw e
}
}
return {
url,
port,
async stop() {
await kill()
await waitUntilStopped()
console.log('Removing temporary directory')
await rimraf(tempDir)
},
}
}