Skip to content

Commit a81a7ac

Browse files
move internal options to env
1 parent e194f12 commit a81a7ac

File tree

10 files changed

+42
-99
lines changed

10 files changed

+42
-99
lines changed

README.md

Lines changed: 0 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -200,32 +200,3 @@ The internal queries that are ran before the queries in ```initSQLString``` are
200200
Default: process.arch
201201

202202
Description: The MySQL binary architecture to execute. MySQL does not offer server builds for Windows on ARM, so to get this package working on Windows on ARM, set the arch option to "x64" and Windows will emulate MySQL.
203-
204-
***
205-
### :warning: Internal Options :warning:
206-
207-
The following options are only meant for internal use (such as for testing this package or the internals for running this package via the CLI). Their behaviour may change or they may get removed between major/minor/patch versions and they are not to be considered stable. The options below will not follow Semantic Versioning so it is advised to not use them.
208-
209-
- `_DO_NOT_USE_deleteDBAfterStopped: boolean`
210-
211-
Default: true
212-
213-
Description: Changes whether or not the database will be deleted after it has been stopped. If set to `true`, the database WILL be deleted after it has been stopped.
214-
215-
- `_DO_NOT_USE_dbPath: string`
216-
217-
Default: `TMPDIR/mysqlmsn/dbs/UUID` (replacing TMPDIR with the OS temp directory and UUID with a UUIDv4 without seperating dashes).
218-
219-
Description: The folder to store database-related data in
220-
221-
- `_DO_NOT_USE_binaryDirectoryPath: string`
222-
223-
Default: `TMPDIR/mysqlmsn/binaries` (replacing TMPDIR with the OS temp directory)
224-
225-
Description: The folder to store the MySQL binaries when they are downloaded from the CDN.
226-
227-
- `_DO_NOT_USE_cli: boolean`
228-
229-
Default: ```false``` if the package is not being executed via the CLI and ```true``` if it is.
230-
231-
Description: If set to ```true```, this enables certain CLI-only functionality. For example, when ran by the CLI, logging a message to the console when a shutdown signal (like CTRL + C) has been received and the MySQL database is shutting down and getting deleted.

src/cli.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,8 @@ import { ServerOptions } from "../types";
55

