Skip to content
Merged
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
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,9 @@ jobs:
- name: Install Redis for ledger integration tests
run: sudo apt-get update && sudo apt-get install -y redis-server

- name: Verify isolated Redis AOF reopen after process exit
run: bun test src/test/redis.test.ts

- name: Verify fleet admission with isolated Redis
run: |
redis_socket="$RUNNER_TEMP/byom-admission.sock"
Expand Down
41 changes: 41 additions & 0 deletions service/src/test/redis.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { expect, test } from 'bun:test';
import { mkdtemp, rm, stat } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { createTestRedisAof } from './redis';

test('reopens the same AOF after SIGKILL and a graceful stop', async () => {
const parent = await mkdtemp(path.join(tmpdir(), 'codeapi-redis-test-'));
try {
const fixture = await createTestRedisAof(parent);
try {
const first = await fixture.reopen();
const { dev, ino } = await stat(fixture.dir);
expect(await first.config('GET', 'appendfsync')).toEqual(['appendfsync', 'always']);
expect(await first.config('GET', 'save')).toEqual(['save', '']);
expect(await first.config('GET', 'port')).toEqual(['port', '0']);
await expect(fixture.reopen()).rejects.toThrow('must be stopped');
// The write reply follows fsync; stop resolves only after the child exits.
expect(await first.set('checkpoint', 'before-crash')).toBe('OK');
await fixture.stop('SIGKILL');
await expect(first.ping()).rejects.toThrow();
expect(await stat(fixture.dir)).toMatchObject({ dev, ino });

const second = await fixture.reopen();
expect(second).not.toBe(first);
expect(await second.get('checkpoint')).toBe('before-crash');
expect(await second.set('checkpoint', 'after-crash')).toBe('OK');
await fixture.stop();
expect(await stat(fixture.dir)).toMatchObject({ dev, ino });
expect(await (await fixture.reopen()).get('checkpoint')).toBe('after-crash');
} finally {
await fixture.dispose();
}
expect(await stat(parent)).toBeDefined();
await expect(stat(fixture.dir)).rejects.toMatchObject({ code: 'ENOENT' });
await expect(stat(path.dirname(fixture.socket))).rejects.toMatchObject({ code: 'ENOENT' });
await expect(fixture.reopen()).rejects.toThrow('not disposed');
} finally {
await rm(parent, { recursive: true, force: true });
}
});
139 changes: 114 additions & 25 deletions service/src/test/redis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,48 +4,137 @@ import { tmpdir } from 'node:os';
import path from 'node:path';
import IORedis from 'ioredis';

