@camunda8/cli 4.3.0-alpha.1 → 4.3.0-alpha.3

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 CHANGED
@@ -70,6 +70,9 @@ c8ctl cluster start
70
70
  # Store a secret for local development (values are never shown or stored by c8ctl)
71
71
  c8ctl cluster secrets set OPENAI_API_KEY
72
72
 
73
+ # Manage isolated local physical tenants (requires a supporting c8run 8.10+ build)
74
+ c8ctl cluster tenants add sales
75
+
73
76
  # Deploy a process and start an instance
74
77
  c8ctl deploy ./my-process.bpmn
75
78
  c8ctl run my-process
@@ -43,6 +43,22 @@ c8ctl cluster install 8.8
43
43
  c8ctl cluster delete 8.8
44
44
  ```
45
45
 
46
+ ## Physical tenants
47
+
48
+ For physical tenants (supporting Camunda 8.10+ builds):
49
+
50
+ ```bash
51
+ c8ctl cluster tenants --c8-version 8.10 add sales
52
+ c8ctl cluster start 8.10
53
+ c8ctl cluster tenants list
54
+ c8ctl cluster secrets --tenant sales set OPENAI_API_KEY
55
+ c8ctl cluster tenants remove sales --yes
56
+ # Or choose tenants for one start only:
57
+ c8ctl cluster start 8.10 --physical-tenants sales,hr
58
+ ```
59
+
60
+ Tenant commands delegate to the selected installed c8run, following the same version selection and terminal behavior as `cluster secrets`. c8run owns tenant configuration and storage. See [local physical tenants](../../docs/getting-started.md#local-physical-tenants) for authentication, profiles, relative paths, and limitations.
61
+
46
62
  ## Version aliases
47
63
 
48
64
  The `stable` and `alpha` aliases are resolved dynamically by querying the
@@ -106,6 +122,26 @@ c8ctl), `cluster stop` terminates it directly using the recorded PID.
106
122
 
107
123
  Set `C8RUN_CACHE_DIR` environment variable to override.
108
124
 
125
+ ### Download interruptions
126
+
127
+ The c8run archive is several hundred MB. If the connection drops, `c8ctl cluster start` and `c8ctl cluster install` retry up to three times and resume from where the download stopped when the server supports it. An attempt that receives no data for 60 seconds is aborted and retried. If the download still fails, the error names the cause and suggests what to try:
128
+
129
+ - Behind a proxy, set `HTTPS_PROXY` together with `NODE_USE_ENV_PROXY=1` (Node.js 22.21+ or 24.5+).
130
+ - Set `C8CTL_C8RUN_DOWNLOAD_URL` to download from a mirror with the same layout as the Camunda Download Center.
131
+ - Add `--verbose` to print HTTP details for each download attempt: request and response headers, timing, throughput, and the full error cause chain.
132
+
133
+ ## Physical-tenant verification
134
+
135
+ The opt-in integration test owns the local cluster lifecycle and needs an installed c8run build with physical-tenant CLI support. Run it separately from the general integration suite, with no other cluster running and a dedicated cache containing that distribution:
136
+
137
+ ```bash
138
+ C8RUN_CACHE_DIR=/path/to/scratch-cache \
139
+ C8CTL_PHYSICAL_TENANTS_VERSION=8.10.1 \
140
+ node --experimental-strip-types --test tests/integration/physical-tenants.test.ts
141
+ ```
142
+
143
+ Set the version to the actual installed cache version. The test uses temporary tenant/secrets/profile files, validates authenticated profile routing and deployment isolation, restarts the cluster, and stops it on completion. Its tenant's engine data remains in the dedicated cache. The normal unit suite tests forwarding and failure handling without downloading or launching Java.
144
+
109
145
  ## Supported platforms
110
146
 
111
147
  - macOS (x86_64, aarch64)
@@ -18,10 +18,13 @@ import {
18
18
  rmSync,
19
19
  readdirSync,
20
20
  readFileSync,
21
+ statSync,
21
22
  } from 'node:fs';
23
+ import { once } from 'node:events';
22
24
  import { chmod } from 'node:fs/promises';
23
25
  import { homedir, platform as osPlatform, arch as osArch } from 'node:os';
24
26
  import { join, dirname, isAbsolute, resolve } from 'node:path';
27
+ import { finished } from 'node:stream/promises';
25
28
  import { fileURLToPath } from 'node:url';
26
29
 
27
30
  // ---------------------------------------------------------------------------
@@ -328,11 +331,12 @@ export const metadata = {
328
331
  // so the subcommand flags are documented via `flagsHint` instead.
329
332
  passthrough: true,
330
333
  passthroughHint:
331
- '--purge, --debug and --c8-version are read by the plugin; everything after `secrets` is forwarded to c8run',
334
+ '--purge, --debug, --physical-tenants and --c8-version are read by the plugin; arguments after `secrets` or `tenants` are forwarded to c8run',
332
335
  flagsHint: [
333
336
  '--c8-version <version> Camunda version, alias or major.minor (alternative to the positional <version>)',
334
337
  '--debug (start, stop) Stream raw c8run output',
335
338
  '--purge (stop only) Also delete runtime data after stopping',
339
+ '--physical-tenants <ids> (start only) Comma-separated physical tenants for this run (repeatable; Camunda 8.10+)',
336
340
  ],
337
341
  subcommands: [
338
342
  { name: 'start', description: 'Start local Camunda 8 cluster' },
@@ -346,6 +350,7 @@ export const metadata = {
346
350
  { name: 'logs', description: 'Stream cluster logs' },
347
351
  { name: 'purge', description: 'Delete runtime data (keeps binary) so the next start is fresh' },
348
352
  { name: 'secrets', description: 'Manage local development secrets (passed through to c8run)' },
353
+ { name: 'tenants', description: 'Manage local physical tenants (passed through to c8run; Camunda 8.10+)' },
349
354
  ],
350
355
  examples: [
351
356
  { command: 'c8ctl cluster start', description: 'Start a local Camunda 8 cluster (latest stable)' },
@@ -364,6 +369,9 @@ export const metadata = {
364
369
  { command: 'c8ctl cluster secrets list', description: 'List secret names (values are never shown)' },
365
370
  { command: 'c8ctl cluster secrets import .env.secrets', description: 'Import secrets from a dotenv file' },
366
371
  { command: 'c8ctl cluster secrets delete OPENAI_API_KEY --yes', description: 'Delete a secret without prompting' },
372
+ { command: 'c8ctl cluster tenants --c8-version 8.10 add sales', description: 'Save a physical tenant using an installed 8.10 build' },
373
+ { command: 'c8ctl cluster start 8.10 --physical-tenants sales,hr', description: 'Start physical tenants for one run only' },
374
+ { command: 'c8ctl cluster secrets --tenant sales set OPENAI_API_KEY', description: 'Store a secret for one physical tenant' },
367
375
  ],
368
376
  },
369
377
  },
@@ -486,98 +494,746 @@ function formatLocalVersionsHint(cacheDir) {
486
494
  return `Locally available versions:\n${versions.map(v => ` ${v}`).join('\n')}`;
487
495
  }
488
496
 
489
- function getDownloadUrl(version) {
497
+ function getArchiveName(version) {
490
498
  const platformInfo = getPlatformIdentifier();
491
- return `${DOWNLOAD_BASE_URL}${version}/camunda8-run-${version}-${platformInfo.platform}-${platformInfo.arch}.${platformInfo.extension}`;
499
+ return `camunda8-run-${version}-${platformInfo.platform}-${platformInfo.arch}.${platformInfo.extension}`;
492
500
  }
493
501
 
494
- async function downloadC8Run(config) {
495
- const logger = getLogger();
496
- const version = config.version;
502
+ function getDownloadUrl(version) {
503
+ return `${DOWNLOAD_BASE_URL}${version}/${getArchiveName(version)}`;
504
+ }
505
+
506
+ // A c8run archive is several hundred MB, so a single dropped connection (a
507
+ // proxy or load balancer closing the socket, a Wi-Fi hiccup) must not fail
508
+ // the whole `cluster start`. downloadWithRetry() makes one initial attempt
509
+ // plus up to DOWNLOAD_MAX_RETRIES retries, resuming with an HTTP Range request
510
+ // where the server allows it, and aborts an attempt that receives no data for
511
+ // DOWNLOAD_STALL_TIMEOUT_MS (undici's own body timeout is 300s).
512
+ const DOWNLOAD_MAX_RETRIES = 3;
513
+ const DOWNLOAD_RETRY_BASE_DELAY_MS = 2_000;
514
+ const DOWNLOAD_STALL_TIMEOUT_MS = 60_000;
515
+ const MB = 1024 * 1024;
516
+ const PROGRESS_STEP_PERCENT = 5;
517
+ const PROGRESS_INTERVAL_MS = 5_000;
518
+
519
+ // TLS certificate errors, which a retry cannot fix (Node's X509 verification
520
+ // codes, see https://nodejs.org/api/tls.html#x509-certificate-error-codes,
521
+ // except OUT_OF_MEM). File-system failures are tagged by fileSystemError().
522
+ const TLS_ERROR_CODES = new Set([
523
+ 'UNABLE_TO_GET_ISSUER_CERT',
524
+ 'UNABLE_TO_GET_CRL',
525
+ 'UNABLE_TO_DECRYPT_CERT_SIGNATURE',
526
+ 'UNABLE_TO_DECRYPT_CRL_SIGNATURE',
527
+ 'UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY',
528
+ 'CERT_SIGNATURE_FAILURE',
529
+ 'CRL_SIGNATURE_FAILURE',
530
+ 'CERT_NOT_YET_VALID',
531
+ 'CERT_HAS_EXPIRED',
532
+ 'CRL_NOT_YET_VALID',
533
+ 'CRL_HAS_EXPIRED',
534
+ 'ERROR_IN_CERT_NOT_BEFORE_FIELD',
535
+ 'ERROR_IN_CERT_NOT_AFTER_FIELD',
536
+ 'ERROR_IN_CRL_LAST_UPDATE_FIELD',
537
+ 'ERROR_IN_CRL_NEXT_UPDATE_FIELD',
538
+ 'DEPTH_ZERO_SELF_SIGNED_CERT',
539
+ 'SELF_SIGNED_CERT_IN_CHAIN',
540
+ 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY',
541
+ 'UNABLE_TO_VERIFY_LEAF_SIGNATURE',
542
+ 'CERT_CHAIN_TOO_LONG',
543
+ 'CERT_REVOKED',
544
+ 'INVALID_CA',
545
+ 'PATH_LENGTH_EXCEEDED',
546
+ 'INVALID_PURPOSE',
547
+ 'CERT_UNTRUSTED',
548
+ 'CERT_REJECTED',
549
+ 'HOSTNAME_MISMATCH',
550
+ 'ERR_TLS_CERT_ALTNAME_INVALID',
551
+ ]);
497
552
 
498
- const downloadUrl = getDownloadUrl(version);
553
+ /**
554
+ * Read a millisecond override from the environment. These are internal knobs
555
+ * (like C8CTL_STOP_WAIT_TIMEOUT_MS) so tests can keep backoff and stall
556
+ * detection fast; unset, empty or invalid values fall back to the default.
557
+ */
558
+ function msFromEnv(name, fallback, { allowZero = true } = {}) {
559
+ const raw = process.env[name];
560
+ if (raw === undefined || raw.trim() === '') return fallback;
561
+ const value = Number(raw);
562
+ if (!Number.isFinite(value) || value < 0 || (!allowZero && value === 0)) return fallback;
563
+ return value;
564
+ }
499
565
 
500
- logger.info(`Downloading Camunda ${version} for ${getPlatformIdentifier().platform}...`);
566
+ function formatMB(bytes) {
567
+ return `${Math.floor(bytes / MB)} MB`;
568
+ }
501
569
 
502
- const cacheDir = config.cacheDir;
503
- mkdirSync(cacheDir, { recursive: true });
570
+ /** Like formatMB, but shows KB below 1 MB so small amounts don't read as "0 MB". */
571
+ function formatSize(bytes) {
572
+ return bytes > 0 && bytes < MB ? `${Math.max(1, Math.floor(bytes / 1024))} KB` : formatMB(bytes);
573
+ }
504
574
 
505
- const platformInfo = getPlatformIdentifier();
506
- const targetFile = join(
507
- cacheDir,
508
- `c8run-${version}-${platformInfo.platform}-${platformInfo.arch}.${platformInfo.extension}`,
509
- );
575
+ function formatMBPrecise(bytes) {
576
+ return `${(bytes / MB).toFixed(1)} MB`;
577
+ }
510
578
 
511
- const response = await fetch(downloadUrl).catch((error) => {
512
- throw new Error(
513
- `Cannot reach the Camunda Download Center.\n` +
514
- `URL: ${downloadUrl}\n` +
515
- `Error: ${error.message}\n` +
516
- `Please check your network connection and proxy settings, then try again.\n\n` +
517
- formatLocalVersionsHint(cacheDir),
518
- );
579
+ function formatDuration(ms) {
580
+ return ms >= 1000 ? `${Math.round(ms / 100) / 10}s` : `${Math.round(ms)}ms`;
581
+ }
582
+
583
+ function formatThroughput(bytes, ms) {
584
+ return ms > 0 ? `${((bytes / MB) / (ms / 1000)).toFixed(1)} MB/s` : 'n/a';
585
+ }
586
+
587
+ function formatEta(ms) {
588
+ const s = Math.ceil(ms / 1000);
589
+ return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m ${String(s % 60).padStart(2, '0')}s`;
590
+ }
591
+
592
+ function downloadError(message, props = {}) {
593
+ const { cause, ...rest } = props;
594
+ return Object.assign(new Error(message, cause === undefined ? undefined : { cause }), rest);
595
+ }
596
+
597
+ /**
598
+ * Flatten an error and its `cause` chain into `{ name, code, message }`
599
+ * entries, outermost first. Undici reports a dropped download as
600
+ * `TypeError: terminated` whose cause carries the useful part (e.g.
601
+ * `UND_ERR_SOCKET: other side closed`).
602
+ */
603
+ export function errorChain(error) {
604
+ const chain = [];
605
+ const seen = new Set();
606
+ let current = error;
607
+ while (current !== undefined && current !== null && !seen.has(current) && chain.length < 10) {
608
+ seen.add(current);
609
+ if (typeof current === 'object') {
610
+ chain.push({
611
+ name: typeof current.name === 'string' ? current.name : 'Error',
612
+ code: typeof current.code === 'string' ? current.code : undefined,
613
+ message: typeof current.message === 'string' ? current.message : String(current),
614
+ });
615
+ current = current.cause;
616
+ } else {
617
+ chain.push({ name: typeof current, code: undefined, message: String(current) });
618
+ break;
619
+ }
620
+ }
621
+ return chain;
622
+ }
623
+
624
+ function formatChainEntry({ name, code, message }) {
625
+ return `${name}${code ? ` [${code}]` : ''}: ${message}`;
626
+ }
627
+
628
+ /** Root cause as "CODE: message" (or just the message when there is no code). */
629
+ function rootCauseDetail(error) {
630
+ const root = errorChain(error).at(-1);
631
+ if (!root) return String(error);
632
+ return root.code ? `${root.code}: ${root.message}` : root.message;
633
+ }
634
+
635
+ /** Map a network failure to plain words a user can act on. */
636
+ export function describeDownloadFailure(error) {
637
+ if (typeof error?.reason === 'string') return error.reason;
638
+ const chain = errorChain(error);
639
+ const codes = new Set(chain.map((entry) => entry.code).filter(Boolean));
640
+ const has = (...candidates) => candidates.some((code) => codes.has(code));
641
+ if (has('UND_ERR_SOCKET', 'ECONNRESET', 'EPIPE', 'UND_ERR_CLOSED', 'ECONNABORTED')) {
642
+ return 'the connection was closed by the server or a proxy';
643
+ }
644
+ if (has('UND_ERR_BODY_TIMEOUT', 'UND_ERR_HEADERS_TIMEOUT', 'UND_ERR_CONNECT_TIMEOUT', 'ETIMEDOUT')) {
645
+ return 'the connection timed out';
646
+ }
647
+ if (has('ENETUNREACH', 'EHOSTUNREACH', 'ENETDOWN', 'EHOSTDOWN')) return 'the network is unreachable';
648
+ if (has('ENOTFOUND', 'EAI_AGAIN')) return 'the server name could not be resolved (DNS lookup failed)';
649
+ if (has('ECONNREFUSED')) return 'the connection was refused';
650
+ if ([...codes].some((code) => TLS_ERROR_CODES.has(code))) {
651
+ return 'the server certificate could not be verified';
652
+ }
653
+ if (chain.some((entry) => entry.message === 'terminated')) return 'the connection was closed unexpectedly';
654
+ return chain.at(-1)?.message ?? String(error);
655
+ }
656
+
657
+ /** Wrap a failure of fetch() or of reading the body as a classified download error. */
658
+ function networkError(error) {
659
+ const codes = errorChain(error).map((entry) => entry.code);
660
+ return downloadError(describeDownloadFailure(error), {
661
+ cause: error,
662
+ reason: describeDownloadFailure(error),
663
+ retryable: !codes.some((code) => code && TLS_ERROR_CODES.has(code)),
519
664
  });
665
+ }
520
666
 
