Skip to content

Commit

Permalink
🐣 portz: init
Browse files Browse the repository at this point in the history
  • Loading branch information
deepsweet committed May 24, 2021
1 parent c3bb1b0 commit 6075c23
Show file tree
Hide file tree
Showing 15 changed files with 731 additions and 0 deletions.
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"packages/pifs",
"packages/pkgu",
"packages/portu",
"packages/portz",
"packages/r11y",
"packages/ramdsk",
"packages/rebox/*",
Expand Down Expand Up @@ -86,6 +87,8 @@
"ws": "^7.3.1"
},
"scripts": {
"service": "echo $PORT",
"app": "echo $PORT $PORT_SERVICE",
"start": "packages/nextools/start-preset/src/cli/index.js"
},
"start": {
Expand Down
21 changes: 21 additions & 0 deletions packages/portz/license.md
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.
29 changes: 29 additions & 0 deletions packages/portz/package.json
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"
}
}
90 changes: 90 additions & 0 deletions packages/portz/readme.md
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
```
109 changes: 109 additions & 0 deletions packages/portz/src/cli.ts
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)
})
20 changes: 20 additions & 0 deletions packages/portz/src/get-free-port.ts
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`)
}
17 changes: 17 additions & 0 deletions packages/portz/src/get-socket-path.ts
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
}
4 changes: 4 additions & 0 deletions packages/portz/src/index.ts
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'
38 changes: 38 additions & 0 deletions packages/portz/src/register-service.ts
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
}
Loading

0 comments on commit 6075c23

Please sign in to comment.