18 KiB
process
Import: dappco.re/go/core/process
Files: 11
Types
ActionProcessStarted
struct
Broadcast payload for a managed process that has successfully started.
Fields:
ID string: Generated managed-process identifier.Command string: Executable name passed to the service.Args []string: Argument vector used to start the process.Dir string: Working directory supplied at start time.PID int: OS process ID of the child process.
ActionProcessOutput
struct
Broadcast payload for one scanned line of process output.
Fields:
ID string: Managed-process identifier.Line string: One line from stdout or stderr, without the trailing newline.Stream Stream: Output source, usingStreamStdoutorStreamStderr.
ActionProcessExited
struct
Broadcast payload emitted after the service wait goroutine finishes.
Fields:
ID string: Managed-process identifier.ExitCode int: Process exit code.Duration time.Duration: Time elapsed sinceStartedAt.Error error: Declared error slot for exit metadata. The currentServiceemitter does not populate it.
ActionProcessKilled
struct
Broadcast payload emitted by Service.Kill.
Fields:
ID string: Managed-process identifier.Signal string: Signal name reported by the service. The current implementation emits"SIGKILL".
RingBuffer
struct
Fixed-size circular byte buffer used for captured process output. The implementation is mutex-protected and overwrites the oldest bytes when full.
Exported fields:
- None.
DaemonOptions
struct
Configuration for NewDaemon.
Fields:
PIDFile string: PID file path. Empty disables PID-file management.ShutdownTimeout time.Duration: Grace period used byStop. Zero is normalized to 30 seconds byNewDaemon.HealthAddr string: Listen address for the health server. Empty disables health endpoints.HealthChecks []HealthCheck: Additional/healthchecks to register on the health server.Registry *Registry: Optional daemon registry used for automatic register/unregister.RegistryEntry DaemonEntry: Base registry payload.Startfills inPID,Health, andStartedbehavior throughRegistry.Register.
Daemon
struct
Lifecycle wrapper around a PID file, optional health server, and optional registry entry.
Exported fields:
- None.
HealthCheck
type HealthCheck func() error
Named function type used by HealthServer and DaemonOptions. Returning nil marks the check healthy; returning an error makes /health respond with 503.
HealthServer
struct
HTTP server exposing /health and /ready endpoints.
Exported fields:
- None.
PIDFile
struct
Single-instance guard backed by a PID file on disk.
Exported fields:
- None.
ManagedProcess
struct
Service-owned process record for a started child process.
Fields:
ID string: Managed-process identifier generated bycore.ID().Command string: Executable name.Args []string: Command arguments.Dir string: Working directory used when starting the process.Env []string: Extra environment entries appended to the command environment.StartedAt time.Time: Timestamp recorded immediately beforecmd.Start.Status Status: Current lifecycle state tracked by the service.ExitCode int: Exit status after completion.Duration time.Duration: Runtime duration set when the wait goroutine finishes.
Process
type alias of ManagedProcess
Compatibility alias that exposes the same fields and methods as ManagedProcess.
Program
struct
Thin helper for finding and running a named executable.
Fields:
Name string: Binary name to look up or execute.Path string: Resolved absolute path populated byFind. When empty,RunandRunDirfall back toName.
DaemonEntry
struct
Serialized daemon-registry record written as JSON.
Fields:
Code string: Application or component code.Daemon string: Daemon name within that code.PID int: Running process ID.Health string: Health endpoint address, if any.Project string: Optional project label.Binary string: Optional binary label.Started time.Time: Start timestamp persisted in RFC3339Nano format.
Registry
struct
Filesystem-backed daemon registry that stores one JSON file per daemon entry.
Exported fields:
- None.
Runner
struct
Pipeline orchestrator that starts RunSpec processes through a Service.
Exported fields:
- None.
RunSpec
struct
One process specification for Runner.
Fields:
Name string: Friendly name used for dependencies and result reporting.Command string: Executable name.Args []string: Command arguments.Dir string: Working directory.Env []string: Additional environment variables.After []string: Dependency names that must complete before this spec can run inRunAll.AllowFailure bool: When true, downstream work is not skipped because of this spec's failure.
RunResult
struct
Per-spec runner result.
Fields:
Name string: Spec name.Spec RunSpec: Original spec payload.ExitCode int: Exit code from the managed process.Duration time.Duration: Process duration or start-attempt duration.Output string: Captured output returned from the managed process.Error error: Start or orchestration error. For a started process that exits non-zero, this remainsnil.Skipped bool: Whether the spec was skipped instead of run.
RunAllResult
struct
Aggregate result returned by RunAll, RunSequential, and RunParallel.
Fields:
Results []RunResult: Collected per-spec results.Duration time.Duration: End-to-end runtime for the orchestration method.Passed int: Count of results wherePassed()is true.Failed int: Count of non-skipped results that did not pass.Skipped int: Count of skipped results.
Service
struct
Core service that owns managed processes and registers action handlers.
Fields:
*core.ServiceRuntime[Options]: Embedded Core runtime used for lifecycle hooks and access toCore().
Options
struct
Service configuration.
Fields:
BufferSize int: Ring-buffer capacity for captured output.Registercurrently initializes this fromDefaultBufferSize.
Status
type Status string
Named lifecycle-state type for a managed process.
Exported values:
StatusPending: queued but not started.StatusRunning: currently executing.StatusExited: completed and waited.StatusFailed: start or wait failure state.StatusKilled: terminated by signal.
Stream
type Stream string
Named output-stream discriminator for process output events.
Exported values:
StreamStdout: stdout line.StreamStderr: stderr line.
RunOptions
struct
Execution settings accepted by Service.StartWithOptions and Service.RunWithOptions.
Fields:
Command string: Executable name. Required by both start and run paths.Args []string: Command arguments.Dir string: Working directory.Env []string: Additional environment entries appended to the command environment.DisableCapture bool: Disables the managed-process ring buffer when true.Detach bool: Starts the child in a separate process group and replaces the parent context withcontext.Background().Timeout time.Duration: Optional watchdog timeout that callsShutdownafter the duration elapses.GracePeriod time.Duration: Delay betweenSIGTERMand fallback kill inShutdown.KillGroup bool: Requests process-group termination. The current service only enables this whenDetachis also true.
ProcessInfo
struct
Serializable snapshot returned by ManagedProcess.Info and Service action lookups.
Fields:
ID string: Managed-process identifier.Command string: Executable name.Args []string: Command arguments.Dir string: Working directory.StartedAt time.Time: Start timestamp.Running bool: Convenience boolean derived fromStatus.Status Status: Current lifecycle state.ExitCode int: Exit status.Duration time.Duration: Runtime duration.PID int: Child PID, or0if no process handle is available.
Info
type alias of ProcessInfo
Compatibility alias that exposes the same fields as ProcessInfo.
Functions
Package Functions
func Register(c *core.Core) core.Result: Builds aServicewith a freshcore.Registry[*ManagedProcess], sets the buffer size toDefaultBufferSize, and returns the service inResult.Value.func NewRingBuffer(size int) *RingBuffer: Allocates a fixed-capacity ring buffer of exactlysizebytes.func NewDaemon(opts DaemonOptions) *Daemon: NormalizesShutdownTimeout, creates optionalPIDFileandHealthServerhelpers, and attaches any configured health checks.func NewHealthServer(addr string) *HealthServer: Returns a health server with the supplied listen address and readiness initialized totrue.func WaitForHealth(addr string, timeoutMs int) bool: Pollshttp://<addr>/healthevery 200 ms until it gets HTTP 200 or the timeout expires.func NewPIDFile(path string) *PIDFile: Returns a PID-file manager forpath.func ReadPID(path string) (int, bool): Reads and parses a PID file, then uses signal0to report whether that PID is still alive.func NewRegistry(dir string) *Registry: Returns a daemon registry rooted atdir.func DefaultRegistry() *Registry: Returns a registry at~/.core/daemons, falling back to the OS temp directory if the home directory cannot be resolved.func NewRunner(svc *Service) *Runner: Returns a runner bound to a specificService.
RingBuffer Methods
func (rb *RingBuffer) Write(p []byte) (n int, err error): Appends bytes one by one, advancing the circular window and overwriting the oldest bytes when capacity is exceeded.func (rb *RingBuffer) String() string: Returns the current buffer contents in logical order as a string.func (rb *RingBuffer) Bytes() []byte: Returns a copied byte slice of the current logical contents, ornilwhen the buffer is empty.func (rb *RingBuffer) Len() int: Returns the number of bytes currently retained.func (rb *RingBuffer) Cap() int: Returns the configured capacity.func (rb *RingBuffer) Reset(): Clears the buffer indexes and full flag.
Daemon Methods
func (d *Daemon) Start() error: Acquires the PID file, starts the health server, marks the daemon running, and auto-registers it whenRegistryis configured. If a later step fails, it rolls back earlier setup.func (d *Daemon) Run(ctx context.Context) error: Requires a started daemon, waits forctx.Done(), and then callsStop.func (d *Daemon) Stop() error: Sets readiness false, shuts down the health server, releases the PID file, unregisters the daemon, and joins health or PID teardown errors withcore.ErrorJoin.func (d *Daemon) SetReady(ready bool): Forwards readiness changes to the health server when one exists.func (d *Daemon) HealthAddr() string: Returns the bound health-server address or""when health endpoints are disabled.
HealthServer Methods
func (h *HealthServer) AddCheck(check HealthCheck): Appends a health-check callback under lock.func (h *HealthServer) SetReady(ready bool): Updates the readiness flag used by/ready.func (h *HealthServer) Start() error: Installs/healthand/readyhandlers, listens onaddr, stores the listener andhttp.Server, and serves in a goroutine.func (h *HealthServer) Stop(ctx context.Context) error: CallsShutdownon the underlyinghttp.Serverwhen started; otherwise returnsnil.func (h *HealthServer) Addr() string: Returns the actual bound listener address afterStart, or the configured address before startup.
PIDFile Methods
func (p *PIDFile) Acquire() error: Rejects a live existing PID file, deletes stale state, creates the parent directory when needed, and writes the current process ID.func (p *PIDFile) Release() error: Deletes the PID file.func (p *PIDFile) Path() string: Returns the configured PID-file path.
ManagedProcess Methods
func (p *ManagedProcess) Info() ProcessInfo: Returns a snapshot containing public fields plus the current child PID.func (p *ManagedProcess) Output() string: Returns captured output as a string, or""when capture is disabled.func (p *ManagedProcess) OutputBytes() []byte: Returns captured output as bytes, ornilwhen capture is disabled.func (p *ManagedProcess) IsRunning() bool: Reports running state by checking whether thedonechannel has closed.func (p *ManagedProcess) Wait() error: Blocks for completion and then returns a wrapped error for failed-start, killed, or non-zero-exit outcomes.func (p *ManagedProcess) Done() <-chan struct{}: Returns the completion channel.func (p *ManagedProcess) Kill() error: SendsSIGKILLto the child, or to the entire process group when group killing is enabled.func (p *ManagedProcess) Shutdown() error: SendsSIGTERM, waits for the configured grace period, and falls back toKill. With no grace period configured, it immediately callsKill.func (p *ManagedProcess) SendInput(input string) error: Writes to the child's stdin pipe while the process is running.func (p *ManagedProcess) CloseStdin() error: Closes the stdin pipe and clears the stored handle.func (p *ManagedProcess) Signal(sig os.Signal) error: Sends an arbitrary signal while the process is inStatusRunning.
Program Methods
func (p *Program) Find() error: ResolvesNamethroughexec.LookPath, stores the absolute path inPath, and wrapsErrProgramNotFoundwhen lookup fails.func (p *Program) Run(ctx context.Context, args ...string) (string, error): Executes the program in the current working directory by delegating toRunDir("", args...).func (p *Program) RunDir(ctx context.Context, dir string, args ...string) (string, error): Runs the program with combined stdout/stderr capture, trims the combined output, and returns that output even when the command fails.
Registry Methods
func (r *Registry) Register(entry DaemonEntry) error: Ensures the registry directory exists, defaultsStartedwhen zero, marshals the entry with the package's JSON writer, and writes one<code>-<daemon>.jsonfile.func (r *Registry) Unregister(code, daemon string) error: Deletes the registry file for the supplied daemon key.func (r *Registry) Get(code, daemon string) (*DaemonEntry, bool): Reads one entry, prunes invalid or stale files, and returns(nil, false)when the daemon is missing or dead.func (r *Registry) List() ([]DaemonEntry, error): Lists all JSON files in the registry directory, prunes invalid or stale entries, and returns only live daemons. A missing registry directory returnsnil, nil.
RunResult and RunAllResult Methods
func (r RunResult) Passed() bool: Returns true only when the result is not skipped, has noError, and hasExitCode == 0.func (r RunAllResult) Success() bool: Returns true whenFailed == 0, regardless of skipped count.
Runner Methods
func (r *Runner) RunAll(ctx context.Context, specs []RunSpec) (*RunAllResult, error): Executes dependency-aware waves of specs, skips dependents after failing required dependencies, and marks circular or missing dependency sets as failed results withExitCode1.func (r *Runner) RunSequential(ctx context.Context, specs []RunSpec) (*RunAllResult, error): Runs specs in order and marks remaining specs skipped after the first disallowed failure.func (r *Runner) RunParallel(ctx context.Context, specs []RunSpec) (*RunAllResult, error): Runs all specs concurrently and aggregates counts after all goroutines finish.
Service Methods
func (s *Service) OnStartup(ctx context.Context) core.Result: Registers the Core actionsprocess.run,process.start,process.kill,process.list, andprocess.get.func (s *Service) OnShutdown(ctx context.Context) core.Result: Iterates all managed processes and callsKillon each one.func (s *Service) Start(ctx context.Context, command string, args ...string) core.Result: Convenience wrapper that buildsRunOptionsand delegates toStartWithOptions.func (s *Service) StartWithOptions(ctx context.Context, opts RunOptions) core.Result: Starts a managed process, configures pipes, optional capture, detach and timeout behavior, stores it in the registry, emitsActionProcessStarted, streams stdout/stderr lines, and emitsActionProcessExitedafter completion.func (s *Service) Get(id string) (*ManagedProcess, error): Returns one managed process orErrProcessNotFound.func (s *Service) List() []*ManagedProcess: Returns all managed processes currently stored in the service registry.func (s *Service) Running() []*ManagedProcess: Returns only processes whosedonechannel has not closed yet.func (s *Service) Kill(id string) error: Kills the managed process by ID and emitsActionProcessKilled.func (s *Service) Remove(id string) error: Deletes a completed process from the registry and rejects removal while it is still running.func (s *Service) Clear(): Deletes every completed process from the registry.func (s *Service) Output(id string) (string, error): Returns the managed process's captured output.func (s *Service) Run(ctx context.Context, command string, args ...string) core.Result: Convenience wrapper aroundRunWithOptions.func (s *Service) RunWithOptions(ctx context.Context, opts RunOptions) core.Result: Executes an unmanaged one-shot command withCombinedOutput. On success it returns the output string inValue; on failure it returns a wrapped error inValueand setsOKfalse.