@livestore/utils-dev 0.4.0-dev.0 → 0.4.0-dev.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/.tsbuildinfo.json +1 -1
- package/dist/node/DockerComposeService/DockerComposeService.d.ts +58 -0
- package/dist/node/DockerComposeService/DockerComposeService.d.ts.map +1 -0
- package/dist/node/DockerComposeService/DockerComposeService.js +144 -0
- package/dist/node/DockerComposeService/DockerComposeService.js.map +1 -0
- package/dist/node/DockerComposeService/DockerComposeService.test.d.ts +2 -0
- package/dist/node/DockerComposeService/DockerComposeService.test.d.ts.map +1 -0
- package/dist/node/DockerComposeService/DockerComposeService.test.js +64 -0
- package/dist/node/DockerComposeService/DockerComposeService.test.js.map +1 -0
- package/dist/node/cmd-log.d.ts +21 -0
- package/dist/node/cmd-log.d.ts.map +1 -0
- package/dist/node/cmd-log.js +50 -0
- package/dist/node/cmd-log.js.map +1 -0
- package/dist/node/cmd.d.ts +36 -0
- package/dist/node/cmd.d.ts.map +1 -0
- package/dist/node/cmd.js +234 -0
- package/dist/node/cmd.js.map +1 -0
- package/dist/node/cmd.test.d.ts +2 -0
- package/dist/node/cmd.test.d.ts.map +1 -0
- package/dist/node/cmd.test.js +101 -0
- package/dist/node/cmd.test.js.map +1 -0
- package/dist/node/mod.d.ts +4 -26
- package/dist/node/mod.d.ts.map +1 -1
- package/dist/node/mod.js +51 -59
- package/dist/node/mod.js.map +1 -1
- package/dist/node-vitest/Vitest.d.ts +41 -7
- package/dist/node-vitest/Vitest.d.ts.map +1 -1
- package/dist/node-vitest/Vitest.js +82 -5
- package/dist/node-vitest/Vitest.js.map +1 -1
- package/dist/node-vitest/Vitest.test.d.ts +2 -0
- package/dist/node-vitest/Vitest.test.d.ts.map +1 -0
- package/dist/node-vitest/Vitest.test.js +70 -0
- package/dist/node-vitest/Vitest.test.js.map +1 -0
- package/dist/wrangler/WranglerDevServer.d.ts +52 -0
- package/dist/wrangler/WranglerDevServer.d.ts.map +1 -0
- package/dist/wrangler/WranglerDevServer.js +90 -0
- package/dist/wrangler/WranglerDevServer.js.map +1 -0
- package/dist/wrangler/WranglerDevServer.test.d.ts +2 -0
- package/dist/wrangler/WranglerDevServer.test.d.ts.map +1 -0
- package/dist/wrangler/WranglerDevServer.test.js +77 -0
- package/dist/wrangler/WranglerDevServer.test.js.map +1 -0
- package/dist/wrangler/fixtures/cf-worker.d.ts +8 -0
- package/dist/wrangler/fixtures/cf-worker.d.ts.map +1 -0
- package/dist/wrangler/fixtures/cf-worker.js +11 -0
- package/dist/wrangler/fixtures/cf-worker.js.map +1 -0
- package/dist/wrangler/mod.d.ts +2 -0
- package/dist/wrangler/mod.d.ts.map +1 -0
- package/dist/wrangler/mod.js +2 -0
- package/dist/wrangler/mod.js.map +1 -0
- package/package.json +11 -10
- package/src/node/DockerComposeService/DockerComposeService.test.ts +91 -0
- package/src/node/DockerComposeService/DockerComposeService.ts +328 -0
- package/src/node/DockerComposeService/test-fixtures/docker-compose.yml +4 -0
- package/src/node/cmd-log.ts +92 -0
- package/src/node/cmd.test.ts +129 -0
- package/src/node/cmd.ts +419 -0
- package/src/node/mod.ts +62 -116
- package/src/node-vitest/Vitest.test.ts +112 -0
- package/src/node-vitest/Vitest.ts +193 -17
- package/src/wrangler/WranglerDevServer.test.ts +133 -0
- package/src/wrangler/WranglerDevServer.ts +180 -0
- package/src/wrangler/fixtures/cf-worker.ts +11 -0
- package/src/wrangler/fixtures/wrangler.toml +11 -0
- package/src/wrangler/mod.ts +6 -0
- package/dist/node-vitest/polyfill.d.ts +0 -2
- package/dist/node-vitest/polyfill.d.ts.map +0 -1
- package/dist/node-vitest/polyfill.js +0 -3
- package/dist/node-vitest/polyfill.js.map +0 -1
package/package.json
CHANGED
|
@@ -1,24 +1,28 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@livestore/utils-dev",
|
|
3
|
-
"version": "0.4.0-dev.
|
|
3
|
+
"version": "0.4.0-dev.10",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"sideEffects": [
|
|
6
|
-
"./src/node-vitest/
|
|
6
|
+
"./src/node-vitest/global.ts",
|
|
7
|
+
"./dist/node-vitest/global.js"
|
|
7
8
|
],
|
|
8
9
|
"exports": {
|
|
9
10
|
"./node": "./dist/node/mod.js",
|
|
10
|
-
"./node-vitest": "./dist/node-vitest/mod.js"
|
|
11
|
+
"./node-vitest": "./dist/node-vitest/mod.js",
|
|
12
|
+
"./wrangler": "./dist/wrangler/mod.js"
|
|
11
13
|
},
|
|
12
14
|
"dependencies": {
|
|
13
|
-
"@effect/opentelemetry": "0.
|
|
14
|
-
"@effect/vitest": "0.
|
|
15
|
+
"@effect/opentelemetry": "0.58.0",
|
|
16
|
+
"@effect/vitest": "0.26.0",
|
|
17
|
+
"@iarna/toml": "2.2.5",
|
|
15
18
|
"@opentelemetry/api": "1.9.0",
|
|
16
19
|
"@opentelemetry/exporter-metrics-otlp-http": "0.203.0",
|
|
17
20
|
"@opentelemetry/exporter-trace-otlp-http": "0.203.0",
|
|
18
21
|
"@opentelemetry/sdk-metrics": "2.0.1",
|
|
19
22
|
"@opentelemetry/sdk-trace-base": "2.0.1",
|
|
20
23
|
"@opentelemetry/sdk-trace-node": "2.0.1",
|
|
21
|
-
"
|
|
24
|
+
"wrangler": "4.38.0",
|
|
25
|
+
"@livestore/utils": "0.4.0-dev.10"
|
|
22
26
|
},
|
|
23
27
|
"devDependencies": {},
|
|
24
28
|
"files": [
|
|
@@ -29,10 +33,7 @@
|
|
|
29
33
|
"license": "Apache-2.0",
|
|
30
34
|
"peerDependencies": {},
|
|
31
35
|
"publishConfig": {
|
|
32
|
-
"access": "public"
|
|
33
|
-
"sideEffects": [
|
|
34
|
-
"./dist/node-vitest/polyfill.js"
|
|
35
|
-
]
|
|
36
|
+
"access": "public"
|
|
36
37
|
},
|
|
37
38
|
"scripts": {
|
|
38
39
|
"test": "echo 'No tests for utils-dev'"
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import path from 'node:path'
|
|
2
|
+
import { Duration, Effect, Layer, Stream } from '@livestore/utils/effect'
|
|
3
|
+
import { PlatformNode } from '@livestore/utils/node'
|
|
4
|
+
import { Vitest } from '@livestore/utils-dev/node-vitest'
|
|
5
|
+
import { expect } from 'vitest'
|
|
6
|
+
import { type DockerComposeArgs, DockerComposeService } from './DockerComposeService.ts'
|
|
7
|
+
|
|
8
|
+
const testTimeout = 30_000
|
|
9
|
+
const testFixturePath = path.join(import.meta.dirname, 'test-fixtures')
|
|
10
|
+
|
|
11
|
+
const DockerComposeTest = (args: Partial<DockerComposeArgs> = {}) =>
|
|
12
|
+
DockerComposeService.Default({
|
|
13
|
+
cwd: testFixturePath,
|
|
14
|
+
...args,
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
Vitest.describe('DockerComposeService', { timeout: testTimeout }, () => {
|
|
18
|
+
Vitest.describe('Basic Operations', () => {
|
|
19
|
+
const withBasicTest = (args: Partial<DockerComposeArgs> = {}) =>
|
|
20
|
+
Vitest.makeWithTestCtx({
|
|
21
|
+
timeout: testTimeout,
|
|
22
|
+
makeLayer: () => DockerComposeTest(args).pipe(Layer.provide(PlatformNode.NodeContext.layer)),
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
Vitest.scopedLive('can pull docker images', (test) =>
|
|
26
|
+
Effect.gen(function* () {
|
|
27
|
+
const dockerCompose = yield* DockerComposeService
|
|
28
|
+
|
|
29
|
+
// Test that pull operation works (should succeed for hello-world image)
|
|
30
|
+
yield* dockerCompose.pull
|
|
31
|
+
}).pipe(withBasicTest()(test)),
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
Vitest.scopedLive('can start and stop docker compose services', (test) =>
|
|
35
|
+
Effect.gen(function* () {
|
|
36
|
+
const dockerCompose = yield* DockerComposeService
|
|
37
|
+
|
|
38
|
+
// Start the service
|
|
39
|
+
yield* dockerCompose.start({ detached: true })
|
|
40
|
+
|
|
41
|
+
// Stop the service
|
|
42
|
+
yield* dockerCompose.stop
|
|
43
|
+
}).pipe(withBasicTest({ serviceName: 'hello-world' })(test)),
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
Vitest.scopedLive('can get logs from docker compose services', (test) =>
|
|
47
|
+
Effect.gen(function* () {
|
|
48
|
+
const dockerCompose = yield* DockerComposeService
|
|
49
|
+
|
|
50
|
+
// Start the service first
|
|
51
|
+
yield* dockerCompose.start({ detached: true })
|
|
52
|
+
|
|
53
|
+
// Get logs (should contain at least the "Hello from Docker!" message)
|
|
54
|
+
const firstLogLine = yield* dockerCompose.logs().pipe(Stream.runHead)
|
|
55
|
+
|
|
56
|
+
expect(firstLogLine._tag).toBe('Some')
|
|
57
|
+
|
|
58
|
+
// Stop the service
|
|
59
|
+
yield* dockerCompose.stop
|
|
60
|
+
}).pipe(withBasicTest({ serviceName: 'hello-world' })(test)),
|
|
61
|
+
)
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
Vitest.describe('Health Check Operations', () => {
|
|
65
|
+
const withHealthCheckTest = (args: Partial<DockerComposeArgs> = {}) =>
|
|
66
|
+
Vitest.makeWithTestCtx({
|
|
67
|
+
timeout: testTimeout,
|
|
68
|
+
makeLayer: () => DockerComposeTest(args).pipe(Layer.provide(PlatformNode.NodeContext.layer)),
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
Vitest.scopedLive('handles health check timeout gracefully', (test) =>
|
|
72
|
+
Effect.gen(function* () {
|
|
73
|
+
const dockerCompose = yield* DockerComposeService
|
|
74
|
+
|
|
75
|
+
// Test starting with a health check that will timeout (invalid URL)
|
|
76
|
+
const result = yield* dockerCompose
|
|
77
|
+
.start({
|
|
78
|
+
detached: true,
|
|
79
|
+
healthCheck: {
|
|
80
|
+
url: 'http://localhost:99999/nonexistent',
|
|
81
|
+
timeout: Duration.seconds(2),
|
|
82
|
+
},
|
|
83
|
+
})
|
|
84
|
+
.pipe(Effect.either)
|
|
85
|
+
|
|
86
|
+
// Should fail due to health check timeout
|
|
87
|
+
expect(result._tag).toBe('Left')
|
|
88
|
+
}).pipe(withHealthCheckTest({ serviceName: 'hello-world' })(test)),
|
|
89
|
+
)
|
|
90
|
+
})
|
|
91
|
+
})
|
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
import { omitUndefineds } from '@livestore/utils'
|
|
2
|
+
import {
|
|
3
|
+
Command,
|
|
4
|
+
type CommandExecutor,
|
|
5
|
+
Duration,
|
|
6
|
+
Effect,
|
|
7
|
+
Fiber,
|
|
8
|
+
type PlatformError,
|
|
9
|
+
Schedule,
|
|
10
|
+
Schema,
|
|
11
|
+
type Scope,
|
|
12
|
+
Stream,
|
|
13
|
+
} from '@livestore/utils/effect'
|
|
14
|
+
|
|
15
|
+
export class DockerComposeError extends Schema.TaggedError<DockerComposeError>()('DockerComposeError', {
|
|
16
|
+
cause: Schema.Defect,
|
|
17
|
+
note: Schema.String,
|
|
18
|
+
}) {}
|
|
19
|
+
|
|
20
|
+
export interface DockerComposeArgs {
|
|
21
|
+
readonly cwd: string
|
|
22
|
+
readonly serviceName?: string
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface StartOptions {
|
|
26
|
+
readonly detached?: boolean
|
|
27
|
+
readonly env?: Record<string, string>
|
|
28
|
+
readonly healthCheck?: {
|
|
29
|
+
readonly url: string
|
|
30
|
+
readonly timeout?: Duration.Duration
|
|
31
|
+
readonly interval?: Duration.Duration
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface LogsOptions {
|
|
36
|
+
readonly follow?: boolean
|
|
37
|
+
readonly tail?: number
|
|
38
|
+
readonly since?: string
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface DockerComposeOperations {
|
|
42
|
+
readonly pull: Effect.Effect<void, DockerComposeError | PlatformError.PlatformError>
|
|
43
|
+
readonly start: (
|
|
44
|
+
options?: StartOptions,
|
|
45
|
+
) => Effect.Effect<void, DockerComposeError | PlatformError.PlatformError, Scope.Scope>
|
|
46
|
+
readonly stop: Effect.Effect<void, DockerComposeError | PlatformError.PlatformError>
|
|
47
|
+
readonly down: (options?: {
|
|
48
|
+
readonly env?: Record<string, string>
|
|
49
|
+
readonly volumes?: boolean
|
|
50
|
+
readonly removeOrphans?: boolean
|
|
51
|
+
}) => Effect.Effect<void, DockerComposeError | PlatformError.PlatformError>
|
|
52
|
+
readonly logs: (
|
|
53
|
+
options?: LogsOptions,
|
|
54
|
+
) => Stream.Stream<string, DockerComposeError | PlatformError.PlatformError, Scope.Scope>
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export class DockerComposeService extends Effect.Service<DockerComposeService>()('DockerComposeService', {
|
|
58
|
+
scoped: (args: DockerComposeArgs) =>
|
|
59
|
+
Effect.gen(function* () {
|
|
60
|
+
const { cwd, serviceName } = args
|
|
61
|
+
|
|
62
|
+
const commandExecutorContext = yield* Effect.context<CommandExecutor.CommandExecutor>()
|
|
63
|
+
|
|
64
|
+
const pull = Effect.gen(function* () {
|
|
65
|
+
yield* Effect.log(`Pulling Docker Compose images in ${cwd}`)
|
|
66
|
+
|
|
67
|
+
// TODO (@IMax153) Refactor the effect command related code below as there is probably a much more elegant way to accomplish what we want here in a more effect idiomatic way.
|
|
68
|
+
const pullCommand = Command.make('docker', 'compose', 'pull').pipe(
|
|
69
|
+
Command.workingDirectory(cwd),
|
|
70
|
+
Command.stdout('pipe'),
|
|
71
|
+
Command.stderr('pipe'),
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
const process = yield* pullCommand.pipe(Command.start, Effect.provide(commandExecutorContext))
|
|
75
|
+
|
|
76
|
+
const stdoutFiber = yield* process.stdout.pipe(
|
|
77
|
+
Stream.decodeText('utf8'),
|
|
78
|
+
Stream.runFold('', (acc, chunk) => acc + chunk),
|
|
79
|
+
Effect.fork,
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
const stderrFiber = yield* process.stderr.pipe(
|
|
83
|
+
Stream.decodeText('utf8'),
|
|
84
|
+
Stream.runFold('', (acc, chunk) => acc + chunk),
|
|
85
|
+
Effect.fork,
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
const exitCode = yield* process.exitCode
|
|
89
|
+
const stdout = yield* Fiber.join(stdoutFiber)
|
|
90
|
+
const stderr = yield* Fiber.join(stderrFiber)
|
|
91
|
+
|
|
92
|
+
const exitCodeNumber = Number(exitCode)
|
|
93
|
+
|
|
94
|
+
if (exitCodeNumber !== 0) {
|
|
95
|
+
const stdoutLog = stdout.length > 0 ? stdout : '<empty stdout>'
|
|
96
|
+
const stderrLog = stderr.length > 0 ? stderr : '<empty stderr>'
|
|
97
|
+
const failureMessage = [
|
|
98
|
+
`Docker compose pull failed with exit code ${exitCodeNumber} in ${cwd}`,
|
|
99
|
+
`stdout:\n${stdoutLog}`,
|
|
100
|
+
`stderr:\n${stderrLog}`,
|
|
101
|
+
].join('\n')
|
|
102
|
+
|
|
103
|
+
yield* Effect.logError(failureMessage)
|
|
104
|
+
|
|
105
|
+
return yield* new DockerComposeError({
|
|
106
|
+
cause: new Error(`Docker compose pull failed with exit code ${exitCodeNumber}`),
|
|
107
|
+
note: failureMessage,
|
|
108
|
+
})
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
yield* Effect.log(`Successfully pulled Docker Compose images`)
|
|
112
|
+
}).pipe(
|
|
113
|
+
Effect.retry({
|
|
114
|
+
schedule: Schedule.exponentialBackoff10Sec,
|
|
115
|
+
while: Schema.is(DockerComposeError),
|
|
116
|
+
}),
|
|
117
|
+
Effect.withSpan('pullDockerComposeImages'),
|
|
118
|
+
Effect.scoped,
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
const start = (options: StartOptions = {}) =>
|
|
122
|
+
Effect.gen(function* () {
|
|
123
|
+
const { detached = true, healthCheck } = options
|
|
124
|
+
|
|
125
|
+
// Build start command
|
|
126
|
+
const baseArgs = ['docker', 'compose', 'up']
|
|
127
|
+
if (detached) baseArgs.push('-d')
|
|
128
|
+
if (serviceName) baseArgs.push(serviceName)
|
|
129
|
+
|
|
130
|
+
const command = yield* Command.make(baseArgs[0]!, ...baseArgs.slice(1)).pipe(
|
|
131
|
+
Command.workingDirectory(cwd),
|
|
132
|
+
Command.env(options.env ?? {}),
|
|
133
|
+
Command.stderr('inherit'),
|
|
134
|
+
Command.stdout('inherit'),
|
|
135
|
+
Command.start,
|
|
136
|
+
Effect.catchAll((cause) =>
|
|
137
|
+
Effect.fail(
|
|
138
|
+
new DockerComposeError({
|
|
139
|
+
cause,
|
|
140
|
+
note: `Failed to start Docker Compose services in ${cwd}`,
|
|
141
|
+
}),
|
|
142
|
+
),
|
|
143
|
+
),
|
|
144
|
+
Effect.provide(commandExecutorContext),
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
// Wait for command completion
|
|
148
|
+
yield* command.exitCode.pipe(
|
|
149
|
+
Effect.flatMap((exitCode) =>
|
|
150
|
+
exitCode === 0
|
|
151
|
+
? Effect.void
|
|
152
|
+
: Effect.fail(
|
|
153
|
+
new DockerComposeError({
|
|
154
|
+
cause: new Error(`Docker compose exited with code ${exitCode}`),
|
|
155
|
+
note: `Docker Compose failed to start with exit code ${exitCode}. Env: ${JSON.stringify(options.env)}`,
|
|
156
|
+
}),
|
|
157
|
+
),
|
|
158
|
+
),
|
|
159
|
+
Effect.provide(commandExecutorContext),
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
// Perform health check if requested
|
|
163
|
+
if (healthCheck) {
|
|
164
|
+
yield* performHealthCheck(healthCheck).pipe(Effect.provide(commandExecutorContext))
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
yield* Effect.log(`Docker Compose services started successfully in ${cwd}`)
|
|
168
|
+
}).pipe(Effect.withSpan('startDockerCompose'))
|
|
169
|
+
|
|
170
|
+
const stop = Effect.gen(function* () {
|
|
171
|
+
yield* Effect.log(`Stopping Docker Compose services in ${cwd}`)
|
|
172
|
+
|
|
173
|
+
const stopCommand = serviceName
|
|
174
|
+
? Command.make('docker', 'compose', 'stop', serviceName)
|
|
175
|
+
: Command.make('docker', 'compose', 'stop')
|
|
176
|
+
|
|
177
|
+
yield* stopCommand.pipe(
|
|
178
|
+
Command.workingDirectory(cwd),
|
|
179
|
+
Command.exitCode,
|
|
180
|
+
Effect.flatMap((exitCode: number) =>
|
|
181
|
+
exitCode === 0
|
|
182
|
+
? Effect.void
|
|
183
|
+
: Effect.fail(
|
|
184
|
+
new DockerComposeError({
|
|
185
|
+
cause: new Error(`Docker compose stop exited with code ${exitCode}`),
|
|
186
|
+
note: `Failed to stop Docker Compose services`,
|
|
187
|
+
}),
|
|
188
|
+
),
|
|
189
|
+
),
|
|
190
|
+
Effect.provide(commandExecutorContext),
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
yield* Effect.log(`Docker Compose services stopped successfully`)
|
|
194
|
+
}).pipe(Effect.withSpan('stopDockerCompose'))
|
|
195
|
+
|
|
196
|
+
const logs = (options: LogsOptions = {}) =>
|
|
197
|
+
Effect.gen(function* () {
|
|
198
|
+
const { follow = false, tail, since } = options
|
|
199
|
+
|
|
200
|
+
const baseArgs = ['docker', 'compose', 'logs']
|
|
201
|
+
if (follow) baseArgs.push('-f')
|
|
202
|
+
if (tail) baseArgs.push('--tail', tail.toString())
|
|
203
|
+
if (since) baseArgs.push('--since', since)
|
|
204
|
+
if (serviceName) baseArgs.push(serviceName)
|
|
205
|
+
|
|
206
|
+
const command = yield* Command.make(baseArgs[0]!, ...baseArgs.slice(1)).pipe(
|
|
207
|
+
Command.workingDirectory(cwd),
|
|
208
|
+
Command.start,
|
|
209
|
+
Effect.catchAll((cause) =>
|
|
210
|
+
Effect.fail(
|
|
211
|
+
new DockerComposeError({
|
|
212
|
+
cause,
|
|
213
|
+
note: `Failed to read Docker Compose logs in ${cwd}`,
|
|
214
|
+
}),
|
|
215
|
+
),
|
|
216
|
+
),
|
|
217
|
+
Effect.provide(commandExecutorContext),
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
return command.stdout.pipe(
|
|
221
|
+
Stream.decodeText('utf8'),
|
|
222
|
+
Stream.splitLines,
|
|
223
|
+
Stream.mapError(
|
|
224
|
+
(cause) =>
|
|
225
|
+
new DockerComposeError({
|
|
226
|
+
cause,
|
|
227
|
+
note: `Error reading Docker Compose logs in ${cwd}`,
|
|
228
|
+
}),
|
|
229
|
+
),
|
|
230
|
+
)
|
|
231
|
+
}).pipe(Stream.unwrapScoped)
|
|
232
|
+
|
|
233
|
+
const down = (options?: {
|
|
234
|
+
readonly env?: Record<string, string>
|
|
235
|
+
readonly volumes?: boolean
|
|
236
|
+
readonly removeOrphans?: boolean
|
|
237
|
+
}) =>
|
|
238
|
+
Effect.gen(function* () {
|
|
239
|
+
yield* Effect.log(`Tearing down Docker Compose services in ${cwd}`)
|
|
240
|
+
|
|
241
|
+
const baseArgs = ['docker', 'compose', 'down']
|
|
242
|
+
if (options?.volumes) baseArgs.push('-v')
|
|
243
|
+
if (options?.removeOrphans) baseArgs.push('--remove-orphans')
|
|
244
|
+
if (serviceName) baseArgs.push(serviceName)
|
|
245
|
+
|
|
246
|
+
yield* Command.make(baseArgs[0]!, ...baseArgs.slice(1)).pipe(
|
|
247
|
+
Command.workingDirectory(cwd),
|
|
248
|
+
Command.env(options?.env ?? {}),
|
|
249
|
+
Command.exitCode,
|
|
250
|
+
Effect.flatMap((exitCode: number) =>
|
|
251
|
+
exitCode === 0
|
|
252
|
+
? Effect.void
|
|
253
|
+
: Effect.fail(
|
|
254
|
+
new DockerComposeError({
|
|
255
|
+
cause: new Error(`Docker compose down exited with code ${exitCode}`),
|
|
256
|
+
note: `Failed to tear down Docker Compose services`,
|
|
257
|
+
}),
|
|
258
|
+
),
|
|
259
|
+
),
|
|
260
|
+
Effect.provide(commandExecutorContext),
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
yield* Effect.log(`Docker Compose services torn down successfully`)
|
|
264
|
+
}).pipe(Effect.withSpan('downDockerCompose'))
|
|
265
|
+
|
|
266
|
+
return { pull, start, stop, down, logs }
|
|
267
|
+
}),
|
|
268
|
+
}) {}
|
|
269
|
+
|
|
270
|
+
const performHealthCheck = ({
|
|
271
|
+
url,
|
|
272
|
+
timeout = Duration.minutes(2),
|
|
273
|
+
interval = Duration.seconds(2),
|
|
274
|
+
}: {
|
|
275
|
+
url: string
|
|
276
|
+
timeout?: Duration.Duration
|
|
277
|
+
interval?: Duration.Duration
|
|
278
|
+
}): Effect.Effect<void, DockerComposeError, CommandExecutor.CommandExecutor | Scope.Scope> =>
|
|
279
|
+
Effect.gen(function* () {
|
|
280
|
+
yield* Effect.log(`Performing health check on ${url}`)
|
|
281
|
+
|
|
282
|
+
const checkHealth = Command.make('curl', '-f', '-s', url).pipe(
|
|
283
|
+
Command.exitCode,
|
|
284
|
+
Effect.map((code: number) => code === 0),
|
|
285
|
+
Effect.catchAll(() => Effect.succeed(false)),
|
|
286
|
+
)
|
|
287
|
+
|
|
288
|
+
const healthCheck = checkHealth.pipe(
|
|
289
|
+
Effect.repeat({
|
|
290
|
+
while: (healthy: boolean) => !healthy,
|
|
291
|
+
schedule: Schedule.fixed(interval),
|
|
292
|
+
}),
|
|
293
|
+
Effect.timeout(timeout),
|
|
294
|
+
Effect.catchAll(() =>
|
|
295
|
+
Effect.fail(
|
|
296
|
+
new DockerComposeError({
|
|
297
|
+
cause: new Error('Health check timeout'),
|
|
298
|
+
note: `Health check failed for ${url} after ${Duration.toMillis(timeout)}ms`,
|
|
299
|
+
}),
|
|
300
|
+
),
|
|
301
|
+
),
|
|
302
|
+
)
|
|
303
|
+
|
|
304
|
+
yield* healthCheck
|
|
305
|
+
yield* Effect.log(`Health check passed for ${url}`)
|
|
306
|
+
})
|
|
307
|
+
|
|
308
|
+
// Convenience function for scoped Docker Compose operations with automatic cleanup
|
|
309
|
+
export const startDockerComposeServicesScoped = (
|
|
310
|
+
args: DockerComposeArgs & {
|
|
311
|
+
healthCheck?: StartOptions['healthCheck']
|
|
312
|
+
},
|
|
313
|
+
): Effect.Effect<
|
|
314
|
+
void,
|
|
315
|
+
DockerComposeError | PlatformError.PlatformError,
|
|
316
|
+
DockerComposeService | CommandExecutor.CommandExecutor | Scope.Scope
|
|
317
|
+
> =>
|
|
318
|
+
Effect.gen(function* () {
|
|
319
|
+
const dockerCompose = yield* DockerComposeService
|
|
320
|
+
|
|
321
|
+
// Start the services
|
|
322
|
+
yield* dockerCompose.start({
|
|
323
|
+
...omitUndefineds({ healthCheck: args.healthCheck ? args.healthCheck : undefined }),
|
|
324
|
+
})
|
|
325
|
+
|
|
326
|
+
// Add cleanup finalizer to the current scope
|
|
327
|
+
yield* Effect.addFinalizer(() => dockerCompose.stop.pipe(Effect.orDie))
|
|
328
|
+
})
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
|
|
4
|
+
import { isNotUndefined } from '@livestore/utils'
|
|
5
|
+
import { Effect, identity } from '@livestore/utils/effect'
|
|
6
|
+
|
|
7
|
+
export type TCmdLoggingOptions = {
|
|
8
|
+
readonly logDir?: string
|
|
9
|
+
readonly logFileName?: string
|
|
10
|
+
readonly logRetention?: number
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Prepares logging directories, archives previous canonical log and prunes archives.
|
|
15
|
+
* Returns the canonical current log path if logging is enabled, otherwise undefined.
|
|
16
|
+
*/
|
|
17
|
+
export const prepareCmdLogging: (options: TCmdLoggingOptions) => Effect.Effect<string | undefined, never, never> =
|
|
18
|
+
Effect.fn('cmd.logging.prepare')(function* ({
|
|
19
|
+
logDir,
|
|
20
|
+
logFileName = 'dev.log',
|
|
21
|
+
logRetention = 50,
|
|
22
|
+
}: TCmdLoggingOptions) {
|
|
23
|
+
if (!logDir || logDir === '') return undefined as string | undefined
|
|
24
|
+
|
|
25
|
+
const logsDir = logDir
|
|
26
|
+
const archiveDir = path.join(logsDir, 'archive')
|
|
27
|
+
const currentLogPath = path.join(logsDir, logFileName)
|
|
28
|
+
|
|
29
|
+
// Ensure directories exist
|
|
30
|
+
yield* Effect.sync(() => fs.mkdirSync(archiveDir, { recursive: true }))
|
|
31
|
+
|
|
32
|
+
// Archive previous log if present
|
|
33
|
+
if (fs.existsSync(currentLogPath)) {
|
|
34
|
+
const safeIso = new Date().toISOString().replaceAll(':', '-')
|
|
35
|
+
const archivedBase = `${path.parse(logFileName).name}-${safeIso}.log`
|
|
36
|
+
const archivedLog = path.join(archiveDir, archivedBase)
|
|
37
|
+
yield* Effect.try({ try: () => fs.renameSync(currentLogPath, archivedLog), catch: identity }).pipe(
|
|
38
|
+
Effect.catchAll(() =>
|
|
39
|
+
Effect.try({
|
|
40
|
+
try: () => {
|
|
41
|
+
fs.copyFileSync(currentLogPath, archivedLog)
|
|
42
|
+
fs.truncateSync(currentLogPath, 0)
|
|
43
|
+
},
|
|
44
|
+
catch: identity,
|
|
45
|
+
}),
|
|
46
|
+
),
|
|
47
|
+
Effect.ignore,
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
// Prune archives to retain only the newest N
|
|
51
|
+
yield* Effect.try({ try: () => fs.readdirSync(archiveDir), catch: identity }).pipe(
|
|
52
|
+
Effect.map((names) => names.filter((n) => n.endsWith('.log'))),
|
|
53
|
+
Effect.map((names) =>
|
|
54
|
+
names
|
|
55
|
+
.map((name) => ({ name, mtimeMs: fs.statSync(path.join(archiveDir, name)).mtimeMs }))
|
|
56
|
+
.sort((a, b) => b.mtimeMs - a.mtimeMs),
|
|
57
|
+
),
|
|
58
|
+
Effect.flatMap((entries) =>
|
|
59
|
+
Effect.forEach(entries.slice(logRetention), (e) =>
|
|
60
|
+
Effect.try({ try: () => fs.unlinkSync(path.join(archiveDir, e.name)), catch: identity }).pipe(
|
|
61
|
+
Effect.ignore,
|
|
62
|
+
),
|
|
63
|
+
),
|
|
64
|
+
),
|
|
65
|
+
Effect.ignore,
|
|
66
|
+
)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
return currentLogPath
|
|
70
|
+
})
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Given a command input, applies logging by piping output through `tee` to the
|
|
74
|
+
* canonical log file. Returns the transformed input and whether a shell is required.
|
|
75
|
+
*/
|
|
76
|
+
export const applyLoggingToCommand: (
|
|
77
|
+
commandInput: string | (string | undefined)[],
|
|
78
|
+
options: TCmdLoggingOptions,
|
|
79
|
+
) => Effect.Effect<{ input: string | string[]; subshell: boolean; logPath?: string }, never, never> = Effect.fn(
|
|
80
|
+
'cmd.logging.apply',
|
|
81
|
+
)(function* (commandInput, options) {
|
|
82
|
+
const asArray = Array.isArray(commandInput)
|
|
83
|
+
const parts = asArray ? (commandInput as (string | undefined)[]).filter(isNotUndefined) : undefined
|
|
84
|
+
|
|
85
|
+
const logPath = yield* prepareCmdLogging(options)
|
|
86
|
+
|
|
87
|
+
return {
|
|
88
|
+
input: asArray ? ((parts as string[]) ?? []) : (commandInput as string),
|
|
89
|
+
subshell: false,
|
|
90
|
+
...(logPath ? { logPath } : {}),
|
|
91
|
+
}
|
|
92
|
+
})
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
|
|
4
|
+
import { CommandExecutor, Duration, Effect } from '@livestore/utils/effect'
|
|
5
|
+
import { PlatformNode } from '@livestore/utils/node'
|
|
6
|
+
import { Vitest } from '@livestore/utils-dev/node-vitest'
|
|
7
|
+
import { expect } from 'vitest'
|
|
8
|
+
import { cmd } from './cmd.ts'
|
|
9
|
+
|
|
10
|
+
const withNode = Vitest.makeWithTestCtx({
|
|
11
|
+
makeLayer: () => PlatformNode.NodeContext.layer,
|
|
12
|
+
timeout: 20_000,
|
|
13
|
+
})
|
|
14
|
+
|
|
15
|
+
Vitest.describe('cmd helper', () => {
|
|
16
|
+
const ansiRegex = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, 'g')
|
|
17
|
+
|
|
18
|
+
Vitest.scopedLive('runs tokenized string without shell', (test) =>
|
|
19
|
+
Effect.gen(function* () {
|
|
20
|
+
const exit = yield* cmd('printf ok')
|
|
21
|
+
expect(exit).toBe(CommandExecutor.ExitCode(0))
|
|
22
|
+
}).pipe(withNode(test)),
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
Vitest.scopedLive('runs array input', (test) =>
|
|
26
|
+
Effect.gen(function* () {
|
|
27
|
+
const exit = yield* cmd(['printf', 'ok'])
|
|
28
|
+
expect(exit).toBe(CommandExecutor.ExitCode(0))
|
|
29
|
+
}).pipe(withNode(test)),
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
Vitest.scopedLive('supports logging with archive + retention', (test) =>
|
|
33
|
+
Effect.gen(function* () {
|
|
34
|
+
const workspace = process.env.WORKSPACE_ROOT!
|
|
35
|
+
const logsDir = path.join(workspace, 'tmp', 'cmd-tests', String(Date.now()))
|
|
36
|
+
|
|
37
|
+
// first run
|
|
38
|
+
const exit1 = yield* cmd('printf first', { logDir: logsDir })
|
|
39
|
+
expect(exit1).toBe(CommandExecutor.ExitCode(0))
|
|
40
|
+
const current = path.join(logsDir, 'dev.log')
|
|
41
|
+
expect(fs.existsSync(current)).toBe(true)
|
|
42
|
+
const firstLog = fs.readFileSync(current, 'utf8')
|
|
43
|
+
const firstStdoutLines = firstLog.split('\n').filter((line) => line.includes('[stdout]'))
|
|
44
|
+
expect(firstStdoutLines.length).toBeGreaterThan(0)
|
|
45
|
+
for (const line of firstStdoutLines) {
|
|
46
|
+
expect(line).toContain('[stdout] first')
|
|
47
|
+
expect(line).toContain('INFO')
|
|
48
|
+
expect(line).toContain('printf first')
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// second run — archives previous
|
|
52
|
+
const exit2 = yield* cmd('printf second', { logDir: logsDir })
|
|
53
|
+
expect(exit2).toBe(CommandExecutor.ExitCode(0))
|
|
54
|
+
const archiveDir = path.join(logsDir, 'archive')
|
|
55
|
+
const archives = fs.readdirSync(archiveDir).filter((f) => f.endsWith('.log'))
|
|
56
|
+
expect(archives.length).toBe(1)
|
|
57
|
+
const archivedPath = path.join(archiveDir, archives[0]!)
|
|
58
|
+
const archivedLog = fs.readFileSync(archivedPath, 'utf8')
|
|
59
|
+
const archivedStdoutLines = archivedLog.split('\n').filter((line) => line.includes('[stdout]'))
|
|
60
|
+
expect(archivedStdoutLines.length).toBeGreaterThan(0)
|
|
61
|
+
for (const line of archivedStdoutLines) {
|
|
62
|
+
expect(line).toContain('[stdout] first')
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const secondLog = fs.readFileSync(current, 'utf8')
|
|
66
|
+
const secondStdoutLines = secondLog.split('\n').filter((line) => line.includes('[stdout]'))
|
|
67
|
+
expect(secondStdoutLines.length).toBeGreaterThan(0)
|
|
68
|
+
for (const line of secondStdoutLines) {
|
|
69
|
+
expect(line).toContain('[stdout] second')
|
|
70
|
+
expect(line).toContain('INFO')
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// generate many archives to exercise retention (keep 50)
|
|
74
|
+
for (let i = 0; i < 60; i++) {
|
|
75
|
+
// Use small unique payloads
|
|
76
|
+
yield* cmd(['printf', String(i)], { logDir: logsDir })
|
|
77
|
+
}
|
|
78
|
+
const archivesAfter = fs.readdirSync(archiveDir).filter((f) => f.endsWith('.log'))
|
|
79
|
+
expect(archivesAfter.length).toBeLessThanOrEqual(50)
|
|
80
|
+
}).pipe(withNode(test)),
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
Vitest.scopedLive('streams stdout and stderr with logger formatting', (test) =>
|
|
84
|
+
Effect.gen(function* () {
|
|
85
|
+
const workspace = process.env.WORKSPACE_ROOT!
|
|
86
|
+
const logsDir = path.join(workspace, 'tmp', 'cmd-tests', `format-${Date.now()}`)
|
|
87
|
+
|
|
88
|
+
const exit = yield* cmd(['node', '-e', "console.log('out'); console.error('err')"], {
|
|
89
|
+
logDir: logsDir,
|
|
90
|
+
})
|
|
91
|
+
expect(exit).toBe(CommandExecutor.ExitCode(0))
|
|
92
|
+
|
|
93
|
+
const current = path.join(logsDir, 'dev.log')
|
|
94
|
+
const logContent = fs.readFileSync(current, 'utf8')
|
|
95
|
+
expect(logContent).toMatch(/\[stdout] out/)
|
|
96
|
+
expect(logContent).toMatch(/\[stderr] err/)
|
|
97
|
+
|
|
98
|
+
const relevantLines = logContent
|
|
99
|
+
.split('\n')
|
|
100
|
+
.map((line) => line.trim())
|
|
101
|
+
.filter((line) => line.includes('[stdout]') || line.includes('[stderr]'))
|
|
102
|
+
|
|
103
|
+
expect(relevantLines.length).toBeGreaterThanOrEqual(2)
|
|
104
|
+
|
|
105
|
+
for (const line of relevantLines) {
|
|
106
|
+
const stripped = line.replace(ansiRegex, '')
|
|
107
|
+
expect(stripped.startsWith('[')).toBe(true)
|
|
108
|
+
expect(stripped).toMatch(/(INFO|WARN)/)
|
|
109
|
+
expect(stripped).toMatch(/\[(stdout|stderr)]/)
|
|
110
|
+
}
|
|
111
|
+
}).pipe(withNode(test)),
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
Vitest.scopedLive('cleans up logged child process when interrupted', (test) =>
|
|
115
|
+
Effect.gen(function* () {
|
|
116
|
+
const workspace = process.env.WORKSPACE_ROOT!
|
|
117
|
+
const logsDir = path.join(workspace, 'tmp', 'cmd-tests', `timeout-${Date.now()}`)
|
|
118
|
+
|
|
119
|
+
const result = yield* cmd(['node', '-e', 'setTimeout(() => {}, 5000)'], {
|
|
120
|
+
logDir: logsDir,
|
|
121
|
+
stdout: 'pipe',
|
|
122
|
+
stderr: 'pipe',
|
|
123
|
+
}).pipe(Effect.timeoutOption(Duration.millis(200)))
|
|
124
|
+
|
|
125
|
+
expect(result._tag).toBe('None')
|
|
126
|
+
expect(fs.existsSync(path.join(logsDir, 'dev.log'))).toBe(true)
|
|
127
|
+
}).pipe(withNode(test)),
|
|
128
|
+
)
|
|
129
|
+
})
|