/**
* Real Lua semantics, isolated Unix socket, no durable data. No TCP listener
* unless `tcpPort` asks for a loopback one, for a process that takes only
* `REDIS_HOST`/`REDIS_PORT`.
*/
export async function startTestRedis(
opts: { tcpPort?: number } = {},
): Promise<IORedis & { closeTestServer(): Promise<void> }> {
const dir = await mkdtemp(path.join(tmpdir(), 'codeapi-redis-'));
const socket = path.join(dir, 'redis.sock');
const process = spawn('redis-server', [
'--port', String(opts.tcpPort ?? 0), '--bind', '127.0.0.1', '--unixsocket', socket, '--unixsocketperm', '700',
'--save', '', '--appendonly', 'no', '--dir', dir,
type StopSignal = 'SIGTERM' | 'SIGKILL';

async function launch(dir: string, socket: string, tcpPort: number, aof: boolean) {
const server = spawn('redis-server', [
'--port', String(tcpPort), '--bind', '127.0.0.1', '--unixsocket', socket, '--unixsocketperm', '700',
'--save', '', '--appendonly', aof ? 'yes' : 'no', '--appendfsync', 'always', '--dir', dir,
], { stdio: 'ignore' });
let failure: Error | undefined;
process.on('error', error => { failure = error; });
const exited = new Promise<void>(resolve => {
process.once('exit', () => resolve());
process.once('error', () => resolve());
const exited = new Promise<{ signal: NodeJS.Signals | null }>(resolve => {
server.once('exit', (code, signal) => {
failure = new Error(`Test Redis exited (${signal ?? code})`);
resolve({ signal });
});
server.once('error', error => {
failure = error;
resolve({ signal: null });
});
});
const client = new IORedis(socket, {
lazyConnect: true, retryStrategy: () => null, maxRetriesPerRequest: 0,
});
const client = new IORedis(socket, { lazyConnect: true, retryStrategy: () => null, maxRetriesPerRequest: 0 });
client.on('error', () => {});
const closeTestServer = async (): Promise<void> => {
const stop = async (signal: StopSignal) => {
client.disconnect();
process.kill('SIGTERM');
await exited;
await rm(dir, { recursive: true, force: true });
server.kill(signal);
const timer = setTimeout(() => server.kill('SIGKILL'), 2_000);
try {
return (await exited).signal;
} finally {
clearTimeout(timer);
}
};
try {
const connect = async () => {
for (let attempt = 0; attempt < 100; attempt++) {
if (failure) throw failure;
try {
await client.connect();
await client.ping();
return Object.assign(client, { closeTestServer });
return;
} catch {
await new Promise(resolve => setTimeout(resolve, 20));
}
}
throw new Error('Test Redis did not start; install redis-server');
};
let timer: ReturnType<typeof setTimeout> | undefined;
try {
await Promise.race([
connect(),
new Promise<never>((_, reject) => {
timer = setTimeout(() => reject(new Error('Test Redis readiness timed out')), 3_000);
}),
]);
return { client, stop };
} catch (error) {
await stop('SIGKILL');
throw error;
} finally {
clearTimeout(timer);
}
}

/**
* Real Lua semantics, isolated Unix socket, no durable data. No TCP listener
* unless `tcpPort` asks for a loopback one, for a process that takes only
* `REDIS_HOST`/`REDIS_PORT`.
*/
export async function startTestRedis(
opts: { tcpPort?: number } = {},
): Promise<IORedis & { closeTestServer(): Promise<void> }> {
const dir = await mkdtemp(path.join(tmpdir(), 'codeapi-redis-'));
try {
const { client, stop } = await launch(dir, path.join(dir, 'redis.sock'), opts.tcpPort ?? 0, false);
return Object.assign(client, { closeTestServer: async () => {
await stop('SIGTERM');
await rm(dir, { recursive: true, force: true });
} });
} catch (error) {
await closeTestServer();
await rm(dir, { recursive: true, force: true });
throw error;
}
}

/** Allocate a private AOF directory under the caller's scratch directory. */
export async function createTestRedisAof(parent: string) {
const socketDir = await mkdtemp(path.join(tmpdir(), 'codeapi-redis-'));
const socket = path.join(socketDir, 'redis.sock');
const dir = await mkdtemp(path.join(path.resolve(parent), 'aof-')).catch(async error => {
await rm(socketDir, { recursive: true, force: true });
throw error;
});
let current: Awaited<ReturnType<typeof launch>> | undefined;
let busy = false;
let disposed = false;

async function transition<T>(run: () => Promise<T>): Promise<T> {
if (busy) throw new Error('Test Redis lifecycle transition is already in progress');
busy = true;
try {
return await run();
} finally {
busy = false;
}
}

async function stop(signal: StopSignal) {
if (!current) return;
const received = await current.stop(signal);
current = undefined;
if (signal === 'SIGKILL' && received !== signal) {
throw new Error(`Expected Test Redis to exit with SIGKILL; got ${received}`);
}
}

return {
dir,
socket,
reopen: () => transition(async () => {
if (disposed || current) throw new Error('Test Redis must be stopped and not disposed to reopen');
await rm(socket, { force: true });
current = await launch(dir, socket, 0, true);
return current.client;
}),
stop: (signal: StopSignal = 'SIGTERM') => transition(() => stop(signal)),
dispose: () => transition(async () => {
disposed = true;
await stop('SIGTERM');
await Promise.all([
rm(socketDir, { recursive: true, force: true }),
rm(dir, { recursive: true, force: true }),
]);
}),
};
}
Loading