@open-mercato/starter 0.10.1-develop.7990.1.82d0a183c5 → 0.10.1-develop.8004.1.a8a79ee43f
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +48 -3
- package/package.json +1 -1
- package/src/__tests__/database-write-guard.test.mjs +111 -0
- package/src/__tests__/existing-infra.test.mjs +412 -0
- package/src/__tests__/port-diagnostics.test.mjs +129 -0
- package/src/__tests__/providers.test.mjs +156 -0
- package/src/__tests__/service-compose-security.test.mjs +134 -0
- package/src/__tests__/service-connections.test.mjs +241 -0
- package/src/__tests__/service-modes.test.mjs +298 -0
- package/src/__tests__/service-selection.test.mjs +292 -0
- package/src/__tests__/setup-streaming.test.mjs +34 -0
- package/src/__tests__/stage-progress.test.mjs +1 -1
- package/src/__tests__/starter.test.mjs +116 -3
- package/src/cli.mjs +114 -18
- package/src/compose.mjs +9 -3
- package/src/constants.mjs +1 -1
- package/src/database-write-guard.mjs +80 -0
- package/src/infra-preflight.mjs +324 -8
- package/src/infra.mjs +2 -1
- package/src/providers.mjs +10 -20
- package/src/service-connections.mjs +167 -0
- package/src/service-modes.mjs +358 -0
- package/src/setup-session.mjs +77 -0
- package/src/steps.mjs +117 -13
package/README.md
CHANGED
|
@@ -11,7 +11,7 @@ yarn setup # same as `yarn om up`: everything from install to a run
|
|
|
11
11
|
yarn om # alias for node packages/starter/bin/om-start.mjs
|
|
12
12
|
```
|
|
13
13
|
|
|
14
|
-
`yarn setup`
|
|
14
|
+
Without a service flag `yarn setup` picks the services itself: it reuses those configured in `apps/mercato/.env` when they answer, their credentials verify and they are not another checkout's containers; starts this checkout's Compose services on the configured ports when nothing answers; starts an isolated stack on free ports (and says why) when the configured ports are held by something unusable; and stops with the Docker problem plus the [Without Docker](https://github.com/open-mercato/open-mercato#without-docker) guide when Docker is unusable and nothing usable answers. An interactive terminal shows the choice with that pick as the default; noninteractive runs never prompt. Setup claims the checkout's dev session first, so a second `yarn setup` while one is running stops before changing `.env` or containers. Use `--ephemeral` for disposable PostgreSQL, Redis and Meilisearch managed by Testcontainers, `--random-ports` for a persistent isolated Compose stack on free ports, or `--infra` for Compose on configured ports. `--no-infra` and `--reuse-services` explicitly select reuse. Random and ephemeral modes update the service ports and matching connection URLs together; ephemeral mode restores the previous settings and removes its containers when the foreground session stops. Compose containers and volumes persist. Nothing installs Docker or asks for sudo.
|
|
15
15
|
|
|
16
16
|
Apps created with `npx create-mercato-app` get the same check: their `yarn setup` (and `yarn infra:up` / `yarn infra:down`) runs this package's preflight from `scripts/dev-infra-preflight.mjs`, a byte-for-byte copy kept in sync by `yarn template:sync`.
|
|
17
17
|
|
|
@@ -34,7 +34,9 @@ No Node yet? The package ships pre-Node bootstraps that install a **portable, ch
|
|
|
34
34
|
| `reset` | Destructive cleanup (containers, volumes, starter state) — asks first. |
|
|
35
35
|
| `infra up\|down` | Just the infra containers. |
|
|
36
36
|
|
|
37
|
-
|
|
37
|
+
AI provider configuration is optional: press Enter or choose `0` at the provider prompt to continue without AI. Non-interactive setup also continues without a key. Configure a provider in `.env` later to enable AI chat.
|
|
38
|
+
|
|
39
|
+
Useful flags: `--verbose`, `--reuse-services`, `--ephemeral` (foreground only), `--random-ports`, `--infra`, `--non-interactive`, `--skip-llm-prompt`, `--skip-db`, `--no-infra` (no Docker calls at all, also passed on to `yarn dev`), `--rebuild`, `--clean`, `--profile <name>`, `-- <args for yarn dev>`.
|
|
38
40
|
|
|
39
41
|
`up --clean` forces a full re-converge: it clears the completed-step markers (install, build, migrations) and rebuilds the OpenCode service image, without touching any data — the one-time database seed stays done, and `reset` remains the destructive variant. Conversely, a plain `up` now also skips the database step entirely when the database is initialized and no `Migration*.ts` file changed since the last run (new migrations are detected by fingerprint and applied automatically).
|
|
40
42
|
|
|
@@ -48,7 +50,7 @@ Use `yarn setup --verbose` or `yarn infra:up --verbose` for live raw output. CI,
|
|
|
48
50
|
|
|
49
51
|
## Design rules
|
|
50
52
|
|
|
51
|
-
- **Node stdlib
|
|
53
|
+
- **Node stdlib bootstrap, no build step.** The CLI runs from a fresh clone before `yarn install`. Testcontainers is loaded lazily from the checkout only after dependencies are installed and only for an explicit ephemeral service choice.
|
|
52
54
|
- **Install nothing system-level.** WSL2, Docker Desktop, and Rancher Desktop are detected and *proposed* (with exact commands and an IT handout), never installed. The starter installs only what it fully owns: portable Node (platform scripts), yarn via corepack, env files, CA bundles, repo state.
|
|
53
55
|
- **Corporate TLS interception is a first-class citizen.** `up` probes real egress hosts, captures the interception CA (wire + Windows certificate store + vendor bundles like Netskope's), and provisions one PEM bundle everywhere: `NODE_EXTRA_CA_CERTS` + `--use-system-ca` for host tooling, `docker/certs/` + `docker/opencode/certs/` for image builds and container egress, a Rancher Desktop provisioning script for engine pulls. Prefer handing the starter your official bundle via `starters/company/config.mjs`.
|
|
54
56
|
- **Probes use `127.0.0.1`, never `localhost`** (Windows resolves `localhost` to `::1` first).
|
|
@@ -57,3 +59,46 @@ Use `yarn setup --verbose` or `yarn infra:up --verbose` for live raw output. CI,
|
|
|
57
59
|
## Company tailoring
|
|
58
60
|
|
|
59
61
|
Organizations customize behavior (mirrors, CA bundles, extra checks/steps, env defaults) via `starters/company/config.mjs` in the repo — see `starters/company/README.md`. The package stays generic; the repo carries the policy.
|
|
62
|
+
|
|
63
|
+
## Recovering from setup failure
|
|
64
|
+
|
|
65
|
+
The starter prints the failed step and a manual path. Check the selected service
|
|
66
|
+
URLs in `apps/mercato/.env`, then run `yarn install`, `yarn build:packages`,
|
|
67
|
+
`yarn generate`, `yarn build:packages`, `yarn db:migrate`,
|
|
68
|
+
`yarn initialize -- --skip-if-initialized`, and `yarn dev --no-infra`.
|
|
69
|
+
Alternatively retry `yarn setup --ephemeral`, `yarn setup --random-ports`, or
|
|
70
|
+
`yarn setup --infra`. Ephemeral URLs are session-scoped; after failure or exit,
|
|
71
|
+
use the restored existing-service URLs or start another ephemeral setup session.
|
|
72
|
+
|
|
73
|
+
Before database setup, the starter verifies PostgreSQL with `SELECT 1`, every configured Redis consumer with an authenticated `PING`, and Meilisearch with its protected indexes API. Invalid credentials or unreachable services stop setup with the relevant configuration key and a redacted endpoint; passwords and API keys are never printed.
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
## Setup security boundaries
|
|
77
|
+
|
|
78
|
+
Plain and noninteractive setup never start services on ports that already
|
|
79
|
+
answer and never contact a database held by another project's containers: they
|
|
80
|
+
reuse verified services, start Compose on free configured ports, or isolate
|
|
81
|
+
themselves on free random ports. Explicit flags keep their exact meaning.
|
|
82
|
+
|
|
83
|
+
Before any setup/development migration or initialization, the guard resolves the
|
|
84
|
+
actual PostgreSQL target (including connection-string overrides). Non-loopback
|
|
85
|
+
writes require an exact target acknowledgement, for example
|
|
86
|
+
`yarn setup --allow-remote-database=staging.example:5432/app_db`. A bare
|
|
87
|
+
`--allow-remote-database` prompts for that exact target only in a terminal;
|
|
88
|
+
unattended runs must provide it. Connection snapshots prevent a changed `.env`
|
|
89
|
+
from redirecting an already-authorized child command. Local reuse needs no flag.
|
|
90
|
+
|
|
91
|
+
Isolated modes generate independent random PostgreSQL, Redis and Meilisearch
|
|
92
|
+
credentials, never reuse configured remote credentials, and pin their images
|
|
93
|
+
(including the Testcontainers cleanup image) by verified multiarch digests.
|
|
94
|
+
Random stacks save their owned `OM_SETUP_LOCAL_*` values in ignored `.env` files
|
|
95
|
+
and reuse those values on later runs despite ambient remote URL overrides.
|
|
96
|
+
The new `mercato-local-v2-*` identity creates separate volumes from earlier
|
|
97
|
+
random stacks; old containers/data are retained and are not deleted or migrated.
|
|
98
|
+
|
|
99
|
+
Development Compose bindings default to `127.0.0.1`. An explicit
|
|
100
|
+
`INFRA_BIND_HOST` outside loopback additionally requires a Redis password and
|
|
101
|
+
matching Redis URLs. Random mode forces loopback regardless of that ambient
|
|
102
|
+
setting. Full application/container deployment Compose files retain their
|
|
103
|
+
existing bindings. Optional profiles not started by setup retain their existing
|
|
104
|
+
image policy; the setup services and OpenCode defaults are pinned.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/starter",
|
|
3
|
-
"version": "0.10.1-develop.
|
|
3
|
+
"version": "0.10.1-develop.8004.1.a8a79ee43f",
|
|
4
4
|
"description": "One-command, cross-platform bootstrap for Open Mercato dev environments: prerequisite doctor, corporate TLS trust, idempotent setup steps, and a supervised hybrid or fully containerized stack.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import assert from 'node:assert/strict'
|
|
2
|
+
import fs from 'node:fs'
|
|
3
|
+
import os from 'node:os'
|
|
4
|
+
import path from 'node:path'
|
|
5
|
+
import { createRequire } from 'node:module'
|
|
6
|
+
import { PassThrough } from 'node:stream'
|
|
7
|
+
import test from 'node:test'
|
|
8
|
+
import { assertDatabaseWriteAllowed, resolveDatabaseWriteTarget, collectRemoteDatabaseFlags } from '../database-write-guard.mjs'
|
|
9
|
+
const pg = createRequire(import.meta.url)('pg')
|
|
10
|
+
const options = (url) => ({ projectDir: '/missing-fixture', env: { DATABASE_URL: url }, loadModule: () => pg })
|
|
11
|
+
|
|
12
|
+
test('local reuse remains automatic without an explicit service flag', async () => {
|
|
13
|
+
for (const host of ['localhost', '127.0.0.1', '127.1.2.3', '[::1]']) {
|
|
14
|
+
const result = await assertDatabaseWriteAllowed({ ...options(`postgres://fixture:secret@${host}:5432/app`), input: {}, output: {} })
|
|
15
|
+
assert.equal(result.remote, false)
|
|
16
|
+
}
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
test('remote writes fail closed without an exact-target acknowledgment and never reveal credentials', async () => {
|
|
20
|
+
const configuration = options('postgres://owner:fixture-secret@staging.example:6543/app?application_name=query-secret')
|
|
21
|
+
for (const argv of [[], ['--allow-remote-database'], ['--allow-remote-database=other.example:6543/app'], ['--allow-remote-database=staging.example:6543/other']]) {
|
|
22
|
+
await assert.rejects(assertDatabaseWriteAllowed({ ...configuration, argv, input: {}, output: {} }), error => {
|
|
23
|
+
assert.match(error.message, /Remote database writes are blocked for staging\.example:6543\/app/)
|
|
24
|
+
assert.ok(!error.message.includes('fixture-secret')); assert.ok(!error.message.includes('query-secret')); return true
|
|
25
|
+
})
|
|
26
|
+
}
|
|
27
|
+
const accepted = await assertDatabaseWriteAllowed({ ...configuration, argv: ['--allow-remote-database=staging.example:6543/app'], input: {}, output: {} })
|
|
28
|
+
assert.equal(accepted.argument, '--allow-remote-database=staging.example:6543/app')
|
|
29
|
+
assert.equal(accepted.connectionEnv.DATABASE_URL, configuration.env.DATABASE_URL)
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
test('acknowledgment uses real pg connection parameters including URL query overrides', async () => {
|
|
33
|
+
const configuration = options('postgres://fixture:secret@localhost:5432/local?host=production.example&port=6544&database=actual_db')
|
|
34
|
+
const target = resolveDatabaseWriteTarget(configuration)
|
|
35
|
+
assert.equal(target.remote, true); assert.equal(target.target, 'production.example:6544/local')
|
|
36
|
+
await assert.rejects(assertDatabaseWriteAllowed({ ...configuration, argv: ['--allow-remote-database=localhost:5432/local'] }), /blocked/)
|
|
37
|
+
const result = await assertDatabaseWriteAllowed({ ...configuration, argv: ['--allow-remote-database=production.example:6544/local'] })
|
|
38
|
+
const parameters = new pg.Client({ ...result.connectionEnv, connectionString: result.connectionEnv.DATABASE_URL }).connectionParameters
|
|
39
|
+
assert.equal(parameters.host, 'production.example'); assert.equal(parameters.port, 6544); assert.equal(parameters.database, 'local')
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
test('TTY boolean flag requires typing the exact target', async () => {
|
|
43
|
+
const input = new PassThrough(); input.isTTY = true
|
|
44
|
+
const output = new PassThrough(); output.isTTY = true
|
|
45
|
+
const pending = assertDatabaseWriteAllowed({ ...options('postgres://fixture:secret@staging.example/app'), argv: ['--allow-remote-database'], input, output })
|
|
46
|
+
setTimeout(() => input.write('staging.example:5432/app\n'), 5)
|
|
47
|
+
const result = await pending
|
|
48
|
+
assert.equal(result.target, 'staging.example:5432/app')
|
|
49
|
+
input.end(); output.end()
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
test('accepted target captures a connection snapshot instead of reloading edited .env before child writes', async () => {
|
|
53
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'om-write-guard-'))
|
|
54
|
+
try {
|
|
55
|
+
const file = path.join(dir, '.env'); const original = 'postgres://fixture:secret@staging.example:6543/app'
|
|
56
|
+
fs.writeFileSync(file, `DATABASE_URL=${original}\n`)
|
|
57
|
+
const result = await assertDatabaseWriteAllowed({ projectDir: dir, env: {}, loadModule: () => pg, argv: ['--allow-remote-database=staging.example:6543/app'] })
|
|
58
|
+
fs.writeFileSync(file, 'DATABASE_URL=postgres://fixture:secret@production.example/other\n')
|
|
59
|
+
const child = new pg.Client({ connectionString: result.connectionEnv.DATABASE_URL }).connectionParameters
|
|
60
|
+
assert.equal(child.host, 'staging.example'); assert.equal(child.database, 'app'); assert.equal(child.port, 6543)
|
|
61
|
+
assert.equal(result.connectionEnv.DATABASE_URL, original)
|
|
62
|
+
} finally { fs.rmSync(dir, { recursive: true, force: true }) }
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
test('shared guard mirrors are identical and parser retains only acknowledgment flags', () => {
|
|
66
|
+
const source = fs.readFileSync(new URL('../database-write-guard.mjs', import.meta.url))
|
|
67
|
+
for (const target of ['../../../../scripts/dev-database-write-guard.mjs', '../../../create-app/template/scripts/dev-database-write-guard.mjs']) assert.deepEqual(source, fs.readFileSync(new URL(target, import.meta.url)))
|
|
68
|
+
assert.deepEqual(collectRemoteDatabaseFlags(['--reuse-services', '--allow-remote-database', 'host:5432/db', '--classic']), ['--allow-remote-database', 'host:5432/db'])
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
test('the actual starter database step blocks remote mutations before running any child command', async () => {
|
|
72
|
+
const { databaseStep } = await import('../steps.mjs')
|
|
73
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'om-starter-write-'))
|
|
74
|
+
try {
|
|
75
|
+
fs.mkdirSync(path.join(dir, 'apps', 'mercato'), { recursive: true })
|
|
76
|
+
fs.writeFileSync(path.join(dir, 'apps', 'mercato', '.env'), 'DATABASE_URL=postgres://fixture:secret@staging.example/app\n')
|
|
77
|
+
const commands = []
|
|
78
|
+
const context = {
|
|
79
|
+
repoRoot: dir, env: {}, flags: { noInfra: true }, log() {},
|
|
80
|
+
assertDatabaseWriteAllowedImpl: options => assertDatabaseWriteAllowed({ ...options, loadModule: () => pg, input: {}, output: {} }),
|
|
81
|
+
runStreamingImpl(_command, args) { commands.push(args); return 0 },
|
|
82
|
+
}
|
|
83
|
+
await assert.rejects(databaseStep.apply(context), /Remote database writes are blocked/)
|
|
84
|
+
assert.deepEqual(commands, [])
|
|
85
|
+
} finally { fs.rmSync(dir, { recursive: true, force: true }) }
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
test('the starter passes the authorized immutable connection snapshot to migration and initialization children', async () => {
|
|
89
|
+
const { databaseStep } = await import('../steps.mjs')
|
|
90
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'om-starter-snapshot-'))
|
|
91
|
+
try {
|
|
92
|
+
const app = path.join(dir, 'apps', 'mercato'); fs.mkdirSync(app, { recursive: true })
|
|
93
|
+
const file = path.join(app, '.env'); const authorized = 'postgres://fixture:secret@staging.example:6543/app'
|
|
94
|
+
fs.writeFileSync(file, `DATABASE_URL=${authorized}\n`)
|
|
95
|
+
const commands = []
|
|
96
|
+
const context = {
|
|
97
|
+
repoRoot: dir, env: {}, flags: { noInfra: true, remoteDatabaseArgs: ['--allow-remote-database=staging.example:6543/app'] }, log() {},
|
|
98
|
+
dbMarker: 'init-fixture', dbMigrationsMarker: 'migrations-fixture', migrationsFingerprint: 'fixture',
|
|
99
|
+
assertDatabaseWriteAllowedImpl: options => assertDatabaseWriteAllowed({ ...options, loadModule: () => pg, input: {}, output: {} }),
|
|
100
|
+
runStreamingImpl(_command, args, options) {
|
|
101
|
+
commands.push({ args, databaseUrl: options.env.DATABASE_URL })
|
|
102
|
+
fs.writeFileSync(file, 'DATABASE_URL=postgres://fixture:secret@production.example/unacknowledged\n')
|
|
103
|
+
return 0
|
|
104
|
+
},
|
|
105
|
+
}
|
|
106
|
+
await databaseStep.apply(context)
|
|
107
|
+
assert.equal(commands.length, 2)
|
|
108
|
+
assert.ok(commands.every(item => item.databaseUrl === authorized))
|
|
109
|
+
assert.equal(context.remoteDatabaseArgument, '--allow-remote-database=staging.example:6543/app')
|
|
110
|
+
} finally { fs.rmSync(dir, { recursive: true, force: true }) }
|
|
111
|
+
})
|
|
@@ -0,0 +1,412 @@
|
|
|
1
|
+
import assert from 'node:assert/strict'
|
|
2
|
+
import { EventEmitter } from 'node:events'
|
|
3
|
+
import { test } from 'node:test'
|
|
4
|
+
|
|
5
|
+
import { findContainerPortOwners, formatInfraProblem, requestExistingServicesConsent, startInfraServices, suggestFreePorts } from '../infra-preflight.mjs'
|
|
6
|
+
import { devRuntimeArgs } from '../infra.mjs'
|
|
7
|
+
import { infraUpStep, runSteps } from '../steps.mjs'
|
|
8
|
+
import { ensureInfra } from '../../../create-app/template/scripts/infra.mjs'
|
|
9
|
+
import { createSetupLogs } from '../setup-logs.mjs'
|
|
10
|
+
|
|
11
|
+
test('existing-service consent suspends compact input and displays guidance on every outcome', async () => {
|
|
12
|
+
for (const answer of [true, false, 'error']) {
|
|
13
|
+
const input = new EventEmitter()
|
|
14
|
+
Object.assign(input, { isTTY: true, isRaw: false, readableFlowing: false,
|
|
15
|
+
setRawMode(value) { this.isRaw = value }, resume() { this.readableFlowing = true }, pause() { this.readableFlowing = false } })
|
|
16
|
+
const terminal = []
|
|
17
|
+
const logs = createSetupLogs({ input, env: {}, output: { isTTY: true, write(line) { terminal.push(String(line)) } } })
|
|
18
|
+
const visible = []
|
|
19
|
+
const ctx = {
|
|
20
|
+
logs, mode: 'hybrid', flags: { noInfra: false, profiles: [] }, log: (line) => visible.push(String(line)),
|
|
21
|
+
runComposeImpl: () => ({ status: 0, stdout: '' }),
|
|
22
|
+
startInfraImpl: async () => ({ ok: false, problem: conflict() }),
|
|
23
|
+
confirmExistingServicesImpl: async (_problem, options) => {
|
|
24
|
+
assert.equal(input.isRaw, false)
|
|
25
|
+
assert.equal(input.listenerCount('data'), 0)
|
|
26
|
+
options.log('Review the existing services before consenting')
|
|
27
|
+
input.emit('data', 'd')
|
|
28
|
+
assert.ok(!terminal.join('').includes('Raw logs shown'))
|
|
29
|
+
if (answer === 'error') throw new Error('consent input failed')
|
|
30
|
+
return answer
|
|
31
|
+
},
|
|
32
|
+
}
|
|
33
|
+
const outcome = await runSteps([infraUpStep], ctx)
|
|
34
|
+
assert.equal(outcome.ok, answer === true)
|
|
35
|
+
assert.ok(visible.includes('Review the existing services before consenting'))
|
|
36
|
+
assert.equal(input.isRaw, false)
|
|
37
|
+
assert.equal(input.listenerCount('data'), 0)
|
|
38
|
+
assert.equal(input.readableFlowing, false)
|
|
39
|
+
assert.equal(ctx.promptLog, undefined)
|
|
40
|
+
if (answer === true) assert.equal(ctx.flags.noInfra, true)
|
|
41
|
+
}
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
const SERVICES = [
|
|
45
|
+
{ service: 'postgres', port: 5432, envKey: 'POSTGRES_PORT' },
|
|
46
|
+
{ service: 'redis', port: 6379, envKey: 'REDIS_PORT' },
|
|
47
|
+
]
|
|
48
|
+
|
|
49
|
+
function fakeContainerScan(entries) {
|
|
50
|
+
const calls = []
|
|
51
|
+
const spawnSyncImpl = (command, args) => {
|
|
52
|
+
calls.push({ command, args })
|
|
53
|
+
if (args[0] === 'ps') return { status: 0, stdout: entries.map((_, index) => index.toString(16).padStart(12, '0')).join('\n') }
|
|
54
|
+
if (args[0] === 'inspect') return { status: 0, stdout: entries.map((entry) => JSON.stringify(entry)).join('\n') }
|
|
55
|
+
throw new Error(`Unexpected Docker command: ${args[0]}`)
|
|
56
|
+
}
|
|
57
|
+
return { calls, spawnSyncImpl }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function owner(overrides = {}) {
|
|
61
|
+
return {
|
|
62
|
+
...SERVICES[0],
|
|
63
|
+
containerName: 'mercato-postgres',
|
|
64
|
+
state: 'running',
|
|
65
|
+
health: 'healthy',
|
|
66
|
+
...overrides,
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function conflict(ports = [owner()]) {
|
|
71
|
+
return { code: 'port-conflict', ports }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
test('container discovery finds published port owners across Compose project identities without mutating Docker', () => {
|
|
75
|
+
const fake = fakeContainerScan([
|
|
76
|
+
{ name: '/previous-postgres', status: 'running', health: 'healthy', ports: { '5432/tcp': [{ HostIp: '0.0.0.0', HostPort: '5432' }] } },
|
|
77
|
+
{ name: '/unrelated-postgres', status: 'running', health: 'healthy', ports: { '5432/tcp': [{ HostIp: '127.0.0.1', HostPort: '55432' }] } },
|
|
78
|
+
{ name: '/stopped-redis', status: 'exited', health: '', ports: { '6379/tcp': [{ HostIp: '0.0.0.0', HostPort: '6379' }] } },
|
|
79
|
+
])
|
|
80
|
+
|
|
81
|
+
const found = findContainerPortOwners(SERVICES, fake)
|
|
82
|
+
|
|
83
|
+
assert.deepEqual(found, [owner({ containerName: 'previous-postgres' })])
|
|
84
|
+
assert.deepEqual(fake.calls.map(({ args }) => args[0]), ['ps', 'inspect'])
|
|
85
|
+
assert.ok(fake.calls[0].args.includes('status=running'))
|
|
86
|
+
assert.ok(fake.calls[0].args.includes('status=restarting'))
|
|
87
|
+
assert.ok(fake.calls[1].args.includes('--format'))
|
|
88
|
+
assert.ok(fake.calls.every(({ command }) => command === 'docker'))
|
|
89
|
+
})
|
|
90
|
+
|
|
91
|
+
test('container discovery retains restarting owners and de-duplicates IPv4 and IPv6 bindings', () => {
|
|
92
|
+
const fake = fakeContainerScan([
|
|
93
|
+
{ name: '/mercato-postgres', status: 'restarting', health: 'unhealthy', ports: { '5432/tcp': [
|
|
94
|
+
{ HostIp: '0.0.0.0', HostPort: '5432' },
|
|
95
|
+
{ HostIp: '::', HostPort: '5432' },
|
|
96
|
+
] } },
|
|
97
|
+
])
|
|
98
|
+
|
|
99
|
+
assert.deepEqual(findContainerPortOwners(SERVICES, fake), [owner({ state: 'restarting', health: 'unhealthy' })])
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
test('container discovery does not infer an owner when Docker inspection fails', () => {
|
|
103
|
+
const calls = []
|
|
104
|
+
const found = findContainerPortOwners(SERVICES, {
|
|
105
|
+
spawnSyncImpl: (command, args) => {
|
|
106
|
+
calls.push(args[0])
|
|
107
|
+
return args[0] === 'ps'
|
|
108
|
+
? { status: 0, stdout: 'abcdef123456\n' }
|
|
109
|
+
: { status: 1, stdout: '', stderr: 'container disappeared' }
|
|
110
|
+
},
|
|
111
|
+
})
|
|
112
|
+
|
|
113
|
+
assert.deepEqual(found, [])
|
|
114
|
+
assert.deepEqual(calls, ['ps', 'inspect'])
|
|
115
|
+
})
|
|
116
|
+
|
|
117
|
+
test('restarting cross-project containers block startup even while their TCP port is briefly closed', async () => {
|
|
118
|
+
const calls = []
|
|
119
|
+
const restarting = owner({ state: 'restarting', health: 'unhealthy' })
|
|
120
|
+
const outcome = await startInfraServices({
|
|
121
|
+
services: SERVICES,
|
|
122
|
+
composeArgs: (extra) => ['compose', ...extra],
|
|
123
|
+
detect: () => ({ ok: true }),
|
|
124
|
+
spawnSyncImpl: (command, args) => {
|
|
125
|
+
calls.push(args)
|
|
126
|
+
return { status: 0, stdout: '' }
|
|
127
|
+
},
|
|
128
|
+
portProbe: async () => false,
|
|
129
|
+
containerProbe: () => [restarting],
|
|
130
|
+
beforeUp: () => assert.fail('image preparation must not run while an existing container owns the port'),
|
|
131
|
+
log: () => {},
|
|
132
|
+
})
|
|
133
|
+
|
|
134
|
+
assert.equal(outcome.ok, false)
|
|
135
|
+
assert.equal(outcome.problem.code, 'port-conflict')
|
|
136
|
+
assert.deepEqual(outcome.problem.ports, [{ ...restarting, suggestedPort: restarting.port + 1 }])
|
|
137
|
+
assert.ok(calls.every((args) => !args.includes('up') && !args.includes('stop') && !args.includes('down')))
|
|
138
|
+
})
|
|
139
|
+
|
|
140
|
+
test('port conflicts suggest the next free port, skipping taken ones and ports suggested for another service', async () => {
|
|
141
|
+
const taken = new Set([5433, 6380])
|
|
142
|
+
const suggested = await suggestFreePorts(
|
|
143
|
+
[{ service: 'postgres', envKey: 'POSTGRES_PORT', port: 5432 }, { service: 'redis', envKey: 'REDIS_PORT', port: 6379 }],
|
|
144
|
+
{ probe: async (port) => taken.has(port), reserved: [5432, 6379, 5435] },
|
|
145
|
+
)
|
|
146
|
+
assert.deepEqual(suggested.map((entry) => entry.suggestedPort), [5434, 6381])
|
|
147
|
+
const skipped = await suggestFreePorts([{ service: 'postgres', envKey: 'POSTGRES_PORT', port: 5432 }], { probe: async () => false, reserved: [5433] })
|
|
148
|
+
assert.equal(skipped[0].suggestedPort, 5434, 'a port configured for another service in the stack is never suggested')
|
|
149
|
+
const text = formatInfraProblem({ code: 'port-conflict', ports: suggested }, { output: { isTTY: false }, env: {} }).join('\n')
|
|
150
|
+
assert.match(text, /set POSTGRES_PORT=5434 in \.env/)
|
|
151
|
+
assert.match(text, /\(:5432 -> :5434\)/)
|
|
152
|
+
})
|
|
153
|
+
|
|
154
|
+
test('running services in this Compose project do not become foreign port conflicts', async () => {
|
|
155
|
+
const inspectedServices = []
|
|
156
|
+
const outcome = await startInfraServices({
|
|
157
|
+
services: SERVICES,
|
|
158
|
+
composeArgs: (extra) => ['compose', ...extra],
|
|
159
|
+
detect: () => ({ ok: true }),
|
|
160
|
+
spawnSyncImpl: (command, args) => ({
|
|
161
|
+
status: 0,
|
|
162
|
+
stdout: args.includes('ps') ? JSON.stringify({ Service: 'postgres', State: 'running', Health: 'healthy' }) : '',
|
|
163
|
+
}),
|
|
164
|
+
portProbe: async () => false,
|
|
165
|
+
containerProbe: (services) => {
|
|
166
|
+
inspectedServices.push(...services)
|
|
167
|
+
return []
|
|
168
|
+
},
|
|
169
|
+
log: () => {},
|
|
170
|
+
})
|
|
171
|
+
|
|
172
|
+
assert.equal(outcome.ok, true)
|
|
173
|
+
assert.deepEqual(outcome.reused, ['postgres'])
|
|
174
|
+
assert.ok(inspectedServices.every(({ service }) => service !== 'postgres'))
|
|
175
|
+
})
|
|
176
|
+
|
|
177
|
+
test('existing-services consent defaults to no and never prompts without an interactive terminal', async () => {
|
|
178
|
+
const messages = []
|
|
179
|
+
const question = async () => assert.fail('non-interactive setup must not prompt')
|
|
180
|
+
const options = { question, log: (line) => messages.push(line) }
|
|
181
|
+
|
|
182
|
+
assert.equal(await requestExistingServicesConsent(conflict(), { ...options, nonInteractive: true }), false)
|
|
183
|
+
assert.equal(await requestExistingServicesConsent(conflict(), { input: { isTTY: false }, log: options.log }), false)
|
|
184
|
+
assert.equal(await requestExistingServicesConsent(conflict(), { ...options, question: async () => '' }), false)
|
|
185
|
+
assert.equal(await requestExistingServicesConsent(conflict(), { ...options, question: async () => 'no' }), false)
|
|
186
|
+
assert.match(messages.join('\n'), /yarn om stop/)
|
|
187
|
+
})
|
|
188
|
+
|
|
189
|
+
test('existing-services consent requires explicit yes and discloses restarting or unhealthy containers', async () => {
|
|
190
|
+
for (const answer of ['y', 'yes']) {
|
|
191
|
+
const messages = []
|
|
192
|
+
const accepted = await requestExistingServicesConsent(conflict([owner({ state: 'restarting', health: 'unhealthy' })]), {
|
|
193
|
+
question: async () => answer,
|
|
194
|
+
log: (line) => messages.push(line),
|
|
195
|
+
})
|
|
196
|
+
|
|
197
|
+
assert.equal(accepted, true)
|
|
198
|
+
assert.match(messages.join('\n'), /mercato-postgres/)
|
|
199
|
+
assert.match(messages.join('\n'), /restart|unhealthy/i)
|
|
200
|
+
assert.match(messages.join('\n'), /yarn om stop/)
|
|
201
|
+
}
|
|
202
|
+
})
|
|
203
|
+
|
|
204
|
+
test('accepted existing infrastructure continues setup without restarting it and forwards no-infra to dev', async () => {
|
|
205
|
+
const calls = []
|
|
206
|
+
const problem = conflict()
|
|
207
|
+
const ctx = {
|
|
208
|
+
repoRoot: '/repo',
|
|
209
|
+
mode: 'hybrid',
|
|
210
|
+
flags: { noInfra: false, nonInteractive: false, profiles: [] },
|
|
211
|
+
log: () => {},
|
|
212
|
+
runComposeImpl: () => ({ status: 0, stdout: '' }),
|
|
213
|
+
startInfraImpl: async () => {
|
|
214
|
+
calls.push('inspect-existing')
|
|
215
|
+
return { ok: false, problem }
|
|
216
|
+
},
|
|
217
|
+
ensureOpencodeImageImpl: () => assert.fail('accepted existing infrastructure must not rebuild images'),
|
|
218
|
+
confirmExistingServicesImpl: async (found) => {
|
|
219
|
+
assert.deepEqual(found, problem)
|
|
220
|
+
calls.push('consent')
|
|
221
|
+
return true
|
|
222
|
+
},
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
const outcome = await runSteps([
|
|
226
|
+
infraUpStep,
|
|
227
|
+
{ id: 'continued', title: 'Continue setup', async apply() { calls.push('continue') } },
|
|
228
|
+
], ctx)
|
|
229
|
+
|
|
230
|
+
assert.equal(outcome.ok, true)
|
|
231
|
+
assert.equal(ctx.existingInfraAccepted, true)
|
|
232
|
+
assert.equal(ctx.flags.noInfra, true)
|
|
233
|
+
assert.deepEqual(calls, ['inspect-existing', 'consent', 'continue'])
|
|
234
|
+
assert.deepEqual(devRuntimeArgs([], ctx.flags), ['--no-infra'])
|
|
235
|
+
})
|
|
236
|
+
|
|
237
|
+
test('declined infrastructure reuse stops setup and gives the non-destructive stop command', async () => {
|
|
238
|
+
const messages = []
|
|
239
|
+
const outcome = await runSteps([
|
|
240
|
+
infraUpStep,
|
|
241
|
+
{ id: 'continued', title: 'Continue setup', async apply() { assert.fail('declined reuse must stop setup') } },
|
|
242
|
+
], {
|
|
243
|
+
repoRoot: '/repo',
|
|
244
|
+
mode: 'hybrid',
|
|
245
|
+
flags: { noInfra: false, nonInteractive: true, profiles: [] },
|
|
246
|
+
log: (line) => messages.push(line),
|
|
247
|
+
runComposeImpl: () => ({ status: 0, stdout: '' }),
|
|
248
|
+
startInfraImpl: async () => ({ ok: false, problem: conflict() }),
|
|
249
|
+
confirmExistingServicesImpl: async () => false,
|
|
250
|
+
ensureOpencodeImageImpl: () => assert.fail('declined reuse must not mutate images'),
|
|
251
|
+
})
|
|
252
|
+
|
|
253
|
+
assert.equal(outcome.ok, false)
|
|
254
|
+
assert.equal(outcome.failedStep, 'infra-up')
|
|
255
|
+
assert.match(messages.join('\n'), /yarn om stop/)
|
|
256
|
+
})
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
test('standalone setup accepts existing services only after explicit confirmation', async () => {
|
|
260
|
+
const problem = conflict([owner({ state: 'restarting', health: 'unhealthy' })])
|
|
261
|
+
const calls = []
|
|
262
|
+
const outcome = await ensureInfra({
|
|
263
|
+
projectDir: '/missing-standalone-fixture',
|
|
264
|
+
env: {},
|
|
265
|
+
allowExistingServices: true,
|
|
266
|
+
startImpl: async () => {
|
|
267
|
+
calls.push('detect')
|
|
268
|
+
return { ok: false, problem }
|
|
269
|
+
},
|
|
270
|
+
confirmExistingServices: async (found) => {
|
|
271
|
+
assert.deepEqual(found, problem)
|
|
272
|
+
calls.push('consent')
|
|
273
|
+
return true
|
|
274
|
+
},
|
|
275
|
+
log: () => {},
|
|
276
|
+
error: () => assert.fail('accepted services must not produce a setup failure'),
|
|
277
|
+
})
|
|
278
|
+
|
|
279
|
+
assert.deepEqual(outcome, { ok: true, existingServices: true })
|
|
280
|
+
assert.deepEqual(calls, ['detect', 'consent'])
|
|
281
|
+
})
|
|
282
|
+
|
|
283
|
+
test('standalone setup preserves the conflict when reuse is declined or not enabled', async () => {
|
|
284
|
+
for (const allowExistingServices of [true, false]) {
|
|
285
|
+
let confirmations = 0
|
|
286
|
+
const failure = { ok: false, problem: conflict() }
|
|
287
|
+
const outcome = await ensureInfra({
|
|
288
|
+
projectDir: '/missing-standalone-fixture',
|
|
289
|
+
env: {},
|
|
290
|
+
allowExistingServices,
|
|
291
|
+
startImpl: async () => failure,
|
|
292
|
+
confirmExistingServices: async () => {
|
|
293
|
+
confirmations += 1
|
|
294
|
+
return false
|
|
295
|
+
},
|
|
296
|
+
log: () => {},
|
|
297
|
+
error: () => {},
|
|
298
|
+
})
|
|
299
|
+
|
|
300
|
+
assert.deepEqual(outcome, failure)
|
|
301
|
+
assert.equal(confirmations, allowExistingServices ? 1 : 0)
|
|
302
|
+
assert.equal(outcome.existingServices, undefined)
|
|
303
|
+
}
|
|
304
|
+
})
|
|
305
|
+
|
|
306
|
+
test('standalone setup does not offer reuse for an unavailable Docker daemon', async () => {
|
|
307
|
+
const failure = { ok: false, problem: { code: 'daemon-stopped', detail: 'engine unavailable' } }
|
|
308
|
+
const outcome = await ensureInfra({
|
|
309
|
+
projectDir: '/missing-standalone-fixture',
|
|
310
|
+
env: {},
|
|
311
|
+
allowExistingServices: true,
|
|
312
|
+
startImpl: async () => failure,
|
|
313
|
+
confirmExistingServices: async () => assert.fail('a runtime failure cannot authorize existing-service reuse'),
|
|
314
|
+
log: () => {},
|
|
315
|
+
error: () => {},
|
|
316
|
+
})
|
|
317
|
+
|
|
318
|
+
assert.deepEqual(outcome, failure)
|
|
319
|
+
})
|
|
320
|
+
|
|
321
|
+
test('standalone setup requires consent before using a reachable configured database without Docker', async () => {
|
|
322
|
+
const failure = { ok: false, problem: { code: 'daemon-stopped', detail: 'engine unavailable' } }
|
|
323
|
+
for (const accepted of [false, true]) {
|
|
324
|
+
let confirmations = 0
|
|
325
|
+
const outcome = await ensureInfra({
|
|
326
|
+
projectDir: '/missing-standalone-fixture',
|
|
327
|
+
env: { DATABASE_URL: 'postgres://postgres:postgres@db.example.test:5544/open_mercato' },
|
|
328
|
+
allowExistingServices: true,
|
|
329
|
+
startImpl: async () => failure,
|
|
330
|
+
databaseProbe: async (port, options) => {
|
|
331
|
+
assert.equal(port, 5544)
|
|
332
|
+
assert.equal(options.host, 'db.example.test')
|
|
333
|
+
return true
|
|
334
|
+
},
|
|
335
|
+
confirmExistingServices: async (problem) => {
|
|
336
|
+
confirmations += 1
|
|
337
|
+
assert.equal(problem.configuredServices, true)
|
|
338
|
+
assert.deepEqual(problem.services, [{ service: 'postgres', host: 'db.example.test', port: 5544, state: 'reachable' }])
|
|
339
|
+
return accepted
|
|
340
|
+
},
|
|
341
|
+
log: () => {},
|
|
342
|
+
error: () => {},
|
|
343
|
+
})
|
|
344
|
+
|
|
345
|
+
assert.deepEqual(outcome, accepted ? { ok: true, existingServices: true } : failure)
|
|
346
|
+
assert.equal(confirmations, 1)
|
|
347
|
+
}
|
|
348
|
+
})
|
|
349
|
+
|
|
350
|
+
for (const state of ['running', 'restarting']) {
|
|
351
|
+
test(`setup preserves existing ${state} unhealthy project services before consent`, async () => {
|
|
352
|
+
for (const mode of ['monorepo', 'standalone']) {
|
|
353
|
+
const calls = []
|
|
354
|
+
const startImpl = async (options) => startInfraServices({
|
|
355
|
+
...options,
|
|
356
|
+
detect: () => ({ ok: true }),
|
|
357
|
+
spawnSyncImpl: (_command, args) => {
|
|
358
|
+
calls.push(args)
|
|
359
|
+
if (!args.includes('ps')) assert.fail('setup must inspect existing unhealthy services without changing containers')
|
|
360
|
+
return { status: 0, stdout: JSON.stringify({ Service: 'postgres', Name: 'existing-postgres', State: state, Health: 'unhealthy' }) }
|
|
361
|
+
},
|
|
362
|
+
beforeUp: () => assert.fail('image preparation must wait for the existing-service decision'),
|
|
363
|
+
portProbe: async () => false,
|
|
364
|
+
containerProbe: () => [],
|
|
365
|
+
processProbe: () => [],
|
|
366
|
+
})
|
|
367
|
+
const confirm = async (problem) => {
|
|
368
|
+
assert.equal(problem.code, 'unhealthy')
|
|
369
|
+
assert.equal(problem.existingServices, true)
|
|
370
|
+
assert.equal(problem.services[0].containerName, 'existing-postgres')
|
|
371
|
+
return true
|
|
372
|
+
}
|
|
373
|
+
if (mode === 'standalone') {
|
|
374
|
+
const outcome = await ensureInfra({ projectDir: '/missing-standalone-fixture', env: {}, allowExistingServices: true, startImpl, confirmExistingServices: confirm, log: () => {}, error: () => assert.fail('reuse must continue') })
|
|
375
|
+
assert.deepEqual(outcome, { ok: true, existingServices: true })
|
|
376
|
+
} else {
|
|
377
|
+
const ctx = { repoRoot: '/repo', mode: 'hybrid', flags: { noInfra: false, nonInteractive: false, profiles: [] }, log: () => {}, startInfraImpl: async (_root, options) => startImpl({ ...options, services: SERVICES, composeArgs: (extra) => ['compose', ...extra] }), confirmExistingServicesImpl: confirm }
|
|
378
|
+
await infraUpStep.apply(ctx)
|
|
379
|
+
assert.equal(ctx.flags.noInfra, true)
|
|
380
|
+
assert.deepEqual(devRuntimeArgs([], ctx.flags), ['--no-infra'])
|
|
381
|
+
}
|
|
382
|
+
assert.equal(calls.length, 1)
|
|
383
|
+
}
|
|
384
|
+
})
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
test('direct infrastructure startup retains its explicit unhealthy-service retry', async () => {
|
|
388
|
+
let prepared = false
|
|
389
|
+
const calls = []
|
|
390
|
+
const outcome = await startInfraServices({
|
|
391
|
+
services: SERVICES,
|
|
392
|
+
composeArgs: (extra) => ['compose', ...extra],
|
|
393
|
+
detect: () => ({ ok: true }),
|
|
394
|
+
spawnSyncImpl: (_command, args) => {
|
|
395
|
+
calls.push(args)
|
|
396
|
+
return { status: 0, stdout: args.includes('ps') ? JSON.stringify({ Service: 'postgres', State: 'running', Health: 'unhealthy' }) : '' }
|
|
397
|
+
},
|
|
398
|
+
beforeUp: () => { prepared = true },
|
|
399
|
+
portProbe: async () => false,
|
|
400
|
+
containerProbe: () => [],
|
|
401
|
+
log: () => {},
|
|
402
|
+
})
|
|
403
|
+
assert.equal(outcome.ok, true)
|
|
404
|
+
assert.equal(prepared, true)
|
|
405
|
+
assert.ok(calls.some((args) => args.includes('up')))
|
|
406
|
+
})
|
|
407
|
+
|
|
408
|
+
test('a failed new startup cannot claim it left existing services untouched', async () => {
|
|
409
|
+
const failure = { ok: false, problem: { code: 'unhealthy', services: [{ service: 'postgres', state: 'running', health: 'unhealthy' }] } }
|
|
410
|
+
const outcome = await ensureInfra({ projectDir: '/missing-standalone-fixture', env: {}, allowExistingServices: true, startImpl: async () => failure, confirmExistingServices: async () => assert.fail('post-startup health failure must remain an error'), log: () => {}, error: () => {} })
|
|
411
|
+
assert.deepEqual(outcome, failure)
|
|
412
|
+
})
|