github.com/rotari-dev/rotari/internal/server

Overview

package server // import "github.com/rotari-dev/rotari/internal/server"

Package server implements the background server's transport and lifetime.

It owns operation names, request and response wire shapes, the pipes that
connect a run client to the supervisor it starts, the server lease and
the liveness check built on it, request dispatch, active-run tracking,
idle shutdown, the synchronous-run detach and disconnect protocol, and the
client side of that protocol. The project work behind each request is supplied
through Operations; this package should not own persisted project state,
run orchestration, or CLI formatting.

Constants

const (
	DisconnectActionDetach = "detach"
	DisconnectActionCancel = "cancel"
)
const DetachedMessage = "Run detached; it continues in the background."
    DetachedMessage reports a synchronous run that was detached from its client.

const OpRun = "run"
    OpRun is the only request: the run a supervisor was started for.

const ProtocolVersion = 13
    ProtocolVersion is reported by Ready. A `run` client talks only to the
    supervisor it started from its own executable, so the version is for
    diagnosis rather than negotiation.

Variables

var ErrAlreadyRunning = errors.New("server is already running")
    ErrAlreadyRunning reports that another supervisor holds the project's lease.

var ErrRunAlreadyStarted = errors.New("this supervisor has already started a run")
    ErrRunAlreadyStarted rejects a second run request to one supervisor.

Functions

func Acquire(dir string, fileMode os.FileMode) (func(), error)
    Acquire takes the lease of dir, a project directory, and records the
    supervisor PID. The returned function releases them. It fails with
    ErrAlreadyRunning while another supervisor holds the lease.

func InheritedConn() (io.ReadWriteCloser, error)
    InheritedConn returns the connection to the run client that started this
    supervisor with Start. The descriptors are closed on exec so that jobs do
    not hold the client's pipes open.

func IsKnownOperation(op string) bool
func LockPath(dir string) string
    LockPath is the lease file of the supervisor of dir, a project directory.

func PIDPath(dir string) string
    PIDPath records the PID of the supervisor of dir while it runs.

func Pipe() (client, server io.ReadWriteCloser, err error)
    Pipe returns the two ends of a connection within one process, for a
    supervisor served in the same process as its client.

func Ready(conn io.Writer, err error) error
    Ready tells the run client on conn that the supervisor holds its project's
    lease and waits for the run request, or why it could not start. It is the
    first message of every connection.

func Running(dir string) (int, bool)
    Running reports whether a supervisor holds the lease of dir, a project
    directory, and its recorded PID, which is 0 while it is being written.
    It never creates the lease file.

func Withdraw(dir string) error
    Withdraw removes the PID record of dir's supervisor, whose run has ended,
    before the run lock is removed and the run's clients return. The supervisor
    keeps its lease until it exits, and a supervisor starting meanwhile waits
    for it instead of reporting that a run is starting or running.

Types

type Client struct {

	// PID is the supervisor's PID, from its Ready message.
	PID int
	// Has unexported fields.
}
    Client is a run client's connection to the supervisor it started. It carries
    one run request.

func Connect(conn io.ReadWriteCloser, timeout time.Duration) (*Client, error)
    Connect waits for the Ready message on conn. It fails with ErrAlreadyRunning
    when another supervisor holds the project's lease, and closes conn on any
    failure.

func Start(command []string, logPath string) (*Client, error)
    Start starts command as a supervisor and returns the connection to it
    once it holds its project's lease. The supervisor is detached from the
    caller's terminal session but inherits the caller's working directory and
    environment, which its run's jobs then inherit in turn. Start never reuses
    a running supervisor: it fails with ErrAlreadyRunning when another one holds
    the lease. logPath names the log that explains a failed start.

func (client *Client) AcceptRun(request Request) (Response, error)
    AcceptRun sends a synchronous run request and reads its startup acceptance
    (or rejection). Subsequent progress and control use the shared filesystem
    follower, not the startup pipe.

func (client *Client) Close() error
    Close closes the startup connection. After acceptance, closing this
    connection is normal and does not control or cancel the run.

func (client *Client) Send(request Request) (Response, error)
    Send sends a request that is answered with one response, such as an
    asynchronous run, and closes the connection.

type Logger struct {
	Path     string
	FileMode os.FileMode
	MaxBytes int64
	// Prefix, if set, starts every event, so the supervisors of several
	// projects can share one log.
	Prefix string
	// Has unexported fields.
}

func (logger *Logger) Writef(format string, args ...any)

type Operations interface {
	// StartRun starts an asynchronous run and calls onDone once it ends. It
	// returns the new run's ID and the message for the client.
	StartRun(request Request, onDone func()) (runID, message string, err error)
	// Run executes a synchronous run, reporting progress as it goes.
	Run(request Request, progress func(Response)) (message string, exitCode int, err error)
}
    Operations performs the project work behind server requests. The server owns
    the transport, active-run bookkeeping, and its own lifetime.

