process

package
v0.0.4-alpha.10 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 4, 2026 License: EUPL-1.2 Imports: 10 Imported by: 0

Documentation

Overview

Package process provides process management with Core IPC integration.

The process package enables spawning, monitoring, and controlling external processes with output streaming via the Core ACTION system.

Getting Started

// Register with Core
core, _ := framework.New(
    framework.WithName("process", process.NewService(process.Options{})),
)

// Get service and run a process
svc := framework.MustServiceFor[*process.Service](core, "process")
proc, _ := svc.Start(ctx, "go", "test", "./...")

Listening for Events

Process events are broadcast via Core.ACTION:

core.RegisterAction(func(c *framework.Core, msg framework.Message) error {
    switch m := msg.(type) {
    case process.ActionProcessOutput:
        fmt.Print(m.Line)
    case process.ActionProcessExited:
        fmt.Printf("Exit code: %d\n", m.ExitCode)
    }
    return nil
})

Index

Constants

View Source
const DefaultBufferSize = 1024 * 1024

Default buffer size for process output (1MB).

Variables

View Source
var (
	ErrProcessNotFound   = errors.New("process not found")
	ErrProcessNotRunning = errors.New("process is not running")
	ErrStdinNotAvailable = errors.New("stdin not available")
)

Errors

View Source
var ErrServiceNotInitialized = &ServiceError{msg: "process: service not initialized"}

ErrServiceNotInitialized is returned when the service is not initialized.

Functions

func Init

func Init(c *framework.Core) error

Init initializes the default global service with a Core instance. This is typically called during application startup.

func Kill

func Kill(id string) error

Kill terminates a process by ID using the default service.

func NewService

func NewService(opts Options) func(*framework.Core) (any, error)

NewService creates a process service factory for Core registration.

core, _ := framework.New(
    framework.WithName("process", process.NewService(process.Options{})),
)

func Run

func Run(ctx context.Context, command string, args ...string) (string, error)

Run executes a command and waits for completion using the default service.

func RunWithOptions

func RunWithOptions(ctx context.Context, opts RunOptions) (string, error)

RunWithOptions executes a command with options and waits using the default service.

func SetDefault

func SetDefault(s *Service)

SetDefault sets the global process service. Thread-safe: can be called concurrently with Default().

Types

type ActionProcessExited

type ActionProcessExited struct {
	ID       string
	ExitCode int
	Duration time.Duration
	Error    error // Non-nil if failed to start or was killed
}

ActionProcessExited is broadcast when a process completes. Check ExitCode for success (0) or failure.

type ActionProcessKilled

type ActionProcessKilled struct {
	ID     string
	Signal string
}

ActionProcessKilled is broadcast when a process is terminated.

type ActionProcessOutput

type ActionProcessOutput struct {
	ID     string
	Line   string
	Stream Stream
}

ActionProcessOutput is broadcast for each line of output. Subscribe to this for real-time streaming.

type ActionProcessStarted

type ActionProcessStarted struct {
	ID      string
	Command string
	Args    []string
	Dir     string
	PID     int
}

ActionProcessStarted is broadcast when a process begins execution.

type Info

type Info struct {
	ID        string        `json:"id"`
	Command   string        `json:"command"`
	Args      []string      `json:"args"`
	Dir       string        `json:"dir"`
	StartedAt time.Time     `json:"startedAt"`
	Status    Status        `json:"status"`
	ExitCode  int           `json:"exitCode"`
	Duration  time.Duration `json:"duration"`
	PID       int           `json:"pid"`
}

Info provides a snapshot of process state without internal fields.

type Options

type Options struct {
	// BufferSize is the ring buffer size for output capture.
	// Default: 1MB (1024 * 1024 bytes).
	BufferSize int
}

Options configures the process service.

type Process

type Process struct {
	ID        string
	Command   string
	Args      []string
	Dir       string
	Env       []string
	StartedAt time.Time
	Status    Status
	ExitCode  int
	Duration  time.Duration
	// contains filtered or unexported fields
}

