import path from "node:path"; import { AbstractStartedContainer, GenericContainer, type StartedTestContainer, Wait } from "testcontainers"; const REDIS_PORT = 6379; export class RedisContainer extends GenericContainer { private readonly importFilePath = "/tmp/import.redis"; private password? = ""; private persistenceVolume? = ""; private initialImportScriptFile? = ""; constructor(image: string) { super(image); this.withExposedPorts(REDIS_PORT) .withStartupTimeout(120_000) .withWaitStrategy(Wait.forLogMessage("Ready to accept connections")); } public withPassword(password: string): this { this.password = password; return this; } public withPersistence(sourcePath: string): this { this.persistenceVolume = sourcePath; return this; } /* Expect data to be in redis import script format, see https://developer.redis.com/explore/import/*/ public withInitialData(importScriptFile: string): this { this.initialImportScriptFile = importScriptFile; return this; } protected override async containerStarted(container: StartedTestContainer): Promise { if (this.initialImportScriptFile) { await this.importInitialData(container); } } public override async start(): Promise { const redisArgs = [ ...(this.password ? [`--requirepass ${this.password}`] : []), ...(this.persistenceVolume ? ["--save 1 1 ", "--appendonly yes"] : []), ]; if (this.imageName.image.includes("redis-stack")) { const existingRedisArgs = this.environment.REDIS_ARGS ?? ""; // merge with filter to remove empty items const mergedRedisArgs = [existingRedisArgs, ...redisArgs].filter(Boolean).join(" "); // remove existing REDIS_ARGS to avoid duplicates this.createOpts.Env = (this.createOpts.Env || []).filter((e) => !e.startsWith("REDIS_ARGS=")); this.withEnvironment({ REDIS_ARGS: mergedRedisArgs, }).withEntrypoint(["/entrypoint.sh"]); } else { const existingCmd = this.createOpts.Cmd || []; const baseCmd = existingCmd.length ? existingCmd : ["redis-server"]; this.withCommand([...baseCmd, ...redisArgs]); } if (this.persistenceVolume) { this.withBindMounts([{ mode: "rw", source: this.persistenceVolume, target: "/data" }]); } if (this.initialImportScriptFile) { this.withCopyFilesToContainer([ { mode: 0o644, source: this.initialImportScriptFile, target: this.importFilePath, }, { mode: 0o755, source: path.join(__dirname, "import.sh"), target: "/tmp/import.sh", }, ]); } const startedRedisContainer = new StartedRedisContainer(await super.start(), this.password); return startedRedisContainer; } private async importInitialData(container: StartedTestContainer) { const re = await container.exec(`/tmp/import.sh ${this.password}`); if (re.exitCode !== 0 || re.output.includes("ERR")) { throw Error(`Could not import initial data from ${this.initialImportScriptFile}: ${re.output}`); } } } export class StartedRedisContainer extends AbstractStartedContainer { constructor( startedTestContainer: StartedTestContainer, private readonly password?: string ) { super(startedTestContainer); } public getPort(): number { return this.getMappedPort(REDIS_PORT); } public getPassword(): string { return this.password ? this.password.toString() : ""; } public getConnectionUrl(): string { const url = new URL("", "redis://"); url.hostname = this.getHost(); url.port = this.getPort().toString(); url.password = this.getPassword(); return url.toString(); } public async executeCliCmd(cmd: string, additionalFlags: string[] = []): Promise { const result = await this.startedTestContainer.exec([ "redis-cli", ...(this.password !== "" ? [`-a ${this.password}`] : []), `${cmd}`, ...additionalFlags, ]); if (result.exitCode !== 0) { throw new Error(`executeQuery failed with exit code ${result.exitCode} for query: ${cmd}. ${result.output}`); } return result.output; } }