@open-mercato/starter 0.10.1-develop.7900.1.69c0120c72 → 0.10.1-develop.7907.1.28240ddda3
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 +6 -1
- package/package.json +1 -1
- package/src/__tests__/starter.test.mjs +351 -3
- package/src/cli.mjs +29 -14
- package/src/compose.mjs +9 -37
- package/src/doctor.mjs +8 -0
- package/src/infra-preflight.mjs +281 -0
- package/src/infra.mjs +74 -1
- package/src/steps.mjs +35 -17
package/README.md
CHANGED
|
@@ -7,9 +7,14 @@ The central, cross-platform way to stand up an Open Mercato dev environment. One
|
|
|
7
7
|
npx @open-mercato/starter
|
|
8
8
|
|
|
9
9
|
# Inside a clone:
|
|
10
|
+
yarn setup # same as `yarn om up`: everything from install to a running app
|
|
10
11
|
yarn om # alias for node packages/starter/bin/om-start.mjs
|
|
11
12
|
```
|
|
12
13
|
|
|
14
|
+
`yarn setup` checks Docker (CLI, Compose v2, a running engine), refuses ports another process already holds, starts PostgreSQL, Redis, Meilisearch and OpenCode, and waits for their healthchecks before it touches the database. Each failure says what to fix. Nothing installs Docker or asks for sudo. Already running those services yourself? `yarn setup --no-infra` skips every Docker call and uses the URLs in your `.env`. Re-running is safe: containers and volumes are reused, `.env` values are never overwritten.
|
|
15
|
+
|
|
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
|
+
|
|
13
18
|
No Node yet? The package ships pre-Node bootstraps that install a **portable, checksum-verified Node 24 without admin rights**, then run the CLI:
|
|
14
19
|
|
|
15
20
|
- **Windows**: double-click `packages\starter\platform\start.cmd`, or `irm https://raw.githubusercontent.com/open-mercato/open-mercato/main/packages/starter/platform/start.ps1 | iex`
|
|
@@ -29,7 +34,7 @@ No Node yet? The package ships pre-Node bootstraps that install a **portable, ch
|
|
|
29
34
|
| `reset` | Destructive cleanup (containers, volumes, starter state) — asks first. |
|
|
30
35
|
| `infra up\|down` | Just the infra containers. |
|
|
31
36
|
|
|
32
|
-
Useful flags: `--non-interactive`, `--skip-llm-prompt`, `--skip-db`, `--no-infra
|
|
37
|
+
Useful flags: `--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>`.
|
|
33
38
|
|
|
34
39
|
`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).
|
|
35
40
|
|
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.7907.1.28240ddda3",
|
|
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",
|
|
@@ -5,15 +5,16 @@ import os from 'node:os'
|
|
|
5
5
|
import path from 'node:path'
|
|
6
6
|
import { test } from 'node:test'
|
|
7
7
|
|
|
8
|
-
import { parseComposePsOutput, resolveRepoRoot } from '../compose.mjs'
|
|
8
|
+
import { detectDocker, parseComposePsOutput, resolveRepoRoot } from '../compose.mjs'
|
|
9
9
|
import { hostTrustEnv, summarizeProbeResults, writeCaBundle } from '../certs.mjs'
|
|
10
10
|
import { DEFAULT_OPENCODE_BASE_IMAGE, DEFAULT_PORTS, resolveStackPorts } from '../constants.mjs'
|
|
11
11
|
import { addEnvValue, readEnvValue, setEnvValue } from '../env-file.mjs'
|
|
12
12
|
import { ensureLlmProvider, syncProviderConfigToAppEnv } from '../providers.mjs'
|
|
13
13
|
import { ensureWindowsUtf8Console, resolveSpawnCommand } from '../spawn.mjs'
|
|
14
|
-
import { StepBlocked, buildToolchainStep, clearConvergenceState, databaseIsInitialized, listMigrationModules, migrationsFingerprint, probePostgresCredentials, readAppliedMigrationModules, resolveOpencodeBaseImage, runSteps, workspaceBuildStep } from '../steps.mjs'
|
|
14
|
+
import { StepBlocked, buildToolchainStep, containerRuntimeStep, databaseStep, hostGatewayStep, infraUpStep, clearConvergenceState, databaseIsInitialized, listMigrationModules, migrationsFingerprint, probePostgresCredentials, readAppliedMigrationModules, resolveOpencodeBaseImage, runSteps, workspaceBuildStep } from '../steps.mjs'
|
|
15
15
|
import { ensureEnvFiles } from '../env-setup.mjs'
|
|
16
|
-
import { removeLeftoverComposeResources } from '../infra.mjs'
|
|
16
|
+
import { describeInfraProblem, devRuntimeArgs, externalDatabaseHost, removeLeftoverComposeResources, resolveUpMode, startInfra } from '../infra.mjs'
|
|
17
|
+
import { detectDockerRuntime, detectWsl, findPortConflicts, findUnhealthyServices, formatInfraProblem, startInfraServices } from '../infra-preflight.mjs'
|
|
17
18
|
import { checkBuildToolchain, defenderExclusionCovers, detectHostGateway, hostIpCandidates } from '../doctor.mjs'
|
|
18
19
|
|
|
19
20
|
function makeTempDir(prefix) {
|
|
@@ -555,3 +556,350 @@ test('databaseIsInitialized reads the seeded-users probe and tolerates a missing
|
|
|
555
556
|
assert.equal(databaseIsInitialized(ctx, { runComposeImpl: () => ({ status: 1, stdout: '' }) }), null)
|
|
556
557
|
assert.equal(databaseIsInitialized(ctx, { runComposeImpl: () => { throw new Error('down') } }), null)
|
|
557
558
|
})
|
|
559
|
+
|
|
560
|
+
function fakeDockerProbe(responses) {
|
|
561
|
+
const calls = []
|
|
562
|
+
const probe = (args) => {
|
|
563
|
+
calls.push(args.join(' '))
|
|
564
|
+
return responses[args[0]] ?? { status: 0, stdout: '' }
|
|
565
|
+
}
|
|
566
|
+
return { probe, calls }
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
test('detectDockerRuntime distinguishes missing CLI, missing compose, stopped daemon, no permission and a hung daemon', () => {
|
|
570
|
+
const missingCli = fakeDockerProbe({ '--version': { error: Object.assign(new Error('spawn docker ENOENT'), { code: 'ENOENT' }) } })
|
|
571
|
+
assert.equal(detectDockerRuntime({ probe: missingCli.probe }).code, 'cli-missing')
|
|
572
|
+
assert.deepEqual(missingCli.calls, ['--version'])
|
|
573
|
+
|
|
574
|
+
assert.equal(detectDockerRuntime(fakeDockerProbe({ compose: { status: 1, stderr: "docker: 'compose' is not a docker command." } })).code, 'compose-missing')
|
|
575
|
+
assert.equal(detectDockerRuntime(fakeDockerProbe({ info: { status: 1, stderr: 'Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?' } })).code, 'daemon-stopped')
|
|
576
|
+
assert.equal(detectDockerRuntime(fakeDockerProbe({ info: { status: 1, stderr: 'permission denied while trying to connect to the Docker daemon socket' } })).code, 'daemon-permission')
|
|
577
|
+
assert.equal(detectDockerRuntime(fakeDockerProbe({ info: { error: Object.assign(new Error('timed out'), { code: 'ETIMEDOUT' }) } })).code, 'daemon-unresponsive')
|
|
578
|
+
|
|
579
|
+
const ok = detectDockerRuntime(fakeDockerProbe({ info: { status: 0, stdout: '27.3.1\n' } }))
|
|
580
|
+
assert.equal(ok.ok, true)
|
|
581
|
+
assert.equal(ok.serverVersion, '27.3.1')
|
|
582
|
+
})
|
|
583
|
+
|
|
584
|
+
test('detectDocker keeps the human reason for doctor and adds the problem code', () => {
|
|
585
|
+
const stopped = detectDocker(fakeDockerProbe({ info: { status: 1, stderr: 'Cannot connect to the Docker daemon' } }))
|
|
586
|
+
assert.deepEqual(stopped, { ok: false, code: 'daemon-stopped', reason: 'docker engine not running' })
|
|
587
|
+
})
|
|
588
|
+
|
|
589
|
+
test('formatInfraProblem explains the fix and always offers the --no-infra opt-out', () => {
|
|
590
|
+
for (const code of ['cli-missing', 'compose-missing', 'daemon-stopped', 'daemon-unresponsive', 'daemon-permission', 'compose-failed']) {
|
|
591
|
+
const lines = formatInfraProblem({ code }, { platform: 'linux', wsl: false })
|
|
592
|
+
assert.ok(lines.length >= 3, code)
|
|
593
|
+
assert.match(lines.join('\n'), /yarn setup --no-infra/, code)
|
|
594
|
+
}
|
|
595
|
+
assert.match(formatInfraProblem({ code: 'cli-missing' }, { platform: 'darwin' }).join('\n'), /never installs Docker/)
|
|
596
|
+
assert.match(formatInfraProblem({ code: 'daemon-stopped' }, { platform: 'linux', wsl: false }).join('\n'), /systemctl start docker/)
|
|
597
|
+
const ports = formatInfraProblem({ code: 'port-conflict', ports: [{ service: 'postgres', port: 5432, envKey: 'POSTGRES_PORT' }] }).join('\n')
|
|
598
|
+
assert.match(ports, /Port 5432 \(postgres\) is already in use/)
|
|
599
|
+
assert.match(ports, /POSTGRES_PORT in \.env/)
|
|
600
|
+
const unhealthy = formatInfraProblem({ code: 'unhealthy', services: [{ service: 'meilisearch', state: 'running', health: 'unhealthy' }], logsCommand: 'docker compose logs meilisearch' }).join('\n')
|
|
601
|
+
assert.match(unhealthy, /meilisearch: running \(unhealthy\)/)
|
|
602
|
+
assert.match(unhealthy, /docker compose logs meilisearch/)
|
|
603
|
+
})
|
|
604
|
+
|
|
605
|
+
test('findPortConflicts only probes services that are not already running in the project', async () => {
|
|
606
|
+
const probed = []
|
|
607
|
+
const conflicts = await findPortConflicts([
|
|
608
|
+
{ service: 'postgres', port: 5432, envKey: 'POSTGRES_PORT' },
|
|
609
|
+
{ service: 'redis', port: 6379, envKey: 'REDIS_PORT' },
|
|
610
|
+
], { running: new Set(['postgres']), probe: async (port) => { probed.push(port); return true } })
|
|
611
|
+
assert.deepEqual(probed, [6379])
|
|
612
|
+
assert.deepEqual(conflicts.map((entry) => entry.service), ['redis'])
|
|
613
|
+
})
|
|
614
|
+
|
|
615
|
+
test('findUnhealthyServices flags missing, exited and failing-healthcheck services', () => {
|
|
616
|
+
const entries = parseComposePsOutput([
|
|
617
|
+
JSON.stringify({ Service: 'postgres', State: 'running', Health: 'healthy' }),
|
|
618
|
+
JSON.stringify({ Service: 'redis', State: 'exited', Health: '' }),
|
|
619
|
+
JSON.stringify({ Service: 'meilisearch', State: 'running', Health: 'unhealthy' }),
|
|
620
|
+
JSON.stringify({ Service: 'opencode', State: 'running', Health: '' }),
|
|
621
|
+
].join('\n'))
|
|
622
|
+
assert.deepEqual(findUnhealthyServices(entries, ['postgres', 'redis', 'meilisearch', 'opencode', 'keycloak']).map((entry) => entry.service), ['redis', 'meilisearch', 'keycloak'])
|
|
623
|
+
})
|
|
624
|
+
|
|
625
|
+
function fakeComposeSpawn({ psBefore = [], psAfter = psBefore, upStatus = 0 } = {}) {
|
|
626
|
+
const calls = []
|
|
627
|
+
let upRan = false
|
|
628
|
+
const spawnSyncImpl = (command, args) => {
|
|
629
|
+
calls.push(args.join(' '))
|
|
630
|
+
if (args.includes('ps')) return { status: 0, stdout: (upRan ? psAfter : psBefore).map((entry) => JSON.stringify(entry)).join('\n') }
|
|
631
|
+
if (args.includes('up')) {
|
|
632
|
+
upRan = true
|
|
633
|
+
return { status: upStatus }
|
|
634
|
+
}
|
|
635
|
+
return { status: 0, stdout: '' }
|
|
636
|
+
}
|
|
637
|
+
return { spawnSyncImpl, calls }
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
const SERVICES = [
|
|
641
|
+
{ service: 'postgres', port: 5432, envKey: 'POSTGRES_PORT' },
|
|
642
|
+
{ service: 'redis', port: 6379, envKey: 'REDIS_PORT' },
|
|
643
|
+
]
|
|
644
|
+
|
|
645
|
+
test('startInfraServices stops before compose up when the runtime or a port is not usable', async () => {
|
|
646
|
+
const stopped = fakeComposeSpawn()
|
|
647
|
+
const noDaemon = await startInfraServices({
|
|
648
|
+
composeArgs: (extra) => ['compose', ...extra], services: SERVICES, spawnSyncImpl: stopped.spawnSyncImpl,
|
|
649
|
+
detect: () => ({ ok: false, code: 'daemon-stopped', detail: 'docker engine not running' }), log: () => {},
|
|
650
|
+
})
|
|
651
|
+
assert.equal(noDaemon.problem.code, 'daemon-stopped')
|
|
652
|
+
assert.deepEqual(stopped.calls, [])
|
|
653
|
+
|
|
654
|
+
const busy = fakeComposeSpawn()
|
|
655
|
+
const conflict = await startInfraServices({
|
|
656
|
+
composeArgs: (extra) => ['compose', ...extra], services: SERVICES, spawnSyncImpl: busy.spawnSyncImpl,
|
|
657
|
+
detect: () => ({ ok: true }), portProbe: async (port) => port === 5432, log: () => {},
|
|
658
|
+
})
|
|
659
|
+
assert.equal(conflict.problem.code, 'port-conflict')
|
|
660
|
+
assert.deepEqual(conflict.problem.ports.map((entry) => entry.port), [5432])
|
|
661
|
+
assert.ok(!busy.calls.some((call) => call.includes(' up ') || call.startsWith('up')))
|
|
662
|
+
})
|
|
663
|
+
|
|
664
|
+
test('startInfraServices reuses running containers, waits on health, and never removes volumes', async () => {
|
|
665
|
+
const fake = fakeComposeSpawn({ psBefore: [{ Service: 'postgres', State: 'running', Health: 'healthy' }] })
|
|
666
|
+
const logs = []
|
|
667
|
+
const outcome = await startInfraServices({
|
|
668
|
+
composeArgs: (extra) => ['compose', '-f', 'x.yml', ...extra], services: SERVICES, upArgs: ['--profile', 'agents'],
|
|
669
|
+
spawnSyncImpl: fake.spawnSyncImpl, detect: () => ({ ok: true }), portProbe: async () => false, log: (line) => logs.push(line),
|
|
670
|
+
})
|
|
671
|
+
assert.equal(outcome.ok, true)
|
|
672
|
+
assert.deepEqual(outcome.reused, ['postgres'])
|
|
673
|
+
assert.ok(fake.calls.includes('compose -f x.yml --profile agents up -d --wait'))
|
|
674
|
+
assert.ok(!fake.calls.some((call) => /down|--volumes|\brm\b/.test(call)))
|
|
675
|
+
assert.match(logs.join('\n'), /reusing running containers: postgres/)
|
|
676
|
+
})
|
|
677
|
+
|
|
678
|
+
test('startInfraServices runs slow preparation only after the cheap checks pass and before compose up', async () => {
|
|
679
|
+
const order = []
|
|
680
|
+
const fake = fakeComposeSpawn()
|
|
681
|
+
const spawnSyncImpl = (command, args, options) => {
|
|
682
|
+
if (args.includes('up')) order.push('up')
|
|
683
|
+
return fake.spawnSyncImpl(command, args, options)
|
|
684
|
+
}
|
|
685
|
+
await startInfraServices({
|
|
686
|
+
composeArgs: (extra) => ['compose', ...extra], services: SERVICES, spawnSyncImpl,
|
|
687
|
+
detect: () => ({ ok: true }), portProbe: async () => false, beforeUp: () => order.push('prepare'), log: () => {},
|
|
688
|
+
})
|
|
689
|
+
assert.deepEqual(order, ['prepare', 'up'])
|
|
690
|
+
|
|
691
|
+
const skipped = []
|
|
692
|
+
await startInfraServices({
|
|
693
|
+
composeArgs: (extra) => ['compose', ...extra], services: SERVICES, spawnSyncImpl: fakeComposeSpawn().spawnSyncImpl,
|
|
694
|
+
detect: () => ({ ok: true }), portProbe: async () => true, beforeUp: () => skipped.push('prepare'), log: () => {},
|
|
695
|
+
})
|
|
696
|
+
assert.deepEqual(skipped, [])
|
|
697
|
+
})
|
|
698
|
+
|
|
699
|
+
test('startInfraServices reports which services failed their healthcheck after compose up fails', async () => {
|
|
700
|
+
const fake = fakeComposeSpawn({ upStatus: 1, psAfter: [
|
|
701
|
+
{ Service: 'postgres', State: 'running', Health: 'healthy' },
|
|
702
|
+
{ Service: 'redis', State: 'running', Health: 'unhealthy' },
|
|
703
|
+
] })
|
|
704
|
+
const outcome = await startInfraServices({
|
|
705
|
+
composeArgs: (extra) => ['compose', ...extra], services: SERVICES,
|
|
706
|
+
spawnSyncImpl: fake.spawnSyncImpl, detect: () => ({ ok: true }), portProbe: async () => false, log: () => {},
|
|
707
|
+
})
|
|
708
|
+
assert.equal(outcome.problem.code, 'unhealthy')
|
|
709
|
+
assert.deepEqual(outcome.problem.services.map((entry) => entry.service), ['redis'])
|
|
710
|
+
assert.equal(outcome.problem.logsCommand, 'docker compose logs redis')
|
|
711
|
+
|
|
712
|
+
const opaque = fakeComposeSpawn({ upStatus: 1, psAfter: [
|
|
713
|
+
{ Service: 'postgres', State: 'running', Health: 'healthy' },
|
|
714
|
+
{ Service: 'redis', State: 'running', Health: 'healthy' },
|
|
715
|
+
] })
|
|
716
|
+
const failed = await startInfraServices({
|
|
717
|
+
composeArgs: (extra) => ['compose', ...extra], services: SERVICES,
|
|
718
|
+
spawnSyncImpl: opaque.spawnSyncImpl, detect: () => ({ ok: true }), portProbe: async () => false, log: () => {},
|
|
719
|
+
})
|
|
720
|
+
assert.equal(failed.problem.code, 'compose-failed')
|
|
721
|
+
})
|
|
722
|
+
|
|
723
|
+
test('--no-infra: database probes return no verdict without invoking docker compose', () => {
|
|
724
|
+
const repo = makeFakeRepo()
|
|
725
|
+
fs.mkdirSync(path.join(repo, 'apps', 'mercato'), { recursive: true })
|
|
726
|
+
fs.writeFileSync(path.join(repo, 'apps', 'mercato', '.env'), 'DATABASE_URL=postgres://me:pw@db.example.com:5432/app\n')
|
|
727
|
+
const ctx = { repoRoot: repo, flags: { noInfra: true } }
|
|
728
|
+
const forbidden = () => { throw new Error('docker compose must not run with --no-infra') }
|
|
729
|
+
assert.equal(readAppliedMigrationModules(ctx, { runComposeImpl: forbidden }), null)
|
|
730
|
+
assert.equal(probePostgresCredentials(ctx, { runComposeImpl: forbidden }), null)
|
|
731
|
+
assert.equal(databaseIsInitialized(ctx, { runComposeImpl: forbidden }), null)
|
|
732
|
+
})
|
|
733
|
+
|
|
734
|
+
test('--no-infra: the container runtime, host gateway and infra steps are skipped and the dev runtime gets the flag', () => {
|
|
735
|
+
const ctx = { mode: 'hybrid', flags: { noInfra: true } }
|
|
736
|
+
assert.equal(containerRuntimeStep.appliesTo(ctx), false)
|
|
737
|
+
assert.equal(hostGatewayStep.appliesTo(ctx), false)
|
|
738
|
+
assert.equal(infraUpStep.appliesTo(ctx), false)
|
|
739
|
+
assert.equal(infraUpStep.appliesTo({ mode: 'hybrid', flags: { noInfra: false } }), true)
|
|
740
|
+
|
|
741
|
+
assert.deepEqual(devRuntimeArgs(['--verbose'], { noInfra: true }), ['--verbose', '--no-infra'])
|
|
742
|
+
assert.deepEqual(devRuntimeArgs(['--no-infra'], { noInfra: true }), ['--no-infra'])
|
|
743
|
+
assert.deepEqual(devRuntimeArgs(['--verbose'], { noInfra: false }), ['--verbose'])
|
|
744
|
+
})
|
|
745
|
+
|
|
746
|
+
test('--no-infra overrides explicit and remembered docker modes for the current run', () => {
|
|
747
|
+
const explicitMode = 'docker'
|
|
748
|
+
const rememberedMode = 'docker'
|
|
749
|
+
assert.equal(resolveUpMode(explicitMode, { noInfra: true }), 'hybrid')
|
|
750
|
+
assert.equal(resolveUpMode(rememberedMode, { noInfra: true }), 'hybrid')
|
|
751
|
+
assert.equal(resolveUpMode('docker', { noInfra: false }), 'docker')
|
|
752
|
+
assert.equal(resolveUpMode('hybrid', { noInfra: true }), 'hybrid')
|
|
753
|
+
})
|
|
754
|
+
|
|
755
|
+
test('monorepo infra reports an external DATABASE_URL before starting local containers', async () => {
|
|
756
|
+
const repo = makeFakeRepo()
|
|
757
|
+
fs.mkdirSync(path.join(repo, 'apps', 'mercato'), { recursive: true })
|
|
758
|
+
fs.writeFileSync(path.join(repo, 'apps', 'mercato', '.env'), 'DATABASE_URL=postgres://me:pw@db.example.com:5432/shared\n')
|
|
759
|
+
const lines = []
|
|
760
|
+
const outcome = await startInfra(repo, {
|
|
761
|
+
env: {},
|
|
762
|
+
log: (line) => lines.push(String(line)),
|
|
763
|
+
startImpl: async () => ({ ok: true }),
|
|
764
|
+
})
|
|
765
|
+
assert.equal(outcome.ok, true)
|
|
766
|
+
assert.equal(externalDatabaseHost(repo, {}), 'db.example.com')
|
|
767
|
+
assert.match(lines.join('\n'), /DATABASE_URL points at db\.example\.com; it is kept as is/)
|
|
768
|
+
assert.match(lines.join('\n'), /--no-infra/)
|
|
769
|
+
})
|
|
770
|
+
|
|
771
|
+
test('an automatic infra failure stops the pipeline before the database step', async () => {
|
|
772
|
+
const order = []
|
|
773
|
+
const ctx = quietCtx({
|
|
774
|
+
mode: 'hybrid',
|
|
775
|
+
flags: { noInfra: false, profiles: [] },
|
|
776
|
+
ensureOpencodeImageImpl: () => order.push('opencode-image'),
|
|
777
|
+
startInfraImpl: async (repoRoot, { beforeUp }) => {
|
|
778
|
+
assert.equal(typeof beforeUp, 'function')
|
|
779
|
+
order.push('infra')
|
|
780
|
+
return { ok: false, problem: { code: 'port-conflict', ports: [{ service: 'postgres', port: 5432, envKey: 'POSTGRES_PORT' }] } }
|
|
781
|
+
},
|
|
782
|
+
})
|
|
783
|
+
const lines = []
|
|
784
|
+
ctx.log = (line) => lines.push(String(line))
|
|
785
|
+
const outcome = await runSteps([
|
|
786
|
+
{ ...infraUpStep, async check() { return { ok: false, detail: 'starting: postgres' } } },
|
|
787
|
+
{ id: 'database', title: 'Database', async check() { order.push('database'); return { ok: false } }, async apply() {} },
|
|
788
|
+
], ctx)
|
|
789
|
+
assert.equal(outcome.ok, false)
|
|
790
|
+
assert.equal(outcome.failedStep, 'infra-up')
|
|
791
|
+
assert.deepEqual(order, ['infra'], 'a failed preflight never pulls or builds the OpenCode image')
|
|
792
|
+
assert.match(lines.join('\n'), /Port 5432 \(postgres\) is already in use/)
|
|
793
|
+
assert.match(lines.join('\n'), /yarn setup --no-infra/)
|
|
794
|
+
})
|
|
795
|
+
|
|
796
|
+
test('root package.json exposes yarn setup through the starter while keeping om, infra and dev entries', () => {
|
|
797
|
+
const rootPackage = JSON.parse(fs.readFileSync(new URL('../../../../package.json', import.meta.url), 'utf8'))
|
|
798
|
+
assert.equal(rootPackage.scripts.setup, 'node packages/starter/bin/om-start.mjs up')
|
|
799
|
+
assert.equal(rootPackage.scripts.om, 'node packages/starter/bin/om-start.mjs')
|
|
800
|
+
assert.equal(rootPackage.scripts['infra:up'], 'node packages/starter/bin/om-start.mjs infra up')
|
|
801
|
+
assert.equal(rootPackage.scripts['infra:down'], 'node packages/starter/bin/om-start.mjs infra down')
|
|
802
|
+
assert.ok(rootPackage.scripts.dev)
|
|
803
|
+
assert.ok(rootPackage.scripts['dev:greenfield'])
|
|
804
|
+
})
|
|
805
|
+
|
|
806
|
+
test('the generated-app copy of the infra preflight is byte-identical to the starter module', () => {
|
|
807
|
+
const source = fs.readFileSync(new URL('../infra-preflight.mjs', import.meta.url))
|
|
808
|
+
const mirror = fs.readFileSync(new URL('../../../create-app/template/scripts/dev-infra-preflight.mjs', import.meta.url))
|
|
809
|
+
assert.ok(source.equals(mirror), 'run yarn template:sync:fix')
|
|
810
|
+
})
|
|
811
|
+
|
|
812
|
+
test('WSL users are sent to Docker Desktop WSL integration instead of installing a second engine', () => {
|
|
813
|
+
assert.equal(detectWsl({ env: { WSL_DISTRO_NAME: 'Ubuntu' }, readFile: () => '' }), true)
|
|
814
|
+
assert.equal(detectWsl({ env: {}, readFile: () => 'Linux version 5.15.153.1-microsoft-standard-WSL2' }), true)
|
|
815
|
+
assert.equal(detectWsl({ env: {}, readFile: () => 'Linux version 6.8.0-45-generic (buildd@lcy02)' }), false)
|
|
816
|
+
assert.equal(detectWsl({ env: {}, readFile: () => { throw new Error('ENOENT') } }), false)
|
|
817
|
+
|
|
818
|
+
const missing = formatInfraProblem({ code: 'cli-missing' }, { platform: 'linux', wsl: true }).join('\n')
|
|
819
|
+
assert.match(missing, /WSL integration/)
|
|
820
|
+
assert.doesNotMatch(missing, /Install Docker Engine with the compose plugin/)
|
|
821
|
+
assert.match(formatInfraProblem({ code: 'daemon-stopped' }, { platform: 'linux', wsl: true }).join('\n'), /Docker Desktop on Windows/)
|
|
822
|
+
assert.match(formatInfraProblem({ code: 'cli-missing' }, { platform: 'linux', wsl: false }).join('\n'), /Install Docker Engine/)
|
|
823
|
+
})
|
|
824
|
+
|
|
825
|
+
test('compose failures point at port allocation errors, with the reserved-range check on Windows', () => {
|
|
826
|
+
const linux = formatInfraProblem({ code: 'compose-failed' }, { platform: 'linux', wsl: false }).join('\n')
|
|
827
|
+
assert.match(linux, /port is already allocated/)
|
|
828
|
+
assert.doesNotMatch(linux, /excludedportrange/)
|
|
829
|
+
assert.match(formatInfraProblem({ code: 'compose-failed' }, { platform: 'win32' }).join('\n'), /excludedportrange/)
|
|
830
|
+
})
|
|
831
|
+
|
|
832
|
+
test('monorepo port conflicts name apps/mercato/.env and the fixed mercato-* container names', () => {
|
|
833
|
+
const problem = { code: 'port-conflict', ports: [{ service: 'postgres', port: 5432, envKey: 'POSTGRES_PORT' }] }
|
|
834
|
+
const monorepo = describeInfraProblem(problem, { platform: 'darwin' }).join('\n')
|
|
835
|
+
assert.match(monorepo, /DATABASE_URL \(apps\/mercato\/\.env\)/)
|
|
836
|
+
assert.match(monorepo, /MERCATO_STACK/)
|
|
837
|
+
assert.match(monorepo, /yarn setup --no-infra/)
|
|
838
|
+
const standalone = formatInfraProblem(problem, { platform: 'darwin' }).join('\n')
|
|
839
|
+
assert.match(standalone, /DATABASE_URL \(\.env\)/)
|
|
840
|
+
assert.doesNotMatch(standalone, /MERCATO_STACK/)
|
|
841
|
+
})
|
|
842
|
+
|
|
843
|
+
test('startInfraServices skips the port check when compose ps fails instead of blaming our own containers', async () => {
|
|
844
|
+
const calls = []
|
|
845
|
+
const logs = []
|
|
846
|
+
const spawnSyncImpl = (command, args) => {
|
|
847
|
+
calls.push(args.join(' '))
|
|
848
|
+
if (args.includes('ps')) return { status: 1, stdout: '', stderr: 'invalid interpolation format' }
|
|
849
|
+
if (args.includes('up')) return { status: 1 }
|
|
850
|
+
return { status: 0, stdout: '' }
|
|
851
|
+
}
|
|
852
|
+
const probed = []
|
|
853
|
+
const outcome = await startInfraServices({
|
|
854
|
+
composeArgs: (extra) => ['compose', ...extra], services: SERVICES, spawnSyncImpl,
|
|
855
|
+
detect: () => ({ ok: true }), portProbe: async (port) => { probed.push(port); return true }, log: (line) => logs.push(line),
|
|
856
|
+
})
|
|
857
|
+
assert.deepEqual(probed, [])
|
|
858
|
+
assert.equal(outcome.problem.code, 'compose-failed')
|
|
859
|
+
assert.ok(calls.some((call) => call.includes('up -d --wait')))
|
|
860
|
+
assert.match(logs.join('\n'), /skipping the port check/)
|
|
861
|
+
})
|
|
862
|
+
|
|
863
|
+
test('infraUpStep.check only converges once every container is healthy, not merely running', async () => {
|
|
864
|
+
const psWith = (entries) => () => ({ status: 0, stdout: entries.map((entry) => JSON.stringify(entry)).join('\n') })
|
|
865
|
+
const healthy = [
|
|
866
|
+
{ Service: 'postgres', State: 'running', Health: 'healthy' },
|
|
867
|
+
{ Service: 'redis', State: 'running', Health: 'healthy' },
|
|
868
|
+
{ Service: 'meilisearch', State: 'running', Health: 'healthy' },
|
|
869
|
+
{ Service: 'opencode', State: 'running', Health: '' },
|
|
870
|
+
]
|
|
871
|
+
const ready = await infraUpStep.check({ repoRoot: '/repo', flags: {}, runComposeImpl: psWith(healthy) })
|
|
872
|
+
assert.equal(ready.ok, true)
|
|
873
|
+
|
|
874
|
+
const ctx = { repoRoot: '/repo', flags: {}, runComposeImpl: psWith([{ ...healthy[0], Health: 'starting' }, ...healthy.slice(1)]) }
|
|
875
|
+
const starting = await infraUpStep.check(ctx)
|
|
876
|
+
assert.equal(starting.ok, false)
|
|
877
|
+
assert.deepEqual(ctx.infraMissing, ['postgres'])
|
|
878
|
+
assert.match(starting.detail, /postgres \(starting\)/)
|
|
879
|
+
})
|
|
880
|
+
|
|
881
|
+
test('the database step initializes with --skip-if-initialized so a re-run never aborts on existing users', async () => {
|
|
882
|
+
const repo = makeFakeRepo()
|
|
883
|
+
fs.mkdirSync(path.join(repo, 'apps', 'mercato'), { recursive: true })
|
|
884
|
+
fs.writeFileSync(path.join(repo, 'apps', 'mercato', '.env'), 'DATABASE_URL=postgres://me:pw@db.example.com:5432/shared\n')
|
|
885
|
+
const invocations = []
|
|
886
|
+
const ctx = quietCtx({
|
|
887
|
+
repoRoot: repo,
|
|
888
|
+
env: {},
|
|
889
|
+
flags: { noInfra: true },
|
|
890
|
+
runStreamingImpl: (command, args, options) => {
|
|
891
|
+
invocations.push({ command, args, env: options.env })
|
|
892
|
+
return 0
|
|
893
|
+
},
|
|
894
|
+
})
|
|
895
|
+
const checked = await databaseStep.check(ctx)
|
|
896
|
+
assert.equal(checked.ok, false)
|
|
897
|
+
await databaseStep.apply(ctx)
|
|
898
|
+
assert.deepEqual(invocations.map((entry) => entry.args), [['db:migrate'], ['initialize', '--', '--skip-if-initialized']])
|
|
899
|
+
assert.equal(invocations[1].env.OM_INIT_DEV_AUTOSTART, '1')
|
|
900
|
+
|
|
901
|
+
invocations.length = 0
|
|
902
|
+
const emptied = quietCtx({ ...ctx, dbReinitialize: true })
|
|
903
|
+
await databaseStep.apply(emptied)
|
|
904
|
+
assert.deepEqual(invocations.map((entry) => entry.args), [['db:migrate'], ['initialize']])
|
|
905
|
+
})
|
package/src/cli.mjs
CHANGED
|
@@ -26,7 +26,7 @@ import { readEnvValue } from './env-file.mjs'
|
|
|
26
26
|
import { FULLAPP_DEV_COMPOSE_FILE, STARTER_STATE_DIR, resolveStackPorts, stackUrls } from './constants.mjs'
|
|
27
27
|
import { loadCompanyConfig } from './company.mjs'
|
|
28
28
|
import { printDoctorReport, runDoctor } from './doctor.mjs'
|
|
29
|
-
import {
|
|
29
|
+
import { describeInfraProblem, devRuntimeArgs, infraDown, ensureMcpSharedDir, removeLeftoverComposeResources, resolveUpMode, startInfra } from './infra.mjs'
|
|
30
30
|
import { buildUpSteps, clearConvergenceState, createStepContext, ensureOpencodeImage, runSteps, yarnInvocation } from './steps.mjs'
|
|
31
31
|
import { collectStatus, printStatus, readRunState, isPidAlive, startDetached, stopDetached, tailLogs } from './supervise.mjs'
|
|
32
32
|
import { ensureWindowsUtf8Console } from './spawn.mjs'
|
|
@@ -156,7 +156,8 @@ async function confirm(question, { nonInteractive }) {
|
|
|
156
156
|
}
|
|
157
157
|
|
|
158
158
|
async function commandUp(flags) {
|
|
159
|
-
const
|
|
159
|
+
const selectedMode = resolveMode(flags.mode)
|
|
160
|
+
const mode = resolveUpMode(selectedMode, flags)
|
|
160
161
|
if (flags.clean) {
|
|
161
162
|
// Full re-converge: drop the completed-step markers (keeps the mode, all
|
|
162
163
|
// data, and the one-time initialize state — `reset` is the destructive
|
|
@@ -169,6 +170,9 @@ async function commandUp(flags) {
|
|
|
169
170
|
printBanner(`dev environment starter — mode: ${mode}${ctx.company.name ? ` — company profile: ${ctx.company.name}` : ''}`)
|
|
170
171
|
console.log(color.dim(` Repo: ${repoRoot}`))
|
|
171
172
|
console.log(color.dim(' Every step is idempotent — re-running always resumes where it stopped.'))
|
|
173
|
+
if (selectedMode !== mode) {
|
|
174
|
+
console.log(color.dim(' --no-infra: using the host runtime for this run so no Docker command is invoked.'))
|
|
175
|
+
}
|
|
172
176
|
|
|
173
177
|
if (mode === 'docker') return commandUpDocker(ctx, flags)
|
|
174
178
|
|
|
@@ -192,12 +196,13 @@ async function commandUp(flags) {
|
|
|
192
196
|
console.log(color.dim(' Stop: Ctrl+C (infra containers keep running; `stop` shuts everything down)'))
|
|
193
197
|
console.log('')
|
|
194
198
|
|
|
199
|
+
const devArgs = devRuntimeArgs(flags.passthrough, { noInfra: flags.noInfra })
|
|
195
200
|
if (flags.detach) {
|
|
196
|
-
startDetached(repoRoot,
|
|
201
|
+
startDetached(repoRoot, devArgs, { env: ctx.env })
|
|
197
202
|
console.log('Manage it with the status / logs / stop subcommands.')
|
|
198
203
|
return
|
|
199
204
|
}
|
|
200
|
-
const dev = yarnInvocation(ctx, ['dev', ...
|
|
205
|
+
const dev = yarnInvocation(ctx, ['dev', ...devArgs])
|
|
201
206
|
const child = spawnStreaming(dev.command, dev.args, { cwd: repoRoot, env: ctx.env })
|
|
202
207
|
child.on('close', (code) => process.exit(code ?? 0))
|
|
203
208
|
child.on('error', (error) => {
|
|
@@ -328,7 +333,8 @@ async function commandReset(flags) {
|
|
|
328
333
|
async function commandInfra(flags) {
|
|
329
334
|
const docker = detectDocker()
|
|
330
335
|
if (!docker.ok) {
|
|
331
|
-
|
|
336
|
+
printInfraProblem({ code: docker.code, detail: docker.reason })
|
|
337
|
+
console.error(' Full environment audit: yarn om doctor')
|
|
332
338
|
process.exit(2)
|
|
333
339
|
}
|
|
334
340
|
if (flags.infraAction === 'down') {
|
|
@@ -338,16 +344,25 @@ async function commandInfra(flags) {
|
|
|
338
344
|
}
|
|
339
345
|
process.exit(infraDown(repoRoot, { volumes: flags.volumes }))
|
|
340
346
|
}
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
console.log(' Next: yarn dev (starts the app and the MCP server on this machine)')
|
|
347
|
+
const outcome = await startInfra(repoRoot, {
|
|
348
|
+
profiles: flags.profiles,
|
|
349
|
+
beforeUp: () => ensureOpencodeImage({ repoRoot, env: process.env, flags: { rebuild: flags.rebuild }, log: console.log }),
|
|
350
|
+
})
|
|
351
|
+
if (!outcome.ok) {
|
|
352
|
+
printInfraProblem(outcome.problem)
|
|
353
|
+
process.exit(2)
|
|
349
354
|
}
|
|
350
|
-
|
|
355
|
+
const ports = resolveStackPorts(repoRoot)
|
|
356
|
+
console.log('')
|
|
357
|
+
console.log(`✅ Infra containers are up (opencode :${ports.opencode}, postgres :${ports.postgres}, redis :${ports.redis}, meilisearch :${ports.meilisearch}).`)
|
|
358
|
+
console.log(' Next: yarn dev (starts the app and the MCP server on this machine)')
|
|
359
|
+
process.exit(0)
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
function printInfraProblem(problem) {
|
|
363
|
+
const [title, ...rest] = describeInfraProblem(problem)
|
|
364
|
+
console.error(`❌ ${title}`)
|
|
365
|
+
for (const line of rest) console.error(` ${line}`)
|
|
351
366
|
}
|
|
352
367
|
|
|
353
368
|
async function main() {
|
package/src/compose.mjs
CHANGED
|
@@ -2,6 +2,7 @@ import { spawn, spawnSync } from 'node:child_process'
|
|
|
2
2
|
import fs from 'node:fs'
|
|
3
3
|
import path from 'node:path'
|
|
4
4
|
|
|
5
|
+
import { detectDockerRuntime, parseComposePsOutput } from './infra-preflight.mjs'
|
|
5
6
|
import { resolveSpawnCommand } from './spawn.mjs'
|
|
6
7
|
|
|
7
8
|
export const INFRA_COMPOSE_FILE = path.join('starters', 'docker', 'compose.infra.yml')
|
|
@@ -49,45 +50,16 @@ export function runCompose(repoRoot, extraArgs, { composeFile, stdio = 'inherit'
|
|
|
49
50
|
return result
|
|
50
51
|
}
|
|
51
52
|
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
return { ok: false, reason: 'docker compose v2 plugin not found' }
|
|
60
|
-
}
|
|
61
|
-
const engine = spawnSync('docker', ['info', '--format', '{{.ServerVersion}}'], { stdio: 'ignore' })
|
|
62
|
-
if (engine.error || engine.status !== 0) {
|
|
63
|
-
return { ok: false, reason: 'docker engine not running' }
|
|
64
|
-
}
|
|
65
|
-
return { ok: true }
|
|
53
|
+
// Thin adapter over the shared preflight: `reason` stays the human-readable
|
|
54
|
+
// string doctor prints; `code` distinguishes missing CLI / missing compose /
|
|
55
|
+
// stopped or unreachable daemon for callers that explain the fix.
|
|
56
|
+
export function detectDocker({ probe } = {}) {
|
|
57
|
+
const runtime = detectDockerRuntime(probe ? { probe } : {})
|
|
58
|
+
if (runtime.ok) return { ok: true, code: runtime.code }
|
|
59
|
+
return { ok: false, code: runtime.code, reason: runtime.detail }
|
|
66
60
|
}
|
|
67
61
|
|
|
68
|
-
|
|
69
|
-
// on older releases — tolerate both.
|
|
70
|
-
export function parseComposePsOutput(raw) {
|
|
71
|
-
const trimmed = String(raw ?? '').trim()
|
|
72
|
-
if (!trimmed) return []
|
|
73
|
-
if (trimmed.startsWith('[')) {
|
|
74
|
-
try {
|
|
75
|
-
return JSON.parse(trimmed)
|
|
76
|
-
} catch {
|
|
77
|
-
return []
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
const entries = []
|
|
81
|
-
for (const line of trimmed.split('\n')) {
|
|
82
|
-
if (!line.trim()) continue
|
|
83
|
-
try {
|
|
84
|
-
entries.push(JSON.parse(line))
|
|
85
|
-
} catch {
|
|
86
|
-
// Ignore non-JSON noise lines.
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
return entries
|
|
90
|
-
}
|
|
62
|
+
export { parseComposePsOutput }
|
|
91
63
|
|
|
92
64
|
export function summarizeServiceStates(entries) {
|
|
93
65
|
const states = {}
|
package/src/doctor.mjs
CHANGED
|
@@ -6,6 +6,7 @@ import os from 'node:os'
|
|
|
6
6
|
import path from 'node:path'
|
|
7
7
|
|
|
8
8
|
import { detectDocker, runCaptureSync } from './compose.mjs'
|
|
9
|
+
import { formatInfraProblem } from './infra-preflight.mjs'
|
|
9
10
|
import { probeTlsInterception, summarizeProbeResults } from './certs.mjs'
|
|
10
11
|
import { CAPTURED_CA_BUNDLE, LOOPBACK_HOST, resolveStackPorts } from './constants.mjs'
|
|
11
12
|
import { color, icons, printBanner } from './ui.mjs'
|
|
@@ -78,6 +79,13 @@ export function checkContainerRuntime() {
|
|
|
78
79
|
}
|
|
79
80
|
const isWindows = process.platform === 'win32'
|
|
80
81
|
const isMac = process.platform === 'darwin'
|
|
82
|
+
if (docker.code && docker.code !== 'cli-missing') {
|
|
83
|
+
const [, ...remediation] = formatInfraProblem({ code: docker.code, detail: docker.reason }, { optOutCommand: 'yarn setup --no-infra' })
|
|
84
|
+
return result('runtime', 'Container runtime', 'fail', `not usable (${docker.reason})`, {
|
|
85
|
+
guide: remediation.map((line) => line.trim()),
|
|
86
|
+
it: docker.code === 'daemon-permission' ? ['Allow this user to use the Docker engine (docker group membership).'] : [],
|
|
87
|
+
})
|
|
88
|
+
}
|
|
81
89
|
const guide = isWindows
|
|
82
90
|
? [
|
|
83
91
|
'Install ONE of (both use the WSL2 backend):',
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
// Docker preflight + health-waited infra startup shared by the monorepo starter
|
|
2
|
+
// (`yarn setup`, `yarn infra:up`) and generated apps (`yarn setup`,
|
|
3
|
+
// `yarn infra:up`). Node stdlib only and free of sibling imports:
|
|
4
|
+
// `yarn template:sync` mirrors this file byte-for-byte to
|
|
5
|
+
// packages/create-app/template/scripts/dev-infra-preflight.mjs, where no
|
|
6
|
+
// `packages/starter` directory exists.
|
|
7
|
+
import { spawnSync } from 'node:child_process'
|
|
8
|
+
import fs from 'node:fs'
|
|
9
|
+
import net from 'node:net'
|
|
10
|
+
|
|
11
|
+
export const INFRA_PROBE_TIMEOUT_MS = 20_000
|
|
12
|
+
export const NO_INFRA_FLAG = '--no-infra'
|
|
13
|
+
|
|
14
|
+
export function runDockerProbe(args, { spawnSyncImpl = spawnSync, timeout = INFRA_PROBE_TIMEOUT_MS } = {}) {
|
|
15
|
+
return spawnSyncImpl('docker', args, {
|
|
16
|
+
encoding: 'utf8',
|
|
17
|
+
timeout,
|
|
18
|
+
windowsHide: true,
|
|
19
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
20
|
+
})
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function firstOutputLine(result) {
|
|
24
|
+
const text = `${result?.stderr ?? ''}\n${result?.stdout ?? ''}`
|
|
25
|
+
return text.split('\n').map((line) => line.trim()).find(Boolean) ?? ''
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Order matters: the CLI and the compose plugin answer without a daemon, so a
|
|
29
|
+
// stopped engine is only reported once both are known to exist.
|
|
30
|
+
export function detectDockerRuntime({ probe = runDockerProbe } = {}) {
|
|
31
|
+
const cli = probe(['--version'])
|
|
32
|
+
if (cli?.error || cli?.status !== 0) {
|
|
33
|
+
return { ok: false, code: 'cli-missing', detail: 'docker CLI not found' }
|
|
34
|
+
}
|
|
35
|
+
const compose = probe(['compose', 'version'])
|
|
36
|
+
if (compose?.error || compose?.status !== 0) {
|
|
37
|
+
return { ok: false, code: 'compose-missing', detail: 'docker compose v2 plugin not found' }
|
|
38
|
+
}
|
|
39
|
+
const engine = probe(['info', '--format', '{{.ServerVersion}}'])
|
|
40
|
+
if (engine?.error?.code === 'ETIMEDOUT') {
|
|
41
|
+
return { ok: false, code: 'daemon-unresponsive', detail: 'docker engine did not respond in time' }
|
|
42
|
+
}
|
|
43
|
+
if (engine?.error || engine?.status !== 0) {
|
|
44
|
+
const output = firstOutputLine(engine)
|
|
45
|
+
if (/permission denied/i.test(output)) {
|
|
46
|
+
return { ok: false, code: 'daemon-permission', detail: 'no permission to talk to the docker engine' }
|
|
47
|
+
}
|
|
48
|
+
return { ok: false, code: 'daemon-stopped', detail: 'docker engine not running' }
|
|
49
|
+
}
|
|
50
|
+
return { ok: true, code: 'ok', serverVersion: String(engine.stdout ?? '').trim() }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// `compose ps --format json` prints NDJSON on compose >= 2.21 and a JSON array
|
|
54
|
+
// on older releases — tolerate both.
|
|
55
|
+
export function parseComposePsOutput(raw) {
|
|
56
|
+
const trimmed = String(raw ?? '').trim()
|
|
57
|
+
if (!trimmed) return []
|
|
58
|
+
if (trimmed.startsWith('[')) {
|
|
59
|
+
try {
|
|
60
|
+
return JSON.parse(trimmed)
|
|
61
|
+
} catch {
|
|
62
|
+
return []
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
const entries = []
|
|
66
|
+
for (const line of trimmed.split('\n')) {
|
|
67
|
+
if (!line.trim()) continue
|
|
68
|
+
try {
|
|
69
|
+
entries.push(JSON.parse(line))
|
|
70
|
+
} catch {
|
|
71
|
+
// Ignore non-JSON noise lines.
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return entries
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function runningComposeServices(entries) {
|
|
78
|
+
return new Set(entries.filter((entry) => entry?.State === 'running').map((entry) => entry.Service).filter(Boolean))
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Services `compose up --wait` gave up on: missing, not running, or running
|
|
82
|
+
// with a failing healthcheck. A service without a healthcheck reports an empty
|
|
83
|
+
// Health and counts as ready once it runs.
|
|
84
|
+
export function findUnhealthyServices(entries, required) {
|
|
85
|
+
const byService = new Map(entries.filter((entry) => entry?.Service).map((entry) => [entry.Service, entry]))
|
|
86
|
+
const unhealthy = []
|
|
87
|
+
for (const service of required) {
|
|
88
|
+
const entry = byService.get(service)
|
|
89
|
+
if (!entry) {
|
|
90
|
+
unhealthy.push({ service, state: 'missing', health: '' })
|
|
91
|
+
continue
|
|
92
|
+
}
|
|
93
|
+
const state = entry.State ?? 'unknown'
|
|
94
|
+
const health = entry.Health ?? ''
|
|
95
|
+
if (state !== 'running' || (health && health !== 'healthy')) unhealthy.push({ service, state, health })
|
|
96
|
+
}
|
|
97
|
+
return unhealthy
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Host-side probes use 127.0.0.1, never `localhost` (modern Windows resolves
|
|
101
|
+
// `localhost` to ::1 first while published container ports listen on IPv4).
|
|
102
|
+
export function probeTcpPort(port, { host = '127.0.0.1', timeoutMs = 750 } = {}) {
|
|
103
|
+
return new Promise((resolve) => {
|
|
104
|
+
const socket = net.connect({ host, port, timeout: timeoutMs })
|
|
105
|
+
socket.once('connect', () => {
|
|
106
|
+
socket.destroy()
|
|
107
|
+
resolve(true)
|
|
108
|
+
})
|
|
109
|
+
const closed = () => {
|
|
110
|
+
socket.destroy()
|
|
111
|
+
resolve(false)
|
|
112
|
+
}
|
|
113
|
+
socket.once('timeout', closed)
|
|
114
|
+
socket.once('error', closed)
|
|
115
|
+
})
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// Only ports of services that are NOT already running in this compose project
|
|
119
|
+
// can conflict: our own running containers legitimately own theirs.
|
|
120
|
+
export async function findPortConflicts(services, { running = new Set(), probe = probeTcpPort } = {}) {
|
|
121
|
+
const conflicts = []
|
|
122
|
+
for (const entry of services) {
|
|
123
|
+
if (running.has(entry.service)) continue
|
|
124
|
+
if (await probe(entry.port)) conflicts.push(entry)
|
|
125
|
+
}
|
|
126
|
+
return conflicts
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// WSL2 reports platform 'linux', but its usual Docker is Docker Desktop on the
|
|
130
|
+
// Windows side, exposed to the distribution through "WSL integration". Telling
|
|
131
|
+
// a WSL user to install Docker Engine would put a second engine next to it.
|
|
132
|
+
export function detectWsl({ env = process.env, readFile = (file) => fs.readFileSync(file, 'utf8') } = {}) {
|
|
133
|
+
if (env.WSL_DISTRO_NAME || env.WSL_INTEROP) return true
|
|
134
|
+
try {
|
|
135
|
+
return /microsoft/i.test(readFile('/proc/version'))
|
|
136
|
+
} catch {
|
|
137
|
+
return false
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const WSL_INTEGRATION_HINT = 'Inside WSL: open Docker Desktop on Windows -> Settings -> Resources -> WSL integration, enable it for this distribution, then open a new terminal. (Only install Docker Engine inside WSL if you do not use Docker Desktop.)'
|
|
142
|
+
|
|
143
|
+
function remediationFor(problem, platform, { wsl = false, databaseUrlFile = '.env', portConflictHints = [] } = {}) {
|
|
144
|
+
switch (problem.code) {
|
|
145
|
+
case 'cli-missing':
|
|
146
|
+
return [
|
|
147
|
+
wsl
|
|
148
|
+
? WSL_INTEGRATION_HINT
|
|
149
|
+
: platform === 'linux'
|
|
150
|
+
? 'Install Docker Engine with the compose plugin: https://docs.docker.com/engine/install/'
|
|
151
|
+
: 'Install Docker Desktop (https://docs.docker.com/get-started/get-docker/) or Rancher Desktop (https://rancherdesktop.io), then start it.',
|
|
152
|
+
'Setup never installs Docker for you.',
|
|
153
|
+
]
|
|
154
|
+
case 'compose-missing':
|
|
155
|
+
return [
|
|
156
|
+
'Install the Docker Compose v2 plugin so that `docker compose version` works: https://docs.docker.com/compose/install/',
|
|
157
|
+
]
|
|
158
|
+
case 'daemon-stopped':
|
|
159
|
+
return [
|
|
160
|
+
wsl
|
|
161
|
+
? 'Start Docker Desktop on Windows and wait until it reports it is running (or start the engine inside WSL if you installed one there).'
|
|
162
|
+
: platform === 'linux'
|
|
163
|
+
? 'Start the engine yourself, for example: sudo systemctl start docker'
|
|
164
|
+
: 'Start Docker Desktop or Rancher Desktop (or `colima start`) and wait until it reports it is running.',
|
|
165
|
+
]
|
|
166
|
+
case 'daemon-unresponsive':
|
|
167
|
+
return ['Docker did not answer in time. Restart Docker Desktop / the engine and re-run.']
|
|
168
|
+
case 'daemon-permission':
|
|
169
|
+
return [
|
|
170
|
+
'Your user may not talk to the Docker engine. Add it to the docker group (sudo usermod -aG docker "$USER"), log out and back in, then re-run.',
|
|
171
|
+
]
|
|
172
|
+
case 'port-conflict':
|
|
173
|
+
return [
|
|
174
|
+
...problem.ports.map(({ service, port, envKey }) => `Port ${port} (${service}) is already in use by another process.${envKey ? ` Stop that process, or pick a free port with ${envKey} in .env.` : ' Stop that process.'}`),
|
|
175
|
+
`If you change POSTGRES_PORT, update the port in DATABASE_URL (${databaseUrlFile}) as well.`,
|
|
176
|
+
'`docker ps` shows containers of other projects that may hold these ports.',
|
|
177
|
+
...portConflictHints,
|
|
178
|
+
]
|
|
179
|
+
case 'unhealthy':
|
|
180
|
+
return [
|
|
181
|
+
...problem.services.map(({ service, state, health }) => `${service}: ${health ? `${state} (${health})` : state}`),
|
|
182
|
+
`Inspect the logs: ${problem.logsCommand ?? 'docker compose logs <service>'}`,
|
|
183
|
+
]
|
|
184
|
+
default:
|
|
185
|
+
return [
|
|
186
|
+
'docker compose failed — see the output above, fix the cause and re-run.',
|
|
187
|
+
'Output says "port is already allocated" or "ports are not available"? Another process holds that port: pick a free one with the matching *_PORT in .env.',
|
|
188
|
+
...(platform === 'win32'
|
|
189
|
+
? ['On Windows the port may sit in a range reserved by Hyper-V/WinNAT (list them: netsh interface ipv4 show excludedportrange protocol=tcp); choose a port outside those ranges.']
|
|
190
|
+
: []),
|
|
191
|
+
]
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const PROBLEM_TITLES = {
|
|
196
|
+
'cli-missing': 'Docker is not installed (docker CLI not found).',
|
|
197
|
+
'compose-missing': 'Docker Compose v2 is not available.',
|
|
198
|
+
'daemon-stopped': 'The Docker engine is not running.',
|
|
199
|
+
'daemon-unresponsive': 'The Docker engine is not responding.',
|
|
200
|
+
'daemon-permission': 'No permission to use the Docker engine.',
|
|
201
|
+
'port-conflict': 'Infrastructure ports are already in use.',
|
|
202
|
+
unhealthy: 'Infrastructure services did not become healthy.',
|
|
203
|
+
'compose-failed': 'Starting the infrastructure containers failed.',
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// Every message ends with the opt-out, so a developer with their own
|
|
207
|
+
// PostgreSQL/Redis/Meilisearch is never stuck behind a Docker problem.
|
|
208
|
+
// databaseUrlFile -> where DATABASE_URL lives (apps/mercato/.env in the monorepo)
|
|
209
|
+
// portConflictHints -> layout-specific extra lines for port conflicts
|
|
210
|
+
export function formatInfraProblem(problem, {
|
|
211
|
+
platform = process.platform,
|
|
212
|
+
optOutCommand = `yarn setup ${NO_INFRA_FLAG}`,
|
|
213
|
+
wsl = platform === 'linux' && detectWsl(),
|
|
214
|
+
databaseUrlFile = '.env',
|
|
215
|
+
portConflictHints = [],
|
|
216
|
+
} = {}) {
|
|
217
|
+
return [
|
|
218
|
+
PROBLEM_TITLES[problem.code] ?? PROBLEM_TITLES['compose-failed'],
|
|
219
|
+
...remediationFor(problem, platform, { wsl, databaseUrlFile, portConflictHints }).map((line) => ` ${line}`),
|
|
220
|
+
` Already running PostgreSQL, Redis and Meilisearch yourself? Re-run with: ${optOutCommand}`,
|
|
221
|
+
' (it makes no Docker calls and keeps the URLs in your .env).',
|
|
222
|
+
]
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// Preflight + `compose up -d --wait`. Never removes containers or volumes:
|
|
226
|
+
// re-running reuses the existing project resources and their data.
|
|
227
|
+
// composeArgs(extra) -> full docker argv for this project's compose file
|
|
228
|
+
// services -> [{ service, port, envKey }] that must become ready
|
|
229
|
+
// upArgs -> extra args placed before `up` (e.g. --profile x)
|
|
230
|
+
// cwd -> directory docker runs in (compose file lookup, .env)
|
|
231
|
+
// beforeUp -> slow preparation (image pulls/builds) that should
|
|
232
|
+
// only run once the cheap checks above passed
|
|
233
|
+
export async function startInfraServices({
|
|
234
|
+
composeArgs,
|
|
235
|
+
services,
|
|
236
|
+
upArgs = [],
|
|
237
|
+
cwd,
|
|
238
|
+
beforeUp,
|
|
239
|
+
detect = detectDockerRuntime,
|
|
240
|
+
spawnSyncImpl = spawnSync,
|
|
241
|
+
portProbe = probeTcpPort,
|
|
242
|
+
log = console.log,
|
|
243
|
+
}) {
|
|
244
|
+
const runtime = detect()
|
|
245
|
+
if (!runtime.ok) return { ok: false, problem: { code: runtime.code, detail: runtime.detail } }
|
|
246
|
+
|
|
247
|
+
const required = services.map((entry) => entry.service)
|
|
248
|
+
// null when `compose ps` itself fails (e.g. an interpolation error in .env).
|
|
249
|
+
const listServices = () => {
|
|
250
|
+
const ps = spawnSyncImpl('docker', composeArgs(['ps', '--all', '--format', 'json']), { cwd, encoding: 'utf8', windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
|
|
251
|
+
return !ps?.error && (ps?.status ?? 1) === 0 ? parseComposePsOutput(ps.stdout) : null
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
const listed = listServices()
|
|
255
|
+
const running = runningComposeServices(listed ?? [])
|
|
256
|
+
// Without the project's container list our own running containers would look
|
|
257
|
+
// like foreign port owners, so the port probe is skipped and `compose up`
|
|
258
|
+
// reports the real compose error instead.
|
|
259
|
+
if (listed === null) {
|
|
260
|
+
log(' could not list this project\'s containers (docker compose ps failed); skipping the port check')
|
|
261
|
+
} else {
|
|
262
|
+
const conflicts = await findPortConflicts(services, { running, probe: portProbe })
|
|
263
|
+
if (conflicts.length > 0) return { ok: false, problem: { code: 'port-conflict', ports: conflicts } }
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
const reused = required.filter((service) => running.has(service))
|
|
267
|
+
if (reused.length > 0) log(` reusing running containers: ${reused.join(', ')} (data preserved)`)
|
|
268
|
+
if (beforeUp) beforeUp()
|
|
269
|
+
|
|
270
|
+
const up = spawnSyncImpl('docker', composeArgs([...upArgs, 'up', '-d', '--wait']), { cwd, stdio: 'inherit', windowsHide: true })
|
|
271
|
+
if (up?.error) return { ok: false, problem: { code: 'compose-failed', detail: up.error.message } }
|
|
272
|
+
if ((up?.status ?? 1) === 0) return { ok: true, reused }
|
|
273
|
+
|
|
274
|
+
const after = listServices()
|
|
275
|
+
const unhealthy = after === null ? [] : findUnhealthyServices(after, required)
|
|
276
|
+
if (unhealthy.length > 0) {
|
|
277
|
+
const logsCommand = `docker ${composeArgs(['logs', unhealthy[0].service]).join(' ')}`
|
|
278
|
+
return { ok: false, problem: { code: 'unhealthy', services: unhealthy, logsCommand } }
|
|
279
|
+
}
|
|
280
|
+
return { ok: false, problem: { code: 'compose-failed' } }
|
|
281
|
+
}
|
package/src/infra.mjs
CHANGED
|
@@ -7,7 +7,12 @@ import fs from 'node:fs'
|
|
|
7
7
|
import path from 'node:path'
|
|
8
8
|
import { fileURLToPath } from 'node:url'
|
|
9
9
|
|
|
10
|
-
import { detectDocker, resolveRepoRoot, runCompose, runCaptureSync } from './compose.mjs'
|
|
10
|
+
import { composeArgs, detectDocker, resolveRepoRoot, runCompose, runCaptureSync } from './compose.mjs'
|
|
11
|
+
import { resolveStackPorts } from './constants.mjs'
|
|
12
|
+
import { readEnvValue } from './env-file.mjs'
|
|
13
|
+
import { formatInfraProblem, startInfraServices } from './infra-preflight.mjs'
|
|
14
|
+
|
|
15
|
+
const LOOPBACK_DATABASE_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '[::1]', 'host.docker.internal'])
|
|
11
16
|
|
|
12
17
|
export function ensureMcpSharedDir(repoRoot) {
|
|
13
18
|
// Pre-create the bind-mount source so dockerd never creates it root-owned
|
|
@@ -31,6 +36,74 @@ export function infraUp(repoRooot, { profiles = [] } = {}) {
|
|
|
31
36
|
return runCompose(repoRoot, upArgs).status ?? 1
|
|
32
37
|
}
|
|
33
38
|
|
|
39
|
+
export const INFRA_SERVICE_PORT_KEYS = {
|
|
40
|
+
postgres: 'POSTGRES_PORT',
|
|
41
|
+
redis: 'REDIS_PORT',
|
|
42
|
+
meilisearch: 'MEILISEARCH_PORT',
|
|
43
|
+
opencode: 'OPENCODE_PORT',
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function infraServices(repoRoot, env = process.env) {
|
|
47
|
+
const ports = resolveStackPorts(repoRoot, env)
|
|
48
|
+
return Object.entries(INFRA_SERVICE_PORT_KEYS).map(([service, envKey]) => ({ service, port: ports[service], envKey }))
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function externalDatabaseHost(repoRoot, env = process.env) {
|
|
52
|
+
const raw = env.DATABASE_URL ?? readEnvValue(path.join(repoRoot, 'apps', 'mercato', '.env'), 'DATABASE_URL')
|
|
53
|
+
if (!raw) return null
|
|
54
|
+
try {
|
|
55
|
+
const host = new URL(raw).hostname.toLowerCase()
|
|
56
|
+
return host && !LOOPBACK_DATABASE_HOSTS.has(host) ? host : null
|
|
57
|
+
} catch {
|
|
58
|
+
return null
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// infraUp plus the shared preflight: distinguishes missing CLI / compose,
|
|
63
|
+
// stopped daemon, port conflicts, and failed healthchecks instead of a bare
|
|
64
|
+
// non-zero compose exit. Returns { ok, problem? }; never touches volumes.
|
|
65
|
+
export async function startInfra(repoRoot, { profiles = [], env = process.env, log = console.log, beforeUp, startImpl = startInfraServices } = {}) {
|
|
66
|
+
ensureMcpSharedDir(repoRoot)
|
|
67
|
+
const externalHost = externalDatabaseHost(repoRoot, env)
|
|
68
|
+
if (externalHost) {
|
|
69
|
+
log(` DATABASE_URL points at ${externalHost}; it is kept as is. Use --no-infra to skip the local containers.`)
|
|
70
|
+
}
|
|
71
|
+
return startImpl({
|
|
72
|
+
composeArgs: (extra) => composeArgs(repoRoot, extra),
|
|
73
|
+
services: infraServices(repoRoot),
|
|
74
|
+
upArgs: profiles.flatMap((profile) => ['--profile', profile]),
|
|
75
|
+
cwd: repoRoot,
|
|
76
|
+
beforeUp,
|
|
77
|
+
log,
|
|
78
|
+
})
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// `--no-infra` promises zero Docker calls for the whole run, including the dev
|
|
82
|
+
// runtime the starter launches afterwards (scripts/dev.mjs honors the flag).
|
|
83
|
+
export function devRuntimeArgs(passthrough, { noInfra = false } = {}) {
|
|
84
|
+
return noInfra && !passthrough.includes('--no-infra') ? [...passthrough, '--no-infra'] : passthrough
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function resolveUpMode(selectedMode, { noInfra = false } = {}) {
|
|
88
|
+
return noInfra && selectedMode === 'docker' ? 'hybrid' : selectedMode
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Monorepo layout: DATABASE_URL lives in apps/mercato/.env, and the compose
|
|
92
|
+
// file pins container names (${MERCATO_STACK:-mercato}-*), so a second checkout
|
|
93
|
+
// clashes on names as well as ports.
|
|
94
|
+
export const MONOREPO_PORT_CONFLICT_HINTS = [
|
|
95
|
+
'Ports held by mercato-* containers of another checkout of this repo? Stop them there (yarn infra:down), or give this checkout its own stack: MERCATO_STACK=<name> plus free *_PORT values in .env (changing ports alone still collides on the container names; see docker/README.md).',
|
|
96
|
+
]
|
|
97
|
+
|
|
98
|
+
export function describeInfraProblem(problem, options = {}) {
|
|
99
|
+
return formatInfraProblem(problem, {
|
|
100
|
+
optOutCommand: 'yarn setup --no-infra',
|
|
101
|
+
databaseUrlFile: 'apps/mercato/.env',
|
|
102
|
+
portConflictHints: MONOREPO_PORT_CONFLICT_HINTS,
|
|
103
|
+
...options,
|
|
104
|
+
})
|
|
105
|
+
}
|
|
106
|
+
|
|
34
107
|
export function infraDown(repoRoot, { volumes = false } = {}) {
|
|
35
108
|
return runCompose(repoRoot ?? resolveRepoRoot(), ['down', ...(volumes ? ['--volumes'] : [])]).status ?? 1
|
|
36
109
|
}
|
package/src/steps.mjs
CHANGED
|
@@ -10,7 +10,8 @@ import { CAPTURED_CA_BUNDLE, DEFAULT_OPENCODE_BASE_IMAGE, OPENCODE_SERVICE_IMAGE
|
|
|
10
10
|
import { checkBuildToolchain, checkContainerRuntime, checkGit, checkNodeVersion, checkWsl2, detectHostGateway } from './doctor.mjs'
|
|
11
11
|
import { ensureEnvFiles } from './env-setup.mjs'
|
|
12
12
|
import { addEnvValue, readEnvValue } from './env-file.mjs'
|
|
13
|
-
import {
|
|
13
|
+
import { describeInfraProblem, startInfra } from './infra.mjs'
|
|
14
|
+
import { findUnhealthyServices } from './infra-preflight.mjs'
|
|
14
15
|
import { ensureLlmProvider } from './providers.mjs'
|
|
15
16
|
import { color, formatDuration, guideBox, statusLine, stepHeader } from './ui.mjs'
|
|
16
17
|
|
|
@@ -129,6 +130,7 @@ export function migrationsFingerprint(repoRoot) {
|
|
|
129
130
|
// probe cannot run (postgres not up yet, compose unavailable) — callers fall
|
|
130
131
|
// back to marker-only behavior.
|
|
131
132
|
export function readAppliedMigrationModules(ctx, { runComposeImpl = runCompose } = {}) {
|
|
133
|
+
if (ctx.flags?.noInfra) return null
|
|
132
134
|
const dbUrl = readEnvValue(path.join(ctx.repoRoot, 'apps', 'mercato', '.env'), 'DATABASE_URL') ?? ''
|
|
133
135
|
const dbName = dbUrl.split('/').pop()?.split('?')[0]?.trim() || 'open-mercato'
|
|
134
136
|
let result
|
|
@@ -168,6 +170,7 @@ export function readAppliedMigrationModules(ctx, { runComposeImpl = runCompose }
|
|
|
168
170
|
// Returns 'ok', 'auth-failed', or null when no verdict is possible (URL
|
|
169
171
|
// unparsable, compose unavailable, postgres not managed here).
|
|
170
172
|
export function probePostgresCredentials(ctx, { runComposeImpl = runCompose } = {}) {
|
|
173
|
+
if (ctx.flags?.noInfra) return null
|
|
171
174
|
const dbUrl = readEnvValue(path.join(ctx.repoRoot, 'apps', 'mercato', '.env'), 'DATABASE_URL') ?? ''
|
|
172
175
|
let parsed
|
|
173
176
|
try {
|
|
@@ -199,6 +202,7 @@ export function probePostgresCredentials(ctx, { runComposeImpl = runCompose } =
|
|
|
199
202
|
// existence in one round trip. Returns true (seeded), false (empty/no table),
|
|
200
203
|
// or null when the probe cannot run.
|
|
201
204
|
export function databaseIsInitialized(ctx, { runComposeImpl = runCompose } = {}) {
|
|
205
|
+
if (ctx.flags?.noInfra) return null
|
|
202
206
|
const dbUrl = readEnvValue(path.join(ctx.repoRoot, 'apps', 'mercato', '.env'), 'DATABASE_URL') ?? ''
|
|
203
207
|
const dbName = dbUrl.split('/').pop()?.split('?')[0]?.trim() || 'open-mercato'
|
|
204
208
|
let result
|
|
@@ -249,7 +253,7 @@ export function yarnInvocation(ctx, args) {
|
|
|
249
253
|
|
|
250
254
|
function runYarn(ctx, args) {
|
|
251
255
|
const invocation = yarnInvocation(ctx, args)
|
|
252
|
-
const status = runStreamingSync(invocation.command, invocation.args, { cwd: ctx.repoRoot, env: ctx.env })
|
|
256
|
+
const status = (ctx.runStreamingImpl ?? runStreamingSync)(invocation.command, invocation.args, { cwd: ctx.repoRoot, env: ctx.env })
|
|
253
257
|
if (status !== 0) {
|
|
254
258
|
throw new Error(`yarn ${args.join(' ')} failed (exit ${status}) — fix the error above and re-run; completed steps are skipped.`)
|
|
255
259
|
}
|
|
@@ -312,7 +316,7 @@ export const containerRuntimeStep = {
|
|
|
312
316
|
if (wsl && wsl.level !== 'pass') guide.push(`WSL2 first: ${wsl.detail}`, ...wsl.guide, '')
|
|
313
317
|
guide.push(...runtime.guide)
|
|
314
318
|
guide.push('', 'Re-run this starter once the runtime is up — every completed step is skipped.')
|
|
315
|
-
if (ctx.mode === 'hybrid') guide.push('No container runtime at all? `up --no-infra` starts just the app against services you point .env at.')
|
|
319
|
+
if (ctx.mode === 'hybrid') guide.push('No container runtime at all? `yarn setup --no-infra` (or `yarn om up --no-infra`) starts just the app against services you point .env at, without any Docker call.')
|
|
316
320
|
throw new StepBlocked(this.id, guide)
|
|
317
321
|
},
|
|
318
322
|
}
|
|
@@ -539,26 +543,34 @@ export const infraUpStep = {
|
|
|
539
543
|
title: 'Infra containers (postgres, redis, meilisearch, opencode)',
|
|
540
544
|
appliesTo: (ctx) => ctx.mode === 'hybrid' && !ctx.flags.noInfra,
|
|
541
545
|
async check(ctx) {
|
|
542
|
-
const ps = runCompose(ctx.repoRoot, ['ps', '--format', 'json'], { stdio: 'pipe' })
|
|
546
|
+
const ps = (ctx.runComposeImpl ?? runCompose)(ctx.repoRoot, ['ps', '--format', 'json'], { stdio: 'pipe' })
|
|
543
547
|
const services = parseComposePsOutput(ps.stdout ?? '')
|
|
544
|
-
const running = new Set(services.filter((entry) => entry.State === 'running').map((entry) => entry.Service))
|
|
545
548
|
const required = ['postgres', 'redis', 'meilisearch', 'opencode']
|
|
546
|
-
|
|
549
|
+
// "running" is not enough: a container whose healthcheck is still
|
|
550
|
+
// `starting` (or `unhealthy`) must go through apply, whose `up --wait`
|
|
551
|
+
// blocks until it is healthy, before the database step touches postgres.
|
|
552
|
+
const notReady = findUnhealthyServices(services, required)
|
|
553
|
+
const missing = notReady.map((entry) => entry.service)
|
|
547
554
|
ctx.infraMissing = missing
|
|
548
|
-
|
|
555
|
+
const detail = missing.length === 0
|
|
556
|
+
? 'all infra containers running and healthy'
|
|
557
|
+
: `starting: ${notReady.map(({ service, state, health }) => (state === 'running' && health ? `${service} (${health})` : service)).join(', ')}`
|
|
558
|
+
return { ok: missing.length === 0 && !ctx.flags.rebuild, detail }
|
|
549
559
|
},
|
|
550
560
|
async apply(ctx) {
|
|
551
|
-
const
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
561
|
+
const prepareOpencodeImage = ctx.ensureOpencodeImageImpl ?? ensureOpencodeImage
|
|
562
|
+
const outcome = await (ctx.startInfraImpl ?? startInfra)(ctx.repoRoot, {
|
|
563
|
+
profiles: ctx.flags.profiles,
|
|
564
|
+
log: ctx.log,
|
|
565
|
+
beforeUp: () => prepareOpencodeImage(ctx),
|
|
566
|
+
})
|
|
567
|
+
if (!outcome.ok) {
|
|
568
|
+
const lines = describeInfraProblem(outcome.problem)
|
|
557
569
|
if (ctx.tlsProbes?.some((entry) => entry.status === 'intercepted')) {
|
|
558
|
-
|
|
570
|
+
lines.push(' TLS/certificate errors from the engine usually mean it does not trust the corporate CA yet: restart Docker Desktop (it re-imports the Windows certificate store) or Rancher Desktop (the starter wrote a provisioning script for it), then re-run.')
|
|
559
571
|
}
|
|
560
|
-
|
|
561
|
-
throw new Error(
|
|
572
|
+
lines.push(' Re-running resumes from this step; database setup is not attempted until the infra is healthy.')
|
|
573
|
+
throw new Error(lines.join('\n'))
|
|
562
574
|
}
|
|
563
575
|
},
|
|
564
576
|
}
|
|
@@ -634,7 +646,13 @@ export const databaseStep = {
|
|
|
634
646
|
if (alreadyInitialized) {
|
|
635
647
|
ctx.log(' database already initialized (existing data volume) — recording state, skipping first-run seed')
|
|
636
648
|
} else {
|
|
637
|
-
|
|
649
|
+
// --skip-if-initialized keeps re-runs non-destructive when no probe
|
|
650
|
+
// could tell (e.g. --no-infra against an external, already seeded
|
|
651
|
+
// database): init then keeps the data instead of aborting with a hint
|
|
652
|
+
// to run the destructive --reinstall. An emptied volume (dbReinitialize)
|
|
653
|
+
// has no users, so it seeds either way; the flag is left off there.
|
|
654
|
+
const initArgs = ctx.dbReinitialize ? ['initialize'] : ['initialize', '--', '--skip-if-initialized']
|
|
655
|
+
runYarn({ ...ctx, env: { ...ctx.env, OM_INIT_DEV_AUTOSTART: '1' } }, initArgs)
|
|
638
656
|
}
|
|
639
657
|
writeState(ctx.repoRoot, ctx.dbMarker, new Date().toISOString())
|
|
640
658
|
}
|