Process represents a managed external process.

func Get

func Get(id string) (*Process, error)

Get returns a process by ID from the default service.

func List

func List() []*Process

List returns all processes from the default service.

func Running

func Running() []*Process

Running returns all currently running processes from the default service.

func Start

func Start(ctx context.Context, command string, args ...string) (*Process, error)

Start spawns a new process using the default service.

func StartWithOptions

func StartWithOptions(ctx context.Context, opts RunOptions) (*Process, error)

StartWithOptions spawns a process with full configuration using the default service.

func (*Process) CloseStdin

func (p *Process) CloseStdin() error

CloseStdin closes the process stdin pipe.

func (*Process) Done

func (p *Process) Done() <-chan struct{}

Done returns a channel that closes when the process exits.

func (*Process) Info

func (p *Process) Info() Info

Info returns a snapshot of process state.

func (*Process) IsRunning

func (p *Process) IsRunning() bool

IsRunning returns true if the process is still executing.

func (*Process) Kill

func (p *Process) Kill() error

Kill forcefully terminates the process.

func (*Process) Output

func (p *Process) Output() string

Output returns the captured output as a string.

func (*Process) OutputBytes

func (p *Process) OutputBytes() []byte

OutputBytes returns the captured output as bytes.

func (*Process) SendInput

func (p *Process) SendInput(input string) error

SendInput writes to the process stdin.

func (*Process) Signal

func (p *Process) Signal(sig interface{ Signal() }) error

Signal sends a signal to the process.

func (*Process) Wait

func (p *Process) Wait() error

Wait blocks until the process exits.

type RingBuffer

type RingBuffer struct {
	// contains filtered or unexported fields
}

RingBuffer is a fixed-size circular buffer that overwrites old data. Thread-safe for concurrent reads and writes.

func NewRingBuffer

func NewRingBuffer(size int) *RingBuffer

NewRingBuffer creates a ring buffer with the given capacity.

func (*RingBuffer) Bytes

func (rb *RingBuffer) Bytes() []byte

Bytes returns a copy of the buffer contents.

func (*RingBuffer) Cap

func (rb *RingBuffer) Cap() int

Cap returns the buffer capacity.

func (*RingBuffer) Len

func (rb *RingBuffer) Len() int

Len returns the current length of data in the buffer.

func (*RingBuffer) Reset

func (rb *RingBuffer) Reset()

Reset clears the buffer.

func (*RingBuffer) String

func (rb *RingBuffer) String() string

String returns the buffer contents as a string.

func (*RingBuffer) Write

func (rb *RingBuffer) Write(p []byte) (n int, err error)

Write appends data to the buffer, overwriting oldest data if full.

type RunAllResult

type RunAllResult struct {
	Results  []RunResult
	Duration time.Duration
	Passed   int
	Failed   int
	Skipped  int
}

RunAllResult is the aggregate result of running multiple specs.

func (RunAllResult) Success

func (r RunAllResult) Success() bool

Success returns true if all non-skipped specs passed.

type RunOptions

type RunOptions struct {
	// Command is the executable to run.
	Command string
	// Args are the command arguments.
	Args []string
	// Dir is the working directory (empty = current).
	Dir string
	// Env are additional environment variables (KEY=VALUE format).
	Env []string
	// DisableCapture disables output buffering.
	// By default, output is captured to a ring buffer.
	DisableCapture bool
}

RunOptions configures process execution.

type RunResult

type RunResult struct {
	Name     string
	Spec     RunSpec
	ExitCode int
	Duration time.Duration
	Output   string
	Error    error
	Skipped  bool
}

RunResult captures the outcome of a single process.

func (RunResult) Passed

func (r RunResult) Passed() bool

Passed returns true if the process succeeded.

type RunSpec

