run

package
v1.23.3 Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2023 License: MPL-2.0 Imports: 53 Imported by: 0

Documentation

Overview

Package run starts and tracks running Encore applications.

Index

Constants

View Source
const TestHeaderDisablePlatformAuth = "X-Encore-Test-Disable-Platform-Auth"

Variables

This section is empty.

Functions

func AsErrorList added in v1.21.0

func AsErrorList(err error) *errlist.List

func GenID added in v1.8.0

func GenID() string

GenID generates a random run/process id. It panics if it cannot get random bytes.

func IgnoreEvents added in v1.11.0

func IgnoreEvents(events []watcher.Event) bool

IgnoreEvents will return true if _all_ events are on files that should be ignored as the do not impact the running app, or are the result of Encore itself generating code.

Types

type CheckParams added in v1.14.5

type CheckParams struct {
	// App is the app to start.
	App *apps.Instance

	// WorkingDir is the working dir, for formatting
	// error messages with relative paths.
	WorkingDir string

	// CodegenDebug, if true, specifies to keep the output
	// around for codegen debugging purposes.
	CodegenDebug bool

	// Environ are the environment variables to set,
	// in the same format as os.Environ().
	Environ []string

	// Tests specifies whether to parse and codegen for tests as well.
	Tests bool
}

type EventListener

type EventListener interface {
	// OnStart is called when a run starts.
	OnStart(r *Run)
	// OnReload is called when a run reloads.
	OnReload(r *Run)
	// OnStop is called when a run stops.
	OnStop(r *Run)
	// OnStdout is called when a run outputs something on stdout.
	OnStdout(r *Run, out []byte)
	// OnStderr is called when a run outputs something on stderr.
	OnStderr(r *Run, out []byte)
	// OnError is called when a run encounters an error.
	OnError(r *Run, err *errlist.List)
}

EventListener is the interface for listening to events about running apps.

type ExecScriptParams added in v1.11.0

type ExecScriptParams struct {
	// App is the app to execute the script for.
	App *apps.Instance

	// NS is the namespace to use.
	NS *namespace.Namespace

	// MainPkg is the package path to the command to execute.
	MainPkg paths.Pkg

	// ScriptArgs are the arguments to pass to the script binary.
	ScriptArgs []string

	// WorkingDir is the working dir to execute the script from.
	// It's relative to the app root.
	WorkingDir string

	// Environ are the environment variables to set when running the tests,
	// in the same format as os.Environ().
	Environ []string

	// Stdout and Stderr are where "go test" output should be written.
	Stdout, Stderr io.Writer

	OpTracker *optracker.OpTracker
}

ExecScriptParams groups the parameters for the ExecScript method.

type ListenAddresses added in v1.21.2

type ListenAddresses struct {
	Gateway  SvcNetCfg            // The entrypoint to the application
	Services map[string]SvcNetCfg // Map from service name to listen address
}

ListenAddresses is a list of listen address and port numbers for services to run on

func GenerateListenAddresses added in v1.21.2

func GenerateListenAddresses(proxy *svcproxy.SvcProxy, serviceList []*meta.Service) (*ListenAddresses, error)

GenerateListenAddresses generates a list of port numbers for services to run on given a list of metadata for an application.

The port numbers will be randomly generated and are guaranteed to be free at the time this function is run (which might not be the cause when the service starts up!)

func (*ListenAddresses) GenerateServiceDiscoveryMap added in v1.21.2

func (la *ListenAddresses) GenerateServiceDiscoveryMap(serviceList []*meta.Service, authMethod string) (map[string]config.Service, error)

GenerateServiceDiscoveryMap generates a map of service names to their listen addresses

type Manager

type Manager struct {
	RuntimePort int // port for Encore runtime
	DBProxyPort int // port for sqldb proxy
	DashPort    int // port for dev dashboard
	Secret      *secret.Manager
	ClusterMgr  *sqldb.ClusterManager
	// contains filtered or unexported fields
}

Manager manages the set of running applications.

func (*Manager) AddListener

func (mgr *Manager) AddListener(ln EventListener)

AddListener adds an event listener to mgr. It must be called before starting the first run.

func (*Manager) CanDeleteNamespace added in v1.23.0

