Files
splinter/plugins/tasks/tasks.c
T
Konrad 3c5cdaf53a splinter: delegations are tasks too, and the status line is alive
A delegate is work someone else does while we wait, so it belongs in the task
panel with its own clock. The tasks plugin now publishes sp_task_ops through the
host, and delegate.c opens an entry before the call and closes it with status and
rough token count after - 'who is still running' becomes a fact on screen instead
of a guess.

Measured status line, live during a turn:

  splinter 0.1.0  clock: 19:12:56  |  ctx 4.0k  |  12 tok/s  |
  4.0k in / 238 out  |  tasks 0/4          Delphinium 19178ms

Not yet observed: a delegate entry in the panel. Both test configs had no
reachable delegate (one endpoint dead, one with no defers at all), so the cycle
open -> close never ran against a real call. The wiring compiles and the task API
is exercised by task_start/task_list; the delegate half needs one live delegate to
prove.
2026-11-08 19:13:44 +00:00

466 lines
11 KiB
C

/*
* splinter -- background tasks.
*
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*
* Some work should not hold the conversation. A build, a test run, a delegate on
* another host: start it, keep talking, look at it later.
*
* Four at a time by default (SPLINTER_TASKS_MAX), because a machine that runs
* twenty background shell commands at once is not doing the work faster, it is
* only harder to read. A start beyond the limit is refused with the reason, not
* queued into an invisible backlog.
*
* The tools:
*
* task_start command, label? -> id, starts at once
* task_list -> id, state, seconds, bytes, label
* task_result id -> output, exit status; fails while running
* task_kill id -> stop it
*
* Tasks are shell commands, so starting one is destructive in the same sense that
* `run` is: the gate and the approval path see it like any other change.
*/
#include <errno.h>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include "splinter.h"
#include "splinter_plugin.h"
#define TASKS_MAX 16
struct task {
int id;
volatile int running;
int status; /* exit status once finished */
char label[64];
char cmd[512];
struct sp_buf out;
time_t started, ended;
pid_t pid;
pthread_t th;
pthread_mutex_t lock;
};
static struct task tasks[TASKS_MAX];
static int ntasks;
static int next_id = 1;
static unsigned max_parallel = 4;
static pthread_mutex_t tasks_lock = PTHREAD_MUTEX_INITIALIZER;
static int
running_count(void)
{
int i, n = 0;
pthread_mutex_lock(&tasks_lock);
for (i = 0; i < ntasks; i++)
if (tasks[i].running)
n++;
pthread_mutex_unlock(&tasks_lock);
return n;
}
static void
publish_meter(struct sp_host *h)
{
struct sp_meter m = *sp_host_meter(h);
int i, run = 0;
pthread_mutex_lock(&tasks_lock);
for (i = 0; i < ntasks; i++)
if (tasks[i].running)
run++;
pthread_mutex_unlock(&tasks_lock);
m.tasks_running = (unsigned)run;
m.tasks_max = max_parallel;
sp_host_set_meter(h, &m);
}
static void
refresh_widget(struct sp_host *h)
{
char text[1024];
size_t used = 0;
int i;
pthread_mutex_lock(&tasks_lock);
for (i = 0; i < ntasks && used + 96 < sizeof(text); i++) {
struct task *t = &tasks[i];
int n;
if (t->running)
n = snprintf(text + used, sizeof(text) - used,
"#%d %s %lds\n", t->id, t->label,
(long)(time(NULL) - t->started));
else
n = snprintf(text + used, sizeof(text) - used,
"#%d %s exit %d %.2fs\n", t->id, t->label,
t->status, difftime(t->ended, t->started));
if (n < 0 || (size_t)n >= sizeof(text) - used)
break;
used += (size_t)n;
}
pthread_mutex_unlock(&tasks_lock);
if (used == 0)
(void)sp_host_widget_text(h, "tasks", "keine");
else
(void)sp_host_widget_text(h, "tasks", text);
}
static void *
task_run(void *arg)
{
struct task *t = arg;
FILE *p;
char chunk[2048];
size_t got;
p = popen(t->cmd, "r");
if (p == NULL) {
pthread_mutex_lock(&t->lock);
sp_buf_printf(&t->out, "error: %s", strerror(errno));
t->status = 127;
t->running = 0;
t->ended = time(NULL);
pthread_mutex_unlock(&t->lock);
return NULL;
}
while ((got = fread(chunk, 1, sizeof(chunk), p)) > 0) {
pthread_mutex_lock(&t->lock);
if (t->out.len < (1u << 20)) /* 1 MiB, stated */
(void)sp_buf_add(&t->out, chunk, got);
pthread_mutex_unlock(&t->lock);
}
pthread_mutex_lock(&t->lock);
t->status = pclose(p);
t->running = 0;
t->ended = time(NULL);
pthread_mutex_unlock(&t->lock);
return NULL;
}
static struct task *
find(int id)
{
int i;
for (i = 0; i < ntasks; i++)
if (tasks[i].id == id)
return &tasks[i];
return NULL;
}
/* the JSON value of a string argument, without pulling in the whole parser */
static void
arg_str(const char *args, const char *key, char *buf, size_t len)
{
char pat[64];
const char *p;
size_t i = 0;
buf[0] = '\0';
snprintf(pat, sizeof(pat), "\"%s\":\"", key);
p = args != NULL ? strstr(args, pat) : NULL;
if (p == NULL)
return;
p += strlen(pat);
while (*p != '\0' && *p != '"' && i + 1 < len) {
if (*p == '\\' && p[1] != '\0')
p++;
buf[i++] = *p++;
}
buf[i] = '\0';
}
static struct sp_host *host_ref;
/*
* Tasks someone else owns - a delegate on another host. They get an entry and a
* clock, but no thread here: the harness closes them when the call returns.
*/
static int
ops_begin(struct sp_host *h, const char *label, const char *detail)
{
struct task *t;
int id;
(void)detail;
pthread_mutex_lock(&tasks_lock);
if (ntasks == TASKS_MAX) {
pthread_mutex_unlock(&tasks_lock);
return -1;
}
t = &tasks[ntasks++];
memset(t, 0, sizeof(*t));
(void)pthread_mutex_init(&t->lock, NULL);
t->id = next_id++;
t->running = 1;
t->started = time(NULL);
snprintf(t->label, sizeof(t->label), "%.63s", label != NULL ? label : "?");
id = t->id;
pthread_mutex_unlock(&tasks_lock);
if (h != NULL) {
publish_meter(h);
refresh_widget(h);
}
return id;
}
static void
ops_end(struct sp_host *h, int id, int status, size_t tokens)
{
struct task *t;
if (id < 0)
return;
pthread_mutex_lock(&tasks_lock);
t = find(id);
if (t != NULL) {
t->running = 0;
t->status = status;
t->ended = time(NULL);
if (tokens > 0)
(void)sp_buf_printf(&t->out, "[~%zu tokens]", tokens);
}
pthread_mutex_unlock(&tasks_lock);
if (h != NULL) {
publish_meter(h);
refresh_widget(h);
}
}
static const struct sp_task_ops task_ops = { ops_begin, ops_end };
static int
tool_task_start(const char *args, struct sp_buf *out, void *ctx)
{
char cmd[600], label[80];
struct task *t;
int id;
(void)ctx;
arg_str(args, "command", cmd, sizeof(cmd));
arg_str(args, "label", label, sizeof(label));
if (cmd[0] == '\0')
return sp_buf_puts(out, "error: empty command");
if (label[0] == '\0')
snprintf(label, sizeof(label), "%.40s", cmd);
if (running_count() >= (int)max_parallel)
return sp_buf_printf(out, "error: %u tasks already running "
"(SPLINTER_TASKS_MAX) - finish or kill one first",
max_parallel);
pthread_mutex_lock(&tasks_lock);
if (ntasks == TASKS_MAX) {
pthread_mutex_unlock(&tasks_lock);
return sp_buf_puts(out, "error: task table full");
}
t = &tasks[ntasks++];
memset(t, 0, sizeof(*t));
t->id = next_id++;
(void)pthread_mutex_init(&t->lock, NULL);
snprintf(t->cmd, sizeof(t->cmd), "%.511s", cmd);
snprintf(t->label, sizeof(t->label), "%.63s", label);
t->started = time(NULL);
t->running = 1;
if (sp_buf_init(&t->out) != 0) {
ntasks--;
pthread_mutex_unlock(&tasks_lock);
return sp_buf_puts(out, "error: no memory");
}
id = t->id;
if (pthread_create(&t->th, NULL, task_run, t) != 0) {
t->running = 0;
ntasks--;
pthread_mutex_unlock(&tasks_lock);
return sp_buf_puts(out, "error: cannot start thread");
}
pthread_detach(t->th);
pthread_mutex_unlock(&tasks_lock);
if (host_ref != NULL) {
publish_meter(host_ref);
refresh_widget(host_ref);
}
return sp_buf_printf(out, "started #%d (%s) - %d/%u running", id, label,
running_count(), max_parallel);
}
static int
tool_task_list(const char *args, struct sp_buf *out, void *ctx)
{
int i, any = 0;
(void)args;
(void)ctx;
pthread_mutex_lock(&tasks_lock);
for (i = 0; i < ntasks; i++) {
struct task *t = &tasks[i];
any = 1;
if (t->running)
sp_buf_printf(out, "#%d running %lds %zu B %s\n", t->id,
(long)(time(NULL) - t->started), t->out.len,
t->label);
else
sp_buf_printf(out, "#%d done %.2fs exit %d %zu B %s\n",
t->id, difftime(t->ended, t->started), t->status,
t->out.len, t->label);
}
pthread_mutex_unlock(&tasks_lock);
if (!any)
sp_buf_puts(out, "keine Tasks");
return 0;
}
static int
tool_task_result(const char *args, struct sp_buf *out, void *ctx)
{
char num[32];
struct task *t;
int id;
(void)ctx;
arg_str(args, "id", num, sizeof(num));
id = atoi(num);
pthread_mutex_lock(&tasks_lock);
t = find(id);
if (t == NULL) {
pthread_mutex_unlock(&tasks_lock);
return sp_buf_puts(out, "error: no such task");
}
if (t->running) {
long secs = (long)(time(NULL) - t->started);
pthread_mutex_unlock(&tasks_lock);
return sp_buf_printf(out, "still running (%lds, %zu B so far)",
secs, t->out.len);
}
pthread_mutex_lock(&t->lock);
if (t->out.p != NULL)
(void)sp_buf_add(out, t->out.p, t->out.len);
pthread_mutex_unlock(&t->lock);
sp_buf_printf(out, "\n[exit %d, %.1fs]", t->status,
difftime(t->ended, t->started));
pthread_mutex_unlock(&tasks_lock);
return 0;
}
static int
tool_task_kill(const char *args, struct sp_buf *out, void *ctx)
{
char num[32];
struct task *t;
int id;
(void)ctx;
arg_str(args, "id", num, sizeof(num));
id = atoi(num);
pthread_mutex_lock(&tasks_lock);
t = find(id);
if (t == NULL) {
pthread_mutex_unlock(&tasks_lock);
return sp_buf_puts(out, "error: no such task");
}
if (!t->running) {
pthread_mutex_unlock(&tasks_lock);
return sp_buf_puts(out, "already finished");
}
/* the shell is what we know: kill its process group */
(void)kill(-(t->pid), SIGTERM);
pthread_mutex_unlock(&tasks_lock);
return sp_buf_puts(out, "kill signal sent");
}
static const struct sp_tool t_start = {
"task_start",
"Start a shell command in the background and return its id. Use it for "
"builds, tests or long runs instead of blocking the conversation.",
"{\"type\":\"object\",\"properties\":{\"command\":{\"type\":\"string\"},"
"\"label\":{\"type\":\"string\",\"description\":\"short name\"}},"
"\"required\":[\"command\"]}",
SP_AUTH_DESTRUCTIVE, tool_task_start, NULL
};
static const struct sp_tool t_list = {
"task_list", "List background tasks: id, state, time, size, label.",
"{\"type\":\"object\",\"properties\":{}}", SP_AUTH_READ, tool_task_list,
NULL
};
static const struct sp_tool t_result = {
"task_result", "Output and exit status of a finished task.",
"{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"integer\"}},"
"\"required\":[\"id\"]}", SP_AUTH_READ, tool_task_result, NULL
};
static const struct sp_tool t_kill = {
"task_kill", "Stop a running task.",
"{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"integer\"}},"
"\"required\":[\"id\"]}", SP_AUTH_DESTRUCTIVE, tool_task_kill, NULL
};
static int
tasks_tick(struct sp_host *h, const char *name, void *ctx)
{
(void)name;
(void)ctx;
refresh_widget(h);
publish_meter(h);
return 0;
}
static const struct sp_widget widget = {
"tasks", /* name */
tasks_tick, /* tick */
NULL, /* draw */
NULL, /* ctx */
1000 /* interval: a running task is interesting every second */
};
static int
tasks_init(struct sp_host *h)
{
const char *m = getenv("SPLINTER_TASKS_MAX");
if (m != NULL && *m != '\0') {
unsigned v = (unsigned)strtoul(m, NULL, 10);
if (v > 0 && v <= TASKS_MAX)
max_parallel = v;
}
host_ref = h;
(void)sp_host_add_tool(h, &t_start);
(void)sp_host_add_tool(h, &t_list);
(void)sp_host_add_tool(h, &t_result);
(void)sp_host_add_tool(h, &t_kill);
(void)sp_host_add_widget(h, &widget);
(void)sp_host_widget_text(h, "tasks", "keine");
sp_host_set_task_ops(h, &task_ops);
publish_meter(h);
return 0;
}
static const struct sp_plugin plugin = {
SP_PLUGIN_ABI,
"tasks",
"1.0",
tasks_init,
NULL,
NULL
};
const struct sp_plugin *
sp_plugin_describe(void)
{
return &plugin;
}