NAME

Developer::Dashboard::GoRoutine - go-style routines on a C event loop with shared Perl data

PURPOSE

This module provides the Developer Dashboard concurrency API: Perl goroutines on a single-threaded C event loop, shared Perl values, channels, and native operating system process management. It keeps those facilities under the existing Developer::Dashboard::* namespace while loading their implementation from the distribution's XS bundle.

WHY IT EXISTS

Dashboard collectors, services, and tools need concurrent work and managed subprocesses across supported operating systems. Perl's direct fork() is not portable to Windows and does not provide shared Perl references between workers. This module supplies explicit APIs for both in-process routines and independent child processes, with errors surfaced to the caller.

WHEN TO USE

Use go for a Perl callback that should run asynchronously, share or channel when workers need to exchange supported values, and spawn when an independent operating-system process is required. Use wait_all before program exit whenever outstanding routines must finish. Choose spawn instead of go when the work must run as a separate process rather than on the main thread.

HOW TO USE

Import go, share, channel, and wait_all from this module, or call their fully-qualified names. Shared values support normal Perl dereferencing; channels provide blocking send and receive operations and can be closed to wake waiters. Use the returned routine handle to inspect, time out, or cancel a routine. For subprocesses, pass an argument array and an optional hash of working-directory, environment, stream-redirection, or process-group options to spawn, then inspect, wait for, or terminate the returned process id.

WHAT USES IT

RuntimeManager uses the process API for collector and web-service supervision. Collector workers use goroutines and shared state to coordinate refresh work. Other Dashboard Perl code can import this module directly when it needs portable concurrent callbacks, cross-worker values, channels, or subprocess lifecycle control.

SYNOPSIS

use Developer::Dashboard::GoRoutine;

share my $state = {
    count => 0,
    jobs  => [],
};

my $worker = go sub {
    $state->{count}++;
    push $state->{jobs}->@*, { id => 1, status => 'done' };
};

$worker->timeout(10);
wait_all();

print $state->{count};

my $chan = channel();

go sub {
    my $value = $chan->receive;
    print $value;
};

$chan->send(123);
wait_all();

DESCRIPTION

go schedules a Perl callback on the main thread and returns a routine handle. It does not call fork(), does not use Perl's threads module, and does not clone the interpreter: a single-threaded C event loop (timers, IO readiness, process exits) invokes the callback on the main thread when one of its triggers fires. go(sub { ... }, \%opts) adds a trigger: after for a one-shot timer, every for a repeating timer, readable / writable for IO readiness, pid for process exit. The handle provides age, is_running, kill, timeout, status, is_killed, and cancel_requested. A fresh routine reports status pending until the engine dispatches it.

A callback MUST be short and non-blocking: it runs on the main thread, so a callback that blocks (sleep, a blocking read, an infinite loop) stalls the whole process. Callers that need to wait use a trigger instead of blocking.

Cancellation is cooperative. kill cancels a pending routine at once; for a running routine it sets a flag the callback can observe with cancel_requested and wind down. An opaque XS/C call that never returns cannot be forcibly torn down safely.

Inside a go routine, Perl exit is scoped to that routine: it unwinds the routine instead of terminating the whole process. exit in the main interpreter keeps normal Perl semantics.

share my $x = VALUE creates one process-wide value that is visible to the main interpreter and every routine. There is only one interpreter, so the value IS the plain Perl value: scalars, hashes, arrays, nested combinations, scalar/reference chains, CODE, GLOB/filehandles, IO references, regular expressions, formats, lvalue/version scalar references, Perl 5.40 field objects, and ordinary blessed data-backed objects are all supported, with normal Perl dereferencing and filehandle syntax retained. share returns the value unchanged; it exists so code written for the old threaded engine keeps working, and so a variable can be marked as shared for readers.

Scalar read/modify/write operations such as ++, --, +=, -=, *=, /=, %= and .= are atomic with respect to other routines, because callbacks never run at the same time: a routine only runs when the engine dispatches it on the main thread. Hash and array structural operations are likewise safe without a lock.