func (m *Manager) CanDeleteNamespace(ctx context.Context, app *apps.Instance, ns *namespace.Namespace) error

CanDeleteNamespace implements namespace.DeletionHandler.

func (*Manager) Check

func (mgr *Manager) Check(ctx context.Context, p CheckParams) (buildDir string, err error)

Check checks the app for errors. It reports a buildDir (if available) when codegenDebug is true.

func (*Manager) DeleteNamespace added in v1.23.0

func (m *Manager) DeleteNamespace(ctx context.Context, app *apps.Instance, ns *namespace.Namespace) error

DeleteNamespace implements namespace.DeletionHandler.

func (*Manager) ExecScript added in v1.11.0

func (mgr *Manager) ExecScript(ctx context.Context, p ExecScriptParams) (err error)

ExecScript executes the script.

func (*Manager) FindProc

func (mgr *Manager) FindProc(procID string) *ProcGroup

FindProc finds the proc with the given id. It reports nil if no such proc was found.

func (*Manager) FindRunByAppID

func (mgr *Manager) FindRunByAppID(appID string) *Run

FindRunByAppID finds the run with the given app id. It reports nil if no such run was found.

func (*Manager) ListRuns

func (mgr *Manager) ListRuns() []*Run

ListRuns provides a snapshot of all runs.

func (*Manager) RunError added in v1.8.0

func (mgr *Manager) RunError(r *Run, err *errlist.List)

func (*Manager) RunStderr added in v1.8.0

func (mgr *Manager) RunStderr(r *Run, out []byte)

func (*Manager) RunStdout added in v1.8.0

func (mgr *Manager) RunStdout(r *Run, out []byte)

func (*Manager) Start

func (mgr *Manager) Start(ctx context.Context, params StartParams) (run *Run, err error)

Start starts the application. Its lifetime is bounded by ctx.

func (*Manager) Test

func (mgr *Manager) Test(ctx context.Context, params TestParams) (err error)

Test runs the tests.

type NewProcParams added in v1.21.2

type NewProcParams struct {
	BinPath string   // The path to the binary to run
	Environ []string // The base environment to run the process with
}

type Proc

type Proc struct {

	// The following fields are only valid after Start() has been called.
	Started   atomic.Bool // whether the process has started
	StartedAt time.Time   // when the process started
	Pid       int         // the OS process id
	// contains filtered or unexported fields
}

Proc represents a single Encore process running within a ProcGroup.

func (*Proc) Close added in v1.8.0

func (p *Proc) Close()

Close closes the process and waits for it to exit. It is safe to call Close multiple times.

func (*Proc) Kill added in v1.21.1

func (p *Proc) Kill()

Kill causes the Process to exit immediately. Kill does not wait until the Process has actually exited. This only kills the Process itself, not any other processes it may have started.

func (*Proc) ProxyReq added in v1.21.2

func (p *Proc) ProxyReq(w http.ResponseWriter, req *http.Request)

ProxyReq proxies the request to the Encore app.

func (*Proc) Start added in v1.21.1

func (p *Proc) Start() error

Start starts the process and returns immediately.

If the process has already been started, this is a no-op.

type ProcGroup added in v1.21.1

type ProcGroup struct {
	ID          string           // unique process id
	Run         *Run             // the run the process belongs to
	Meta        *meta.Data       // app metadata snapshot
	Experiments *experiments.Set // enabled experiments

	Gateway  *Proc            // the API gateway process
	Services map[string]*Proc // all the service processes by name

	EnvGenerator *RuntimeEnvGenerator // generates runtime environment variables
	// contains filtered or unexported fields
}

ProcGroup represents a running Encore application

It is a collection of Proc's that are all part of the same application, where each Proc represents a one or more services or a API gateway.

func (*ProcGroup) Close added in v1.21.1

func (pg *ProcGroup) Close()

Close closes the process and waits for it to shutdown. It can safely be called multiple times.

func (*ProcGroup) Done added in v1.21.1

func (pg *ProcGroup) Done() <-chan struct{}

Done returns a channel that is closed when all processes in the group have exited.

func (*ProcGroup) Kill added in v1.21.2

func (pg *ProcGroup) Kill()

