@norskvideo/ctl-sdk 0.1.24 → 0.1.26

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.
@@ -13,8 +13,19 @@ export interface ProductRunOpts {
13
13
  }
14
14
  /** argv (sans leading "docker") that launches a product container: detached,
15
15
  * auto-removed, loopback-published to its internal 4321, and role-labelled so
16
- * it shows up in the Infrastructure tab. */
17
- export declare function productRunArgs(image: string, hostPort: number, opts?: ProductRunOpts): string[];
16
+ * it shows up in the Infrastructure tab.
17
+ *
18
+ * The host side of the publish is EMPTY on purpose. ctl used to pick it from
19
+ * a fixed 14321+ range while consulting only its own registrations, which is
20
+ * no allocator at all: it cannot see another ctl daemon, another compose
21
+ * stack, or any other process on the host. Sibling CI runner containers
22
+ * sharing one docker daemon both picked 14321 and the second died with
23
+ * "driver failed programming external connectivity". Worse, a daemon that is
24
+ * itself a container cannot even probe for the clash — a bind in its own
25
+ * network namespace says nothing about the docker host's port space, which is
26
+ * where the publish actually lands. So the allocation belongs to the docker
27
+ * daemon, which owns that space; ctl reads back what it was given. */
28
+ export declare function productRunArgs(image: string, opts?: ProductRunOpts): string[];
18
29
  /** Stable container name for a product, derived from its manifest name, so
19
30
  * `docker ps` shows `norsk-product-studio` instead of a random docker alias.
20
31
  * Mirrors the singleton naming of norsk-proxy / norsk-ctl-cpu-monitor. */
@@ -23,7 +34,23 @@ export declare function productContainerName(productName: string): string;
23
34
  * so there is nothing to refresh; a tag can move under a registration. */
24
35
  export declare function isDigestRef(image: string): boolean;
25
36
  export declare function dockerPull(image: string): Promise<void>;
26
- export declare function dockerRun(image: string, hostPort: number, opts?: ProductRunOpts): Promise<string>;
37
+ /** Where a started product container ended up: its id, and the host port
38
+ * docker chose for it. The two are produced together because they change
39
+ * together — the container is `--rm`, so every restart is a new container
40
+ * with a new assignment and a stored port from the last one is already
41
+ * stale. */
42
+ export interface ProductPlacement {
43
+ containerId: string;
44
+ hostPort: number;
45
+ }
46
+ /** The host port from `docker inspect`'s HostPort lookup. Docker prints one
47
+ * line per binding (an IPv4 and an IPv6 row for the same publish is normal),
48
+ * and `<no value>` when the template finds nothing. */
49
+ export declare function parsePublishedPort(inspectOutput: string): number | undefined;
50
+ /** The host port docker published a container's internal 4321 on, or undefined
51
+ * when docker cannot say. */
52
+ export declare function dockerPublishedPort(containerId: string): Promise<number | undefined>;
53
+ export declare function dockerRun(image: string, opts?: ProductRunOpts): Promise<ProductPlacement>;
27
54
  /** The container's address on its first network (the default bridge for a
28
55
  * product container), or undefined when docker cannot say. */
29
56
  export declare function dockerAddress(containerId: string): Promise<string | undefined>;
package/docker-runner.js CHANGED
@@ -7,8 +7,19 @@ export const CONTAINER_INTERNAL_PORT = 4321;
7
7
  export const PRODUCT_ROLE_LABEL = "norsk-ctl.role=product";
