File size: 5,038 Bytes
94e1b2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import { spawn } from 'child_process'
import { createLogger } from './logger'
import { getProcessMemory } from './process-memory'
import type { ManimExecuteOptions, ManimExecutionResult } from './manim-executor'

const logger = createLogger('ManimExecutorRuntime')

const STDOUT_LOG_INTERVAL_MS = 5000
const PROGRESS_LOG_INTERVAL_MS = 3000
const STDERR_LOG_INTERVAL_MS = 10000
const MEMORY_MONITOR_INTERVAL_MS = 2000
const IS_PRODUCTION = process.env.NODE_ENV === 'production'

function parseBooleanEnv(value: string | undefined): boolean | undefined {
  if (typeof value !== 'string') return undefined
  const normalized = value.trim().toLowerCase()
  if (['1', 'true', 'yes', 'on'].includes(normalized)) return true
  if (['0', 'false', 'no', 'off'].includes(normalized)) return false
  return undefined
}

const renderMemoryLogEnabled = parseBooleanEnv(process.env.RENDER_MEMORY_LOG_ENABLED) ?? false

const RESOLUTION_MAP: Record<string, { width: number; height: number }> = {
  low: { width: 854, height: 480 },
  medium: { width: 1280, height: 720 },
  high: { width: 1920, height: 1080 }
}

export interface NormalizedExecuteOptions {
  jobId: string
  quality: string
  frameRate: number
  format: 'mp4' | 'png'
  sceneName: string
  tempDir: string
  mediaDir: string
  timeoutMs: number
}

export interface ExecutionState {
  stdout: string
  stderr: string
  peakMemoryMB: number
  lastProgressLogAt: number
  lastStdoutLogAt: number
  lastStderrLogAt: number
}

export function normalizeExecuteOptions(options: ManimExecuteOptions): NormalizedExecuteOptions {
  return {
    jobId: options.jobId,
    quality: options.quality,
    frameRate: options.frameRate ?? 15,
    format: options.format ?? 'mp4',
    sceneName: options.sceneName ?? 'MainScene',
    tempDir: options.tempDir,
    mediaDir: options.mediaDir,
    timeoutMs: options.timeoutMs ?? 10 * 60 * 1000
  }
}

export function buildManimArgs(codeFile: string, options: NormalizedExecuteOptions): string[] {
  const resolution = RESOLUTION_MAP[options.quality] || RESOLUTION_MAP.medium
  const args = [
    'render',
    '--format',
    options.format,
    '--fps',
    options.frameRate.toString(),
    '--resolution',
    `${resolution.width},${resolution.height}`,
    '--media_dir',
    options.mediaDir
  ]

  if (options.format === 'png') {
    args.push('-s')
  }

  args.push(codeFile, options.sceneName)
  return args
}

export function createExecutionState(): ExecutionState {
  const now = Date.now()
  return {
    stdout: '',
    stderr: '',
    peakMemoryMB: 0,
    lastProgressLogAt: now,
    lastStdoutLogAt: now,
    lastStderrLogAt: now
  }
}

export function startMemoryMonitor(
  proc: ReturnType<typeof spawn>,
  options: NormalizedExecuteOptions,
  state: ExecutionState
): NodeJS.Timeout {
  return setInterval(async () => {
    if (!proc.pid) {
      return
    }

    const memory = await getProcessMemory(proc.pid)
    if (memory === null) {
      return
    }

    if (memory > state.peakMemoryMB) {
      state.peakMemoryMB = memory
    }

    if (renderMemoryLogEnabled) {
      logger.info(`Job ${options.jobId}: Manim memory usage`, {
        memoryMB: memory,
        peakMemoryMB: state.peakMemoryMB
      })
    }
  }, MEMORY_MONITOR_INTERVAL_MS)
}

export function handleStdoutData(state: ExecutionState, jobId: string, text: string): void {
  state.stdout += text

  const elapsedSinceLastStdoutLog = Date.now() - state.lastStdoutLogAt
  if (elapsedSinceLastStdoutLog > STDOUT_LOG_INTERVAL_MS) {
    logger.info(`Job ${jobId}: Manim stdout`, {
      output: text.trim(),
      totalOutputLength: state.stdout.length
    })
    state.lastStdoutLogAt = Date.now()
  }

  if (!text.includes('%') && !text.includes('it/s')) {
    return
  }

  const elapsedSinceLastProgressLog = Date.now() - state.lastProgressLogAt
  if (elapsedSinceLastProgressLog > PROGRESS_LOG_INTERVAL_MS) {
    logger.info(`Job ${jobId}: Manim progress`, { progress: text.trim() })
    state.lastProgressLogAt = Date.now()
  }
}

export function handleStderrData(state: ExecutionState, jobId: string, text: string): void {
  state.stderr += text

  const trimmed = text.trim()
  if (!trimmed) {
    return
  }

  const isProgressLike = trimmed.includes('%') || trimmed.includes('it/s') || /animation\s+\d+/i.test(trimmed)
  const elapsedSinceLastStderrLog = Date.now() - state.lastStderrLogAt

  if (isProgressLike && elapsedSinceLastStderrLog < STDERR_LOG_INTERVAL_MS) {
    return
  }

  logger.info(`Job ${jobId}: Manim stderr`, {
    output: trimmed,
    totalStderrLength: state.stderr.length
  })
  state.lastStderrLogAt = Date.now()
}

export function elapsedSeconds(startTime: number): string {
  return ((Date.now() - startTime) / 1000).toFixed(1)
}

export function buildResult(
  success: boolean,
  state: ExecutionState,
  stderrOverride?: string,
  exitCode?: number
): ManimExecutionResult {
  return {
    success,
    stdout: state.stdout,
    stderr: stderrOverride ?? state.stderr,
    peakMemoryMB: state.peakMemoryMB,
    exitCode
  }
}