-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathdocker.ts
More file actions
514 lines (485 loc) · 19.7 KB
/
docker.ts
File metadata and controls
514 lines (485 loc) · 19.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
import * as Command from "@effect/platform/Command"
import type * as CommandExecutor from "@effect/platform/CommandExecutor"
import { ExitCode } from "@effect/platform/CommandExecutor"
import type { PlatformError } from "@effect/platform/Error"
import { Duration, Effect, pipe, Schedule } from "effect"
import { runCommandCapture, runCommandExitCode, runCommandWithExitCodes } from "./command-runner.js"
import { composeSpec, resolveDockerComposeEnv } from "./docker-compose-env.js"
import { parseInspectNetworkEntry } from "./docker-inspect-parse.js"
import { CommandFailedError, DockerCommandError } from "./errors.js"
export { classifyDockerAccessIssue, ensureDockerDaemonAccess } from "./docker-daemon-access.js"
export { parseDockerPublishedHostPorts, runDockerPsPublishedHostPorts } from "./docker-published-ports.js"
const runCompose = (
cwd: string,
args: ReadonlyArray<string>,
okExitCodes: ReadonlyArray<number>
): Effect.Effect<void, DockerCommandError | PlatformError, CommandExecutor.CommandExecutor> =>
Effect.gen(function*(_) {
const env = yield* _(resolveDockerComposeEnv(cwd))
yield* _(
runCommandWithExitCodes(
{
...composeSpec(cwd, args),
...(Object.keys(env).length > 0 ? { env } : {})
},
okExitCodes,
(exitCode) => new DockerCommandError({ exitCode })
)
)
})
const runComposeCapture = (
cwd: string,
args: ReadonlyArray<string>,
okExitCodes: ReadonlyArray<number>
): Effect.Effect<string, DockerCommandError | PlatformError, CommandExecutor.CommandExecutor> =>
Effect.gen(function*(_) {
const env = yield* _(resolveDockerComposeEnv(cwd))
return yield* _(
runCommandCapture(
{
...composeSpec(cwd, args),
...(Object.keys(env).length > 0 ? { env } : {})
},
okExitCodes,
(exitCode) => new DockerCommandError({ exitCode })
)
)
})
const dockerComposeUpRetrySchedule = Schedule.addDelay(
Schedule.recurs(2),
() => Duration.seconds(2)
)
const retryDockerComposeUp = (
cwd: string,
effect: Effect.Effect<void, DockerCommandError | PlatformError, CommandExecutor.CommandExecutor>
): Effect.Effect<void, DockerCommandError | PlatformError, CommandExecutor.CommandExecutor> =>
effect.pipe(
Effect.tapError(() =>
Effect.logWarning(
`docker compose up failed in ${cwd}; retrying (possible transient Docker Hub/DNS issue)...`
)
),
Effect.retry(dockerComposeUpRetrySchedule)
)
// CHANGE: run docker compose up -d --build in the target directory
// WHY: provide a controlled shell effect for image creation
// QUOTE(ТЗ): "создавать докер образы"
// REF: user-request-2026-01-07
// SOURCE: n/a
// FORMAT THEOREM: forall dir: exitCode(cmd(dir)) = 0 -> image_built(dir)
// PURITY: SHELL
// EFFECT: Effect<void, DockerCommandError | PlatformError, CommandExecutor>
// INVARIANT: command output is inherited from the parent process
// COMPLEXITY: O(command)
export const runDockerComposeUp = (
cwd: string
): Effect.Effect<void, DockerCommandError | PlatformError, CommandExecutor.CommandExecutor> =>
retryDockerComposeUp(
cwd,
runCompose(cwd, ["up", "-d", "--build"], [Number(ExitCode(0))])
)
export const dockerComposeUpRecreateArgs: ReadonlyArray<string> = [
"up",
"-d",
"--build",
"--force-recreate"
]
// CHANGE: recreate running containers and refresh images when needed
// WHY: apply env/template updates while preserving workspace volumes
// QUOTE(ТЗ): "сбросит только окружение"
// REF: user-request-2026-02-11-force-env
// SOURCE: n/a
// FORMAT THEOREM: ∀dir: up_force_recreate(dir) → recreated(containers(dir)) ∧ preserved(volumes(dir)) ∧ updated(images(dir))
// PURITY: SHELL
// EFFECT: Effect<void, DockerCommandError | PlatformError, CommandExecutor>
// INVARIANT: may rebuild images but does not remove volumes
// COMPLEXITY: O(command)
export const runDockerComposeUpRecreate = (
cwd: string
): Effect.Effect<void, DockerCommandError | PlatformError, CommandExecutor.CommandExecutor> =>
retryDockerComposeUp(
cwd,
runCompose(cwd, dockerComposeUpRecreateArgs, [Number(ExitCode(0))])
)
// CHANGE: run docker compose down in the target directory
// WHY: allow stopping managed containers from the CLI/menu
// QUOTE(ТЗ): "Могу удалить / Отключить"
// REF: user-request-2026-01-07
// SOURCE: n/a
// FORMAT THEOREM: forall dir: exitCode(cmd(dir)) = 0 -> containers_stopped(dir)
// PURITY: SHELL
// EFFECT: Effect<void, DockerCommandError | PlatformError, CommandExecutor>
// INVARIANT: command output is inherited from the parent process
// COMPLEXITY: O(command)
export const runDockerComposeDown = (
cwd: string
): Effect.Effect<void, DockerCommandError | PlatformError, CommandExecutor.CommandExecutor> =>
runCompose(cwd, ["down"], [Number(ExitCode(0))])
// CHANGE: run docker compose down -v in the target directory
// WHY: allow a truly fresh environment by wiping the named volumes (e.g. /home/dev)
// QUOTE(ТЗ): "контейнер полностью должен же очищаться при --force"
// REF: user-request-2026-02-07-force-wipe-volumes
// SOURCE: n/a
// FORMAT THEOREM: ∀dir: down_v(dir) → removed(volumes(dir))
// PURITY: SHELL
// EFFECT: Effect<void, DockerCommandError | PlatformError, CommandExecutor>
// INVARIANT: removes only resources within the compose project (containers, networks, volumes)
// COMPLEXITY: O(command)
export const runDockerComposeDownVolumes = (
cwd: string
): Effect.Effect<void, DockerCommandError | PlatformError, CommandExecutor.CommandExecutor> =>
runCompose(cwd, ["down", "-v"], [Number(ExitCode(0))])
// CHANGE: recreate docker compose environment in the target directory
// WHY: allow a clean rebuild of the container from the UI
// QUOTE(ТЗ): "дропнул контейнер и заново его создал"
// REF: user-request-2026-01-13
// SOURCE: n/a
// FORMAT THEOREM: forall dir: down(dir) && up(dir) -> recreated(dir)
// PURITY: SHELL
// EFFECT: Effect<void, DockerCommandError | PlatformError, CommandExecutor>
// INVARIANT: down completes before up starts
// COMPLEXITY: O(command)
export const runDockerComposeRecreate = (
cwd: string
): Effect.Effect<void, DockerCommandError | PlatformError, CommandExecutor.CommandExecutor> =>
pipe(
runDockerComposeDown(cwd),
Effect.zipRight(runDockerComposeUp(cwd))
)
// CHANGE: run docker compose ps in the target directory
// WHY: expose runtime status in the interactive menu
// QUOTE(ТЗ): "вижу всю инфу по ним"
// REF: user-request-2026-01-07
// SOURCE: n/a
// FORMAT THEOREM: forall dir: exitCode(cmd(dir)) = 0 -> status_listed(dir)
// PURITY: SHELL
// EFFECT: Effect<void, DockerCommandError | PlatformError, CommandExecutor>
// INVARIANT: command output is inherited from the parent process
// COMPLEXITY: O(command)
export const runDockerComposePs = (
cwd: string
): Effect.Effect<void, DockerCommandError | PlatformError, CommandExecutor.CommandExecutor> =>
runCompose(cwd, ["ps"], [Number(ExitCode(0))])
// CHANGE: capture docker compose ps output in a parseable format
// WHY: allow structured, readable status output for CLI
// QUOTE(ТЗ): "информация отображалиась удобно"
// REF: user-request-2026-01-28
// SOURCE: n/a
// FORMAT THEOREM: forall dir: ps_fmt(dir) -> tabbed_string
// PURITY: SHELL
// EFFECT: Effect<string, DockerCommandError | PlatformError, CommandExecutor>
// INVARIANT: output is tab-delimited columns from docker compose ps
// COMPLEXITY: O(command)
export const runDockerComposePsFormatted = (
cwd: string
): Effect.Effect<string, DockerCommandError | PlatformError, CommandExecutor.CommandExecutor> =>
runComposeCapture(
cwd,
["ps", "--format", "{{.Name}}\t{{.Status}}\t{{.Ports}}\t{{.Image}}"],
[Number(ExitCode(0))]
)
// CHANGE: run docker compose logs in the target directory
// WHY: allow quick inspection of container output without leaving the menu
// QUOTE(ТЗ): "вижу всю инфу по ним"
// REF: user-request-2026-01-07
// SOURCE: n/a
// FORMAT THEOREM: forall dir: exitCode(cmd(dir)) in {0,130} -> logs_shown(dir)
// PURITY: SHELL
// EFFECT: Effect<void, DockerCommandError | PlatformError, CommandExecutor>
// INVARIANT: command output is inherited from the parent process
// COMPLEXITY: O(command)
export const runDockerComposeLogs = (
cwd: string
): Effect.Effect<void, DockerCommandError | PlatformError, CommandExecutor.CommandExecutor> =>
runCompose(cwd, ["logs", "--tail", "200"], [Number(ExitCode(0)), 130])
// CHANGE: stream docker compose logs until interrupted
// WHY: allow synchronous clone flow to surface container output
// QUOTE(ТЗ): "должно работать синхронно отображая весь процесс"
// REF: user-request-2026-01-28
// SOURCE: n/a
// FORMAT THEOREM: forall dir: logs_follow(dir) -> stdout(stream)
// PURITY: SHELL
// EFFECT: Effect<void, DockerCommandError | PlatformError, CommandExecutor>
// INVARIANT: command output is inherited from the parent process
// COMPLEXITY: O(command)
export const runDockerComposeLogsFollow = (
cwd: string
): Effect.Effect<void, DockerCommandError | PlatformError, CommandExecutor.CommandExecutor> =>
runCompose(cwd, ["logs", "--follow", "--tail", "0"], [Number(ExitCode(0)), 130])
// CHANGE: run docker exec and return its exit code
// WHY: allow polling for clone completion markers inside the container
// QUOTE(ТЗ): "весь процесс от и до"
// REF: user-request-2026-01-28
// SOURCE: n/a
// FORMAT THEOREM: forall cmd: exitCode(docker exec cmd) = n -> deterministic(n)
// PURITY: SHELL
// EFFECT: Effect<number, PlatformError, CommandExecutor>
// INVARIANT: stdout/stderr are suppressed for polling commands
// COMPLEXITY: O(command)
export const runDockerExecExitCode = (
cwd: string,
containerName: string,
args: ReadonlyArray<string>
): Effect.Effect<number, PlatformError, CommandExecutor.CommandExecutor> =>
Effect.gen(function*(_) {
const command = pipe(
Command.make("docker", "exec", containerName, ...args),
Command.workingDirectory(cwd),
Command.stdout("pipe"),
Command.stderr("pipe")
)
const exitCode = yield* _(Command.exitCode(command))
return Number(exitCode)
})
// CHANGE: inspect container IP address
// WHY: enable per-container DNS mapping on the host
// QUOTE(ТЗ): "У каждого контейнера свой IP т.е свой домен"
// REF: user-request-2026-01-30-dns
// SOURCE: n/a
// FORMAT THEOREM: forall c: inspect(c) -> ip(c)
// PURITY: SHELL
// EFFECT: Effect<string, DockerCommandError | PlatformError, CommandExecutor>
// INVARIANT: returns empty string when not available
// COMPLEXITY: O(command)
export const runDockerInspectContainerIp = (
cwd: string,
containerName: string
): Effect.Effect<string, DockerCommandError | PlatformError, CommandExecutor.CommandExecutor> =>
pipe(
runCommandCapture(
{
cwd,
command: "docker",
args: [
"inspect",
"-f",
// Prefer the built-in `bridge` network IP when present so the printed IP
// works from "external" containers that default to `bridge`.
// Example output:
// bridge=172.17.0.4
// <project>_dg-<repo>-net=192.168.64.3
String.raw`{{range $k,$v := .NetworkSettings.Networks}}{{printf "%s=%s\n" $k $v.IPAddress}}{{end}}`,
containerName
]
},
[Number(ExitCode(0))],
(exitCode) => new DockerCommandError({ exitCode })
),
Effect.map((output) => {
const lines = output
.trim()
.split(/\r?\n/)
.map((line) => line.trim())
.filter((line) => line.length > 0)
const entries = lines.flatMap((line) => parseInspectNetworkEntry(line))
if (entries.length === 0) {
return ""
}
const map = new Map(entries)
return map.get("bridge") ?? entries[0]![1]
})
)
// CHANGE: inspect the container IP address on the default `bridge` network
// WHY: allow callers to decide whether `docker network connect bridge` is needed
// QUOTE(ТЗ): "подключиться с внешнего контейнера"
// REF: user-request-2026-02-10-bridge-ip
// SOURCE: n/a
// FORMAT THEOREM: ∀c: bridge(c) → ip_bridge(c) ≠ ""
// PURITY: SHELL
// EFFECT: Effect<string, DockerCommandError | PlatformError, CommandExecutor>
// INVARIANT: returns "" when the container is not connected to `bridge`
// COMPLEXITY: O(command)
export const runDockerInspectContainerBridgeIp = (
cwd: string,
containerName: string
): Effect.Effect<string, DockerCommandError | PlatformError, CommandExecutor.CommandExecutor> =>
pipe(
runCommandCapture(
{
cwd,
command: "docker",
args: [
"inspect",
"-f",
"{{with (index .NetworkSettings.Networks \"bridge\")}}{{.IPAddress}}{{end}}",
containerName
]
},
[Number(ExitCode(0))],
(exitCode) => new DockerCommandError({ exitCode })
),
Effect.map((output) => output.trim())
)
// CHANGE: connect an existing container to the default `bridge` network
// WHY: allow "external" containers (which default to `bridge`) to reach services by container IP
// QUOTE(ТЗ): "Всё что запущено в докере должно быть публично наружу"
// REF: user-request-2026-02-10-public-ports
// SOURCE: n/a
// FORMAT THEOREM: ∀c: up(c) → reachable(bridge_ip(c), ports(c))
// PURITY: SHELL
// EFFECT: Effect<void, DockerCommandError | PlatformError, CommandExecutor>
// INVARIANT: does not fail the overall flow when already connected (handled by caller)
// COMPLEXITY: O(command)
export const runDockerNetworkConnectBridge = (
cwd: string,
containerName: string
): Effect.Effect<void, DockerCommandError | PlatformError, CommandExecutor.CommandExecutor> =>
pipe(
runCommandCapture(
{
cwd,
command: "docker",
args: ["network", "connect", "bridge", containerName]
},
[Number(ExitCode(0))],
(exitCode) => new DockerCommandError({ exitCode })
),
Effect.asVoid
)
// CHANGE: check whether a Docker network already exists
// WHY: allow shared-network mode to create the network only when missing
// QUOTE(ТЗ): "Что бы текущие проекты не ложились"
// REF: user-request-2026-02-20-network-shared
// SOURCE: n/a
// FORMAT THEOREM: ∀n: exists(n) ∈ {true,false}
// PURITY: SHELL
// EFFECT: Effect<boolean, PlatformError, CommandExecutor>
// INVARIANT: returns false for non-zero inspect exit codes
// COMPLEXITY: O(command)
export const runDockerNetworkExists = (
cwd: string,
networkName: string
): Effect.Effect<boolean, PlatformError, CommandExecutor.CommandExecutor> =>
runCommandExitCode({
cwd,
command: "docker",
args: ["network", "inspect", networkName]
}).pipe(Effect.map((exitCode) => exitCode === 0))
// CHANGE: create a Docker bridge network with a deterministic name
// WHY: shared-network mode requires an external network before compose up
// QUOTE(ТЗ): "сделай что бы я эту ошибку больше не видел"
// REF: user-request-2026-02-20-network-shared
// SOURCE: n/a
// FORMAT THEOREM: ∀n: create(n)=0 -> network_exists(n)
// PURITY: SHELL
// EFFECT: Effect<void, DockerCommandError | PlatformError, CommandExecutor>
// INVARIANT: network driver is always `bridge`
// COMPLEXITY: O(command)
export const runDockerNetworkCreateBridge = (
cwd: string,
networkName: string
): Effect.Effect<void, DockerCommandError | PlatformError, CommandExecutor.CommandExecutor> =>
runCommandWithExitCodes(
{
cwd,
command: "docker",
args: ["network", "create", "--driver", "bridge", networkName]
},
[Number(ExitCode(0))],
(exitCode) => new DockerCommandError({ exitCode })
)
// CHANGE: create a Docker bridge network with an explicit subnet
// WHY: allow callers to bypass default address-pool allocation when it is exhausted
// QUOTE(ТЗ): "научилось создавать сети правильно"
// REF: user-request-2026-02-20-network-fallback
// SOURCE: n/a
// FORMAT THEOREM: ∀(n,s): create(n,s)=0 -> exists(n) ∧ subnet(n)=s
// PURITY: SHELL
// EFFECT: Effect<void, DockerCommandError | PlatformError, CommandExecutor>
// INVARIANT: network driver is always `bridge`
// COMPLEXITY: O(command)
export const runDockerNetworkCreateBridgeWithSubnet = (
cwd: string,
networkName: string,
subnet: string
): Effect.Effect<void, DockerCommandError | PlatformError, CommandExecutor.CommandExecutor> =>
runCommandWithExitCodes(
{
cwd,
command: "docker",
args: ["network", "create", "--driver", "bridge", "--subnet", subnet, networkName]
},
[Number(ExitCode(0))],
(exitCode) => new DockerCommandError({ exitCode })
)
// CHANGE: inspect how many containers are attached to a network
// WHY: network GC must remove only detached networks
// QUOTE(ТЗ): "Только так что бы текущие проекты не ложились"
// REF: user-request-2026-02-20-network-gc
// SOURCE: n/a
// FORMAT THEOREM: ∀n: count(n) = |containers(n)|
// PURITY: SHELL
// EFFECT: Effect<number, DockerCommandError | PlatformError, CommandExecutor>
// INVARIANT: parse fallback is 0 when docker inspect output is empty
// COMPLEXITY: O(command)
export const runDockerNetworkContainerCount = (
cwd: string,
networkName: string
): Effect.Effect<number, DockerCommandError | PlatformError, CommandExecutor.CommandExecutor> =>
runCommandCapture(
{
cwd,
command: "docker",
args: ["network", "inspect", "-f", "{{len .Containers}}", networkName]
},
[Number(ExitCode(0))],
(exitCode) => new DockerCommandError({ exitCode })
).pipe(
Effect.map((output) => {
const parsed = Number.parseInt(output.trim(), 10)
return Number.isNaN(parsed) ? 0 : parsed
})
)
// CHANGE: remove a Docker network by name
// WHY: network GC should reclaim detached project-scoped networks
// QUOTE(ТЗ): "убирать мусорные сети автоматически"
// REF: user-request-2026-02-20-network-gc
// SOURCE: n/a
// FORMAT THEOREM: ∀n: rm(n)=0 -> !exists(n)
// PURITY: SHELL
// EFFECT: Effect<void, DockerCommandError | PlatformError, CommandExecutor>
// INVARIANT: removes exactly the named network
// COMPLEXITY: O(command)
export const runDockerNetworkRemove = (
cwd: string,
networkName: string
): Effect.Effect<void, DockerCommandError | PlatformError, CommandExecutor.CommandExecutor> =>
runCommandWithExitCodes(
{
cwd,
command: "docker",
args: ["network", "rm", networkName]
},
[Number(ExitCode(0))],
(exitCode) => new DockerCommandError({ exitCode })
)
// CHANGE: list names of running Docker containers
// WHY: support TUI filtering (e.g. stop only running docker-git containers)
// QUOTE(ТЗ): "Если я выбираю остановку контейнера значит он мне должен показывать контейнеры которые запущены"
// REF: user-request-2026-02-07-stop-only-running
// SOURCE: n/a
// FORMAT THEOREM: forall c: c in ps -> running(c)
// PURITY: SHELL
// EFFECT: Effect<ReadonlyArray<string>, CommandFailedError | PlatformError, CommandExecutor>
// INVARIANT: result contains only non-empty container names
// COMPLEXITY: O(command)
export const runDockerPsNames = (
cwd: string
): Effect.Effect<ReadonlyArray<string>, CommandFailedError | PlatformError, CommandExecutor.CommandExecutor> =>
pipe(
runCommandCapture(
{
cwd,
command: "docker",
args: ["ps", "--format", "{{.Names}}"]
},
[Number(ExitCode(0))],
(exitCode) => new CommandFailedError({ command: "docker ps", exitCode })
),
Effect.map((output) =>
output
.split(/\r?\n/)
.map((line) => line.trim())
.filter((line) => line.length > 0)
)
)