66
function main() {
77
const definedOptions = process.argv.filter((option) => option.startsWith('--'))
8-
const options: ServerOptions = {
9-
_DO_NOT_USE_cli: true
10-
}
8+
const options: ServerOptions = {}
9+
process.env.mysqlmsn_internal_DO_NOT_USE_cli = 'true'
1110
for (const opt of definedOptions) {
1211
if (!DEFAULT_OPTIONS_KEYS.includes(opt.replace('--', ''))) {
1312
console.error(`Option ${opt} is not a valid option.`)

src/constants.ts

Lines changed: 12 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,7 @@ export const DEFAULT_OPTIONS_GENERATOR: () => InternalServerOptions = () => ({
2020
xPort: 0,
2121
downloadRetries: 10,
2222
initSQLString: '',
23-
arch: process.arch,
24-
_DO_NOT_USE_deleteDBAfterStopped: true,
25-
//mysqlmsn = MySQL Memory Server Node.js
26-
_DO_NOT_USE_dbPath: normalizePath(`${tmpdir()}/mysqlmsn/dbs/${randomUUID().replace(/-/g, '')}`),
27-
_DO_NOT_USE_binaryDirectoryPath: `${tmpdir()}/mysqlmsn/binaries`,
28-
_DO_NOT_USE_cli: false
23+
arch: process.arch
2924
});
3025

3126
export const DEFAULT_OPTIONS_KEYS = Object.freeze(Object.keys(DEFAULT_OPTIONS_GENERATOR()))
@@ -36,7 +31,17 @@ export const LOG_LEVELS = {
3631
'ERROR': 2
3732
} as const;
3833

39-
export const INTERNAL_OPTIONS = ['_DO_NOT_USE_deleteDBAfterStopped', '_DO_NOT_USE_dbPath', '_DO_NOT_USE_binaryDirectoryPath', '_DO_NOT_USE_cli'] as const;
34+
const internalOptions = {
35+
deleteDBAfterStopped: 'true',
36+
//mysqlmsn = MySQL Memory Server Node.js
37+
dbPath: normalizePath(`${tmpdir()}/mysqlmsn/dbs/${randomUUID().replace(/-/g, '')}`),
38+
binaryDirectoryPath: `${tmpdir()}/mysqlmsn/binaries`,
39+
cli: 'false'
40+
}
41+
42+
export function getInternalEnvVariable(envVar: keyof typeof internalOptions): string {
43+
return process.env['mysqlmsn_internal_DO_NOT_USE_' + envVar] || internalOptions[envVar]
44+
}
4045

4146
const allowedArches = ['x64', 'arm64', undefined]
4247
export const OPTION_TYPE_CHECKS: OptionTypeChecks = {
@@ -109,25 +114,5 @@ export const OPTION_TYPE_CHECKS: OptionTypeChecks = {
109114
check: (opt: any) => allowedArches.includes(opt),
110115
errorMessage: `Option arch must be either of the following: ${allowedArches.join(', ')}`,
111116
definedType: 'string'
112-
},
113-
_DO_NOT_USE_deleteDBAfterStopped: {
114-
check: (opt: any) => opt === undefined || typeof opt === 'boolean',
115-
errorMessage: 'Option _DO_NOT_USE_deleteDBAfterStopped must be either undefined or a boolean.',
116-
definedType: 'boolean'
117-
},
118-
_DO_NOT_USE_dbPath: {
119-
check: (opt: any) => opt === undefined || typeof opt === 'string',
120-
errorMessage: 'Option _DO_NOT_USE_dbPath must be either undefined or a string.',
121-
definedType: 'string'
122-
},
123-
_DO_NOT_USE_binaryDirectoryPath: {
124-
check: (opt: any) => opt === undefined || typeof opt === 'string',
125-
errorMessage: 'Option _DO_NOT_USE_binaryDirectoryPath must be either undefined or a string.',
126-
definedType: 'string'
127-
},
128-
_DO_NOT_USE_cli: {
129-
check: (opt: any) => opt === undefined || typeof opt === 'boolean',
130-
errorMessage: 'Option _DO_NOT_USE_cli must be either undefined or a boolean.',
131-
definedType: 'boolean'
132117
}
133118
} as const;

src/index.ts

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,22 +2,16 @@ import Logger from './libraries/Logger'
22
import * as os from 'node:os'
33
import Executor from "./libraries/Executor"
44
import { satisfies, lt, coerce } from "semver"
5-
import { BinaryInfo, InternalServerOptions, ServerOptions } from '../types'
5+
import { BinaryInfo, ServerOptions } from '../types'
66
import getBinaryURL from './libraries/Version'
77
import MySQLVersions from './versions.json'
88
import { downloadBinary } from './libraries/Downloader'
9-
import { MIN_SUPPORTED_MYSQL, DEFAULT_OPTIONS_KEYS, OPTION_TYPE_CHECKS, INTERNAL_OPTIONS, DEFAULT_OPTIONS_GENERATOR } from './constants'
9+
import { MIN_SUPPORTED_MYSQL, DEFAULT_OPTIONS_KEYS, OPTION_TYPE_CHECKS, DEFAULT_OPTIONS_GENERATOR } from './constants'
1010

1111
export async function createDB(opts?: ServerOptions) {
1212
const suppliedOpts = opts || {};
1313
const suppliedOptsKeys = Object.keys(suppliedOpts);
1414

15-
for (const opt of INTERNAL_OPTIONS) {
16-
if (suppliedOptsKeys.includes(opt)) {
17-
console.warn(`[ mysql-memory-server - Options WARN ]: Creating MySQL database with option ${opt}. This is considered unstable and should not be used externally. Please consider removing this option.`)
18-
}
19-
}
20-
2115
const options = DEFAULT_OPTIONS_GENERATOR();
2216

2317
for (const opt of suppliedOptsKeys) {

src/libraries/Downloader.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { randomUUID } from 'crypto';
88
import { execFile } from 'child_process';
99
import { BinaryInfo, InternalServerOptions } from '../../types';
1010
import { lockFile, waitForLock } from './FileLock';
11+
import { getInternalEnvVariable } from '../constants';
1112

1213
function getZipData(entry: AdmZip.IZipEntry): Promise<Buffer> {
1314
return new Promise((resolve, reject) => {
@@ -181,7 +182,7 @@ function extractBinary(url: string, archiveLocation: string, extractedLocation:
181182
export function downloadBinary(binaryInfo: BinaryInfo, options: InternalServerOptions, logger: Logger): Promise<string> {
182183
return new Promise(async (resolve, reject) => {
183184
const {url, version} = binaryInfo;
184-
const dirpath = options._DO_NOT_USE_binaryDirectoryPath
185+
const dirpath = getInternalEnvVariable('binaryDirectoryPath')
185186
logger.log('Binary path:', dirpath)
186187
await fsPromises.mkdir(dirpath, {recursive: true})
187188

src/libraries/Executor.ts

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {normalize as normalizePath, resolve as resolvePath} from 'path'
1010
import { lockFile, waitForLock } from "./FileLock";
1111
import { onExit } from "signal-exit";
1212
import { randomUUID } from "crypto";
13+
import { getInternalEnvVariable } from "../constants";
1314

1415
class Executor {
1516
logger: Logger;
@@ -117,7 +118,7 @@ class Executor {
117118
if (portIssue || xPortIssue) {
118119
this.logger.log('Error log when exiting for port in use error:', errorLog)
119120
try {
120-
await this.#deleteDatabaseDirectory(options._DO_NOT_USE_dbPath)
121+
await this.#deleteDatabaseDirectory(getInternalEnvVariable('dbPath'))
121122
} catch (e) {
122123
this.logger.error(e)
123124
return reject(`MySQL failed to listen on a certain port. To restart MySQL with a different port, the database directory needed to be deleted. An error occurred while deleting the database directory. Aborting. The error was: ${e}`)
@@ -126,7 +127,7 @@ class Executor {
126127
}
127128

128129
try {
129-
if (options._DO_NOT_USE_deleteDBAfterStopped) {
130+
if (getInternalEnvVariable('deleteDBAfterStopped') === 'true') {
130131
await this.#deleteDatabaseDirectory(dbPath)
131132
}
132133
} catch (e) {
@@ -421,7 +422,7 @@ class Executor {
421422

422423
this.logger.log('Writing init file')
423424

424-
await fsPromises.writeFile(`${options._DO_NOT_USE_dbPath}/init.sql`, initText, {encoding: 'utf8'})
425+
await fsPromises.writeFile(`${getInternalEnvVariable('dbPath')}/init.sql`, initText, {encoding: 'utf8'})
425426

426427
this.logger.log('Finished writing init file')
427428
}
@@ -430,15 +431,15 @@ class Executor {
430431
this.version = installedMySQLBinary.version
431432
this.versionInstalledOnSystem = installedMySQLBinary.installedOnSystem
432433
this.removeExitHandler = onExit(() => {
433-
if (options._DO_NOT_USE_cli) {
434+
if (getInternalEnvVariable('cli') === 'true') {
434435
console.log('\nShutting down the ephemeral MySQL database and cleaning all related files...')
435436
}
436437

437438
this.DBDestroySignal.abort()
438439

439-
if (options._DO_NOT_USE_deleteDBAfterStopped) {
440+
if (getInternalEnvVariable('deleteDBAfterStopped') === 'true') {
440441
try {
441-
fs.rmSync(options._DO_NOT_USE_dbPath, {recursive: true, maxRetries: 50, force: true})
442+
fs.rmSync(getInternalEnvVariable('dbPath'), {recursive: true, maxRetries: 50, force: true})
442443
} catch (e) {
443444
this.logger.error('An error occurred while deleting database directory path:', e)
444445
}
@@ -453,14 +454,14 @@ class Executor {
453454
}
454455
}
455456

456-
if (options._DO_NOT_USE_cli) {
457+
if (getInternalEnvVariable('cli') === 'true') {
457458
console.log('Shutdown and cleanup is complete.')
458459
}
459460
})
460461

461462
let retries = 0;
462463

463-
const datadir = normalizePath(`${options._DO_NOT_USE_dbPath}/data`)
464+
const datadir = normalizePath(`${getInternalEnvVariable('dbPath')}/data`)
464465

465466
do {
466467
await this.#setupDataDirectories(options, installedMySQLBinary.path, datadir, true);
@@ -472,7 +473,7 @@ class Executor {
472473

473474
try {
474475
this.logger.log('Starting MySQL process')
475-
const resolved = await this.#startMySQLProcess(options, port, mySQLXPort, datadir, options._DO_NOT_USE_dbPath, installedMySQLBinary.path)
476+
const resolved = await this.#startMySQLProcess(options, port, mySQLXPort, datadir, getInternalEnvVariable('dbPath'), installedMySQLBinary.path)
476477
this.logger.log('Starting process was successful')
477478
return resolved
478479
} catch (e) {

stress-tests/stress.test.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,17 +14,18 @@ for (let i = 0; i < 100; i++) {
1414
test.concurrent(`if run ${i} is successful`, async () => {
1515
Error.stackTraceLimit = Infinity
1616
console.log('CI:', process.env.useCIDBPath)
17+
18+
process.env.mysqlmsn_internal_DO_NOT_USE_deleteDBAfterStopped = String(!process.env.useCIDBPath)
1719

1820
const options: ServerOptions = {
1921
username: 'dbuser',
2022
logLevel: 'LOG',
21-
_DO_NOT_USE_deleteDBAfterStopped: !process.env.useCIDBPath,
2223
ignoreUnsupportedSystemVersion: true
2324
}
2425

2526
if (process.env.useCIDBPath) {
26-
options._DO_NOT_USE_dbPath = `${dbPath}/${i}`
27-
options._DO_NOT_USE_binaryDirectoryPath = binaryPath
27+
process.env.mysqlmsn_internal_DO_NOT_USE_dbPath = `${dbPath}/${i}`
28+
process.env.mysqlmsn_internal_DO_NOT_USE_binaryDirectoryPath = binaryPath
2829
}
2930

3031
const db = await createDB(options)

tests/sql.test.ts

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,24 +14,23 @@ const dbPath = normalize(GitHubActionsTempFolder + '/dbs')
1414
const binaryPath = normalize(GitHubActionsTempFolder + '/binaries')
1515

1616
beforeEach(async () => {
17-
Error.stackTraceLimit = Infinity
17+
process.env.mysqlmsn_internal_DO_NOT_USE_deleteDBAfterStopped = String(!process.env.useCIDBPath)
18+
1819
const options: ServerOptions = {
1920
username: 'root',
2021
logLevel: 'LOG',
21-
_DO_NOT_USE_deleteDBAfterStopped: !process.env.useCIDBPath,
2222
ignoreUnsupportedSystemVersion: true
2323
}
2424

2525
if (process.env.useCIDBPath) {
26-
options._DO_NOT_USE_dbPath = `${dbPath}/${randomUUID()}`
27-
options._DO_NOT_USE_binaryDirectoryPath = binaryPath
26+
process.env.mysqlmsn_internal_DO_NOT_USE_dbPath = `${dbPath}/${randomUUID()}`
27+
process.env.mysqlmsn_internal_DO_NOT_USE_binaryDirectoryPath = binaryPath
2828
}
2929

3030
db = await createDB(options)
3131
})
3232

3333
afterEach(async () => {
34-
Error.stackTraceLimit = Infinity
3534
await db.stop();
3635
})
3736

tests/versions.test.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,20 +18,20 @@ jest.setTimeout(500_000);
1818
for (const version of versions) {
1919
for (const username of usernames) {
2020
test.concurrent(`running on version ${version} with username ${username}`, async () => {
21-
Error.stackTraceLimit = Infinity
21+
process.env.mysqlmsn_internal_DO_NOT_USE_deleteDBAfterStopped = String(!process.env.useCIDBPath)
22+
2223
const options: ServerOptions = {
2324
version,
2425
dbName: 'testingdata',
2526
username: username,
2627
logLevel: 'LOG',
27-
_DO_NOT_USE_deleteDBAfterStopped: !process.env.useCIDBPath,
2828
ignoreUnsupportedSystemVersion: true,
2929
initSQLString: 'CREATE DATABASE mytestdb;'
3030
}
3131

3232
if (process.env.useCIDBPath) {
33-
options._DO_NOT_USE_dbPath = `${dbPath}/${randomUUID()}`
34-
options._DO_NOT_USE_binaryDirectoryPath = binaryPath
33+
process.env.mysqlmsn_internal_DO_NOT_USE_dbPath = `${dbPath}/${randomUUID()}`
34+
process.env.mysqlmsn_internal_DO_NOT_USE_binaryDirectoryPath = binaryPath
3535
}
3636

3737
const db = await createDB(options)

types/index.ts

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,7 @@ export type ServerOptions = {
1616
xPort?: number | undefined,
1717
downloadRetries?: number | undefined,
1818
initSQLString?: string | undefined,
19-
arch?: "arm64" | "x64" | undefined,
20-
_DO_NOT_USE_deleteDBAfterStopped?: boolean | undefined,
21-
_DO_NOT_USE_dbPath?: string | undefined,
22-
_DO_NOT_USE_binaryDirectoryPath?: string | undefined,
23-
_DO_NOT_USE_cli?: boolean | undefined
19+
arch?: "arm64" | "x64" | undefined
2420
}
2521

2622
export type InternalServerOptions = {
@@ -37,11 +33,7 @@ export type InternalServerOptions = {
3733
xPort: number,
3834
downloadRetries: number,
3935
initSQLString: string,
40-
arch: string,
41-
_DO_NOT_USE_deleteDBAfterStopped: boolean,
42-
_DO_NOT_USE_dbPath: string,
43-
_DO_NOT_USE_binaryDirectoryPath: string,
44-
_DO_NOT_USE_cli: boolean
36+
arch: string
4537
}
4638

4739
export type ExecutorOptions = {

0 commit comments

Comments
 (0)