Kill kills all the processes in the group. It does not wait for them to exit.

func (*ProcGroup) NewAllInOneProc added in v1.21.1

func (pg *ProcGroup) NewAllInOneProc(params *NewProcParams) error

func (*ProcGroup) NewProcForGateway added in v1.21.2

func (pg *ProcGroup) NewProcForGateway(listenAddr netip.AddrPort, params *NewProcParams) error

func (*ProcGroup) NewProcForService added in v1.21.2

func (pg *ProcGroup) NewProcForService(service *meta.Service, listenAddr netip.AddrPort, params *NewProcParams) error

func (*ProcGroup) Start added in v1.21.2

func (pg *ProcGroup) Start() (err error)

Start starts all the processes in the group.

func (*ProcGroup) SymTable added in v1.21.1

func (pg *ProcGroup) SymTable(ctx context.Context) (*sym.Table, error)

SymTable waits for the proc's symbol table to be parsed and then returns it. ctx is used to cancel the wait.

func (*ProcGroup) Warnings added in v1.21.2

func (pg *ProcGroup) Warnings() (rtn []warning)

type Run

type Run struct {
	ID              string // unique ID for this instance of the running app
	App             *apps.Instance
	ListenAddr      string // the address the app is listening on
	SvcProxy        *svcproxy.SvcProxy
	ResourceManager *infra.ResourceManager
	NS              *namespace.Namespace

	Mgr *Manager
	// contains filtered or unexported fields
}

Run represents a running Encore application.

func (*Run) Close added in v1.21.2

func (r *Run) Close()

func (*Run) Done

func (r *Run) Done() <-chan struct{}

Done returns a channel that is closed when the run is closed.

func (*Run) ProcGroup added in v1.21.1

func (r *Run) ProcGroup() *ProcGroup

ProcGroup returns the current running process. It may have already exited. If the proc has not yet started it may return nil.

func (*Run) Reload

func (r *Run) Reload() error

Reload rebuilds the app and, if successful, starts a new proc and switches over.

func (*Run) ServeHTTP

func (r *Run) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP implements http.Handler by forwarding the request to the currently running process.

func (*Run) StartProcGroup added in v1.21.1

func (r *Run) StartProcGroup(params *StartProcGroupParams) (p *ProcGroup, err error)

StartProcGroup starts a single actual OS process for app.

func (*Run) StoreProc added in v1.8.0

func (r *Run) StoreProc(p *ProcGroup)

type RunLogger added in v1.10.0

type RunLogger interface {
	RunStdout(r *Run, line []byte)
	RunStderr(r *Run, line []byte)
}

RunLogger is the interface for listening to run logs. The log methods are called for each logline on stdout and stderr respectively.

type RuntimeEnvGenerator added in v1.21.2

type RuntimeEnvGenerator struct {

	// The application to generate the config for
	App interface {
		PlatformID() string
		PlatformOrLocalID() string
		GlobalCORS() (appfile.CORS, error)
	}

	// The infra manager to use
	InfraManager interface {
		SQLConfig(db *meta.SQLDatabase) (config.SQLServer, config.SQLDatabase, error)
		PubSubTopicConfig(topic *meta.PubSubTopic) (config.PubsubProvider, config.PubsubTopic, error)
		PubSubSubscriptionConfig(topic *meta.PubSubTopic, sub *meta.PubSubTopic_Subscription) (config.PubsubSubscription, error)
		RedisConfig(redis *meta.CacheCluster) (config.RedisServer, config.RedisDatabase, error)
	}

	// Data from the build which is required
	Meta       *meta.Data        // The metadata for the build
	Secrets    map[string]string // All the secrets for the application
	SvcConfigs map[string]string // All the compiled service configs for the application

	// General data about the application
	AppID           option.Option[string]                 // The ID of the application (if not set defaults to the local or platform ID)
	EnvID           option.Option[string]                 // The ID of the environment (if not set defaults to "local")
	EnvName         option.Option[string]                 // The name of the environment (if not set defaults to "local")
	EnvType         option.Option[encore.EnvironmentType] // The type of the environment (if not set defaults to the development environment type)
	CloudType       option.Option[encore.CloudProvider]   // The cloud type (if not set defaults to the local cloud type)
	TraceEndpoint   option.Option[string]                 // The endpoint to send trace data to (if not set defaults to none)
	ServiceAuthType option.Option[string]                 // Auth type to use for service to service calls (defaults to "encore-auth")
	AuthKey         option.Option[config.EncoreAuthKey]   // The auth key to use for service to service calls (if not set generates one on init)
	MetricsConfig   option.Option[*config.Metrics]        // The metrics config to use (if not set defaults to none)

	// Shutdown Timings
	GracefulShutdownTime option.Option[time.Duration] // The total time the application is given to shutdown gracefully
	ShutdownHooksGrace   option.Option[time.Duration] // The duration before GracefulShutdownTime that shutdown hooks are given to complete
	HandlersGrace        option.Option[time.Duration] // The duration before GracefulShutdownTime that handlers are given to complete

	// Data about this specific run
	DaemonProxyAddr option.Option[netip.AddrPort] // The address of the daemon proxy (if not set defaults to the gateway address in ListenAddresses)
	ListenAddresses *ListenAddresses              // The listen addresses for the application
	// contains filtered or unexported fields
}

