ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
http_renderer_process.c
Go to the documentation of this file.
1
2/* Existing buffer budgets in bytes, including NUL for text storage. */
3#define MCP_RENDER_ENV_CAPACITY 16
4
5#include "http_renderer.h"
7#include <libplatform/filesystem.h>
8#include <signal.h>
9#include <string.h>
10#include <uv.h>
11
12// libuv supplies portable process and pipe I/O; each renderer owns its event
13// loop.
31static void stop_worker(render_worker_t *w, const char *reason) {
32 if (w->failed)
33 return;
34 w->failed = true;
35 w->stopped = true;
36 SAFE_STRNCPY(w->result->error, reason, sizeof(w->result->error));
37 if (!w->exited)
38 uv_process_kill(&w->process, SIGKILL);
39}
40static void allocate(uv_handle_t *handle, size_t suggested, uv_buf_t *buf) {
41 (void)handle;
42 (void)suggested;
43 buf->len = 16384;
44 buf->base = SAFE_MALLOC(buf->len, char *);
45}
46static void read_output(uv_stream_t *stream, ssize_t count,
47 const uv_buf_t *buf) {
48 render_worker_t *w = stream->data;
49 if (count > 0) {
50 if (stream == (uv_stream_t *)&w->output) {
51 size_t n = (size_t)count;
53 stop_worker(w, "Rendered text exceeds 8 MiB");
54 else {
55 memcpy(w->result->text + w->result->length, buf->base, n);
56 w->result->length += n;
57 w->result->text[w->result->length] = '\0';
58 }
59 } else if (!w->stopped) {
60 // Keep the tail, which normally contains the most useful decoder error.
61 size_t old = strlen(w->result->error), n = (size_t)count,
62 cap = sizeof(w->result->error) - 1;
63 if (n >= cap) {
64 memcpy(w->result->error, buf->base + n - cap, cap);
65 w->result->error[cap] = '\0';
66 } else {
67 if (old + n > cap) {
68 size_t drop = old + n - cap;
69 memmove(w->result->error, w->result->error + drop, old - drop);
70 old -= drop;
71 }
72 memcpy(w->result->error + old, buf->base, n);
73 w->result->error[old + n] = '\0';
74 }
75 }
76 }
77 char *allocation = buf->base;
78 SAFE_FREE(allocation);
79 if (count < 0 && !uv_is_closing((uv_handle_t *)stream))
80 uv_close((uv_handle_t *)stream, NULL);
81}
82static void exited(uv_process_t *process, int64_t status, int signal) {
83 render_worker_t *w = process->data;
84 w->exited = true;
85 w->exit_time = time_get_ns();
86 if (!w->failed && (status || signal)) {
87 w->failed = true;
88 if (!w->result->error[0])
89 SAFE_SNPRINTF(w->result->error, sizeof(w->result->error),
90 "Renderer failed (exit %lld, signal %d)", (long long)status,
91 signal);
92 }
93 uv_close((uv_handle_t *)process, NULL);
94}
95static void tick(uv_timer_t *timer) {
96 render_worker_t *w = timer->data;
98 stop_worker(w, "Rendering cancelled");
99 if (!w->failed &&
100 time_get_ns() - w->started > (uint64_t)w->timeout * 1000000) {
101 w->result->timed_out = true;
102 stop_worker(w, "Rendering exceeded timeout_ms");
103 }
104 if (w->exited) {
105 bool drained = uv_is_closing((uv_handle_t *)&w->output) &&
106 uv_is_closing((uv_handle_t *)&w->errors);
107 // Allow pending pipe reads to drain after process exit, but bound
108 // inherited-descriptor stalls.
109 if (drained || time_get_ns() - w->exit_time > 1000000000) {
110 if (!drained)
111 stop_worker(w, "Renderer output pipes did not close");
112 uv_close((uv_handle_t *)&w->timer, NULL);
113 if (!uv_is_closing((uv_handle_t *)&w->output))
114 uv_close((uv_handle_t *)&w->output, NULL);
115 if (!uv_is_closing((uv_handle_t *)&w->errors))
116 uv_close((uv_handle_t *)&w->errors, NULL);
117 }
118 }
119}
121 atomic_t *cancelled,
123 memset(result, 0, sizeof(*result));
126 SAFE_STRNCPY(result->error, "Renderer output must select text or files",
127 sizeof(result->error));
128 return;
129 }
130 render_worker_t w = {.cancelled = cancelled,
131 .result = result,
132 .started = time_get_ns(),
133 .timeout = r->timeout_ms};
134 result->text = SAFE_CALLOC(HTTP_RENDERER_MAX_OUTPUT + 1, 1, char *);
135 if (uv_loop_init(&w.loop)) {
136 SAFE_STRNCPY(result->error, "Cannot initialize renderer event loop",
137 sizeof(result->error));
138 return;
139 }
140 uv_pipe_init(&w.loop, &w.output, 0);
141 uv_pipe_init(&w.loop, &w.errors, 0);
142 uv_timer_init(&w.loop, &w.timer);
143 w.output.data = w.errors.data = w.timer.data = w.process.data = &w;
144 uv_stdio_container_t streams[3] = {0};
145 streams[0].flags = UV_IGNORE;
146 streams[1].flags = UV_CREATE_PIPE | UV_WRITABLE_PIPE;
147 streams[1].data.stream = (uv_stream_t *)&w.output;
148 streams[2].flags = UV_CREATE_PIPE | UV_WRITABLE_PIPE;
149 streams[2].data.stream = (uv_stream_t *)&w.errors;
150 // Only runtime essentials are inherited; user config, ASCII_CHAT_* and
151 // credentials are excluded.
152 const char *keys[] = {
153 "PATH", "SystemRoot", "WINDIR", "TEMP",
154 "TMP", "TMPDIR", "LD_LIBRARY_PATH", "DYLD_LIBRARY_PATH",
155 "TESTING", NULL};
156 char *env[MCP_RENDER_ENV_CAPACITY] = {0};
157 size_t ne = 0;
158 for (size_t i = 0; keys[i]; ++i) {
159 const char *v = platform_getenv(keys[i]);
160 if (v) {
161 size_t n = strlen(keys[i]) + strlen(v) + 2;
162 env[ne] = SAFE_MALLOC(n, char *);
163 SAFE_SNPRINTF(env[ne], n, "%s=%s", keys[i], v);
164 ++ne;
165 }
166 }
167 // The private staging directory provides an isolated home for media
168 // libraries.
169 if (r->stage_dir[0]) {
170 size_t n = strlen(r->stage_dir) + sizeof("HOME=");
171 env[ne] = SAFE_MALLOC(n, char *);
172 SAFE_SNPRINTF(env[ne], n, "HOME=%s", r->stage_dir);
173 ++ne;
174 }
175 env[ne++] = platform_strdup("ASCII_CHAT_MCP_WORKER=1");
176 env[ne++] = platform_strdup("ASCII_CHAT_OTEL_ENABLED_TELEMETRY=none");
177 if (r->capture_webcam)
178 env[ne++] = platform_strdup("ASCII_CHAT_MCP_WEBCAM=1");
179 uv_process_options_t opts = {.exit_cb = exited,
180 .file = r->argv[0],
181 .args = r->argv,
182 .env = env,
183 .stdio_count = 3,
184 .stdio = streams};
185 int rc = uv_spawn(&w.loop, &w.process, &opts);
186 for (size_t i = 0; i < ne; ++i)
187 SAFE_FREE(env[i]);
188 if (rc) {
189 SAFE_SNPRINTF(result->error, sizeof(result->error),
190 "Cannot start renderer: %s", uv_strerror(rc));
191 uv_close((uv_handle_t *)&w.output, NULL);
192 uv_close((uv_handle_t *)&w.errors, NULL);
193 uv_close((uv_handle_t *)&w.timer, NULL);
194 } else {
195 uv_read_start((uv_stream_t *)&w.output, allocate, read_output);
196 uv_read_start((uv_stream_t *)&w.errors, allocate, read_output);
197 uv_timer_start(&w.timer, tick, 20, 20);
198 }
199 uv_run(&w.loop, UV_RUN_DEFAULT);
200 uv_loop_close(&w.loop);
201 result->elapsed_ms = (time_get_ns() - w.started) / 1000000;
202 if (rc || w.failed)
203 return;
204 result->error[0] = '\0';
205 if (!result->length && !r->stage_file[0]) {
206 SAFE_STRNCPY(result->error, "Renderer returned no ASCII art",
207 sizeof(result->error));
208 return;
209 }
210 if (r->stage_file[0]) {
211 uv_fs_t fs;
212 int e = uv_fs_stat(NULL, &fs, r->stage_file, NULL);
213 bool valid = e == 0 && fs.statbuf.st_size > 0;
214 uv_fs_req_cleanup(&fs);
215 if (!valid) {
216 SAFE_STRNCPY(result->error, "Renderer did not create an output file",
217 sizeof(result->error));
218 return;
219 }
220 // Hard-link publication is atomic and fails if any file/symlink already
221 // owns the destination. Staging beside the destination keeps this on the
222 // same filesystem.
223 e = uv_fs_link(NULL, &fs, r->stage_file, r->output_path, NULL);
224 uv_fs_req_cleanup(&fs);
225 if (e) {
226 SAFE_SNPRINTF(result->error, sizeof(result->error),
227 "Cannot save without replacing an existing file: %s",
228 uv_strerror(e));
229 return;
230 }
232 sizeof(result->output_path));
233 }
234 http_render_result_t frames = {0};
235 if (result->text && result->length)
236 (void)http_render_result_add_text_frame(&frames, result->text,
237 result->length, 0);
238 if (result->output_path[0])
239 (void)http_render_result_add_file_frame(&frames, result->output_path, 0);
240 result->frames = frames.frames;
241 result->frame_count = frames.frame_count;
242}
243
246 if (!result)
247 return;
248 for (size_t i = 0; i < result->frame_count; ++i)
249 SAFE_FREE(result->frames[i].text);
250 SAFE_FREE(result->frames);
251 SAFE_FREE(result->text);
252 memset(result, 0, sizeof(*result));
253}
bool atomic_load_bool(atomic_t *a)
Atomic pointer wrapper.
bool valid
Definition fft.c:29
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
#define SAFE_SNPRINTF(buffer, buffer_size,...)
#define SAFE_CALLOC(count, size, cast)
unsigned long long uint64_t
asciichat_error_t http_render_result_add_file_frame(http_render_result_t *result, const char *path, uint64_t timestamp_ms)
asciichat_error_t http_render_result_add_text_frame(http_render_result_t *result, const char *text, size_t length, uint64_t timestamp_ms)
#define HTTP_RENDERER_MAX_OUTPUT
@ HTTP_RENDER_OUTPUT_FILE
@ HTTP_RENDER_OUTPUT_TEXT
void http_renderer_process(http_renderer_process_request_t *r, atomic_t *cancelled, http_renderer_process_result_t *result)
void http_renderer_process_result_destroy(http_renderer_process_result_t *result)
#define MCP_RENDER_ENV_CAPACITY
char * platform_strdup(const char *s)
🔤 String Manipulation and Shell Escaping Utilities
Atomic value wrapper for integral/boolean types.
Definition atomic.h:80
http_render_frame_t * frames
http_render_output_type_t output_type
char stage_file[PLATFORM_MAX_PATH_LENGTH]
char stage_dir[PLATFORM_MAX_PATH_LENGTH]
char output_path[PLATFORM_MAX_PATH_LENGTH]
char output_path[PLATFORM_MAX_PATH_LENGTH]
http_render_frame_t * frames
http_renderer_process_result_t * result
const char * platform_getenv(const char *name)
Definition system.c:45
⏱️ High-precision timing utilities using sokol_time.h and uthash