edge

package
v1.19.0 Latest Latest
Warning

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

Go to latest
Published: May 11, 2026 License: BSD-3-Clause Imports: 44 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultHeartbeatInterval is how often the client sends heartbeats
	DefaultHeartbeatInterval = 30 * time.Second
	// DefaultWriteTimeout is the timeout for write operations
	DefaultWriteTimeout = 10 * time.Second
	// DefaultRequestTimeout is the timeout for executing local requests
	DefaultRequestTimeout = 5 * time.Minute
	// DefaultGRPCRegistrationTimeout bounds how long the agent waits for the
	// manager to acknowledge gRPC tunnel registration before treating it as a
	// failed transport attempt.
	DefaultGRPCRegistrationTimeout = 10 * time.Second
	// DefaultWebSocketPreferenceTTL keeps websocket as the preferred transport
	// for a short period after a successful auto-mode fallback.
	DefaultWebSocketPreferenceTTL = 2 * time.Minute
)
View Source
const (
	// DefaultTunnelPollInterval is how often poll-mode agents should check in.
	DefaultTunnelPollInterval = 2 * time.Second
	// DefaultPollRuntimeTTL is how long a poll check-in is considered fresh for
	// runtime status reporting when no live tunnel is currently open.
	DefaultPollRuntimeTTL = 6 * time.Second
	// DefaultTunnelDemandTTL is how long the manager should keep an edge tunnel
	// marked as required after a user/API request touches the environment.
	DefaultTunnelDemandTTL = 2 * time.Minute

	// TunnelStatusIdle indicates that no reverse tunnel is currently needed.
	TunnelStatusIdle = "IDLE"
	// TunnelStatusRequired indicates that the manager needs the agent to open a tunnel.
	TunnelStatusRequired = "REQUIRED"
	// TunnelStatusActive indicates that the manager still needs the tunnel and it is already open.
	TunnelStatusActive = "ACTIVE"
)
View Source
const (
	// DefaultProxyTimeout is the default timeout for proxied requests
	DefaultProxyTimeout = 5 * time.Minute
	// DefaultTunnelAcquirePollEvery is how frequently the manager checks for a
	// newly activated edge tunnel while waiting for poll mode to connect.
	DefaultTunnelAcquirePollEvery = 100 * time.Millisecond
)
View Source
const (
	HeaderAPIKey        = "X-API-Key" // #nosec G101: header name, not a credential
	HeaderAuthorization = "Authorization"
	HeaderCookie        = "Cookie"
	HeaderAgentToken    = "X-Arcane-Agent-Token" // #nosec G101: header name, not a credential
	HeaderUpgrade       = "Upgrade"
	HeaderConnection    = "Connection"

	ConnectionUpgradeToken = "upgrade"
)
View Source
const (
	// EdgeTransportWebSocket forces WebSocket tunnel transport.
	EdgeTransportWebSocket = "websocket"
	// EdgeTransportGRPC forces gRPC transport without WebSocket fallback.
	EdgeTransportGRPC = "grpc"
	// EdgeTransportPoll uses an HTTP polling control plane with the existing
	// websocket tunnel as an on-demand data plane.
	EdgeTransportPoll = "poll"
	// EdgeTransportAuto preserves the legacy managed tunnel behavior: try gRPC
	// first and fall back to websocket when available.
	EdgeTransportAuto = "auto"

	// EdgeMTLSModeDisabled disables edge tunnel mTLS.
	EdgeMTLSModeDisabled = "disabled"
	// EdgeMTLSModeOptional enables edge tunnel mTLS when certificates are configured.
	EdgeMTLSModeOptional = "optional"
	// EdgeMTLSModeRequired requires a verified client certificate on edge tunnel endpoints
	// when Arcane terminates TLS; external TLS terminators must enforce mTLS before proxying.
	EdgeMTLSModeRequired = "required"
)
View Source
const (
	// TunnelStaleTimeout is how long before a tunnel is considered stale.
	TunnelStaleTimeout = 2 * time.Minute
)

Variables

View Source
var DefaultCommandClient = NewCommandClient()
View Source
var ErrNoActiveAgentTunnel = errors.New("no active edge agent tunnel")

ErrNoActiveAgentTunnel is returned when no active agent tunnel exists for outbound event sync.

Functions

func AdvertisedEdgeCommands added in v1.19.0

func AdvertisedEdgeCommands() []string

func BuildHopByHopHeaders added in v1.17.0

func BuildHopByHopHeaders(respHeader http.Header) map[string]struct{}

func BuildManagerServerTLSConfig added in v1.19.0

func BuildManagerServerTLSConfig(cfg *Config) (*tls.Config, error)

BuildManagerServerTLSConfig returns the manager TLS configuration needed to support optional edge mTLS on the shared Arcane listener.