521
- if (!response.ok) {
522
- throw new Error(
523
- `Failed to download c8run ${version}: HTTP ${response.status}\n` +
524
- `URL: ${downloadUrl}\n` +
525
- `Please check the version exists or try a different version.\n\n` +
526
- formatLocalVersionsHint(cacheDir),
667
+ /** Wrap a failure of the file stream: local, so neither retried nor a network problem. */
668
+ function fileSystemError(error) {
669
+ return downloadError(error.message, { cause: error, reason: error.message, retryable: false, fileSystem: true });
670
+ }
671
+
672
+ function isRetryableDownloadError(error) {
673
+ return error?.retryable === true;
674
+ }
675
+
676
+ function parseContentRange(header) {
677
+ const match = /^bytes (\d+)-(\d+)\/(\d+|\*)$/i.exec((header || '').trim());
678
+ if (!match) return null;
679
+ return {
680
+ start: Number(match[1]),
681
+ end: Number(match[2]),
682
+ total: match[3] === '*' ? 0 : Number(match[3]),
683
+ };
684
+ }
685
+
686
+ function fileSizeOrZero(file) {
687
+ try {
688
+ return statSync(file).size;
689
+ } catch {
690
+ return 0;
691
+ }
692
+ }
693
+
694
+ /**
695
+ * Show a URL without credentials: userinfo becomes `***`, and the query
696
+ * (e.g. a signed CDN redirect) and fragment are replaced by `?<redacted>`.
697
+ */
698
+ function redactUrl(value, fallback = '(invalid URL)') {
699
+ try {
700
+ const url = new URL(value);
701
+ if (url.username || url.password) {
702
+ url.username = '***';
703
+ url.password = '';
704
+ }
705
+ const query = url.search || url.hash ? '?<redacted>' : '';
706
+ url.search = '';
707
+ url.hash = '';
708
+ return `${url.toString()}${query}`;
709
+ } catch {
710
+ return fallback;
711
+ }
712
+ }
713
+
714
+ const PROXY_ENV_VARS = ['HTTPS_PROXY', 'https_proxy', 'HTTP_PROXY', 'http_proxy', 'NO_PROXY', 'no_proxy'];
715
+
716
+ function isHttpsProxyConfigured() {
717
+ return Boolean(process.env.HTTPS_PROXY || process.env.https_proxy);
718
+ }
719
+
720
+ function isEnvProxyEnabled() {
721
+ return process.env.NODE_USE_ENV_PROXY === '1';
722
+ }
723
+
724
+ function proxyHint() {
725
+ if (isHttpsProxyConfigured() && !isEnvProxyEnabled()) {
726
+ return (
727
+ 'HTTPS_PROXY is set, but Node.js only uses it when NODE_USE_ENV_PROXY=1 is set as well ' +
728
+ '(Node.js 22.21+ or 24.5+). Set NODE_USE_ENV_PROXY=1 and try again.'
527
729
  );
528
730
  }
731
+ return 'Behind a proxy? Set HTTPS_PROXY together with NODE_USE_ENV_PROXY=1 (Node.js 22.21+ or 24.5+).';
732
+ }
529
733
 
530
- const totalSize = parseInt(response.headers.get('content-length') || '0');
734
+ function mirrorHint() {
735
+ const override = process.env.C8CTL_C8RUN_DOWNLOAD_URL;
736
+ if (override) {
737
+ return (
738
+ `C8CTL_C8RUN_DOWNLOAD_URL points the download at ${redactUrl(override)}. ` +
739
+ 'Make sure that server is reachable, or unset it to use the Camunda Download Center.'
740
+ );
741
+ }
742
+ return 'Use a mirror: set C8CTL_C8RUN_DOWNLOAD_URL to a base URL with the same layout as the Camunda Download Center.';
743
+ }
744
+
745
+ function buildDownloadFailureMessage({
746
+ error,
747
+ url,
748
+ attempts,
749
+ connected,
750
+ maxBytesReceived,
751
+ total,
752
+ targetFile,
753
+ keptFileNote,
754
+ extraHints,
755
+ }) {
756
+ const codes = errorChain(error).map((entry) => entry.code).filter(Boolean);
757
+
758
+ // A local file-system failure has nothing to do with the network.
759
+ if (error?.fileSystem === true) {
760
+ return (
761
+ `Could not save the download to ${targetFile}: ${rootCauseDetail(error)}\n` +
762
+ (keptFileNote ? `${keptFileNote}\n` : '') +
763
+ `URL: ${redactUrl(url)}\n` +
764
+ 'What you can try:\n' +
765
+ ' - Check that there is enough free disk space and that you can write to that directory.\n' +
766
+ ' - Set C8RUN_CACHE_DIR to a different directory to download there instead.'
767
+ );
768
+ }
531
769
 
532
- if (!response.body) {
533
- throw new Error(
534
- `Failed to download c8run ${version}: empty response body\n` +
535
- `URL: ${downloadUrl}\n` +
536
- `Please try again or use a different version.`,
770
+ const reason = describeDownloadFailure(error);
771
+ const detail = rootCauseDetail(error);
772
+ const attemptsText = `${attempts} attempt${attempts === 1 ? '' : 's'}`;
773
+ const lines = [
774
+ connected
775
+ ? `Download failed after ${attemptsText}: ${reason}.`
776
+ : `Cannot reach the Camunda Download Center (${attemptsText}): ${reason}.`,
777
+ ];
778
+ // Our own errors (stall, HTTP status, size mismatch) are fully described by `reason`.
779
+ if (errorChain(error).length > 1 && detail !== reason) lines.push(`Cause: ${detail}`);
780
+ lines.push(`URL: ${redactUrl(url)}`);
781
+ if (maxBytesReceived > 0) {
782
+ lines.push(
783
+ `Received ${formatSize(maxBytesReceived)}${total > 0 ? ` of ${formatSize(total)}` : ''} before giving up` +
784
+ (keptFileNote ? '.' : '; the incomplete download was removed.'),
537
785
  );
538
786
  }
787
+ if (keptFileNote) lines.push(keptFileNote);
788
+ const hints = [
789
+ 'Please check your network connection and VPN, then try again.',
790
+ proxyHint(),
791
+ ...(codes.some((code) => TLS_ERROR_CODES.has(code))
792
+ ? ['If your network inspects HTTPS traffic, point NODE_EXTRA_CA_CERTS at your organization\'s CA certificate file.']
793
+ : []),
794
+ mirrorHint(),
795
+ ...extraHints,
796
+ ];
797
+ lines.push('What you can try:', ...hints.map((hint) => ` - ${hint}`));
798
+ return lines.join('\n');
799
+ }
539
800
 
540
- const etag = response.headers.get('etag') || response.headers.get('last-modified') || null;
541
- // Note: 'etag' values are quoted strings (e.g. '"abc123"') while 'last-modified'
542
- // values are date strings. Both are used as opaque version tokens for equality
543
- // comparison — the format difference does not affect correctness.
801
+ /**
802
+ * Download `url` to `targetFile`, surviving dropped connections.
803
+ *
804
+ * - One initial attempt plus up to `maxRetries` retries, with exponential
805
+ * backoff (`retryDelayMs`, doubled per retry), for transient failures only:
806
+ * network errors, dropped or stalled connections, HTTP 5xx and 429, and an
807
+ * archive whose final size does not match what the server announced.
808
+ * - Resumes with `Range: bytes=<written>-` and `If-Range: <validator>` when
809
+ * the first response carried a strong ETag or a Last-Modified date. A 206
810
+ * answer is appended to the partial file; a 200 answer restarts from zero.
811
+ * - An attempt fails when no bytes arrive for `stallTimeoutMs`.
812
+ * - Other HTTP errors (e.g. 404) are not retried: the thrown error carries
813
+ * `status` so the caller can explain it.
814
+ * - The partial file is kept between retries and deleted when giving up.
815
+ * - With `verbose`, logs request/response details, per-attempt timing,
816
+ * and full error cause chains.
817
+ *
818
+ * Resolves to `{ bytes, etag }`, where `etag` is the ETag (or Last-Modified)
819
+ * of the downloaded content, or null.
820
+ */
821
+ export async function downloadWithRetry({
822
+ url,
823
+ targetFile,
824
+ logger = getLogger(),
825
+ verbose = false,
826
+ maxRetries = DOWNLOAD_MAX_RETRIES,
827
+ retryDelayMs = DOWNLOAD_RETRY_BASE_DELAY_MS,
828
+ stallTimeoutMs = DOWNLOAD_STALL_TIMEOUT_MS,
829
+ progressIntervalMs = PROGRESS_INTERVAL_MS,
830
+ extraHints = [],
831
+ }) {
832
+ const vlog = verbose ? (message) => logger.info(`[verbose] ${message}`, { stream: 'stderr' }) : () => {};
833
+ const invalid = invalidDownloadUrlReason(url);
834
+ if (invalid) {
835
+ throw downloadError(
836
+ `Cannot download from ${redactUrl(url)}: ${invalid}.` +
837
+ (process.env.C8CTL_C8RUN_DOWNLOAD_URL ? ' Check C8CTL_C8RUN_DOWNLOAD_URL.' : ''),
838
+ { reason: invalid, retryable: false },
839
+ );
840
+ }
841
+ const totalAttempts = maxRetries + 1;
842
+ const state = {
843
+ written: 0,
844
+ total: 0,
845
+ validator: null,
846
+ etag: null,
847
+ reportedPercent: 0,
848
+ reportedBytes: 0,
849
+ reportedAt: Date.now(),
850
+ connected: false,
851
+ maxBytesReceived: 0,
852
+ attemptBytes: 0,
853
+ };
544
854
 
545
- const fileStream = createWriteStream(targetFile);
855
+ if (verbose) {
856
+ const proxyVars = PROXY_ENV_VARS.filter((name) => process.env[name]).map((name) =>
857
+ name.toLowerCase() === 'no_proxy' ? `${name}=${process.env[name]}` : `${name}=${redactUrl(process.env[name], '(set)')}`,
858
+ );
859
+ vlog(`Download URL: ${redactUrl(url)}`);
860
+ vlog(`Target file: ${targetFile}`);
861
+ vlog(`Node.js ${process.version}; NODE_USE_ENV_PROXY=${process.env.NODE_USE_ENV_PROXY ?? '(not set)'}`);
862
+ vlog(`Proxy environment: ${proxyVars.length > 0 ? proxyVars.join(', ') : '(none set)'}`);
863
+ vlog(
864
+ `Retry policy: up to ${maxRetries} retries (backoff starting at ${formatDuration(retryDelayMs)}), ` +
865
+ `stall timeout ${formatDuration(stallTimeoutMs)}`,
866
+ );
867
+ }
546
868
 
547
- let downloadedSize = 0;
548
- let lastReportedPercentage = 0;
869
+ let lastError;
870
+ let attempt = 0;
871
+ while (attempt < totalAttempts) {
872
+ attempt += 1;
873
+ const startedAt = Date.now();
874
+ state.attemptBytes = 0;
875
+ vlog(`Attempt ${attempt}/${totalAttempts} started`);
876
+ try {
877
+ await downloadAttempt({ url, targetFile, state, stallTimeoutMs, progressIntervalMs, logger, vlog, startedAt });
878
+ const elapsed = Date.now() - startedAt;
879
+ vlog(
880
+ `Attempt ${attempt}/${totalAttempts} completed after ${formatDuration(elapsed)}: ` +
881
+ `${formatMBPrecise(state.attemptBytes)} received (${formatThroughput(state.attemptBytes, elapsed)}), ` +
882
+ `${formatMBPrecise(state.written)} total`,
883
+ );
884
+ return { bytes: state.written, etag: state.etag };
885
+ } catch (error) {
886
+ lastError = error;
887
+ const elapsed = Date.now() - startedAt;
888
+ vlog(
889
+ `Attempt ${attempt}/${totalAttempts} failed after ${formatDuration(elapsed)}: ` +
890
+ `${formatMBPrecise(state.attemptBytes)} received in this attempt, ${formatMBPrecise(state.written)} on disk`,
891
+ );
892
+ const chain = errorChain(error);
893
+ chain.forEach((entry, index) => vlog(`${index === 0 ? 'Error details' : ' caused by'}: ${formatChainEntry(entry)}`));
894
+
895
+ if (!isRetryableDownloadError(error) || attempt >= totalAttempts) break;
896
+
897
+ const retry = attempt;
898
+ const delay = retryDelayMs * 2 ** (retry - 1);
899
+ const reason = describeDownloadFailure(error);
900
+ const resumable = state.written > 0 && state.validator !== null;
901
+ const next = resumable
902
+ ? `, resuming from ${formatSize(state.written)}...`
903
+ : state.written > 0
904
+ ? ', restarting from the beginning (the server did not send an ETag or Last-Modified header, so the download cannot be resumed safely)...'
905
+ : '...';
906
+ logger.warn(
907
+ state.written > 0
908
+ ? `Download interrupted at ${formatSize(state.written)}${state.total > 0 ? ` / ${formatSize(state.total)}` : ''} (${reason}). ` +
909
+ `Retrying (${retry}/${maxRetries}) in ${formatDuration(delay)}${next}`
910
+ : `Download failed (${reason}). Retrying (${retry}/${maxRetries}) in ${formatDuration(delay)}...`,
911
+ );
912
+ if (!resumable) state.written = 0;
913
+ await sleep(delay);
914
+ }
915
+ }
549
916
 
550
- const reader = response.body.getReader();
917
+ // An unremovable file must not hide why the download failed; the message says
918
+ // it was kept (only if it is really there, e.g. not for ENAMETOOLONG).
919
+ let cleanupError;
920
+ try {
921
+ rmSync(targetFile, { force: true });
922
+ } catch (error) {
923
+ if (existsSync(targetFile)) cleanupError = error;
924
+ }
925
+ const keptFileNote = cleanupError
926
+ ? `The incomplete download could not be removed (${cleanupError.code ?? cleanupError.message}); delete it yourself: ${targetFile}`
927
+ : undefined;
928
+
929
+ if (lastError?.status !== undefined && !isRetryableDownloadError(lastError)) {
930
+ throw Object.assign(lastError, { keptFileNote });
931
+ }
932
+
933
+ throw downloadError(
934
+ buildDownloadFailureMessage({
935
+ error: lastError,
936
+ url,
937
+ attempts: attempt,
938
+ connected: state.connected,
939
+ maxBytesReceived: state.maxBytesReceived,
940
+ total: state.total,
941
+ targetFile,
942
+ keptFileNote,
943
+ extraHints,
944
+ }),
945
+ { cause: lastError, attempts: attempt },
946
+ );
947
+ }
551
948
 
552
- while (true) {
553
- const { done, value } = await reader.read();
554
- if (done) break;
949
+ /** Why fetch() would reject `url` before sending anything, or null if it would not. */
950
+ function invalidDownloadUrlReason(url) {
951
+ let parsed;
952
+ try {
953
+ parsed = new URL(url);
954
+ } catch {
955
+ return 'not a valid URL';
956
+ }
957
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
958
+ return `unsupported protocol ${parsed.protocol} (use http or https)`;
959
+ }
960
+ if (parsed.username || parsed.password) return 'the URL contains credentials, which fetch() does not send';
961
+ return null;
962
+ }
963
+
964
+ /** One HTTP request; updates `state` and throws a classified error on failure. */
965
+ async function downloadAttempt({ url, targetFile, state, stallTimeoutMs, progressIntervalMs, logger, vlog, startedAt }) {
966
+ const controller = new AbortController();
967
+ let stallTimer;
968
+ let stalled = false;
969
+ const armStallTimer = () => {
970
+ clearTimeout(stallTimer);
971
+ stallTimer = setTimeout(() => {
972
+ stalled = true;
973
+ controller.abort();
974
+ }, stallTimeoutMs);
975
+ };
976
+ const disarmStallTimer = () => clearTimeout(stallTimer);
977
+ const classify = (error) => {
978
+ if (stalled) {
979
+ const reason = `no data received for ${formatDuration(stallTimeoutMs)}`;
980
+ return downloadError(reason, { reason, retryable: true });
981
+ }
982
+ return networkError(error);
983
+ };
555
984
 
556
- fileStream.write(value);
557
- downloadedSize += value.length;
985
+ const resume = state.written > 0 && state.validator !== null;
986
+ // fetch() decodes a Content-Encoding transparently, while Content-Length and
987
+ // byte ranges count encoded bytes; ask for the raw bytes so both match the file.
988
+ const headers = {
989
+ 'Accept-Encoding': 'identity',
990
+ ...(resume ? { Range: `bytes=${state.written}-`, 'If-Range': state.validator } : {}),
991
+ };
992
+ vlog(`GET ${redactUrl(url)}`);
993
+ vlog(`Request headers: ${Object.entries(headers).map(([name, value]) => `${name}: ${value}`).join(', ')}`);
558
994
 
559
- if (totalSize > 0) {
560
- const percentage = Math.floor((downloadedSize / totalSize) * 100);
561
- if (percentage >= lastReportedPercentage + 10) {
562
- logger.info(
563
- `Progress: ${percentage}% (${Math.floor(downloadedSize / 1024 / 1024)} MB / ${Math.floor(totalSize / 1024 / 1024)} MB)`,
564
- );
565
- lastReportedPercentage = percentage;
566
- }
995
+ let response;
996
+ armStallTimer();
997
+ try {
998
+ response = await fetch(url, { headers, signal: controller.signal });
999
+ } catch (error) {
1000
+ throw classify(error);
1001
+ } finally {
1002
+ disarmStallTimer();
1003
+ }
1004
+ state.connected = true;
1005
+
1006
+ const header = (name) => response.headers.get(name);
1007
+ vlog(
1008
+ `Response: HTTP ${response.status}${response.statusText ? ` ${response.statusText}` : ''} from ${redactUrl(response.url || url)}` +
1009
+ `${response.redirected ? ' (after redirect)' : ''}`,
1010
+ );
1011
+ vlog(
1012
+ `Response headers: ${['content-length', 'content-range', 'content-encoding', 'etag', 'last-modified', 'accept-ranges']
1013
+ .map((name) => `${name}: ${header(name) ?? '(none)'}`)
1014
+ .join(', ')}`,
1015
+ );
1016
+
1017
+ const discardBody = () => response.body?.cancel().catch(() => {});
1018
+ let append = false;
1019
+ // Where a 206 body must end; the only size check when the total is `*`.
1020
+ let rangeEnd = 0;
1021
+ // A server may encode the body anyway; its sizes and ranges then don't apply.
1022
+ const encoded = !['', 'identity'].includes((header('content-encoding') ?? '').trim().toLowerCase());
1023
+
1024
+ if (response.status === 206) {
1025
+ const range = parseContentRange(header('content-range'));
1026
+ if (!resume || !range || range.start !== state.written || encoded) {
1027
+ await discardBody();
1028
+ state.written = 0;
1029
+ const reason = `the server sent an unexpected byte range (${header('content-range') ?? 'no Content-Range header'})`;
1030
+ throw downloadError(reason, { reason, retryable: true });
567
1031
  }
1032
+ if (range.total > 0) state.total = range.total;
1033
+ rangeEnd = range.end + 1;
1034
+ append = true;
1035
+ } else if (response.ok) {
1036
+ if (resume) {
1037
+ logger.info('The server did not resume the download; restarting from the beginning.');
1038
+ }
1039
+ state.written = 0;
1040
+ state.reportedPercent = 0;
1041
+ state.reportedBytes = 0;
1042
+ state.total = encoded ? 0 : Number.parseInt(header('content-length') || '0', 10) || 0;
1043
+ // Note: 'etag' values are quoted strings (e.g. '"abc123"') while 'last-modified'
1044
+ // values are date strings. Both are used as opaque version tokens for equality
1045
+ // comparison — the format difference does not affect correctness.
1046
+ state.etag = header('etag') || header('last-modified') || null;
1047
+ // If-Range needs a strong validator; a weak ETag (W/"...") must not be used.
1048
+ const strongEtag = header('etag') && !header('etag').startsWith('W/') ? header('etag') : null;
1049
+ state.validator = encoded ? null : strongEtag || header('last-modified') || null;
1050
+ } else {
1051
+ await discardBody();
1052
+ if (response.status === 416 && resume) {
1053
+ state.written = 0;
1054
+ const reason = 'the server rejected the request to resume the download (HTTP 416)';
1055
+ throw downloadError(reason, { status: 416, reason, retryable: true });
1056
+ }
1057
+ const reason = `the server responded with HTTP ${response.status}${response.statusText ? ` ${response.statusText}` : ''}`;
1058
+ throw downloadError(reason, {
1059
+ status: response.status,
1060
+ reason,
1061
+ retryable: response.status >= 500 || response.status === 429,
1062
+ });
568
1063
  }
569
1064
 
570
- await new Promise((resolve, reject) => {
571
- fileStream.on('finish', resolve);
572
- fileStream.on('error', reject);
1065
+ if (!response.body) {
1066
+ const reason = 'the server sent an empty response';
1067
+ throw downloadError(reason, { reason, retryable: true });
1068
+ }
1069
+
1070
+ const fileStream = createWriteStream(targetFile, { flags: append ? 'a' : 'w' });
1071
+ let fileError;
1072
+ fileStream.on('error', (error) => {
1073
+ fileError = error;
1074
+ });
1075
+ const reader = response.body.getReader();
1076
+
1077
+ try {
1078
+ while (true) {
1079
+ let chunk;
1080
+ armStallTimer();
1081
+ try {
1082
+ chunk = await reader.read();
1083
+ } catch (error) {
1084
+ throw classify(error);
1085
+ } finally {
1086
+ disarmStallTimer();
1087
+ }
1088
+ if (chunk.done) break;
1089
+
1090
+ // The stream may have failed while we awaited the read; writing to it then
1091
+ // returns false and 'drain' never comes.
1092
+ if (fileError) throw fileError;
1093
+ if (!fileStream.write(chunk.value)) {
1094
+ await once(fileStream, 'drain');
1095
+ }
1096
+ if (fileError) throw fileError;
1097
+ state.written += chunk.value.length;
1098
+ state.attemptBytes += chunk.value.length;
1099
+ state.maxBytesReceived = Math.max(state.maxBytesReceived, state.written);
1100
+ reportDownloadProgress({ state, logger, startedAt, progressIntervalMs });
1101
+ }
573
1102
  fileStream.end();
1103
+ await finished(fileStream);
1104
+ } catch (error) {
1105
+ disarmStallTimer();
1106
+ await reader.cancel().catch(() => {});
1107
+ if (!fileStream.destroyed) fileStream.end();
1108
+ await finished(fileStream).catch(() => {});
1109
+ // What actually reached the disk is what a resume continues from.
1110
+ state.written = fileSizeOrZero(targetFile);
1111
+ throw fileError ? fileSystemError(fileError) : error;
1112
+ }
1113
+
1114
+ state.written = fileSizeOrZero(targetFile);
1115
+ const expected = state.total > 0 ? state.total : rangeEnd;
1116
+ if (expected > 0 && state.written !== expected) {
1117
+ const reason =
1118
+ state.written < expected
1119
+ ? `the download ended early (received ${formatSize(state.written)} of ${formatSize(expected)})`
1120
+ : `the download is larger than announced (${formatSize(state.written)} instead of ${formatSize(expected)})`;
1121
+ // An oversized file cannot be repaired by resuming; start over.
1122
+ if (state.written > expected) state.written = 0;
1123
+ throw downloadError(reason, { reason, retryable: true });
1124
+ }
1125
+ }
1126
+
1127
+ function reportDownloadProgress({ state, logger, startedAt, progressIntervalMs }) {
1128
+ const now = Date.now();
1129
+ const percentage = state.total > 0 ? Math.floor((state.written / state.total) * 100) : 0;
1130
+ const stepReached = state.total > 0 && percentage >= state.reportedPercent + PROGRESS_STEP_PERCENT;
1131
+ const intervalPassed = now - state.reportedAt >= progressIntervalMs && state.written > state.reportedBytes;
1132
+ if (!stepReached && !intervalPassed) return;
1133
+
1134
+ const elapsed = now - startedAt;
1135
+ const rate = formatThroughput(state.attemptBytes, elapsed);
1136
+ const remaining = state.total - state.written;
1137
+ const eta =
1138
+ state.total > 0 && remaining > 0 && state.attemptBytes > 0 && elapsed > 0
1139
+ ? `, ETA ${formatEta((remaining * elapsed) / state.attemptBytes)}`
1140
+ : '';
1141
+ logger.info(
1142
+ state.total > 0
1143
+ ? `//> ${percentage}% (${formatMBPrecise(state.written)} / ${formatMBPrecise(state.total)}) at ${rate}${eta}`
1144
+ : `//> ${formatMBPrecise(state.written)} (total size unknown) at ${rate}`,
1145
+ );
1146
+ state.reportedPercent = percentage;
1147
+ state.reportedBytes = state.written;
1148
+ state.reportedAt = now;
1149
+ }
1150
+
1151
+ /**
1152
+ * Render an error for a "Failed to ...:" line without losing its cause.
1153
+ * `${error}` alone hides `error.cause`, which is where undici puts the useful
1154
+ * part of a network failure (e.g. "TypeError: terminated" is caused by
1155
+ * "UND_ERR_SOCKET: other side closed").
1156
+ */
1157
+ export function formatErrorWithCause(error) {
1158
+ const base = `${error}`;
1159
+ if (error?.cause === undefined || error?.cause === null) return base;
1160
+ const detail = rootCauseDetail(error);
1161
+ return base.includes(detail) ? base : `${base} (cause: ${detail})`;
1162
+ }
1163
+
1164
+ /** Shell-quote a path for display in a hint when it contains spaces. */
1165
+ /** Quote a path for a copy-paste command: single quotes for POSIX shells, double quotes on Windows. */
1166
+ export function quoteForHint(path, platform = osPlatform()) {
1167
+ if (platform === 'win32') {
1168
+ // Windows paths cannot contain `"`; cmd and PowerShell both accept double quotes.
1169
+ return /^[\w.:\\/-]+$/.test(path) ? path : `"${path}"`;
1170
+ }
1171
+ return /^[\w@%+=:,./-]+$/.test(path) ? path : `'${path.replaceAll("'", "'\\''")}'`;
1172
+ }
1173
+
1174
+ async function downloadC8Run(config) {
1175
+ const logger = getLogger();
1176
+ const version = config.version;
1177
+
1178
+ const downloadUrl = getDownloadUrl(version);
1179
+
1180
+ logger.info(`Downloading Camunda ${version} for ${getPlatformIdentifier().platform}...`);
1181
+
1182
+ const cacheDir = config.cacheDir;
1183
+ mkdirSync(cacheDir, { recursive: true });
1184
+
1185
+ const platformInfo = getPlatformIdentifier();
1186
+ const targetFile = join(
1187
+ cacheDir,
1188
+ `c8run-${version}-${platformInfo.platform}-${platformInfo.arch}.${platformInfo.extension}`,
1189
+ );
1190
+
1191
+ // A manually downloaded and extracted archive in the install dir is picked
1192
+ // up by isC8RunInstalled(), exactly like one c8ctl extracted itself.
1193
+ const installDir = join(cacheDir, `c8run-${version}`);
1194
+ // Not parsed from downloadUrl: a malformed C8CTL_C8RUN_DOWNLOAD_URL must reach
1195
+ // downloadWithRetry()'s validation instead of throwing a bare TypeError here.
1196
+ const archiveName = getArchiveName(version);
1197
+ const extract = resolveExtractCommand({
1198
+ archivePath: archiveName,
1199
+ targetDir: quoteForHint(installDir),
1200
+ platform: osPlatform(),
574
1201
  });
1202
+ const manualHint =
1203
+ `Or download ${archiveName} yourself (e.g. with a browser or a download manager), create ${quoteForHint(installDir)} ` +
1204
+ `and extract it there: ${extract.command} ${extract.args.join(' ')}`;
1205
+
1206
+ let result;
1207
+ try {
1208
+ result = await downloadWithRetry({
1209
+ url: downloadUrl,
1210
+ targetFile,
1211
+ logger,
1212
+ verbose: config.verbose === true,
1213
+ retryDelayMs: msFromEnv('C8CTL_C8RUN_DOWNLOAD_RETRY_DELAY_MS', DOWNLOAD_RETRY_BASE_DELAY_MS),
1214
+ stallTimeoutMs: msFromEnv('C8CTL_C8RUN_DOWNLOAD_STALL_TIMEOUT_MS', DOWNLOAD_STALL_TIMEOUT_MS, {
1215
+ allowZero: false,
1216
+ }),
1217
+ extraHints: [manualHint],
1218
+ });
1219
+ } catch (error) {
1220
+ if (error.status !== undefined && !isRetryableDownloadError(error)) {
1221
+ throw new Error(
1222
+ `Failed to download c8run ${version}: HTTP ${error.status}\n` +
1223
+ `URL: ${redactUrl(downloadUrl)}\n` +
1224
+ (error.keptFileNote ? `${error.keptFileNote}\n` : '') +
1225
+ `Please check the version exists or try a different version.\n\n` +
1226
+ formatLocalVersionsHint(cacheDir),
1227
+ );
1228
+ }
1229
+ throw new Error(`${error.message}\n\n${formatLocalVersionsHint(cacheDir)}`, { cause: error.cause ?? error });
1230
+ }
575
1231
 
576
1232
  logger.info(
577
- `Downloaded and saved to ${targetFile} (${Math.floor(downloadedSize / 1024 / 1024)} MB)`,
1233
+ `Downloaded and saved to ${targetFile} (${formatMB(result.bytes)})`,
578
1234
  );
579
1235
 
580
- return { archivePath: targetFile, etag };
1236
+ return { archivePath: targetFile, etag: result.etag };
581
1237
  }
582
1238
 
583
1239
  async function extractArchive(archivePath, targetDir) {
@@ -758,7 +1414,13 @@ export async function hasNewerVersionAvailable(config) {
758
1414
  const controller = new AbortController();
759
1415
  const timeout = setTimeout(() => controller.abort(), 5_000);
760
1416
  try {
761
- const response = await fetch(downloadUrl, { method: 'HEAD', signal: controller.signal });
1417
+ // Same representation as the download, whose ETag was stored: with
1418
+ // Vary: Accept-Encoding a gzip variant can carry a different ETag.
1419
+ const response = await fetch(downloadUrl, {
1420
+ method: 'HEAD',
1421
+ headers: { 'Accept-Encoding': 'identity' },
1422
+ signal: controller.signal,
1423
+ });
762
1424
  if (!response.ok) {
763
1425
  // Can't determine — keep the current installation
764
1426
  return false;
@@ -934,7 +1596,7 @@ function printSummary(rawOutput, version) {
934
1596
  console.log('');
935
1597
  }
936
1598
 
937
- async function startC8Run(config, debug = false) {
1599
+ async function startC8Run(config, debug = false, startArgs = []) {
938
1600
  const logger = getLogger();
939
1601
  const binaryPath = getC8RunBinaryPath(config);
940
1602
  const logDir = join(dirname(binaryPath), 'log');
@@ -988,9 +1650,10 @@ async function startC8Run(config, debug = false) {
988
1650
 
989
1651
  logger.info('Starting Camunda 8 local cluster...');
990
1652
 
991
- const proc = spawn(binaryPath, ['start'], {
1653
+ const proc = spawn(binaryPath, ['start', ...startArgs], {
992
1654
  stdio: ['ignore', 'pipe', 'pipe'],
993
1655
  cwd: dirname(binaryPath),
1656
+ env: { ...resolveLocalStoreEnv(process.env, process.cwd()), C8RUN_CLI_NAME },
994
1657
  });
995
1658
 
996
1659
  if (typeof proc.pid !== 'number') {
@@ -1034,9 +1697,19 @@ async function startC8Run(config, debug = false) {
1034
1697
  });
1035
1698
 
1036
1699
  if (exitCode !== 0) {
1700
+ // A failed tenant probe leaves healthy engines alive; preserve their identity
1701
+ // for stop/status even if the installation directory is subsequently replaced.
1702
+ try {
1703
+ recordRunningClusterPids(config, { skipEmpty: true });
1704
+ } catch (error) {
1705
+ logger.warn(`Could not record surviving cluster processes: ${formatErrorWithCause(error)}. Use "c8ctl cluster stop" while the installation is still present.`);
1706
+ }
1037
1707
  if (startupOutput.trim()) {
1038
1708
  logger.error(`c8run output:\n${startupOutput.trim()}`);
1039
1709
  }
1710
+ if (startArgs.length > 0 && /flag provided but not defined: -physical-tenants/.test(startupOutput)) {
1711
+ logger.error('This cached c8run build lacks --physical-tenants. Install a Camunda 8.10+ build containing physical-tenant CLI support with "c8ctl cluster install 8.10".');
1712
+ }
1040
1713
  logger.error(
1041
1714
  `c8run start exited with code ${exitCode ?? 'unknown'}${exitSignal ? ` (signal: ${exitSignal})` : ''}. Cluster will not be marked as running.`,
1042
1715
  );
@@ -1423,7 +2096,7 @@ export function liveRecordedPids(cacheDir) {
1423
2096
  * with a start signature so a later stop/status can tell the recorded process
1424
2097
  * apart from an unrelated one that reused its PID.
1425
2098
  */
1426
- export function recordRunningClusterPids(config, { signatureOf = processStartSignature } = {}) {
2099
+ export function recordRunningClusterPids(config, { signatureOf = processStartSignature, skipEmpty = false } = {}) {
1427
2100
  const canFingerprint = platformSupportsProcessSignature();
1428
2101
  const pids = [];
1429
2102
  const signatures = {};
@@ -1451,7 +2124,9 @@ export function recordRunningClusterPids(config, { signatureOf = processStartSig
1451
2124
  pids.push(pid);
1452
2125
  }
1453
2126
  }
2127
+ if (skipEmpty && pids.length === 0) return 0;
1454
2128
  writeRunningClusterRecord(config.cacheDir, { version: config.version, pids, signatures });
2129
+ return pids.length;
1455
2130
  }
1456
2131
 
1457
2132
  /**
@@ -1818,13 +2493,15 @@ export async function stopC8Run(config, debug = false) {
1818
2493
  * `--yes` / `-y` are c8ctl GLOBAL flags, so the host consumes them (it sets
1819
2494
  * `ctx.yes`) and strips them from a passthrough command's args. c8run's own
1820
2495
  * `secrets delete` has a `--yes` flag that skips its confirmation prompt, so
1821
- * restore it when the user asked for it. Scoped to `delete` — the only verb
1822
- * documented to take it — so it is never appended to a c8run verb that may
1823
- * not accept the flag. Never mutates `tail`.
2496
+ * restore it when the user asked for it. Tenant removal/reset also require
2497
+ * confirmation. Skip tenant selectors when locating a secrets verb, and never
2498
+ * append confirmation to a verb that does not accept it. Never mutates `tail`.
1824
2499
  */
1825
- export function withForwardedYes(tail, ctx) {
1826
- const verbIndex = tail[0]?.startsWith('--c8-version=') ? 1 : tail[0] === '--c8-version' ? 2 : 0;
1827
- if (ctx?.yes !== true || tail[verbIndex] !== 'delete') return tail;
2500
+ export function withForwardedYes(tail, ctx, command = 'secrets') {
2501
+ const versionEnd = tail[0]?.startsWith('--c8-version=') ? 1 : tail[0] === '--c8-version' ? 2 : 0;
2502
+ const positions = forwardedPositionals(tail, versionEnd, command === 'secrets');
2503
+ const verbs = command === 'tenants' ? ['remove', 'rm', 'reset'] : ['delete'];
2504
+ if (ctx?.yes !== true || !verbs.includes(tail[positions[0]])) return tail;
1828
2505
  // Everything after a `--` terminator is literal for c8run, so the flag goes
1829
2506
  // immediately before it, and a `--yes` that only appears after it does not count.
1830
2507
  const terminator = tail.indexOf('--');
@@ -1847,7 +2524,7 @@ export function withForwardedYes(tail, ctx) {
1847
2524
  * unreleased c8run's verb set (including one c8ctl has never heard of) is
1848
2525
  * still forwarded and its own error surfaces as-is.
1849
2526
  */
1850
- export function parseSecretsArgs(tail) {
2527
+ export function parseSecretsArgs(tail, command = 'secrets') {
1851
2528
  let version = null;
1852
2529
  let passthrough = tail;
1853
2530
 
@@ -1863,14 +2540,14 @@ export function parseSecretsArgs(tail) {
1863
2540
  }
1864
2541
  if (!version || version.startsWith('-')) {
1865
2542
  throw new Error(
1866
- 'Missing value for --c8-version. Example: c8ctl cluster secrets --c8-version 8.10 list',
2543
+ `Missing value for --c8-version. Example: c8ctl cluster ${command} --c8-version 8.10 list`,
1867
2544
  );
1868
2545
  }
1869
2546
  }
1870
2547
 
1871
2548
  if (passthrough.length === 0) {
1872
2549
  throw new Error(
1873
- 'usage: c8ctl cluster secrets [--c8-version <version>] <set|list|path|delete|import|...>',
2550
+ `usage: c8ctl cluster ${command} [--c8-version <version>] <${command === 'tenants' ? 'add|list|remove|reset|path|help|...' : 'set|list|path|delete|import|...'}>`,
1874
2551
  );
1875
2552
  }
1876
2553
 
@@ -1884,30 +2561,55 @@ export function parseSecretsArgs(tail) {
1884
2561
  * C8RUN_SECRETS_DIR would otherwise resolve against the wrong directory and
1885
2562
  * silently miss the file the user meant.
1886
2563
  *
1887
- * Only touches an `import` positional and C8RUN_SECRETS_DIR; every other
2564
+ * Only touches an `import` positional and the local store environment paths; every other
1888
2565
  * verb and flag passes through untouched. "-" (stdin) and already-absolute
1889
2566
  * paths are left alone. Never mutates the passthrough array or env object
1890
2567
  * it receives.
1891
2568
  */
1892
2569
  export function resolveSecretsPaths(passthrough, { cwd = process.cwd(), env = process.env } = {}) {
1893
2570
  let resolvedPassthrough = passthrough;
2571
+ const positions = forwardedPositionals(passthrough, 0, true);
2572
+ const [verbIndex, fileIndex] = positions;
1894
2573
  if (
1895
- passthrough[0] === 'import' &&
1896
- passthrough[1] &&
1897
- passthrough[1] !== '-' &&
1898
- !isAbsolute(passthrough[1])
2574
+ passthrough[verbIndex] === 'import' &&
2575
+ passthrough[fileIndex] &&
2576
+ passthrough[fileIndex] !== '-' &&
2577
+ !isAbsolute(passthrough[fileIndex])
1899
2578
  ) {
1900
2579
  resolvedPassthrough = [...passthrough];
1901
- resolvedPassthrough[1] = resolve(cwd, passthrough[1]);
2580
+ resolvedPassthrough[fileIndex] = resolve(cwd, passthrough[fileIndex]);
1902
2581
  }
1903
2582
 
1904
- let resolvedEnv = env;
1905
- const secretsDir = env.C8RUN_SECRETS_DIR;
1906
- if (secretsDir && !isAbsolute(secretsDir)) {
1907
- resolvedEnv = { ...env, C8RUN_SECRETS_DIR: resolve(cwd, secretsDir) };
2583
+ return { passthrough: resolvedPassthrough, env: resolveLocalStoreEnv(env, cwd) };
2584
+ }
2585
+
2586
+ function forwardedPositionals(args, start, tenantScoped) {
2587
+ const positions = [];
2588
+ for (let i = start; i < args.length; i++) {
2589
+ if (args[i] === '--') break;
2590
+ if (tenantScoped && args[i] === '--tenant') {
2591
+ i++;
2592
+ continue;
2593
+ }
2594
+ if (tenantScoped && args[i].startsWith('--tenant=')) continue;
2595
+ // Unknown options belong to c8run. Do not guess which tokens they consume.
2596
+ positions.push(i);
1908
2597
  }
2598
+ return positions;
2599
+ }
2600
+
2601
+ // Tells c8run which command prefix to print in its hints ("c8ctl cluster tenants list"
2602
+ // instead of "c8run tenants list"); c8run builds without support ignore it.
2603
+ const C8RUN_CLI_NAME = 'c8ctl cluster';
1909
2604
 
1910
- return { passthrough: resolvedPassthrough, env: resolvedEnv };
2605
+ function resolveLocalStoreEnv(env, cwd) {
2606
+ let resolvedEnv = env;
2607
+ for (const name of ['C8RUN_SECRETS_DIR', 'C8RUN_TENANTS_FILE']) {
2608
+ if (env[name] && !isAbsolute(env[name])) {
2609
+ resolvedEnv = { ...resolvedEnv, [name]: resolve(cwd, env[name]) };
2610
+ }
2611
+ }
2612
+ return resolvedEnv;
1911
2613
  }
1912
2614
 
1913
2615
  /**
@@ -1980,6 +2682,15 @@ export function mapSecretsFailure(exitCode, stderrTail, version) {
1980
2682
  * environment).
1981
2683
  */
1982
2684
  export async function runClusterSecrets(
2685
+ cacheDir,
2686
+ tail,
2687
+ options = {},
2688
+ ) {
2689
+ return runClusterLocalCommand('secrets', cacheDir, tail, options);
2690
+ }
2691
+
2692
+ async function runClusterLocalCommand(
2693
+ command,
1983
2694
  cacheDir,
1984
2695
  tail,
1985
2696
  { explicitVersion, spawnFn = spawn, cwd = process.cwd(), env = process.env } = {},
@@ -1989,7 +2700,7 @@ export async function runClusterSecrets(
1989
2700
  const version = await selectSecretsVersion(cacheDir, { explicit: explicitVersion });
1990
2701
  if (!version) {
1991
2702
  logger.error(
1992
- 'No c8run installed locally. Install one first: c8ctl cluster install alpha',
2703
+ `No c8run installed locally. Install one first: c8ctl cluster install ${command === 'tenants' ? '8.10' : 'alpha'}`,
1993
2704
  );
1994
2705
  process.exit(1);
1995
2706
  return;
@@ -1999,18 +2710,20 @@ export async function runClusterSecrets(
1999
2710
  try {
2000
2711
  binaryPath = getC8RunBinaryPath({ cacheDir, version });
2001
2712
  } catch (error) {
2002
- logger.error(`Failed to run secrets command: ${error.message}`);
2713
+ logger.error(`Failed to run ${command} command: ${error.message}`);
2003
2714
  process.exit(1);
2004
2715
  return;
2005
2716
  }
2006
2717
 
2007
- const { passthrough, env: resolvedEnv } = resolveSecretsPaths(tail, { cwd, env });
2718
+ const { passthrough, env: resolvedEnv } = command === 'secrets'
2719
+ ? resolveSecretsPaths(tail, { cwd, env })
2720
+ : { passthrough: tail, env: resolveLocalStoreEnv(env, cwd) };
2008
2721
 
2009
2722
  const exitCode = await new Promise((resolvePromise, reject) => {
2010
- const proc = spawnFn(binaryPath, ['secrets', ...passthrough], {
2723
+ const proc = spawnFn(binaryPath, [command, ...passthrough], {
2011
2724
  stdio: ['inherit', 'inherit', 'pipe'],
2012
2725
  cwd: dirname(binaryPath),
2013
- env: resolvedEnv,
2726
+ env: { ...resolvedEnv, C8RUN_CLI_NAME },
2014
2727
  });
2015
2728
 
2016
2729
  let stderrTail = '';
@@ -2024,7 +2737,11 @@ export async function runClusterSecrets(
2024
2737
  reject(new Error(`Failed to spawn c8run: ${err.message}`));
2025
2738
  });
2026
2739
  proc.on('close', (code) => {
2027
- const hint = mapSecretsFailure(code ?? 1, stderrTail, version);
2740
+ const hint = command === 'secrets'
2741
+ ? mapSecretsFailure(code ?? 1, stderrTail, version)
2742
+ : code !== 0 && /unsupported operation:\s*tenants/i.test(stderrTail)
2743
+ ? `c8run ${version} does not support "tenants" yet. Install a Camunda 8.10+ c8run build containing physical-tenant CLI support with "c8ctl cluster install 8.10"; older cached builds may predate this feature.`
2744
+ : null;
2028
2745
  if (hint) {
2029
2746
  logger.error(hint);
2030
2747
  }
@@ -2512,6 +3229,16 @@ export function parsePluginArgs(args) {
2512
3229
  while (i < args.length) {
2513
3230
  const arg = args[i];
2514
3231
 
3232
+ if (arg === '--physical-tenants' || arg.startsWith('--physical-tenants=')) {
3233
+ const value = arg === '--physical-tenants' ? args[i + 1] : arg.slice('--physical-tenants='.length);
3234
+ if (!value || value.startsWith('-')) throw new Error('--physical-tenants requires comma-separated tenant IDs');
3235
+ result.startArgs ??= [];
3236
+ result.startArgs.push(arg);
3237
+ if (arg === '--physical-tenants') { result.startArgs.push(value); i++; }
3238
+ i++;
3239
+ continue;
3240
+ }
3241
+
2515
3242
  if (arg === '--c8-version') {
2516
3243
  const next = args[i + 1];
2517
3244
  if (!next || next.startsWith('-')) {
@@ -2564,6 +3291,9 @@ export function parsePluginArgs(args) {
2564
3291
  i += 1;
2565
3292
  }
2566
3293
 
3294
+ if (result.startArgs && result.subcommand !== 'start') {
3295
+ throw new Error('--physical-tenants can only be used with the start subcommand');
3296
+ }
2567
3297
  return result;
2568
3298
  }
2569
3299
 
@@ -2580,20 +3310,32 @@ export const commands = {
2580
3310
  'cluster': async (args, _flags, ctx) => {
2581
3311
  const logger = getLogger();
2582
3312
 
2583
- // Secrets passthrough (#314) is intercepted before parsePluginArgs:
3313
+ // Local management passthrough is intercepted before parsePluginArgs:
2584
3314
  // its arguments (verbs, flags, positionals) belong to c8run, not to
2585
3315
  // c8ctl's own version/--debug/--purge parsing.
2586
- if (args[0] === 'secrets') {
2587
- let parsedSecrets;
3316
+ if (args[0] === 'secrets' || args[0] === 'tenants') {
3317
+ const command = args[0];
3318
+ let parsedLocal;
2588
3319
  try {
2589
- parsedSecrets = parseSecretsArgs(withForwardedYes(args.slice(1), ctx));
3320
+ parsedLocal = parseSecretsArgs(withForwardedYes(args.slice(1), ctx, command), command);
2590
3321
  } catch (error) {
2591
3322
  logger.error(error.message);
2592
3323
  process.exit(1);
2593
3324
  return;
2594
3325
  }
2595
- await runClusterSecrets(getCacheDir(), parsedSecrets.passthrough, {
2596
- explicitVersion: parsedSecrets.version,
3326
+ if (ctx?.dryRun) {
3327
+ // Local-only lookup (no download) so the preview shows the c8run that would run.
3328
+ let version = null;
3329
+ try {
3330
+ version = await selectSecretsVersion(getCacheDir(), { explicit: parsedLocal.version });
3331
+ } catch {
3332
+ version = parsedLocal.version;
3333
+ }
3334
+ console.log(JSON.stringify({ dryRun: true, command: `cluster ${command}`, version, args: parsedLocal.passthrough }));
3335
+ return;
3336
+ }
3337
+ await runClusterLocalCommand(command, getCacheDir(), parsedLocal.passthrough, {
3338
+ explicitVersion: parsedLocal.version,
2597
3339
  });
2598
3340
  return;
2599
3341
  }
@@ -2619,6 +3361,7 @@ export const commands = {
2619
3361
  console.log(' c8ctl cluster delete <version>');
2620
3362
  console.log(' c8ctl cluster purge <version>');
2621
3363
  console.log(' c8ctl cluster secrets [--c8-version <version>] <set|list|path|delete|import|...>');
3364
+ console.log(' c8ctl cluster tenants [--c8-version <version>] <add|list|remove|reset|path|help>');
2622
3365
  console.log('');
2623
3366
  console.log('Subcommands:');
2624
3367
  console.log(' start Download (if needed) and start a local Camunda 8 cluster');
@@ -2631,12 +3374,14 @@ export const commands = {
2631
3374
  console.log(' delete Remove a locally cached version to reclaim disk space');
2632
3375
  console.log(' purge Delete runtime data for a version (binary stays intact, next start is fresh)');
2633
3376
  console.log(' secrets Manage local development secrets (forwarded verbatim to c8run)');
3377
+ console.log(' tenants Manage local physical tenants (Camunda 8.10+; forwarded to c8run)');
2634
3378
  console.log('');
2635
3379
  console.log('Options:');
2636
3380
  console.log(' <version> Camunda version, alias, or major.minor (default: stable)');
2637
3381
  console.log(' --c8-version <version> Alternative flag form for version');
2638
3382
  console.log(' --debug Stream raw c8run output during start');
2639
3383
  console.log(' --purge (stop only) also delete runtime data after stopping');
3384
+ console.log(' --physical-tenants <ids> (start only) Extra physical tenants for this run; repeatable');
2640
3385
  console.log('');
2641
3386
  console.log('A <version> can be:');
2642
3387
  console.log(' stable / alpha Named aliases');
@@ -2669,6 +3414,9 @@ export const commands = {
2669
3414
  console.log(' c8ctl cluster secrets list');
2670
3415
  console.log(' c8ctl cluster secrets import .env.secrets');
2671
3416
  console.log(' c8ctl cluster secrets delete OPENAI_API_KEY --yes');
3417
+ console.log(' c8ctl cluster tenants --c8-version 8.10 add sales');
3418
+ console.log(' c8ctl cluster start 8.10 --physical-tenants sales,hr');
3419
+ console.log(' c8ctl cluster secrets --tenant sales set OPENAI_API_KEY');
2672
3420
  console.log('');
2673
3421
  console.log('secrets forwards everything after it to c8run\'s own "secrets" command —');
2674
3422
  console.log('c8ctl never sees or stores a secret value. Run "c8ctl cluster secrets help"');
@@ -2770,6 +3518,14 @@ export const commands = {
2770
3518
  preferLocal: isStart,
2771
3519
  cacheDir: theCacheDir,
2772
3520
  });
3521
+
3522
+ // Dry-run start: report the version a real start would select (same
3523
+ // local-preferred resolution), but skip install and launch.
3524
+ if (ctx?.dryRun && isStart) {
3525
+ console.log(JSON.stringify({ dryRun: true, command: 'cluster start', version, requestedVersion: versionSpec, args: ['start', ...(parsed.startArgs || [])] }));
3526
+ return;
3527
+ }
3528
+
2773
3529
  if (isVersionAlias(versionSpec)) {
2774
3530
  logger.info(`Resolved alias "${versionSpec}" → ${version}`);
2775
3531
  }
@@ -2788,14 +3544,16 @@ export const commands = {
2788
3544
  checkForUpdates: parsed.subcommand === 'install' && rolling,
2789
3545
  // start: soft hint about available updates for rolling versions (non-blocking)
2790
3546
  checkForUpdateHint: parsed.subcommand === 'start' && rolling,
3547
+ // --verbose: detailed HTTP diagnostics for the c8run download
3548
+ verbose: ctx?.verbose === true,
2791
3549
  };
2792
3550
 
2793
3551
  if (parsed.subcommand === 'start') {
2794
3552
  try {
2795
3553
  await ensureC8RunInstalled(config);
2796
- await startC8Run(config, parsed.debug);
3554
+ await startC8Run(config, parsed.debug, parsed.startArgs);
2797
3555
  } catch (error) {
2798
- logger.error(`Failed to start cluster: ${error}`);
3556
+ logger.error(`Failed to start cluster: ${formatErrorWithCause(error)}`);
2799
3557
  process.exit(1);
2800
3558
  }
2801
3559
  } else if (parsed.subcommand === 'stop') {
@@ -2838,7 +3596,7 @@ export const commands = {
2838
3596
  await ensureC8RunInstalled(config);
2839
3597
  logger.info(`Version ${version} is ready. Start it with: c8ctl cluster start ${parsed.version || ''}`);
2840
3598
  } catch (error) {
2841
- logger.error(`Failed to install version: ${error}`);
3599
+ logger.error(`Failed to install version: ${formatErrorWithCause(error)}`);
2842
3600
  process.exit(1);
2843
3601
  }
2844
3602
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@camunda8/cli",
3
- "version": "4.3.0-alpha.1",
3
+ "version": "4.3.0-alpha.3",
4
4
  "description": "Camunda 8 CLI - minimal-dependency CLI for Camunda 8 operations",
5
5
  "type": "module",
6
6
  "engines": {