|
| 1 | +#!/usr/bin/env node |
| 2 | +// Shared per-workspace port allocator for parallel Superset workspaces of |
| 3 | +// this repo. Superset itself only observes listening ports, it does not |
| 4 | +// assign them (docs.superset.sh/ports), so this implements the |
| 5 | +// shared-allocation-file pattern the docs point to. Callers are expected to |
| 6 | +// hold lib/lock.sh's lock around invocations to avoid a read/write race |
| 7 | +// between two workspaces allocating at once. |
| 8 | +// |
| 9 | +// Usage: |
| 10 | +// port-alloc.cjs allocate <workspaceKey> <rangeStart> <rangeEnd> |
| 11 | +// port-alloc.cjs release <workspaceKey> |
| 12 | +'use strict'; |
| 13 | + |
| 14 | +const fs = require('fs'); |
| 15 | +const os = require('os'); |
| 16 | +const path = require('path'); |
| 17 | + |
| 18 | +const file = path.join(os.homedir(), '.superset', 'debatelab-ports', 'allocations.json'); |
| 19 | + |
| 20 | +function readData() { |
| 21 | + try { |
| 22 | + return JSON.parse(fs.readFileSync(file, 'utf8')); |
| 23 | + } catch { |
| 24 | + return {}; |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +function writeData(data) { |
| 29 | + fs.mkdirSync(path.dirname(file), { recursive: true }); |
| 30 | + fs.writeFileSync(file, JSON.stringify(data, null, 2)); |
| 31 | +} |
| 32 | + |
| 33 | +const [, , cmd, workspace, start, end] = process.argv; |
| 34 | + |
| 35 | +if (!cmd || !workspace) { |
| 36 | + console.error('usage: port-alloc.cjs allocate|release <workspaceKey> [rangeStart] [rangeEnd]'); |
| 37 | + process.exit(1); |
| 38 | +} |
| 39 | + |
| 40 | +if (cmd === 'allocate') { |
| 41 | + const data = readData(); |
| 42 | + if (data[workspace]) { |
| 43 | + console.log(data[workspace]); |
| 44 | + process.exit(0); |
| 45 | + } |
| 46 | + const used = new Set(Object.values(data)); |
| 47 | + for (let p = Number(start); p <= Number(end); p++) { |
| 48 | + if (!used.has(p)) { |
| 49 | + data[workspace] = p; |
| 50 | + writeData(data); |
| 51 | + console.log(p); |
| 52 | + process.exit(0); |
| 53 | + } |
| 54 | + } |
| 55 | + console.error(`port-alloc: no free port in ${start}-${end}`); |
| 56 | + process.exit(1); |
| 57 | +} else if (cmd === 'release') { |
| 58 | + const data = readData(); |
| 59 | + delete data[workspace]; |
| 60 | + writeData(data); |
| 61 | +} else { |
| 62 | + console.error(`port-alloc: unknown command "${cmd}"`); |
| 63 | + process.exit(1); |
| 64 | +} |
0 commit comments