refactor: Restructure monorepo to apps/server/ and apps/web/ layout
Move src/ → apps/server/ and packages/web/ → apps/web/ to adopt standard monorepo conventions (apps/ for runnable apps, packages/ for reusable libraries). Update all config files, shared package imports, test fixtures, and documentation to reflect new paths. Key fixes: - Update workspace config to ["apps/*", "packages/*"] - Update tsconfig.json rootDir/include for apps/server/ - Add apps/web/** to vitest exclude list - Update drizzle.config.ts schema path - Fix ensure-schema.ts migration path detection (3 levels up in dev, 2 levels up in dist) - Fix tests/integration/cli-server.test.ts import paths - Update packages/shared imports to apps/server/ paths - Update all docs/ files with new paths
This commit is contained in:
9
apps/server/process/index.ts
Normal file
9
apps/server/process/index.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* Process Module
|
||||
*
|
||||
* Exports for process management functionality.
|
||||
*/
|
||||
|
||||
export { ProcessManager } from './manager.js';
|
||||
export { ProcessRegistry } from './registry.js';
|
||||
export type { ProcessInfo, ProcessStatus, SpawnOptions } from './types.js';
|
||||
414
apps/server/process/manager.test.ts
Normal file
414
apps/server/process/manager.test.ts
Normal file
@@ -0,0 +1,414 @@
|
||||
/**
|
||||
* ProcessManager Tests
|
||||
*
|
||||
* Tests for the process lifecycle manager.
|
||||
* Mocks execa to avoid spawning real processes.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
|
||||
import { ProcessRegistry } from './registry.js';
|
||||
import { ProcessManager } from './manager.js';
|
||||
import type { EventBus, ProcessSpawnedEvent, ProcessStoppedEvent, ProcessCrashedEvent } from '../events/index.js';
|
||||
|
||||
// Mock execa module
|
||||
vi.mock('execa', () => {
|
||||
return {
|
||||
execa: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
// Import execa mock after mocking
|
||||
import { execa } from 'execa';
|
||||
const mockExeca = vi.mocked(execa);
|
||||
|
||||
describe('ProcessManager', () => {
|
||||
let registry: ProcessRegistry;
|
||||
let manager: ProcessManager;
|
||||
let mockSubprocess: {
|
||||
pid: number;
|
||||
on: ReturnType<typeof vi.fn>;
|
||||
kill: ReturnType<typeof vi.fn>;
|
||||
unref: ReturnType<typeof vi.fn>;
|
||||
catch: ReturnType<typeof vi.fn>;
|
||||
then: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let exitHandler: ((code: number | null, signal: string | null) => void) | null;
|
||||
|
||||
beforeEach(() => {
|
||||
registry = new ProcessRegistry();
|
||||
manager = new ProcessManager(registry);
|
||||
exitHandler = null;
|
||||
|
||||
// Create mock subprocess
|
||||
mockSubprocess = {
|
||||
pid: 12345,
|
||||
on: vi.fn((event: string, handler: (code: number | null, signal: string | null) => void) => {
|
||||
if (event === 'exit') {
|
||||
exitHandler = handler;
|
||||
}
|
||||
}),
|
||||
kill: vi.fn(),
|
||||
unref: vi.fn(),
|
||||
catch: vi.fn().mockReturnThis(),
|
||||
then: vi.fn().mockReturnThis(),
|
||||
};
|
||||
|
||||
// Setup execa mock to return subprocess
|
||||
mockExeca.mockReturnValue(mockSubprocess as unknown as ReturnType<typeof execa>);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('spawn()', () => {
|
||||
it('should create process and register it', async () => {
|
||||
const info = await manager.spawn({
|
||||
id: 'proc-1',
|
||||
command: 'node',
|
||||
args: ['server.js'],
|
||||
});
|
||||
|
||||
expect(info.id).toBe('proc-1');
|
||||
expect(info.pid).toBe(12345);
|
||||
expect(info.command).toBe('node');
|
||||
expect(info.args).toEqual(['server.js']);
|
||||
expect(info.status).toBe('running');
|
||||
expect(info.startedAt).toBeInstanceOf(Date);
|
||||
|
||||
// Verify registered in registry
|
||||
expect(registry.get('proc-1')).toBe(info);
|
||||
});
|
||||
|
||||
it('should call execa with correct arguments', async () => {
|
||||
await manager.spawn({
|
||||
id: 'proc-1',
|
||||
command: 'node',
|
||||
args: ['app.js', '--port', '3000'],
|
||||
cwd: '/app',
|
||||
env: { NODE_ENV: 'production' },
|
||||
});
|
||||
|
||||
expect(mockExeca).toHaveBeenCalledWith('node', ['app.js', '--port', '3000'], {
|
||||
cwd: '/app',
|
||||
env: expect.objectContaining({ NODE_ENV: 'production' }),
|
||||
detached: true,
|
||||
stdio: 'ignore',
|
||||
});
|
||||
});
|
||||
|
||||
it('should throw if process ID already running', async () => {
|
||||
await manager.spawn({
|
||||
id: 'proc-1',
|
||||
command: 'node',
|
||||
args: [],
|
||||
});
|
||||
|
||||
await expect(
|
||||
manager.spawn({
|
||||
id: 'proc-1',
|
||||
command: 'node',
|
||||
args: [],
|
||||
})
|
||||
).rejects.toThrow("Process with id 'proc-1' is already running");
|
||||
});
|
||||
|
||||
it('should throw if PID is undefined', async () => {
|
||||
mockSubprocess.pid = undefined as unknown as number;
|
||||
|
||||
await expect(
|
||||
manager.spawn({
|
||||
id: 'proc-1',
|
||||
command: 'node',
|
||||
args: [],
|
||||
})
|
||||
).rejects.toThrow("Failed to get PID for process 'proc-1'");
|
||||
});
|
||||
|
||||
it('should set up exit handler that updates registry on normal exit', async () => {
|
||||
await manager.spawn({
|
||||
id: 'proc-1',
|
||||
command: 'node',
|
||||
args: [],
|
||||
});
|
||||
|
||||
// Simulate normal exit
|
||||
exitHandler?.(0, null);
|
||||
|
||||
expect(registry.get('proc-1')?.status).toBe('stopped');
|
||||
});
|
||||
|
||||
it('should mark as crashed on non-zero exit', async () => {
|
||||
await manager.spawn({
|
||||
id: 'proc-1',
|
||||
command: 'node',
|
||||
args: [],
|
||||
});
|
||||
|
||||
// Simulate crash (non-zero exit)
|
||||
exitHandler?.(1, null);
|
||||
|
||||
expect(registry.get('proc-1')?.status).toBe('crashed');
|
||||
});
|
||||
});
|
||||
|
||||
describe('stop()', () => {
|
||||
it('should terminate process', async () => {
|
||||
await manager.spawn({
|
||||
id: 'proc-1',
|
||||
command: 'node',
|
||||
args: [],
|
||||
});
|
||||
|
||||
// Make subprocess.then resolve immediately to simulate exit
|
||||
mockSubprocess.then.mockImplementation((cb: () => void) => {
|
||||
cb();
|
||||
return mockSubprocess;
|
||||
});
|
||||
|
||||
await manager.stop('proc-1');
|
||||
|
||||
expect(mockSubprocess.kill).toHaveBeenCalledWith('SIGTERM');
|
||||
});
|
||||
|
||||
it('should throw if process not found', async () => {
|
||||
await expect(manager.stop('non-existent')).rejects.toThrow(
|
||||
"Process with id 'non-existent' not found"
|
||||
);
|
||||
});
|
||||
|
||||
it('should not throw for already stopped process', async () => {
|
||||
await manager.spawn({
|
||||
id: 'proc-1',
|
||||
command: 'node',
|
||||
args: [],
|
||||
});
|
||||
|
||||
// Simulate process already stopped via exit handler
|
||||
exitHandler?.(0, null);
|
||||
|
||||
// Should not throw
|
||||
await expect(manager.stop('proc-1')).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('stopAll()', () => {
|
||||
it('should stop all running processes', async () => {
|
||||
// Create multiple mock subprocesses
|
||||
const mockSubprocess1 = { ...mockSubprocess, pid: 111 };
|
||||
const mockSubprocess2 = { ...mockSubprocess, pid: 222 };
|
||||
const mockSubprocess3 = { ...mockSubprocess, pid: 333 };
|
||||
|
||||
let callCount = 0;
|
||||
mockExeca.mockImplementation(() => {
|
||||
callCount++;
|
||||
const sub = [mockSubprocess1, mockSubprocess2, mockSubprocess3][callCount - 1];
|
||||
sub.then = vi.fn().mockImplementation((cb: () => void) => {
|
||||
cb();
|
||||
return sub;
|
||||
});
|
||||
return sub as unknown as ReturnType<typeof execa>;
|
||||
});
|
||||
|
||||
await manager.spawn({ id: 'proc-1', command: 'node', args: [] });
|
||||
await manager.spawn({ id: 'proc-2', command: 'node', args: [] });
|
||||
await manager.spawn({ id: 'proc-3', command: 'node', args: [] });
|
||||
|
||||
await manager.stopAll();
|
||||
|
||||
expect(mockSubprocess1.kill).toHaveBeenCalledWith('SIGTERM');
|
||||
expect(mockSubprocess2.kill).toHaveBeenCalledWith('SIGTERM');
|
||||
expect(mockSubprocess3.kill).toHaveBeenCalledWith('SIGTERM');
|
||||
});
|
||||
});
|
||||
|
||||
describe('restart()', () => {
|
||||
it('should stop and respawn process', async () => {
|
||||
const mockSubprocess2 = { ...mockSubprocess, pid: 54321 };
|
||||
|
||||
// First spawn returns original subprocess
|
||||
mockExeca.mockReturnValueOnce(mockSubprocess as unknown as ReturnType<typeof execa>);
|
||||
|
||||
await manager.spawn({
|
||||
id: 'proc-1',
|
||||
command: 'node',
|
||||
args: ['server.js'],
|
||||
});
|
||||
|
||||
// Make stop work
|
||||
mockSubprocess.then.mockImplementation((cb: () => void) => {
|
||||
cb();
|
||||
return mockSubprocess;
|
||||
});
|
||||
|
||||
// Second spawn (after restart) returns new subprocess
|
||||
mockExeca.mockReturnValueOnce(mockSubprocess2 as unknown as ReturnType<typeof execa>);
|
||||
|
||||
const newInfo = await manager.restart('proc-1');
|
||||
|
||||
expect(newInfo.id).toBe('proc-1');
|
||||
expect(newInfo.pid).toBe(54321);
|
||||
expect(newInfo.status).toBe('running');
|
||||
});
|
||||
|
||||
it('should throw if process not found', async () => {
|
||||
await expect(manager.restart('non-existent')).rejects.toThrow(
|
||||
"Process with id 'non-existent' not found"
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isRunning()', () => {
|
||||
it('should return true for running process', async () => {
|
||||
// Mock process.kill to not throw (process exists)
|
||||
const originalKill = process.kill;
|
||||
vi.spyOn(process, 'kill').mockImplementation(() => true);
|
||||
|
||||
await manager.spawn({
|
||||
id: 'proc-1',
|
||||
command: 'node',
|
||||
args: [],
|
||||
});
|
||||
|
||||
expect(manager.isRunning('proc-1')).toBe(true);
|
||||
|
||||
process.kill = originalKill;
|
||||
});
|
||||
|
||||
it('should return false for non-existent process', () => {
|
||||
expect(manager.isRunning('non-existent')).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false and update status if process is dead', async () => {
|
||||
await manager.spawn({
|
||||
id: 'proc-1',
|
||||
command: 'node',
|
||||
args: [],
|
||||
});
|
||||
|
||||
// Mock process.kill to throw (process dead)
|
||||
vi.spyOn(process, 'kill').mockImplementation(() => {
|
||||
throw new Error('ESRCH');
|
||||
});
|
||||
|
||||
expect(manager.isRunning('proc-1')).toBe(false);
|
||||
expect(registry.get('proc-1')?.status).toBe('crashed');
|
||||
});
|
||||
|
||||
it('should return false for stopped process', async () => {
|
||||
await manager.spawn({
|
||||
id: 'proc-1',
|
||||
command: 'node',
|
||||
args: [],
|
||||
});
|
||||
|
||||
// Simulate exit
|
||||
exitHandler?.(0, null);
|
||||
|
||||
expect(manager.isRunning('proc-1')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('event emission', () => {
|
||||
let mockEventBus: EventBus;
|
||||
let managerWithBus: ProcessManager;
|
||||
|
||||
beforeEach(() => {
|
||||
mockEventBus = {
|
||||
emit: vi.fn(),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
once: vi.fn(),
|
||||
};
|
||||
managerWithBus = new ProcessManager(registry, mockEventBus);
|
||||
});
|
||||
|
||||
it('should emit ProcessSpawned event on spawn', async () => {
|
||||
await managerWithBus.spawn({
|
||||
id: 'proc-1',
|
||||
command: 'node',
|
||||
args: ['server.js'],
|
||||
});
|
||||
|
||||
expect(mockEventBus.emit).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: 'process:spawned',
|
||||
timestamp: expect.any(Date),
|
||||
payload: {
|
||||
processId: 'proc-1',
|
||||
pid: 12345,
|
||||
command: 'node',
|
||||
},
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('should emit ProcessStopped event on normal exit', async () => {
|
||||
await managerWithBus.spawn({
|
||||
id: 'proc-1',
|
||||
command: 'node',
|
||||
args: [],
|
||||
});
|
||||
|
||||
// Clear spawn event
|
||||
vi.mocked(mockEventBus.emit).mockClear();
|
||||
|
||||
// Simulate normal exit (code 0)
|
||||
exitHandler?.(0, null);
|
||||
|
||||
expect(mockEventBus.emit).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: 'process:stopped',
|
||||
timestamp: expect.any(Date),
|
||||
payload: {
|
||||
processId: 'proc-1',
|
||||
pid: 12345,
|
||||
exitCode: 0,
|
||||
},
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('should emit ProcessCrashed event on non-zero exit', async () => {
|
||||
await managerWithBus.spawn({
|
||||
id: 'proc-1',
|
||||
command: 'node',
|
||||
args: [],
|
||||
});
|
||||
|
||||
// Clear spawn event
|
||||
vi.mocked(mockEventBus.emit).mockClear();
|
||||
|
||||
// Simulate crash (non-zero exit with signal)
|
||||
exitHandler?.(1, 'SIGTERM');
|
||||
|
||||
expect(mockEventBus.emit).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: 'process:crashed',
|
||||
timestamp: expect.any(Date),
|
||||
payload: {
|
||||
processId: 'proc-1',
|
||||
pid: 12345,
|
||||
exitCode: 1,
|
||||
signal: 'SIGTERM',
|
||||
},
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('should not emit events if eventBus is not provided', async () => {
|
||||
// Use manager without event bus
|
||||
await manager.spawn({
|
||||
id: 'proc-1',
|
||||
command: 'node',
|
||||
args: [],
|
||||
});
|
||||
|
||||
// Simulate exit
|
||||
exitHandler?.(0, null);
|
||||
|
||||
// No errors should occur (events just don't get emitted)
|
||||
expect(mockEventBus.emit).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
316
apps/server/process/manager.ts
Normal file
316
apps/server/process/manager.ts
Normal file
@@ -0,0 +1,316 @@
|
||||
/**
|
||||
* Process Manager
|
||||
*
|
||||
* Manages spawning, stopping, and lifecycle of child processes.
|
||||
* Uses execa for process spawning with detached mode support.
|
||||
* Emits domain events via optional EventBus for coordination.
|
||||
*/
|
||||
|
||||
import { execa, type ResultPromise } from 'execa';
|
||||
import type { ProcessInfo, SpawnOptions } from './types.js';
|
||||
import type { ProcessRegistry } from './registry.js';
|
||||
import type { EventBus, ProcessSpawnedEvent, ProcessStoppedEvent, ProcessCrashedEvent } from '../events/index.js';
|
||||
|
||||
/** Stop timeout in milliseconds before sending SIGKILL */
|
||||
const STOP_TIMEOUT_MS = 5000;
|
||||
|
||||
/**
|
||||
* Internal tracking for spawned process handles.
|
||||
* Maps process ID to execa subprocess for control operations.
|
||||
*/
|
||||
interface ProcessHandle {
|
||||
subprocess: ResultPromise;
|
||||
options: SpawnOptions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Manager for spawning, tracking, and controlling child processes.
|
||||
*/
|
||||
export class ProcessManager {
|
||||
private handles: Map<string, ProcessHandle> = new Map();
|
||||
|
||||
/**
|
||||
* Create a new ProcessManager.
|
||||
* @param registry - Registry for tracking process metadata
|
||||
* @param eventBus - Optional event bus for emitting domain events
|
||||
*/
|
||||
constructor(
|
||||
private registry: ProcessRegistry,
|
||||
private eventBus?: EventBus
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Spawn a new child process.
|
||||
* @param options - Spawn configuration
|
||||
* @returns Process info for the spawned process
|
||||
* @throws If process fails to start
|
||||
*/
|
||||
async spawn(options: SpawnOptions): Promise<ProcessInfo> {
|
||||
const { id, command, args = [], cwd, env } = options;
|
||||
|
||||
// Check if process with this ID already exists
|
||||
const existing = this.registry.get(id);
|
||||
if (existing && existing.status === 'running') {
|
||||
throw new Error(`Process with id '${id}' is already running`);
|
||||
}
|
||||
|
||||
// Spawn the process in detached mode
|
||||
const subprocess = execa(command, args, {
|
||||
cwd,
|
||||
env: env ? { ...process.env, ...env } : undefined,
|
||||
detached: true,
|
||||
stdio: 'ignore', // Don't inherit stdio for background processes
|
||||
});
|
||||
|
||||
// Ensure we have a PID
|
||||
const pid = subprocess.pid;
|
||||
if (pid === undefined) {
|
||||
throw new Error(`Failed to get PID for process '${id}'`);
|
||||
}
|
||||
|
||||
// Create process info
|
||||
const info: ProcessInfo = {
|
||||
id,
|
||||
pid,
|
||||
command,
|
||||
args,
|
||||
startedAt: new Date(),
|
||||
status: 'running',
|
||||
};
|
||||
|
||||
// Store handle for later control
|
||||
this.handles.set(id, { subprocess, options });
|
||||
|
||||
// Register in registry
|
||||
this.registry.register(info);
|
||||
|
||||
// Emit ProcessSpawned event
|
||||
if (this.eventBus) {
|
||||
const event: ProcessSpawnedEvent = {
|
||||
type: 'process:spawned',
|
||||
timestamp: new Date(),
|
||||
payload: {
|
||||
processId: id,
|
||||
pid,
|
||||
command,
|
||||
},
|
||||
};
|
||||
this.eventBus.emit(event);
|
||||
}
|
||||
|
||||
// Set up exit handler to update status and emit events
|
||||
subprocess.on('exit', (code, signal) => {
|
||||
const status = code === 0 ? 'stopped' : 'crashed';
|
||||
this.registry.updateStatus(id, status);
|
||||
this.handles.delete(id);
|
||||
|
||||
// Emit appropriate event based on exit status
|
||||
if (this.eventBus) {
|
||||
if (status === 'stopped') {
|
||||
const event: ProcessStoppedEvent = {
|
||||
type: 'process:stopped',
|
||||
timestamp: new Date(),
|
||||
payload: {
|
||||
processId: id,
|
||||
pid,
|
||||
exitCode: code,
|
||||
},
|
||||
};
|
||||
this.eventBus.emit(event);
|
||||
} else {
|
||||
const event: ProcessCrashedEvent = {
|
||||
type: 'process:crashed',
|
||||
timestamp: new Date(),
|
||||
payload: {
|
||||
processId: id,
|
||||
pid,
|
||||
exitCode: code,
|
||||
signal,
|
||||
},
|
||||
};
|
||||
this.eventBus.emit(event);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Suppress unhandled rejection when process is killed
|
||||
// This is expected behavior - we're intentionally killing processes
|
||||
subprocess.catch(() => {
|
||||
// Intentionally ignored - we handle exit via the 'exit' event
|
||||
});
|
||||
|
||||
// Unref the subprocess so it doesn't keep the parent alive
|
||||
subprocess.unref();
|
||||
|
||||
return info;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop a running process.
|
||||
* Sends SIGTERM first, then SIGKILL after timeout if needed.
|
||||
* @param id - Process ID to stop
|
||||
* @throws If process not found
|
||||
*/
|
||||
async stop(id: string): Promise<void> {
|
||||
const handle = this.handles.get(id);
|
||||
const info = this.registry.get(id);
|
||||
|
||||
if (!info) {
|
||||
throw new Error(`Process with id '${id}' not found`);
|
||||
}
|
||||
|
||||
if (info.status !== 'running') {
|
||||
// Already stopped, just clean up
|
||||
this.handles.delete(id);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!handle) {
|
||||
// Process exists in registry but we don't have a handle
|
||||
// Try to kill by PID directly
|
||||
try {
|
||||
process.kill(info.pid, 'SIGTERM');
|
||||
await this.waitForExit(info.pid, STOP_TIMEOUT_MS);
|
||||
} catch {
|
||||
// Process might already be dead
|
||||
}
|
||||
this.registry.updateStatus(id, 'stopped');
|
||||
return;
|
||||
}
|
||||
|
||||
// Send SIGTERM
|
||||
handle.subprocess.kill('SIGTERM');
|
||||
|
||||
// Wait for graceful shutdown
|
||||
const exited = await this.waitForProcessExit(handle.subprocess, STOP_TIMEOUT_MS);
|
||||
|
||||
if (!exited) {
|
||||
// Force kill with SIGKILL
|
||||
handle.subprocess.kill('SIGKILL');
|
||||
await this.waitForProcessExit(handle.subprocess, 1000).catch(() => {});
|
||||
}
|
||||
|
||||
// Update status (exit handler should have done this, but ensure it)
|
||||
this.registry.updateStatus(id, 'stopped');
|
||||
this.handles.delete(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop all running processes.
|
||||
*/
|
||||
async stopAll(): Promise<void> {
|
||||
const processes = this.registry.getAll().filter(p => p.status === 'running');
|
||||
await Promise.all(processes.map(p => this.stop(p.id).catch(() => {})));
|
||||
}
|
||||
|
||||
/**
|
||||
* Restart a process with the same configuration.
|
||||
* @param id - Process ID to restart
|
||||
* @returns New process info
|
||||
* @throws If process not found or original config unavailable
|
||||
*/
|
||||
async restart(id: string): Promise<ProcessInfo> {
|
||||
const handle = this.handles.get(id);
|
||||
const info = this.registry.get(id);
|
||||
|
||||
if (!info) {
|
||||
throw new Error(`Process with id '${id}' not found`);
|
||||
}
|
||||
|
||||
// Get original spawn options
|
||||
let options: SpawnOptions;
|
||||
if (handle) {
|
||||
options = handle.options;
|
||||
} else {
|
||||
// Reconstruct options from process info
|
||||
options = {
|
||||
id,
|
||||
command: info.command,
|
||||
args: info.args,
|
||||
};
|
||||
}
|
||||
|
||||
// Stop if running
|
||||
if (info.status === 'running') {
|
||||
await this.stop(id);
|
||||
}
|
||||
|
||||
// Unregister old process
|
||||
this.registry.unregister(id);
|
||||
|
||||
// Spawn with same options
|
||||
return this.spawn(options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a process is currently running.
|
||||
* @param id - Process ID to check
|
||||
* @returns true if process exists and is running
|
||||
*/
|
||||
isRunning(id: string): boolean {
|
||||
const info = this.registry.get(id);
|
||||
if (!info || info.status !== 'running') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Double-check by probing the actual process
|
||||
try {
|
||||
process.kill(info.pid, 0);
|
||||
return true;
|
||||
} catch {
|
||||
// Process is dead, update registry
|
||||
this.registry.updateStatus(id, 'crashed');
|
||||
this.handles.delete(id);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for a subprocess to exit within a timeout.
|
||||
* @returns true if process exited, false if timeout
|
||||
*/
|
||||
private waitForProcessExit(subprocess: ResultPromise, timeoutMs: number): Promise<boolean> {
|
||||
return new Promise(resolve => {
|
||||
const timeout = setTimeout(() => {
|
||||
resolve(false);
|
||||
}, timeoutMs);
|
||||
|
||||
// Use both then and catch to handle success and kill scenarios
|
||||
subprocess
|
||||
.then(() => {
|
||||
clearTimeout(timeout);
|
||||
resolve(true);
|
||||
})
|
||||
.catch(() => {
|
||||
// Process was killed (expected) - this is success for our purposes
|
||||
clearTimeout(timeout);
|
||||
resolve(true);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for a PID to exit within a timeout.
|
||||
* @returns true if process exited, false if timeout
|
||||
*/
|
||||
private waitForExit(pid: number, timeoutMs: number): Promise<boolean> {
|
||||
return new Promise(resolve => {
|
||||
const start = Date.now();
|
||||
const check = () => {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
// Still alive
|
||||
if (Date.now() - start >= timeoutMs) {
|
||||
resolve(false);
|
||||
} else {
|
||||
setTimeout(check, 100);
|
||||
}
|
||||
} catch {
|
||||
// Dead
|
||||
resolve(true);
|
||||
}
|
||||
};
|
||||
check();
|
||||
});
|
||||
}
|
||||
}
|
||||
183
apps/server/process/registry.test.ts
Normal file
183
apps/server/process/registry.test.ts
Normal file
@@ -0,0 +1,183 @@
|
||||
/**
|
||||
* ProcessRegistry Tests
|
||||
*
|
||||
* Tests for the in-memory process registry.
|
||||
* Verifies CRUD operations for process metadata.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { ProcessRegistry } from './registry.js';
|
||||
import type { ProcessInfo } from './types.js';
|
||||
|
||||
describe('ProcessRegistry', () => {
|
||||
let registry: ProcessRegistry;
|
||||
|
||||
// Helper to create a ProcessInfo object
|
||||
const createProcessInfo = (id: string, overrides: Partial<ProcessInfo> = {}): ProcessInfo => ({
|
||||
id,
|
||||
pid: 12345,
|
||||
command: 'node',
|
||||
args: ['server.js'],
|
||||
startedAt: new Date(),
|
||||
status: 'running',
|
||||
...overrides,
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
registry = new ProcessRegistry();
|
||||
});
|
||||
|
||||
describe('register()', () => {
|
||||
it('should add process to registry', () => {
|
||||
const info = createProcessInfo('proc-1');
|
||||
registry.register(info);
|
||||
|
||||
expect(registry.size).toBe(1);
|
||||
expect(registry.get('proc-1')).toBe(info);
|
||||
});
|
||||
|
||||
it('should overwrite process with same ID', () => {
|
||||
const info1 = createProcessInfo('proc-1', { pid: 111 });
|
||||
const info2 = createProcessInfo('proc-1', { pid: 222 });
|
||||
|
||||
registry.register(info1);
|
||||
registry.register(info2);
|
||||
|
||||
expect(registry.size).toBe(1);
|
||||
expect(registry.get('proc-1')?.pid).toBe(222);
|
||||
});
|
||||
});
|
||||
|
||||
describe('get()', () => {
|
||||
it('should retrieve registered process', () => {
|
||||
const info = createProcessInfo('proc-1');
|
||||
registry.register(info);
|
||||
|
||||
const retrieved = registry.get('proc-1');
|
||||
expect(retrieved).toBe(info);
|
||||
});
|
||||
|
||||
it('should return undefined for non-existent process', () => {
|
||||
const result = registry.get('non-existent');
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAll()', () => {
|
||||
it('should return all registered processes', () => {
|
||||
const info1 = createProcessInfo('proc-1');
|
||||
const info2 = createProcessInfo('proc-2');
|
||||
const info3 = createProcessInfo('proc-3');
|
||||
|
||||
registry.register(info1);
|
||||
registry.register(info2);
|
||||
registry.register(info3);
|
||||
|
||||
const all = registry.getAll();
|
||||
expect(all).toHaveLength(3);
|
||||
expect(all).toContain(info1);
|
||||
expect(all).toContain(info2);
|
||||
expect(all).toContain(info3);
|
||||
});
|
||||
|
||||
it('should return empty array when registry is empty', () => {
|
||||
const all = registry.getAll();
|
||||
expect(all).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateStatus()', () => {
|
||||
it('should change process status correctly', () => {
|
||||
const info = createProcessInfo('proc-1', { status: 'running' });
|
||||
registry.register(info);
|
||||
|
||||
const result = registry.updateStatus('proc-1', 'stopped');
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(registry.get('proc-1')?.status).toBe('stopped');
|
||||
});
|
||||
|
||||
it('should return false for non-existent process', () => {
|
||||
const result = registry.updateStatus('non-existent', 'stopped');
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should update to crashed status', () => {
|
||||
const info = createProcessInfo('proc-1', { status: 'running' });
|
||||
registry.register(info);
|
||||
|
||||
registry.updateStatus('proc-1', 'crashed');
|
||||
|
||||
expect(registry.get('proc-1')?.status).toBe('crashed');
|
||||
});
|
||||
});
|
||||
|
||||
describe('unregister()', () => {
|
||||
it('should remove process from registry', () => {
|
||||
const info = createProcessInfo('proc-1');
|
||||
registry.register(info);
|
||||
|
||||
expect(registry.size).toBe(1);
|
||||
|
||||
registry.unregister('proc-1');
|
||||
|
||||
expect(registry.size).toBe(0);
|
||||
expect(registry.get('proc-1')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should do nothing for non-existent process', () => {
|
||||
registry.register(createProcessInfo('proc-1'));
|
||||
|
||||
registry.unregister('non-existent');
|
||||
|
||||
expect(registry.size).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getByPid()', () => {
|
||||
it('should find process by OS PID', () => {
|
||||
const info = createProcessInfo('proc-1', { pid: 54321 });
|
||||
registry.register(info);
|
||||
|
||||
const found = registry.getByPid(54321);
|
||||
expect(found).toBe(info);
|
||||
});
|
||||
|
||||
it('should return undefined for unknown PID', () => {
|
||||
registry.register(createProcessInfo('proc-1', { pid: 111 }));
|
||||
|
||||
const found = registry.getByPid(99999);
|
||||
expect(found).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('clear()', () => {
|
||||
it('should remove all processes from registry', () => {
|
||||
registry.register(createProcessInfo('proc-1'));
|
||||
registry.register(createProcessInfo('proc-2'));
|
||||
registry.register(createProcessInfo('proc-3'));
|
||||
|
||||
expect(registry.size).toBe(3);
|
||||
|
||||
registry.clear();
|
||||
|
||||
expect(registry.size).toBe(0);
|
||||
expect(registry.getAll()).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('size', () => {
|
||||
it('should return count of registered processes', () => {
|
||||
expect(registry.size).toBe(0);
|
||||
|
||||
registry.register(createProcessInfo('proc-1'));
|
||||
expect(registry.size).toBe(1);
|
||||
|
||||
registry.register(createProcessInfo('proc-2'));
|
||||
expect(registry.size).toBe(2);
|
||||
|
||||
registry.unregister('proc-1');
|
||||
expect(registry.size).toBe(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
95
apps/server/process/registry.ts
Normal file
95
apps/server/process/registry.ts
Normal file
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* Process Registry
|
||||
*
|
||||
* In-memory registry for tracking managed processes.
|
||||
* Provides CRUD operations for process metadata.
|
||||
*
|
||||
* Note: This is in-memory for now. Phase 2 adds SQLite persistence.
|
||||
*/
|
||||
|
||||
import type { ProcessInfo } from './types.js';
|
||||
|
||||
/**
|
||||
* Registry for tracking managed processes.
|
||||
* Stores process information in memory using a Map.
|
||||
*/
|
||||
export class ProcessRegistry {
|
||||
private processes: Map<string, ProcessInfo> = new Map();
|
||||
|
||||
/**
|
||||
* Register a new process in the registry.
|
||||
* @param info - Process information to register
|
||||
*/
|
||||
register(info: ProcessInfo): void {
|
||||
this.processes.set(info.id, info);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a process from the registry.
|
||||
* @param id - Process ID to unregister
|
||||
*/
|
||||
unregister(id: string): void {
|
||||
this.processes.delete(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a process by its ID.
|
||||
* @param id - Process ID to look up
|
||||
* @returns Process info if found, undefined otherwise
|
||||
*/
|
||||
get(id: string): ProcessInfo | undefined {
|
||||
return this.processes.get(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all registered processes.
|
||||
* @returns Array of all process info objects
|
||||
*/
|
||||
getAll(): ProcessInfo[] {
|
||||
return Array.from(this.processes.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a process by its operating system PID.
|
||||
* @param pid - OS process ID to search for
|
||||
* @returns Process info if found, undefined otherwise
|
||||
*/
|
||||
getByPid(pid: number): ProcessInfo | undefined {
|
||||
for (const process of this.processes.values()) {
|
||||
if (process.pid === pid) {
|
||||
return process;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all processes from the registry.
|
||||
*/
|
||||
clear(): void {
|
||||
this.processes.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a process's status in the registry.
|
||||
* @param id - Process ID to update
|
||||
* @param status - New status value
|
||||
* @returns true if process was found and updated, false otherwise
|
||||
*/
|
||||
updateStatus(id: string, status: ProcessInfo['status']): boolean {
|
||||
const process = this.processes.get(id);
|
||||
if (process) {
|
||||
process.status = status;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the count of registered processes.
|
||||
* @returns Number of processes in the registry
|
||||
*/
|
||||
get size(): number {
|
||||
return this.processes.size;
|
||||
}
|
||||
}
|
||||
45
apps/server/process/types.ts
Normal file
45
apps/server/process/types.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* Process Management Types
|
||||
*
|
||||
* Type definitions for process lifecycle management.
|
||||
* Used by ProcessRegistry and ProcessManager.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Process status states
|
||||
*/
|
||||
export type ProcessStatus = 'running' | 'stopped' | 'crashed';
|
||||
|
||||
/**
|
||||
* Information about a managed process
|
||||
*/
|
||||
export interface ProcessInfo {
|
||||
/** Unique identifier for the process */
|
||||
id: string;
|
||||
/** Operating system process ID */
|
||||
pid: number;
|
||||
/** Command that was executed */
|
||||
command: string;
|
||||
/** Arguments passed to the command */
|
||||
args: string[];
|
||||
/** When the process was started */
|
||||
startedAt: Date;
|
||||
/** Current status of the process */
|
||||
status: ProcessStatus;
|
||||
}
|
||||
|
||||
/**
|
||||
* Options for spawning a new process
|
||||
*/
|
||||
export interface SpawnOptions {
|
||||
/** Unique identifier for tracking this process */
|
||||
id: string;
|
||||
/** Command to execute */
|
||||
command: string;
|
||||
/** Arguments to pass to the command */
|
||||
args?: string[];
|
||||
/** Working directory for the process */
|
||||
cwd?: string;
|
||||
/** Environment variables for the process */
|
||||
env?: Record<string, string>;
|
||||
}
|
||||
Reference in New Issue
Block a user