func (*RuntimeEnvGenerator) ForAllInOne added in v1.22.0

func (g *RuntimeEnvGenerator) ForAllInOne(listenAddr netip.AddrPort) ([]string, error)

ForAllInOne generates the runtime environmental variables required for the build to startup and run as an all-in-one service

This service will have CORs enabled as is not behind a gateway

func (*RuntimeEnvGenerator) ForGateway added in v1.21.2

func (g *RuntimeEnvGenerator) ForGateway(listenAddr netip.AddrPort, hostNames ...string) ([]string, error)

ForGateway generates the runtime environmental variables required for the build to startup and run as an API gateway for the given host names

The gateway will have CORs enabled and respond to CORs requests directly.

func (*RuntimeEnvGenerator) ForServices added in v1.21.2

func (g *RuntimeEnvGenerator) ForServices(listenAddr netip.AddrPort, services ...*meta.Service) ([]string, error)

ForServices generates the runtime environmental variables required for the build to startup and run the given service(s)

These services will not have CORs enabled as they should be behind a gateway

type StartParams

type StartParams struct {
	// App is the app to start.
	App *apps.Instance

	// NS is the namespace to use.
	NS *namespace.Namespace

	// WorkingDir is the working dir, for formatting
	// error messages with relative paths.
	WorkingDir string

	// Watch enables watching for code changes for live reloading.
	Watch bool

	Listener   net.Listener // listener to use
	ListenAddr string       // address we're listening on

	// Environ are the environment variables to set for the running app,
	// in the same format as os.Environ().
	Environ []string

	// The Ops tracker being used for this run
	OpsTracker *optracker.OpTracker

	// Debug specifies to compile the application for debugging.
	Debug bool
}

StartParams groups the parameters for the Run method.

type StartProcGroupParams added in v1.21.1

type StartProcGroupParams struct {
	Ctx            context.Context
	BuildDir       string
	BinPath        string
	Meta           *meta.Data
	Secrets        map[string]string
	ServiceConfigs map[string]string
	Logger         RunLogger
	Environ        []string
	WorkingDir     string
	Experiments    *experiments.Set
}

type SvcNetCfg added in v1.21.2

type SvcNetCfg struct {
	BaseURL    string         // The base URL that other services should use to connect to this service
	ListenAddr netip.AddrPort // The address:port that this service should listen on
}

type TestParams

type TestParams struct {
	// App is the app to test.
	App *apps.Instance

	// NS is the namespace to use.
	NS *namespace.Namespace

	// WorkingDir is the working dir, for formatting
	// error messages with relative paths.
	WorkingDir string

	// Secrets are the secrets to use.
	Secrets *secret.LoadResult

	// Args are the arguments to pass to "go test".
	Args []string

	// Environ are the environment variables to set when running the tests,
	// in the same format as os.Environ().
	Environ []string

	// CodegenDebug, if true, specifies to keep the output
	// around for codegen debugging purposes.
	CodegenDebug bool

	// Stdout and Stderr are where "go test" output should be written.
	Stdout, Stderr io.Writer
}

TestParams groups the parameters for the Test method.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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