func BuildWebSocketHeaders added in v1.17.0

func BuildWebSocketHeaders(c *gin.Context, accessToken *string) http.Header

BuildWebSocketHeaders constructs a header set for proxying WebSocket requests to a remote environment, forwarding authentication in the same way as HTTP proxying.

func CopyBodyWithFlush added in v1.17.0

func CopyBodyWithFlush(w http.ResponseWriter, body io.Reader)

CopyBodyWithFlush streams bytes from body to w, flushing when supported. Useful for progress/streaming endpoints where incremental delivery matters.

func CopyRequestHeaders added in v1.17.0

func CopyRequestHeaders(from http.Header, to http.Header, skip map[string]struct{})

func CopyResponseHeaders added in v1.17.0

func CopyResponseHeaders(from http.Header, to http.Header, hop map[string]struct{})

func DefaultTunnelAcquireTimeout added in v1.16.2

func DefaultTunnelAcquireTimeout() time.Duration

DefaultTunnelAcquireTimeout returns a poll-aware wait timeout for acquiring an on-demand edge tunnel.

func DoRequest

func DoRequest(ctx context.Context, envID, method, path string, body []byte) (int, []byte, error)

DoRequest performs an HTTP request through an edge tunnel. This is for service-level calls that need to route through the tunnel. Returns (statusCode, responseBody, error)

func EnsureAgentMTLSAssets added in v1.19.0

func EnsureAgentMTLSAssets(ctx context.Context, cfg *Config) error

EnsureAgentMTLSAssets downloads manager-generated client certificates when edge mTLS is enabled and explicit client cert/key files are not configured.

func GeneratedManagerClientMTLSCertPath added in v1.19.0

func GeneratedManagerClientMTLSCertPath(cfg *Config, envID string) (string, error)

GeneratedManagerClientMTLSCertPath returns the manager-side generated client certificate path for an environment.

func GeneratedManagerMTLSCAPath added in v1.19.0

func GeneratedManagerMTLSCAPath(cfg *Config) (string, error)

GeneratedManagerMTLSCAPath returns the configured or Arcane-managed manager CA path without creating assets.

func GetActiveTunnelTransport

func GetActiveTunnelTransport(envID string) (string, bool)

GetActiveTunnelTransport returns the currently active tunnel transport for an environment.

func GetHopByHopHeaders added in v1.17.0

func GetHopByHopHeaders() map[string]struct{}

func GetSkipHeaders added in v1.17.0

func GetSkipHeaders() map[string]struct{}

func HTTPToWebSocketURL added in v1.17.0

func HTTPToWebSocketURL(url string) string

HTTPToWebSocketURL converts an HTTP(S) URL to WS(S).

func HasActiveTunnel

func HasActiveTunnel(envID string) bool

HasActiveTunnel checks if an environment has an active edge tunnel

func IsInternalTunnelRequest added in v1.19.0

func IsInternalTunnelRequest(ctx context.Context) bool

IsInternalTunnelRequest reports whether a request is being dispatched by the in-process edge tunnel client instead of a real network listener.

func NewManagerHTTPClient added in v1.19.0

func NewManagerHTTPClient(cfg *Config, timeout time.Duration) (*http.Client, error)

NewManagerHTTPClient creates an HTTP client for agent-to-manager requests, applying edge TLS settings when the manager URL uses HTTPS.

func NormalizeEdgeMTLSMode added in v1.19.0

func NormalizeEdgeMTLSMode(value string) string

NormalizeEdgeMTLSMode normalizes edge mTLS config and defaults to disabled.

func NormalizeEdgeTransport

func NormalizeEdgeTransport(value string) string

NormalizeEdgeTransport normalizes transport config and defaults to the legacy managed tunnel auto mode for backwards compatibility.

func PrepareManagerMTLSAssetsWithContext added in v1.19.0

func PrepareManagerMTLSAssetsWithContext(ctx context.Context, cfg *Config) error

PrepareManagerMTLSAssetsWithContext ensures Arcane-managed edge mTLS assets exist when edge mTLS is enabled and no explicit manager CA file is configured.

func ProxyHTTPRequest

func ProxyHTTPRequest(c *gin.Context, tunnel *AgentTunnel, targetPath string)

ProxyHTTPRequest is a helper that proxies a gin context through a tunnel

func ProxyRequest

func ProxyRequest(ctx context.Context, tunnel *AgentTunnel, method, path, query string, headers map[string]string, body []byte) (int, map[string]string, []byte, error)

ProxyRequest sends an HTTP request through an edge tunnel Returns the response status, headers, and body

func ProxyWebSocketRequest

func ProxyWebSocketRequest(c *gin.Context, tunnel *AgentTunnel, targetPath string)