8
8
  /** argv (sans leading "docker") that launches a product container: detached,
9
9
  * auto-removed, loopback-published to its internal 4321, and role-labelled so
10
- * it shows up in the Infrastructure tab. */
11
- export function productRunArgs(image, hostPort, opts = {}) {
10
+ * it shows up in the Infrastructure tab.
11
+ *
12
+ * The host side of the publish is EMPTY on purpose. ctl used to pick it from
13
+ * a fixed 14321+ range while consulting only its own registrations, which is
14
+ * no allocator at all: it cannot see another ctl daemon, another compose
15
+ * stack, or any other process on the host. Sibling CI runner containers
16
+ * sharing one docker daemon both picked 14321 and the second died with
17
+ * "driver failed programming external connectivity". Worse, a daemon that is
18
+ * itself a container cannot even probe for the clash — a bind in its own
19
+ * network namespace says nothing about the docker host's port space, which is
20
+ * where the publish actually lands. So the allocation belongs to the docker
21
+ * daemon, which owns that space; ctl reads back what it was given. */
22
+ export function productRunArgs(image, opts = {}) {
12
23
  return [
13
24
  "run",
14
25
  "-d",
@@ -17,7 +28,7 @@ export function productRunArgs(image, hostPort, opts = {}) {
17
28
  PRODUCT_ROLE_LABEL,
18
29
  ...(opts.network ? ["--network", opts.network] : []),
19
30
  "-p",
20
- `127.0.0.1:${hostPort}:${CONTAINER_INTERNAL_PORT}`,
31
+ `127.0.0.1::${CONTAINER_INTERNAL_PORT}`,
21
32
  image,
22
33
  ];
23
34
  }
@@ -44,15 +55,50 @@ export async function dockerPull(image) {
44
55
  throw new ProductError("DOCKER_PULL_FAILED", `docker pull failed (exit ${exitCode}): ${stderr || "no stderr"}`);
45
56
  }
46
57
  }
47
- export async function dockerRun(image, hostPort, opts = {}) {
48
- const proc = Bun.spawn(["docker", ...productRunArgs(image, hostPort, opts)], { stdout: "pipe", stderr: "pipe" });
58
+ /** The host port from `docker inspect`'s HostPort lookup. Docker prints one
59
+ * line per binding (an IPv4 and an IPv6 row for the same publish is normal),
60
+ * and `<no value>` when the template finds nothing. */
61
+ export function parsePublishedPort(inspectOutput) {
62
+ for (const line of inspectOutput.split(/\r?\n/)) {
63
+ const port = Number.parseInt(line.trim(), 10);
64
+ if (Number.isInteger(port) && port > 0)
65
+ return port;
66
+ }
67
+ return undefined;
68
+ }
69
+ /** The host port docker published a container's internal 4321 on, or undefined
70
+ * when docker cannot say. */
71
+ export async function dockerPublishedPort(containerId) {
72
+ const proc = Bun.spawn([
73
+ "docker",
74
+ "inspect",
75
+ "-f",
76
+ `{{range index .NetworkSettings.Ports "${CONTAINER_INTERNAL_PORT}/tcp"}}{{.HostPort}}\n{{end}}`,
77
+ containerId,
78
+ ], { stdout: "pipe", stderr: "pipe" });
79
+ const exitCode = await proc.exited;
80
+ const stdout = await new Response(proc.stdout).text();
81
+ if (exitCode !== 0)
82
+ return undefined;
83
+ return parsePublishedPort(stdout);
84
+ }
85
+ export async function dockerRun(image, opts = {}) {
86
+ const proc = Bun.spawn(["docker", ...productRunArgs(image, opts)], { stdout: "pipe", stderr: "pipe" });
49
87
  const exitCode = await proc.exited;
50
88
  const stdout = (await new Response(proc.stdout).text()).trim();
51
89
  const stderr = (await new Response(proc.stderr).text()).trim();
52
90
  if (exitCode !== 0 || !stdout) {
53
91
  throw new ProductError("DOCKER_RUN_FAILED", `docker run failed (exit ${exitCode}): ${stderr || "no stderr"}`);
54
92
  }
55
- return stdout;
93
+ const containerId = stdout;
94
+ const hostPort = await dockerPublishedPort(containerId);
95
+ if (hostPort === undefined) {
96
+ // Nothing to fall back to: the port is docker's to report, and a
97
+ // registration without one cannot be dialled or restarted.
98
+ await dockerRm(containerId);
99
+ throw new ProductError("DOCKER_RUN_FAILED", `docker did not report a published host port for ${CONTAINER_INTERNAL_PORT}/tcp`);
100
+ }
101
+ return { containerId, hostPort };
56
102
  }
57
103
  /** The container's address on its first network (the default bridge for a
58
104
  * product container), or undefined when docker cannot say. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@norskvideo/ctl-sdk",
3
- "version": "0.1.24",
3
+ "version": "0.1.26",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {
@@ -8,14 +8,30 @@ export interface ProductHealthState {
8
8
  restartAttempts: number;
9
9
  /** Clock value of the most recent restart attempt; gates backoff. */
10
10
  lastRestartAt?: number;
11
+ /** URL the last failing probe dialled. Cleared on a healthy probe. */
12
+ lastProbeUrl?: string;
13
+ /** Why the last probe failed — status line or transport error. Cleared on
14
+ * a healthy probe. */
15
+ lastProbeDetail?: string;
16
+ }
17
+ /** What one liveness probe saw. A bare boolean here cost three CI runs that
18
+ * reported a product restart-looping with no record of what was dialled or
19
+ * what came back, so the URL and the reason travel with the verdict. */
20
+ export interface ProductProbeResult {
21
+ ok: boolean;
22
+ /** The address dialled, or "" when the probe declined to dial at all. */
23
+ url: string;
24
+ /** Present whenever `ok` is false: the HTTP status, the transport error, or
25
+ * the reason no dial was attempted. */
26
+ detail?: string;
11
27
  }
12
28
  export interface ProductHealthMonitorOptions {
13
29
  /** Products to consider. Non-container products are ignored (externally
14
30
  * owned), so this can safely be the unfiltered `productService.list`. */
15
31
  listProducts: () => ProductRegistration[];
16
- /** Liveness probe — true means healthy. Injected so tests don't hit the
17
- * network; the daemon wires `probeProductHealth`. */
18
- probe: (reg: ProductRegistration) => Promise<boolean>;
32
+ /** Liveness probe. Injected so tests don't hit the network; the daemon
33
+ * wires `probeProductHealth`. */
34
+ probe: (reg: ProductRegistration) => Promise<ProductProbeResult>;
19
35
  /** Recovery action for a product over threshold. Typically
20
36
  * `productService.restart`. Rejection counts as a failed attempt. */
21
37
  restart: (name: string) => Promise<void>;
@@ -69,4 +85,4 @@ export declare class ProductHealthMonitor {
69
85
  * (default /healthz) with a short timeout. Any non-2xx, network error, or
70
86
  * timeout reads as unhealthy. Container-only — dev products are externally
71
87
  * owned and never reach here. */
72
- export declare function probeProductHealth(reg: ProductRegistration, timeoutMs?: number): Promise<boolean>;
88
+ export declare function probeProductHealth(reg: ProductRegistration, timeoutMs?: number): Promise<ProductProbeResult>;
@@ -75,62 +75,83 @@ export class ProductHealthMonitor {
75
75
  }
76
76
  async checkOne(reg) {
77
77
  const prev = this.states.get(reg.name) ?? UNKNOWN;
78
- let healthy;
78
+ let result;
79
79
  try {
80
- healthy = await this.probe(reg);
80
+ result = await this.probe(reg);
81
81
  }
82
- catch {
83
- healthy = false;
82
+ catch (e) {
83
+ result = { ok: false, url: "", detail: `probe threw: ${e instanceof Error ? e.message : String(e)}` };
84
84
  }
85
- if (healthy) {
85
+ if (result.ok) {
86
86
  this.set(reg.name, { status: "healthy", consecutiveFailures: 0, restartAttempts: 0 }, prev);
87
87
  return;
88
88
  }
89
89
  const consecutiveFailures = prev.consecutiveFailures + 1;
90
+ const probed = { lastProbeUrl: result.url, lastProbeDetail: result.detail };
91
+ // One line per unhealthy episode, not per sweep: enough to diagnose a
92
+ // restart loop without a warn every interval for a product known bad.
93
+ if (prev.consecutiveFailures === 0) {
94
+ logger.warn(`Product '${reg.name}' health probe failed: ${result.url || "not dialled"} — ${result.detail ?? "no detail"}`);
95
+ }
96
+ else {
97
+ logger.debug(`Product '${reg.name}' health probe failed (${consecutiveFailures}): ${result.url || "not dialled"} — ${result.detail ?? "no detail"}`);
98
+ }
90
99
  const belowThreshold = consecutiveFailures < this.failureThreshold;
91
100
  const gaveUp = prev.restartAttempts >= this.maxRestarts;
92
101
  const backoffElapsed = prev.lastRestartAt === undefined || this.now() - prev.lastRestartAt >= this.restartBackoffMs;
93
102
  if (belowThreshold || gaveUp || !backoffElapsed) {
94
- this.set(reg.name, { ...prev, status: "unhealthy", consecutiveFailures }, prev);
103
+ this.set(reg.name, { ...prev, ...probed, status: "unhealthy", consecutiveFailures }, prev);
95
104
  return;
96
105
  }
97
106
  // Threshold reached, attempts left, backoff elapsed: attempt recovery.
98
107
  const at = this.now();
99
108
  const restartAttempts = prev.restartAttempts + 1;
100
- this.set(reg.name, { status: "restarting", consecutiveFailures: 0, restartAttempts, lastRestartAt: at }, prev);
109
+ this.set(reg.name, { ...probed, status: "restarting", consecutiveFailures: 0, restartAttempts, lastRestartAt: at }, prev);
101
110
  try {
102
111
  await this.restart(reg.name);
103
112
  // Stay "restarting"; the next sweep re-probes to confirm recovery.
104
113
  }
105
114
  catch (e) {
106
115
  logger.warn(`Product '${reg.name}': restart failed — ${e instanceof Error ? e.message : String(e)}`);
107
- this.set(reg.name, { status: "unhealthy", consecutiveFailures: 0, restartAttempts, lastRestartAt: at }, prev);
116
+ this.set(reg.name, { ...probed, status: "unhealthy", consecutiveFailures: 0, restartAttempts, lastRestartAt: at }, prev);
108
117
  }
109
118
  }
110
119
  set(name, next, prev) {
111
120
  this.states.set(name, next);
112
121
  if (next.status !== prev.status) {
113
- logger.info(`Product '${name}' health: ${prev.status} -> ${next.status}`);
122
+ const why = next.status === "healthy" ? "" : detailSuffix(next);
123
+ logger.info(`Product '${name}' health: ${prev.status} -> ${next.status}${why}`);
114
124
  this.onChange?.(name, next);
115
125
  }
116
126
  }
117
127
  }
128
+ /** Renders the recorded probe failure onto a transition log line, so the CI
129
+ * log of a restart loop carries the address and the reason. */
130
+ function detailSuffix(state) {
131
+ if (state.lastProbeUrl === undefined && state.lastProbeDetail === undefined)
132
+ return "";
133
+ return ` (${state.lastProbeUrl || "not dialled"} — ${state.lastProbeDetail ?? "no detail"})`;
134
+ }
118
135
  /** Default liveness probe: GET the product's manifest-declared health path
119
136
  * (default /healthz) with a short timeout. Any non-2xx, network error, or
120
137
  * timeout reads as unhealthy. Container-only — dev products are externally
121
138
  * owned and never reach here. */
122
139
  export async function probeProductHealth(reg, timeoutMs = 3_000) {
123
- if (reg.spec.kind !== "container" || reg.port === undefined)
124
- return false;
140
+ if (reg.spec.kind !== "container") {
141
+ return { ok: false, url: "", detail: `not a container product (kind '${reg.spec.kind}')` };
142
+ }
143
+ if (reg.port === undefined && reg.reachHost === undefined) {
144
+ return { ok: false, url: "", detail: "registration has no published port and no reachHost" };
145
+ }
125
146
  const path = reg.manifest.api?.healthCheckPath ?? "/healthz";
126
- const base = productBaseUrl(reg);
147
+ const url = `${productBaseUrl(reg)}${path.startsWith("/") ? path : `/${path}`}`;
127
148
  try {
128
- const r = await fetch(`${base}${path.startsWith("/") ? path : `/${path}`}`, {
129
- signal: AbortSignal.timeout(timeoutMs),
130
- });
131
- return r.ok;
149
+ const r = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
150
+ if (r.ok)
151
+ return { ok: true, url };
152
+ return { ok: false, url, detail: `HTTP ${r.status} ${r.statusText}`.trim() };
132
153
  }
133
- catch {
134
- return false;
154
+ catch (e) {
155
+ return { ok: false, url, detail: e instanceof Error ? `${e.name}: ${e.message}` : String(e) };
135
156
  }
136
157
  }
@@ -1,3 +1,4 @@
1
+ import { type ProductPlacement } from "./docker-runner.js";
1
2
  import { type LicenseStager } from "./license-registration.js";
2
3
  import { type ProductReach } from "./product-reach.js";
3
4
  import type { ProductTemplateSource } from "./product-template-record.js";
@@ -80,7 +81,9 @@ export type RefreshProductTemplateBytesFn = ImportProductTemplateBytesFn;
80
81
  * made an injected fake silently inert on add/remove. */
81
82
  export interface ProductContainerOps {
82
83
  pull(image: string): Promise<void>;
83
- run(image: string, hostPort: number): Promise<string>;
84
+ /** Start the container. The host port comes back from docker rather than
85
+ * going in: docker owns the host port space (see docker-runner.ts). */
86
+ run(image: string): Promise<ProductPlacement>;
84
87
  remove(containerId: string): Promise<void>;
85
88
  rename(containerId: string, name: string): Promise<void>;
86
89
  waitForReady(baseUrl: string): Promise<void>;
@@ -94,7 +97,6 @@ export interface ProductContainerOps {
94
97
  export declare const defaultProductContainerOps: ProductContainerOps;
95
98
  export interface ProductServiceOptions {
96
99
  store: ProductStore;
97
- allocatePort: AllocatePortFn;
98
100
  /** Optional: called once per `manifest.defaultProductTemplates` entry at
99
101
  * registration time. Omit on hosts that don't store product templates
100
102
  * (defaultProductTemplates is then silently skipped). */
@@ -135,7 +137,6 @@ export declare class ProductService {
135
137
  */
136
138
  private readonly mutations;
137
139
  private readonly store;
138
- private readonly allocatePort;
139
140
  private readonly importProductTemplateBytes?;
140
141
  private readonly refreshProductTemplateBytes?;
141
142
  private readonly stageLicense?;
@@ -52,7 +52,6 @@ export class ProductService {
52
52
  */
53
53
  mutations = new Mutex();
54
54
  store;
55
- allocatePort;
56
55
  importProductTemplateBytes;
57
56
  refreshProductTemplateBytes;
58
57
  stageLicense;
@@ -61,7 +60,6 @@ export class ProductService {
61
60
  reach;
62
61
  constructor(opts) {
63
62
  this.store = opts.store;
64
- this.allocatePort = opts.allocatePort;
65
63
  this.importProductTemplateBytes = opts.importProductTemplateBytes;
66
64
  this.refreshProductTemplateBytes = opts.refreshProductTemplateBytes;
67
65
  this.stageLicense = opts.stageLicense;
@@ -117,18 +115,12 @@ export class ProductService {
117
115
  baseUrl = specBaseUrl(spec);
118
116
  }
119
117
  else {
120
- const portMap = {};
121
- for (const p of existing)
122
- if (p.port !== undefined)
123
- portMap[p.name] = { port: p.port };
124
- const allocated = this.allocatePort(portMap);
125
- if (allocated === null) {
126
- throw new ProductError("PORT_EXHAUSTED", `no free port available for new product`);
127
- }
128
- port = allocated;
129
118
  await this.refreshImage(spec.image);
130
- logger.info(`Starting product container: ${spec.image} on host port ${port} (reach: ${this.reach})`);
131
- containerId = await this.containerOps.run(spec.image, port);
119
+ logger.info(`Starting product container: ${spec.image} (reach: ${this.reach})`);
120
+ const placement = await this.containerOps.run(spec.image);
121
+ containerId = placement.containerId;
122
+ port = placement.hostPort;
123
+ logger.info(`Product container ${containerId.slice(0, 12)} published on host port ${port}`);
132
124
  reachHost = await this.reachHostFor(containerId);
133
125
  baseUrl = specBaseUrl(spec, port, reachHost);
134
126
  }
@@ -317,10 +309,10 @@ export class ProductService {
317
309
  // Already gone (crashed / --rm reaped) — nothing to stop.
318
310
  }
319
311
  }
320
- const containerId = await this.containerOps.run(target.spec.image, target.port);
312
+ const { containerId, hostPort } = await this.containerOps.run(target.spec.image);
321
313
  const reachHost = await this.reachHostFor(containerId);
322
- await this.store.update((products) => products.map((p) => (p.name === name ? withContainerId(p, containerId, reachHost) : p)));
323
- await this.containerOps.waitForReady(specBaseUrl(target.spec, target.port, reachHost));
314
+ await this.store.update((products) => products.map((p) => (p.name === name ? withPlacement(p, containerId, hostPort, reachHost) : p)));
315
+ await this.containerOps.waitForReady(specBaseUrl(target.spec, hostPort, reachHost));
324
316
  await this.containerOps.rename(containerId, productContainerName(name));
325
317
  containerRestarted = true;
326
318
  }
@@ -408,12 +400,12 @@ export class ProductService {
408
400
  return;
409
401
  }
410
402
  try {
411
- const containerId = await this.containerOps.run(reg.spec.image, reg.port);
403
+ const { containerId, hostPort } = await this.containerOps.run(reg.spec.image);
412
404
  const reachHost = await this.reachHostFor(containerId);
413
- await this.containerOps.waitForReady(specBaseUrl(reg.spec, reg.port, reachHost));
405
+ await this.containerOps.waitForReady(specBaseUrl(reg.spec, hostPort, reachHost));
414
406
  await this.containerOps.rename(containerId, productContainerName(reg.name));
415
- restored.set(reg.name, { containerId, reachHost });
416
- logger.info(`Product '${reg.name}' container restored on host port ${reg.port}`);
407
+ restored.set(reg.name, { containerId, hostPort, reachHost });
408
+ logger.info(`Product '${reg.name}' container restored on host port ${hostPort}`);
417
409
  }
418
410
  catch (e) {
419
411
  restored.set(reg.name, undefined);
@@ -424,7 +416,9 @@ export class ProductService {
424
416
  if (!restored.has(p.name))
425
417
  return p;
426
418
  const r = restored.get(p.name);
427
- return withContainerId(p, r?.containerId, r?.reachHost);
419
+ return r === undefined
420
+ ? withContainerId(p, undefined)
421
+ : withPlacement(p, r.containerId, r.hostPort, r.reachHost);
428
422
  }));
429
423
  }
430
424
  /** Stop (if still present) and relaunch a single container-kind product,
@@ -455,12 +449,12 @@ export class ProductService {
455
449
  // Already gone (crashed / --rm reaped) — nothing to stop.
456
450
  }
457
451
  }
458
- const containerId = await this.containerOps.run(target.spec.image, target.port);
452
+ const { containerId, hostPort } = await this.containerOps.run(target.spec.image);
459
453
  const reachHost = await this.reachHostFor(containerId);
460
- await this.store.update((products) => products.map((p) => (p.name === name ? withContainerId(p, containerId, reachHost) : p)));
461
- await this.containerOps.waitForReady(specBaseUrl(target.spec, target.port, reachHost));
454
+ await this.store.update((products) => products.map((p) => (p.name === name ? withPlacement(p, containerId, hostPort, reachHost) : p)));
455
+ await this.containerOps.waitForReady(specBaseUrl(target.spec, hostPort, reachHost));
462
456
  await this.containerOps.rename(containerId, productContainerName(name));
463
- logger.info(`Product '${name}' container restarted on host port ${target.port}`);
457
+ logger.info(`Product '${name}' container restarted on host port ${hostPort}`);
464
458
  }
465
459
  }
466
460
  /** Return a copy of `reg` with containerId (and the address it was reached at)
@@ -473,3 +467,9 @@ function withContainerId(reg, containerId, reachHost) {
473
467
  return rest;
474
468
  return { ...rest, containerId, ...(reachHost !== undefined ? { reachHost } : {}) };
475
469
  }
470
+ /** As withContainerId, but also records the host port docker assigned THIS
471
+ * container. Every (re)start is a new container with a new assignment, so the
472
+ * port travels with the id or the next dial goes to the dead one's port. */
473
+ function withPlacement(reg, containerId, hostPort, reachHost) {
474
+ return { ...withContainerId(reg, containerId, reachHost), port: hostPort };
475
+ }