@cotal-ai/cli 0.175.0 → 0.175.2
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/command.d.ts.map +1 -1
- package/dist/command.js +27 -20
- package/dist/command.js.map +1 -1
- package/dist/commands/agents.d.ts +1 -1
- package/dist/commands/agents.d.ts.map +1 -1
- package/dist/commands/agents.js +25 -14
- package/dist/commands/agents.js.map +1 -1
- package/dist/commands/backup-read.d.ts.map +1 -1
- package/dist/commands/backup-read.js +15 -11
- package/dist/commands/backup-read.js.map +1 -1
- package/dist/commands/backup.d.ts.map +1 -1
- package/dist/commands/backup.js +8 -2
- package/dist/commands/backup.js.map +1 -1
- package/dist/commands/clean.d.ts.map +1 -1
- package/dist/commands/clean.js +8 -3
- package/dist/commands/clean.js.map +1 -1
- package/dist/commands/config.d.ts.map +1 -1
- package/dist/commands/config.js +3 -3
- package/dist/commands/config.js.map +1 -1
- package/dist/commands/doctor.d.ts.map +1 -1
- package/dist/commands/doctor.js +3 -1
- package/dist/commands/doctor.js.map +1 -1
- package/dist/commands/down.d.ts.map +1 -1
- package/dist/commands/down.js +16 -9
- package/dist/commands/down.js.map +1 -1
- package/dist/commands/endpoint-authoring.d.ts.map +1 -1
- package/dist/commands/endpoint-authoring.js +15 -5
- package/dist/commands/endpoint-authoring.js.map +1 -1
- package/dist/commands/endpoint.d.ts.map +1 -1
- package/dist/commands/endpoint.js +2 -0
- package/dist/commands/endpoint.js.map +1 -1
- package/dist/commands/help.js +1 -1
- package/dist/commands/help.js.map +1 -1
- package/dist/commands/history-clear.d.ts.map +1 -1
- package/dist/commands/history-clear.js +14 -3
- package/dist/commands/history-clear.js.map +1 -1
- package/dist/commands/models.d.ts.map +1 -1
- package/dist/commands/models.js +9 -10
- package/dist/commands/models.js.map +1 -1
- package/dist/commands/personas.d.ts.map +1 -1
- package/dist/commands/personas.js +10 -3
- package/dist/commands/personas.js.map +1 -1
- package/dist/commands/removed-start.d.ts +4 -0
- package/dist/commands/removed-start.d.ts.map +1 -0
- package/dist/commands/removed-start.js +68 -0
- package/dist/commands/removed-start.js.map +1 -0
- package/dist/commands/revoke-credential.d.ts.map +1 -1
- package/dist/commands/revoke-credential.js +9 -6
- package/dist/commands/revoke-credential.js.map +1 -1
- package/dist/commands/service-actions.d.ts.map +1 -1
- package/dist/commands/service-actions.js +4 -2
- package/dist/commands/service-actions.js.map +1 -1
- package/dist/commands/service-registry.d.ts.map +1 -1
- package/dist/commands/service-registry.js +21 -3
- package/dist/commands/service-registry.js.map +1 -1
- package/dist/commands/space-delete.d.ts.map +1 -1
- package/dist/commands/space-delete.js +4 -3
- package/dist/commands/space-delete.js.map +1 -1
- package/dist/commands/space-registration.d.ts +2 -0
- package/dist/commands/space-registration.d.ts.map +1 -1
- package/dist/commands/space-registration.js +15 -8
- package/dist/commands/space-registration.js.map +1 -1
- package/dist/commands/space.d.ts +1 -1
- package/dist/commands/space.d.ts.map +1 -1
- package/dist/commands/space.js +7 -4
- package/dist/commands/space.js.map +1 -1
- package/dist/commands/spawn-flags.d.ts +2 -0
- package/dist/commands/spawn-flags.d.ts.map +1 -1
- package/dist/commands/spawn-flags.js +1 -1
- package/dist/commands/spawn-flags.js.map +1 -1
- package/dist/commands/spawn-preview.js +1 -1
- package/dist/commands/spawn-preview.js.map +1 -1
- package/dist/commands/spawn.js +1 -1
- package/dist/commands/spawn.js.map +1 -1
- package/dist/commands/stack-down.d.ts +3 -1
- package/dist/commands/stack-down.d.ts.map +1 -1
- package/dist/commands/stack-down.js +56 -6
- package/dist/commands/stack-down.js.map +1 -1
- package/dist/commands/stack-up.d.ts +9 -9
- package/dist/commands/stack-up.d.ts.map +1 -1
- package/dist/commands/stack-up.js +23 -31
- package/dist/commands/stack-up.js.map +1 -1
- package/dist/commands/status-health.d.ts +2 -2
- package/dist/commands/status-health.d.ts.map +1 -1
- package/dist/commands/status-health.js +19 -2
- package/dist/commands/status-health.js.map +1 -1
- package/dist/commands/status-meshes.js +3 -3
- package/dist/commands/status-meshes.js.map +1 -1
- package/dist/commands/status.js +1 -1
- package/dist/commands/status.js.map +1 -1
- package/dist/commands/team-agent-apply.d.ts.map +1 -1
- package/dist/commands/team-agent-apply.js +5 -4
- package/dist/commands/team-agent-apply.js.map +1 -1
- package/dist/commands/team-deploy-apply.d.ts.map +1 -1
- package/dist/commands/team-deploy-apply.js +9 -3
- package/dist/commands/team-deploy-apply.js.map +1 -1
- package/dist/commands/team.js +2 -2
- package/dist/commands/team.js.map +1 -1
- package/dist/commands/up-args.d.ts +65 -0
- package/dist/commands/up-args.d.ts.map +1 -0
- package/dist/commands/up-args.js +541 -0
- package/dist/commands/up-args.js.map +1 -0
- package/dist/commands/up-detach.d.ts +373 -0
- package/dist/commands/up-detach.d.ts.map +1 -0
- package/dist/commands/up-detach.js +819 -0
- package/dist/commands/up-detach.js.map +1 -0
- package/dist/commands/up-manifest.d.ts +109 -0
- package/dist/commands/up-manifest.d.ts.map +1 -0
- package/dist/commands/up-manifest.js +549 -0
- package/dist/commands/up-manifest.js.map +1 -0
- package/dist/commands/up-stores.d.ts +2 -2
- package/dist/commands/up-stores.d.ts.map +1 -1
- package/dist/commands/up-stores.js +5 -5
- package/dist/commands/up-stores.js.map +1 -1
- package/dist/commands/up.d.ts +7 -245
- package/dist/commands/up.d.ts.map +1 -1
- package/dist/commands/up.js +39 -1882
- package/dist/commands/up.js.map +1 -1
- package/dist/commands/update-release.d.ts +2 -4
- package/dist/commands/update-release.d.ts.map +1 -1
- package/dist/commands/update-release.js +30 -12
- package/dist/commands/update-release.js.map +1 -1
- package/dist/commands/update.d.ts +3 -3
- package/dist/commands/update.d.ts.map +1 -1
- package/dist/commands/update.js +29 -25
- package/dist/commands/update.js.map +1 -1
- package/dist/help.d.ts +1 -1
- package/dist/help.d.ts.map +1 -1
- package/dist/help.js +6 -2
- package/dist/help.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -9
- package/dist/index.js.map +1 -1
- package/dist/lib/backup-artifact.d.ts +2 -2
- package/dist/lib/backup-artifact.d.ts.map +1 -1
- package/dist/lib/backup-artifact.js +39 -14
- package/dist/lib/backup-artifact.js.map +1 -1
- package/dist/lib/broker-service.d.ts +2 -0
- package/dist/lib/broker-service.d.ts.map +1 -1
- package/dist/lib/broker-service.js +13 -0
- package/dist/lib/broker-service.js.map +1 -1
- package/dist/lib/confirmation-required.d.ts.map +1 -1
- package/dist/lib/confirmation-required.js +7 -1
- package/dist/lib/confirmation-required.js.map +1 -1
- package/dist/lib/credential-authority.d.ts.map +1 -1
- package/dist/lib/credential-authority.js +13 -1
- package/dist/lib/credential-authority.js.map +1 -1
- package/dist/lib/foreground-hold.d.ts +2 -1
- package/dist/lib/foreground-hold.d.ts.map +1 -1
- package/dist/lib/foreground-hold.js +25 -7
- package/dist/lib/foreground-hold.js.map +1 -1
- package/dist/lib/nearest-word.d.ts +3 -4
- package/dist/lib/nearest-word.d.ts.map +1 -1
- package/dist/lib/nearest-word.js +9 -5
- package/dist/lib/nearest-word.js.map +1 -1
- package/dist/lib/persona-files.d.ts +1 -1
- package/dist/lib/persona-files.d.ts.map +1 -1
- package/dist/lib/persona-files.js +23 -5
- package/dist/lib/persona-files.js.map +1 -1
- package/dist/lib/service-preset-target.d.ts +3 -2
- package/dist/lib/service-preset-target.d.ts.map +1 -1
- package/dist/lib/service-preset-target.js +8 -3
- package/dist/lib/service-preset-target.js.map +1 -1
- package/dist/lib/service-presets.d.ts.map +1 -1
- package/dist/lib/service-presets.js +17 -9
- package/dist/lib/service-presets.js.map +1 -1
- package/dist/lib/service-process.d.ts +2 -2
- package/dist/lib/service-process.d.ts.map +1 -1
- package/dist/lib/service-process.js +7 -4
- package/dist/lib/service-process.js.map +1 -1
- package/dist/lib/spawn-defaults.d.ts +2 -2
- package/dist/lib/spawn-defaults.d.ts.map +1 -1
- package/dist/lib/spawn-defaults.js +3 -3
- package/dist/lib/spawn-defaults.js.map +1 -1
- package/dist/lib/stack-journal.d.ts +2 -2
- package/dist/lib/stack-journal.d.ts.map +1 -1
- package/dist/lib/stack-journal.js +9 -5
- package/dist/lib/stack-journal.js.map +1 -1
- package/dist/lib/store-dir.js +1 -1
- package/dist/lib/store-dir.js.map +1 -1
- package/dist/lib/team-deploy-inspection.d.ts +3 -1
- package/dist/lib/team-deploy-inspection.d.ts.map +1 -1
- package/dist/lib/team-deploy-inspection.js +23 -2
- package/dist/lib/team-deploy-inspection.js.map +1 -1
- package/package.json +4 -4
package/dist/commands/up.js
CHANGED
|
@@ -1,80 +1,67 @@
|
|
|
1
1
|
import { noManagerCredentialWarning } from "../lib/daemon-credential-warning.js";
|
|
2
2
|
import { drainAndClose } from "@cotal-ai/core";
|
|
3
|
-
import {} from "node:child_process";
|
|
4
3
|
import { openBrokerLog, prepareForegroundBrokerLog } from "../lib/broker-log.js";
|
|
5
4
|
import { spawnBroker } from "../lib/broker-spawn.js";
|
|
6
5
|
import { randomUUID } from "node:crypto";
|
|
7
|
-
import { createConnection
|
|
6
|
+
import { createConnection } from "node:net";
|
|
8
7
|
import { homedir, hostname } from "node:os";
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import { isReachable, dialerFor, DEFAULT_SERVER,
|
|
12
|
-
import { assertManagerName, processStopped, readManagerName, readManagerSeatCap, DEFAULT_SEAT_CAP, recordManagerName, parseSeatCapFlag, seatCapText, CommandFailure, codeSpan,
|
|
8
|
+
import { mkdirSync, readFileSync, existsSync, lstatSync, realpathSync, readdirSync, rmdirSync, } from "node:fs";
|
|
9
|
+
import { join, resolve } from "node:path";
|
|
10
|
+
import { isReachable, dialerFor, DEFAULT_SERVER, CONTRACT_ARTIFACT_MAX_BYTES, MANAGER_START_PAYLOAD_FLOOR, mintCreds, mintLifecycleUid, DEV_OWNER, newIdentity, reconcileSpaceMemoryBuckets, standaloneConnectOpts, LEASE_TTL_MS, } from "@cotal-ai/core";
|
|
11
|
+
import { assertManagerName, processStopped, readManagerName, readManagerSeatCap, DEFAULT_SEAT_CAP, recordManagerName, parseSeatCapFlag, seatCapText, CommandFailure, codeSpan, failureEnvelope, writeEnvelope, isCommandFailure, protectedLocalDirectory, jsonFlag, plainFlag, renderReport, assertSingleSpaceBroker, authDir, getSoleSpaceAuth, getSpaceAuth, listSpaceAccounts, brokerAddressKey, canonicalRoot, clearCurrent, findMesh, legacyStackOtherHome, stackHomeRemedy, getCurrent, loadMeshes, localMeshesForRoot, keepsRegistration, presentationOf, writeResult, parsePositiveIntegerFlag, retainedLegacyBroker, removeMesh, userAuthStateDir, workspaceSecretStore, acquireMaintenanceLock, assertStoreIdentity, assessMaintenanceClaim, assessRestoreClaim, beginOrdinaryResume, bindOrdinaryResumeListener, consumeRetiredMaintenance, markOrdinaryResumeActive, markOrdinaryResumeDegraded, replaceDeadOrdinaryResumeListener, localProcessOwnerStatus, readMaintenanceJournal, readMaintenanceResumeDocument, readStoreIdentity, recordOrdinaryResumeManagerCommit, releaseMaintenanceLock, retireOrdinaryResume, settleTokenHandoff, sweepTokenHandoff, writeTokenHandoff, sameStoreIdentity, cutController, readBrokerPolicy, removePidPair, verifyIdentityPin, processesNaming, connectUserControlOrThrow, userViewAuth, recordOperationSpace, recordOperationWarning, restoreLeftOut, NATS_PIDFILE, exitCode, terminalWidth, } from "@cotal-ai/workspace";
|
|
13
12
|
import { FlagValueRefusal } from "../lib/flag-value-refusal.js";
|
|
14
|
-
import {
|
|
15
|
-
import { resolveSpace } from "../lib/status.js";
|
|
13
|
+
import { resolveAuthProvider, stopAuthService } from "../lib/auth-proc.js";
|
|
16
14
|
import { c, hang, stderrLine } from "../ui.js";
|
|
17
15
|
import { admitAndRestoreSeatCheckpoints } from "../lib/seat-resume.js";
|
|
18
16
|
import { NATS_DEFAULT_MAX_PAYLOAD, natsServerLabel, resolveNatsServer, unreadVersion } from "../lib/nats-bin.js";
|
|
19
|
-
import { cotalPath, cotalRoot
|
|
17
|
+
import { cotalPath, cotalRoot } from "../lib/paths.js";
|
|
20
18
|
import { channelsReads, readChannelsFile } from "../lib/channel-seed.js";
|
|
21
19
|
import { controllerManifestRemedy, detachedNext, renderDetachedSummary } from "../lib/up-report.js";
|
|
22
|
-
import { seedDefaultPersona } from "../lib/default-persona.js";
|
|
23
20
|
import { seedBeforeLaunch, seedMoveNote } from "../seed/launch.js";
|
|
24
21
|
import { seedDir } from "../seed/paths.js";
|
|
25
22
|
import { seedStoreMoved } from "../seed/reconcile.js";
|
|
26
23
|
import { upSystemdSupervisionWarning } from "../lib/systemd-supervision.js";
|
|
27
|
-
import { deliveryStoppedByDown, deliveryUp,
|
|
28
|
-
import { RESPONDER_UNBOUND_CONSEQUENCE } from "../lib/delivery-responder.js";
|
|
24
|
+
import { deliveryStoppedByDown, deliveryUp, ensureDelivery, stopDelivery } from "../lib/delivery-proc.js";
|
|
29
25
|
import { displayCmd } from "../lib/self-exec.js";
|
|
30
26
|
import { shellWord } from "../lib/endpoint-errors.js";
|
|
31
|
-
import { clearManagerArtifacts, liveManagerWouldApplyMaxSessions, managerHasDeliveryMarker,
|
|
32
|
-
import {
|
|
33
|
-
import {
|
|
34
|
-
import {
|
|
35
|
-
import {
|
|
36
|
-
import {
|
|
37
|
-
import { listAdditiveTeamAttempts, retainedAdditiveTeamAttempts } from "../lib/team-additive-attempt.js";
|
|
38
|
-
import { renderUpPlan, renderInherited, renderWarnings } from "../lib/manifest/render.js";
|
|
39
|
-
import { idpUrlProblem, serverUrlProblems } from "../lib/manifest/resolve.js";
|
|
40
|
-
import { failManifest, refuseManifestSpaceMismatch } from "./topology.js";
|
|
41
|
-
import { liveMeshProcesses } from "./clean.js";
|
|
42
|
-
import { checkSpaceFlagValue, checkSpaceName } from "./meshes-add.js";
|
|
43
|
-
import { checkLocalSpace } from "./space-registration.js";
|
|
44
|
-
import { checkNewUpSpace, checkPublicExchangePort, preparedUpRoot } from "./up-target.js";
|
|
45
|
-
import { cleanedManifestStart, interruptedStartBroker, retainedOpenSpace } from "../lib/legacy-start.js";
|
|
46
|
-
import { bindReaches, canonicalServer, controllerStackApplies, recheckExistingStore, requestedStackMode, refuseForegroundStackHolder, requestsTls, stackUp, stackUpForegroundNotice, stackUpInterrupted, keptOnUp, selectedOnUp, } from "./stack-up.js";
|
|
27
|
+
import { clearManagerArtifacts, liveManagerWouldApplyMaxSessions, managerHasDeliveryMarker, managerRecordState, stopManager } from "../lib/manager-proc.js";
|
|
28
|
+
import { loadManifest } from "../lib/manifest/index.js";
|
|
29
|
+
import { checkNewUpSpace, preparedUpRoot } from "./up-target.js";
|
|
30
|
+
import { cleanedManifestStart, interruptedStartBroker } from "../lib/legacy-start.js";
|
|
31
|
+
import { canonicalServer } from "../lib/broker-service.js";
|
|
32
|
+
import { controllerStackApplies, requestedStackMode, refuseForegroundStackHolder, stackUp, stackUpForegroundNotice, stackUpInterrupted, } from "./stack-up.js";
|
|
47
33
|
import { exitInterrupted, handOverStartupNotice, noticeOnInterrupt, releaseStartupNotice } from "../lib/interrupt-notice.js";
|
|
48
34
|
import { claimForegroundHold, foregroundHolder, foregroundStackEnd, releaseForegroundHold } from "../lib/foreground-hold.js";
|
|
49
35
|
import { settleInterruptedLaunches } from "../lib/service-process.js";
|
|
50
36
|
import { assertUserStackTransport, preflightUserStack } from "./stack-user-auth.js";
|
|
51
|
-
import {
|
|
37
|
+
import { stopForegroundStack } from "./stack-down.js";
|
|
52
38
|
import { assertControllerCoupling, assertControllerMembersLive, assertControllerResumeEligible, beginControllerResume, bindControllerBroker, controllerAttemptBrokerInstance, currentControllerAttempt, managerResumeAttempt, relaunchCommittedManager, settleControllerResume, startControllerMember, startControllerMembers, } from "../lib/controller-resume.js";
|
|
53
39
|
import { removeRetiredBrokerInstance } from "../lib/controller-restore.js";
|
|
54
|
-
import { acquireStackOperationLock,
|
|
40
|
+
import { acquireStackOperationLock, admittedStackRestore, readStackJournal, STACK_DEFINITION, STACK_ROLES } from "../lib/stack-journal.js";
|
|
55
41
|
import { observeServiceProcess, serviceInstances } from "../lib/service-instances.js";
|
|
56
42
|
import { serviceDefinitionStore } from "../lib/service-definitions.js";
|
|
57
43
|
import { MissingFlags } from "../lib/missing-flags.js";
|
|
58
|
-
import {
|
|
59
|
-
import { serviceInstallIntents } from "../lib/service-install-intent.js";
|
|
60
|
-
import { serviceUninstallIntents } from "../lib/service-uninstall-intent.js";
|
|
61
|
-
import { serviceUnitActionStore } from "../lib/service-unit-action.js";
|
|
62
|
-
import { assertStoreDirArgument, startupStoreProblem, warnForeignStoreEntries } from "../lib/store-dir.js";
|
|
44
|
+
import { warnForeignStoreEntries } from "../lib/store-dir.js";
|
|
63
45
|
import { extensionNames, preflightRuntime } from "../ext-loader.js";
|
|
64
46
|
import { completingFlagValue } from "../lib/completion.js";
|
|
65
47
|
import { metadataPositionals } from "../lib/command-path.js";
|
|
66
48
|
import { bindPreparedRestoreListener, isManagerCommitResult, isManagerFinalizeResult, isManagerCommittedRestore, markPreparedRestoreActive, markPreparedRestoreDegraded, heldRestoreAttempt, heldClaim, movedFolderRefusal, prepareRestore, restoreArtifactPath, restoreLaunch, preservedSourceState, recordPreparedRestoreManagerCommit, rehydratePreparedRestore, journaledMaxFileStore, journaledRestoredStreams, leftOutNotes, rearmUnboundRestore, replacePreparedDeadRestoreListener, restoreComposition, restoreInterruptNotice, restoreNextStep, restoreOnlyCopy, } from "../lib/restore.js";
|
|
67
49
|
import { attemptProcessesGone } from "../lib/isolated-broker.js";
|
|
68
50
|
import { assertEndpointUnreachable } from "../lib/endpoint-cut.js";
|
|
69
|
-
import { brokerAddressConflict } from "../lib/broker-service.js";
|
|
70
51
|
import { freshStackServer, retryStackAddress, serverWithFreePort } from "../lib/up-broker-address.js";
|
|
71
52
|
import { askManager } from "@cotal-ai/workspace/control";
|
|
72
53
|
import { cliControl } from "../lib/control.js";
|
|
73
54
|
import { pendingRestores, pendingOrdinaryResumes } from "./up-pending.js";
|
|
74
|
-
import { parseMaxFileStore, parseAuthTimeout, parseMaxPayload, assertManagerPayload, parseAccountResolver, authTimeoutArgs, loadChannelsFile, refuseRunningElsewhere, refuseRecordsElsewhere, resolveTransport, assertTlsIntentServed, assertTlsAddressServed,
|
|
75
|
-
import {
|
|
76
|
-
import { registeredAddressHolder, refuseRegisteredAddress, membershipConversionRefusal, fileMembershipStore,
|
|
55
|
+
import { parseMaxFileStore, parseAuthTimeout, parseMaxPayload, assertManagerPayload, parseAccountResolver, authTimeoutArgs, loadChannelsFile, refuseRunningElsewhere, refuseRecordsElsewhere, resolveTransport, assertTlsIntentServed, assertTlsAddressServed, tlsAddress, liveListenerRequiresTls, assertServesDialHost, adoptedTlsRequired, reopenLastStore, refuseMissingNamedStore, checkStartStore, } from "./up-transport.js";
|
|
56
|
+
import { reconcileHostAndServer } from "./up-host.js";
|
|
57
|
+
import { registeredAddressHolder, refuseRegisteredAddress, membershipConversionRefusal, fileMembershipStore, recreateAdoptedMemoryBuckets, } from "./up-stores.js";
|
|
77
58
|
import { brokerVersion, writeOpenBrokerConf, authSetup, provisionWebCreds } from "./up-broker-auth.js";
|
|
59
|
+
import { validateUpArguments, freshFolderRoot, folderNamedSpace, recordsNameNoSpace, inheritedMachineHomeRoot, assertFreshTeamBootOwnership, publicExchangeArgs, serviceEndpointsArgs, folderSpace, assertSelectionNotMoved, } from "./up-args.js";
|
|
60
|
+
import { failedListeners, startUserAuthService, startDeliveryWithBroker, reportDegradedControlPlane, recordSpawnedListener, awaitSpawnedListener, listenerExitRemedy, serveReadyListener, startMeshDetached, assertBrokerAddressFree, refuseStartOverUserState, ensureRootForSpace, unnamedDefault, claimSpace, attachHostFor, maxSessionsFor, recordOurMesh, seedPersonaAfterUp, belowPresenceSafeBroker, } from "./up-detach.js";
|
|
61
|
+
import { controllerStackNative, manifestFileRefusal, upManifest } from "./up-manifest.js";
|
|
62
|
+
export { prepareFreshTeamBoot, prepareResumeTeamBoot, recordedBrokerTransport, recheckFreshTeamBoot, controllerStackNative } from "./up-manifest.js";
|
|
63
|
+
export { prepareBrokerStart, startMeshDetached, claimSpace, attachHostFor, maxSessionsFor, recordOurMeshForTest } from "./up-detach.js";
|
|
64
|
+
export { validateUpArguments } from "./up-args.js";
|
|
78
65
|
const restoreSinks = new Map();
|
|
79
66
|
/** Run the guarded `up --restore` startup and return its result instead of printing it. The
|
|
80
67
|
* restore inputs and fences are exactly `up --restore`'s; this adds no route, flag or authority. */
|
|
@@ -150,451 +137,12 @@ export function upComplete(argv) {
|
|
|
150
137
|
const items = upFlags.map((f) => ({ value: `--${f.name}`, description: f.description }));
|
|
151
138
|
return { items, directive: items.length ? "nofiles" : "default" };
|
|
152
139
|
}
|
|
153
|
-
/** `--recreate-issued-stores <backup-dir>` names a directory the step creates, so it must not exist
|
|
154
|
-
* and its parent must. Checked before anything starts; the step checks again when it creates it. */
|
|
155
|
-
function assertIssuedBackupDirArgument(raw) {
|
|
156
|
-
const dir = resolve(raw);
|
|
157
|
-
const problem = !raw.trim() ? "is empty" : existsSync(dir) ? `${dir} already exists` : !existsSync(dirname(dir)) ? `${dirname(dir)} does not exist` : undefined;
|
|
158
|
-
if (problem)
|
|
159
|
-
throw new CommandFailure("refused", "USAGE_INVALID", `--recreate-issued-stores names a new backup directory, and ${problem}; nothing was started`, { target: { backupDir: dir }, remedy: "name a directory that does not exist yet, inside one that does" });
|
|
160
|
-
}
|
|
161
|
-
/** Launch intent is checked by the kernel before seed or effect preparation. A recovery
|
|
162
|
-
* re-entry supplies its recorded mode explicitly rather than inheriting the new public default. */
|
|
163
|
-
export function validateUpArguments(args) {
|
|
164
|
-
presentationOf(args.values);
|
|
165
|
-
if (typeof args.values.file === "string" && !args.values.file.trim())
|
|
166
|
-
throw new CommandFailure("refused", "USAGE_INVALID", "--file is empty, so it names no manifest; nothing was started or written", { remedy: "name a manifest with --file <cotal.yaml>, or omit --file to start the folder's stack" });
|
|
167
|
-
if (args.values.restore === "")
|
|
168
|
-
throw new CommandFailure("refused", "USAGE_INVALID", "--restore is empty, so it names no backup folder; nothing was started or written", { remedy: "pass the backup folder as --restore <dir>, or omit --restore to start without restoring", selfContained: true });
|
|
169
|
-
// A `.cotal` that is a link, or leads nowhere, is refused before anything reads through it.
|
|
170
|
-
const linked = args.values.root === undefined ? linkedCotalRefusal("up") : undefined;
|
|
171
|
-
if (linked)
|
|
172
|
-
throw linked;
|
|
173
|
-
if (args.values["user-auth"] === true && args.values.open === true)
|
|
174
|
-
throw new CommandFailure("refused", "USAGE_INVALID", "--user-auth and --open contradict - a user-auth space cannot run unauthenticated", { remedy: "drop --open for user auth, or drop --user-auth for an open space" });
|
|
175
|
-
if (args.values.open === true) {
|
|
176
|
-
publicExchangeArgs(args.values, false);
|
|
177
|
-
serviceEndpointsArgs(args.values, false);
|
|
178
|
-
}
|
|
179
|
-
else if (typeof args.values["exchange-public-port"] === "string")
|
|
180
|
-
checkPublicExchangePort(args.values["exchange-public-port"]);
|
|
181
|
-
if (args.values.idp !== undefined && args.values["user-auth"] !== true && !args.values.file)
|
|
182
|
-
throw new CommandFailure("refused", "USAGE_INVALID", '--idp is for user-auth spaces; pair it with --user-auth, or set broker.auth: "user" in a manifest', { remedy: "use --user-auth --idp <auth base URL>, without --open" });
|
|
183
|
-
if (args.values.restore !== undefined && args.values["no-manager"] === true)
|
|
184
|
-
throw new CommandFailure("refused", "USAGE_INVALID", "--no-manager cannot be combined with --restore: the restore needs a manager to commit its state; nothing was restored", { remedy: "rerun the restore without --no-manager" });
|
|
185
|
-
if (args.values["no-manager"] === true && args.values.runtime !== undefined)
|
|
186
|
-
throw new CommandFailure("refused", "USAGE_INVALID", "--no-manager cannot be combined with --runtime because no manager starts", { remedy: "drop --runtime, or drop --no-manager to select a manager runtime" });
|
|
187
|
-
// Only an omitted --runtime selects the default runtime. An empty one, as an unset variable gives,
|
|
188
|
-
// is a value that names no runtime (#7114).
|
|
189
|
-
if (typeof args.values.runtime === "string" && !args.values.runtime.trim())
|
|
190
|
-
throw new CommandFailure("refused", "USAGE_INVALID", "--runtime is empty, so it names no runtime; nothing was started or written", { remedy: "name a runtime, such as `--runtime pty`, or omit --runtime to use the default" });
|
|
191
|
-
if (args.values["no-manager"] === true && args.values["max-sessions"] !== undefined)
|
|
192
|
-
throw new CommandFailure("refused", "USAGE_INVALID", "--no-manager cannot be combined with --max-sessions because no manager starts", { remedy: "drop --max-sessions, or drop --no-manager to set the manager session ceiling" });
|
|
193
|
-
if (args.values.foreground === true && args.values.detach === true)
|
|
194
|
-
throw new CommandFailure("refused", "USAGE_INVALID", "choose --foreground or --detach, not both");
|
|
195
|
-
// Only a manifest launch has a plan to print; without -f every route would start the stack.
|
|
196
|
-
if (args.values["dry-run"] === true && !args.values.file)
|
|
197
|
-
throw new CommandFailure("refused", "USAGE_INVALID", "--dry-run previews a manifest launch and needs -f <cotal.yaml>; nothing was started or written", { remedy: "pass -f <cotal.yaml> to print that manifest's plan; `cotal status` shows what this folder records" });
|
|
198
|
-
// The stack passes its space to its own children as `--space <name>`, which a leading - breaks.
|
|
199
|
-
const named = typeof args.values.space === "string" ? checkSpaceFlagValue(args.values.space) : undefined;
|
|
200
|
-
if (named && !named.ok)
|
|
201
|
-
throw new CommandFailure("refused", "USAGE_INVALID", `${named.message.replace(/^✗ /, "")}; nothing was started or written`, { remedy: named.remedy });
|
|
202
|
-
// A manifest boot checks its own `--server` override against `broker.servers`.
|
|
203
|
-
const serverProblem = args.values.server !== undefined && !args.values.file ? upServerProblem(String(args.values.server)) : undefined;
|
|
204
|
-
if (serverProblem)
|
|
205
|
-
throw new FlagValueRefusal(`${serverProblem}; nothing was started or written`, `pass the IP address the local broker listens on, for example ${serverExample(String(args.values.server))}`);
|
|
206
|
-
// A --host that is no bind host, or a bind that does not serve --server's address, refuses here,
|
|
207
|
-
// before the controller stack writes its journal or trust.
|
|
208
|
-
const hostProblem = !args.values.file ? upHostProblem(args.values.host, args.values.server) : undefined;
|
|
209
|
-
if (hostProblem)
|
|
210
|
-
throw new CommandFailure("refused", "USAGE_INVALID", `${hostProblem.problem}; nothing was started or written`, { remedy: hostProblem.remedy });
|
|
211
|
-
const spaceTooLong = typeof args.values.space === "string" ? spaceNameTooLong(args.values.space) : undefined;
|
|
212
|
-
if (spaceTooLong)
|
|
213
|
-
throw new CommandFailure("refused", "USAGE_INVALID", `${spaceTooLong}; nothing was started or written`, { remedy: `choose a space name of at most ${SPACE_NAME_MAX} characters` });
|
|
214
|
-
// A prepared or controller-owned root has no route that serves TLS, so any TLS input refuses here,
|
|
215
|
-
// once and naming the route that does, before the checks below send it from one TLS form to another.
|
|
216
|
-
const tlsRoot = typeof args.values.root === "string" ? resolve(args.values.root) : freshFolderRoot(args.values) ?? cotalRoot();
|
|
217
|
-
if (!args.values.file && requestsTls(args.values) && !readMaintenanceJournal(tlsRoot))
|
|
218
|
-
controllerStackApplies(tlsRoot, args.values.space ?? folderSpace(), args.values);
|
|
219
|
-
// A --tls-cert broker serves TLS only, and its address says so, so every client dials tls:// and
|
|
220
|
-
// checks the certificate against the address it names.
|
|
221
|
-
if (!args.values.file && args.values["tls-cert"] !== undefined && typeof args.values.server === "string" && /^nats:\/\//i.test(args.values.server))
|
|
222
|
-
throw new CommandFailure("refused", "USAGE_INVALID", "--tls-cert serves the broker over TLS, so --server must be a tls:// address; nothing was started or written", { remedy: `pass --server ${tlsAddress(args.values.server)}`, selfContained: true });
|
|
223
|
-
if (args.values.file !== undefined && args.values.foreground === true)
|
|
224
|
-
throw new CommandFailure("refused", "UNSUPPORTED", "manifest boot has no native foreground custody path; a detached broker was not substituted for the requested terminal-bound lifetime");
|
|
225
|
-
if (args.values.foreground === true && (args.values.json === true || args.values.plain === true))
|
|
226
|
-
throw new CommandFailure("refused", "USAGE_INVALID", "foreground up keeps native terminal custody and cannot produce a finite JSON or plain receipt", { remedy: `omit ${args.values.json ? "--json" : "--plain"} to keep the stack in this terminal, or omit --foreground for a finite receipt from a controller-owned stack` });
|
|
227
|
-
// Flag values and combinations are usage, so they refuse here, before any effect. The run keeps
|
|
228
|
-
// its own checks for maintenance re-entries, which do not pass through this validation.
|
|
229
|
-
parsePositiveIntegerFlag("--max-sessions", args.values["max-sessions"]);
|
|
230
|
-
parseSeatCapFlag("--seat-cap", args.values["seat-cap"]);
|
|
231
|
-
parseMaxFileStore(args.values["max-file-store"]);
|
|
232
|
-
const logFile = args.values["log-file"];
|
|
233
|
-
if (logFile !== undefined && (!logFile.trim() || /[\u0000-\u001f\u007f]/u.test(logFile)))
|
|
234
|
-
throw new CommandFailure("refused", "USAGE_INVALID", "--log-file must be a non-empty file path without control characters");
|
|
235
|
-
const logfileSizeLimit = parsePositiveIntegerFlag("--logfile-size-limit", args.values["logfile-size-limit"]);
|
|
236
|
-
const logfileMaxNum = parsePositiveIntegerFlag("--logfile-max-num", args.values["logfile-max-num"]);
|
|
237
|
-
// A controller restart can use its saved path. A restore still needs an explicit path.
|
|
238
|
-
if (!args.values.file && logFile === undefined && (logfileSizeLimit !== undefined || logfileMaxNum !== undefined)
|
|
239
|
-
&& (args.values.restore !== undefined || readStackJournal(tlsRoot)?.journal.broker?.logFile === undefined))
|
|
240
|
-
throw new CommandFailure("refused", "USAGE_INVALID", "--logfile-size-limit and --logfile-max-num require --log-file");
|
|
241
|
-
// The timeout belongs to the auth callout, which only a user-auth space has. A manifest or a
|
|
242
|
-
// restore starts the broker its own record describes, so neither takes it.
|
|
243
|
-
if (parseAuthTimeout(args.values["auth-timeout"]) !== undefined) {
|
|
244
|
-
if (args.values.open === true)
|
|
245
|
-
throw new CommandFailure("refused", "USAGE_INVALID", "--auth-timeout sets the auth callout's timeout, and an open space has no auth callout; nothing was started", { remedy: "drop --auth-timeout, or start a user-auth space with --user-auth" });
|
|
246
|
-
if (args.values.file !== undefined || args.values.restore !== undefined)
|
|
247
|
-
throw new CommandFailure("refused", "USAGE_INVALID", `--auth-timeout cannot be combined with ${args.values.file !== undefined ? "--file/-f" : "--restore"}, which starts the broker its own record describes; nothing was started`, { remedy: "start it without --auth-timeout; a recorded timeout is rendered again" });
|
|
248
|
-
}
|
|
249
|
-
// Both broker modes render the payload limit. A manifest or a restore starts the broker its own
|
|
250
|
-
// record describes, so neither takes the flag.
|
|
251
|
-
const requestedPayload = parseMaxPayload(args.values["max-payload"]);
|
|
252
|
-
if (requestedPayload !== undefined) {
|
|
253
|
-
if (args.values.file !== undefined || args.values.restore !== undefined)
|
|
254
|
-
throw new CommandFailure("refused", "USAGE_INVALID", `--max-payload cannot be combined with ${args.values.file !== undefined ? "--file/-f" : "--restore"}, which starts the broker its own record describes; nothing was started`, { remedy: "start it without --max-payload; a recorded limit is rendered again" });
|
|
255
|
-
// A space that admits service endpoints is a space whose auth host asserts the caller payload
|
|
256
|
-
// precondition at startup, and that assertion REFUSES below the floor, so the auth context does
|
|
257
|
-
// not open at all. Refusing the pair here is the difference between a usage error before
|
|
258
|
-
// anything starts and a broker that comes up without its auth plane.
|
|
259
|
-
if (args.values["service-endpoints"] === true && requestedPayload < SERVICE_CALLER_PAYLOAD_FLOOR)
|
|
260
|
-
throw new CommandFailure("refused", "USAGE_INVALID", `--max-payload ${requestedPayload} is below ${SERVICE_CALLER_PAYLOAD_FLOOR} bytes, the least a space with --service-endpoints starts on: a caller policy row may grow to ${SERVICE_AUTHORITY_MAX_BYTES} bytes and its write needs ${SERVICE_CALLER_PAYLOAD_FLOOR - SERVICE_AUTHORITY_MAX_BYTES} more, so the auth host refuses to open; nothing was started`, { remedy: `pass --max-payload ${SERVICE_CALLER_PAYLOAD_FLOOR} or more, or drop --service-endpoints` });
|
|
261
|
-
if (args.values["no-manager"] !== true)
|
|
262
|
-
assertManagerPayload(requestedPayload);
|
|
263
|
-
}
|
|
264
|
-
// The account resolver belongs to the auth-mode broker configuration as well: the open broker has
|
|
265
|
-
// no operator and so no accounts to resolve, and a manifest or a restore starts the broker its own
|
|
266
|
-
// record describes.
|
|
267
|
-
if (parseAccountResolver(args.values["account-resolver"]) !== undefined) {
|
|
268
|
-
if (args.values.open === true)
|
|
269
|
-
throw new CommandFailure("refused", "USAGE_INVALID", "--account-resolver sets how the broker resolves space accounts, and the open broker configuration has none; nothing was started", { remedy: "drop --account-resolver, or start an auth space without --open" });
|
|
270
|
-
if (args.values.file !== undefined || args.values.restore !== undefined)
|
|
271
|
-
throw new CommandFailure("refused", "USAGE_INVALID", `--account-resolver cannot be combined with ${args.values.file !== undefined ? "--file/-f" : "--restore"}, which starts the broker its own record describes; nothing was started`, { remedy: "start it without --account-resolver; a recorded resolver is rendered again" });
|
|
272
|
-
}
|
|
273
|
-
if (typeof args.values["store-dir"] === "string")
|
|
274
|
-
assertStoreDirArgument(args.values["store-dir"], typeof args.values.root === "string" ? resolve(args.values.root) : freshFolderRoot(args.values) ?? cotalRoot());
|
|
275
|
-
const restoreOnly = args.values["restore-only"];
|
|
276
|
-
if (restoreOnly !== undefined && restoreOnly !== "registry")
|
|
277
|
-
throw new CommandFailure("refused", "USAGE_INVALID", `--restore-only takes registry (got ${JSON.stringify(restoreOnly)})`);
|
|
278
|
-
if (!args.values.restore && (restoreOnly !== undefined || args.values["accept-missing-source"] === true))
|
|
279
|
-
throw new CommandFailure("refused", "USAGE_INVALID", "--restore-only and --accept-missing-source require --restore <dir>");
|
|
280
|
-
if (args.values.file !== undefined && args.values["accept-stale-checkpoint"] === true)
|
|
281
|
-
throw new FlagValueRefusal("--accept-stale-checkpoint cannot be combined with --file/-f: a manifest starts a fresh mesh, not a preserved stack", "drop --accept-stale-checkpoint for a fresh start, or omit --file/-f to resume a preserved stack");
|
|
282
|
-
if (args.values.restore && (args.values.file !== undefined || args.values.channels !== undefined))
|
|
283
|
-
throw new CommandFailure("refused", "USAGE_INVALID", "--restore cannot be combined with --file/-f or --channels");
|
|
284
|
-
if (args.values.restore && args.values["rotate-sys"] === true)
|
|
285
|
-
throw new CommandFailure("refused", "USAGE_INVALID", "--restore cannot be combined with --rotate-sys", { remedy: "restore the space and verify it first, then rotate: `cotal down`, then `cotal up --rotate-sys`" });
|
|
286
|
-
if (args.values["recreate-issued-stores"] !== undefined) {
|
|
287
|
-
if (args.values.file !== undefined || args.values.restore !== undefined)
|
|
288
|
-
throw new CommandFailure("refused", "USAGE_INVALID", `--recreate-issued-stores cannot be combined with ${args.values.file !== undefined ? "--file/-f" : "--restore"}; nothing was started`, { remedy: "run `cotal up --space <space> --recreate-issued-stores <backup-dir>` on its own first" });
|
|
289
|
-
assertIssuedBackupDirArgument(String(args.values["recreate-issued-stores"]));
|
|
290
|
-
}
|
|
291
|
-
if (args.values["recreate-membership-store"] === true && (args.values.file !== undefined || args.values.restore !== undefined))
|
|
292
|
-
throw new CommandFailure("refused", "USAGE_INVALID", `--recreate-membership-store cannot be combined with ${args.values.file !== undefined ? "--file/-f" : "--restore"}; nothing was started`, { remedy: "run `cotal up --space <space> --recreate-membership-store` on its own first" });
|
|
293
|
-
if (args.values.root !== undefined)
|
|
294
|
-
preparedUpRoot(String(args.values.root));
|
|
295
|
-
else if (!(args.values.file && args.values["dry-run"] === true)) {
|
|
296
|
-
const inheritedRoot = inheritedMachineHomeRoot();
|
|
297
|
-
if (inheritedRoot) {
|
|
298
|
-
if (!freshFolderRoot(args.values))
|
|
299
|
-
throw new CommandFailure("refused", "CONFLICT", "this folder inherits the machine's home .cotal; up did not start a stack in that home root", { target: { root: process.cwd(), inheritedRoot }, remedy: "prepare this folder with `cotal space create <space> --root .`, then run `cotal up` again from this folder" });
|
|
300
|
-
}
|
|
301
|
-
else {
|
|
302
|
-
const home = machineHomeRoot();
|
|
303
|
-
if (home && !homeHoldsStack(home))
|
|
304
|
-
throw new CommandFailure("refused", "CONFLICT", `${home} is your home folder, whose .cotal holds this machine's own records, so up started no stack there`, { target: { root: home }, remedy: "prepare a project folder with `cotal space create <space> --root <dir>`, then run `cotal up` there, or pass --root <dir> from here" });
|
|
305
|
-
}
|
|
306
|
-
}
|
|
307
|
-
if (args.values.restore !== undefined)
|
|
308
|
-
refuseControllerCut(args.values.root !== undefined ? preparedUpRoot(String(args.values.root)) : cotalRoot(), "up --restore");
|
|
309
|
-
if (!(args.values.file && args.values["dry-run"] === true)) {
|
|
310
|
-
const root = args.values.root !== undefined ? preparedUpRoot(String(args.values.root)) : freshFolderRoot(args.values) ?? cotalRoot();
|
|
311
|
-
// A path with a control character or a bidirectional formatting mark is refused before any write.
|
|
312
|
-
const pathProblem = rootPathProblem(root) ?? rootPathProblem(canonicalRoot(root));
|
|
313
|
-
if (pathProblem)
|
|
314
|
-
throw new CommandFailure("refused", "USAGE_INVALID", `${pathProblem}; nothing was started or written`, { target: { root }, remedy: "rename the folder without those characters, then run `cotal up` there" });
|
|
315
|
-
const control = rootControlProblem(root);
|
|
316
|
-
if (control)
|
|
317
|
-
throw new CommandFailure("refused", "CONFLICT", `${control.message}; nothing was started or written`, { target: { root, controlDirectory: control.controlDirectory }, remedy: control.project === undefined
|
|
318
|
-
? "prepare a project folder with `cotal space create <space> --root <dir>`, then run `cotal up` there"
|
|
319
|
-
: `run \`cotal up\` from the project folder ${shellWord(control.project)}` });
|
|
320
|
-
assertUpRootWritable(root);
|
|
321
|
-
// A restore creates its own store. A manifest uses the explicit or default store, not a legacy one.
|
|
322
|
-
if (args.values.restore === undefined)
|
|
323
|
-
assertUpStoreWritable(root, typeof args.values["store-dir"] === "string" ? args.values["store-dir"] : args.values.file === undefined ? undefined : join(root, ".cotal", "nats"));
|
|
324
|
-
}
|
|
325
|
-
}
|
|
326
|
-
/** Every launch route writes under the root's .cotal first, or makes it when it is missing. A folder
|
|
327
|
-
* this account cannot write is refused here, by name, instead of as the raw error of whichever
|
|
328
|
-
* write came first. */
|
|
329
|
-
function assertUpRootWritable(root) {
|
|
330
|
-
// A `.cotal` that is a file is refused by name before any command runs, so only a directory is tested here.
|
|
331
|
-
const path = statSync(join(root, ".cotal"), { throwIfNoEntry: false })?.isDirectory() ? join(root, ".cotal") : root;
|
|
332
|
-
try {
|
|
333
|
-
accessSync(path, constants.W_OK | constants.X_OK);
|
|
334
|
-
}
|
|
335
|
-
catch (error) {
|
|
336
|
-
const code = error.code;
|
|
337
|
-
if (code !== "EACCES" && code !== "EPERM" && code !== "EROFS")
|
|
338
|
-
throw error;
|
|
339
|
-
throw new CommandFailure("refused", "PERMISSION_DENIED", `${path} does not grant this account both write and search access (${code}); nothing was started or written`, { target: { root, path }, remedy: `make it writable and searchable by you, for example with chmod u+wx ${shellWord(path)}` });
|
|
340
|
-
}
|
|
341
|
-
}
|
|
342
|
-
/** The broker exits when it cannot write its store, naming the cause only in its own log. The store
|
|
343
|
-
* a start here opens, as `--store-dir` names it, as the stack or legacy records name it, or `.cotal/nats`,
|
|
344
|
-
* is refused here, by name, when this account cannot write it. */
|
|
345
|
-
function assertUpStoreWritable(root, storeDir) {
|
|
346
|
-
const problem = startupStoreProblem(root, storeDir);
|
|
347
|
-
if (problem)
|
|
348
|
-
throw new CommandFailure("refused", "PERMISSION_DENIED", `${problem.message}; nothing was started or written`, { target: { root, path: problem.path }, remedy: problem.remedy });
|
|
349
|
-
}
|
|
350
|
-
/** Why `--server` cannot be the address a local broker listens on, or undefined when it can. Both
|
|
351
|
-
* launch routes need one nats:// or tls:// URL with an IP address and a TCP port, and without this
|
|
352
|
-
* check a typo reached their first write. The message names at most the host, never the whole
|
|
353
|
-
* value, which may carry a credential. */
|
|
354
|
-
function upServerProblem(server) {
|
|
355
|
-
let url;
|
|
356
|
-
try {
|
|
357
|
-
url = new URL(server);
|
|
358
|
-
}
|
|
359
|
-
catch {
|
|
360
|
-
return "--server is not a URL";
|
|
361
|
-
}
|
|
362
|
-
if (url.protocol !== "nats:" && url.protocol !== "tls:")
|
|
363
|
-
return "--server must be a nats:// or tls:// URL";
|
|
364
|
-
if (url.username || url.password)
|
|
365
|
-
return "--server must not embed credentials";
|
|
366
|
-
if (url.search || url.hash || (url.pathname && url.pathname !== "/") || server.includes(","))
|
|
367
|
-
return "--server must be one broker URL without a path, query or fragment";
|
|
368
|
-
if (!url.hostname)
|
|
369
|
-
return "--server names no host";
|
|
370
|
-
// An explicit address is taken as given, so a missing port is never filled in with the default.
|
|
371
|
-
if (!url.port)
|
|
372
|
-
return "--server names no port";
|
|
373
|
-
if (url.port === "0")
|
|
374
|
-
return "--server needs a TCP port from 1 to 65535";
|
|
375
|
-
if (url.hostname.startsWith("["))
|
|
376
|
-
return IPV6_UNSERVED("--server");
|
|
377
|
-
// The broker reports its listener by IP address, which is how both launch routes find it ready.
|
|
378
|
-
if (!isIP(url.hostname))
|
|
379
|
-
return `--server names the host ${url.hostname}, and up needs the IP address the broker listens on`;
|
|
380
|
-
return undefined;
|
|
381
|
-
}
|
|
382
|
-
/** The `--server` a refusal gives as its example: 127.0.0.1 on the port the user passed, or a
|
|
383
|
-
* placeholder when the value names none. */
|
|
384
|
-
function serverExample(server) {
|
|
385
|
-
let port;
|
|
386
|
-
try {
|
|
387
|
-
port = new URL(server).port || undefined;
|
|
388
|
-
}
|
|
389
|
-
catch {
|
|
390
|
-
port = undefined;
|
|
391
|
-
}
|
|
392
|
-
port ??= /:(\d{1,5})\/?$/.exec(server)?.[1];
|
|
393
|
-
const valid = port !== undefined && Number(port) >= 1 && Number(port) <= 65535;
|
|
394
|
-
return `--server ${/^tls:/i.test(server) ? "tls" : "nats"}://127.0.0.1:${valid ? Number(port) : "<port>"}`;
|
|
395
|
-
}
|
|
396
|
-
/** The refusal of a manifest start whose effective `--server` or `broker.servers` lists more than
|
|
397
|
-
* one URL, or undefined when it names one. The start binds one new local broker to one address, so
|
|
398
|
-
* it does not pick an entry. The manifest still validates with a list, which `topology view` shows.
|
|
399
|
-
* The message counts the entries and never repeats them, as one may carry a credential. */
|
|
400
|
-
function bindListRefusal(command, file, space, server, servers) {
|
|
401
|
-
const count = (server ?? servers)?.split(",").filter((entry) => entry.trim()).length ?? 0;
|
|
402
|
-
if (count < 2)
|
|
403
|
-
return undefined;
|
|
404
|
-
const source = server !== undefined ? "--server" : "broker.servers";
|
|
405
|
-
return new CommandFailure("refused", "USAGE_INVALID", `${source} lists ${count} broker URLs, and ${command} binds a single broker address; nothing was started or written`, {
|
|
406
|
-
target: { space, path: resolve(file), source, entries: count },
|
|
407
|
-
remedy: server !== undefined ? "pass one --server URL for the new broker to listen on" : `set broker.servers in ${file} to the one URL the new broker listens on`,
|
|
408
|
-
selfContained: true,
|
|
409
|
-
});
|
|
410
|
-
}
|
|
411
|
-
/** The local stack's own clients cannot reach a broker on an IPv6 address, so neither flag may name one. */
|
|
412
|
-
const IPV6_UNSERVED = (flag) => `${flag} names an IPv6 address, and the local stack's own clients cannot reach a broker there`;
|
|
413
|
-
/** Why `--host` cannot be the local broker's bind address beside `server`, with the step that fixes
|
|
414
|
-
* it, or undefined when it can. A wildcard bind keeps a loopback URL, so it pairs with any address.
|
|
415
|
-
* With no `--host` the broker binds 127.0.0.1, so a `--server` naming another IPv4 address needs one. */
|
|
416
|
-
function upHostProblem(host, server) {
|
|
417
|
-
if (host === undefined) {
|
|
418
|
-
const named = server === undefined ? undefined : new URL(server).hostname;
|
|
419
|
-
return named !== undefined && isIP(named) === 4 && named !== "127.0.0.1" && !WILDCARD_HOSTS.has(named)
|
|
420
|
-
? { problem: `--server ${server} names ${named}, and with no --host the broker binds 127.0.0.1, so it would not listen where its clients connect`, remedy: `pass --host ${named} to bind the broker there` }
|
|
421
|
-
: undefined;
|
|
422
|
-
}
|
|
423
|
-
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(host))
|
|
424
|
-
return { problem: `--host ${host} looks like a URL, and it takes a bind host only (an IP or hostname, no scheme)`, remedy: "pass the broker URL with --server instead" };
|
|
425
|
-
if (WILDCARD_HOSTS.has(host))
|
|
426
|
-
return undefined;
|
|
427
|
-
const bare = host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
|
|
428
|
-
if (isIP(bare) === 6)
|
|
429
|
-
return { problem: IPV6_UNSERVED("--host"), remedy: "pass an IPv4 bind address, for example --host 127.0.0.1" };
|
|
430
|
-
let url;
|
|
431
|
-
try {
|
|
432
|
-
url = new URL(`nats://${host}:1`);
|
|
433
|
-
}
|
|
434
|
-
catch {
|
|
435
|
-
url = undefined;
|
|
436
|
-
}
|
|
437
|
-
if (!url || url.port !== "1" || url.pathname || url.search || url.hash || url.username || url.password)
|
|
438
|
-
return { problem: `--host ${host} is not a valid bind host: an IP or hostname only, with no port; the port comes from --server (or its default)`, remedy: "pass the port in --server, for example --server nats://127.0.0.1:4222" };
|
|
439
|
-
if (server !== undefined && !bindReaches(host, server))
|
|
440
|
-
return { problem: `--host ${host} and --server ${server} name different addresses: the broker would bind ${host} but be probed at ${new URL(server).hostname}`, remedy: "pass one of them, or make both name the same address" };
|
|
441
|
-
return undefined;
|
|
442
|
-
}
|
|
443
|
-
/** The invoking folder, when a bare `up` makes it its own project root: the only `.cotal` above it is
|
|
444
|
-
* the machine home's. The folder has no records of its own, so `up` starts it as it starts a folder
|
|
445
|
-
* with no `.cotal` above it. A stack an earlier release started in the home is left as it is and
|
|
446
|
-
* still starts from the home. A manifest or a restore still needs a prepared folder. */
|
|
447
|
-
function freshFolderRoot(values) {
|
|
448
|
-
if (values.root !== undefined || values.file !== undefined || values.restore !== undefined)
|
|
449
|
-
return undefined;
|
|
450
|
-
return inheritedMachineHomeRoot() !== undefined ? resolve(process.cwd()) : undefined;
|
|
451
|
-
}
|
|
452
|
-
/** The space a bare `up` starts in a new project: the name of the project folder, when no `--space`
|
|
453
|
-
* names one and the folder's records name no space. The name passes the rules `space create`
|
|
454
|
-
* applies, and a name another folder on this machine holds, running, stopped or prepared, refuses
|
|
455
|
-
* rather than being taken over. Each refusal names `--space`, before anything is written. */
|
|
456
|
-
function folderNamedSpace(values) {
|
|
457
|
-
if (values.space !== undefined || values.root !== undefined || values.file !== undefined || values.restore !== undefined)
|
|
458
|
-
return undefined;
|
|
459
|
-
const root = freshFolderRoot(values) ?? (machineHomeRoot() ? undefined : cotalRoot());
|
|
460
|
-
if (root === undefined || !recordsNameNoSpace(root))
|
|
461
|
-
return undefined;
|
|
462
|
-
const space = basename(resolve(root));
|
|
463
|
-
const named = `up names a new project's space after its folder, and`;
|
|
464
|
-
const checked = checkSpaceName(space);
|
|
465
|
-
const invalid = spaceNameTooLong(space) ?? (checked.ok ? undefined : checked.message.replace(/^✗ /, ""));
|
|
466
|
-
if (invalid)
|
|
467
|
-
throw new CommandFailure("refused", "USAGE_INVALID", `${named} the folder name ${JSON.stringify(space)} cannot be one: ${invalid}; nothing was started or written`, { target: { root }, remedy: "name the space with `cotal up --space <name>`", selfContained: true });
|
|
468
|
-
assertSelectionNotMoved(root, space);
|
|
469
|
-
const held = findMesh(space) ?? findPreparedSpace(space);
|
|
470
|
-
if (held)
|
|
471
|
-
throw new CommandFailure("refused", "CONFLICT", `${named} "${space}" is already ${"server" in held ? `registered at ${held.server}` : "prepared"} for ${held.root}; nothing was started or written`, { target: { root, space, heldBy: held.root }, remedy: "name this folder's space with `cotal up --space <name>`, naming one this machine does not use; `cotal space` lists the names in use" });
|
|
472
|
-
checkLocalSpace(space, root, "--root", false);
|
|
473
|
-
return space;
|
|
474
|
-
}
|
|
475
|
-
/** Whether no record names a space for `root`: this machine prepared and registered none there, and
|
|
476
|
-
* it has no `.cotal`, an empty one, or one with no account, stack journal, runtime record, broker
|
|
477
|
-
* configuration or maintenance attempt. */
|
|
478
|
-
function recordsNameNoSpace(root) {
|
|
479
|
-
if (preparedSpaceAt(root) || meshesForRoot(root).length)
|
|
480
|
-
return false;
|
|
481
|
-
const control = join(root, ".cotal");
|
|
482
|
-
let entries;
|
|
483
|
-
try {
|
|
484
|
-
entries = readdirSync(control);
|
|
485
|
-
}
|
|
486
|
-
catch (error) {
|
|
487
|
-
return error.code === "ENOENT";
|
|
488
|
-
}
|
|
489
|
-
try {
|
|
490
|
-
if (readMaintenanceJournal(root))
|
|
491
|
-
return false;
|
|
492
|
-
}
|
|
493
|
-
catch {
|
|
494
|
-
return false;
|
|
495
|
-
}
|
|
496
|
-
return entries.length === 0 || rootNamesNoSpace(root);
|
|
497
|
-
}
|
|
498
|
-
function inheritedMachineHomeRoot() {
|
|
499
|
-
const root = machineHomeRoot();
|
|
500
|
-
return root !== undefined && canonicalRoot(process.cwd()) !== canonicalRoot(root) ? root : undefined;
|
|
501
|
-
}
|
|
502
|
-
/** The root this `up` resolves when it is the machine home, whose `.cotal` holds this machine's own records. */
|
|
503
|
-
function machineHomeRoot() {
|
|
504
|
-
const root = cotalRoot();
|
|
505
|
-
return canonicalRoot(root) === canonicalRoot(homedir()) || canonicalRoot(join(root, ".cotal")) === canonicalRoot(homeCotalDir()) ? root : undefined;
|
|
506
|
-
}
|
|
507
140
|
export { preparedUpRoot } from "./up-target.js";
|
|
508
|
-
/** The fresh team entry refuses retained custody before `up -f` can write a launch spec,
|
|
509
|
-
* regenerate trust or stop a leftover manager. Only a recorded local root is eligible. */
|
|
510
|
-
function assertFreshTeamBootOwnership(root, space, mode, own) {
|
|
511
|
-
const current = findMesh(space), prepared = findPreparedSpace(space);
|
|
512
|
-
if (!current && !prepared)
|
|
513
|
-
throw new CommandFailure("refused", "TARGET_UNAVAILABLE", "fresh team boot needs a prepared local space; no checkout or machine-home root was guessed", { target: { root, space } });
|
|
514
|
-
if (current && (current.origin !== "up" || canonicalRoot(current.root) !== canonicalRoot(root)) || prepared && canonicalRoot(prepared.root) !== canonicalRoot(root))
|
|
515
|
-
throw new CommandFailure("refused", "CONFLICT", "the selected space is externally registered or its prepared root moved; no fresh local boot was started", { target: { root, space } });
|
|
516
|
-
if (current && mode && current.mode !== mode)
|
|
517
|
-
throw new CommandFailure("refused", "CONFLICT", "the requested fresh boot changes the locally recorded authentication mode; no trust was replaced", { target: { root, space, recordedMode: current.mode, requestedMode: mode } });
|
|
518
|
-
assertSingleSpaceBroker(authDir(root), "team boot");
|
|
519
|
-
const accounts = listSpaceAccounts(authDir(root));
|
|
520
|
-
if (mode === "open" && accounts.length)
|
|
521
|
-
throw new CommandFailure("refused", "CONFLICT", "the selected root retains a broker account; an open team boot did not bypass its recorded authorization", { target: { root, space } });
|
|
522
|
-
if (accounts.some((hosted) => hosted !== space))
|
|
523
|
-
throw new CommandFailure("refused", "CONFLICT", "the local broker root retains another space's account; team boot did not reassign that trust", { target: { root, space } });
|
|
524
|
-
const userSpaces = userAuthSpacesOnDisk(authDir(root));
|
|
525
|
-
if (mode === "user" && (userSpaces.some((hosted) => hosted !== space) || (accounts.includes(space) && !userSpaces.includes(space))))
|
|
526
|
-
throw new CommandFailure("refused", "CONFLICT", "the selected root holds another user-auth space or static trust without matching user-auth state; team boot did not convert its identity", { target: { root, space } });
|
|
527
|
-
if (mode && mode !== "user" && userSpaces.length)
|
|
528
|
-
throw new CommandFailure("refused", "CONFLICT", "this root retains user-auth state; a static or open team boot did not re-mode its identity", { target: { root, space } });
|
|
529
|
-
if (localMeshesForRoot(root).some((entry) => entry.space !== space))
|
|
530
|
-
throw new CommandFailure("refused", "CONFLICT", "another locally registered space uses this broker root; fresh team boot did not reuse or replace its stack", { target: { root, space } });
|
|
531
|
-
if (readMaintenanceJournal(root))
|
|
532
|
-
throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "this root retains a recovery or maintenance attempt; team boot cannot substitute an ordinary startup", { target: { root, space } });
|
|
533
|
-
const manager = managerRecordState(space, root);
|
|
534
|
-
if (manager.state !== "absent")
|
|
535
|
-
throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "a manager record remains, including when its process appears dead; team boot will not stop or overwrite it", { target: { root, space, state: manager.state, path: manager.path }, remedy: "inspect the recorded manager and reconcile its own lifecycle before a fresh team boot" });
|
|
536
|
-
const processes = liveMeshProcesses(root, space);
|
|
537
|
-
if (processes.length)
|
|
538
|
-
throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "a local component may still own this stack; team boot did not replace it", { target: { root, space, processes } });
|
|
539
|
-
const instances = serviceInstances(space), supervisors = serviceSupervisorStore(space).list();
|
|
540
|
-
if (instances.length || supervisors.length)
|
|
541
|
-
throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "service-controller instances or supervisor receipts remain for this space; their ownership was not replaced by fresh team boot", { target: { root, space, instances: instances.map((row) => row.name), supervisors: supervisors.map((row) => row.name) }, remedy: "inspect each service instance and its native supervisor before booting the whole stack" });
|
|
542
|
-
const actions = serviceUnitActionStore(space).list();
|
|
543
|
-
if (actions.some((row) => row.name !== row.record.value.instanceId))
|
|
544
|
-
throw new CommandFailure("refused", "SCHEMA_INVALID", "a retained native action filename differs from its full instance ID; no fresh boot ownership was inferred", { target: { root, space } });
|
|
545
|
-
const attempts = [
|
|
546
|
-
...serviceInstallIntents(space).map((row) => ({ kind: "install", instanceId: row.name, attemptId: row.record.value.attemptId })),
|
|
547
|
-
...serviceUninstallIntents(space).map((row) => ({ kind: "uninstall", instanceId: row.name, attemptId: row.record.value.attemptId })),
|
|
548
|
-
...actions.map((row) => ({ kind: "unit-action", instanceId: row.name, attemptId: row.record.value.attemptId })),
|
|
549
|
-
];
|
|
550
|
-
if (attempts.length)
|
|
551
|
-
throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "native service attempts remain for this space; a submitted step may have changed state, so fresh team boot did not replace their custody", { target: { root, space, attempts }, remedy: "inspect and reconcile each retained attempt on its original service instance before fresh boot" });
|
|
552
|
-
let ledgers;
|
|
553
|
-
try {
|
|
554
|
-
ledgers = listLedgerFiles(root, { requireReadable: true });
|
|
555
|
-
}
|
|
556
|
-
catch {
|
|
557
|
-
throw new CommandFailure("refused", "TARGET_UNAVAILABLE", "the root's additive ledger directory could not be inspected; no absence of prior owned resources was inferred", { target: { root, space } });
|
|
558
|
-
}
|
|
559
|
-
if (ledgers.valid.length || ledgers.refused.length)
|
|
560
|
-
throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "additive ownership ledgers or unreadable ledger records remain under this root; fresh team boot did not adopt or erase them", { target: { root, space, deploymentIds: ledgers.valid.map(({ ledger }) => ledger.runId), unreadable: ledgers.refused.map(({ path }) => path) }, remedy: "inspect and finish each additive deployment's own lifecycle before a fresh team boot" });
|
|
561
|
-
let additiveAttempts;
|
|
562
|
-
try {
|
|
563
|
-
additiveAttempts = listAdditiveTeamAttempts(root);
|
|
564
|
-
}
|
|
565
|
-
catch {
|
|
566
|
-
throw new CommandFailure("refused", "TARGET_UNAVAILABLE", "the root's additive attempt inventory could not be read; fresh boot did not assume it was empty", { target: { root, space } });
|
|
567
|
-
}
|
|
568
|
-
if (retainedAdditiveTeamAttempts(additiveAttempts).length || additiveAttempts.refused.length)
|
|
569
|
-
throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "an additive deployment attempt remains under this root; its native outcome was not adopted as whole-stack ownership", { target: { root, space, deploymentIds: retainedAdditiveTeamAttempts(additiveAttempts).map((attempt) => attempt.deploymentId), unreadable: additiveAttempts.refused.map(({ path }) => path) } });
|
|
570
|
-
let bootAttempts, summaries;
|
|
571
|
-
try {
|
|
572
|
-
bootAttempts = listFreshTeamAttempts(root);
|
|
573
|
-
summaries = listFreshTeamSummaries(root);
|
|
574
|
-
}
|
|
575
|
-
catch {
|
|
576
|
-
throw new CommandFailure("refused", "TARGET_UNAVAILABLE", "fresh boot attempt or summary records could not be read; no earlier startup was assumed settled", { target: { root, space } });
|
|
577
|
-
}
|
|
578
|
-
const byId = new Map(summaries.valid.map((summary) => [summary.deploymentId, summary]));
|
|
579
|
-
const ownAttempt = own && bootAttempts.valid.find((attempt) => attempt.deploymentId === own.deploymentId);
|
|
580
|
-
if (own && (!ownAttempt || ownAttempt.space !== space || ownAttempt.root !== root || ownAttempt.server !== own.server || ownAttempt.manifestPath !== own.manifestPath || ownAttempt.authMode !== mode || byId.has(own.deploymentId)))
|
|
581
|
-
throw new CommandFailure("refused", "CONFLICT", "this fresh boot's own intent changed or acquired a summary during preparation; no launch spec was written", { target: { root, space, deploymentId: own.deploymentId } });
|
|
582
|
-
const unsettled = bootAttempts.valid.filter((attempt) => attempt.deploymentId !== own?.deploymentId && !freshTeamAttemptSettled(attempt, byId.get(attempt.deploymentId)));
|
|
583
|
-
if (bootAttempts.refused.length || summaries.refused.length || unsettled.length)
|
|
584
|
-
throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "a prior fresh boot attempt lacks a matching readable summary, or an attempt/summary is unreadable; its outcome was not treated as absent", { target: { root, space, unsettledIds: unsettled.map((attempt) => attempt.deploymentId), unreadable: [...bootAttempts.refused, ...summaries.refused].map(({ path }) => path) }, remedy: "inspect each full boot attempt and its original listener before another fresh start; do not retry an unknown boot" });
|
|
585
|
-
}
|
|
586
|
-
/** The guarded whole-stack stop a foreground signal runs, acknowledged by that signal's exit code. A
|
|
587
|
-
* failed or unknown stop is reported with its retained members; nothing is force-killed. */
|
|
588
|
-
function stopForegroundStack(root, signal) {
|
|
589
|
-
return stackDown(root, { yes: true }).catch((error) => {
|
|
590
|
-
process.stderr.write(`${renderReport(commandFailureReport(isCommandFailure(error) ? error : new CommandFailure("unknown", "OPERATION_UNKNOWN", "the foreground stack stop did not confirm its outcome; its members were retained")), "rich", process.stderr)}\n`);
|
|
591
|
-
}).finally(() => { process.exitCode = signal === "SIGINT" ? 130 : 143; });
|
|
592
|
-
}
|
|
593
141
|
/** A hangup, such as a closed terminal, is not a stop. The stack keeps running and the notice names
|
|
594
142
|
* the command that stops it. Release this process's hold before the immediate exit, which does not
|
|
595
143
|
* unwind the surrounding finally, so a later foreground `up` can take the running stack over. */
|
|
596
144
|
function hangupForegroundStack(root) {
|
|
597
|
-
process.stderr.write(`The terminal closed. This stack
|
|
145
|
+
process.stderr.write(`The terminal closed. This stack is still running; ${codeSpan(`cd ${shellWord(root)} && cotal down`)} stops it.\n`);
|
|
598
146
|
process.exitCode = 129;
|
|
599
147
|
releaseForegroundHold(root);
|
|
600
148
|
process.exit(129);
|
|
@@ -619,7 +167,7 @@ async function holdStack(root, start, releaseRestoreNotice) {
|
|
|
619
167
|
// The start's listeners go only once the hold's own are installed. Node runs a listener for a
|
|
620
168
|
// signal when the loop next polls, and drops the signal if its last listener was removed first,
|
|
621
169
|
// so a signal that lands in the start's last synchronous step would be lost in between.
|
|
622
|
-
let releaseStart = () => { };
|
|
170
|
+
let held = undefined, releaseStart = () => { };
|
|
623
171
|
if (start) {
|
|
624
172
|
let requested;
|
|
625
173
|
const request = (signal) => {
|
|
@@ -637,7 +185,7 @@ async function holdStack(root, start, releaseRestoreNotice) {
|
|
|
637
185
|
handOverStartupNotice();
|
|
638
186
|
let failure;
|
|
639
187
|
try {
|
|
640
|
-
await start();
|
|
188
|
+
held = await start();
|
|
641
189
|
}
|
|
642
190
|
catch (error) {
|
|
643
191
|
failure = { error };
|
|
@@ -648,25 +196,24 @@ async function holdStack(root, start, releaseRestoreNotice) {
|
|
|
648
196
|
if (requested === "SIGHUP")
|
|
649
197
|
hangupForegroundStack(root);
|
|
650
198
|
if (requested)
|
|
651
|
-
await stopForegroundStack(root, requested);
|
|
199
|
+
await stopForegroundStack(root, requested, true);
|
|
652
200
|
if (failure)
|
|
653
201
|
throw failure.error;
|
|
654
202
|
if (requested)
|
|
655
203
|
return;
|
|
656
204
|
}
|
|
657
205
|
return new Promise((resolveHold) => {
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
return readStackJournal(root)?.journal.operation.id;
|
|
206
|
+
const observed = held ?? (() => { try {
|
|
207
|
+
return readStackJournal(root)?.journal;
|
|
661
208
|
}
|
|
662
209
|
catch {
|
|
663
210
|
return undefined;
|
|
664
211
|
} })();
|
|
665
212
|
let stopping = false;
|
|
666
|
-
const
|
|
213
|
+
const checkLifetime = () => {
|
|
667
214
|
if (stopping)
|
|
668
215
|
return;
|
|
669
|
-
const code = foregroundStackEnd(root,
|
|
216
|
+
const code = foregroundStackEnd(root, observed);
|
|
670
217
|
if (code === undefined)
|
|
671
218
|
return;
|
|
672
219
|
stopping = true;
|
|
@@ -676,7 +223,7 @@ async function holdStack(root, start, releaseRestoreNotice) {
|
|
|
676
223
|
clearInterval(lifetime);
|
|
677
224
|
process.exitCode = code;
|
|
678
225
|
resolveHold();
|
|
679
|
-
}, 1000);
|
|
226
|
+
}, lifetime = setInterval(checkLifetime, 1000);
|
|
680
227
|
const stop = (signal) => {
|
|
681
228
|
if (stopping)
|
|
682
229
|
return;
|
|
@@ -689,7 +236,7 @@ async function holdStack(root, start, releaseRestoreNotice) {
|
|
|
689
236
|
};
|
|
690
237
|
const interrupt = () => stop("SIGINT");
|
|
691
238
|
const terminate = () => stop("SIGTERM");
|
|
692
|
-
const hangup = () => { if (!stopping)
|
|
239
|
+
const hangup = () => { checkLifetime(); if (!stopping)
|
|
693
240
|
hangupForegroundStack(root); };
|
|
694
241
|
process.on("SIGINT", interrupt);
|
|
695
242
|
process.on("SIGTERM", terminate);
|
|
@@ -1488,13 +1035,12 @@ async function runUp(args, invokedFrom, inheritedLock, onAdopt, freshTeamBoot =
|
|
|
1488
1035
|
try {
|
|
1489
1036
|
const stackLock = acquireStackOperationLock(meshRoot, values.foreground ? "foreground up" : undefined);
|
|
1490
1037
|
const native = controllerStackNative();
|
|
1491
|
-
|
|
1492
|
-
const start = async () => {
|
|
1038
|
+
const prepare = async () => {
|
|
1493
1039
|
try {
|
|
1494
1040
|
const stackServer = values.server ?? readStackJournal(meshRoot)?.journal.server ?? localMeshesForRoot(meshRoot).find((m) => m.space === stackSpace)?.server ?? await unrecordedStackServer(meshRoot, stackSpace, values.host);
|
|
1495
1041
|
if (values.foreground && presentation !== "json")
|
|
1496
1042
|
stackUpForegroundNotice(presentation, stackSpace, takeover);
|
|
1497
|
-
await stackUp({ maintenanceLock: stackLock, root: meshRoot, space: stackSpace, server: stackServer, transport, runtime: values.runtime ?? "pty", noManager, managerSeatCap, ...(stackMode ? { mode: stackMode } : {}), ...(values.idp ? { idp: values.idp } : {}), ...(values.host ? { host: values.host } : {}), ...(values["store-dir"] ? { storeDir: values["store-dir"] } : {}), ...(values["rotate-sys"] ? { rotateSys: true } : {}), ...(values["recreate-membership-store"] ? { recreateMembershipStore: true } : {}), ...(values["recreate-issued-stores"] !== undefined ? { recreateIssuedStores: resolve(values["recreate-issued-stores"]) } : {}), ...(maxFileStore !== undefined ? { maxFileStore } : {}), ...(logFile !== undefined ? { logFile } : {}), ...(logfileSizeLimit !== undefined ? { logfileSizeLimit } : {}), ...(logfileMaxNum !== undefined ? { logfileMaxNum } : {}), ...(authTimeout !== undefined ? { authTimeout } : {}), ...(maxPayload !== undefined ? { maxPayload } : {}), ...(accountResolver !== undefined ? { accountResolver } : {}), ...(maxSessions !== undefined ? { maxSessions } : {}), ...(values.channels ? { channels: values.channels } : {}), ...(values.__invokedRoot ? { invokedRoot: values.__invokedRoot } : {}), foreground: values.foreground === true, presentation,
|
|
1043
|
+
return await stackUp({ maintenanceLock: stackLock, root: meshRoot, space: stackSpace, server: stackServer, transport, runtime: values.runtime ?? "pty", noManager, managerSeatCap, ...(stackMode ? { mode: stackMode } : {}), ...(values.idp ? { idp: values.idp } : {}), ...(values.host ? { host: values.host } : {}), ...(values["store-dir"] ? { storeDir: values["store-dir"] } : {}), ...(values["rotate-sys"] ? { rotateSys: true } : {}), ...(values["recreate-membership-store"] ? { recreateMembershipStore: true } : {}), ...(values["recreate-issued-stores"] !== undefined ? { recreateIssuedStores: resolve(values["recreate-issued-stores"]) } : {}), ...(maxFileStore !== undefined ? { maxFileStore } : {}), ...(logFile !== undefined ? { logFile } : {}), ...(logfileSizeLimit !== undefined ? { logfileSizeLimit } : {}), ...(logfileMaxNum !== undefined ? { logfileMaxNum } : {}), ...(authTimeout !== undefined ? { authTimeout } : {}), ...(maxPayload !== undefined ? { maxPayload } : {}), ...(accountResolver !== undefined ? { accountResolver } : {}), ...(maxSessions !== undefined ? { maxSessions } : {}), ...(values.channels ? { channels: values.channels } : {}), ...(values.__invokedRoot ? { invokedRoot: values.__invokedRoot } : {}), foreground: values.foreground === true, presentation,
|
|
1498
1044
|
retryAtAnotherAddress: (host) => retryStackAddress(args.raw, invokedFrom, stackServer, host),
|
|
1499
1045
|
}, native);
|
|
1500
1046
|
}
|
|
@@ -1502,6 +1048,7 @@ async function runUp(args, invokedFrom, inheritedLock, onAdopt, freshTeamBoot =
|
|
|
1502
1048
|
releaseMaintenanceLock(stackLock);
|
|
1503
1049
|
}
|
|
1504
1050
|
};
|
|
1051
|
+
const start = async () => { const { journal, writeReceipt } = await prepare(); writeReceipt(); return journal; };
|
|
1505
1052
|
if (values.foreground)
|
|
1506
1053
|
await holdForegroundStack(meshRoot, start);
|
|
1507
1054
|
else
|
|
@@ -2651,40 +2198,6 @@ function restoreListenerOwner(pid, nonce, startedAt) {
|
|
|
2651
2198
|
throw new Error("restore listener spawn returned no pid");
|
|
2652
2199
|
return { pid, host: hostname(), startedAt, id: `restore-listener-${nonce}` };
|
|
2653
2200
|
}
|
|
2654
|
-
function waitForChildExit(child, timeoutMs) {
|
|
2655
|
-
if (child.exitCode !== null || child.signalCode !== null)
|
|
2656
|
-
return Promise.resolve(true);
|
|
2657
|
-
return new Promise((resolveExit) => {
|
|
2658
|
-
const onExit = () => finish(true);
|
|
2659
|
-
const timer = setTimeout(() => finish(false), timeoutMs);
|
|
2660
|
-
const finish = (exited) => {
|
|
2661
|
-
clearTimeout(timer);
|
|
2662
|
-
child.off("exit", onExit);
|
|
2663
|
-
resolveExit(exited);
|
|
2664
|
-
};
|
|
2665
|
-
child.once("exit", onExit);
|
|
2666
|
-
});
|
|
2667
|
-
}
|
|
2668
|
-
/** Listeners {@link stopFailedListener} is stopping. Their launch reports its own error, so the
|
|
2669
|
-
* foreground's broker-exit handler must not report that exit as a crash and exit first. */
|
|
2670
|
-
const failedListeners = new WeakSet();
|
|
2671
|
-
/**
|
|
2672
|
-
* Stop a listener whose launch failed before it served. A signal is not proof of exit, so SIGTERM
|
|
2673
|
-
* escalates to SIGKILL and `nats.pid` is removed only once the exit is observed. A listener that
|
|
2674
|
-
* outlives both keeps its record and fails loud with its pid. A listener whose pid publish threw
|
|
2675
|
-
* passes `published` false and leaves `nats.pid` as found.
|
|
2676
|
-
*/
|
|
2677
|
-
async function stopFailedListener(child, published = true) {
|
|
2678
|
-
failedListeners.add(child);
|
|
2679
|
-
child.kill("SIGTERM");
|
|
2680
|
-
if (!await waitForChildExit(child, 5_000)) {
|
|
2681
|
-
child.kill("SIGKILL");
|
|
2682
|
-
if (!await waitForChildExit(child, 5_000))
|
|
2683
|
-
throw new Error(`nats-server process ${child.pid ?? "unknown"} did not exit after SIGKILL`);
|
|
2684
|
-
}
|
|
2685
|
-
if (published)
|
|
2686
|
-
removePidPair(cotalPath(NATS_PIDFILE), String(child.pid));
|
|
2687
|
-
}
|
|
2688
2201
|
function bindSpawnedRestoreListener(prepared, pid, startedAt, heldLock) {
|
|
2689
2202
|
bindRestoreListenerOwner(prepared, restoreListenerOwner(pid, prepared.serverNonce, startedAt), heldLock);
|
|
2690
2203
|
}
|
|
@@ -3274,1361 +2787,5 @@ async function completeResumeActivation(attemptId, healthy, reason, server, held
|
|
|
3274
2787
|
retireActiveRestoreBroker(restored.root, attemptId, retireBroker, heldLock);
|
|
3275
2788
|
}
|
|
3276
2789
|
}
|
|
3277
|
-
/** Validate + assemble the auth-service daemon's public-exchange argv from `up`'s flags. The three
|
|
3278
|
-
* flags travel with --user-auth (an open mesh has no exchange to publish); --exchange-public-url
|
|
3279
|
-
* and --exchange-trusted-proxy modify the public listener, so they require its port. Returned as
|
|
3280
|
-
* an argv ARRAY — the daemon re-exec never shell-interpolates. */
|
|
3281
|
-
function publicExchangeArgs(v, wantUser) {
|
|
3282
|
-
const port = v["exchange-public-port"];
|
|
3283
|
-
const url = v["exchange-public-url"];
|
|
3284
|
-
const proxy = Boolean(v["exchange-trusted-proxy"]);
|
|
3285
|
-
const advertised = v["advertised-server"];
|
|
3286
|
-
const provisioning = v["agent-provisioning-url"];
|
|
3287
|
-
if (port === undefined && url === undefined && !proxy && advertised === undefined && provisioning === undefined)
|
|
3288
|
-
return [];
|
|
3289
|
-
const flags = [port !== undefined && "--exchange-public-port", url !== undefined && "--exchange-public-url", proxy && "--exchange-trusted-proxy", advertised !== undefined && "--advertised-server", provisioning !== undefined && "--agent-provisioning-url"].filter(Boolean);
|
|
3290
|
-
if (!wantUser)
|
|
3291
|
-
throw userAuthFlagsRefusal(flags.join(", "));
|
|
3292
|
-
if (port === undefined)
|
|
3293
|
-
throw new CommandFailure("refused", "USAGE_INVALID", `${flags.join(", ")} ${flags.length === 1 ? "requires" : "require"} --exchange-public-port. Nothing started.`, { remedy: "add --exchange-public-port with the public listener port, or remove the flags that need it" });
|
|
3294
|
-
return [
|
|
3295
|
-
"--exchange-public-port", port,
|
|
3296
|
-
...(url !== undefined ? ["--exchange-public-url", url] : []),
|
|
3297
|
-
...(proxy ? ["--exchange-trusted-proxy"] : []),
|
|
3298
|
-
...(advertised !== undefined ? ["--advertised-server", advertised] : []),
|
|
3299
|
-
...(provisioning !== undefined ? ["--agent-provisioning-url", provisioning] : []),
|
|
3300
|
-
];
|
|
3301
|
-
}
|
|
3302
|
-
/** The daemon argv for `--service-endpoints`: the auth service hosts the service endpoint door and
|
|
3303
|
-
* host route. User-auth only; an open mesh has no owner to decide. */
|
|
3304
|
-
function serviceEndpointsArgs(v, wantUser) {
|
|
3305
|
-
if (!v["service-endpoints"])
|
|
3306
|
-
return [];
|
|
3307
|
-
if (!wantUser)
|
|
3308
|
-
throw userAuthFlagsRefusal("--service-endpoints");
|
|
3309
|
-
return ["--service-endpoints"];
|
|
3310
|
-
}
|
|
3311
|
-
function userAuthFlagsRefusal(flags) {
|
|
3312
|
-
return new CommandFailure("refused", "USAGE_INVALID", `${flags} can only be used with user auth. Nothing started.`, { remedy: "remove the incompatible flags for an open space, or use them with --user-auth instead of --open" });
|
|
3313
|
-
}
|
|
3314
|
-
/** Bring the space's USER-AUTH service up with the broker (user mode only — `setup.prepared` is the
|
|
3315
|
-
* provider's output). Loud both ways (U5): a ready service prints the login line; a service that
|
|
3316
|
-
* never became ready prints the exact consequence + recourse. Returns the registry metadata either
|
|
3317
|
-
* way — the mesh IS a user-auth mesh even while its service is down (connects must say "auth
|
|
3318
|
-
* service down", never fall back to static semantics) — plus `ok`, so the exiting `up` surfaces
|
|
3319
|
-
* (detach / manifest / refresh-heal) turn a dead identity plane into a NON-ZERO exit: automation
|
|
3320
|
-
* must not read "user mesh up" from a mesh whose every user connect will be denied. */
|
|
3321
|
-
async function startUserAuthService(space, server, setup, publicExchange, quietBoot = false) {
|
|
3322
|
-
if (!setup?.prepared || !setup.stateDir)
|
|
3323
|
-
return { ok: true };
|
|
3324
|
-
try {
|
|
3325
|
-
const raw = await ensureAuthService({ space, server, stateDir: setup.stateDir, prepared: setup.prepared, extraArgs: publicExchange });
|
|
3326
|
-
// The PUBLIC face's advertised URL (when enabled) supersedes the loopback bind in the registry's
|
|
3327
|
-
// convenience endpoint — the discovery bundle is GENERATED from what the daemon actually serves,
|
|
3328
|
-
// never hand-written. The provider reports it; nothing here reads provider state files.
|
|
3329
|
-
const base = typeof raw.publicUrl === "string" ? raw.publicUrl : String(raw.url);
|
|
3330
|
-
const endpoints = { url: base, ...(typeof raw.publicUrl === "string" ? { managerAuthorityUrl: `${base.replace(/\/$/, "")}/manager-service-authority` } : {}) };
|
|
3331
|
-
const info = assertUserAuthInfo({ ...setup.prepared.publicAuth, endpoints });
|
|
3332
|
-
if (!quietBoot)
|
|
3333
|
-
console.log(c.green("✓ user-auth service up") + c.dim(` - sign in with: \`cotal login --idp ${info.idp.url}\``));
|
|
3334
|
-
return { userAuth: info, ok: true };
|
|
3335
|
-
}
|
|
3336
|
-
catch (e) {
|
|
3337
|
-
// A typed refusal leads with its code and each detail's reason, e.g. a plane claim's
|
|
3338
|
-
// `unknown` liveness against its `live-peer` contention, so no caller parses the copy.
|
|
3339
|
-
const typed = e instanceof EpEnvelopeError
|
|
3340
|
-
? ` [${[e.code, ...(e.details ?? []).map((d) => typeof d.reason === "string" ? `${d.kind}: ${d.reason}` : d.kind)].join("; ")}]`
|
|
3341
|
-
: "";
|
|
3342
|
-
stderrLine("✗ ", `user-auth service did not come up${typed} (${e.message}) - user connects to "${space}" will fail until a re-\`cotal up\` succeeds`, c.red);
|
|
3343
|
-
return { userAuth: assertUserAuthInfo(setup.prepared.publicAuth), ok: false };
|
|
3344
|
-
}
|
|
3345
|
-
}
|
|
3346
|
-
/** The fresh boot's read-only preparation, shared by the controller team boot. It runs the same
|
|
3347
|
-
* manifest load, override, mode agreement, ownership, bind, runtime, reachability and connector
|
|
3348
|
-
* refusals as the retained `upManifest` fresh path, in the same order, and writes nothing. */
|
|
3349
|
-
export async function prepareFreshTeamBoot(file, opts) {
|
|
3350
|
-
const flags = { ...opts, dryRun: false, freshTeamBoot: true };
|
|
3351
|
-
let prepared;
|
|
3352
|
-
try {
|
|
3353
|
-
prepared = loadManifest(resolve(file));
|
|
3354
|
-
}
|
|
3355
|
-
catch {
|
|
3356
|
-
throw new CommandFailure("refused", "SCHEMA_INVALID", "the fresh boot manifest changed or could not be resolved before startup; no broker was started", { target: { path: resolve(file), space: opts.space } });
|
|
3357
|
-
}
|
|
3358
|
-
if (opts.space !== prepared.manifest.space)
|
|
3359
|
-
throw new CommandFailure("refused", "CONFLICT", "the fresh boot manifest no longer names the selected space; no broker was started", { target: { selectedSpace: opts.space, declaredSpace: prepared.manifest.space } });
|
|
3360
|
-
const declared = prepared.manifest.broker?.auth;
|
|
3361
|
-
if (opts.open && declared === "user")
|
|
3362
|
-
throw new CommandFailure("refused", "CONFLICT", "--open contradicts this manifest's user-auth mode; no trust or broker was changed", { target: { space: opts.space } });
|
|
3363
|
-
if (opts.userAuth && declared !== "user")
|
|
3364
|
-
throw new CommandFailure("refused", "CONFLICT", "--user-auth contradicts this manifest's declared auth mode; no trust or broker was changed", { target: { space: opts.space } });
|
|
3365
|
-
if (opts.idp && declared !== "user")
|
|
3366
|
-
throw new CommandFailure("refused", "CONFLICT", "--idp needs this manifest's user-auth mode; no trust or broker was changed", { target: { space: opts.space } });
|
|
3367
|
-
const idpProblem = opts.idp === undefined ? undefined : idpUrlProblem(opts.idp, "--idp");
|
|
3368
|
-
if (idpProblem)
|
|
3369
|
-
throw new CommandFailure("refused", "SCHEMA_INVALID", idpProblem, { target: { space: opts.space } });
|
|
3370
|
-
const serverProblems = opts.server === undefined ? [] : serverUrlProblems(opts.server, "--server");
|
|
3371
|
-
if (serverProblems.length)
|
|
3372
|
-
throw new CommandFailure("refused", "SCHEMA_INVALID", serverProblems.join("; "), { target: { space: opts.space } });
|
|
3373
|
-
const list = bindListRefusal("team boot", file, opts.space, opts.server, prepared.manifest.broker?.servers);
|
|
3374
|
-
if (list)
|
|
3375
|
-
throw list;
|
|
3376
|
-
const { prepared: eff, hostSource, serverSource } = applyUpOverrides(prepared, flags);
|
|
3377
|
-
const m = eff.manifest;
|
|
3378
|
-
const host = m.broker?.host ?? "127.0.0.1";
|
|
3379
|
-
const server = m.broker?.host ? reconcileHostAndServer(m.broker.host, m.broker?.servers, hostSource, serverSource) : (m.broker?.servers ?? DEFAULT_SERVER);
|
|
3380
|
-
const open = m.broker?.auth === false;
|
|
3381
|
-
const mode = open ? "open" : m.broker?.auth === "user" ? "user" : "auth";
|
|
3382
|
-
const runtime = m.runtime ?? "pty";
|
|
3383
|
-
if (open && (m.defaults?.deliveryClass === "durable" || m.channels.some((channel) => channel.deliveryClass === "durable")))
|
|
3384
|
-
throw new CommandFailure("refused", "UNSUPPORTED", "this open manifest explicitly requests durable channel delivery, but the open broker has no delivery daemon; no channel metadata or broker was written", { target: { space: m.space }, remedy: "use static/user authentication for durable delivery, or declare live delivery for an open mesh" });
|
|
3385
|
-
const other = loadMeshes().filter((row) => row.space !== m.space && row.server === server);
|
|
3386
|
-
if (other.length)
|
|
3387
|
-
throw new CommandFailure("refused", "CONFLICT", "another local registration names this exact broker address; fresh team boot did not create a listener over its recorded target", { target: { space: m.space, server: brokerAddressForDisplay(server) ?? "not displayable", otherSpaces: other.map((row) => row.space) } });
|
|
3388
|
-
assertFreshTeamBootOwnership(cotalRoot(), m.space, mode);
|
|
3389
|
-
await assertFreshTeamBindAvailable(server, host, m.space);
|
|
3390
|
-
try {
|
|
3391
|
-
await preflightRuntime(runtime);
|
|
3392
|
-
}
|
|
3393
|
-
catch (error) {
|
|
3394
|
-
throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", "the requested runtime did not pass preflight; no fresh boot intent or broker was started", { target: { space: m.space, runtime }, remedy: error instanceof Error ? error.message : "inspect the selected runtime provider" });
|
|
3395
|
-
}
|
|
3396
|
-
if (await isReachable(server))
|
|
3397
|
-
throw new CommandFailure("refused", "CONFLICT", "the selected address already has a broker; fresh boot did not adopt it or start a competing listener", { target: { space: m.space, server: brokerAddressForDisplay(server) ?? "not displayable" } });
|
|
3398
|
-
const conn = await preflightConnectors(prepared);
|
|
3399
|
-
if (conn)
|
|
3400
|
-
throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", "connector preflight failed before the fresh boot intent; no native effect was requested", { target: { space: m.space }, remedy: conn });
|
|
3401
|
-
return { root: canonicalRoot(cotalRoot()), space: m.space, server, host: m.broker?.host, mode, idp: m.broker?.idp, runtime, manifestPath: resolve(file), prepared: eff, transport: assertServesDialHost(opts.transport, new URL(server).hostname), maxSessions: opts.maxSessions, logFile: m.broker?.logFile, logfileSizeLimit: m.broker?.logfileSizeLimit, logfileMaxNum: m.broker?.logfileMaxNum };
|
|
3402
|
-
}
|
|
3403
|
-
/** A stack's auth mode in words, and the manifest's `broker.auth` value that declares it. */
|
|
3404
|
-
const RESUME_MODE = { open: { words: "open", field: "false" }, auth: { words: "static auth", field: "static" }, user: { words: "user auth", field: "user" } };
|
|
3405
|
-
/** A team boot that resumes one exact stopped controller stack whose manager was never attempted.
|
|
3406
|
-
* The same manifest load, agreement, durable-on-open, runtime, reachability and connector refusals
|
|
3407
|
-
* as {@link prepareFreshTeamBoot}, without the fresh zero-instance ownership gate: that gate is
|
|
3408
|
-
* replaced by the stopped-stack eligibility the caller binds under its lock. The manifest may not
|
|
3409
|
-
* move the recorded broker: its server must equal the recorded one, and a declared bind host must
|
|
3410
|
-
* equal the recorded host. Writes nothing. */
|
|
3411
|
-
export async function prepareResumeTeamBoot(file, opts) {
|
|
3412
|
-
let prepared;
|
|
3413
|
-
try {
|
|
3414
|
-
prepared = loadManifest(resolve(file));
|
|
3415
|
-
}
|
|
3416
|
-
catch {
|
|
3417
|
-
throw new CommandFailure("refused", "SCHEMA_INVALID", "the team manifest changed or could not be resolved before startup; nothing was resumed", { target: { path: resolve(file), space: opts.space } });
|
|
3418
|
-
}
|
|
3419
|
-
if (opts.space !== prepared.manifest.space)
|
|
3420
|
-
throw new CommandFailure("refused", "CONFLICT", "the team manifest no longer names the selected space; nothing was resumed", { target: { selectedSpace: opts.space, declaredSpace: prepared.manifest.space } });
|
|
3421
|
-
const { prepared: eff, hostSource, serverSource } = applyUpOverrides(prepared, { transport: opts.transport, dryRun: false, freshTeamBoot: true });
|
|
3422
|
-
const m = eff.manifest;
|
|
3423
|
-
const server = m.broker?.host ? reconcileHostAndServer(m.broker.host, m.broker?.servers, hostSource, serverSource) : (m.broker?.servers ?? DEFAULT_SERVER);
|
|
3424
|
-
const open = m.broker?.auth === false;
|
|
3425
|
-
const mode = open ? "open" : m.broker?.auth === "user" ? "user" : "auth";
|
|
3426
|
-
const runtime = m.runtime ?? "pty";
|
|
3427
|
-
// Each setting the manifest moves, with both values and the manifest change that keeps the recorded one.
|
|
3428
|
-
const shown = (address) => brokerAddressForDisplay(address) ?? "not displayable";
|
|
3429
|
-
const moved = [
|
|
3430
|
-
...(server !== opts.recorded.server ? [{ name: "broker address", recorded: shown(opts.recorded.server), declared: shown(server), keep: `set \`broker.servers\` to ${shown(opts.recorded.server)}` }] : []),
|
|
3431
|
-
...(m.broker?.host !== undefined && m.broker.host !== opts.recorded.host ? [{ name: "bind host", recorded: opts.recorded.host ?? "none", declared: m.broker.host, keep: opts.recorded.host ? `set \`broker.host\` to ${opts.recorded.host}` : "remove `broker.host`" }] : []),
|
|
3432
|
-
...(mode !== opts.recorded.mode ? [{ name: "auth mode", recorded: RESUME_MODE[opts.recorded.mode].words, declared: RESUME_MODE[mode].words, keep: `set \`broker.auth\` to \`${RESUME_MODE[opts.recorded.mode].field}\`` }] : []),
|
|
3433
|
-
];
|
|
3434
|
-
if (moved.length) {
|
|
3435
|
-
const named = moved.map((row) => `${row.name} (recorded ${row.recorded}, declared ${row.declared})`);
|
|
3436
|
-
throw new CommandFailure("refused", "CONFLICT", `the manifest differs from the recorded stopped stack in its ${named.length > 1 ? `${named.slice(0, -1).join(", ")} and ${named.at(-1)}` : named[0]}; nothing was resumed`, {
|
|
3437
|
-
target: { space: m.space, recorded: { ...opts.recorded, server: shown(opts.recorded.server) }, declared: { server: shown(server), host: m.broker?.host ?? null, mode } },
|
|
3438
|
-
remedy: `${moved.map((row) => row.keep).join(" and ")} in the manifest to resume this stack, or boot the manifest as a new space in another folder prepared with \`cotal space create <space>\``,
|
|
3439
|
-
});
|
|
3440
|
-
}
|
|
3441
|
-
if (open && (m.defaults?.deliveryClass === "durable" || m.channels.some((channel) => channel.deliveryClass === "durable")))
|
|
3442
|
-
throw new CommandFailure("refused", "UNSUPPORTED", "this open manifest explicitly requests durable channel delivery, but the open broker has no delivery daemon; nothing was resumed", { target: { space: m.space } });
|
|
3443
|
-
const other = loadMeshes().filter((row) => row.space !== m.space && row.server === server);
|
|
3444
|
-
if (other.length)
|
|
3445
|
-
throw new CommandFailure("refused", "CONFLICT", "another local registration names this exact broker address; the stopped stack was not resumed over it", { target: { space: m.space, otherSpaces: other.map((row) => row.space) } });
|
|
3446
|
-
try {
|
|
3447
|
-
await preflightRuntime(runtime);
|
|
3448
|
-
}
|
|
3449
|
-
catch (error) {
|
|
3450
|
-
throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", "the requested runtime did not pass preflight; nothing was resumed", { target: { space: m.space, runtime }, remedy: error instanceof Error ? error.message : "inspect the selected runtime provider" });
|
|
3451
|
-
}
|
|
3452
|
-
if (await isReachable(server))
|
|
3453
|
-
throw new CommandFailure("refused", "CONFLICT", "the recorded broker address already answers; the stopped stack was not resumed over it", { target: { space: m.space, server: brokerAddressForDisplay(server) ?? "not displayable" } });
|
|
3454
|
-
const conn = await preflightConnectors(prepared);
|
|
3455
|
-
if (conn)
|
|
3456
|
-
throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", "connector preflight failed; nothing was resumed", { target: { space: m.space }, remedy: conn });
|
|
3457
|
-
return { root: canonicalRoot(cotalRoot()), space: m.space, server, host: opts.recorded.host, mode, idp: m.broker?.idp, runtime, manifestPath: resolve(file), prepared: eff, transport: assertServesDialHost(opts.transport, new URL(server).hostname), maxSessions: undefined, logFile: m.broker?.logFile, logfileSizeLimit: m.broker?.logfileSizeLimit, logfileMaxNum: m.broker?.logfileMaxNum };
|
|
3458
|
-
}
|
|
3459
|
-
/** The recorded broker transport of a prepared root, decided without persisting anything: a team
|
|
3460
|
-
* boot names no TLS flags, so it inherits the root's recorded policy exactly as a bare `up` does. */
|
|
3461
|
-
export function recordedBrokerTransport(root) {
|
|
3462
|
-
return resolveTransport({}, undefined, root, { persist: false, quiet: true });
|
|
3463
|
-
}
|
|
3464
|
-
/** Recheck, under the fresh boot's own lock, the ownership and bind refusals that a concurrent
|
|
3465
|
-
* writer could have invalidated after {@link prepareFreshTeamBoot}. */
|
|
3466
|
-
export async function recheckFreshTeamBoot(plan, own) {
|
|
3467
|
-
assertFreshTeamBootOwnership(plan.root, plan.space, plan.mode, own ? { deploymentId: own.deploymentId, server: plan.server, manifestPath: plan.manifestPath } : undefined);
|
|
3468
|
-
await assertFreshTeamBindAvailable(plan.server, plan.host ?? "127.0.0.1", plan.space);
|
|
3469
|
-
}
|
|
3470
|
-
/** The native callbacks a controller stack start uses, shared by `cotal up` and a controller team
|
|
3471
|
-
* boot so both prepare, seed and record through the same native path. */
|
|
3472
|
-
export function controllerStackNative() {
|
|
3473
|
-
return {
|
|
3474
|
-
prepareBroker: async (opts) => {
|
|
3475
|
-
const prepared = await prepareBrokerStart({ transport: opts.transport, server: opts.server, space: opts.space, ...(opts.open ? { open: true } : {}), ...(opts.userAuth ? { userAuth: opts.userAuth } : {}), ...(opts.host ? { host: opts.host } : {}), ...(opts.wsPort !== undefined ? { wsPort: opts.wsPort } : {}), ...(opts.storeDir ? { storeDir: opts.storeDir } : {}), ...(opts.existingStore ? { existingStore: opts.existingStore } : {}), ...(opts.maxFileStore !== undefined ? { maxFileStore: opts.maxFileStore } : {}), ...(opts.logFile !== undefined ? { logFile: opts.logFile } : {}), ...(opts.logfileSizeLimit !== undefined ? { logfileSizeLimit: opts.logfileSizeLimit } : {}), ...(opts.logfileMaxNum !== undefined ? { logfileMaxNum: opts.logfileMaxNum } : {}), ...(opts.authTimeout !== undefined ? { authTimeout: opts.authTimeout } : {}), ...(opts.maxPayload !== undefined ? { maxPayload: opts.maxPayload } : {}), ...(opts.accountResolver !== undefined ? { accountResolver: opts.accountResolver } : {}), ...(opts.noManager ? { noManager: true } : {}), ...(opts.seed !== undefined ? { seed: opts.seed } : opts.channels ? { channels: opts.channels } : {}), quietBoot: true });
|
|
3476
|
-
return { root: prepared.root, server: prepared.server, space: prepared.space, storeDir: prepared.storeDir, transport: prepared.transport, ...(prepared.setup ? { setup: { mintProvisioner: prepared.setup.mintProvisioner, wsPort: prepared.setup.wsPort, moveWebsocketPort: prepared.setup.moveWebsocketPort } } : {}), ...(prepared.setup?.prepared && prepared.setup.stateDir ? { user: { prepared: prepared.setup.prepared, stateDir: prepared.setup.stateDir } } : {}), confPath: prepared.confPath, bin: prepared.bin, source: prepared.source, version: prepared.version, seedFile: prepared.seedFile, ...(prepared.setup?.authTimeout !== undefined ? { authTimeout: prepared.setup.authTimeout } : {}), ...(prepared.maxPayload !== undefined ? { maxPayload: prepared.maxPayload } : {}), ...(prepared.setup?.accountResolver !== undefined ? { accountResolver: prepared.setup.accountResolver } : {}) };
|
|
3477
|
-
},
|
|
3478
|
-
initializeStreams: async (server, space, setup, seedFile, recreateIssuedStores, recreateMembershipStore) => postStart(server, space, setup && { creds: await setup.mintProvisioner() }, seedFile, recreateIssuedStores, recreateMembershipStore, true),
|
|
3479
|
-
recreateDeletedStreams: ({ seed, ...opts }) => recreateDeletedStreams({ ...opts, ...(seed !== undefined ? { seed: seed } : {}) }),
|
|
3480
|
-
recordMesh: (entry) => recordOurMesh({ ...entry, ts: new Date().toISOString() }, "started", true),
|
|
3481
|
-
commitTransport: (root, chosen, limits) => commitTransportPolicy(root, chosen, true, undefined, limits),
|
|
3482
|
-
};
|
|
3483
|
-
}
|
|
3484
|
-
/** The structured refusal for a manifest `up -f` cannot use: the located problems of one that does
|
|
3485
|
-
* not validate, or the read failure of one that cannot be read. Both exit 1, as the text path does. */
|
|
3486
|
-
function manifestFileRefusal(e, path) {
|
|
3487
|
-
if (e instanceof ManifestError) {
|
|
3488
|
-
// One line per problem: a parse error's code frame stays out of the sentence.
|
|
3489
|
-
const issues = e.issues.map((issue) => ({ ...issue, message: issue.message.split("\n")[0].replace(/(at line \d+, column \d+):$/, "$1") }));
|
|
3490
|
-
return new CommandFailure("refused", "SCHEMA_INVALID", `the manifest does not validate, so nothing was started: ${issues.map((issue) => formatIssue(e.file, issue)).join("; ")}`, { target: { path, issues }, remedy: "fix each named problem and run the command again" });
|
|
3491
|
-
}
|
|
3492
|
-
// A refusal that already names the problem, such as a directory given as the manifest, keeps its
|
|
3493
|
-
// own sentence and remedy, as the text path prints them.
|
|
3494
|
-
if (e instanceof CommandFailure)
|
|
3495
|
-
return e;
|
|
3496
|
-
const code = e?.code;
|
|
3497
|
-
return new UnusableFile(code === "ENOENT" ? `manifest file not found: ${path}` : `the manifest ${path} could not be read (${code ?? e.message})`, { file: path });
|
|
3498
|
-
}
|
|
3499
|
-
/** `cotal up -f cotal.yaml` — bring up a FRESH mesh from a manifest (broker + channels + booted
|
|
3500
|
-
* agents). `up -f` is a broker-CREATION command: `broker.servers` is the bind address for the NEW
|
|
3501
|
-
* local broker, never a connect target. A broker already reachable there (local OR remote) means
|
|
3502
|
-
* fresh boot refusal; an unbindable/remote address makes the broker fail to start (no silent
|
|
3503
|
-
* local fallback). It owns the whole space, so `cotal down` tears it down without an additive
|
|
3504
|
-
* ownership ledger. */
|
|
3505
|
-
async function upManifest(file, opts) {
|
|
3506
|
-
let prepared;
|
|
3507
|
-
try {
|
|
3508
|
-
prepared = loadManifest(resolve(file), opts.logFile);
|
|
3509
|
-
}
|
|
3510
|
-
catch (e) {
|
|
3511
|
-
if (opts.freshTeamBoot)
|
|
3512
|
-
throw new CommandFailure("refused", "SCHEMA_INVALID", "the fresh boot manifest changed or could not be resolved before startup; no broker was started", { target: { path: resolve(file), space: opts.space } });
|
|
3513
|
-
failManifest(e);
|
|
3514
|
-
}
|
|
3515
|
-
if (opts.freshTeamBoot && opts.space !== prepared.manifest.space)
|
|
3516
|
-
throw new CommandFailure("refused", "CONFLICT", "the fresh boot manifest no longer names the selected space; no broker was started", { target: { selectedSpace: opts.space, declaredSpace: prepared.manifest.space } });
|
|
3517
|
-
refuseManifestSpaceMismatch(prepared, opts.space);
|
|
3518
|
-
// The auth-mode sources (flags vs manifest) must AGREE — any mismatch names both sources and the
|
|
3519
|
-
// exact correction in one sentence (a no-fallback identity decision, never a bare enum error).
|
|
3520
|
-
const declared = prepared.manifest.broker?.auth;
|
|
3521
|
-
const declaredStr = declared === undefined ? '"static" (the unset default)' : JSON.stringify(declared);
|
|
3522
|
-
if (opts.open && declared === "user") {
|
|
3523
|
-
if (opts.freshTeamBoot)
|
|
3524
|
-
throw new CommandFailure("refused", "CONFLICT", "--open contradicts this manifest's user-auth mode; no trust or broker was changed", { target: { space: prepared.manifest.space } });
|
|
3525
|
-
console.error(c.red('✗ --open contradicts this manifest\'s broker.auth: "user" - a user-auth space cannot run unauthenticated. Drop --open, or change the manifest.'));
|
|
3526
|
-
process.exit(1);
|
|
3527
|
-
}
|
|
3528
|
-
if (opts.userAuth && declared !== "user") {
|
|
3529
|
-
if (opts.freshTeamBoot)
|
|
3530
|
-
throw new CommandFailure("refused", "CONFLICT", "--user-auth contradicts this manifest's declared auth mode; no trust or broker was changed", { target: { space: prepared.manifest.space } });
|
|
3531
|
-
stderrLine("✗ ", `--user-auth requires manifest broker.auth: "user" (this manifest's broker.auth is ${declaredStr}). Either set broker.auth: "user" in the manifest, or drop --user-auth.`, c.red);
|
|
3532
|
-
process.exit(1);
|
|
3533
|
-
}
|
|
3534
|
-
if (opts.idp && declared !== "user") {
|
|
3535
|
-
if (opts.freshTeamBoot)
|
|
3536
|
-
throw new CommandFailure("refused", "CONFLICT", "--idp needs this manifest's user-auth mode; no trust or broker was changed", { target: { space: prepared.manifest.space } });
|
|
3537
|
-
stderrLine("✗ ", `--idp is for user-auth spaces (this manifest's broker.auth is ${declaredStr}) - set broker.auth: "user" in the manifest, or drop --idp.`, c.red);
|
|
3538
|
-
process.exit(1);
|
|
3539
|
-
}
|
|
3540
|
-
const idpProblem = opts.idp === undefined ? undefined : idpUrlProblem(opts.idp, "--idp");
|
|
3541
|
-
if (idpProblem) {
|
|
3542
|
-
if (opts.freshTeamBoot)
|
|
3543
|
-
throw new CommandFailure("refused", "SCHEMA_INVALID", idpProblem, { target: { space: prepared.manifest.space } });
|
|
3544
|
-
stderrLine("✗ ", `${idpProblem}`, c.red);
|
|
3545
|
-
process.exit(1);
|
|
3546
|
-
}
|
|
3547
|
-
const serverProblems = opts.server === undefined ? [] : serverUrlProblems(opts.server, "--server");
|
|
3548
|
-
if (serverProblems.length) {
|
|
3549
|
-
if (opts.freshTeamBoot)
|
|
3550
|
-
throw new CommandFailure("refused", "SCHEMA_INVALID", serverProblems.join("; "), { target: { space: prepared.manifest.space } });
|
|
3551
|
-
for (const problem of serverProblems)
|
|
3552
|
-
stderrLine("✗ ", `${problem}`, c.red);
|
|
3553
|
-
process.exit(1);
|
|
3554
|
-
}
|
|
3555
|
-
// Each entry of a list is checked above; the start still needs one address, before any parse of it.
|
|
3556
|
-
const list = bindListRefusal(opts.freshTeamBoot ? "team boot" : "up -f", file, prepared.manifest.space, opts.server, prepared.manifest.broker?.servers);
|
|
3557
|
-
if (list)
|
|
3558
|
-
throw list;
|
|
3559
|
-
// Apply CLI overrides to one effective manifest (flag > manifest > default) so render + seed +
|
|
3560
|
-
// broker + launch all agree on the same values.
|
|
3561
|
-
const { prepared: eff, hostSource, serverSource } = applyUpOverrides(prepared, opts);
|
|
3562
|
-
const m = eff.manifest;
|
|
3563
|
-
if (m.broker?.logFile === undefined && (opts.logfileSizeLimit !== undefined || opts.logfileMaxNum !== undefined))
|
|
3564
|
-
throw new CommandFailure("refused", "USAGE_INVALID", "--logfile-size-limit and --logfile-max-num require --log-file or broker.logFile in the manifest", { remedy: "pass --log-file <path>, set broker.logFile in the manifest, or omit the rotation flags" });
|
|
3565
|
-
const host = m.broker?.host ?? "127.0.0.1";
|
|
3566
|
-
// Same bind-vs-probe reconciliation as the flag path: a manifest that sets `broker.host` without
|
|
3567
|
-
// an explicit `broker.servers` would otherwise bind one address and be probed at another.
|
|
3568
|
-
const server = m.broker?.host ? reconcileHostAndServer(m.broker.host, m.broker?.servers, hostSource, serverSource) : (m.broker?.servers ?? DEFAULT_SERVER);
|
|
3569
|
-
assertTlsIntentServed(server, opts.transport, opts.server !== undefined ? "--server" : "the manifest's broker.servers");
|
|
3570
|
-
// A --tls-cert broker serves TLS only, so its address says tls://, as a bare up requires of --server.
|
|
3571
|
-
if (opts.transport.kind === "tls-required" && server.split(",").some((url) => /^nats:\/\//i.test(url.trim())))
|
|
3572
|
-
throw new CommandFailure("refused", "USAGE_INVALID", `--tls-cert serves the broker over TLS, so ${opts.server !== undefined ? "--server" : "the manifest's broker.servers"} must be a tls:// address; nothing was started or written`, {
|
|
3573
|
-
target: { space: m.space, server: brokerAddressForDisplay(server) ?? "not displayable" },
|
|
3574
|
-
remedy: opts.server !== undefined ? `pass --server ${tlsAddress(server)}` : `set broker.servers to ${tlsAddress(server)} in ${file}`,
|
|
3575
|
-
});
|
|
3576
|
-
const open = m.broker?.auth === false; // default is auth
|
|
3577
|
-
const userAuth = m.broker?.auth === "user" ? { idpUrl: m.broker.idp } : undefined;
|
|
3578
|
-
const runtime = m.runtime ?? "pty";
|
|
3579
|
-
if (open && (m.defaults?.deliveryClass === "durable" || m.channels.some((channel) => channel.deliveryClass === "durable")))
|
|
3580
|
-
throw new CommandFailure("refused", "UNSUPPORTED", "this open manifest explicitly requests durable channel delivery, but the open broker has no delivery daemon; no channel metadata or broker was written", { target: { space: m.space, defaultDurable: m.defaults?.deliveryClass === "durable", channels: m.channels.filter((channel) => channel.deliveryClass === "durable").map((channel) => channel.name) }, remedy: "use static/user authentication for durable delivery, or declare live delivery for an open mesh" });
|
|
3581
|
-
// The address this manifest names is held by the same rule as a `--server` on the flag path: a
|
|
3582
|
-
// stopped space keeps its registered address, and a second stack started there answers for both
|
|
3583
|
-
// registrations. A fresh team boot has its own refusal below, so this is the ordinary `up -f`.
|
|
3584
|
-
if (!opts.freshTeamBoot)
|
|
3585
|
-
refuseRegisteredAddress(server, m.space, opts.server !== undefined
|
|
3586
|
-
? `start this one at another address with \`cotal up -f ${file} --server nats://${host}:<port>\``
|
|
3587
|
-
: `point broker.servers in ${file} at another address`);
|
|
3588
|
-
if (opts.freshTeamBoot) {
|
|
3589
|
-
const other = loadMeshes().filter((row) => row.space !== m.space && row.server === server);
|
|
3590
|
-
if (other.length)
|
|
3591
|
-
throw new CommandFailure("refused", "CONFLICT", "another local registration names this exact broker address; fresh team boot did not create a listener over its recorded target", { target: { space: m.space, server: brokerAddressForDisplay(server) ?? "not displayable", otherSpaces: other.map((row) => row.space) }, remedy: "inspect both registrations and their native brokers; exact-address conflicts block creation, while no conflict does not prove exclusivity" });
|
|
3592
|
-
}
|
|
3593
|
-
if (opts.freshTeamBoot) {
|
|
3594
|
-
assertFreshTeamBootOwnership(cotalRoot(), m.space, open ? "open" : userAuth ? "user" : "auth");
|
|
3595
|
-
await assertFreshTeamBindAvailable(server, host, m.space);
|
|
3596
|
-
}
|
|
3597
|
-
// A manifest needs its manager to boot declared agents.
|
|
3598
|
-
if (opts.noManager && eff.agents.length)
|
|
3599
|
-
throw new FlagValueRefusal(`--no-manager cannot launch this manifest: it declares ${eff.agents.length} agent(s), and a manifest's agents are booted by its manager (which --no-manager omits)`, "drop --no-manager, or use a broker-only manifest with no agents");
|
|
3600
|
-
const effectiveNoManager = Boolean(opts.noManager);
|
|
3601
|
-
// The open-mesh refusal must be RE-STATED here, not only against the CLI `--open` flag: on this
|
|
3602
|
-
// path openness comes from the MANIFEST (`broker.auth: false`), which the flag-level guard cannot
|
|
3603
|
-
// see. Without it, `cotal up -f open.yaml --rotate-sys` boots an open broker, exits 0 and rotates
|
|
3604
|
-
// nothing: a rotation ask answered with silent success, the exact failure class this change
|
|
3605
|
-
// exists to remove. Before the dry-run print and before anything boots.
|
|
3606
|
-
if (opts.rotateSys && open)
|
|
3607
|
-
throw new FlagValueRefusal("--rotate-sys is for auth meshes: this manifest sets broker.auth: false (open), so there is no system account or $SYS credentials to rotate, and nothing was started", "drop --rotate-sys for this open manifest");
|
|
3608
|
-
// Before the dry-run print and before connector preflight or any write, as the refusals above.
|
|
3609
|
-
if (!opts.storeDir)
|
|
3610
|
-
refuseUnnamedLastStore(cotalPath("nats"));
|
|
3611
|
-
else
|
|
3612
|
-
refuseMissingNamedStore(resolve(opts.storeDir));
|
|
3613
|
-
if (userAuth)
|
|
3614
|
-
await preflightUserStack(cotalRoot(), m.space, userAuth.idpUrl);
|
|
3615
|
-
checkStartStore(opts.storeDir, m.space);
|
|
3616
|
-
// Preview and apply only probe a runtime when starting a manager.
|
|
3617
|
-
try {
|
|
3618
|
-
if (!effectiveNoManager)
|
|
3619
|
-
await preflightRuntime(runtime);
|
|
3620
|
-
}
|
|
3621
|
-
catch (error) {
|
|
3622
|
-
throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", `the requested runtime did not pass preflight; ${opts.freshTeamBoot ? "no fresh boot intent or broker was started" : "no broker was started"}`, { target: { space: m.space, runtime }, remedy: error instanceof Error ? error.message : "inspect the selected runtime provider" });
|
|
3623
|
-
}
|
|
3624
|
-
if (opts.dryRun) {
|
|
3625
|
-
// Dial-host SAN must refuse here too (S6). The real route runs assertServesDialHost after
|
|
3626
|
-
// the plan is computed; dry-run used to return before that check and green-lit a launch
|
|
3627
|
-
// the applying command refuses. Validate against the effective server; still no writes.
|
|
3628
|
-
// Announce only AFTER the dial-host check so a wrong-SAN dry-run does not print TLS: serving.
|
|
3629
|
-
assertServesDialHost(opts.transport, new URL(server).hostname);
|
|
3630
|
-
// Connector preflight on the dry-run path too (#315): the real route refuses a manifest at
|
|
3631
|
-
// preflightConnectors before anything boots; a dry run that plans a launch the applying
|
|
3632
|
-
// command refuses is the same green-lit-a-refusal failure class.
|
|
3633
|
-
const dryConn = await preflightConnectors(prepared);
|
|
3634
|
-
if (dryConn) {
|
|
3635
|
-
stderrLine("✗ ", `connector preflight failed: ${dryConn}`, c.red);
|
|
3636
|
-
process.exit(1);
|
|
3637
|
-
}
|
|
3638
|
-
if (opts.transport.kind === "tls-required")
|
|
3639
|
-
announceTransport(opts.transport);
|
|
3640
|
-
console.log(renderUpPlan(eff, server));
|
|
3641
|
-
// The omission is part of the plan (#1417): a dry run that lists a manager the real boot
|
|
3642
|
-
// will not start is the exact "green-lit a launch the applying command refuses" failure.
|
|
3643
|
-
if (effectiveNoManager)
|
|
3644
|
-
console.log(c.dim(" no manager will start on this host (--no-manager): broker, channels and, in auth mode, the delivery daemon come up, and no agents launch from here"));
|
|
3645
|
-
return;
|
|
3646
|
-
}
|
|
3647
|
-
// up -f never adopts a running broker. The old spawn -f route is no longer a manifest deploy.
|
|
3648
|
-
if (await isReachable(server)) {
|
|
3649
|
-
if (opts.freshTeamBoot)
|
|
3650
|
-
throw new CommandFailure("refused", "CONFLICT", "the selected address already has a broker; fresh boot did not adopt it or start a competing listener", { target: { space: m.space, server: brokerAddressForDisplay(server) ?? "not displayable" }, remedy: "inspect the existing broker and selected local records, or use another prepared address" });
|
|
3651
|
-
// This folder's own mesh for the manifest's space is named as running, as a bare `up` names it,
|
|
3652
|
-
// with the routes that change it instead of the advice for a foreign broker.
|
|
3653
|
-
if (loadMeshes().some((row) => row.server === server && row.root === cotalRoot() && row.space === m.space)) {
|
|
3654
|
-
stderrLine("✗ ", `mesh "${m.space}" is already running at ${brokerAddressForDisplay(server) ?? "its address"} from this folder - \`up -f\` boots a fresh mesh and does not apply a manifest to a running one; stop it with \`cotal down\`, then retry your original command`, c.red);
|
|
3655
|
-
process.exit(1);
|
|
3656
|
-
}
|
|
3657
|
-
stderrLine("✗ ", `${brokerAddressForDisplay(server) ?? "selected address"} already has a broker - a fresh boot will not adopt it. Stop the owned stack or select another address; team deploy supports only all-new channel cards, not agent apply.`, c.red);
|
|
3658
|
-
process.exit(1);
|
|
3659
|
-
}
|
|
3660
|
-
await assertBrokerAddressFree(server, `${displayCmd()} up -f ${shellWord(file)}`, host);
|
|
3661
|
-
// Connectors + their required binaries must exist before any mutation (no fallback).
|
|
3662
|
-
const conn = await preflightConnectors(prepared);
|
|
3663
|
-
if (conn) {
|
|
3664
|
-
if (opts.freshTeamBoot)
|
|
3665
|
-
throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", "connector preflight failed before the fresh boot intent; no native effect was requested", { target: { space: m.space }, remedy: conn });
|
|
3666
|
-
stderrLine("✗ ", `connector preflight failed: ${conn}`, c.red);
|
|
3667
|
-
process.exit(1);
|
|
3668
|
-
}
|
|
3669
|
-
if (opts.freshTeamBoot) {
|
|
3670
|
-
assertFreshTeamBootOwnership(cotalRoot(), m.space, open ? "open" : userAuth ? "user" : "auth");
|
|
3671
|
-
await assertFreshTeamBindAvailable(server, host, m.space);
|
|
3672
|
-
}
|
|
3673
|
-
const deploymentId = genRunId();
|
|
3674
|
-
if (opts.freshTeamBoot) {
|
|
3675
|
-
try {
|
|
3676
|
-
writeFreshTeamAttempt(cotalRoot(), { schemaVersion: 1, kind: "fresh-team-attempt", deploymentId, space: m.space, root: cotalRoot(), server, authMode: open ? "open" : userAuth ? "user" : "auth", manifestPath: resolve(file), createdAt: new Date().toISOString() });
|
|
3677
|
-
}
|
|
3678
|
-
catch {
|
|
3679
|
-
throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "fresh boot intent creation or its durability did not confirm; no trust preparation, launch spec or listener was requested", { target: { space: m.space, deploymentId, root: cotalRoot(), intentPath: join(cotalRoot(), ".cotal", `team-boot-attempt-${deploymentId}.json`) }, remedy: "inspect the exact intent path before deciding whether any further boot can be attempted" });
|
|
3680
|
-
}
|
|
3681
|
-
}
|
|
3682
|
-
// USER-AUTH manifest: the agents run under the LOGGED-IN operator's owner, and the launch spec
|
|
3683
|
-
// (consumed by the manager at boot) must carry it — so resolve it NOW. On a fresh mesh the
|
|
3684
|
-
// derivation material doesn't exist yet; ensure it just-in-time (authSetup + prepareServer are
|
|
3685
|
-
// idempotent ensure-* — the same contract the refresh-heal path already rides). Not logged in /
|
|
3686
|
-
// no provider = the exact recovery sentence, before anything boots.
|
|
3687
|
-
let owner;
|
|
3688
|
-
if (userAuth) {
|
|
3689
|
-
try {
|
|
3690
|
-
mkdirSync(cotalPath("nats"), { recursive: true, mode: 0o700 });
|
|
3691
|
-
// NO `rotateSys` here on purpose: this is an owner-derivation pre-resolve that runs BEFORE the
|
|
3692
|
-
// real boot, and the boot below carries the flag. Rotating in both would burn two generations
|
|
3693
|
-
// per `up -f --rotate-sys` and retire the account the first pass just minted creds against.
|
|
3694
|
-
const setup = await authSetup(cotalPath("nats"), server, m.space, host, userAuth, assertServesDialHost(opts.transport, new URL(server).hostname), false, undefined, opts.freshTeamBoot);
|
|
3695
|
-
owner = await resolveAuthProvider().ownerForLogin({ store: workspaceSecretStore(cotalRoot()), dir: setup.stateDir, space: m.space });
|
|
3696
|
-
}
|
|
3697
|
-
catch (e) {
|
|
3698
|
-
if (opts.freshTeamBoot)
|
|
3699
|
-
throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "the fresh user-auth owner preparation did not confirm; trust or provider state may have changed, but no launch spec or listener was requested", { target: { space: m.space, deploymentId, root: cotalRoot() }, remedy: "inspect the retained boot intent, trust state and login before deciding another action; do not repeat an uncertain preparation" });
|
|
3700
|
-
stderrLine("✗ ", `${e.message}`, c.red);
|
|
3701
|
-
process.exit(1);
|
|
3702
|
-
}
|
|
3703
|
-
}
|
|
3704
|
-
// The resolved launch spec is written FIRST so the ONE control-plane manager that comes up with
|
|
3705
|
-
// the broker (inside startMeshDetached) carries it. Exactly one manager serves a space (the
|
|
3706
|
-
// singleton lease): a second `supervise` started here for the launch would race the plain one for
|
|
3707
|
-
// the lease — the loser refuses, so either the agents never boot or the incumbent is orphaned
|
|
3708
|
-
// behind an overwritten pid file. The manager materializes each transient persona and mints creds
|
|
3709
|
-
// from the resolved policy — never re-reading a file for authority.
|
|
3710
|
-
if (opts.freshTeamBoot) {
|
|
3711
|
-
assertFreshTeamBootOwnership(cotalRoot(), m.space, open ? "open" : userAuth ? "user" : "auth", { deploymentId, server, manifestPath: resolve(file) });
|
|
3712
|
-
try {
|
|
3713
|
-
await assertFreshTeamBindAvailable(server, host, m.space);
|
|
3714
|
-
}
|
|
3715
|
-
catch {
|
|
3716
|
-
throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "the fresh boot's bind address was not confirmed after owner preparation; no launch spec or listener was requested, but its retained intent and any prepared trust were not discarded", { target: { space: m.space, deploymentId, server: brokerAddressForDisplay(server) ?? "not displayable" }, remedy: "inspect the exact retained intent, trust state and address before deciding another boot; this bind probe does not reserve the listener" });
|
|
3717
|
-
}
|
|
3718
|
-
}
|
|
3719
|
-
let specPath;
|
|
3720
|
-
try {
|
|
3721
|
-
specPath = writeLaunchSpec(cotalRoot(), buildLaunchSpec(eff, deploymentId, owner));
|
|
3722
|
-
}
|
|
3723
|
-
catch (error) {
|
|
3724
|
-
if (opts.freshTeamBoot)
|
|
3725
|
-
throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "the fresh boot intent was recorded, but launch-spec creation did not confirm its outcome; no broker launch was attempted and the intent remains for inspection", { target: { space: m.space, deploymentId, root: cotalRoot() }, remedy: "inspect the original intent and launch-spec path before another boot; no effect was retried" });
|
|
3726
|
-
throw error;
|
|
3727
|
-
}
|
|
3728
|
-
// Ordinary up can reconcile a leftover manager. Fresh team boot must not signal one: its
|
|
3729
|
-
// stricter prewrite gate required no manager record at all, and a later contender wins
|
|
3730
|
-
// neither stop authority nor permission to replace it.
|
|
3731
|
-
if (!opts.freshTeamBoot) {
|
|
3732
|
-
await stopManager(m.space);
|
|
3733
|
-
clearManagerArtifacts(m.space);
|
|
3734
|
-
}
|
|
3735
|
-
let pid;
|
|
3736
|
-
let controlPlane = false;
|
|
3737
|
-
let authService = true;
|
|
3738
|
-
let deliveryResponderBound = null;
|
|
3739
|
-
try {
|
|
3740
|
-
// `m.broker?.host`, not the defaulted `host`: same reason as the flag path — only a host the
|
|
3741
|
-
// manifest actually declared is an exposure decision worth persisting.
|
|
3742
|
-
({ pid, controlPlane, authService, deliveryResponderBound } = await startMeshDetached({ transport: opts.transport, server, space: m.space, open, userAuth, rotateSys: opts.rotateSys, host: m.broker?.host, logFile: m.broker?.logFile, logfileSizeLimit: m.broker?.logfileSizeLimit, logfileMaxNum: m.broker?.logfileMaxNum, seed: manifestToChannels(eff), runtime, launch: specPath, maxSessions: opts.maxSessions, noManager: effectiveNoManager, quietBoot: opts.freshTeamBoot, ...(opts.storeDir ? { storeDir: opts.storeDir } : {}) }));
|
|
3743
|
-
}
|
|
3744
|
-
catch (e) {
|
|
3745
|
-
if (opts.freshTeamBoot)
|
|
3746
|
-
throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "the fresh broker startup did not confirm completion after its launch spec was written; the listener or control plane may have changed state and the boot was not retried", { target: { space: m.space, deploymentId, launchSpec: specPath }, changed: [{ kind: "launch-spec-written", path: specPath }], remedy: "inspect this exact run and the recorded local listener, manager and auth state before another boot" });
|
|
3747
|
-
// A classified failure, such as a certificate this client refuses, keeps its code and next step.
|
|
3748
|
-
if (isCommandFailure(e))
|
|
3749
|
-
throw e;
|
|
3750
|
-
stderrLine("✗ ", `${e.message}`, c.red);
|
|
3751
|
-
process.exit(1);
|
|
3752
|
-
}
|
|
3753
|
-
// Transport committed inside startMeshDetached before delivery (S5+S9).
|
|
3754
|
-
let summaryRecorded = false;
|
|
3755
|
-
try {
|
|
3756
|
-
writeFreshTeamSummary(cotalRoot(), {
|
|
3757
|
-
schemaVersion: 1, kind: "fresh-team-summary", deploymentId, space: m.space,
|
|
3758
|
-
root: cotalRoot(), server, authMode: open ? "open" : userAuth ? "user" : "auth", brokerPid: pid, manifestPath: resolve(file),
|
|
3759
|
-
requestedAgents: eff.agents.map((agent) => agent.name),
|
|
3760
|
-
declaredChannels: m.channels.map((channel) => channel.name),
|
|
3761
|
-
recordedAt: new Date().toISOString(), managerRequested: !effectiveNoManager,
|
|
3762
|
-
controlPlaneReturned: controlPlane, authServiceReturned: authService, deliveryResponderBound,
|
|
3763
|
-
agentReadiness: "not-checked",
|
|
3764
|
-
});
|
|
3765
|
-
summaryRecorded = true;
|
|
3766
|
-
}
|
|
3767
|
-
catch {
|
|
3768
|
-
console.error(c.yellow(`! the native fresh boot returned but its local team summary could not be recorded (run ${deploymentId}); do not repeat the boot just to recreate the summary`));
|
|
3769
|
-
}
|
|
3770
|
-
if (opts.freshTeamBoot) {
|
|
3771
|
-
if (!authService || !controlPlane || !summaryRecorded || (!open && deliveryResponderBound !== true))
|
|
3772
|
-
throw new CommandFailure("partial", "OPERATION_PARTIAL", "the fresh broker started, but its control plane, auth service, delivery responder or local deployment summary did not confirm readiness; the same boot was not retried", { target: { space: m.space, deploymentId, brokerPid: pid, launchSpec: specPath }, changed: [{ kind: "broker-started", pid, server: brokerAddressForDisplay(server) ?? "not displayable" }, { kind: "launch-spec-written", path: specPath }, ...(summaryRecorded ? [{ kind: "fresh-summary-recorded", deploymentId }] : [])], remedy: "inspect this exact run, the local broker and manager, and any retained summary before deciding another action" });
|
|
3773
|
-
const inheritedAccess = eff.agents.flatMap((agent) => {
|
|
3774
|
-
const access = agent.inherited;
|
|
3775
|
-
return access.capabilities.length || access.subscribe.length || access.allowSubscribe.length || access.allowPublish.length
|
|
3776
|
-
? [{ agent: agent.name, persona: agent.persona ?? null, capabilities: access.capabilities, subscribe: access.subscribe, allowSubscribe: access.allowSubscribe, allowPublish: access.allowPublish }]
|
|
3777
|
-
: [];
|
|
3778
|
-
});
|
|
3779
|
-
let currentSelection = null;
|
|
3780
|
-
let selectionChecked = false;
|
|
3781
|
-
try {
|
|
3782
|
-
currentSelection = getCurrent() ?? null;
|
|
3783
|
-
selectionChecked = true;
|
|
3784
|
-
}
|
|
3785
|
-
catch { /* The returned broker receipt remains usable without a current-default read. */ }
|
|
3786
|
-
const result = { kind: "fresh-team-boot", space: m.space, root: cotalRoot(), deploymentId, server: brokerAddressForDisplay(server) ?? "not displayable", brokerPid: pid, manifestPath: resolve(file), runtime, currentSelection, selectionChecked,
|
|
3787
|
-
mode: open ? "open" : userAuth ? "user-auth" : "static-auth", controlPlaneReturned: controlPlane, authServiceReturned: authService, deliveryResponderBound, summaryRecorded,
|
|
3788
|
-
requestedAgents: eff.agents.map((agent) => ({ name: agent.name, application: agent.agentType, role: agent.role ?? null })),
|
|
3789
|
-
declaredChannels: m.channels.map((channel) => ({ name: channel.name, deliveryClass: channel.deliveryClass ?? null, replay: channel.replay ?? null, replayWindow: channel.replayWindow ?? null })), inheritedAccess, agentReadiness: "not-checked" };
|
|
3790
|
-
writeResult(opts.presentation ?? "rich", { command: "team boot", target: { space: m.space, root: cotalRoot(), deploymentId }, result, completeness: "partial", warnings: [...eff.warnings.map((warning) => ({ code: "MANIFEST_WARNING", target: { agent: warning.agent }, message: warning.message })), ...(!selectionChecked ? [{ code: "CURRENT_SELECTION_UNAVAILABLE", target: { space: m.space }, message: "The current default space could not be read after boot; no default was inferred." }] : [])] }, (data) => ({ sections: [
|
|
3791
|
-
{ title: "Fresh team broker returned", blocks: [{ kind: "fields", rows: [["Space", data.space], ["Deployment", data.deploymentId], ["Root", data.root], ["Broker", data.server], ["Broker PID", String(data.brokerPid)], ["Manifest", data.manifestPath], ["Auth mode", data.mode], ["Runtime request", data.runtime], ["Current default", data.selectionChecked ? data.currentSelection ?? "none selected" : "not checked"], ["Control-plane ensure", "returned"], ["Delivery responder", data.deliveryResponderBound === null ? "not required" : "bound when boot returned"], ["Membership material", "not checked by this receipt"], ["Auth service", data.mode === "user-auth" ? "returned at boot" : "not required"], ["Launch summary", "recorded"], ["Agent readiness", "not checked"]] }, { kind: "lines", lines: ["The manager was requested as part of boot; this receipt does not establish agent joins, current broker health or whole-stack stop authority."] }] },
|
|
3792
|
-
{ title: "Requested topology", blocks: [data.requestedAgents.length ? { kind: "table", columns: [{ key: "name", label: "Agent" }, { key: "application", label: "Application" }, { key: "role", label: "Role" }], rows: data.requestedAgents.slice(0, 100).map((agent) => ({ ...agent, role: agent.role ?? "none" })) } : { kind: "lines", lines: ["No agents requested."] }, data.declaredChannels.length ? { kind: "table", columns: [{ key: "name", label: "Channel" }, { key: "delivery", label: "Declared delivery" }, { key: "replay", label: "Declared replay" }, { key: "window", label: "Declared window" }], rows: data.declaredChannels.slice(0, 100).map((channel) => ({ name: `#${channel.name}`, delivery: channel.deliveryClass ?? "not declared", replay: channel.replay === null ? "not declared" : channel.replay ? "on" : "off", window: channel.replayWindow ?? "not declared" })) } : { kind: "lines", lines: ["No channels declared."] }, ...((data.requestedAgents.length > 100 || data.declaredChannels.length > 100) ? [{ kind: "lines", lines: ["Showing at most 100 declared agents and channels; the saved summary retains all names."] }] : [])] },
|
|
3793
|
-
...(data.inheritedAccess.length ? [{ title: "Persona-inherited access", blocks: [{ kind: "table", columns: [{ key: "agent", label: "Agent" }, { key: "persona", label: "Persona" }, { key: "scope", label: "Outside manifest channels" }], rows: data.inheritedAccess.slice(0, 100).map((row) => ({ agent: row.agent, persona: row.persona ?? "none", scope: [row.capabilities.length ? `capabilities ${row.capabilities.join(",")}` : "", row.subscribe.length ? `subscribe ${row.subscribe.join(",")}` : "", row.allowSubscribe.length ? `read ${row.allowSubscribe.join(",")}` : "", row.allowPublish.length ? `post ${row.allowPublish.join(",")}` : ""].filter(Boolean).join(" · ") })) }, { kind: "lines", lines: [...(data.inheritedAccess.length > 100 ? ["Additional inherited scopes are not shown in this terminal view."] : []), "These scopes came from referenced personas and are not limited to channels declared by this manifest."] }] }] : []),
|
|
3794
|
-
{ title: "Next", blocks: [{ kind: "commands", items: [{ command: `cotal team show ${data.deploymentId}`, description: "Read this local launch summary" }, { command: `cotal watch --space ${data.space}`, description: "Observe the selected mesh" }, { command: `cotal down --space ${data.space} --dry-run`, description: "Inspect local stop records without stopping the stack" }] }] },
|
|
3795
|
-
] }));
|
|
3796
|
-
return;
|
|
3797
|
-
}
|
|
3798
|
-
console.log(c.green(`✓ mesh "${m.space}" up at ${server}`) + c.dim(` (broker pid ${pid})`));
|
|
3799
|
-
console.log(c.dim(` seeded ${m.channels.length} channel(s): ${m.channels.map((ch) => "#" + ch.name).join(", ")}`));
|
|
3800
|
-
if (summaryRecorded)
|
|
3801
|
-
console.log(c.dim(` fresh deployment ${deploymentId} recorded; \`cotal team show ${deploymentId}\` reads its launch summary, not live ownership`));
|
|
3802
|
-
// Never claim a launch the control plane can't deliver: the manager carries the launch spec, so a
|
|
3803
|
-
// degraded control plane (announced above) means the agents are NOT coming up.
|
|
3804
|
-
if (effectiveNoManager) {
|
|
3805
|
-
// Truthful summary for the broker-only boot (#1417): nothing was omitted by accident, and the
|
|
3806
|
-
// agents this manifest declares (none — a declaring manifest is refused above) launch elsewhere.
|
|
3807
|
-
console.log(c.dim(` broker-only (--no-manager): no manager started on this host - run \`cotal supervise --space ${m.space} --server ${server}\` from a manager host to manage agents`));
|
|
3808
|
-
}
|
|
3809
|
-
else if (controlPlane) {
|
|
3810
|
-
// U6: on a user mesh the agents run under the OPERATOR's identity — say whose they are.
|
|
3811
|
-
// The manager launches them after this command returns, so nothing here knows whether one joined:
|
|
3812
|
-
// no success mark, and name where the outcome shows.
|
|
3813
|
-
console.log(` launch pending: the manager (${runtime}) starts ${eff.agents.length} agent(s)${owner ? ` as you (owner ${owner})` : ""} after this returns; up -f does not wait for them to join`);
|
|
3814
|
-
console.log(c.dim(` who joined: \`cotal ps --space ${m.space}\` · a failed launch and its reason: ${managerLogDisplayPath(m.space)}`));
|
|
3815
|
-
}
|
|
3816
|
-
else {
|
|
3817
|
-
stderrLine("✗ ", `${eff.agents.length} agent(s) NOT launched - the control plane did not come up (see above)`, c.red);
|
|
3818
|
-
}
|
|
3819
|
-
// Loud summary: any persona-inherited access an `include` manifest dragged in, plus warnings.
|
|
3820
|
-
const inherited = renderInherited(eff);
|
|
3821
|
-
if (inherited)
|
|
3822
|
-
console.log("\n" + inherited);
|
|
3823
|
-
if (eff.warnings.length)
|
|
3824
|
-
console.log("\n" + renderWarnings(eff.warnings));
|
|
3825
|
-
const downRoute = opts.root ? `from ${oneLine(cotalRoot())}, run \`cotal down\`` : "`cotal down`";
|
|
3826
|
-
console.log(c.dim(`\nWatch: \`cotal watch --space ${m.space}\` (terminal) · Dashboard: configure the explicit web service preset separately · Tear down: ${downRoute}`));
|
|
3827
|
-
// A declared-user-auth manifest whose auth service never became ready, or a degraded control
|
|
3828
|
-
// plane: the mesh is up + recorded, but this launch did not deliver what it declared — exit
|
|
3829
|
-
// non-zero so CI/wrappers don't read success (the consequence line printed at the failure above).
|
|
3830
|
-
if (!authService || !controlPlane || !summaryRecorded)
|
|
3831
|
-
process.exitCode = 1;
|
|
3832
|
-
}
|
|
3833
|
-
/** Return a copy of the prepared manifest with CLI overrides applied to broker/space/runtime, so the
|
|
3834
|
-
* whole launch (render, seed, broker, manager, launch spec) runs against one effective manifest.
|
|
3835
|
-
* A flag names itself. A value that came from the file keeps that file's key, and a value neither
|
|
3836
|
-
* supplied is named by the flag that would supply it. */
|
|
3837
|
-
function applyUpOverrides(prepared, o) {
|
|
3838
|
-
const m = prepared.manifest;
|
|
3839
|
-
const broker = { ...m.broker };
|
|
3840
|
-
if (o.server)
|
|
3841
|
-
broker.servers = o.server;
|
|
3842
|
-
if (o.host)
|
|
3843
|
-
broker.host = o.host;
|
|
3844
|
-
if (o.open)
|
|
3845
|
-
broker.auth = false;
|
|
3846
|
-
if (o.idp)
|
|
3847
|
-
broker.idp = o.idp;
|
|
3848
|
-
if (o.logFile !== undefined)
|
|
3849
|
-
broker.logFile = o.logFile;
|
|
3850
|
-
if (o.logfileSizeLimit !== undefined)
|
|
3851
|
-
broker.logfileSizeLimit = o.logfileSizeLimit;
|
|
3852
|
-
if (o.logfileMaxNum !== undefined)
|
|
3853
|
-
broker.logfileMaxNum = o.logfileMaxNum;
|
|
3854
|
-
return {
|
|
3855
|
-
prepared: {
|
|
3856
|
-
...prepared,
|
|
3857
|
-
manifest: {
|
|
3858
|
-
...m,
|
|
3859
|
-
broker: Object.keys(broker).length ? broker : undefined,
|
|
3860
|
-
runtime: o.runtime ?? m.runtime,
|
|
3861
|
-
},
|
|
3862
|
-
},
|
|
3863
|
-
hostSource: !o.host && m.broker?.host !== undefined ? "broker.host" : "--host",
|
|
3864
|
-
serverSource: !o.server && m.broker?.servers !== undefined ? "broker.servers" : "--server",
|
|
3865
|
-
};
|
|
3866
|
-
}
|
|
3867
|
-
/** Start the CONTROL PLANE alongside the broker: old-manager preflight → delivery daemon (auth
|
|
3868
|
-
* mode only) → detached manager. `up` is the launching command — since `setup` became
|
|
3869
|
-
* configure-only (stage 2b), the whole local stack comes up HERE, so `spawn --detach` /
|
|
3870
|
-
* cotal_spawn find a manager without any setup side effect. Coupled to the broker by the
|
|
3871
|
-
* daemon's watchdog + the `up`/`down` teardown. `mgr` rides through to the manager start — the
|
|
3872
|
-
* `up -f` path hands THE manager its runtime + resolved launch spec here (one manager per space,
|
|
3873
|
-
* so the launch can never be a second supervise). Returns the control plane it ensured, or
|
|
3874
|
-
* `undefined` when it is degraded, so a caller whose output claims a manager (the `up -f` launching
|
|
3875
|
-
* line) can tell the truth. */
|
|
3876
|
-
async function startDeliveryWithBroker(space, server,
|
|
3877
|
-
/**
|
|
3878
|
-
* Whether this listener requires TLS, decided by the CALLER.
|
|
3879
|
-
*
|
|
3880
|
-
* NON-OPTIONAL, for exactly the reason {@link DetachOpts.transport} is. This used to be an
|
|
3881
|
-
* optional `transport` that the callee fell back on `readBrokerPolicy(cotalRoot())` for whenever
|
|
3882
|
-
* it was absent — and the refresh path (#836) never passed it. That path decides the same fact
|
|
3883
|
-
* from the mesh-registry entry AND the live `INFO`, refuses on any disagreement, and then handed
|
|
3884
|
-
* the decision to nobody: a root whose registry records `tlsRequired` while holding no
|
|
3885
|
-
* `broker-policy.json` (registered with `cotal meshes add --tls`, or a mesh that predates the
|
|
3886
|
-
* policy file) relaunched the delivery daemon FLAGLESS against a TLS broker. Nothing looked
|
|
3887
|
-
* wrong, because the daemon still upgrades on the server's unauthenticated INFO — and it holds a
|
|
3888
|
-
* STANDING credential and reconnects unattended, so that exposure repeats with nobody watching.
|
|
3889
|
-
*
|
|
3890
|
-
* A second durable record consulted in the callee is how the caller's copy went silently unused.
|
|
3891
|
-
* One decision, and it arrives as an argument.
|
|
3892
|
-
*/
|
|
3893
|
-
tlsRequired, mgr, afterDelivery, isStopping) {
|
|
3894
|
-
try {
|
|
3895
|
-
const plane = await ensureControlPlane({ space, server, tls: tlsRequired, ...(mgr ?? {}) }, afterDelivery);
|
|
3896
|
-
// #1576: `up` either BINDS the responder or SAYS SO HERE. The delivery daemon is a hard
|
|
3897
|
-
// dependency of spawn, retirement and the durable backstop, and this function used to return `true` for a boot
|
|
3898
|
-
// that started a daemon whose responder never bound — so `cotal up` printed its success banner
|
|
3899
|
-
// over a control plane that could not perform any of the three. The reporter's fleet ran 22
|
|
3900
|
-
// hours in that state. This is not a failure of `up` (live messaging is unaffected and the
|
|
3901
|
-
// responder may still bind), so it does not throw; it states the condition and its consequence.
|
|
3902
|
-
if (plane.responderBound === false)
|
|
3903
|
-
console.error(c.yellow(`! delivery responder did not bind before this boot finished - ${RESPONDER_UNBOUND_CONSEQUENCE}`) +
|
|
3904
|
-
c.dim(`\n The daemon process is running and the wait is open-ended; boot durable joins reconcile by themselves once it binds (agents do NOT need respawning).\n Watch it with \`${displayCmd()} status --components\`.`));
|
|
3905
|
-
return plane;
|
|
3906
|
-
}
|
|
3907
|
-
catch (e) {
|
|
3908
|
-
// A running mesh must report its missing control plane. A foreground stop can remove the
|
|
3909
|
-
// manager while this startup observation is still pending; that is intentional teardown.
|
|
3910
|
-
if (!isStopping?.())
|
|
3911
|
-
reportDegradedControlPlane(e.message);
|
|
3912
|
-
return undefined;
|
|
3913
|
-
}
|
|
3914
|
-
}
|
|
3915
|
-
/** The degraded control plane on stderr: each line of `why`, then its consequence, wrapped to the
|
|
3916
|
-
* terminal as every other warning is. */
|
|
3917
|
-
function reportDegradedControlPlane(why) {
|
|
3918
|
-
const [first, ...rest] = why.split("\n");
|
|
3919
|
-
stderrLine("! ", `control plane degraded: ${first}`, c.dim);
|
|
3920
|
-
for (const line of [...rest, "Spawn and retirement require a functioning control plane."])
|
|
3921
|
-
stderrLine(" ", line, c.dim);
|
|
3922
|
-
}
|
|
3923
|
-
/**
|
|
3924
|
-
* Publish a spawned listener's pid, and bind a maintenance-bound one to its attempt, before anything
|
|
3925
|
-
* waits on it. A launch that dies before its listener serves then leaves `nats.pid` for `cotal down`
|
|
3926
|
-
* and a journal naming the exact process for recovery to adopt or retire. A publish or bind that
|
|
3927
|
-
* throws stops the listener. Both launch modes call it right after the spawn.
|
|
3928
|
-
*/
|
|
3929
|
-
async function recordSpawnedListener(child, startedAt, bound) {
|
|
3930
|
-
if (!child.pid)
|
|
3931
|
-
throw new Error("nats-server spawned with no pid");
|
|
3932
|
-
try {
|
|
3933
|
-
writeSecretFile(cotalPath("stack-home.json"), JSON.stringify({ home: canonicalRoot(homeCotalDir()) }));
|
|
3934
|
-
writePidPair(cotalPath(NATS_PIDFILE), child.pid); // #969/#1238: publish the pair by rename, never torn
|
|
3935
|
-
}
|
|
3936
|
-
catch (error) {
|
|
3937
|
-
// The entry at `nats.pid` may be the one that refused the publish (a directory there fails the
|
|
3938
|
-
// rename), so it is left as found: unrecording would read it and throw over this error.
|
|
3939
|
-
await stopFailedListener(child, false);
|
|
3940
|
-
throw error;
|
|
3941
|
-
}
|
|
3942
|
-
if (!bound)
|
|
3943
|
-
return;
|
|
3944
|
-
if (process.env.COTAL_SMOKE_EXIT_AFTER_RESTORE_LISTENER_SPAWN === "1")
|
|
3945
|
-
process.exit(87);
|
|
3946
|
-
try {
|
|
3947
|
-
bound.onSpawn(child.pid, startedAt);
|
|
3948
|
-
}
|
|
3949
|
-
catch (error) {
|
|
3950
|
-
await stopFailedListener(child);
|
|
3951
|
-
throw error;
|
|
3952
|
-
}
|
|
3953
|
-
}
|
|
3954
|
-
/**
|
|
3955
|
-
* Everything between spawning a listener and serving it: readiness, the broker version read and a
|
|
3956
|
-
* bound listener's identity check. Foreground `up` and {@link startMeshDetached} both call it, so a
|
|
3957
|
-
* guard added here reaches both launch modes (#2924).
|
|
3958
|
-
*
|
|
3959
|
-
* A listener that never answers or whose version read throws is stopped and its `nats.pid` removed
|
|
3960
|
-
* before `up` fails. Nothing has recorded the mesh yet, so a listener left running would hold the
|
|
3961
|
-
* port with no registry entry. A bound listener that fails its identity check is kept: its
|
|
3962
|
-
* maintenance journal is already bound to it.
|
|
3963
|
-
*/
|
|
3964
|
-
async function awaitSpawnedListener(l) {
|
|
3965
|
-
const { child, server, space } = l;
|
|
3966
|
-
let facts;
|
|
3967
|
-
try {
|
|
3968
|
-
if (!(await waitReady(server, l.creds, l.tls, l.log)))
|
|
3969
|
-
throw exitedBeforeReady(l) ?? new Error(`nats-server did not become reachable at ${server} - see ${l.log}`);
|
|
3970
|
-
facts = await brokerVersion(server, space, l.creds);
|
|
3971
|
-
}
|
|
3972
|
-
catch (e) {
|
|
3973
|
-
await stopFailedListener(child);
|
|
3974
|
-
throw e;
|
|
3975
|
-
}
|
|
3976
|
-
if (belowPresenceSafeBroker(facts.version) && facts.presenceFileBacked)
|
|
3977
|
-
console.error(c.yellow(`! nats-server ${facts.version} is below 2.14.5 and the presence bucket of "${space}" is file-backed: it can latch after a stall and close the mesh to new joins (#1356); put a nats-server 2.14.5 or newer on PATH (it wins over the bundled one)`));
|
|
3978
|
-
if (l.boundListener)
|
|
3979
|
-
await l.boundListener.verify();
|
|
3980
|
-
}
|
|
3981
|
-
/** The failure of a listener that exited before it answered: the executable, the exit code or signal
|
|
3982
|
-
* Node observed, and where its output went. Undefined when no exit was observed, so a listener that
|
|
3983
|
-
* only stayed silent keeps an unconfirmed outcome. */
|
|
3984
|
-
function exitedBeforeReady(l) {
|
|
3985
|
-
const { exitCode, signalCode } = l.child;
|
|
3986
|
-
if (exitCode === null && signalCode === null)
|
|
3987
|
-
return undefined;
|
|
3988
|
-
const exit = exitCode !== null ? `exited with code ${exitCode}` : `was stopped by ${signalCode}`;
|
|
3989
|
-
return new CommandFailure("failed", "OPERATION_FAILED", `${natsServerLabel(l.executable)} ${exit} before it answered at ${l.server}; see ${l.log}`, {
|
|
3990
|
-
target: { executable: l.executable.path, ...(exitCode !== null ? { exitCode } : { signal: signalCode }), server: l.server, log: l.log },
|
|
3991
|
-
remedy: listenerExitRemedy(l.executable, l.log),
|
|
3992
|
-
});
|
|
3993
|
-
}
|
|
3994
|
-
/** The next step for a listener that exited before it answered: read its output, then fix a
|
|
3995
|
-
* nats-server found on PATH or take it off PATH, and start again. */
|
|
3996
|
-
function listenerExitRemedy(executable, log) {
|
|
3997
|
-
return executable.source === "path" ? `read ${log}, then fix ${executable.path} or take it off PATH so cotal uses its bundled nats-server, and run \`cotal up\` again` : `read ${log}, then run \`cotal up\` again`;
|
|
3998
|
-
}
|
|
3999
|
-
/**
|
|
4000
|
-
* Everything a launch runs once its listener answers: the space setup, the user-auth service, the
|
|
4001
|
-
* mesh record, the transport commit and the control plane. Foreground `up` and
|
|
4002
|
-
* {@link startMeshDetached} both call it, so the two launch modes cannot drift apart (#2496).
|
|
4003
|
-
*
|
|
4004
|
-
* A fresh boot whose setup throws stops the listener and removes `nats.pid` before rethrowing the
|
|
4005
|
-
* original error. Nothing has recorded the mesh yet, so a listener left running would hold the port
|
|
4006
|
-
* with no registry entry for `cotal down` to reach. A channel seed with an unparseable value fails
|
|
4007
|
-
* here. A resume keeps its listener: its maintenance journal is already bound to it.
|
|
4008
|
-
*/
|
|
4009
|
-
async function serveReadyListener(l) {
|
|
4010
|
-
const { child, server, space, setup, transport } = l;
|
|
4011
|
-
try {
|
|
4012
|
-
if (l.resumeAttempt) {
|
|
4013
|
-
const ordinaryResume = pendingOrdinaryResumes.has(l.resumeAttempt);
|
|
4014
|
-
await recreateMemoryBuckets(server, space, setup, ordinaryResume ? { convertMembership: l.recreateMembershipStore === true } : undefined);
|
|
4015
|
-
}
|
|
4016
|
-
else {
|
|
4017
|
-
await postStart(server, space, setup, l.seedFile, l.recreateIssuedStores, l.recreateMembershipStore, true);
|
|
4018
|
-
}
|
|
4019
|
-
}
|
|
4020
|
-
catch (e) {
|
|
4021
|
-
await stopFailedListener(child);
|
|
4022
|
-
throw e;
|
|
4023
|
-
}
|
|
4024
|
-
// Register the prepared trust before delivery starts. Auth follows delivery's liveness oracle,
|
|
4025
|
-
// then the manager: a crashed auth claim cannot be reclaimed while that oracle is absent.
|
|
4026
|
-
let svc = {
|
|
4027
|
-
ok: setup?.prepared === undefined,
|
|
4028
|
-
...(setup?.prepared ? { userAuth: assertUserAuthInfo(setup.prepared.publicAuth) } : {}),
|
|
4029
|
-
};
|
|
4030
|
-
// Record BEFORE the control plane comes up: the manager's fail-closed mode detection requires
|
|
4031
|
-
// an authoritative registry entry (marker-without-registry is a refused start, not a guess),
|
|
4032
|
-
// so the record must exist by the time it boots. A manager/delivery failure after this leaves
|
|
4033
|
-
// a recorded-but-degraded mesh — the documented, healable posture.
|
|
4034
|
-
// Read the prior host and session limit before replacing the registry entry on resume.
|
|
4035
|
-
const attachHost = attachHostFor(space, l.host);
|
|
4036
|
-
const maxSessions = maxSessionsFor(space, l.maxSessions);
|
|
4037
|
-
try {
|
|
4038
|
-
recordOurMesh({
|
|
4039
|
-
space, server, root: cotalRoot(),
|
|
4040
|
-
mode: setup?.prepared ? "user" : setup ? "auth" : "open",
|
|
4041
|
-
// Record the transport decision even for plaintext. Omit the host unless the operator chose one.
|
|
4042
|
-
tlsRequired: transport.kind === "tls-required",
|
|
4043
|
-
...(svc.userAuth ? { userAuth: svc.userAuth } : {}),
|
|
4044
|
-
...(attachHost ? { attachHost } : {}),
|
|
4045
|
-
...(maxSessions !== undefined ? { maxSessions } : {}),
|
|
4046
|
-
...(l.maxFileStore !== undefined ? { maxFileStore: l.maxFileStore } : {}),
|
|
4047
|
-
storeDir: l.storeDir,
|
|
4048
|
-
ts: new Date().toISOString(),
|
|
4049
|
-
}, "started", l.quietBoot);
|
|
4050
|
-
}
|
|
4051
|
-
catch (e) {
|
|
4052
|
-
await stopFailedListener(child);
|
|
4053
|
-
throw e;
|
|
4054
|
-
}
|
|
4055
|
-
// Commit the policy only for a listener that is up and recorded (S5), and before the control
|
|
4056
|
-
// plane (S9). startDeliveryWithBroker is HANDED the transport decision, so it does not depend on
|
|
4057
|
-
// the file at all.
|
|
4058
|
-
commitTransportPolicy(cotalRoot(), transport, l.quietBoot, server, { authTimeout: setup?.authTimeout, maxPayload: l.maxPayload ?? setup?.maxPayload, accountResolver: setup?.accountResolver });
|
|
4059
|
-
// An open mesh has no delivery daemon. Its mode is passed down because the root can still hold a
|
|
4060
|
-
// static stack's accounts. Class-2 credential renewal is NOT wired here: the MANAGER is the
|
|
4061
|
-
// renewal owner (it is resident in every mesh mode, where a foreground `up` process is not).
|
|
4062
|
-
const controlPlane = await startDeliveryWithBroker(space, server, transport.kind === "tls-required", {
|
|
4063
|
-
open: setup === undefined,
|
|
4064
|
-
onDeliveryExit: l.onDeliveryExit,
|
|
4065
|
-
runtime: l.runtime,
|
|
4066
|
-
launch: l.launch,
|
|
4067
|
-
// The address the broker was bound to. This is what lets `cotal attach` reach this manager
|
|
4068
|
-
// from another machine; without it the attach face stays loopback-only, so exposing terminals
|
|
4069
|
-
// is never a side effect of anything but the operator binding the mesh somewhere reachable.
|
|
4070
|
-
attachHost,
|
|
4071
|
-
maxSessions,
|
|
4072
|
-
managerSeatCap: l.managerSeatCap,
|
|
4073
|
-
noManager: l.noManager,
|
|
4074
|
-
resumeAttempt: l.resumeAttempt,
|
|
4075
|
-
resumeCommit: l.resumeCommit,
|
|
4076
|
-
wsPort: setup?.wsPort, // P2 item 6: the console session client's broker ws port
|
|
4077
|
-
}, async () => {
|
|
4078
|
-
svc = await startUserAuthService(space, server, setup, [...(l.publicExchange ?? []), ...authTimeoutArgs(setup?.authTimeout)], l.quietBoot);
|
|
4079
|
-
if (svc.userAuth)
|
|
4080
|
-
recordOurMesh({ space, server, root: cotalRoot(), mode: "user", userAuth: svc.userAuth, ts: new Date().toISOString() }, "refresh", true);
|
|
4081
|
-
}, l.isStopping);
|
|
4082
|
-
const registered = findMesh(space);
|
|
4083
|
-
if (registered)
|
|
4084
|
-
recordOurMesh(registered, "refresh", true);
|
|
4085
|
-
seedPersonaAfterUp(cotalRoot(), l.quietBoot);
|
|
4086
|
-
return { authService: svc.ok, controlPlane };
|
|
4087
|
-
}
|
|
4088
|
-
/** Prepare the existing broker's local trust, configuration and launch inputs without starting a
|
|
4089
|
-
* listener, auth service, delivery daemon or manager. This is an explicit mutating phase, not a
|
|
4090
|
-
* dry-run or service-adapter planning hook. Its returned setup includes private authority material
|
|
4091
|
-
* for the coordinating caller only; it must not be logged or serialized into a public receipt. */
|
|
4092
|
-
export async function prepareBrokerStart(opts) {
|
|
4093
|
-
const server = opts.server ?? DEFAULT_SERVER;
|
|
4094
|
-
const useAuth = !opts.open;
|
|
4095
|
-
// Belt on the one boot that both renders the broker config and can be reached by any caller: an
|
|
4096
|
-
// open boot skips `authSetup` entirely, so a `rotateSys` arriving here would be dropped in silence
|
|
4097
|
-
// rather than refused. Callers guard this too; this is the seam that cannot be bypassed.
|
|
4098
|
-
if (opts.rotateSys && !useAuth)
|
|
4099
|
-
throw new Error("startMeshDetached: --rotate-sys is for auth meshes; an open mesh has no system account or $SYS credentials to rotate");
|
|
4100
|
-
const space = opts.space ?? folderSpace();
|
|
4101
|
-
ensureRootForSpace(space); // may pin the cwd as this space's root — before any cotalPath use
|
|
4102
|
-
refuseStartOverUserState(Boolean(opts.open), opts.userAuth !== undefined, space);
|
|
4103
|
-
const root = cotalRoot();
|
|
4104
|
-
const storeDir = opts.storeDir ? resolve(opts.storeDir) : cotalPath("nats");
|
|
4105
|
-
if (opts.storeDir)
|
|
4106
|
-
warnForeignStoreEntries(storeDir);
|
|
4107
|
-
if (opts.existingStore) {
|
|
4108
|
-
if (opts.existingStore.named !== storeDir)
|
|
4109
|
-
throw new Error("prepareBrokerStart: the pinned existing store is not the store being prepared");
|
|
4110
|
-
recheckExistingStore(opts.existingStore, { space, storeDir });
|
|
4111
|
-
}
|
|
4112
|
-
else
|
|
4113
|
-
mkdirSync(storeDir, { recursive: true, mode: 0o700 });
|
|
4114
|
-
await claimSpace(space, server, root);
|
|
4115
|
-
const seedFile = opts.seed ?? loadChannelsFile(opts.channels);
|
|
4116
|
-
const host = opts.host ?? "127.0.0.1";
|
|
4117
|
-
// The transport arrives decided. The dial-host SAN is re-checked here because THIS is where the
|
|
4118
|
-
// effective server is finally known — a manifest may name a different host than the flags did, and
|
|
4119
|
-
// a certificate that is valid for one is not thereby valid for the other.
|
|
4120
|
-
const transport = assertServesDialHost(opts.transport, new URL(server).hostname);
|
|
4121
|
-
if (opts.logFile === undefined && (opts.logfileSizeLimit !== undefined || opts.logfileMaxNum !== undefined))
|
|
4122
|
-
throw new Error("rotation bounds require --log-file");
|
|
4123
|
-
const logFile = opts.logFile === undefined ? undefined : resolve(opts.logFile);
|
|
4124
|
-
if (logFile !== undefined)
|
|
4125
|
-
mkdirSync(dirname(logFile), { recursive: true, mode: 0o700 });
|
|
4126
|
-
if (logFile !== undefined) {
|
|
4127
|
-
let fd;
|
|
4128
|
-
try {
|
|
4129
|
-
fd = openBrokerLog(logFile);
|
|
4130
|
-
}
|
|
4131
|
-
finally {
|
|
4132
|
-
if (fd !== undefined)
|
|
4133
|
-
closeSync(fd);
|
|
4134
|
-
}
|
|
4135
|
-
}
|
|
4136
|
-
const setup = useAuth ? await authSetup(storeDir, server, space, host, opts.userAuth, transport, opts.rotateSys, opts.maxFileStore, opts.quietBoot, { authTimeout: opts.authTimeout, maxPayload: opts.maxPayload, accountResolver: opts.accountResolver, manager: opts.noManager !== true, logFile, logfileSizeLimit: opts.logfileSizeLimit, logfileMaxNum: opts.logfileMaxNum, wsPort: opts.wsPort }) : undefined;
|
|
4137
|
-
const maxPayload = setup?.maxPayload ?? opts.maxPayload ?? readBrokerPolicy(root)?.maxPayload;
|
|
4138
|
-
const port = Number(new URL(server).port) || 4222;
|
|
4139
|
-
// Same rule as the foreground path: every route to a listener names its transport (see
|
|
4140
|
-
// `writeOpenBrokerConf`). Detach must not be the mode where the fence quietly does not apply.
|
|
4141
|
-
const renderingBinary = setup?.brokerBinary ?? await resolveNatsServer();
|
|
4142
|
-
if (!renderingBinary.version)
|
|
4143
|
-
throw unreadVersion(renderingBinary);
|
|
4144
|
-
const confPath = setup ? setup.confPath : writeOpenBrokerConf(storeDir, space, { brokerVersion: renderingBinary.version, port, host, transport, maxFileStore: opts.maxFileStore, maxPayload, logFile, logfileSizeLimit: opts.logfileSizeLimit, logfileMaxNum: opts.logfileMaxNum });
|
|
4145
|
-
// Trust preparation awaits; the pinned store is checked again before its config is handed back.
|
|
4146
|
-
if (opts.existingStore)
|
|
4147
|
-
recheckExistingStore(opts.existingStore, { space, storeDir });
|
|
4148
|
-
const args = [
|
|
4149
|
-
"-c", confPath,
|
|
4150
|
-
...(opts.boundListener ? ["--name", opts.boundListener.serverName] : []),
|
|
4151
|
-
];
|
|
4152
|
-
const { path: bin, source, version } = renderingBinary;
|
|
4153
|
-
return { root, server, space, useAuth, storeDir, seedFile, host, transport, setup, maxPayload, confPath, args, bin, source, version };
|
|
4154
|
-
}
|
|
4155
2790
|
export { openBrokerLog };
|
|
4156
|
-
/**
|
|
4157
|
-
* Start a background nats-server (JetStream), wait until it's reachable, pre-create the
|
|
4158
|
-
* space's streams, and leave it running detached (pid in `.cotal/nats.pid`). Used by
|
|
4159
|
-
* `up --detach`. The child writes to the log file, so it survives the parent exiting.
|
|
4160
|
-
*/
|
|
4161
|
-
export async function startMeshDetached(
|
|
4162
|
-
// The `= {}` default is gone with the optional transport: an options object that can be omitted
|
|
4163
|
-
// entirely cannot carry a mandatory decision.
|
|
4164
|
-
opts) {
|
|
4165
|
-
const { server, space, useAuth, storeDir, seedFile, transport, setup: brokerSetup, maxPayload, args, bin, source, version } = await prepareBrokerStart(opts);
|
|
4166
|
-
await seedBeforeLaunch();
|
|
4167
|
-
const setup = brokerSetup && { ...brokerSetup, creds: await brokerSetup.mintProvisioner() };
|
|
4168
|
-
const logPath = cotalPath("nats.log");
|
|
4169
|
-
const fd = openBrokerLog(logPath);
|
|
4170
|
-
const listenerStartedAt = new Date().toISOString();
|
|
4171
|
-
let child;
|
|
4172
|
-
try {
|
|
4173
|
-
child = spawnBroker(bin, args, { cwd: cotalRoot(), detached: true, stdio: ["ignore", fd, fd] });
|
|
4174
|
-
}
|
|
4175
|
-
finally {
|
|
4176
|
-
closeSync(fd);
|
|
4177
|
-
}
|
|
4178
|
-
await recordSpawnedListener(child, listenerStartedAt, opts.boundListener);
|
|
4179
|
-
child.unref();
|
|
4180
|
-
await awaitSpawnedListener({ child, executable: { path: bin, source, version }, server, space, creds: setup?.creds, tls: transport.kind === "tls-required", log: logPath, boundListener: opts.boundListener });
|
|
4181
|
-
const { authService, controlPlane } = await serveReadyListener({
|
|
4182
|
-
child, server, space, storeDir, setup, seedFile, transport, maxPayload,
|
|
4183
|
-
...(opts.recreateIssuedStores !== undefined ? { recreateIssuedStores: opts.recreateIssuedStores } : {}),
|
|
4184
|
-
...(opts.recreateMembershipStore ? { recreateMembershipStore: true } : {}),
|
|
4185
|
-
host: opts.host,
|
|
4186
|
-
maxSessions: opts.maxSessions,
|
|
4187
|
-
managerSeatCap: opts.managerSeatCap,
|
|
4188
|
-
maxFileStore: opts.maxFileStore,
|
|
4189
|
-
publicExchange: opts.publicExchange,
|
|
4190
|
-
resumeAttempt: opts.resumeAttempt,
|
|
4191
|
-
resumeCommit: opts.resumeCommit,
|
|
4192
|
-
runtime: opts.runtime,
|
|
4193
|
-
launch: opts.launch,
|
|
4194
|
-
noManager: opts.noManager,
|
|
4195
|
-
quietBoot: opts.quietBoot,
|
|
4196
|
-
});
|
|
4197
|
-
if (opts.noManager && useAuth && controlPlane)
|
|
4198
|
-
recordOperationWarning(await noManagerCredentialWarning(cotalRoot(), space));
|
|
4199
|
-
const delivery = useAuth && deliveryUp(space);
|
|
4200
|
-
// A daemon this boot started can still stop before the boot ends, such as on a SIGTERM while the
|
|
4201
|
-
// manager starts, and it removes its own record as it goes.
|
|
4202
|
-
const lost = controlPlane?.delivery?.started && !delivery ? controlPlane.delivery : undefined;
|
|
4203
|
-
return {
|
|
4204
|
-
server,
|
|
4205
|
-
pid: child.pid ?? 0,
|
|
4206
|
-
executable: natsServerLabel({ path: bin, source, version }),
|
|
4207
|
-
controlPlane: controlPlane !== undefined,
|
|
4208
|
-
authService,
|
|
4209
|
-
deliveryResponderBound: useAuth ? controlPlane?.responderBound === true : null,
|
|
4210
|
-
delivery,
|
|
4211
|
-
...(lost ? { deliveryLost: `the delivery daemon started for space "${space}" (pid ${lost.pid}) exited before this boot finished. It logged its reason to ${canonicalLocalProcessPath(DELIVERY_LOGFILE, { root: cotalRoot(), space })}` } : {}),
|
|
4212
|
-
manager: managerUp(space),
|
|
4213
|
-
};
|
|
4214
|
-
}
|
|
4215
|
-
/** Refuse a broker address another program holds without answering NATS, such as a web server, as
|
|
4216
|
-
* the controller stack refuses it. nats-server would exit on its bind with only a log line, and the
|
|
4217
|
-
* readiness probe would wait on that program instead. `command` is the start the remedy reruns. */
|
|
4218
|
-
async function assertBrokerAddressFree(server, command, bindHost) {
|
|
4219
|
-
const conflict = await brokerAddressConflict(server, command, bindHost);
|
|
4220
|
-
if (!conflict)
|
|
4221
|
-
return;
|
|
4222
|
-
throw new CommandFailure("refused", "CONFLICT", `${conflict.message} (bind failed: address already in use); no broker was launched`, {
|
|
4223
|
-
target: { root: cotalRoot(), server, bindError: "EADDRINUSE" }, remedy: conflict.remedy,
|
|
4224
|
-
});
|
|
4225
|
-
}
|
|
4226
|
-
/** THE FLIP: a start without `--user-auth` must never boot a broker over a root whose space has
|
|
4227
|
-
* user-auth state on disk. `--open` would serve the space's existing JetStream store to anyone and
|
|
4228
|
-
* re-record the mesh "open" over its user entry; a static start would boot without the callout that
|
|
4229
|
-
* state belongs to. Refused before the store, the space claim or the trust is touched, so the
|
|
4230
|
-
* refusal is a refusal and not an unconfirmed outcome. authSetup keeps the same rule for the
|
|
4231
|
-
* routes that reach it without passing here. */
|
|
4232
|
-
function refuseStartOverUserState(open, userAuth, space) {
|
|
4233
|
-
if (userAuth || !hasUserAuthState(cotalRoot(), space))
|
|
4234
|
-
return;
|
|
4235
|
-
const stateDir = userAuthStateDir(cotalRoot(), space);
|
|
4236
|
-
throw new CommandFailure("refused", "CONFLICT", `space "${space}" has user auth enabled (state under ${stateDir})${open ? ", and --open would serve its streams without auth" : ""}; nothing was started`, {
|
|
4237
|
-
target: { root: cotalRoot(), space },
|
|
4238
|
-
remedy: `${open ? "replace --open with --user-auth" : "add --user-auth"} to start it with user auth, or remove ${shellWord(stateDir)} deliberately to disable user auth (existing logins and grants die with it)`,
|
|
4239
|
-
});
|
|
4240
|
-
}
|
|
4241
|
-
/** Pin cwd as its own mesh root when the nearest ancestor root already belongs to a DIFFERENT
|
|
4242
|
-
* space — mode-independent.
|
|
4243
|
-
*
|
|
4244
|
-
* Auth path: a root's `.cotal/auth` is space-bound, so an explicit `--space` naming another space
|
|
4245
|
-
* cannot share that trust material. Open path: the same ancestor still owns policy, store, pid
|
|
4246
|
-
* and MeshEntry; reusing it for a second space collides those (S4 open arm — child `--open --tls-*`
|
|
4247
|
-
* wrote the parent's broker-policy and nats.pid while a second broker shared the JetStream store).
|
|
4248
|
-
*
|
|
4249
|
-
* A mismatch only exists when the resolved space differs from what the ancestor already hosts.
|
|
4250
|
-
* When the root was merely inherited (cwd has no `.cotal`), honor the new-space intent by making
|
|
4251
|
-
* cwd its own root. Only a folder that itself holds the other space's material refuses.
|
|
4252
|
-
* (When multi-space-per-root lands, that refusal becomes provision-the-new-space instead.)
|
|
4253
|
-
*
|
|
4254
|
-
* The question this asks is "does this root hold the space being booted", NOT "what is THE space of
|
|
4255
|
-
* this root". A root holding several tenants has no sole space, and asking for one there threw
|
|
4256
|
-
* before the boot could reach the config render - so a `cotal up --space alpha` against a root that
|
|
4257
|
-
* legitimately holds alpha and beta refused on ambiguity that its own `--space` had already
|
|
4258
|
-
* resolved. The tenant list answers the real question without picking. */
|
|
4259
|
-
function ensureRootForSpace(space) {
|
|
4260
|
-
const root = cotalRoot();
|
|
4261
|
-
const cwd = process.cwd();
|
|
4262
|
-
// A prepared space starts only in the root `cotal space create` gave it. Checked before the mkdir
|
|
4263
|
-
// below, so a refused start leaves nothing behind.
|
|
4264
|
-
const prepared = findPreparedSpace(space);
|
|
4265
|
-
if (prepared && canonicalRoot(prepared.root) !== canonicalRoot(root)) {
|
|
4266
|
-
const gone = !existsSync(prepared.root);
|
|
4267
|
-
throw new CommandFailure("refused", "TARGET_UNAVAILABLE", `space "${space}" is prepared in ${prepared.root}${gone ? ", which no longer exists" : ""}`, {
|
|
4268
|
-
target: { space, root: prepared.root },
|
|
4269
|
-
remedy: gone ? `forget it with \`cotal space forget ${space}\`, then start it here` : `start it in its folder with \`cotal up --root ${shellWord(prepared.root)} --space ${space}\`, or \`cotal space forget ${space}\` to start it here`,
|
|
4270
|
-
});
|
|
4271
|
-
}
|
|
4272
|
-
// Auth material, a locally started registration, or a preparation names what this root hosts.
|
|
4273
|
-
// A remote registration uses the root as a connection folder, not as a stack root.
|
|
4274
|
-
const hosted = listSpaceAccounts(authDir(root));
|
|
4275
|
-
if (hosted.includes(space))
|
|
4276
|
-
return;
|
|
4277
|
-
const existing = hosted.length
|
|
4278
|
-
? hosted
|
|
4279
|
-
: [localMeshesForRoot(root)[0]?.space ?? preparedSpaceAt(root)?.space].filter((s) => !!s);
|
|
4280
|
-
if (existing.length === 0 || existing.includes(space))
|
|
4281
|
-
return;
|
|
4282
|
-
const names = existing.map((s) => `"${s}"`).join(", ");
|
|
4283
|
-
if (root !== cwd) {
|
|
4284
|
-
mkdirSync(join(cwd, ".cotal"), { recursive: true, mode: 0o700 });
|
|
4285
|
-
console.log(c.dim(`nearest mesh root ${root} hosts ${names} - making this folder its own root for "${space}"`));
|
|
4286
|
-
return;
|
|
4287
|
-
}
|
|
4288
|
-
throw new CommandFailure("refused", "CONFLICT", `this folder is the root of ${names} (${root}/.cotal), so it can't also run "${space}"`, {
|
|
4289
|
-
target: { space, root, hosted: existing },
|
|
4290
|
-
remedy: `${existing.length === 1 ? `run ${names} with \`cotal up --space ${existing[0]}\`` : "run one of those with `cotal up --space <name>`"}, or start "${space}" from a different folder (it becomes that mesh's own root)`,
|
|
4291
|
-
});
|
|
4292
|
-
}
|
|
4293
|
-
/** The space a `cotal up` that names none runs in this folder. The root's sole account names it
|
|
4294
|
-
* first, as {@link resolveSpace} does. An open mesh has no account, and its first start replaces
|
|
4295
|
-
* the prepared record with a registration, so the space this root's stack journal or its locally
|
|
4296
|
-
* started registration names comes next. Without it a second `up` in the same folder resolved the
|
|
4297
|
-
* default space and refused its own mesh. Several names there are refused, never picked. Then the
|
|
4298
|
-
* space prepared here. A stopped open root with none prepared names its space in the broker
|
|
4299
|
-
* configuration its last start rendered. Then the default.
|
|
4300
|
-
*
|
|
4301
|
-
* Only `up` asks this. `resolveSpace` also decides whether identity cleanup may attribute a root to
|
|
4302
|
-
* a space (`reset-space-plan.ts`) and, through `resolveRuntimeSpace`, which space a legacy `down`
|
|
4303
|
-
* removes credentials for; those keep their own answer. */
|
|
4304
|
-
function folderSpace() {
|
|
4305
|
-
const root = cotalRoot();
|
|
4306
|
-
if (soleSpaceOf(authDir(root)) === undefined) {
|
|
4307
|
-
const named = [...new Set([readStackJournal(root)?.journal.space, ...localMeshesForRoot(root).map((m) => m.space)])].filter((s) => s !== undefined);
|
|
4308
|
-
if (named.length > 1)
|
|
4309
|
-
throw new CommandFailure("refused", "CONFLICT", `this folder's stack and registrations name ${named.length} spaces (${named.map((s) => `"${s}"`).join(", ")}), so up cannot pick one`, {
|
|
4310
|
-
target: { root, spaces: named },
|
|
4311
|
-
remedy: "name the space to run with `--space`",
|
|
4312
|
-
});
|
|
4313
|
-
if (named.length === 1)
|
|
4314
|
-
return named[0];
|
|
4315
|
-
// A stopped open root holds no account, so its broker configuration names its space.
|
|
4316
|
-
const deployed = preparedSpaceAt(root) ? undefined : retainedOpenSpace(root);
|
|
4317
|
-
if (deployed)
|
|
4318
|
-
return deployed;
|
|
4319
|
-
}
|
|
4320
|
-
return resolveSpace(process.cwd());
|
|
4321
|
-
}
|
|
4322
|
-
/** Whether `space` is the default space a bare `up` starts because this folder names none. */
|
|
4323
|
-
function unnamedDefault(root, space) {
|
|
4324
|
-
return space === DEFAULT_SPACE && soleSpaceOf(authDir(root)) === undefined && !preparedSpaceAt(root) && !localMeshesForRoot(root).length && !readStackJournal(root);
|
|
4325
|
-
}
|
|
4326
|
-
/** A bare `up` in a folder that names no space starts a space it names itself. When the selected
|
|
4327
|
-
* space is prepared in a folder that no longer exists, as after that folder was moved, that space is
|
|
4328
|
-
* not what was meant, so `up` refuses with the step that prepares the selection here. */
|
|
4329
|
-
function assertSelectionNotMoved(root, space) {
|
|
4330
|
-
const current = getCurrent();
|
|
4331
|
-
const prepared = current === undefined || current === space ? undefined : findPreparedSpace(current);
|
|
4332
|
-
if (!prepared || existsSync(prepared.root))
|
|
4333
|
-
return;
|
|
4334
|
-
throw new CommandFailure("refused", "TARGET_UNAVAILABLE", `the selected space "${current}" is prepared in ${prepared.root}, which no longer exists, and this folder names no space, so up did not start "${space}" here`, {
|
|
4335
|
-
target: { root, space: current, preparedRoot: prepared.root },
|
|
4336
|
-
remedy: `if this is that folder moved, forget it with \`cotal space forget ${current}\`, then prepare it here with \`cotal space create ${current}\` and run \`cotal up\`; to start "${space}" here, pass --space ${space}`,
|
|
4337
|
-
});
|
|
4338
|
-
}
|
|
4339
|
-
/** The remedy for a hand-registered (`origin === "manual"`) space `claimSpace` refuses to touch.
|
|
4340
|
-
* Branches on whether the REGISTERED server is loopback, the one authority for that being
|
|
4341
|
-
* `isLoopbackHost` (`@cotal-ai/workspace`) — never a second opinion here.
|
|
4342
|
-
*
|
|
4343
|
-
* Non-loopback: the mesh runs on another machine and this one does not take over its control
|
|
4344
|
-
* plane by deleting the registry route (that route is what attach, spawn-from-anywhere, and
|
|
4345
|
-
* every read verb hang off) or by forking the identity under a different `--space`. The actual
|
|
4346
|
-
* next step is running that control plane FROM here, against the broker the record already
|
|
4347
|
-
* names: `cotal supervise` (plus `cotal deliver` for the daemon). Dropping the record
|
|
4348
|
-
* (`meshes rm`) is a separate decision for a genuinely stale record, out of scope here.
|
|
4349
|
-
*
|
|
4350
|
-
* Loopback: unchanged — a loopback registration this machine cannot reach the "real" mesh behind
|
|
4351
|
-
* (or is stale) keeps the original two-way remedy, byte for byte.
|
|
4352
|
-
*
|
|
4353
|
-
* A server string `new URL` rejects is a record shape this function never validated before
|
|
4354
|
-
* (nothing here parsed it), so it keeps the loopback wording rather than growing a parser. */
|
|
4355
|
-
function manualClaimRemedy(space, server) {
|
|
4356
|
-
let loopback = true;
|
|
4357
|
-
try {
|
|
4358
|
-
loopback = isLoopbackHost(new URL(server).hostname);
|
|
4359
|
-
}
|
|
4360
|
-
catch {
|
|
4361
|
-
loopback = true;
|
|
4362
|
-
}
|
|
4363
|
-
if (!loopback)
|
|
4364
|
-
return `\`cotal supervise --space ${space} --server ${server}\` to run its control plane from here (and \`cotal deliver --space ${space} --server ${server}\` for the daemon)`;
|
|
4365
|
-
return `\`cotal meshes rm ${space}\` to drop that record first, or start this one under a different \`--space\``;
|
|
4366
|
-
}
|
|
4367
|
-
/** Where a prior holder's absolute root physically resolves, or undefined when it is proven gone: it
|
|
4368
|
-
* does not resolve (ENOENT, ENOTDIR) or resolves to something other than a directory. Any other
|
|
4369
|
-
* failure, such as EACCES, EPERM, EIO or ELOOP, proves nothing about the root or its journal, so the
|
|
4370
|
-
* name is kept and the refusal says why. No lexical spelling stands in for the physical path: under
|
|
4371
|
-
* an unreadable ancestor, `<root>/link/..` resolves lexically to `<root>` while it names another. */
|
|
4372
|
-
function priorRootPath(space, root) {
|
|
4373
|
-
let real;
|
|
4374
|
-
let kind;
|
|
4375
|
-
try {
|
|
4376
|
-
real = realpathSync.native(root);
|
|
4377
|
-
kind = statSync(real);
|
|
4378
|
-
}
|
|
4379
|
-
catch (e) {
|
|
4380
|
-
const code = e.code;
|
|
4381
|
-
if (code === "ENOENT" || code === "ENOTDIR")
|
|
4382
|
-
return undefined;
|
|
4383
|
-
throw new CommandFailure("refused", code === "EACCES" || code === "EPERM" ? "PERMISSION_DENIED" : "TARGET_UNAVAILABLE", `space "${space}" is registered to ${root}, which could not be resolved (${code ?? String(e)}) - \`cotal up\` did not take the name`, { target: { space, root }, remedy: `restore access to ${root} and run this again, or start this stack under a different \`--space\`` });
|
|
4384
|
-
}
|
|
4385
|
-
return kind.isDirectory() ? real : undefined;
|
|
4386
|
-
}
|
|
4387
|
-
/** A space name maps to one mesh in the registry (the key `--space`/`use`/`down` act on). Before
|
|
4388
|
-
* starting a broker, refuse to reuse a space already claimed by a DIFFERENT live mesh — a stale/dead
|
|
4389
|
-
* holder is reclaimed, and said so when it was another root's, unless that root still holds a
|
|
4390
|
-
* maintenance journal. Re-`up`ping the same mesh (same server + root) is a refresh (port-reachable
|
|
4391
|
-
* path). NOTE: this is a best-effort sequential guard — two `cotal up --space X` racing from
|
|
4392
|
-
* different roots within the same instant can both pass the check before either records; that
|
|
4393
|
-
* concurrent case is out of scope (a single-operator CLI action), not synchronized with a lock. */
|
|
4394
|
-
export async function claimSpace(space, server, root) {
|
|
4395
|
-
const existing = findMesh(space);
|
|
4396
|
-
if (!existing)
|
|
4397
|
-
return;
|
|
4398
|
-
// A relative recorded root names no directory without a guess against the cwd, so it is never
|
|
4399
|
-
// taken as this root, compared with it or reclaimed. Its record stays until it is removed by hand.
|
|
4400
|
-
const relative = !isAbsolute(existing.root);
|
|
4401
|
-
if (!relative && existing.server === server && existing.root === root)
|
|
4402
|
-
return;
|
|
4403
|
-
// Every refusal below is made before the registry changes, so it is typed as refused with its own
|
|
4404
|
-
// remedy, and the controller and legacy routes both show the reason and exit 2.
|
|
4405
|
-
const target = { space, root: existing.root, server: existing.server };
|
|
4406
|
-
// An OPERATOR-REGISTERED holder is decided FIRST, before liveness, because liveness changes
|
|
4407
|
-
// nothing about it and the two outcomes would otherwise print the wrong remedy. It is never
|
|
4408
|
-
// reclaimed: unreachable is not proof the mesh is gone (the record describes a broker on another
|
|
4409
|
-
// machine), the reclaim runs BEFORE this launch starts anything, and `cotal down` — what the
|
|
4410
|
-
// liveness branch below would advise — cannot stop a mesh this machine does not run.
|
|
4411
|
-
if (existing.origin === "manual" || existing.origin === "catalog")
|
|
4412
|
-
throw new CommandFailure("refused", "CONFLICT", `space "${space}" is registered to a mesh at ${existing.server} (${existing.root}) - it is ${existing.origin === "catalog" ? "owned by a signed-in space catalog" : "registered by hand"}, so \`cotal up\` neither takes it over nor reclaims the name`, { target, remedy: existing.origin === "catalog" ? "use a different `--space`, or remove access at the IdP and run `cotal sync`" : manualClaimRemedy(space, existing.server) });
|
|
4413
|
-
if (relative)
|
|
4414
|
-
throw new CommandFailure("refused", "CONFLICT", `space "${space}" is registered to ${existing.root}, which is not an absolute path - \`cotal up\` did not take the name`, { target, remedy: `drop that record with \`cotal meshes rm ${space}\`, or start this stack under a different \`--space\`` });
|
|
4415
|
-
if (await isReachable(existing.server)) {
|
|
4416
|
-
// A space name is this machine's, so a separate space here needs a name of its own.
|
|
4417
|
-
let controller = false;
|
|
4418
|
-
try {
|
|
4419
|
-
controller = readStackJournal(existing.root)?.journal.space === space;
|
|
4420
|
-
}
|
|
4421
|
-
catch { /* named with the legacy stop */ }
|
|
4422
|
-
// THIS project's own space, running at its own address, started again with another one. The
|
|
4423
|
-
// refusal below belongs to a name another folder holds: it reads as if this folder were a
|
|
4424
|
-
// stranger to the space and offers to start a separate one here, when the folder IS that
|
|
4425
|
-
// space's project and a start naming no address joins the mesh already running in it. No
|
|
4426
|
-
// command moves a stack that ran to another address, so say which address it runs at.
|
|
4427
|
-
// The address must differ for this sentence to be true: the early return above compares roots
|
|
4428
|
-
// as written while this compares them resolved, so a record naming this root by another
|
|
4429
|
-
// spelling reaches here at its OWN address, and that case keeps the refusal below.
|
|
4430
|
-
if (canonicalRoot(existing.root) === canonicalRoot(root) && existing.server !== server)
|
|
4431
|
-
throw new CommandFailure("refused", "CONFLICT", `space "${space}" already runs from this project at ${existing.server}, and this start names ${server}; nothing was started`, {
|
|
4432
|
-
target,
|
|
4433
|
-
remedy: `run \`cotal up\` here with no --server or --host to reach the mesh at ${existing.server}, or stop it first with \`cotal down${controller ? " --yes" : ""}\` in ${shellWord(existing.root)}`,
|
|
4434
|
-
});
|
|
4435
|
-
throw new CommandFailure("refused", "CONFLICT", `space "${space}" is already in use by a mesh at ${existing.server} (${existing.root})`, { target, remedy: `start a separate space in this folder with \`cotal up --space <name>\`, naming one no other folder uses, or stop "${space}" first with \`cotal down${controller ? " --yes" : ""}\` in ${shellWord(existing.root)}` });
|
|
4436
|
-
}
|
|
4437
|
-
// The recorded root is this root only where it physically resolves, so it is resolved before any
|
|
4438
|
-
// comparison, and one that cannot be resolved refuses. A dead holder at another root keeps its name
|
|
4439
|
-
// while that root holds a preserved cut or a restore: taking it would cut that root's recovery off
|
|
4440
|
-
// from its space. A journal that cannot be read keeps it too. A root proven gone or not a directory
|
|
4441
|
-
// has no journal to read; a readable root without one is reclaimed.
|
|
4442
|
-
const prior = priorRootPath(space, existing.root);
|
|
4443
|
-
const otherRoot = prior !== canonicalRoot(root);
|
|
4444
|
-
if (otherRoot && prior !== undefined) {
|
|
4445
|
-
let held;
|
|
4446
|
-
try {
|
|
4447
|
-
held = readMaintenanceJournal(existing.root)?.state;
|
|
4448
|
-
}
|
|
4449
|
-
catch {
|
|
4450
|
-
held = "unreadable";
|
|
4451
|
-
}
|
|
4452
|
-
if (held)
|
|
4453
|
-
throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", `space "${space}" is registered to ${existing.root}, whose maintenance journal holds a preserved cut or a restore (state ${held}) - \`cotal up\` did not take the name`, { target, remedy: `finish that attempt from ${existing.root}, or start this stack under a different \`--space\`` });
|
|
4454
|
-
}
|
|
4455
|
-
removeMesh(space); // the prior holder's broker is gone — reclaim the name
|
|
4456
|
-
if (otherRoot)
|
|
4457
|
-
console.error(`• space "${space}" was registered to ${existing.root}, whose broker at ${existing.server} is not running - this up takes the name over`);
|
|
4458
|
-
}
|
|
4459
|
-
/**
|
|
4460
|
-
* The manager attach/console BIND host for a launch into `space`.
|
|
4461
|
-
*
|
|
4462
|
-
* Exposure is an operator DECISION, made at `up --host` and recorded on the mesh entry. Every later
|
|
4463
|
-
* launch for the same mesh — a same-root repair, adopting a preserved or restored listener, a
|
|
4464
|
-
* manifest deploy — has no `--host` of its own to consult, so it reads the decision back. Without
|
|
4465
|
-
* this a replacement manager falls to loopback and remote `cotal attach` dies at the first repair,
|
|
4466
|
-
* silently: the broker and every agent stay up, only the terminal face moves.
|
|
4467
|
-
*
|
|
4468
|
-
* An explicit host on THIS invocation always wins, so an operator can widen or narrow exposure by
|
|
4469
|
-
* saying so. Absent both, undefined — the manager's own loopback default, unchanged.
|
|
4470
|
-
*/
|
|
4471
|
-
export function attachHostFor(space, explicit) {
|
|
4472
|
-
return explicit ?? findMesh(space)?.attachHost;
|
|
4473
|
-
}
|
|
4474
|
-
/**
|
|
4475
|
-
* The manager live-session ceiling for a launch into `space`.
|
|
4476
|
-
*
|
|
4477
|
-
* Like {@link attachHostFor}, this is an operator DECISION (`--max-sessions`), not something later
|
|
4478
|
-
* commands can reconstruct. Every later manager launch — same-root repair, resume, `spawn -f` —
|
|
4479
|
-
* has no flag of its own unless the operator typed one, so it reads the decision back. Without
|
|
4480
|
-
* this a replacement manager silently falls to 64 and the next console pane past that is refused.
|
|
4481
|
-
*
|
|
4482
|
-
* An explicit value on THIS invocation always wins. Absent both, undefined — the plane's own
|
|
4483
|
-
* default of 64, unchanged, and nothing is recorded as though chosen.
|
|
4484
|
-
*/
|
|
4485
|
-
export function maxSessionsFor(space, explicit) {
|
|
4486
|
-
return explicit ?? findMesh(space)?.maxSessions;
|
|
4487
|
-
}
|
|
4488
|
-
/** {@link recordOurMesh} under a name that says it is a test seam: the origin rule it enforces is
|
|
4489
|
-
* asserted directly by the registry smoke, since reaching each branch through a full `up` would
|
|
4490
|
-
* need a live broker per case. */
|
|
4491
|
-
export const recordOurMeshForTest = (m, provenance) => recordOurMesh(m, provenance);
|
|
4492
|
-
/** Record this mesh in the registry, and set it as the `current` default when there's no usable one
|
|
4493
|
-
* — i.e. the first mesh, OR when `current` dangles at a space that's no longer in the registry (a
|
|
4494
|
-
* ghost pointer is not a default), and say so. Never silently redirect a `current` that still resolves
|
|
4495
|
-
* to a live mesh; just say another is the default and how to switch. */
|
|
4496
|
-
function recordOurMesh(m, provenance, quietBoot = false) {
|
|
4497
|
-
const cur = getCurrent();
|
|
4498
|
-
const usableCurrent = cur && (findMesh(cur) || findPreparedSpace(cur)) ? cur : undefined; // compute before recording m
|
|
4499
|
-
const prior = findMesh(m.space);
|
|
4500
|
-
const origin = provenance === "refresh" && (prior?.origin === "manual" || prior?.origin === "catalog") ? prior.origin : "up";
|
|
4501
|
-
// A REFRESH starts nothing: it concluded the mesh is up from reachability alone, so `m` holds only
|
|
4502
|
-
// what THIS launch decided, and every other field is the record as it stands now. That covers the
|
|
4503
|
-
// operator's past decisions (origin, overlay consent, TLS requirement) and anything another writer
|
|
4504
|
-
// committed while the refresh ensured the control plane; rebuilding from the refresh's earlier
|
|
4505
|
-
// read reverted those and still exited 0. A `started` takeover may replace the record outright
|
|
4506
|
-
// (that launch really is the mesh now).
|
|
4507
|
-
if (provenance === "refresh" && !prior)
|
|
4508
|
-
throw new Error(`mesh "${m.space}" was removed from the registry while \`cotal up\` refreshed it - not re-recording it from an earlier read`);
|
|
4509
|
-
const nativeMembers = [];
|
|
4510
|
-
for (const [role, template] of [["manager", MANAGER_PIDFILE], ["delivery", DELIVERY_PIDFILE], ["auth", AUTH_PIDFILE], ["broker", NATS_PIDFILE]]) {
|
|
4511
|
-
const pin = verifyIdentityPin(role === "broker" ? join(m.root, ".cotal", template) : localProcessPath(template, { root: m.root, space: m.space }));
|
|
4512
|
-
if (pin.kind === "match")
|
|
4513
|
-
nativeMembers.push({ role, process: pin.record });
|
|
4514
|
-
}
|
|
4515
|
-
const nativeHost = nativeMembers.length ? knownStackRecoveryHost() : undefined;
|
|
4516
|
-
const recorded = { ...m, origin, ...(nativeHost !== undefined ? { nativeMembers, nativeHost } : {}) };
|
|
4517
|
-
recordMesh(provenance === "refresh" ? { ...prior, ...recorded, stoppedByDown: undefined, stoppedWithAgents: undefined } : recorded);
|
|
4518
|
-
removePreparedSpace(m.space); // started: the registration is its record now
|
|
4519
|
-
if (!usableCurrent) {
|
|
4520
|
-
setAdoptedCurrent(m.space);
|
|
4521
|
-
if (!quietBoot)
|
|
4522
|
-
for (const line of hang("", selectedOnUp(m.space), terminalWidth(process.stdout), c.dim))
|
|
4523
|
-
console.log(line);
|
|
4524
|
-
return;
|
|
4525
|
-
}
|
|
4526
|
-
if (usableCurrent !== m.space && !quietBoot)
|
|
4527
|
-
for (const line of hang("", keptOnUp(m.space, usableCurrent), terminalWidth(process.stdout), c.dim))
|
|
4528
|
-
console.log(line);
|
|
4529
|
-
}
|
|
4530
|
-
/** Write the default persona into the root this `up` started or refreshed when it has none, and
|
|
4531
|
-
* say so. The mesh is already up, so a write that fails is reported and the start stands. */
|
|
4532
|
-
function seedPersonaAfterUp(root, quiet = false) {
|
|
4533
|
-
let written;
|
|
4534
|
-
try {
|
|
4535
|
-
written = seedDefaultPersona(root);
|
|
4536
|
-
}
|
|
4537
|
-
catch (e) {
|
|
4538
|
-
console.error(c.yellow(`! the default persona was not written in ${root}: ${e.message}`));
|
|
4539
|
-
return;
|
|
4540
|
-
}
|
|
4541
|
-
if (written && !quiet)
|
|
4542
|
-
for (const line of hang(" ", `wrote ${written.what}: ${written.path}`, terminalWidth(process.stdout)))
|
|
4543
|
-
console.log(c.dim(line));
|
|
4544
|
-
}
|
|
4545
|
-
async function waitReady(server, creds, tls = false, log) {
|
|
4546
|
-
// Fifty silent probes is the bound for a broker that is not advancing. A listener that is up, or a
|
|
4547
|
-
// broker log that keeps growing or recording a JetStream restore, is evidence the process is still
|
|
4548
|
-
// recovering, so the wait continues instead of stopping it at a fixed count.
|
|
4549
|
-
let evidence = 0;
|
|
4550
|
-
let silent = 0;
|
|
4551
|
-
for (let i = 0; silent < 50; i++) {
|
|
4552
|
-
const reachable = await isReachable(server, creds ? { creds } : undefined);
|
|
4553
|
-
if (tls)
|
|
4554
|
-
await refuseUntrustedListener(server, creds);
|
|
4555
|
-
if (reachable)
|
|
4556
|
-
return true;
|
|
4557
|
-
const { evidence: next, restoring } = brokerRecoveryEvidence(log);
|
|
4558
|
-
// Any restore evidence seen during the wait is progress, including evidence already present on
|
|
4559
|
-
// the first probe. A restore that has started and not finished is progress on every probe, since
|
|
4560
|
-
// the broker writes nothing to its log until it completes; the probe cap bounds that wait. Only a
|
|
4561
|
-
// probe with no new evidence and no restore in flight counts toward the silent bound.
|
|
4562
|
-
if (next > evidence || restoring) {
|
|
4563
|
-
evidence = Math.max(evidence, next);
|
|
4564
|
-
silent = 0;
|
|
4565
|
-
}
|
|
4566
|
-
else {
|
|
4567
|
-
silent++;
|
|
4568
|
-
}
|
|
4569
|
-
if (i >= 1_500)
|
|
4570
|
-
return false;
|
|
4571
|
-
await new Promise((r) => setTimeout(r, 200));
|
|
4572
|
-
}
|
|
4573
|
-
return false;
|
|
4574
|
-
}
|
|
4575
|
-
/** Bytes plus completed-restore lines in the broker log, and whether a restore is in flight. A
|
|
4576
|
-
* foreground broker logging to the terminal has no file to read, so it keeps the silent-probe bound. */
|
|
4577
|
-
function brokerRecoveryEvidence(log) {
|
|
4578
|
-
const none = { evidence: 0, restoring: false };
|
|
4579
|
-
if (!log || log.startsWith("the terminal"))
|
|
4580
|
-
return none;
|
|
4581
|
-
let text = "";
|
|
4582
|
-
let size = 0;
|
|
4583
|
-
try {
|
|
4584
|
-
const stat = statSync(log);
|
|
4585
|
-
if (!stat.isFile())
|
|
4586
|
-
return none;
|
|
4587
|
-
size = stat.size;
|
|
4588
|
-
text = readFileSync(log, "utf8");
|
|
4589
|
-
}
|
|
4590
|
-
catch {
|
|
4591
|
-
return none;
|
|
4592
|
-
}
|
|
4593
|
-
const started = text.match(/Starting restore/g)?.length ?? 0;
|
|
4594
|
-
const restored = text.match(/Restored \d/g)?.length ?? 0;
|
|
4595
|
-
return { evidence: size + restored, restoring: started > restored };
|
|
4596
|
-
}
|
|
4597
|
-
/** Throw when the TLS listener at `server` answers and this client refuses its certificate in the
|
|
4598
|
-
* handshake, which waiting does not change. It dials as the setup that follows does. */
|
|
4599
|
-
async function refuseUntrustedListener(server, creds) {
|
|
4600
|
-
let code, reason = "";
|
|
4601
|
-
try {
|
|
4602
|
-
const nc = await dialerFor(server)({ servers: server, timeout: 1_000, reconnect: false, maxReconnectAttempts: 0, ...standaloneConnectOpts({ creds, tls: false }) });
|
|
4603
|
-
await nc.close();
|
|
4604
|
-
return;
|
|
4605
|
-
}
|
|
4606
|
-
catch (e) {
|
|
4607
|
-
code = e?.code;
|
|
4608
|
-
reason = e instanceof Error ? e.message.split(";")[0] : String(e);
|
|
4609
|
-
}
|
|
4610
|
-
const untrusted = typeof code === "string" && UNTRUSTED_CERTIFICATE.has(code);
|
|
4611
|
-
if (!untrusted && code !== "ERR_TLS_CERT_ALTNAME_INVALID")
|
|
4612
|
-
return;
|
|
4613
|
-
const { hostname, port } = new URL(server);
|
|
4614
|
-
throw new CommandFailure("failed", "OPERATION_FAILED", `nats-server answered at ${server}, but this client refused its TLS certificate in the handshake (${reason}); up stopped it and recorded nothing`, {
|
|
4615
|
-
native: { code: String(code) },
|
|
4616
|
-
remedy: untrusted
|
|
4617
|
-
? "trust the certificate's CA, or a self-signed certificate itself, by setting NODE_EXTRA_CA_CERTS to that PEM file for `cotal up` and every cotal command of this space, then run `cotal up` again"
|
|
4618
|
-
: /^tls:/i.test(server) ? `serve a certificate that names ${hostname}, then run \`cotal up\` again` : `pass --server tls://${hostname}:${port}, so every dial checks the certificate against ${hostname}`,
|
|
4619
|
-
});
|
|
4620
|
-
}
|
|
4621
|
-
// #1356: the presence bucket's file-backed latch is fixed in nats-server 2.14.5. Below that,
|
|
4622
|
-
// `cotal up` warns when the space's presence bucket is file-backed (never refuses: 2.14.0 meets the
|
|
4623
|
-
// SPEC §13.12 floor and is the bundled broker). A memory-backed bucket has no file store to latch.
|
|
4624
|
-
function belowPresenceSafeBroker(version) {
|
|
4625
|
-
const p = parseServerVersion(version);
|
|
4626
|
-
if (!p)
|
|
4627
|
-
return false;
|
|
4628
|
-
if (p.major !== 2)
|
|
4629
|
-
return p.major < 2;
|
|
4630
|
-
if (p.minor !== 14)
|
|
4631
|
-
return p.minor < 14;
|
|
4632
|
-
return p.patch < 5;
|
|
4633
|
-
}
|
|
4634
2791
|
//# sourceMappingURL=up.js.map
|