type Request struct {
	Op               string                  `json:"op"`
	QueueName        string                  `json:"project_name,omitempty"`
	LocalConcurrency int                     `json:"local_concurrency,omitempty"`
	BatchMaxActive   int                     `json:"batch_max_active,omitempty"`
	ExecutorSettings executor.RunSettingsMap `json:"executor_settings,omitempty"`
	Retry            int                     `json:"retry,omitempty"`
	RunName          string                  `json:"run_name,omitempty"`
	// Note is why the run is made, recorded as its first note.
	Note             string                    `json:"note,omitempty"`
	CWD              string                    `json:"cwd,omitempty"`
	ConfigPath       string                    `json:"config_path,omitempty"`
	FileConfig       *model.FileConfigSnapshot `json:"file_config,omitempty"`
	Async            bool                      `json:"async,omitempty"`
	DisconnectAction string                    `json:"disconnect_action,omitempty"`
	ClientSessionID  string                    `json:"client_session_id,omitempty"`
	// HintLocation is how the requesting CLI renders the location options of
	// commands it prints for this project (CLI-22); empty names --basedir.
	HintLocation string `json:"hint_location,omitempty"`
	// LaunchOrigin is the process that ran the requesting rotari command.
	LaunchOrigin *model.LaunchOrigin `json:"launch_origin,omitempty"`
	// StartedBy is the interface and actor label of the requester.
	StartedBy       *model.StartedBy `json:"started_by,omitempty"`
	Quiet           bool             `json:"quiet,omitempty"`
	Executor        string           `json:"executor,omitempty"`
	ExecutorOptions []string         `json:"executor_options,omitempty"`
	EnvMode         string           `json:"env_mode,omitempty"`
	JobIDs          []string         `json:"job_ids,omitempty"`
	Selection       string           `json:"selection,omitempty"`
	// ScopeStage and ScopeMatrix narrow Selection to one stage or matrix, and
	// Filter narrows it further.
	ScopeStage   string           `json:"scope_stage,omitempty"`
	ScopeMatrix  string           `json:"scope_matrix,omitempty"`
	Filter       jobfilter.Filter `json:"filter"`
	SourceRunID  string           `json:"source_run_id,omitempty"`
	SourcePolicy string           `json:"source_policy,omitempty"`
	// SourceProject, when it names another project, holds SourceRunID.
	SourceProject string   `json:"source_project,omitempty"`
	CopyAttempts  bool     `json:"copy_attempts,omitempty"`
	CopyJobIDs    []string `json:"copy_job_ids,omitempty"`
	PartialArray  bool     `json:"partial_array,omitempty"`
	MatchBy       string   `json:"match_by,omitempty"`
	// IfRevision, when set, starts the run only if the project is still at
	// this revision; see project.Guard.
	IfRevision string `json:"if_revision,omitempty"`
}

type Response struct {
	OK        bool   `json:"ok"`
	Message   string `json:"message,omitempty"`
	PID       int    `json:"pid,omitempty"`
	Protocol  int    `json:"protocol,omitempty"`
	ExitCode  int    `json:"exit_code,omitempty"`
	Accepted  bool   `json:"accepted,omitempty"`
	Notice    string `json:"notice,omitempty"`
	Progress  bool   `json:"progress,omitempty"`
	JobID     string `json:"job_id,omitempty"`
	Completed int    `json:"completed,omitempty"`
	Total     int    `json:"total,omitempty"`
	Succeeded int    `json:"succeeded,omitempty"`
	Failed    int    `json:"failed,omitempty"`
	// RunID is the run accepted by either a synchronous or asynchronous request.
	RunID string `json:"run_id,omitempty"`
}

type Server struct {
	// Has unexported fields.
}
    Server is the supervisor of one run of one project. It accepts a single run
    request and stops once that run ends, or when it is idle before one arrives.
    A new run starts a new supervisor, so the run's jobs inherit the working
    directory and environment of the command that started it.

func New(ops Operations, logger *Logger) *Server
    New returns a server whose connection is passed to Serve or Handle.

func (server *Server) BeginRun()
    BeginRun records a started run.

func (server *Server) Busy() bool
    Busy reports whether any run is active.

func (server *Server) Done() <-chan struct{}
    Done is closed when the server stops.

func (server *Server) EndRun()
    EndRun records a finished run and stops the server after its last run.

func (server *Server) Handle(conn io.ReadWriteCloser)
    Handle serves one connection's request.

func (server *Server) Serve(conn io.ReadWriteCloser)
    Serve serves the run request on conn, the supervisor's only connection,
    and stops the server when the request leaves no run active.

func (server *Server) Stop()
    Stop stops the server; the supervisor process exits once it has.

func (server *Server) Stopped() bool
    Stopped reports whether Stop has been called.

func (server *Server) WatchIdle(interval, timeout time.Duration, heartbeat func())
    WatchIdle stops the server once it has no active runs and no requests for
    timeout. heartbeat, if set, runs on every check.