Objects backed by normal Perl containers retain their blessing so normal methods continue to work. GLOB/IO values are the same underlying open-file description in every routine. Opaque XS objects are the same object in every routine too, because there is only one interpreter.

channel() creates a process-wide channel object; it does not need share. With no argument it is unbuffered, matching an unbuffered Go channel: send blocks until a receiver accepts the value, and receive blocks until a sender supplies one. channel(N) creates a buffered channel of capacity N: sends block only while the buffer is full and receives block only while it is empty. Blocking is done by pumping the engine, never by sleeping, so other routines keep running while a sender or receiver waits. Values are plain Perl values passed by reference, so nested Perl data and supported objects cross without copying. close wakes blocked waiters; receiving from a closed, drained channel returns undef in scalar context or (undef, 0) in list context, while a successful list-context receive returns ($value, 1). Sending on a closed channel throws an exception.

wait_all() is the explicit barrier: call it whenever outstanding routines must finish before the program continues or exits. It pumps until no finite routine is pending. Repeating routines (a repeating timer, the accept loop) are services, not tasks, and are not waited for. At normal process exit an END block drains outstanding finite routines first (repeating routines are cancelled), with a 30 second bound, so a routine that was scheduled but never waited for still runs before the process ends. POSIX::_exit skips the drain, as before.

NATIVE PROCESSES

spawn(\@argv, \%options) starts an independent operating-system process through the Dashboard XS bundle. It accepts literal argument strings and supports cwd, env, stdin, stdout, stderr, and process_group options. The returned positive process id identifies the child independently of the Perl interpreter. This API is separate from go: a go routine runs a Perl callback on the main thread, while spawn starts a process that can outlive its caller.

process_running($pid) reports whether the process appears live. process_exited($pid) checks completion without reaping a POSIX child, which allows a supervisor to poll safely before collecting its exit result. wait_process($pid) waits for and returns the shell-style exit status. On Windows, waiting for a child that has already exited and been reaped returns 255 because no exit code survives to report. The Windows spawn wrapper keeps one handle open per child until wait_process collects it, so a completed child still reports as running and its real exit code survives; it also merges the env overrides into the parent environment for the duration of the spawn, because the native layer has no environment-block builder and the child inherits its parent environment. reap_child($pid) reaps one spawned child that has already exited and reports whether it did; reap_any_exited() reaps every spawned child that has already exited and returns how many it collected, which is how a supervisor collects direct children on Windows, where waitpid(-1) has no equivalent. is_spawn_child($pid) reports whether the pid is a GoRoutine-spawned child the registry still tracks, so a caller can tell a child with a handle to collect from one it never spawned. terminate_process($pid, $signal) sends TERM, KILL, HUP, or INT on POSIX. Windows supports TERM and KILL, mapped to native process termination because POSIX signal handlers are unavailable there. Unsupported signals, invalid identifiers and operating-system errors are reported as exceptions; callers must not treat an inspection failure as a stopped process.

my $pid = Developer::Dashboard::GoRoutine::spawn(
    [ $^X, '-e', 'sleep 1' ],
    { cwd => $workspace, process_group => 1 },
);
while (!Developer::Dashboard::GoRoutine::process_exited($pid)) {
    select undef, undef, undef, 0.02;
}
my $exit = Developer::Dashboard::GoRoutine::wait_process($pid);

EXAMPLES

Share a counter between a routine and the main program, then wait for the routine to finish:

use Developer::Dashboard::GoRoutine qw(go share wait_all);
share my $count = 0;
go sub { $count++ };
wait_all();
print "count=$count\n";

Start and collect a child process using literal arguments, without a shell:

use Developer::Dashboard::GoRoutine qw(spawn wait_process);
my $pid = spawn([ $^X, '-e', 'print "ready\\n"' ], {});
my $exit = wait_process($pid);
die "child failed with status $exit" if $exit != 0;