Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion docs/features/containers.md
Original file line number Diff line number Diff line change
Expand Up @@ -716,6 +716,8 @@ The following options can be provided to modify the command execution:

3. **`env`:** A map of environment variables to set inside the container.

4. **`signal`:** An `AbortSignal` to stop waiting for the command. `exec` rejects when the signal aborts. Docker cannot kill a command it has started, so the process keeps running inside the container until it exits or the container stops.

```js
const container = await new GenericContainer("alpine")
.withCommand(["sleep", "infinity"])
Expand All @@ -727,7 +729,8 @@ const { output, stdout, stderr, exitCode } = await container.exec(["echo", "hell
env: {
"VAR1": "enabled",
"VAR2": "/app/debug.log",
}
},
signal: AbortSignal.timeout(5_000),
});
```

Expand Down
2 changes: 2 additions & 0 deletions docs/features/wait-strategies.md
Original file line number Diff line number Diff line change
Expand Up @@ -267,3 +267,5 @@ const container = await new GenericContainer("alpine")
.withWaitStrategy(new ReadyAfterDelayWaitStrategy())
.start();
```

`checkStartupState` is passed an `AbortSignal` as a third argument. It aborts when the startup timeout is reached, so pass it to Dockerode calls as `abortSignal` to cancel them.
85 changes: 39 additions & 46 deletions packages/modules/couchbase/src/couchbase-container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import {
GenericContainer,
getContainerRuntimeClient,
type InspectResult,
IntervalRetry,
log,
poll,
type StartedTestContainer,
Wait,
type WaitStrategy,
Expand Down Expand Up @@ -402,13 +402,13 @@ export class CouchbaseContainer extends GenericContainer {
await this.waitUntilBucketIsHealthy(client, inspectResult, startedTestContainer, bucket, remainingStartupMs());

if (this.enabledServices.has(CouchbaseService.QUERY)) {
await this.waitUntilKeyspaceIsPresent(client, startedTestContainer, bucket, remainingStartupMs());
await this.waitUntilKeyspaceIsPresent(startedTestContainer, bucket, remainingStartupMs());
}

if (bucket.hasPrimaryIndex()) {
if (this.enabledServices.has(CouchbaseService.QUERY)) {
await this.createPrimaryIndex(startedTestContainer, bucket);
await this.waitUntilPrimaryIndexIsOnline(client, startedTestContainer, bucket, remainingStartupMs());
await this.waitUntilPrimaryIndexIsOnline(startedTestContainer, bucket, remainingStartupMs());
} else {
log.info(
`Primary index creation for bucket ${bucket.getName()} ignored, since QUERY service is not present.`
Expand Down Expand Up @@ -503,12 +503,11 @@ export class CouchbaseContainer extends GenericContainer {
}

private async waitUntilKeyspaceIsPresent(
client: ContainerRuntimeClient,
startedTestContainer: StartedTestContainer,
bucket: BucketDefinition,
timeoutMs: number
) {
await new IntervalRetry<Response | undefined, Error>(1000).retryUntil(
await poll(
async () => {
try {
const body = new URLSearchParams();
Expand All @@ -533,20 +532,18 @@ export class CouchbaseContainer extends GenericContainer {
return undefined;
}
},
async (response) => {
if (response === undefined) {
return false;
}
const jsonResponse = (await response.json()) as { results: Array<{ present: boolean }> };
return jsonResponse.results[0].present;
},
() => {
const message = `URL /query/service not accessible after ${timeoutMs}ms`;
log.error(message, { containerId: client.container.getById(startedTestContainer.getId()).id });

throw new Error(message);
},
timeoutMs
{
until: async (response) => {
if (response === undefined) {
return false;
}
const jsonResponse = (await response.json()) as { results: Array<{ present: boolean }> };
return jsonResponse.results[0].present;
},
intervalMs: 1000,
timeoutMs,
timeoutMessage: `URL /query/service not accessible after ${timeoutMs}ms`,
}
);
}

Expand All @@ -567,12 +564,11 @@ export class CouchbaseContainer extends GenericContainer {
}

private async waitUntilPrimaryIndexIsOnline(
client: ContainerRuntimeClient,
startedTestContainer: StartedTestContainer,
bucket: BucketDefinition,
timeoutMs: number
) {
await new IntervalRetry<Response | undefined, Error>(1000).retryUntil(
await poll(
async () => {
try {
const body = new URLSearchParams();
Expand All @@ -597,20 +593,18 @@ export class CouchbaseContainer extends GenericContainer {
return undefined;
}
},
async (response) => {
if (response === undefined) {
return false;
}
const jsonResponse = (await response.json()) as { results: Array<{ online: boolean }> };
return jsonResponse.results[0].online;
},
() => {
const message = `URL /query/service not accessible after ${timeoutMs}ms`;
log.error(message, { containerId: client.container.getById(startedTestContainer.getId()).id });

throw new Error(message);
},
timeoutMs
{
until: async (response) => {
if (response === undefined) {
return false;
}
const jsonResponse = (await response.json()) as { results: Array<{ online: boolean }> };
return jsonResponse.results[0].online;
},
intervalMs: 1000,
timeoutMs,
timeoutMessage: `URL /query/service not accessible after ${timeoutMs}ms`,
}
);
}

Expand Down Expand Up @@ -658,22 +652,21 @@ export class CouchbaseContainer extends GenericContainer {
}

private async waitUntilKvAcceptsCredentials(container: StartedTestContainer, timeoutMs: number) {
await new IntervalRetry<number, Error>(100).retryUntil(
async () => {
await poll(
async ({ signal }) => {
const { exitCode } = await container.exec(
["/opt/couchbase/bin/mcstat", "--host", `127.0.0.1:${PORTS.KV_PORT}`, "--user", this.username, "connections"],
{ env: { CB_PASSWORD: this.password } }
{ env: { CB_PASSWORD: this.password }, signal }
);
return exitCode;
},
(exitCode) => exitCode === 0,
() => {
const message = `KV service did not accept credentials after ${timeoutMs}ms`;
log.error(message, { containerId: container.getId() });

throw new Error(message);
},
timeoutMs
{
until: (exitCode) => exitCode === 0,
intervalMs: 100,
timeoutMs,
timeoutMessage: `KV service did not accept credentials after ${timeoutMs}ms`,
retryOnError: false,
}
);
}

Expand Down
28 changes: 15 additions & 13 deletions packages/modules/mongodb/src/mongodb-atlas-local-container.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import mongoose from "mongoose";
import { IntervalRetry } from "testcontainers";
import { poll } from "testcontainers";
import { getImage } from "../../../testcontainers/src/utils/test-helper";
import { MongoDBAtlasLocalContainer } from "./mongodb-atlas-local-container";

Expand Down Expand Up @@ -114,19 +114,22 @@ describe("MongoDBAtlasLocalContainer", { timeout: 240_000 }, () => {
definition: ATLAS_SEARCH_INDEX,
});

await new IntervalRetry<string | undefined, Error>(10).retryUntil(
await poll(
async () => {
const searchIndexes = await collection.listSearchIndexes("AtlasSearchIndex").toArray();
return (searchIndexes[0] as { status?: string } | undefined)?.status;
},
(status) => status?.toUpperCase() === "READY",
() => new Error("Atlas Search index did not become ready in time"),
5_000
{
until: (status) => status?.toUpperCase() === "READY",
intervalMs: 10,
timeoutMs: 5_000,
timeoutMessage: "Atlas Search index did not become ready in time",
}
);

await collection.insertOne({ test: "tests", test2: 123, test3: true });

const found = await new IntervalRetry<Record<string, unknown> | null, Error>(10).retryUntil(
const found = await poll(
async () =>
collection
.aggregate([
Expand All @@ -142,15 +145,14 @@ describe("MongoDBAtlasLocalContainer", { timeout: 240_000 }, () => {
},
])
.next(),
(result) => result !== null,
() => new Error("Atlas Search did not return a result in time"),
5_000
{
until: (result) => result !== null,
intervalMs: 10,
timeoutMs: 5_000,
timeoutMessage: "Atlas Search did not return a result in time",
}
);

if (found instanceof Error) {
throw found;
}

expect(found).toMatchObject({ test: "tests", test2: 123, test3: true });
} finally {
await db.close();
Expand Down
11 changes: 0 additions & 11 deletions packages/testcontainers/src/common/clock.ts

This file was deleted.

2 changes: 1 addition & 1 deletion packages/testcontainers/src/common/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export { withFileLock } from "./file-lock";
export { hash } from "./hash";
export { buildLog, composeLog, containerLog, execLog, Logger, log, pullLog } from "./logger";
export { IntervalRetry, Retry } from "./retry";
export { IntervalRetry, PollOptions, poll, Retry } from "./retry";
export * from "./time";
export * from "./type-guards";
export { RandomUuid, randomUuid, Uuid } from "./uuid";
Loading
Loading