-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
15 changed files
with
731 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
# The MIT License (MIT) | ||
|
||
Copyright (c) 2021–present NexTools | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in | ||
all copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
THE SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
{ | ||
"name": "portz", | ||
"version": "0.0.0", | ||
"description": "Service port registry and dependency queue manager", | ||
"keywords": [], | ||
"main": "src/index.ts", | ||
"bin": "src/cli.ts", | ||
"repository": "nextools/metarepo", | ||
"license": "MIT", | ||
"engines": { | ||
"node": ">=12.13.0" | ||
}, | ||
"publishConfig": { | ||
"access": "public" | ||
}, | ||
"dependencies": { | ||
"@babel/runtime": "^7.14.0", | ||
"commander": "^7.2.0", | ||
"dleet": "^2.0.1", | ||
"pifs": "^2.0.0", | ||
"portu": "^0.2.0", | ||
"sleap": "^0.1.0", | ||
"unchunk": "^0.2.0" | ||
}, | ||
"devDependencies": { | ||
"@types/tape": "^4.2.34", | ||
"tape": "^5.0.0" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,90 @@ | ||
# portz ![npm](https://flat.badgen.net/npm/v/portz) | ||
|
||
Service port registry and dependency queue manager. | ||
|
||
Allows to run services concurrently respecting cross-dependencies by waiting for TCP port to become in use on `0.0.0.0` interface. | ||
|
||
## Install | ||
|
||
```sh | ||
$ yarn add portz | ||
``` | ||
|
||
## Usage | ||
|
||
### API | ||
|
||
```ts | ||
type TStartServerOptions = { | ||
fromPort: number, | ||
toPort: number | ||
} | ||
|
||
const startServer: (options: TStartServerOptions) => Promise<() => Promise<void>> | ||
``` | ||
```ts | ||
type TRegisterServiceOptions = { | ||
name: string, | ||
deps?: string[] | ||
} | ||
|
||
type TRegisterServiceResult = { | ||
port: number, | ||
deps?: { | ||
[k: string]: number | ||
}, | ||
} | ||
|
||
const registerService: (options: TRegisterServiceOptions) => Promise<TRegisterServiceResult> | ||
``` | ||
```ts | ||
const unregisterService: (name: string) => Promise<void> | ||
``` | ||
```ts | ||
import { startServer, registerService } from 'portz' | ||
|
||
const stopServer = await startServer({ | ||
fromPort: 3000, | ||
toPort: 4000 | ||
}) | ||
|
||
console.log( | ||
await Promise.all([ | ||
registerService({ name: 'foo', deps: ['bar'] }), | ||
registerService({ name: 'bar' }), | ||
registerService({ name: 'baz', deps: ['foo', 'bar'] } | ||
]) | ||
) | ||
/* | ||
[ | ||
{ port: 3001, deps: { bar: 3000 } }, | ||
{ port: 3000 }, | ||
{ port: 3002, deps: { foo: 3001, bar: 3000 } } | ||
] | ||
*/ | ||
|
||
await stopServer() | ||
``` | ||
### CLI | ||
```json | ||
{ | ||
"scripts": { | ||
"foo": "echo $PORT", | ||
"bar": "echo $PORT $PORT_FOO" | ||
} | ||
} | ||
``` | ||
```sh | ||
portz start --range 3000:4000 | ||
``` | ||
```sh | ||
portz register --name foo -- npm run foo | ||
portz register --name bar --deps foo -- npm run bar | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,109 @@ | ||
#!/usr/bin/env node | ||
import { spawn } from 'child_process' | ||
import { program } from 'commander' | ||
import { version } from '../package.json' | ||
import { registerService } from './register-service' | ||
import { startServer } from './start-server' | ||
import { unregisterService } from './unregister-service' | ||
|
||
type TSignalMap = { | ||
[k in NodeJS.Signals]?: number | ||
} | ||
|
||
const signals: TSignalMap = { | ||
SIGHUP: 1, | ||
SIGINT: 2, | ||
SIGTERM: 15, | ||
} | ||
|
||
program.version(version) | ||
|
||
program | ||
.command('register') | ||
.description('register service through portz server') | ||
.requiredOption('-n, --name [name]', 'service name') | ||
.option('-d, --deps <name...>', 'dependency name') | ||
.action(async ({ name, deps }) => { | ||
const result = await registerService({ name, deps }) | ||
const dashDashArgIndex = program.args.findIndex((arg) => arg === '--') | ||
|
||
if (dashDashArgIndex === -1) { | ||
throw new Error('Arguments to spawn a process are required') | ||
} | ||
|
||
const spawnCommand = program.args[dashDashArgIndex + 1] | ||
const spawnArgs = program.args.slice(dashDashArgIndex + 2) | ||
|
||
const depsEnv: { [k: string]: string } = {} | ||
|
||
if (result.deps != null) { | ||
for (const [name, port] of Object.entries(result.deps)) { | ||
depsEnv[`PORT_${name.toUpperCase()}`] = String(port) | ||
} | ||
} | ||
|
||
const childProcess = spawn(spawnCommand, spawnArgs, { | ||
stdio: 'inherit', | ||
env: { | ||
...process.env, | ||
...depsEnv, | ||
PORT: String(result.port), | ||
}, | ||
}) | ||
|
||
childProcess.on('error', async (err) => { | ||
console.error(err) | ||
await unregisterService(name) | ||
process.exit(1) | ||
}) | ||
|
||
const kill = async (signal: NodeJS.Signals) => { | ||
await unregisterService(name) | ||
console.log('\nbye') | ||
// https://github.com/npm/cli/issues/1591 | ||
// https://nodejs.org/api/process.html#process_exit_codes | ||
process.exit(128 + signals[signal]!) | ||
} | ||
|
||
process.on('SIGTERM', kill) | ||
process.on('SIGINT', kill) | ||
process.on('SIGHUP', kill) | ||
}) | ||
|
||
program | ||
.command('unregister') | ||
.description('unregister service through portz server') | ||
.requiredOption('-n, --name [name]', 'service name') | ||
.action(({ name }) => unregisterService(name)) | ||
|
||
program | ||
.command('start') | ||
.description('start portz server') | ||
.requiredOption('-r, --range <from:to>', 'port range, separated by :', (value) => value.split(':')) | ||
.action(async ({ range }) => { | ||
const stopServer = await startServer({ | ||
fromPort: range[0], | ||
toPort: range[1], | ||
}) | ||
|
||
const kill = async (signal: NodeJS.Signals) => { | ||
await stopServer() | ||
console.log('\nbye') | ||
// https://github.com/npm/cli/issues/1591 | ||
// https://nodejs.org/api/process.html#process_exit_codes | ||
process.exit(128 + signals[signal]!) | ||
} | ||
|
||
process.on('SIGTERM', kill) | ||
process.on('SIGINT', kill) | ||
process.on('SIGHUP', kill) | ||
|
||
console.log('portz server is up and ready') | ||
}) | ||
|
||
program | ||
.parseAsync(process.argv) | ||
.catch((err) => { | ||
console.error(err) | ||
process.exit(1) | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
import { isPortFree } from 'portu' | ||
|
||
export const getFreePort = async (from: number, to: number, skipPorts: number[]): Promise<number> => { | ||
const _from = Math.max(1, from) | ||
const _to = Math.min(65535, to) | ||
|
||
for (let port = _from; port <= _to; port++) { | ||
if (skipPorts.includes(port)) { | ||
continue | ||
} | ||
|
||
const isFree = await isPortFree(port, '0.0.0.0') | ||
|
||
if (isFree) { | ||
return port | ||
} | ||
} | ||
|
||
throw new Error(`Unable to find free port within ${from}-${to} range`) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
import { tmpdir } from 'os' | ||
import path from 'path' | ||
import { realpath } from 'pifs' | ||
|
||
let socketPath: null | string = null | ||
|
||
export const getSocketPath = async () => { | ||
if (socketPath !== null) { | ||
return socketPath | ||
} | ||
|
||
const tmpDir = await realpath(tmpdir()) | ||
|
||
socketPath = path.join(tmpDir, 'portz.sock') | ||
|
||
return socketPath | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
export * from './start-server' | ||
export * from './register-service' | ||
export * from './unregister-service' | ||
export type { TRegisterServiceOptions, TRegisterServiceResult } from './types' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
import { once } from 'events' | ||
import http from 'http' | ||
import type { IncomingMessage } from 'http' | ||
import { unchunkJson } from 'unchunk' | ||
import { getSocketPath } from './get-socket-path' | ||
import type { TRegisterServiceOptions } from './types' | ||
|
||
type TRegisterService = { | ||
<T extends string>(options: TRegisterServiceOptions & { deps: T[] }): Promise<{ port: number, deps: { [k in T]: number } }>, | ||
(options: TRegisterServiceOptions): Promise<{ port: number }>, | ||
} | ||
|
||
export const registerService: TRegisterService = async (options: any) => { | ||
const socketPath = await getSocketPath() | ||
const data = JSON.stringify(options) | ||
|
||
const req = http.request({ | ||
method: 'POST', | ||
path: '/register', | ||
socketPath, | ||
headers: { | ||
'Content-Type': 'application/json', | ||
}, | ||
}) | ||
|
||
req.write(data) | ||
req.end() | ||
|
||
const [res] = await once(req, 'response') as [IncomingMessage] | ||
|
||
if (res.statusCode !== 200) { | ||
throw new Error(res.statusMessage) | ||
} | ||
|
||
const result = await unchunkJson<any>(res) | ||
|
||
return result | ||
} |
Oops, something went wrong.