ProxyWebSocketRequest proxies a WebSocket upgrade through an edge tunnel. This handles logs, stats, and other streaming endpoints.

func PublishEventToManager

func PublishEventToManager(event *TunnelEvent) error

PublishEventToManager sends an event from the active agent tunnel to the manager.

func ResolveEdgeCommandName added in v1.19.0

func ResolveEdgeCommandName(method, requestPath string, stream bool) (string, bool)

func SetAgentToken added in v1.17.0

func SetAgentToken(req *http.Request, accessToken *string)

func SetAuthHeader added in v1.17.0

func SetAuthHeader(req *http.Request, c *gin.Context)

func SetDefaultRegistry

func SetDefaultRegistry(registry *TunnelRegistry)

SetDefaultRegistry replaces the process-wide default tunnel registry.

func SetForwardedHeaders added in v1.17.0

func SetForwardedHeaders(req *http.Request, clientIP, host string)

func StartTunnelClientWithErrors

func StartTunnelClientWithErrors(ctx context.Context, cfg *Config, handler http.Handler) (<-chan error, error)

StartTunnelClientWithErrors starts the tunnel client and returns a channel for connection errors.

func StartupLogAttrs added in v1.19.0

func StartupLogAttrs(cfg *Config) []any

func TouchTunnelDemand added in v1.16.2

func TouchTunnelDemand(envID string, ttl time.Duration) time.Time

TouchTunnelDemand marks an edge environment as requiring an on-demand tunnel.

func UseGRPCEdgeTransport

func UseGRPCEdgeTransport(cfg *Config) bool

UseGRPCEdgeTransport reports whether gRPC managed tunnel mode should be attempted.

func UsePollEdgeTransport added in v1.16.2

func UsePollEdgeTransport(cfg *Config) bool

UsePollEdgeTransport reports whether the Portainer-style polling control plane should be used.

func UseWebSocketEdgeTransport

func UseWebSocketEdgeTransport(cfg *Config) bool

UseWebSocketEdgeTransport reports whether websocket managed tunnel mode is allowed.

func ValidateAgentMTLSConfig added in v1.19.0

func ValidateAgentMTLSConfig(cfg *Config) error

ValidateAgentMTLSConfig validates the edge agent TLS configuration before the reverse tunnel client starts.

func ValidateEdgeCommand added in v1.19.0

func ValidateEdgeCommand(commandName, method, requestPath string, stream bool) bool

func ValidateManagerMTLSConfig added in v1.19.0

func ValidateManagerMTLSConfig(cfg *Config) error

ValidateManagerMTLSConfig validates the manager-side mTLS configuration used by edge tunnel endpoints.

Types

type AgentTunnel

type AgentTunnel struct {
	EnvironmentID string
	Conn          TunnelConnection
	Pending       sync.Map // map[string]*PendingRequest
	ConnectedAt   time.Time
	LastHeartbeat time.Time
	SessionID     string
	AgentInstance string
	Transport     string
	SecurityMode  string
	Capabilities  []string
	State         string
	DisconnectErr string
	// contains filtered or unexported fields
}

AgentTunnel represents an active tunnel connection from an edge agent

func GetActiveTunnel added in v1.16.2

func GetActiveTunnel(envID string) (*AgentTunnel, bool)

GetActiveTunnel returns the active tunnel for an environment, if one exists.

func NewAgentTunnelWithConn

func NewAgentTunnelWithConn(envID string, conn TunnelConnection) *AgentTunnel

NewAgentTunnelWithConn creates a new agent tunnel from a transport-agnostic connection.

func RequestTunnelAndWait added in v1.16.2

func RequestTunnelAndWait(ctx context.Context, envID string, demandTTL, timeout time.Duration) (*AgentTunnel, bool)

RequestTunnelAndWait marks an edge environment as needed and waits for the agent to establish a live tunnel.

func WaitForActiveTunnel added in v1.16.2

func WaitForActiveTunnel(ctx context.Context, envID string, timeout time.Duration) (*AgentTunnel, bool)

WaitForActiveTunnel waits for an environment to establish a live tunnel.

func (*AgentTunnel) Close

func (t *AgentTunnel) Close() error

Close closes the tunnel connection

func (*AgentTunnel) CloseWithReason added in v1.19.0

func (t *AgentTunnel) CloseWithReason(reason string) error

CloseWithReason closes the tunnel connection and records the disconnect reason.

func (*AgentTunnel) GetLastHeartbeat

func (t *AgentTunnel) GetLastHeartbeat() time.Time

GetLastHeartbeat returns the last heartbeat time

func (*AgentTunnel) UpdateHeartbeat

func (t *AgentTunnel) UpdateHeartbeat()

UpdateHeartbeat updates the last heartbeat timestamp

type CommandClient added in v1.19.0

type CommandClient struct{}

func NewCommandClient added in v1.19.0

func NewCommandClient() *CommandClient

func (*CommandClient) Execute added in v1.19.0

func (c *CommandClient) Execute(ctx context.Context, tunnel *AgentTunnel, req *CommandRequest) (*CommandResult, error)

func (*CommandClient) OpenStream added in v1.19.0

func (c *CommandClient) OpenStream(ctx context.Context, tunnel *AgentTunnel, req *CommandRequest) error

type CommandRequest added in v1.19.0

type CommandRequest struct {
	ID            string
	Command       string
	Method        string
	Path          string
	Query         string
	Headers       map[string]string
	Body          []byte
	TimeoutMillis int64
}

type CommandResult added in v1.19.0

type CommandResult struct {
	Status  int
	Headers map[string]string
	Body    []byte
}

type Config added in v1.17.0

type Config struct {
	EdgeAgent             bool
	EdgeTransport         string
	EdgeReconnectInterval int
	EdgeMTLSMode          string
	EdgeMTLSCAFile        string
	EdgeMTLSCertFile      string
	EdgeMTLSKeyFile       string
	EdgeMTLSServerName    string
	EdgeMTLSAssetsDir     string
	AppURL                string
	ManagerApiUrl         string
	AgentToken            string
	Port                  string
	Listen                string
}

Config contains the public edge-tunnel runtime settings needed by pkg/libarcane/edge.

func (*Config) GetManagerBaseURL added in v1.17.0

func (c *Config) GetManagerBaseURL() string

GetManagerBaseURL returns the base URL of the manager application. It strips any trailing slashes or /api suffix from MANAGER_API_URL.

func (*Config) GetManagerGRPCAddr added in v1.17.0

func (c *Config) GetManagerGRPCAddr() string

GetManagerGRPCAddr returns the manager gRPC address in host:port form.

type EnrollmentCallback added in v1.19.0

type EnrollmentCallback func(ctx context.Context, environmentID, remoteAddr string, certIssued bool, caGenerated bool, reenrolled bool)

EnrollmentCallback is called after a successful manager-side mTLS enrollment of an edge agent, allowing the host to record audit events or metrics. remoteAddr is the client socket address as seen by the manager. reenrolled is true when an environment that had already enrolled receives assets again after the enrollment cooldown.

type EnvironmentNameResolver added in v1.19.0

type EnvironmentNameResolver func(ctx context.Context, environmentID string) (environmentName string, err error)

EnvironmentNameResolver resolves a display name for an environment ID.

type EnvironmentResolver

type EnvironmentResolver func(ctx context.Context, token string) (environmentID string, err error)

EnvironmentResolver resolves an agent token to an environment ID.

type EventCallback

type EventCallback func(ctx context.Context, environmentID string, event *TunnelEvent) error

EventCallback is called when an edge agent publishes an event.

type GRPCAgentTunnelConn

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

GRPCAgentTunnelConn wraps the agent-side gRPC tunnel stream.

func NewGRPCAgentTunnelConn

func NewGRPCAgentTunnelConn(stream grpcAgentStream, cancelFns ...context.CancelFunc) *GRPCAgentTunnelConn

NewGRPCAgentTunnelConn creates an agent-side gRPC tunnel wrapper.

func (*GRPCAgentTunnelConn) Close

func (t *GRPCAgentTunnelConn) Close() error

Close closes the client send stream.

func (*GRPCAgentTunnelConn) IsClosed

func (t *GRPCAgentTunnelConn) IsClosed() bool

IsClosed returns whether the stream is closed.

func (*GRPCAgentTunnelConn) IsExpectedReceiveError

func (t *GRPCAgentTunnelConn) IsExpectedReceiveError(err error) bool

IsExpectedReceiveError returns true for expected gRPC stream shutdown errors.

func (*GRPCAgentTunnelConn) Receive

func (t *GRPCAgentTunnelConn) Receive() (*TunnelMessage, error)

Receive receives a manager->agent tunnel message from gRPC.

func (*GRPCAgentTunnelConn) Send

func (t *GRPCAgentTunnelConn) Send(msg *TunnelMessage) error

Send sends an agent->manager tunnel message over gRPC.

func (*GRPCAgentTunnelConn) SendRequest

func (t *GRPCAgentTunnelConn) SendRequest(ctx context.Context, msg *TunnelMessage, pending *sync.Map) (*TunnelMessage, error)

SendRequest sends a request and waits for response.

type GRPCManagerTunnelConn

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

GRPCManagerTunnelConn wraps the manager-side gRPC tunnel stream.

func NewGRPCManagerTunnelConn

func NewGRPCManagerTunnelConn(stream grpcManagerStream) *GRPCManagerTunnelConn

NewGRPCManagerTunnelConn creates a manager-side gRPC tunnel wrapper.

func (*GRPCManagerTunnelConn) Close

func (t *GRPCManagerTunnelConn) Close() error

Close marks the stream closed on manager side.

func (*GRPCManagerTunnelConn) IsClosed

func (t *GRPCManagerTunnelConn) IsClosed() bool

IsClosed returns whether the stream is closed.

func (*GRPCManagerTunnelConn) IsExpectedReceiveError

func (t *GRPCManagerTunnelConn) IsExpectedReceiveError(err error) bool

IsExpectedReceiveError returns true for expected gRPC stream shutdown errors.

func (*GRPCManagerTunnelConn) Receive

func (t *GRPCManagerTunnelConn) Receive() (*TunnelMessage, error)

Receive receives an agent->manager tunnel message from gRPC.

func (*GRPCManagerTunnelConn) Send

Send sends a manager->agent tunnel message over gRPC.

func (*GRPCManagerTunnelConn) SendRequest

func (t *GRPCManagerTunnelConn) SendRequest(ctx context.Context, msg *TunnelMessage, pending *sync.Map) (*TunnelMessage, error)

SendRequest sends a request and waits for response.

type GeneratedMTLSAssets added in v1.19.0

type GeneratedMTLSAssets struct {
	Files       []GeneratedMTLSFile `json:"files"`
	HostDirHint string              `json:"hostDirHint"`
	CertIssued  bool                `json:"-"`
	CAGenerated bool                `json:"-"`
	Reenrolled  bool                `json:"-"`
}

GeneratedMTLSAssets contains manager-generated edge client certificates and snippet metadata.

func GenerateManagerClientMTLSAssetsWithContext added in v1.19.0

func GenerateManagerClientMTLSAssetsWithContext(ctx context.Context, cfg *Config, envID string, envName string) (*GeneratedMTLSAssets, error)

GenerateManagerClientMTLSAssetsWithContext creates or loads the generated CA and per-environment client certificate bundle.

type GeneratedMTLSFile added in v1.19.0

type GeneratedMTLSFile struct {
	Name          string `json:"name"`
	Content       string `json:"content"`
	ContainerPath string `json:"containerPath"`
	Permissions   string `json:"permissions"`
}

GeneratedMTLSFile describes a generated file that should be copied to the edge agent host.

type PendingRequest

type PendingRequest struct {
	ResponseCh chan *TunnelMessage
	CreatedAt  time.Time
}

PendingRequest tracks an in-flight request waiting for response.

type PollRuntimeRegistry added in v1.16.2

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

PollRuntimeRegistry tracks recent poll check-ins from edge agents.

func GetPollRuntimeRegistry added in v1.16.2

func GetPollRuntimeRegistry() *PollRuntimeRegistry

GetPollRuntimeRegistry returns the process-wide poll runtime registry.

func NewPollRuntimeRegistry added in v1.16.2

func NewPollRuntimeRegistry() *PollRuntimeRegistry

NewPollRuntimeRegistry creates a new poll runtime registry.

func (*PollRuntimeRegistry) Get added in v1.16.2

func (r *PollRuntimeRegistry) Get(envID string, now time.Time) (PollRuntimeState, bool)

Get returns the most recent poll runtime state if it is still fresh.

func (*PollRuntimeRegistry) Update added in v1.16.2

func (r *PollRuntimeRegistry) Update(envID string, interval time.Duration, now time.Time) PollRuntimeState

Update records a poll check-in for an environment.

type PollRuntimeState added in v1.16.2

type PollRuntimeState struct {
	LastPollAt          *time.Time
	PollIntervalSeconds int
}

PollRuntimeState describes the most recent poll-based control-plane activity observed for an edge environment.

type StatusUpdateCallback

type StatusUpdateCallback func(ctx context.Context, environmentID string, connected bool)

StatusUpdateCallback is called when an edge agent connects or disconnects. The connected parameter is true on connect, false on disconnect.

type TunnelClient

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

TunnelClient represents the agent-side tunnel client

func NewTunnelClient

func NewTunnelClient(cfg *Config, handler http.Handler) *TunnelClient

NewTunnelClient creates a new tunnel client

func (*TunnelClient) StartWithErrorChan

func (c *TunnelClient) StartWithErrorChan(ctx context.Context, errCh chan error)

StartWithErrorChan runs the tunnel client and optionally emits connection errors.

type TunnelConn

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

TunnelConn wraps a WebSocket connection with send/receive helpers.

func NewTunnelConn

func NewTunnelConn(conn *websocket.Conn) *TunnelConn

NewTunnelConn creates a new WebSocket tunnel connection wrapper.

func (*TunnelConn) Close

func (t *TunnelConn) Close() error

Close closes the WebSocket tunnel connection.

func (*TunnelConn) IsClosed

func (t *TunnelConn) IsClosed() bool

IsClosed returns whether the connection is closed.

func (*TunnelConn) IsExpectedReceiveError

func (t *TunnelConn) IsExpectedReceiveError(err error) bool

IsExpectedReceiveError returns true for normal WebSocket close/teardown errors.

func (*TunnelConn) Receive

func (t *TunnelConn) Receive() (*TunnelMessage, error)

Receive receives a tunnel message from the WebSocket connection.

func (*TunnelConn) Send

func (t *TunnelConn) Send(msg *TunnelMessage) error

Send sends a tunnel message over the WebSocket connection.

func (*TunnelConn) SendRequest

func (t *TunnelConn) SendRequest(ctx context.Context, msg *TunnelMessage, pending *sync.Map) (*TunnelMessage, error)

SendRequest sends a request and waits for response.

type TunnelConnection

type TunnelConnection interface {
	Send(msg *TunnelMessage) error
	Receive() (*TunnelMessage, error)
	IsExpectedReceiveError(err error) bool
	Close() error
	IsClosed() bool
	SendRequest(ctx context.Context, msg *TunnelMessage, pending *sync.Map) (*TunnelMessage, error)
}

TunnelConnection is the transport contract shared by WebSocket and gRPC wrappers.

type TunnelDemandRegistry added in v1.16.2

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

TunnelDemandRegistry tracks short-lived tunnel demand on the manager side.

func GetDemandRegistry added in v1.16.2

func GetDemandRegistry() *TunnelDemandRegistry

GetDemandRegistry returns the process-wide tunnel demand registry.

func NewTunnelDemandRegistry added in v1.16.2

func NewTunnelDemandRegistry() *TunnelDemandRegistry

NewTunnelDemandRegistry creates a new tunnel demand registry.

func (*TunnelDemandRegistry) DesiredStatus added in v1.16.2

func (r *TunnelDemandRegistry) DesiredStatus(envID string, hasActiveTunnel bool, now time.Time) string

DesiredStatus returns the desired manager-side tunnel state for an environment.

func (*TunnelDemandRegistry) Touch added in v1.16.2

func (r *TunnelDemandRegistry) Touch(envID string, ttl time.Duration) time.Time

Touch marks an environment as requiring a reverse tunnel for the specified TTL.

type TunnelEvent

type TunnelEvent struct {
	Type         string `json:"type"`
	Severity     string `json:"severity,omitempty"`
	Title        string `json:"title"`
	Description  string `json:"description,omitempty"`
	ResourceType string `json:"resource_type,omitempty"`
	ResourceID   string `json:"resource_id,omitempty"`
	ResourceName string `json:"resource_name,omitempty"`
	UserID       string `json:"user_id,omitempty"`
	Username     string `json:"username,omitempty"`
	MetadataJSON []byte `json:"metadata_json,omitempty"`
}

TunnelEvent is an event payload sent from an agent to the manager.

type TunnelMessage

type TunnelMessage struct {
	ID            string            `json:"id"`                        // Unique request/stream ID
	Type          TunnelMessageType `json:"type"`                      // Message type
	Method        string            `json:"method,omitempty"`          // HTTP method for requests
	Path          string            `json:"path,omitempty"`            // Request path
	Query         string            `json:"query,omitempty"`           // Query string
	Headers       map[string]string `json:"headers,omitempty"`         // HTTP headers
	Body          []byte            `json:"body,omitempty"`            // Request/response body
	WSMessageType int               `json:"ws_message_type,omitempty"` // WebSocket message type
	Status        int               `json:"status,omitempty"`          // HTTP status for responses
	Accepted      bool              `json:"accepted,omitempty"`        // Registration accepted
	AgentToken    string            `json:"agent_token,omitempty"`     // Register request token
	EnvironmentID string            `json:"environment_id,omitempty"`  // Manager-resolved environment ID
	Error         string            `json:"error,omitempty"`           // Error field for register response
	Event         *TunnelEvent      `json:"event,omitempty"`           // Agent event payload
	Command       string            `json:"command,omitempty"`         // Typed command name
	SessionID     string            `json:"session_id,omitempty"`      // Manager-issued session identifier
	ResumeSession string            `json:"resume_session,omitempty"`  // Previous session being resumed
	AgentInstance string            `json:"agent_instance,omitempty"`  // Stable agent runtime identity
	Capabilities  []string          `json:"capabilities,omitempty"`    // Agent advertised capabilities
	SecurityMode  string            `json:"security_mode,omitempty"`   // token, mtls, etc.
	DrainPrevious bool              `json:"drain_previous,omitempty"`  // Replace previous session
	TimeoutMillis int64             `json:"timeout_millis,omitempty"`  // Command timeout
	Sequence      int64             `json:"sequence,omitempty"`        // Chunk sequence number
	Streaming     bool              `json:"streaming,omitempty"`       // Response used chunked output
	Metadata      map[string]string `json:"metadata,omitempty"`        // Correlation and audit metadata
	EOF           bool              `json:"eof,omitempty"`             // Final chunk indicator
}

TunnelMessage represents a transport-agnostic edge tunnel message.

func (*TunnelMessage) MarshalJSON

func (m *TunnelMessage) MarshalJSON() ([]byte, error)

MarshalJSON custom marshaler to handle nil body as empty.

type TunnelMessageType

type TunnelMessageType string

TunnelMessageType represents the type of message sent over the tunnel.

const (
	// MessageTypeRequest is sent from manager to agent to initiate a request.
	MessageTypeRequest TunnelMessageType = "request"
	// MessageTypeResponse is sent from agent to manager with the response.
	MessageTypeResponse TunnelMessageType = "response"
	// MessageTypeHeartbeat is sent by agents to keep the connection alive.
	MessageTypeHeartbeat TunnelMessageType = "heartbeat"
	// MessageTypeHeartbeatAck is sent by manager to acknowledge a heartbeat.
	MessageTypeHeartbeatAck TunnelMessageType = "heartbeat_ack"
	// MessageTypeStreamData is sent for streaming responses (logs, stats).
	MessageTypeStreamData TunnelMessageType = "stream_data"
	// MessageTypeStreamEnd indicates end of a stream.
	MessageTypeStreamEnd TunnelMessageType = "stream_end"
	// MessageTypeWebSocketStart starts a WebSocket stream for logs/stats.
	MessageTypeWebSocketStart TunnelMessageType = "ws_start"
	// MessageTypeWebSocketData is a WebSocket message in either direction.
	MessageTypeWebSocketData TunnelMessageType = "ws_data"
	// MessageTypeWebSocketClose closes a WebSocket stream.
	MessageTypeWebSocketClose TunnelMessageType = "ws_close"
	// MessageTypeRegister is the first message sent by the agent on gRPC transport.
	MessageTypeRegister TunnelMessageType = "register"
	// MessageTypeRegisterResponse is sent by manager after register validation.
	MessageTypeRegisterResponse TunnelMessageType = "register_response"
	// MessageTypeEvent carries an event emitted by an agent to the manager.
	MessageTypeEvent TunnelMessageType = "event"
	// MessageTypeCommandRequest sends a typed edge command from manager to agent.
	MessageTypeCommandRequest TunnelMessageType = "command_request"
	// MessageTypeCommandAck acknowledges a command was accepted by the agent.
	MessageTypeCommandAck TunnelMessageType = "command_ack"
	// MessageTypeCommandOutput carries chunked command output from agent to manager.
	MessageTypeCommandOutput TunnelMessageType = "command_output"
	// MessageTypeCommandComplete indicates final command completion.
	MessageTypeCommandComplete TunnelMessageType = "command_complete"
	// MessageTypeFileChunk carries chunked request or response payload data.
	MessageTypeFileChunk TunnelMessageType = "file_chunk"
	// MessageTypeStreamOpen opens a command-backed stream.
	MessageTypeStreamOpen TunnelMessageType = "stream_open"
	// MessageTypeStreamClose closes a command-backed stream.
	MessageTypeStreamClose TunnelMessageType = "stream_close"
	// MessageTypeCancelRequest requests cancellation of an in-flight command.
	MessageTypeCancelRequest TunnelMessageType = "cancel_request"
)

type TunnelPollRequest added in v1.16.2

type TunnelPollRequest struct {
	Transport string `json:"transport,omitempty"`
	Connected bool   `json:"connected,omitempty"`
}

TunnelPollRequest is a forward-compatible control-plane check-in request.

type TunnelPollResponse added in v1.16.2

type TunnelPollResponse struct {
	Status              string `json:"status"`
	PollIntervalSeconds int    `json:"pollIntervalSeconds"`
	ActiveTransport     string `json:"activeTransport,omitempty"`
	Connected           bool   `json:"connected,omitempty"`
}

TunnelPollResponse is a forward-compatible control-plane response.

type TunnelRegistry

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

TunnelRegistry manages active edge agent tunnel connections

func GetRegistry

func GetRegistry() *TunnelRegistry

GetRegistry returns the global tunnel registry

func NewTunnelRegistry

func NewTunnelRegistry() *TunnelRegistry

NewTunnelRegistry creates a new tunnel registry

func (*TunnelRegistry) CleanupStale

func (r *TunnelRegistry) CleanupStale(maxAge time.Duration) int

CleanupStale removes tunnels that haven't had a heartbeat within the given duration

func (*TunnelRegistry) Get

func (r *TunnelRegistry) Get(envID string) (*AgentTunnel, bool)

Get retrieves a tunnel by environment ID

func (*TunnelRegistry) Register

func (r *TunnelRegistry) Register(envID string, tunnel *AgentTunnel)

Register adds a tunnel to the registry, closing any existing tunnel for the same env

func (*TunnelRegistry) RegisterSession added in v1.19.0

func (r *TunnelRegistry) RegisterSession(tunnel *AgentTunnel, staleAfter time.Duration) (accepted bool, drainPrevious bool, reason string)

RegisterSession adds a tunnel with duplicate-session handling.

func (*TunnelRegistry) Unregister

func (r *TunnelRegistry) Unregister(envID string)

Unregister removes a tunnel from the registry

func (*TunnelRegistry) UnregisterCurrent added in v1.19.0

func (r *TunnelRegistry) UnregisterCurrent(envID string, current *AgentTunnel) (removed bool, activeReplacement bool)

UnregisterCurrent removes the active tunnel only when it still matches the provided tunnel reference. It reports whether the tunnel was removed and whether another active session for the environment is already present.

type TunnelRuntimeState

type TunnelRuntimeState struct {
	Transport     string
	ConnectedAt   *time.Time
	LastHeartbeat *time.Time
	SessionID     string
	AgentInstance string
	SecurityMode  string
	Capabilities  []string
	State         string
}

TunnelRuntimeState describes the live, in-memory state of an active edge tunnel.

func GetTunnelRuntimeState

func GetTunnelRuntimeState(envID string) (*TunnelRuntimeState, bool)

GetTunnelRuntimeState returns live metadata for an active tunnel.

type TunnelServer

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

TunnelServer handles incoming edge agent connections on the manager side.

func NewTunnelServer

func NewTunnelServer(resolver EnvironmentResolver, statusCallback StatusUpdateCallback) *TunnelServer

NewTunnelServer creates a new tunnel server.

func NewTunnelServerWithRegistry

func NewTunnelServerWithRegistry(registry *TunnelRegistry, resolver EnvironmentResolver, statusCallback StatusUpdateCallback) *TunnelServer

NewTunnelServerWithRegistry creates a new tunnel server using an injected tunnel registry.

func (*TunnelServer) Connect

Connect is the gRPC bidi stream handler for edge agent connections.

func (*TunnelServer) GRPCServerOptions

func (s *TunnelServer) GRPCServerOptions(ctx context.Context) []grpc.ServerOption

GRPCServerOptions returns the stream interceptor chain used by the tunnel service.

func (*TunnelServer) HandleConnect

func (s *TunnelServer) HandleConnect(c *gin.Context)

HandleConnect is the WebSocket handler for edge agent connections. This is registered at /api/tunnel/connect.

func (*TunnelServer) HandleMTLSEnroll added in v1.19.0

func (s *TunnelServer) HandleMTLSEnroll(c *gin.Context)

HandleMTLSEnroll returns manager-generated edge client certificates for the calling environment when generated edge mTLS is enabled. The response includes private key material, so response-body logging must not be enabled here.

func (*TunnelServer) HandlePoll added in v1.16.2

func (s *TunnelServer) HandlePoll(c *gin.Context)

HandlePoll is the HTTP control-plane endpoint used by poll-mode agents.

func (*TunnelServer) SetConfig added in v1.19.0

func (s *TunnelServer) SetConfig(cfg *Config)

SetConfig attaches edge tunnel runtime config to the manager-side server.

func (*TunnelServer) SetEnrollmentCallback added in v1.19.0

func (s *TunnelServer) SetEnrollmentCallback(callback EnrollmentCallback)

SetEnrollmentCallback configures the manager callback invoked after a successful edge mTLS enrollment. Passing nil clears the callback.

func (*TunnelServer) SetEnvironmentNameResolver added in v1.19.0

func (s *TunnelServer) SetEnvironmentNameResolver(resolver EnvironmentNameResolver)

SetEnvironmentNameResolver configures environment name lookup for manager-generated assets.

func (*TunnelServer) SetEventCallback

func (s *TunnelServer) SetEventCallback(callback EventCallback)

SetEventCallback configures the manager callback invoked for agent events.

func (*TunnelServer) StartCleanupLoop

func (s *TunnelServer) StartCleanupLoop(ctx context.Context)

StartCleanupLoop periodically cleans up stale tunnels.

func (*TunnelServer) WaitForCleanupDone

func (s *TunnelServer) WaitForCleanupDone()

WaitForCleanupDone blocks until the cleanup loop has stopped.

Directories

Path Synopsis
proto

Jump to

Keyboard shortcuts

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