@bakers-build/addon-ports 0.5.1-next.855 → 0.5.1-next.857
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/dist/src/index.d.ts +1 -0
- package/dist/src/index.js +100 -127
- package/dist/src/preset.d.ts +1 -0
- package/dist/src/preset.js +8 -0
- package/dist/src/tool-definitions.d.ts +2 -0
- package/dist/src/tool-definitions.js +22 -0
- package/dist/src/tools.d.ts +23 -0
- package/dist/src/tools.js +179 -0
- package/package.json +5 -5
package/dist/src/index.d.ts
CHANGED
|
@@ -68,6 +68,7 @@ export declare function revalidatesForKill(fresh: {
|
|
|
68
68
|
* reaped on a failed host `ss`; container services must not be reaped on a
|
|
69
69
|
* failed Docker probe). */
|
|
70
70
|
export declare function shouldKeepTunnelRecord(discovery: ClaimedDiscovery, key: string): boolean;
|
|
71
|
+
export declare function currentBranch(worktree: string): string | null;
|
|
71
72
|
/** Is a recorded route still backed by a claim, and with which rule? Used
|
|
72
73
|
* by `reap` and by every `up`. A changed rule (restarted container, new
|
|
73
74
|
* IP or port) comes back so the caller can refresh the route instead of
|
package/dist/src/index.js
CHANGED
|
@@ -14,11 +14,11 @@
|
|
|
14
14
|
// return an actionable "pick a service key" error instead of silently
|
|
15
15
|
// tunnelling an unclaimed listener.
|
|
16
16
|
import { execFileSync } from 'node:child_process';
|
|
17
|
-
import {
|
|
17
|
+
import { readdirSync, readFileSync } from 'node:fs';
|
|
18
|
+
import { isAbsolute, join, relative, resolve } from 'node:path';
|
|
18
19
|
import { homeBbDir } from '@bakers-build/core';
|
|
19
|
-
import {
|
|
20
|
-
import {
|
|
21
|
-
import { isOwnedByCurrentUser, listCloudflaredProcesses, nodeDeps, nodeHttpProbe, nodeTunnelOpsDeps, processStartTime, readLegacyTunnelPids, } from './deps-node.js';
|
|
20
|
+
import { discoverClaimedServices, loadPortsTransport, portsSettings, readPortsSettings, } from './core.js';
|
|
21
|
+
import { isOwnedByCurrentUser, listCloudflaredProcesses, nodeDeps, nodeHttpProbe, processStartTime, readLegacyTunnelPids, } from './deps-node.js';
|
|
22
22
|
import { serviceRules } from './service-config.js';
|
|
23
23
|
import { recordMatchesRule } from './tunnel-ops.js';
|
|
24
24
|
// Deliberately stricter than `claims.ts`'s `TICKET_RE` (which also validates
|
|
@@ -176,7 +176,7 @@ export function shouldKeepTunnelRecord(discovery, key) {
|
|
|
176
176
|
return true;
|
|
177
177
|
});
|
|
178
178
|
}
|
|
179
|
-
function currentBranch(worktree) {
|
|
179
|
+
export function currentBranch(worktree) {
|
|
180
180
|
try {
|
|
181
181
|
return execFileSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], {
|
|
182
182
|
cwd: worktree,
|
|
@@ -257,19 +257,6 @@ export function liveTunnel(record, discovery) {
|
|
|
257
257
|
const rule = claimed?.rules.find((r) => r.key === record.key) ?? claimed?.rules[0];
|
|
258
258
|
return rule ? { live: true, rule } : { live: true };
|
|
259
259
|
}
|
|
260
|
-
async function checkLive(record, zone) {
|
|
261
|
-
if (!existsSync(record.worktree))
|
|
262
|
-
return { live: false };
|
|
263
|
-
let discovery;
|
|
264
|
-
try {
|
|
265
|
-
discovery = await discover(record.worktree, record.ticket, zone);
|
|
266
|
-
}
|
|
267
|
-
catch {
|
|
268
|
-
// Unreadable settings are no evidence the route is gone: keep it.
|
|
269
|
-
return { live: true };
|
|
270
|
-
}
|
|
271
|
-
return liveTunnel(record, discovery);
|
|
272
|
-
}
|
|
273
260
|
/** Keys of present records whose freshly claimed rule no longer matches
|
|
274
261
|
* them (e.g. a new container IP after `ddev restart`). A key with no claim
|
|
275
262
|
* at all is `reap`'s business, not stale. */
|
|
@@ -298,6 +285,88 @@ export function quickTunnelNotice(url) {
|
|
|
298
285
|
return undefined;
|
|
299
286
|
return 'Quick Tunnel: no fixed name, no uptime guarantee, 200 in-flight request limit, no SSE';
|
|
300
287
|
}
|
|
288
|
+
const NO_CONDUCTOR = 'no running conductor for this checkout — the conductor is the only writer of the tunnel routes (start it with `bakers oven start`)';
|
|
289
|
+
/** The live conductor endpoint whose workspace root holds `worktree`; the
|
|
290
|
+
* most specific root wins. A dead pid's leftover file does not count. */
|
|
291
|
+
function conductorEndpoint(worktree) {
|
|
292
|
+
const dir = join(homeBbDir(), 'conductors');
|
|
293
|
+
let names;
|
|
294
|
+
try {
|
|
295
|
+
names = readdirSync(dir).filter((n) => n.endsWith('.json'));
|
|
296
|
+
}
|
|
297
|
+
catch {
|
|
298
|
+
return undefined;
|
|
299
|
+
}
|
|
300
|
+
const alive = (pid) => {
|
|
301
|
+
try {
|
|
302
|
+
process.kill(pid, 0);
|
|
303
|
+
return true;
|
|
304
|
+
}
|
|
305
|
+
catch (err) {
|
|
306
|
+
return err.code === 'EPERM';
|
|
307
|
+
}
|
|
308
|
+
};
|
|
309
|
+
const holds = (root) => {
|
|
310
|
+
const rel = relative(resolve(root), resolve(worktree));
|
|
311
|
+
return !rel.startsWith('..') && !isAbsolute(rel);
|
|
312
|
+
};
|
|
313
|
+
const live = names
|
|
314
|
+
.map((n) => {
|
|
315
|
+
try {
|
|
316
|
+
return JSON.parse(readFileSync(join(dir, n), 'utf8'));
|
|
317
|
+
}
|
|
318
|
+
catch {
|
|
319
|
+
return undefined;
|
|
320
|
+
}
|
|
321
|
+
})
|
|
322
|
+
.filter((e) => typeof e?.url === 'string' &&
|
|
323
|
+
typeof e.operatorToken === 'string' &&
|
|
324
|
+
typeof e.workspaceRoot === 'string' &&
|
|
325
|
+
e.workspaceRoot !== '' &&
|
|
326
|
+
Number.isInteger(e.pid) &&
|
|
327
|
+
alive(e.pid) &&
|
|
328
|
+
holds(e.workspaceRoot))
|
|
329
|
+
.sort((a, b) => b.workspaceRoot.length - a.workspaceRoot.length);
|
|
330
|
+
return live[0];
|
|
331
|
+
}
|
|
332
|
+
/** Call a ports tool on `worktree` through the conductor; prints its answer
|
|
333
|
+
* and sets a failing exit code on an error. Returns the text on success. */
|
|
334
|
+
async function viaConductor(worktree, tool, args, ticket, print = true) {
|
|
335
|
+
const fail = (message) => {
|
|
336
|
+
process.stdout.write(`${message}\n`);
|
|
337
|
+
process.exitCode = 1;
|
|
338
|
+
return undefined;
|
|
339
|
+
};
|
|
340
|
+
const endpoint = conductorEndpoint(worktree);
|
|
341
|
+
if (!endpoint)
|
|
342
|
+
return fail(NO_CONDUCTOR);
|
|
343
|
+
let body;
|
|
344
|
+
try {
|
|
345
|
+
const res = await fetch(`${endpoint.url}/call`, {
|
|
346
|
+
method: 'POST',
|
|
347
|
+
headers: {
|
|
348
|
+
authorization: `Bearer ${endpoint.operatorToken}`,
|
|
349
|
+
'content-type': 'application/json',
|
|
350
|
+
},
|
|
351
|
+
body: JSON.stringify({
|
|
352
|
+
tool,
|
|
353
|
+
args,
|
|
354
|
+
worktree,
|
|
355
|
+
...(ticket ? { ticket } : {}),
|
|
356
|
+
}),
|
|
357
|
+
});
|
|
358
|
+
body = (await res.json());
|
|
359
|
+
if (!res.ok)
|
|
360
|
+
return fail(String(body.error ?? `HTTP ${res.status}`));
|
|
361
|
+
}
|
|
362
|
+
catch (err) {
|
|
363
|
+
return fail(`${NO_CONDUCTOR}: ${err instanceof Error ? err.message : String(err)}`);
|
|
364
|
+
}
|
|
365
|
+
const text = String(body.text ?? '');
|
|
366
|
+
if (print && text !== '')
|
|
367
|
+
process.stdout.write(`${text}\n`);
|
|
368
|
+
return text;
|
|
369
|
+
}
|
|
301
370
|
/** Register `bakers ports <sub>` on the program. Exported for a registration test. */
|
|
302
371
|
export function registerPorts(program, worktree) {
|
|
303
372
|
const ports = program
|
|
@@ -347,23 +416,19 @@ export function registerPorts(program, worktree) {
|
|
|
347
416
|
.command('status')
|
|
348
417
|
.description("this worktree's machine tunnel records")
|
|
349
418
|
.action(async () => {
|
|
350
|
-
const
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
419
|
+
const text = await viaConductor(worktree(), 'ports_status', {}, undefined, false);
|
|
420
|
+
if (text === undefined)
|
|
421
|
+
return;
|
|
422
|
+
const rows = JSON.parse(text);
|
|
423
|
+
if (rows.length === 0) {
|
|
354
424
|
process.stdout.write('No tunnels recorded for this worktree.\n');
|
|
355
425
|
return;
|
|
356
426
|
}
|
|
357
|
-
const
|
|
358
|
-
|
|
359
|
-
return;
|
|
360
|
-
const stale = staleKeys(records, discovery);
|
|
361
|
-
for (const r of records) {
|
|
362
|
-
const at = r.url ?? (r.hostname ? `https://${r.hostname}` : '-');
|
|
363
|
-
const staleMark = stale.has(r.key)
|
|
427
|
+
for (const r of rows) {
|
|
428
|
+
const staleMark = r.stale
|
|
364
429
|
? ' stale (origin changed — run bakers ports up)'
|
|
365
430
|
: '';
|
|
366
|
-
process.stdout.write(`${r.
|
|
431
|
+
process.stdout.write(`${r.service}\t${r.url ?? '-'}\t${r.status}${r.error ? ` (${r.error})` : ''}${staleMark}\n`);
|
|
367
432
|
const notice = quickTunnelNotice(r.url);
|
|
368
433
|
if (notice)
|
|
369
434
|
process.stdout.write(` (${notice})\n`);
|
|
@@ -375,112 +440,22 @@ export function registerPorts(program, worktree) {
|
|
|
375
440
|
.argument('[service]', 'the claimed service key (or its base name); every eligible service when omitted')
|
|
376
441
|
.option('--ticket <identifier>', 'ticket identifier, when it cannot be inferred from the branch')
|
|
377
442
|
.action(async (service, opts) => {
|
|
378
|
-
|
|
379
|
-
if (!cfg.ok) {
|
|
380
|
-
process.stdout.write(`${cfg.message}\n`);
|
|
381
|
-
process.exitCode = 1;
|
|
382
|
-
return;
|
|
383
|
-
}
|
|
384
|
-
const wt = worktree();
|
|
385
|
-
const ticket = resolveTicketIdentifier(opts.ticket, currentBranch(wt));
|
|
386
|
-
if (!ticket.ok) {
|
|
387
|
-
process.stdout.write(`${ticket.message}\n`);
|
|
388
|
-
process.exitCode = 1;
|
|
389
|
-
return;
|
|
390
|
-
}
|
|
391
|
-
// A container IP reused by another DDEV project after `ddev restart`
|
|
392
|
-
// would serve that project under a stale route, so every `up` first
|
|
393
|
-
// re-checks every recorded route machine-wide, exactly like `reap`.
|
|
394
|
-
const recheck = await reapTunnels({ home: homeBbDir(), transport: cfg.transport }, (record) => checkLive(record, cfg.transport.zone ?? ''), nodeTunnelOpsDeps);
|
|
395
|
-
if (!recheck.ok ||
|
|
396
|
-
recheck.removedRecords > 0 ||
|
|
397
|
-
(recheck.refreshedRecords ?? 0) > 0) {
|
|
398
|
-
process.stdout.write(`${recheck.message}\n`);
|
|
399
|
-
}
|
|
400
|
-
const discovery = await discoverOrFail(wt, ticket.identifier, cfg.transport.zone ?? '');
|
|
401
|
-
if (!discovery)
|
|
402
|
-
return;
|
|
403
|
-
const ctx = {
|
|
404
|
-
worktree: wt,
|
|
405
|
-
ticket: ticket.identifier,
|
|
406
|
-
home: homeBbDir(),
|
|
407
|
-
transport: cfg.transport,
|
|
408
|
-
};
|
|
409
|
-
if (service === undefined) {
|
|
410
|
-
// spec v5: no key ⇒ bring up everything eligible, same semantics as
|
|
411
|
-
// the `tunnel` inbox message ("Share tunnels") — skip what is
|
|
412
|
-
// already applied, keep going past a single failure, and report
|
|
413
|
-
// every outcome rather than stopping at the first one.
|
|
414
|
-
const toShare = servicesToShare(discovery);
|
|
415
|
-
if (toShare.length === 0) {
|
|
416
|
-
process.stdout.write('no eligible service to share\n');
|
|
417
|
-
return;
|
|
418
|
-
}
|
|
419
|
-
const outcomes = await shareAll(toShare, (claimed) => bringUpTunnel(claimed.rules[0], ctx, nodeTunnelOpsDeps));
|
|
420
|
-
let anyFailed = false;
|
|
421
|
-
for (const { service: claimed, result } of outcomes) {
|
|
422
|
-
process.stdout.write(`${claimed.key}: ${result.message}\n`);
|
|
423
|
-
if (!result.ok)
|
|
424
|
-
anyFailed = true;
|
|
425
|
-
}
|
|
426
|
-
if (anyFailed)
|
|
427
|
-
process.exitCode = 1;
|
|
428
|
-
return;
|
|
429
|
-
}
|
|
430
|
-
const selection = selectService(discovery, service);
|
|
431
|
-
if (!selection.ok) {
|
|
432
|
-
process.stdout.write(`${selection.message}\n`);
|
|
433
|
-
process.exitCode = 1;
|
|
434
|
-
return;
|
|
435
|
-
}
|
|
436
|
-
const claimed = selection.service;
|
|
437
|
-
if (claimed.rules.length === 0) {
|
|
438
|
-
process.stdout.write(`${claimed.key} cannot be shared (${claimed.status}${claimed.limitation ? `: ${claimed.limitation}` : ''})\n`);
|
|
439
|
-
process.exitCode = 1;
|
|
440
|
-
return;
|
|
441
|
-
}
|
|
442
|
-
const result = await bringUpTunnel(claimed.rules[0], ctx, nodeTunnelOpsDeps);
|
|
443
|
-
process.stdout.write(`${result.message}\n`);
|
|
444
|
-
if (claimed.limitation)
|
|
445
|
-
process.stdout.write(`${claimed.limitation}\n`);
|
|
446
|
-
if (!result.ok)
|
|
447
|
-
process.exitCode = 1;
|
|
443
|
+
await viaConductor(worktree(), 'ports_up', service === undefined ? {} : { service }, opts.ticket);
|
|
448
444
|
});
|
|
449
445
|
ports
|
|
450
446
|
.command('down')
|
|
451
447
|
.description("take a service's tunnel down, or every tunnel of this worktree")
|
|
452
448
|
.argument('[key]', 'the service key to stop sharing; every key of this worktree when omitted')
|
|
453
449
|
.action(async (key) => {
|
|
454
|
-
|
|
455
|
-
if (!cfg.ok) {
|
|
456
|
-
process.stdout.write(`${cfg.message}\n`);
|
|
457
|
-
process.exitCode = 1;
|
|
458
|
-
return;
|
|
459
|
-
}
|
|
460
|
-
const wt = worktree();
|
|
461
|
-
const ctx = {
|
|
462
|
-
worktree: wt,
|
|
463
|
-
ticket: '',
|
|
464
|
-
home: homeBbDir(),
|
|
465
|
-
transport: cfg.transport,
|
|
466
|
-
};
|
|
467
|
-
const result = await takeDownTunnel(wt, key, ctx, nodeTunnelOpsDeps);
|
|
468
|
-
process.stdout.write(`${result.message}\n`);
|
|
469
|
-
if (!result.ok)
|
|
470
|
-
process.exitCode = 1;
|
|
450
|
+
await viaConductor(worktree(), 'ports_down', key === undefined ? {} : { service: key });
|
|
471
451
|
});
|
|
472
452
|
ports
|
|
473
453
|
.command('reap')
|
|
474
454
|
.description('reconcile machine-wide tunnel records and kill orphaned legacy tunnel processes')
|
|
475
455
|
.action(async () => {
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
process.exitCode = 1;
|
|
480
|
-
return;
|
|
481
|
-
}
|
|
482
|
-
const result = await reapTunnels({ home: homeBbDir(), transport: cfg.transport }, (record) => checkLive(record, cfg.transport.zone ?? ''), nodeTunnelOpsDeps);
|
|
483
|
-
process.stdout.write(`${result.message}\n`);
|
|
456
|
+
// The route reconcile runs in the conductor; a failure there still
|
|
457
|
+
// lets the host-local legacy cleanup below run.
|
|
458
|
+
await viaConductor(worktree(), 'ports_reap', {});
|
|
484
459
|
let killed = 0;
|
|
485
460
|
for (const proc of await listCloudflaredProcesses()) {
|
|
486
461
|
// Only a legacy `tunnel --url …` quick tunnel, never the machine's
|
|
@@ -510,8 +485,6 @@ export function registerPorts(program, worktree) {
|
|
|
510
485
|
}
|
|
511
486
|
if (killed > 0)
|
|
512
487
|
process.stdout.write(`killed ${killed} legacy tunnel process(es)\n`);
|
|
513
|
-
if (!result.ok)
|
|
514
|
-
process.exitCode = 1;
|
|
515
488
|
});
|
|
516
489
|
}
|
|
517
490
|
const portsCommandPlugin = {
|
package/dist/src/preset.d.ts
CHANGED
package/dist/src/preset.js
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
// `inbox` (contract 2, see below): the `tunnel` message's Markdown result is
|
|
7
7
|
// rendered in the ticket's addon card in the web UI and in `bakers ui`, and the
|
|
8
8
|
// handler runs on the conductor's machine.
|
|
9
|
+
import { PORTS_TOOL_DEFINITIONS } from './tool-definitions.js';
|
|
9
10
|
export const commands = (acc) => [
|
|
10
11
|
...acc,
|
|
11
12
|
{
|
|
@@ -28,3 +29,10 @@ export const inbox = {
|
|
|
28
29
|
export const scopes = ['machine', 'project'];
|
|
29
30
|
// Merge and check the entry's own settings (services, all_node, transport).
|
|
30
31
|
export { checkWith, mergeWith } from './service-config.js';
|
|
32
|
+
// Agent tools the conductor serves to every run (and the CLI calls through
|
|
33
|
+
// it): the conductor is the only writer of the tunnel routes.
|
|
34
|
+
export const tools = {
|
|
35
|
+
contract: 1,
|
|
36
|
+
tools: PORTS_TOOL_DEFINITIONS,
|
|
37
|
+
handlers: (options) => import('./tools.js').then((m) => m.toolsFor(options)),
|
|
38
|
+
};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// The ports tools' definitions, apart from their handlers so the preset
|
|
2
|
+
// stays import-light (the handlers load lazily).
|
|
3
|
+
const service = {
|
|
4
|
+
type: 'string',
|
|
5
|
+
description: 'a service key this worktree claims (see ports_status)',
|
|
6
|
+
};
|
|
7
|
+
export const PORTS_TOOL_DEFINITIONS = {
|
|
8
|
+
ports_up: {
|
|
9
|
+
description: "Share one of this worktree's claimed services over the tunnel and return its URL; every eligible service when `service` is omitted.",
|
|
10
|
+
input: { type: 'object', properties: { service } },
|
|
11
|
+
},
|
|
12
|
+
ports_down: {
|
|
13
|
+
description: "Take a claimed service's tunnel down; every tunnel of this worktree when `service` is omitted.",
|
|
14
|
+
input: { type: 'object', properties: { service } },
|
|
15
|
+
},
|
|
16
|
+
ports_status: {
|
|
17
|
+
description: "This worktree's tunnels as JSON rows: service, status, local origin, URL.",
|
|
18
|
+
},
|
|
19
|
+
ports_reap: {
|
|
20
|
+
description: 'Reconcile the tunnel records: drop routes whose worktree or service is gone.',
|
|
21
|
+
},
|
|
22
|
+
};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { ToolHandler } from '@bakers-build/conductor/contract';
|
|
2
|
+
import type { ClaimedDiscovery, TunnelRule } from './claims.js';
|
|
3
|
+
import { type OperationContext, type PortsTransport, type TunnelDesiredRecord } from './core.js';
|
|
4
|
+
import type { OpResult, ReapLiveness, ReapResult } from './tunnel-ops.js';
|
|
5
|
+
export interface PortsToolDeps {
|
|
6
|
+
loadTransport(): Promise<{
|
|
7
|
+
readonly ok: true;
|
|
8
|
+
readonly transport: PortsTransport;
|
|
9
|
+
} | {
|
|
10
|
+
readonly ok: false;
|
|
11
|
+
readonly message: string;
|
|
12
|
+
}>;
|
|
13
|
+
discover(worktree: string, ticket: string, zone: string): Promise<ClaimedDiscovery>;
|
|
14
|
+
readRecords(worktree: string): Promise<readonly TunnelDesiredRecord[]>;
|
|
15
|
+
bringUp(rule: TunnelRule, ctx: OperationContext): Promise<OpResult>;
|
|
16
|
+
takeDown(worktree: string, key: string | undefined, ctx: OperationContext): Promise<OpResult>;
|
|
17
|
+
reap(ctx: Pick<OperationContext, 'home' | 'transport' | 'signal'>, isLive: (record: TunnelDesiredRecord) => Promise<ReapLiveness>): Promise<ReapResult>;
|
|
18
|
+
branch(worktree: string): string | null;
|
|
19
|
+
home(): string;
|
|
20
|
+
}
|
|
21
|
+
export declare function portsTools(deps: PortsToolDeps): Record<string, ToolHandler>;
|
|
22
|
+
/** The live tools for the conductor's effective ports entry `with`. */
|
|
23
|
+
export declare function toolsFor(options: unknown): Record<string, ToolHandler>;
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
// The ports addon's agent tools, served by the conductor — the only writer
|
|
2
|
+
// of the machine's tunnel routes. Every tool acts on the worktree bound to
|
|
3
|
+
// the caller (a run's session, or the operator's cwd), never on an argument,
|
|
4
|
+
// and only on services that worktree claims. `bakers ports up/down/status/
|
|
5
|
+
// reap` call these same tools through the conductor.
|
|
6
|
+
import { existsSync, realpathSync } from 'node:fs';
|
|
7
|
+
import { homeBbDir } from '@bakers-build/core';
|
|
8
|
+
import { servicesToShare, shareAll } from './claim-share.js';
|
|
9
|
+
import { discoverClaimedServices } from './claims.js';
|
|
10
|
+
import { assertNoMachinePorts, bringUpTunnel, loadPortsTransport, readMachineTunnelRecords, reapTunnels, takeDownTunnel, withProblems, } from './core.js';
|
|
11
|
+
import { nodeDeps, nodeHttpProbe, nodeTunnelOpsDeps } from './deps-node.js';
|
|
12
|
+
import { currentBranch, liveTunnel, resolveTicketIdentifier, selectService, staleKeys, } from './index.js';
|
|
13
|
+
import { serviceRules } from './service-config.js';
|
|
14
|
+
/** DDEV labels containers with the real path; discovery matches it exactly. */
|
|
15
|
+
function canonicalPath(path) {
|
|
16
|
+
try {
|
|
17
|
+
return realpathSync(path);
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return path;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
export function portsTools(deps) {
|
|
24
|
+
const transportOf = async () => {
|
|
25
|
+
const loaded = await deps.loadTransport();
|
|
26
|
+
if (!loaded.ok)
|
|
27
|
+
throw new Error(loaded.message);
|
|
28
|
+
return loaded.transport;
|
|
29
|
+
};
|
|
30
|
+
const ticketOf = (req, worktree) => {
|
|
31
|
+
if (req.ticket)
|
|
32
|
+
return req.ticket.identifier;
|
|
33
|
+
const resolved = resolveTicketIdentifier(undefined, deps.branch(worktree));
|
|
34
|
+
if (!resolved.ok)
|
|
35
|
+
throw new Error(resolved.message);
|
|
36
|
+
return resolved.identifier;
|
|
37
|
+
};
|
|
38
|
+
const reapAll = (transport, signal) => deps.reap({ home: deps.home(), transport, signal }, async (record) => {
|
|
39
|
+
if (!existsSync(record.worktree))
|
|
40
|
+
return { live: false };
|
|
41
|
+
try {
|
|
42
|
+
const discovery = await deps.discover(record.worktree, record.ticket, transport.zone ?? '');
|
|
43
|
+
return liveTunnel(record, discovery);
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
// Unreadable settings are no evidence the route is gone: keep it.
|
|
47
|
+
return { live: true };
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
return {
|
|
51
|
+
ports_up: async (req) => {
|
|
52
|
+
const transport = await transportOf();
|
|
53
|
+
const worktree = canonicalPath(req.worktreePath);
|
|
54
|
+
const ticket = ticketOf(req, worktree);
|
|
55
|
+
const lines = [];
|
|
56
|
+
// A container IP reused by another DDEV project after `ddev restart`
|
|
57
|
+
// would serve that project under a stale route, so every `up` first
|
|
58
|
+
// re-checks every recorded route machine-wide, exactly like `reap`.
|
|
59
|
+
const recheck = await reapAll(transport, req.signal);
|
|
60
|
+
if (!recheck.ok ||
|
|
61
|
+
recheck.removedRecords > 0 ||
|
|
62
|
+
(recheck.refreshedRecords ?? 0) > 0)
|
|
63
|
+
lines.push(recheck.message);
|
|
64
|
+
const discovery = await deps.discover(worktree, ticket, transport.zone ?? '');
|
|
65
|
+
const ctx = {
|
|
66
|
+
worktree,
|
|
67
|
+
ticket,
|
|
68
|
+
home: deps.home(),
|
|
69
|
+
transport,
|
|
70
|
+
signal: req.signal,
|
|
71
|
+
};
|
|
72
|
+
const key = req.args.service;
|
|
73
|
+
if (key === undefined) {
|
|
74
|
+
const toShare = servicesToShare(discovery);
|
|
75
|
+
if (toShare.length === 0)
|
|
76
|
+
return { text: 'no eligible service to share' };
|
|
77
|
+
const outcomes = await shareAll(toShare, (claimed) => deps.bringUp(claimed.rules[0], ctx));
|
|
78
|
+
for (const { service: claimed, result } of outcomes)
|
|
79
|
+
lines.push(`${claimed.key}: ${result.message}`);
|
|
80
|
+
if (outcomes.some(({ result }) => !result.ok))
|
|
81
|
+
throw new Error(lines.join('\n'));
|
|
82
|
+
return { text: lines.join('\n') };
|
|
83
|
+
}
|
|
84
|
+
const selection = selectService(discovery, key);
|
|
85
|
+
if (!selection.ok)
|
|
86
|
+
throw new Error(selection.message);
|
|
87
|
+
const claimed = selection.service;
|
|
88
|
+
if (claimed.rules.length === 0)
|
|
89
|
+
throw new Error(`${claimed.key} cannot be shared (${claimed.status}${claimed.limitation ? `: ${claimed.limitation}` : ''})`);
|
|
90
|
+
const result = await deps.bringUp(claimed.rules[0], ctx);
|
|
91
|
+
lines.push(result.message);
|
|
92
|
+
if (claimed.limitation)
|
|
93
|
+
lines.push(claimed.limitation);
|
|
94
|
+
if (!result.ok)
|
|
95
|
+
throw new Error(lines.join('\n'));
|
|
96
|
+
return { text: lines.join('\n') };
|
|
97
|
+
},
|
|
98
|
+
ports_down: async (req) => {
|
|
99
|
+
const transport = await transportOf();
|
|
100
|
+
const worktree = canonicalPath(req.worktreePath);
|
|
101
|
+
const result = await deps.takeDown(worktree, req.args.service, {
|
|
102
|
+
worktree,
|
|
103
|
+
ticket: '',
|
|
104
|
+
home: deps.home(),
|
|
105
|
+
transport,
|
|
106
|
+
signal: req.signal,
|
|
107
|
+
});
|
|
108
|
+
if (!result.ok)
|
|
109
|
+
throw new Error(result.message);
|
|
110
|
+
return { text: result.message };
|
|
111
|
+
},
|
|
112
|
+
ports_status: async (req) => {
|
|
113
|
+
const worktree = canonicalPath(req.worktreePath);
|
|
114
|
+
const records = await deps.readRecords(worktree);
|
|
115
|
+
let stale = new Set();
|
|
116
|
+
const [first] = records;
|
|
117
|
+
if (first) {
|
|
118
|
+
try {
|
|
119
|
+
stale = staleKeys(records, await deps.discover(worktree, first.ticket, ''));
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
// Without discovery nothing is known to be stale.
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
const rows = records.map((r) => ({
|
|
126
|
+
service: r.key,
|
|
127
|
+
status: r.applied,
|
|
128
|
+
local: r.service,
|
|
129
|
+
...(r.url || r.hostname
|
|
130
|
+
? { url: r.url ?? `https://${r.hostname}` }
|
|
131
|
+
: {}),
|
|
132
|
+
...(r.error ? { error: r.error } : {}),
|
|
133
|
+
...(stale.has(r.key) ? { stale: true } : {}),
|
|
134
|
+
}));
|
|
135
|
+
return { text: JSON.stringify(rows) };
|
|
136
|
+
},
|
|
137
|
+
ports_reap: async (req) => {
|
|
138
|
+
const result = await reapAll(await transportOf(), req.signal);
|
|
139
|
+
if (!result.ok)
|
|
140
|
+
throw new Error(result.message);
|
|
141
|
+
return { text: result.message };
|
|
142
|
+
},
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
/** The live tools for the conductor's effective ports entry `with`. */
|
|
146
|
+
export function toolsFor(options) {
|
|
147
|
+
return portsTools({
|
|
148
|
+
loadTransport: async () => {
|
|
149
|
+
const [problem] = withProblems(options);
|
|
150
|
+
if (problem)
|
|
151
|
+
return { ok: false, message: problem };
|
|
152
|
+
try {
|
|
153
|
+
await assertNoMachinePorts();
|
|
154
|
+
return {
|
|
155
|
+
ok: true,
|
|
156
|
+
transport: await loadPortsTransport(options, homeBbDir()),
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
catch (err) {
|
|
160
|
+
return {
|
|
161
|
+
ok: false,
|
|
162
|
+
message: err instanceof Error ? err.message : String(err),
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
},
|
|
166
|
+
discover: (worktree, ticket, zone) => discoverClaimedServices(worktree, nodeDeps, {
|
|
167
|
+
ticket,
|
|
168
|
+
zone,
|
|
169
|
+
probe: nodeHttpProbe,
|
|
170
|
+
rules: serviceRules(options),
|
|
171
|
+
}),
|
|
172
|
+
readRecords: (worktree) => readMachineTunnelRecords(worktree, homeBbDir(), nodeTunnelOpsDeps),
|
|
173
|
+
bringUp: (rule, ctx) => bringUpTunnel(rule, ctx, nodeTunnelOpsDeps),
|
|
174
|
+
takeDown: (worktree, key, ctx) => takeDownTunnel(worktree, key, ctx, nodeTunnelOpsDeps),
|
|
175
|
+
reap: (ctx, isLive) => reapTunnels(ctx, isLive, nodeTunnelOpsDeps),
|
|
176
|
+
branch: currentBranch,
|
|
177
|
+
home: () => homeBbDir(),
|
|
178
|
+
});
|
|
179
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bakers-build/addon-ports",
|
|
3
|
-
"version": "0.5.1-next.
|
|
3
|
+
"version": "0.5.1-next.857",
|
|
4
4
|
"description": "bakers.build ports command plugin: discover a ticket worktree's running services (DDEV, Designbook, ad-hoc listeners) and bring shareable tunnels up and down. The command half of BB-475; usable without the cockpit half.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -23,15 +23,15 @@
|
|
|
23
23
|
"directory": "bakers-cli/addons/ports"
|
|
24
24
|
},
|
|
25
25
|
"dependencies": {
|
|
26
|
-
"@bakers-build/addon-ddev": "^0.5.1-next.
|
|
26
|
+
"@bakers-build/addon-ddev": "^0.5.1-next.857",
|
|
27
27
|
"commander": "^12.1.0"
|
|
28
28
|
},
|
|
29
29
|
"peerDependencies": {
|
|
30
|
-
"@bakers-build/conductor": "^0.5.1-next.
|
|
31
|
-
"@bakers-build/core": "^0.5.1-next.
|
|
30
|
+
"@bakers-build/conductor": "^0.5.1-next.857",
|
|
31
|
+
"@bakers-build/core": "^0.5.1-next.857"
|
|
32
32
|
},
|
|
33
33
|
"bakersBuild": {
|
|
34
|
-
"commit": "
|
|
34
|
+
"commit": "31830084e7db17fb0417b4681ec7dace42ae4138",
|
|
35
35
|
"channel": "next"
|
|
36
36
|
}
|
|
37
37
|
}
|