@b12k/porto 0.9.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +157 -96
- package/dist/busy-ports-error.d.ts +2 -2
- package/dist/cli.js +45 -51
- package/dist/config.d.ts +45 -44
- package/dist/config.js +55 -66
- package/dist/errors.d.ts +22 -10
- package/dist/errors.js +22 -10
- package/dist/git.d.ts +1 -1
- package/dist/git.js +12 -12
- package/dist/index.d.ts +84 -29
- package/dist/index.js +58 -46
- package/dist/output.d.ts +10 -9
- package/dist/output.js +48 -42
- package/dist/ports.d.ts +7 -10
- package/dist/ports.js +10 -15
- package/dist/registry.d.ts +3 -12
- package/dist/registry.js +17 -12
- package/dist/reserve.d.ts +71 -23
- package/dist/reserve.js +96 -63
- package/dist/schemas.d.ts +52 -13
- package/dist/schemas.js +57 -41
- package/dist/vars.d.ts +7 -4
- package/dist/vars.js +18 -14
- package/package.json +19 -3
- package/dist/load-config.d.ts +0 -1
- package/dist/load-config.js +0 -17
package/dist/output.js
CHANGED
|
@@ -36,16 +36,16 @@ async function assertExportPaths(exportPaths, registryPath) {
|
|
|
36
36
|
lockPath,
|
|
37
37
|
lockTarget
|
|
38
38
|
].map((filePath)=>normalizePathForComparison(filePath));
|
|
39
|
-
const
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
const
|
|
45
|
-
if (exportPaths.some((filePath)=>{
|
|
39
|
+
const [registryIdentity, lockIdentity, ...exportIdentities] = await Promise.all([
|
|
40
|
+
registryTarget,
|
|
41
|
+
lockTarget,
|
|
42
|
+
...exportPaths
|
|
43
|
+
].map((filePath)=>fetchFileIdentity(filePath)));
|
|
44
|
+
const hasProtectedPath = exportPaths.some((filePath)=>{
|
|
46
45
|
const normalizedPath = normalizePathForComparison(filePath);
|
|
47
46
|
return registryPaths.has(normalizedPath) || lockPaths.some((targetPath)=>normalizedPath === targetPath || normalizedPath.startsWith(`${targetPath}${node_path.sep}`));
|
|
48
|
-
})
|
|
47
|
+
});
|
|
48
|
+
if (hasProtectedPath || exportIdentities.some((identity)=>identity && (identity === registryIdentity || identity === lockIdentity))) throw new PortoError('exportInvalid', 'The Porto registry and its lock are reserved.');
|
|
49
49
|
}
|
|
50
50
|
async function fetchEnvironmentContents(filePath) {
|
|
51
51
|
try {
|
|
@@ -57,35 +57,35 @@ async function fetchEnvironmentContents(filePath) {
|
|
|
57
57
|
}
|
|
58
58
|
async function fetchExportPaths(settings, commonDirectory) {
|
|
59
59
|
const jsonPath = settings.jsonFile ? await fetchCanonicalPath(node_path.resolve(settings.jsonFile)) : void 0;
|
|
60
|
-
const
|
|
61
|
-
const arePathsEqual = void 0 !== jsonPath && void 0 !==
|
|
60
|
+
const envPath = settings.env ? await fetchCanonicalPath(node_path.resolve(settings.envFile)) : void 0;
|
|
61
|
+
const arePathsEqual = void 0 !== jsonPath && void 0 !== envPath && normalizePathForComparison(jsonPath) === normalizePathForComparison(envPath);
|
|
62
62
|
if (arePathsEqual) throw new PortoError('exportInvalid', '--json-file and --env-file must use different files.');
|
|
63
63
|
await assertExportPaths([
|
|
64
64
|
jsonPath,
|
|
65
|
-
|
|
65
|
+
envPath
|
|
66
66
|
].filter((filePath)=>void 0 !== filePath), getRegistryPath(commonDirectory));
|
|
67
67
|
return {
|
|
68
|
-
|
|
68
|
+
envPath,
|
|
69
69
|
jsonPath
|
|
70
70
|
};
|
|
71
71
|
}
|
|
72
|
-
function formatEnvironmentValue(
|
|
73
|
-
const text = String(
|
|
72
|
+
function formatEnvironmentValue(value) {
|
|
73
|
+
const text = String(value);
|
|
74
74
|
if (/^[A-Za-z0-9_./:@%+,-]*$/u.test(text)) return text;
|
|
75
75
|
if (!text.includes("'")) return `'${text}'`;
|
|
76
76
|
if (!text.includes('"') && !text.includes('\\')) return `"${text}"`;
|
|
77
77
|
throw new PortoError('mappingInvalid', 'Value cannot be represented safely on a single env line.');
|
|
78
78
|
}
|
|
79
|
-
function formatEnvironment(
|
|
80
|
-
return Object.entries(
|
|
79
|
+
function formatEnvironment(vars) {
|
|
80
|
+
return Object.entries(vars).map(([name, value])=>`${name}=${formatEnvironmentValue(value)}`).join('\n');
|
|
81
81
|
}
|
|
82
|
-
function formatReserveOutput(
|
|
83
|
-
if (isJson) return JSON.stringify(
|
|
84
|
-
|
|
85
|
-
index:
|
|
86
|
-
|
|
82
|
+
function formatReserveOutput(slot, vars, isJson) {
|
|
83
|
+
if (isJson) return JSON.stringify(vars ?? {
|
|
84
|
+
firstPort: slot.firstPort,
|
|
85
|
+
index: slot.index,
|
|
86
|
+
lastPort: slot.lastPort
|
|
87
87
|
});
|
|
88
|
-
return
|
|
88
|
+
return vars ? formatEnvironment(vars) : String(slot.index);
|
|
89
89
|
}
|
|
90
90
|
function formatTable(headers, rows) {
|
|
91
91
|
const widths = headers.map((header, index)=>Math.max(header.length, ...rows.map((row)=>row[index]?.length ?? 0)));
|
|
@@ -94,10 +94,10 @@ function formatTable(headers, rows) {
|
|
|
94
94
|
...rows
|
|
95
95
|
].map((row)=>row.map((cell, index)=>cell.padEnd(widths[index] ?? 0)).join(' ').trimEnd()).join('\n');
|
|
96
96
|
}
|
|
97
|
-
function formatStatsTable(
|
|
97
|
+
function formatStatsTable(slots) {
|
|
98
98
|
const now = Date.now();
|
|
99
99
|
return formatTable([
|
|
100
|
-
'
|
|
100
|
+
'SLOT',
|
|
101
101
|
'PORTS',
|
|
102
102
|
'WORKTREE',
|
|
103
103
|
'PATH',
|
|
@@ -105,35 +105,35 @@ function formatStatsTable(reservations) {
|
|
|
105
105
|
'IDLE (MIN)',
|
|
106
106
|
'KEEP',
|
|
107
107
|
'EXPIRED'
|
|
108
|
-
],
|
|
109
|
-
String(
|
|
110
|
-
`${
|
|
111
|
-
node_path.basename(
|
|
112
|
-
|
|
113
|
-
formatDistance(
|
|
108
|
+
], slots.map((slot)=>[
|
|
109
|
+
String(slot.index),
|
|
110
|
+
`${slot.firstPort}-${slot.lastPort}`,
|
|
111
|
+
node_path.basename(slot.worktreePath) || slot.worktreePath,
|
|
112
|
+
slot.worktreePath,
|
|
113
|
+
formatDistance(slot.lastUsedAt, now, {
|
|
114
114
|
addSuffix: true
|
|
115
115
|
}),
|
|
116
|
-
String(
|
|
117
|
-
|
|
118
|
-
|
|
116
|
+
String(slot.idleTtlMinutes),
|
|
117
|
+
slot.keep ? 'yes' : 'no',
|
|
118
|
+
slot.isExpired ? 'yes' : 'no'
|
|
119
119
|
]));
|
|
120
120
|
}
|
|
121
|
-
async function saveEnvironmentFile(filePath,
|
|
121
|
+
async function saveEnvironmentFile(filePath, vars) {
|
|
122
122
|
const contents = await fetchEnvironmentContents(filePath);
|
|
123
123
|
const lineEnding = contents.includes('\r\n') ? '\r\n' : '\n';
|
|
124
|
-
const
|
|
124
|
+
const pendingVars = new Map(Object.entries(vars));
|
|
125
125
|
const updated = contents.replaceAll(ENV_ASSIGNMENT_PATTERN, (line, ...captures)=>{
|
|
126
126
|
const [prefix, name, separator, suffix] = captures;
|
|
127
|
-
const entry = Object.hasOwn(
|
|
127
|
+
const entry = Object.hasOwn(vars, name) ? vars[name] : void 0;
|
|
128
128
|
if (void 0 === entry) return line;
|
|
129
|
-
|
|
129
|
+
pendingVars.delete(name);
|
|
130
130
|
return `${prefix}${name}${separator}${formatEnvironmentValue(entry)}${suffix}`;
|
|
131
131
|
});
|
|
132
|
-
const appended = formatEnvironment(Object.fromEntries(
|
|
132
|
+
const appended = formatEnvironment(Object.fromEntries(pendingVars)).replaceAll('\n', lineEnding);
|
|
133
133
|
const separator = updated.length > 0 && !updated.endsWith('\n') ? lineEnding : '';
|
|
134
134
|
await writeFileAtomically(filePath, `${updated}${appended ? `${separator}${appended}${lineEnding}` : ''}`);
|
|
135
135
|
}
|
|
136
|
-
async function updateEnvironmentFile(filePath,
|
|
136
|
+
async function updateEnvironmentFile(filePath, vars, commonDirectory) {
|
|
137
137
|
const targetPath = await fetchCanonicalPath(filePath);
|
|
138
138
|
if (void 0 !== commonDirectory) await assertExportPaths([
|
|
139
139
|
targetPath
|
|
@@ -148,12 +148,18 @@ async function updateEnvironmentFile(filePath, environment, commonDirectory) {
|
|
|
148
148
|
}
|
|
149
149
|
});
|
|
150
150
|
try {
|
|
151
|
-
await saveEnvironmentFile(targetPath,
|
|
151
|
+
await saveEnvironmentFile(targetPath, vars);
|
|
152
152
|
} finally{
|
|
153
153
|
await unlock();
|
|
154
154
|
}
|
|
155
155
|
}
|
|
156
|
-
async function writeReserveJsonFile(filePath,
|
|
157
|
-
|
|
156
|
+
async function writeReserveJsonFile(filePath, slot, vars) {
|
|
157
|
+
const variables = vars ?? {
|
|
158
|
+
firstPort: slot.firstPort,
|
|
159
|
+
index: slot.index,
|
|
160
|
+
lastPort: slot.lastPort,
|
|
161
|
+
...slot.vars
|
|
162
|
+
};
|
|
163
|
+
await writeFileAtomically(filePath, `${JSON.stringify(variables)}\n`);
|
|
158
164
|
}
|
|
159
165
|
export { fetchExportPaths, formatEnvironment, formatReserveOutput, formatStatsTable, formatTable, updateEnvironmentFile, writeReserveJsonFile };
|
package/dist/ports.d.ts
CHANGED
|
@@ -1,16 +1,13 @@
|
|
|
1
|
-
declare function
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
}): {
|
|
6
|
-
end: number;
|
|
1
|
+
declare function buildSlot<Slot extends {
|
|
2
|
+
firstPort: number;
|
|
3
|
+
lastPort: number;
|
|
4
|
+
}>(record: Slot, index: number): Slot & {
|
|
7
5
|
getPort(offset?: number): number;
|
|
8
6
|
index: number;
|
|
9
|
-
start: number;
|
|
10
7
|
};
|
|
11
|
-
declare function listBusyPorts(start: number, end: number, { host,
|
|
8
|
+
declare function listBusyPorts(start: number, end: number, { host, stopAtFirst }?: {
|
|
12
9
|
host?: string | undefined;
|
|
13
|
-
|
|
10
|
+
stopAtFirst?: boolean;
|
|
14
11
|
}): Promise<number[]>;
|
|
15
12
|
declare function checkHasBusyPort(start: number, end: number, host?: string): Promise<boolean>;
|
|
16
|
-
export {
|
|
13
|
+
export { buildSlot, checkHasBusyPort, listBusyPorts };
|
package/dist/ports.js
CHANGED
|
@@ -1,16 +1,14 @@
|
|
|
1
1
|
import { createServer } from "node:net";
|
|
2
2
|
import { networkInterfaces } from "node:os";
|
|
3
3
|
import { PortoError } from "./error.js";
|
|
4
|
-
function
|
|
5
|
-
const start = record.start + record.index * record.size;
|
|
4
|
+
function buildSlot(record, index) {
|
|
6
5
|
return {
|
|
7
|
-
|
|
6
|
+
...record,
|
|
8
7
|
getPort (offset = 0) {
|
|
9
|
-
if (!Number.isInteger(offset) || offset < 0 || offset
|
|
10
|
-
return
|
|
8
|
+
if (!Number.isInteger(offset) || offset < 0 || record.firstPort + offset > record.lastPort) throw new PortoError('offsetInvalid', `offset must be an integer between 0 and ${record.lastPort - record.firstPort}.`);
|
|
9
|
+
return record.firstPort + offset;
|
|
11
10
|
},
|
|
12
|
-
index
|
|
13
|
-
start
|
|
11
|
+
index
|
|
14
12
|
};
|
|
15
13
|
}
|
|
16
14
|
function checkIsAddressAvailable(port, host, isAutomatic) {
|
|
@@ -27,10 +25,7 @@ function checkIsAddressAvailable(port, host, isAutomatic) {
|
|
|
27
25
|
ipv6Only: true,
|
|
28
26
|
port
|
|
29
27
|
}, ()=>{
|
|
30
|
-
server.close((
|
|
31
|
-
if (error) reject(error);
|
|
32
|
-
else resolve(true);
|
|
33
|
-
});
|
|
28
|
+
server.close(()=>resolve(true));
|
|
34
29
|
});
|
|
35
30
|
});
|
|
36
31
|
}
|
|
@@ -48,14 +43,14 @@ function getProbeHosts() {
|
|
|
48
43
|
...interfaceHosts
|
|
49
44
|
]);
|
|
50
45
|
}
|
|
51
|
-
async function listBusyPorts(start, end, { host,
|
|
46
|
+
async function listBusyPorts(start, end, { host, stopAtFirst = false } = {}) {
|
|
52
47
|
const busyPorts = [];
|
|
53
48
|
const hosts = void 0 === host ? getProbeHosts() : [
|
|
54
49
|
host
|
|
55
50
|
];
|
|
56
51
|
for(let port = start; port <= end; port += 1)for (const probeHost of hosts)if (!await checkIsAddressAvailable(port, probeHost, void 0 === host)) {
|
|
57
52
|
busyPorts.push(port);
|
|
58
|
-
if (
|
|
53
|
+
if (stopAtFirst) return busyPorts;
|
|
59
54
|
break;
|
|
60
55
|
}
|
|
61
56
|
return busyPorts;
|
|
@@ -63,8 +58,8 @@ async function listBusyPorts(start, end, { host, limit = 1 / 0 } = {}) {
|
|
|
63
58
|
async function checkHasBusyPort(start, end, host) {
|
|
64
59
|
const busyPorts = await listBusyPorts(start, end, {
|
|
65
60
|
host,
|
|
66
|
-
|
|
61
|
+
stopAtFirst: true
|
|
67
62
|
});
|
|
68
63
|
return busyPorts.length > 0;
|
|
69
64
|
}
|
|
70
|
-
export {
|
|
65
|
+
export { buildSlot, checkHasBusyPort, listBusyPorts };
|
package/dist/registry.d.ts
CHANGED
|
@@ -1,14 +1,5 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
import type { ReserveOptions } from './index.js';
|
|
3
|
-
type ReservationRecord = SetRequired<Omit<ReserveOptions, 'vars'>, 'idleTtlMinutes' | 'size' | 'start'> & {
|
|
4
|
-
index: number;
|
|
5
|
-
keep: boolean;
|
|
6
|
-
lastUsedAt: string;
|
|
7
|
-
ports: Array<number>;
|
|
8
|
-
worktree: string;
|
|
9
|
-
worktreeId: string;
|
|
10
|
-
};
|
|
1
|
+
import type { Registry } from './schemas.js';
|
|
11
2
|
declare function getRegistryPath(commonDirectory: string): string;
|
|
12
|
-
declare function updateRegistry<Result>(commonDirectory: string,
|
|
3
|
+
declare function updateRegistry<Result>(commonDirectory: string, handleRegistry: (registry: Registry) => Promise<Result> | Result): Promise<Result>;
|
|
13
4
|
export { getRegistryPath, updateRegistry };
|
|
14
|
-
export type { ReservationRecord };
|
|
5
|
+
export type { Registry, ReservationRecord } from './schemas.js';
|
package/dist/registry.js
CHANGED
|
@@ -1,27 +1,32 @@
|
|
|
1
1
|
import { readFile } from "node:fs/promises";
|
|
2
2
|
import node_path from "node:path";
|
|
3
3
|
import proper_lockfile from "proper-lockfile";
|
|
4
|
+
import { DEFAULT_CONFIG } from "./config.js";
|
|
4
5
|
import { PortoError } from "./error.js";
|
|
5
6
|
import { checkIsFileMissing, writeFileAtomically } from "./files.js";
|
|
6
7
|
import { REGISTRY_SCHEMA } from "./schemas.js";
|
|
7
|
-
function
|
|
8
|
-
return node_path.join(commonDirectory, 'porto-registry.json');
|
|
9
|
-
}
|
|
10
|
-
async function listReservations(filePath) {
|
|
8
|
+
async function fetchRegistry(filePath) {
|
|
11
9
|
try {
|
|
12
10
|
return REGISTRY_SCHEMA.parse(JSON.parse(await readFile(filePath, 'utf8')));
|
|
13
11
|
} catch (error) {
|
|
14
|
-
if (checkIsFileMissing(error)) return
|
|
12
|
+
if (checkIsFileMissing(error)) return {
|
|
13
|
+
portsPerSlot: DEFAULT_CONFIG.size,
|
|
14
|
+
slots: {},
|
|
15
|
+
startPort: DEFAULT_CONFIG.start
|
|
16
|
+
};
|
|
15
17
|
throw new PortoError('registryInvalid', filePath, {
|
|
16
18
|
cause: error
|
|
17
19
|
});
|
|
18
20
|
}
|
|
19
21
|
}
|
|
20
|
-
|
|
21
|
-
|
|
22
|
+
function getRegistryPath(commonDirectory) {
|
|
23
|
+
return node_path.join(commonDirectory, 'porto-registry.json');
|
|
24
|
+
}
|
|
25
|
+
async function writeRegistry(filePath, registry, previousContents) {
|
|
26
|
+
const contents = JSON.stringify(registry);
|
|
22
27
|
if (contents !== previousContents) await writeFileAtomically(filePath, `${contents}\n`);
|
|
23
28
|
}
|
|
24
|
-
async function updateRegistry(commonDirectory,
|
|
29
|
+
async function updateRegistry(commonDirectory, handleRegistry) {
|
|
25
30
|
const filePath = getRegistryPath(commonDirectory);
|
|
26
31
|
const unlock = await proper_lockfile.lock(filePath, {
|
|
27
32
|
realpath: false,
|
|
@@ -33,10 +38,10 @@ async function updateRegistry(commonDirectory, handleRecords) {
|
|
|
33
38
|
}
|
|
34
39
|
});
|
|
35
40
|
try {
|
|
36
|
-
const
|
|
37
|
-
const previousContents = JSON.stringify(
|
|
38
|
-
const result = await
|
|
39
|
-
await
|
|
41
|
+
const registry = await fetchRegistry(filePath);
|
|
42
|
+
const previousContents = JSON.stringify(registry);
|
|
43
|
+
const result = await handleRegistry(registry);
|
|
44
|
+
await writeRegistry(filePath, registry, previousContents);
|
|
40
45
|
return result;
|
|
41
46
|
} finally{
|
|
42
47
|
await unlock();
|
package/dist/reserve.d.ts
CHANGED
|
@@ -1,40 +1,88 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { z } from 'zod';
|
|
2
|
+
import type { PortoConfig } from './config.js';
|
|
3
|
+
import type { Registry, ReservationRecord } from './registry.js';
|
|
4
|
+
import type { OPTIONS_SCHEMA } from './schemas.js';
|
|
2
5
|
import type { Vars, VarsResult } from './vars.js';
|
|
3
6
|
import { fetchGitContext } from './git.js';
|
|
4
|
-
import {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
7
|
+
import { buildSlot } from './ports.js';
|
|
8
|
+
type ReservedSlot<Entries extends Vars = Vars> = Omit<ReturnType<typeof buildSlot<ReservationRecord>>, 'vars'> & {
|
|
9
|
+
vars: Entries extends readonly [] ? {
|
|
10
|
+
SLOT: number;
|
|
11
|
+
} : VarsResult<Entries>;
|
|
9
12
|
};
|
|
10
|
-
type ReserveOptions = Partial<
|
|
13
|
+
type ReserveOptions = Partial<z.output<typeof OPTIONS_SCHEMA>> & {
|
|
11
14
|
vars?: undefined | Vars;
|
|
12
15
|
};
|
|
13
|
-
declare function checkIsExpired(record: Pick<ReservationRecord, '
|
|
14
|
-
declare function
|
|
15
|
-
|
|
16
|
+
declare function checkIsExpired(record: Pick<ReservationRecord, 'expiresAt'>, now: number): boolean;
|
|
17
|
+
declare function releaseRecord(registry: Registry, index: number, record: ReservationRecord, force?: boolean): Promise<{
|
|
18
|
+
env: boolean;
|
|
19
|
+
envFile: string;
|
|
20
|
+
jsonFile: string | false;
|
|
21
|
+
silent: boolean;
|
|
22
|
+
expiresAt: string | null;
|
|
23
|
+
firstPort: number;
|
|
24
|
+
host?: string | undefined;
|
|
25
|
+
idleTtlMinutes: number;
|
|
26
|
+
keep: boolean;
|
|
27
|
+
lastPort: number;
|
|
28
|
+
lastUsedAt: string;
|
|
29
|
+
ports: number[];
|
|
30
|
+
vars: {
|
|
31
|
+
[k: string]: string | number;
|
|
32
|
+
};
|
|
33
|
+
worktreeId: string;
|
|
34
|
+
worktreePath: string;
|
|
35
|
+
} & {
|
|
16
36
|
getPort(offset?: number): number;
|
|
17
37
|
index: number;
|
|
18
|
-
|
|
38
|
+
}>;
|
|
39
|
+
declare function removeExpiredRecords(registry: Registry, now: number): Promise<({
|
|
40
|
+
env: boolean;
|
|
41
|
+
envFile: string;
|
|
42
|
+
jsonFile: string | false;
|
|
43
|
+
silent: boolean;
|
|
44
|
+
expiresAt: string | null;
|
|
45
|
+
firstPort: number;
|
|
46
|
+
host?: string | undefined;
|
|
47
|
+
idleTtlMinutes: number;
|
|
48
|
+
keep: boolean;
|
|
49
|
+
lastPort: number;
|
|
50
|
+
lastUsedAt: string;
|
|
51
|
+
ports: number[];
|
|
52
|
+
vars: {
|
|
53
|
+
[k: string]: string | number;
|
|
54
|
+
};
|
|
55
|
+
worktreeId: string;
|
|
56
|
+
worktreePath: string;
|
|
19
57
|
} & {
|
|
58
|
+
getPort(offset?: number): number;
|
|
59
|
+
index: number;
|
|
60
|
+
})[]>;
|
|
61
|
+
declare function commitReservation({ commonDirectory, worktreeId, worktreePath }: Awaited<ReturnType<typeof fetchGitContext>>, { vars, ...options }: Omit<PortoConfig, 'onReleased' | 'onReserved'>): Promise<{
|
|
62
|
+
env: boolean;
|
|
63
|
+
envFile: string;
|
|
64
|
+
jsonFile: string | false;
|
|
65
|
+
silent: boolean;
|
|
66
|
+
expiresAt: string | null;
|
|
67
|
+
firstPort: number;
|
|
68
|
+
host?: string | undefined;
|
|
69
|
+
idleTtlMinutes: number;
|
|
70
|
+
keep: boolean;
|
|
71
|
+
lastPort: number;
|
|
72
|
+
lastUsedAt: string;
|
|
20
73
|
ports: number[];
|
|
21
74
|
vars: {
|
|
22
75
|
[k: string]: string | number;
|
|
23
76
|
};
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
77
|
+
worktreeId: string;
|
|
78
|
+
worktreePath: string;
|
|
79
|
+
} & {
|
|
27
80
|
getPort(offset?: number): number;
|
|
28
81
|
index: number;
|
|
29
|
-
|
|
30
|
-
}[]>;
|
|
31
|
-
declare function commitReservation<Result>({ git, host, idleTtlMinutes, keep, size, start, vars, }: ReturnType<typeof parseOptions> & {
|
|
32
|
-
git?: Awaited<ReturnType<typeof fetchGitContext>>;
|
|
33
|
-
vars?: undefined | Vars;
|
|
34
|
-
}, prepare: (block: ReturnType<typeof issuePorts>) => Result): Promise<Result>;
|
|
82
|
+
}>;
|
|
35
83
|
declare function reserve<const Entries extends Vars>(options: ReserveOptions & {
|
|
36
84
|
vars: Entries;
|
|
37
|
-
}): Promise<
|
|
38
|
-
declare function reserve(options?: ReserveOptions): Promise<
|
|
39
|
-
export { checkIsExpired, commitReservation, removeExpiredRecords, reserve };
|
|
85
|
+
}): Promise<ReservedSlot<Entries>>;
|
|
86
|
+
declare function reserve(options?: ReserveOptions): Promise<ReservedSlot>;
|
|
87
|
+
export { checkIsExpired, commitReservation, releaseRecord, removeExpiredRecords, reserve };
|
|
40
88
|
export type { ReserveOptions };
|
package/dist/reserve.js
CHANGED
|
@@ -1,86 +1,119 @@
|
|
|
1
|
-
import { range,
|
|
1
|
+
import { range, union } from "es-toolkit";
|
|
2
|
+
import { BusyPortsError } from "./busy-ports-error.js";
|
|
3
|
+
import { applyReserveDefaults } from "./config.js";
|
|
2
4
|
import { PortoError } from "./error.js";
|
|
3
5
|
import { fetchGitContext } from "./git.js";
|
|
4
|
-
import {
|
|
6
|
+
import { buildSlot, checkHasBusyPort, listBusyPorts } from "./ports.js";
|
|
5
7
|
import { updateRegistry } from "./registry.js";
|
|
6
8
|
import { parseOptions } from "./schemas.js";
|
|
7
|
-
import { assertVarsFit,
|
|
8
|
-
async function allocateRecord(
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
const
|
|
15
|
-
|
|
16
|
-
const
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
9
|
+
import { assertVarsFit, mapSlotToVars, parseVarEntries } from "./vars.js";
|
|
10
|
+
async function allocateRecord(registry, options) {
|
|
11
|
+
const { portsPerSlot, slots, startPort } = registry;
|
|
12
|
+
const slotsCount = Math.floor((65536 - startPort) / portsPerSlot);
|
|
13
|
+
for(let index = 0; index < slotsCount; index += 1){
|
|
14
|
+
const firstPort = startPort + index * portsPerSlot;
|
|
15
|
+
const lastPort = firstPort + portsPerSlot - 1;
|
|
16
|
+
const isOccupied = void 0 !== slots[index];
|
|
17
|
+
if (!isOccupied && !await checkHasBusyPort(firstPort, lastPort, options.host)) {
|
|
18
|
+
const record = {
|
|
19
|
+
...options,
|
|
20
|
+
firstPort,
|
|
21
|
+
lastPort,
|
|
22
|
+
vars: {}
|
|
23
|
+
};
|
|
24
|
+
slots[index] = record;
|
|
25
|
+
return {
|
|
26
|
+
index,
|
|
27
|
+
record
|
|
28
|
+
};
|
|
29
|
+
}
|
|
20
30
|
}
|
|
21
|
-
throw new PortoError('
|
|
31
|
+
throw new PortoError('slotUnavailable');
|
|
22
32
|
}
|
|
23
33
|
function checkIsExpired(record, now) {
|
|
24
|
-
return
|
|
34
|
+
return null !== record.expiresAt && now > Date.parse(record.expiresAt);
|
|
25
35
|
}
|
|
26
|
-
function issuePorts(record, entries) {
|
|
27
|
-
const
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
});
|
|
36
|
+
function issuePorts(record, index, entries) {
|
|
37
|
+
const { firstPort } = record;
|
|
38
|
+
record.vars = 0 === entries.length ? {
|
|
39
|
+
SLOT: index
|
|
40
|
+
} : mapSlotToVars({
|
|
41
|
+
firstPort,
|
|
42
|
+
index
|
|
43
|
+
}, entries);
|
|
44
|
+
record.ports = union(record.ports, range(firstPort, firstPort + entries.length));
|
|
45
|
+
return buildSlot(record, index);
|
|
34
46
|
}
|
|
35
|
-
async function
|
|
36
|
-
|
|
37
|
-
const
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
47
|
+
async function releaseRecord(registry, index, record, force = false) {
|
|
48
|
+
if (!force) {
|
|
49
|
+
const busyPorts = await listBusyPorts(record.firstPort, record.lastPort, {
|
|
50
|
+
host: record.host
|
|
51
|
+
});
|
|
52
|
+
if (busyPorts.length > 0) throw new BusyPortsError(busyPorts.map((port)=>({
|
|
53
|
+
port,
|
|
54
|
+
slot: index
|
|
55
|
+
})));
|
|
56
|
+
}
|
|
57
|
+
delete registry.slots[index];
|
|
58
|
+
return buildSlot(record, index);
|
|
59
|
+
}
|
|
60
|
+
async function removeExpiredRecords(registry, now) {
|
|
61
|
+
const checkedSlots = await Promise.all(Object.entries(registry.slots).flatMap(([key, record])=>{
|
|
62
|
+
const index = Number(key);
|
|
63
|
+
if (!checkIsExpired(record, now)) return [];
|
|
64
|
+
return [
|
|
65
|
+
checkHasBusyPort(record.firstPort, record.lastPort, record.host).then((hasBusyPort)=>hasBusyPort ? void 0 : buildSlot(record, index))
|
|
66
|
+
];
|
|
42
67
|
}));
|
|
43
|
-
const
|
|
44
|
-
|
|
45
|
-
return
|
|
68
|
+
const expiredSlots = checkedSlots.filter((slot)=>void 0 !== slot);
|
|
69
|
+
for (const { index } of expiredSlots)delete registry.slots[index];
|
|
70
|
+
return expiredSlots;
|
|
46
71
|
}
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
72
|
+
function commitReservation({ commonDirectory, worktreeId, worktreePath }, { vars = [], ...options }) {
|
|
73
|
+
return updateRegistry(commonDirectory, async (registry)=>{
|
|
74
|
+
const { env, envFile, host, idleTtlMinutes, jsonFile, keep, silent, size, start } = applyReserveDefaults(options, registry);
|
|
75
|
+
assertVarsFit(vars.length, size);
|
|
76
|
+
if ((registry.startPort !== start || registry.portsPerSlot !== size) && Object.keys(registry.slots).length > 0) throw new PortoError('rangeMismatch');
|
|
77
|
+
registry.startPort = start;
|
|
78
|
+
registry.portsPerSlot = size;
|
|
51
79
|
const now = Date.now();
|
|
52
|
-
const
|
|
80
|
+
const existingEntry = Object.entries(registry.slots).find(([, record])=>record.worktreeId === worktreeId);
|
|
81
|
+
const existingIndex = void 0 === existingEntry ? -1 : Number(existingEntry[0]);
|
|
82
|
+
const existingRecord = existingEntry?.[1];
|
|
53
83
|
const lastUsedAt = new Date(now).toISOString();
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
});
|
|
61
|
-
await removeExpiredRecords(records, now);
|
|
62
|
-
const record = existingRecord ?? await allocateRecord(records, {
|
|
63
|
-
host,
|
|
84
|
+
const isKept = keep ?? existingRecord?.keep ?? false;
|
|
85
|
+
const settings = {
|
|
86
|
+
env,
|
|
87
|
+
envFile,
|
|
88
|
+
expiresAt: isKept ? null : new Date(now + 60000 * idleTtlMinutes).toISOString(),
|
|
89
|
+
host: host ?? existingRecord?.host,
|
|
64
90
|
idleTtlMinutes,
|
|
65
|
-
|
|
91
|
+
jsonFile,
|
|
92
|
+
keep: isKept,
|
|
66
93
|
lastUsedAt,
|
|
94
|
+
silent,
|
|
95
|
+
worktreePath
|
|
96
|
+
};
|
|
97
|
+
if (existingRecord) Object.assign(existingRecord, settings);
|
|
98
|
+
await removeExpiredRecords(registry, now);
|
|
99
|
+
const { index, record } = existingRecord ? {
|
|
100
|
+
index: existingIndex,
|
|
101
|
+
record: existingRecord
|
|
102
|
+
} : await allocateRecord(registry, {
|
|
103
|
+
...settings,
|
|
67
104
|
ports: [],
|
|
68
|
-
size,
|
|
69
|
-
start,
|
|
70
|
-
worktree,
|
|
71
105
|
worktreeId
|
|
72
106
|
});
|
|
73
|
-
|
|
74
|
-
return prepare(issuePorts(record, vars));
|
|
107
|
+
return issuePorts(record, index, vars);
|
|
75
108
|
});
|
|
76
109
|
}
|
|
77
110
|
async function reserve(options = {}) {
|
|
78
|
-
const
|
|
79
|
-
const vars = void 0 ===
|
|
80
|
-
const
|
|
81
|
-
|
|
111
|
+
const { vars: entries, ...optionsWithoutVars } = options;
|
|
112
|
+
const vars = void 0 === entries ? void 0 : parseVarEntries(entries);
|
|
113
|
+
const git = await fetchGitContext();
|
|
114
|
+
return commitReservation(git, {
|
|
115
|
+
...parseOptions(optionsWithoutVars),
|
|
82
116
|
vars
|
|
83
|
-
}
|
|
84
|
-
return block;
|
|
117
|
+
});
|
|
85
118
|
}
|
|
86
|
-
export { checkIsExpired, commitReservation, removeExpiredRecords, reserve };
|
|
119
|
+
export { checkIsExpired, commitReservation, releaseRecord, removeExpiredRecords, reserve };
|