type RunSpec struct {
	// Name is a friendly identifier (e.g., "lint", "test").
	Name string
	// Command is the executable to run.
	Command string
	// Args are the command arguments.
	Args []string
	// Dir is the working directory.
	Dir string
	// Env are additional environment variables.
	Env []string
	// After lists spec names that must complete successfully first.
	After []string
	// AllowFailure if true, continues pipeline even if this spec fails.
	AllowFailure bool
}

RunSpec defines a process to run with optional dependencies.

type Runner

type Runner struct {
	// contains filtered or unexported fields
}

Runner orchestrates multiple processes with dependencies.

func NewRunner

func NewRunner(svc *Service) *Runner

NewRunner creates a runner for the given service.

func (*Runner) RunAll

func (r *Runner) RunAll(ctx context.Context, specs []RunSpec) (*RunAllResult, error)

RunAll executes specs respecting dependencies, parallelising where possible.

func (*Runner) RunParallel

func (r *Runner) RunParallel(ctx context.Context, specs []RunSpec) (*RunAllResult, error)

RunParallel executes all specs concurrently, regardless of dependencies.

func (*Runner) RunSequential

func (r *Runner) RunSequential(ctx context.Context, specs []RunSpec) (*RunAllResult, error)

RunSequential executes specs one after another, stopping on first failure.

type Service

type Service struct {
	*framework.ServiceRuntime[Options]
	// contains filtered or unexported fields
}

Service manages process execution with Core IPC integration.

func Default

func Default() *Service

Default returns the global process service. Returns nil if not initialized.

func (*Service) Clear

func (s *Service) Clear()

Clear removes all completed processes.

func (*Service) Get

func (s *Service) Get(id string) (*Process, error)

Get returns a process by ID.

func (*Service) Kill

func (s *Service) Kill(id string) error

Kill terminates a process by ID.

func (*Service) List

func (s *Service) List() []*Process

List returns all processes.

func (*Service) OnShutdown

func (s *Service) OnShutdown(ctx context.Context) error

OnShutdown implements framework.Stoppable. Kills all running processes on shutdown.

func (*Service) OnStartup

func (s *Service) OnStartup(ctx context.Context) error

OnStartup implements framework.Startable.

func (*Service) Output

func (s *Service) Output(id string) (string, error)

Output returns the captured output of a process.

func (*Service) Remove

func (s *Service) Remove(id string) error

Remove removes a completed process from the list.

func (*Service) Run

func (s *Service) Run(ctx context.Context, command string, args ...string) (string, error)

Run executes a command and waits for completion. Returns the combined output and any error.

func (*Service) RunWithOptions

func (s *Service) RunWithOptions(ctx context.Context, opts RunOptions) (string, error)

RunWithOptions executes a command with options and waits for completion.

func (*Service) Running

func (s *Service) Running() []*Process

Running returns all currently running processes.

func (*Service) Start

func (s *Service) Start(ctx context.Context, command string, args ...string) (*Process, error)

Start spawns a new process with the given command and args.

func (*Service) StartWithOptions

func (s *Service) StartWithOptions(ctx context.Context, opts RunOptions) (*Process, error)

StartWithOptions spawns a process with full configuration.

type ServiceError

type ServiceError struct {
	// contains filtered or unexported fields
}

ServiceError represents a service-level error.

func (*ServiceError) Error

func (e *ServiceError) Error() string

Error returns the service error message.

type Status

type Status string

Status represents the process lifecycle state.

const (
	// StatusPending indicates the process is queued but not yet started.
	StatusPending Status = "pending"
	// StatusRunning indicates the process is actively executing.
	StatusRunning Status = "running"
	// StatusExited indicates the process completed (check ExitCode).
	StatusExited Status = "exited"
	// StatusFailed indicates the process could not be started.
	StatusFailed Status = "failed"
	// StatusKilled indicates the process was terminated by signal.
	StatusKilled Status = "killed"
)

type Stream

type Stream string

Stream identifies the output source.

const (
	// StreamStdout is standard output.
	StreamStdout Stream = "stdout"
	// StreamStderr is standard error.
	StreamStderr Stream = "stderr"
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL