diff --git a/apps/agent/src/index.ts b/apps/agent/src/index.ts index 66dd1be9..64f174e7 100644 --- a/apps/agent/src/index.ts +++ b/apps/agent/src/index.ts @@ -4,6 +4,7 @@ loadEnvConfig(process.cwd(), process.env.NODE_ENV !== 'production') import { workflowService } from '@shumai/workflow-core' import { TaskQueueAgent } from '@shumai/workflow-core' import { initAgentWorkflows } from '@shumai/agent' +import { handleDaemonCommands } from '@shumai/core/src/utils/daemon' if (process.argv.includes('--check')) { console.log('āœ… Agent worker evaluated successfully!') @@ -28,7 +29,7 @@ async function run() { await workflowService.startWorkers(TaskQueueAgent, options) } -run().catch((err) => { +handleDaemonCommands('shumai-agent', run).catch((err) => { console.error(err) process.exit(1) }) diff --git a/apps/transcode/src/index.ts b/apps/transcode/src/index.ts index 915b3692..cd020430 100644 --- a/apps/transcode/src/index.ts +++ b/apps/transcode/src/index.ts @@ -3,6 +3,7 @@ loadEnvConfig(process.cwd(), process.env.NODE_ENV !== 'production') import { initTranscodeWorkflows } from '@shumai/transcode' import { TaskQueueTranscode, workflowService } from '@shumai/workflow-core' +import { handleDaemonCommands } from '@shumai/core/src/utils/daemon' if (process.argv.includes('--check')) { console.log('āœ… Transcode worker evaluated successfully!') @@ -27,7 +28,7 @@ async function run() { await workflowService.startWorkers(TaskQueueTranscode, options) } -run().catch((err) => { +handleDaemonCommands('shumai-transcode', run).catch((err) => { console.error(err) process.exit(1) }) diff --git a/apps/web/src/index.ts b/apps/web/src/index.ts index d5860a94..465f497d 100644 --- a/apps/web/src/index.ts +++ b/apps/web/src/index.ts @@ -11,118 +11,127 @@ import { initTranscodeWorkflows } from '@shumai/transcode' import { workflowService } from '@shumai/workflow-core' import { app } from '@shumai/api' +import { handleDaemonCommands } from '@shumai/core/src/utils/daemon' + if (process.argv.includes('--check')) { console.log('āœ… Web app evaluated successfully!') process.exit(0) } -// Initialize workflows and activities for local executor mode -initAgentWorkflows() -initTranscodeWorkflows() +async function run() { + // Initialize workflows and activities for local executor mode + initAgentWorkflows() + initTranscodeWorkflows() -// Start services -await metadataService.syncSystemFields().catch(console.error) -assetService.startCleanupJob() -workflowService.start() -if (process.env.WORKFLOW_EXECUTOR === 'temporal') { - const args = process.argv.slice(2) - let workersOption = '' - for (let i = 0; i < args.length; i++) { - if (args[i] === '--workers') { - workersOption = args[i + 1] || '' - } else if (args[i].startsWith('--workers=')) { - workersOption = args[i].split('=')[1] + // Start services + await metadataService.syncSystemFields().catch(console.error) + assetService.startCleanupJob() + workflowService.start() + if (process.env.WORKFLOW_EXECUTOR === 'temporal') { + const args = process.argv.slice(2) + let workersOption = '' + for (let i = 0; i < args.length; i++) { + if (args[i] === '--workers') { + workersOption = args[i + 1] || '' + } else if (args[i].startsWith('--workers=')) { + workersOption = args[i].split('=')[1] + } } + + const queuesToStart: string[] = [] + if (workersOption === 'agent' || workersOption === 'ai') { + queuesToStart.push('agent_queue') + } else if (workersOption === 'transcode') { + queuesToStart.push('transcode_queue') + } else if (workersOption === 'all') { + queuesToStart.push('agent_queue', 'transcode_queue') + } + + Promise.all(queuesToStart.map((q) => workflowService.startWorkers(q))).catch(console.error) } - const queuesToStart: string[] = [] - if (workersOption === 'agent' || workersOption === 'ai') { - queuesToStart.push('agent_queue') - } else if (workersOption === 'transcode') { - queuesToStart.push('transcode_queue') - } else if (workersOption === 'all') { - queuesToStart.push('agent_queue', 'transcode_queue') - } + const isProd = process.env.NODE_ENV === 'production' - Promise.all(queuesToStart.map((q) => workflowService.startWorkers(q))).catch(console.error) -} + const port = process.env.SHUMAI_SERVER_PORT ? parseInt(process.env.SHUMAI_SERVER_PORT) : 3000 -const isProd = process.env.NODE_ENV === 'production' + const server = Bun.serve( + isProd + ? { + port, + maxRequestBodySize: process.env.MAX_REQUEST_BODY_SIZE + ? parseInt(process.env.MAX_REQUEST_BODY_SIZE) + : 1024 * 1024 * 1024 * 10, // Default 10GB + development: false, + async fetch(req) { + const url = new URL(req.url) -const port = process.env.SHUMAI_SERVER_PORT ? parseInt(process.env.SHUMAI_SERVER_PORT) : 3000 - -const server = Bun.serve( - isProd - ? { - port, - maxRequestBodySize: process.env.MAX_REQUEST_BODY_SIZE - ? parseInt(process.env.MAX_REQUEST_BODY_SIZE) - : 1024 * 1024 * 1024 * 10, // Default 10GB - development: false, - async fetch(req) { - const url = new URL(req.url) - - if (!url.pathname.startsWith('/api/') && !url.pathname.startsWith('/files/')) { - const filepath = join(import.meta.dir, url.pathname) - const file = Bun.file(filepath) - if (await file.exists()) { - try { - const stat = await file.stat() - if (stat.isFile()) { - return new Response(file) + if (!url.pathname.startsWith('/api/') && !url.pathname.startsWith('/files/')) { + const filepath = join(import.meta.dir, url.pathname) + const file = Bun.file(filepath) + if (await file.exists()) { + try { + const stat = await file.stat() + if (stat.isFile()) { + return new Response(file) + } + } catch { + // ignore stat errors } - } catch { - // ignore stat errors + } + + const htmlFile = Bun.file(join(import.meta.dir, 'index.html')) + if (await htmlFile.exists()) { + return new Response(htmlFile, { + headers: { 'Content-Type': 'text/html' }, + }) + } + + const htmlFileNpm = Bun.file(join(import.meta.dir, 'shumai-app.html')) + if (await htmlFileNpm.exists()) { + return new Response(htmlFileNpm, { + headers: { 'Content-Type': 'text/html' }, + }) } } - const htmlFile = Bun.file(join(import.meta.dir, 'index.html')) - if (await htmlFile.exists()) { - return new Response(htmlFile, { - headers: { 'Content-Type': 'text/html' }, - }) - } + return app.fetch(req) + }, + } + : { + port, + maxRequestBodySize: process.env.MAX_REQUEST_BODY_SIZE + ? parseInt(process.env.MAX_REQUEST_BODY_SIZE) + : 1024 * 1024 * 1024 * 10, // Default 10GB + development: true, + fetch: app.fetch, + routes: { + // Serve index.html for root + '/': index, - const htmlFileNpm = Bun.file(join(import.meta.dir, 'shumai-app.html')) - if (await htmlFileNpm.exists()) { - return new Response(htmlFileNpm, { - headers: { 'Content-Type': 'text/html' }, - }) - } - } + // Proxy API requests to Hono + '/api/*': app.fetch, + '/files/*': app.fetch, - return app.fetch(req) + // Catch-all for SPA routing (fallback to index.html) + '/*': index, + }, }, - } - : { - port, - maxRequestBodySize: process.env.MAX_REQUEST_BODY_SIZE - ? parseInt(process.env.MAX_REQUEST_BODY_SIZE) - : 1024 * 1024 * 1024 * 10, // Default 10GB - development: true, - fetch: app.fetch, - routes: { - // Serve index.html for root - '/': index, + ) - // Proxy API requests to Hono - '/api/*': app.fetch, - '/files/*': app.fetch, + console.log(`šŸš€ Server running at ${server.url}`) - // Catch-all for SPA routing (fallback to index.html) - '/*': index, - }, - }, -) + const shutdown = () => { + console.log('\nShutting down gracefully...') + assetService.stopCleanupJob() + server.stop(true) + process.exit(0) + } -console.log(`šŸš€ Server running at ${server.url}`) - -const shutdown = () => { - console.log('\nShutting down gracefully...') - assetService.stopCleanupJob() - server.stop(true) - process.exit(0) + process.on('SIGINT', shutdown) + process.on('SIGTERM', shutdown) } -process.on('SIGINT', shutdown) -process.on('SIGTERM', shutdown) +handleDaemonCommands('shumai', run).catch((err) => { + console.error(err) + process.exit(1) +}) diff --git a/packages/core/src/utils/daemon.test.ts b/packages/core/src/utils/daemon.test.ts new file mode 100644 index 00000000..4bfc6287 --- /dev/null +++ b/packages/core/src/utils/daemon.test.ts @@ -0,0 +1,125 @@ +import { describe, expect, it, vi, beforeEach, afterEach, type MockInstance } from 'vitest' +import { existsSync, writeFileSync, readFileSync, rmSync, mkdirSync, openSync } from 'node:fs' +import { join } from 'node:path' +import { handleDaemonCommands } from './daemon' +import { spawn } from 'node:child_process' + +// Mock os.homedir to return a temporary directory for test isolation +vi.mock('node:os', async (importOriginal) => { + const actual = await importOriginal() + const mockTempDir = `${actual.tmpdir()}/shumai-test-daemon-${Math.random().toString(36).substring(2)}` + return { + ...actual, + homedir: () => mockTempDir, + } +}) + +// Mock node:child_process for spawn tests +vi.mock('node:child_process', () => { + return { + spawn: vi.fn(() => { + return { + pid: 99999, + unref: vi.fn(), + } + }), + } +}) + +// Mock node:fs to mock openSync for ESM safety +vi.mock('node:fs', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + openSync: vi.fn(() => 42), + } +}) + +import { homedir } from 'node:os' + +describe('handleDaemonCommands', () => { + const appName = 'test-app' + const mockTempDir = homedir() + const pidFile = join(mockTempDir, '.shumai', 'pids', `${appName}.pid`) + + let mockExit: MockInstance + let mockKill: MockInstance + const originalArgv = process.argv + + beforeEach(() => { + mkdirSync(mockTempDir, { recursive: true }) + mockExit = vi.spyOn(process, 'exit').mockImplementation(() => { + throw new Error('process.exit') + }) + mockKill = vi.spyOn(process, 'kill').mockImplementation(() => true) + + vi.mocked(spawn).mockClear() + vi.mocked(openSync).mockClear() + }) + + afterEach(() => { + process.argv = originalArgv + vi.restoreAllMocks() + try { + rmSync(mockTempDir, { recursive: true, force: true }) + } catch { + // Ignore + } + }) + + it('runs the runFn on normal startup', async () => { + process.argv = ['node', 'script.js'] + const runFn = vi.fn().mockResolvedValue(undefined) + + await handleDaemonCommands(appName, runFn) + + expect(runFn).toHaveBeenCalled() + expect(existsSync(pidFile)).toBe(true) + expect(readFileSync(pidFile, 'utf8').trim()).toBe(process.pid.toString()) + }) + + it('stops the process if stop command is passed', async () => { + process.argv = ['node', 'script.js', 'stop'] + const runFn = vi.fn().mockResolvedValue(undefined) + + // Write a dummy PID file + mkdirSync(join(mockTempDir, '.shumai', 'pids'), { recursive: true }) + writeFileSync(pidFile, '12345') + + await expect(handleDaemonCommands(appName, runFn)).rejects.toThrow('process.exit') + + expect(runFn).not.toHaveBeenCalled() + expect(mockKill).toHaveBeenCalledWith(12345, 'SIGTERM') + expect(mockExit).toHaveBeenCalledWith(0) + expect(openSync).not.toHaveBeenCalled() + }) + + it('daemonizes the process if -d is passed', async () => { + process.argv = ['node', 'script.js', '-d'] + const runFn = vi.fn().mockResolvedValue(undefined) + + await expect(handleDaemonCommands(appName, runFn)).rejects.toThrow('process.exit') + + expect(runFn).not.toHaveBeenCalled() + expect(spawn).toHaveBeenCalled() + expect(existsSync(pidFile)).toBe(true) + expect(readFileSync(pidFile, 'utf8').trim()).toBe('99999') + expect(mockExit).toHaveBeenCalledWith(0) + }) + + it('restarts the process if restart command is passed', async () => { + process.argv = ['node', 'script.js', 'restart'] + const runFn = vi.fn().mockResolvedValue(undefined) + + // Write a dummy PID file + mkdirSync(join(mockTempDir, '.shumai', 'pids'), { recursive: true }) + writeFileSync(pidFile, '12345') + + await expect(handleDaemonCommands(appName, runFn)).rejects.toThrow('process.exit') + + expect(runFn).not.toHaveBeenCalled() + expect(mockKill).toHaveBeenCalledWith(12345, 'SIGTERM') + expect(spawn).toHaveBeenCalled() + expect(mockExit).toHaveBeenCalledWith(0) + }) +}) diff --git a/packages/core/src/utils/daemon.ts b/packages/core/src/utils/daemon.ts new file mode 100644 index 00000000..e4b3e360 --- /dev/null +++ b/packages/core/src/utils/daemon.ts @@ -0,0 +1,269 @@ +import { spawn } from 'node:child_process' +import { + existsSync, + writeFileSync, + readFileSync, + unlinkSync, + mkdirSync, + statSync, + createReadStream, + openSync, +} from 'node:fs' +import { join } from 'node:path' +import { homedir } from 'node:os' + +const SHUMAI_DIR = join(homedir(), '.shumai') +const PID_DIR = join(SHUMAI_DIR, 'pids') +const LOG_DIR = join(SHUMAI_DIR, 'logs') + +function isProcessRunning(pid: number): boolean { + try { + process.kill(pid, 0) + return true + } catch (err) { + if (err && typeof err === 'object' && 'code' in err && err.code === 'EPERM') { + return true + } + return false + } +} + +async function stopProcess(appName: string, pidFile: string): Promise { + if (!existsSync(pidFile)) { + console.log(`No running instance of ${appName} found.`) + return false + } + + const pid = parseInt(readFileSync(pidFile, 'utf8').trim(), 10) + if (isNaN(pid)) { + console.log(`Invalid PID found in ${pidFile}. Cleaning up file.`) + try { + unlinkSync(pidFile) + } catch { + // Ignore + } + return false + } + + let isRunning = isProcessRunning(pid) + if (!isRunning) { + console.log(`Process ${pid} is not running. Cleaning up PID file.`) + try { + unlinkSync(pidFile) + } catch { + // Ignore + } + return false + } + + console.log(`Stopping ${appName} (PID: ${pid})...`) + try { + process.kill(pid, 'SIGTERM') + } catch (err) { + console.error(`Failed to send SIGTERM to process ${pid}:`, err) + return false + } + + // Wait for it to stop + for (let i = 0; i < 30; i++) { + if (!isProcessRunning(pid)) { + isRunning = false + break + } + await new Promise((resolve) => setTimeout(resolve, 100)) + } + + if (isRunning) { + console.log(`Process ${pid} did not stop gracefully. Sending SIGKILL...`) + try { + process.kill(pid, 'SIGKILL') + } catch (err) { + console.error(`Failed to send SIGKILL to process ${pid}:`, err) + } + } + + try { + unlinkSync(pidFile) + } catch { + // Ignore + } + + console.log(`Successfully stopped ${appName}.`) + return true +} + +function startDaemon(appName: string, pidFile: string, logFile: string): void { + // Check if already running + if (existsSync(pidFile)) { + const pid = parseInt(readFileSync(pidFile, 'utf8').trim(), 10) + if (!isNaN(pid) && pid !== process.pid) { + if (isProcessRunning(pid)) { + console.error( + `${appName} is already running (PID: ${pid}). Use '${appName} stop' or '${appName} restart'.`, + ) + process.exit(1) + } else { + try { + unlinkSync(pidFile) + } catch { + // Ignore + } + } + } + } + + console.log(`Starting ${appName} in background...`) + const logFd = openSync(logFile, 'w') + + const childArgs = process.argv.slice(1).filter((arg) => arg !== '-d' && arg !== 'restart') + + const child = spawn(process.argv[0], childArgs, { + detached: true, + stdio: ['ignore', logFd, logFd], + env: { + ...process.env, + SHUMAI_DAEMONIZED: 'true', + }, + }) + + if (child.pid === undefined) { + console.error(`Failed to spawn background process for ${appName}.`) + process.exit(1) + } + + child.unref() + writeFileSync(pidFile, child.pid.toString(), 'utf8') + console.log(`šŸš€ Started ${appName} in background (PID: ${child.pid}).`) + console.log(`šŸ“„ Logs are being written to ${logFile}`) + process.exit(0) +} + +function viewLogs(appName: string, logFile: string): void { + if (!existsSync(logFile)) { + console.log(`No log file found for ${appName}.`) + process.exit(0) + } + + // Print existing content (last 100 lines) + const content = readFileSync(logFile, 'utf8') + const lines = content.split('\n') + const lastLines = lines.slice(-100).join('\n') + process.stdout.write(lastLines + '\n') + + let cursor = statSync(logFile).size + const interval = setInterval(() => { + try { + if (existsSync(logFile)) { + const stats = statSync(logFile) + if (stats.size > cursor) { + const stream = createReadStream(logFile, { start: cursor, end: stats.size - 1 }) + stream.pipe(process.stdout, { end: false }) + cursor = stats.size + } else if (stats.size < cursor) { + cursor = stats.size + } + } + } catch { + // Ignore read errors + } + }, 250) + + const cleanup = () => { + clearInterval(interval) + process.exit(0) + } + process.on('SIGINT', cleanup) + process.on('SIGTERM', cleanup) +} + +export async function handleDaemonCommands( + appName: string, + runFn: () => Promise, +): Promise { + const pidFile = join(PID_DIR, `${appName}.pid`) + const logFile = join(LOG_DIR, `${appName}.log`) + + // Ensure directories exist + mkdirSync(PID_DIR, { recursive: true }) + mkdirSync(LOG_DIR, { recursive: true }) + + const args = process.argv.slice(2) + const isStop = args.includes('stop') + const isRestart = args.includes('restart') + const isLogs = args.includes('logs') + const isDaemon = args.includes('-d') && process.env.SHUMAI_DAEMONIZED !== 'true' + + if (isStop) { + await stopProcess(appName, pidFile) + process.exit(0) + } + + if (isRestart) { + await stopProcess(appName, pidFile) + await new Promise((resolve) => setTimeout(resolve, 500)) + startDaemon(appName, pidFile, logFile) + process.exit(0) + } + + if (isLogs) { + viewLogs(appName, logFile) + // Keep process open for logs tailing + return new Promise(() => {}) + } + + if (isDaemon) { + startDaemon(appName, pidFile, logFile) + process.exit(0) + } + + // Normal Startup logic: check if already running + if (existsSync(pidFile)) { + const pid = parseInt(readFileSync(pidFile, 'utf8').trim(), 10) + if (!isNaN(pid) && pid !== process.pid) { + if (isProcessRunning(pid)) { + console.error( + `${appName} is already running (PID: ${pid}). Use '${appName} stop' or '${appName} restart'.`, + ) + process.exit(1) + } else { + // Process is dead, clean up PID file + try { + unlinkSync(pidFile) + } catch { + // Ignore + } + } + } + } + + // Write the PID file + writeFileSync(pidFile, process.pid.toString(), 'utf8') + + const cleanPidFile = () => { + try { + if (existsSync(pidFile)) { + const pidStr = readFileSync(pidFile, 'utf8').trim() + if (parseInt(pidStr, 10) === process.pid) { + unlinkSync(pidFile) + } + } + } catch { + // Ignore + } + } + + // Register cleanups + process.on('exit', cleanPidFile) + + const handleSignal = (signal: string) => { + if (process.listenerCount(signal) === 1) { + process.exit(0) + } + } + + process.on('SIGINT', () => handleSignal('SIGINT')) + process.on('SIGTERM', () => handleSignal('SIGTERM')) + + // Run the main app + await runFn() +} diff --git a/scripts/build-npm.ts b/scripts/build-npm.ts index 46f0296d..467d663d 100644 --- a/scripts/build-npm.ts +++ b/scripts/build-npm.ts @@ -165,6 +165,7 @@ async function buildPlatformPackages( entrypoint: string, // eslint-disable-next-line @typescript-eslint/no-explicit-any plugins: any[] = [], + external?: string[], ) { for (const target of targets) { const dirName = `${appName}-${target.platform}-${target.arch}` @@ -180,6 +181,7 @@ async function buildPlatformPackages( binaryName, bunTarget: target.bunTarget, plugins, + external, }) // Generate package.json for platform-specific package @@ -209,6 +211,7 @@ async function buildMainPackage({ entrypoint, plugins = [], extraDependencies = {}, + external = commonExternal, }: { appName: string description: string @@ -217,6 +220,7 @@ async function buildMainPackage({ // eslint-disable-next-line @typescript-eslint/no-explicit-any plugins?: any[] extraDependencies?: Record + external?: string[] }) { console.log(`\nšŸ“„ Packaging wrapper app ${appName}...`) const mainOutDir = path.join(distDir, appName) @@ -235,7 +239,7 @@ async function buildMainPackage({ minify: true, naming: `${appName}-app.[ext]`, plugins, - external: commonExternal, + external, define: { 'process.env.NODE_ENV': JSON.stringify('production'), }, @@ -373,7 +377,8 @@ console.log(\`ā„¹ļø [${appName}] Running from CWD: \${process.cwd()}\`) console.log(\`ā„¹ļø [${appName}] DATABASE_URL is: \${process.env.DATABASE_URL ? '(defined)' : '(undefined)'}\`) const prismaSchemaPath = join(__dirname, '..', 'prisma', 'schema.prisma') -if (existsSync(prismaSchemaPath)) { +const isUtilityCommand = process.argv.includes('stop') || process.argv.includes('logs') +if (existsSync(prismaSchemaPath) && !isUtilityCommand) { console.log('šŸ”„ Running database migrations...') activeProcess = spawn( binaryPath, @@ -488,13 +493,15 @@ const shumaiPlugins = [ }), tailwindPlugin, ] -await buildPlatformPackages('shumai', dummyRunnerPath) +const shumaiExternal = commonExternal.filter((dep) => dep !== 'zod') +await buildPlatformPackages('shumai', dummyRunnerPath, shumaiPlugins, shumaiExternal) await buildMainPackage({ appName: 'shumai', description: 'A fullstack AI-powered media workspace and workflow engine', hasPrisma: true, entrypoint: './apps/web/src/index.ts', plugins: shumaiPlugins, + external: shumaiExternal, }) // 3. Build shumai-agent (Agent app & platform binaries)