common

package
v0.0.0-...-3c06ded Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: AGPL-3.0 Imports: 75 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	LogOffsetHeader  = "x-beta9-log-offset"
	RequestIDHeader  = "x-beta9-request-id"
	RequestAckHeader = "x-beta9-request-ack"
)
View Source
const (
	KeyOperationHSet    string = "hset"
	KeyOperationSet     string = "set"
	KeyOperationDel     string = "del"
	KeyOperationExpire  string = "expire"
	KeyOperationExpired string = "expired"
)
View Source
const (
	PreparedStubCacheMetadata = "preparation-cache-key"
	PreparedStubCacheTTL      = 5 * time.Minute
)
View Source
const (
	InvokeUrlTypePath string = "path"
	InvokeUrlTypeHost string = "host"
)
View Source
const CompletedContainerLogRetention = 3 * time.Minute

CompletedContainerLogRetention allows clients to finish replaying logs after a gateway restart, without retaining the container or its resources.

View Source
const MaxAllowListEntries = 64
View Source
const PortPlaceholder = "<PORT>"

PortPlaceholder stands in for the port in the URL of a container with several.

View Source
const TigrisConsistencyHeader = "X-Tigris-Consistent"

Variables

View Source
var (
	ErrNilMessage       = errors.New("redis: nil message")
	ErrChannelClosed    = errors.New("redis: channel closed")
	ErrConnectionIssue  = errors.New("redis: connection issue")
	ErrUnknownRedisMode = errors.New("redis: unknown mode")
)
View Source
var ErrPrivateAddress = errors.New("destination must resolve to a public address")
View Source
var (
	ErrSubdomainDoesNotMatchRegex = errors.New("subdomain does not match regex")
)
View Source
var RedisKeys = &redisKeys{}

Functions

func AWSHTTPClient

func AWSHTTPClient() *awshttp.BuildableClient

func AddSkopeoEnvVars

func AddSkopeoEnvVars(env []string) []string

AddSkopeoEnvVars adds performance-tuning environment variables for skopeo These control parallel blob transfers and other performance characteristics Exported so it can be used by other packages (e.g., image.go)

func BuildDeploymentLatestURL

func BuildDeploymentLatestURL(externalUrl, urlType string, stub *types.Stub, deployment *types.Deployment) string

BuildDeploymentLatestURL is the version-independent address of a deployment, the one other services should be wired to.

func BuildDeploymentURL

func BuildDeploymentURL(externalUrl, urlType string, stub *types.StubWithRelated, deployment *types.Deployment) string

func BuildHandlerPath

func BuildHandlerPath(stub *types.Stub, fields *SubdomainFields, extraPaths ...string) string

BuildHandlerPath builds the path for the handler based on the stub and subdomain fields. The extraPaths are appended to the end of the path. It supports /public, /id, and /name/version paths.

func BuildPodDeploymentURL

func BuildPodDeploymentURL(externalUrl, urlType string, deployment *types.Deployment, stubConfig *types.StubConfigV1) string

func BuildPodURL

func BuildPodURL(externalUrl, urlType string, stub *types.StubWithRelated, stubConfig *types.StubConfigV1) string

func BuildSandboxURL

func BuildSandboxURL(externalUrl, urlType string, stub *types.StubWithRelated, containerId string, port int32) string

func BuildStubURL

func BuildStubURL(externalUrl, urlType string, stub *types.StubWithRelated) string

func CheckPublicAddress

func CheckPublicAddress(_ context.Context, _, address string, _ syscall.RawConn) error

CheckPublicAddress is a net.Dialer.ControlContext hook. It checks the actual resolved IP immediately before connecting, preventing DNS rebinding.

func ConvertValue

func ConvertValue(targetType reflect.Type, value interface{}) (reflect.Value, error)

func CopyStruct

func CopyStruct(src, dst any) error

func Decrypt

func Decrypt(secretKey []byte, ciphertext64 string) (string, error)

func DecryptAllSecrets

func DecryptAllSecrets(signingKey []byte, secrets []string) ([]string, error)

DecryptAllSecrets decrypts all the given secrets in the order they are given.

func Encrypt

func Encrypt(secretKey []byte, plaintext string) (string, error)

func EventChannelKey

func EventChannelKey(eventType EventType) string

func ExtractObjectFile

func ExtractObjectFile(ctx context.Context, objectPath, destPath string) error

func ExtractStubIdFromContainerId

func ExtractStubIdFromContainerId(containerId string) (string, error)

func ExtractStubIdFromStubScopedContainerId

func ExtractStubIdFromStubScopedContainerId(containerId string) (string, bool)

func FindField

func FindField(v reflect.Value, fieldName string) (reflect.Value, bool)

func GRPCClientAuthInterceptor

func GRPCClientAuthInterceptor(token string) grpc.UnaryClientInterceptor

GRPCClientAuthInterceptor adds an authorization header to the outgoing context for unary calls

func GRPCClientAuthStreamInterceptor

func GRPCClientAuthStreamInterceptor(token string) grpc.StreamClientInterceptor

GRPCClientAuthStreamInterceptor adds an authorization header to the outgoing context for streaming calls

func GRPCClientRetryInterceptor

func GRPCClientRetryInterceptor(maxRetries int, delay time.Duration) grpc.UnaryClientInterceptor

GRPCClientRetryInterceptor retries the call on some gRPC errors

func GenerateObjectId

func GenerateObjectId() (string, error)

This simulates Mongo's object ID function which utilizes a 4-byte encoded timestamp value in the beginning of the id Used to even further reduce any chance of collision across distributed containers

func GetAWSConfig

func GetAWSConfig(accessKey string, secretKey string, region string, endpoint string) (aws.Config, error)

func GetConfigParser

func GetConfigParser(format ConfigFormat) (koanf.Parser, error)

func GetStubForSubdomain

func GetStubForSubdomain(ctx context.Context, repo SubdomainBackendRepo, fields *SubdomainFields) (*types.Stub, error)

func GetTimeoutContext

func GetTimeoutContext(baseCtx context.Context, timeoutSeconds int) (context.Context, context.CancelFunc)

func HostPatternCovered

func HostPatternCovered(pattern string, allowList []string) bool

HostPatternCovered requires the whole credential rule to fit within egress.

func IsPublicIP

func IsPublicIP(ip net.IP) bool

IsPublicIP excludes local and special-use address space. IPv4-mapped and well-known NAT64 addresses are checked against their embedded IPv4 address.

func IsRedisLockNotObtained

func IsRedisLockNotObtained(err error) bool

func IsTigrisEndpoint

func IsTigrisEndpoint(endpoint string) bool

IsTigrisEndpoint recognizes Tigris's S3 endpoints, including virtual-hosted buckets.

func MatchDomain

func MatchDomain(host, pattern string) bool

MatchDomain wildcards match subdomains, never the apex or a partial label.

func MergeContexts

func MergeContexts(ctxs ...context.Context) (context.Context, context.CancelFunc)

func NewChunkReader

func NewChunkReader(first []byte, next func() ([]byte, error)) io.Reader

NewChunkReader adapts streamed chunks to a reader without buffering the upload.

func NormalizeWorkerNetworkPrefix

func NormalizeWorkerNetworkPrefix(clusterName, networkPrefix string) string

func ParseSecretKey

func ParseSecretKey(secretKey string) ([]byte, error)

func ParseVersion

func ParseVersion(version string) uint

parseVersion parses the version string and returns the version number. If the version is unparsable, this will return 0.

func PublishReloadInstance

func PublishReloadInstance(rdb *RedisClient, stubId, stubType string)

PublishReloadInstance asks running instances of a stub to re-read its config.

func RunBatchQueue

func RunBatchQueue[T any](queue <-chan T, limit int, dispatch func([]T))

RunBatchQueue collects bounded one-millisecond windows and dispatches them serially. Closing the queue drains its remaining requests before returning.

func SetupTelemetry

func SetupTelemetry(ctx context.Context, serviceName string, appConfig types.AppConfig) (shutdown func(context.Context) error, err error)

SetupTelemetry bootstraps the OpenTelemetry pipeline

func ShellQuote

func ShellQuote(value string) string

func SplitAllowList

func SplitAllowList(list []string) (cidrs, hosts []string)

SplitAllowList separates normalized IP networks from hostname patterns.

func ToSlice

func ToSlice(v interface{}) []interface{}

Flattens a struct using its field tags so it can be used by HSet. Struct fields must have the redis tag on them otherwise they will be ignored.

func ToStruct

func ToStruct(m map[string]string, out interface{}) error

Copies the result of HGetAll to a provided struct. If a field cannot be parsed, we use Go's default value. Struct fields must have the redis tag on them otherwise they will be ignored.

func UnzipBytesToPath

func UnzipBytesToPath(destPath string, objBytes []byte, request *types.ContainerRequest) error

func ValidateAllowList

func ValidateAllowList(list []string) error

func ValidateCIDR

func ValidateCIDR(entry string) (string, bool, error)

ValidateCIDR normalizes a network or a single IP address.

func ValidateHostPattern

func ValidateHostPattern(pattern string) error

func ValidatePublicHTTPURL

func ValidatePublicHTTPURL(ctx context.Context, raw string) error

ValidatePublicHTTPURL checks both URL syntax and every resolved address. Callers must also enforce CheckPublicAddress when dialing the destination.

func ValidateSandboxSecrets

func ValidateSandboxSecrets(secrets []types.Secret, allowList []string) error

func ValidateSecretHosts

func ValidateSecretHosts(hosts []string, value string) error

ValidateSecretHosts shares the hostname grammar with egress, excluding IPs.

func WithClientName

func WithClientName(name string) func(*redis.UniversalOptions)

func WorkerNetworkPrefix

func WorkerNetworkPrefix(clusterName, nodeName string) string

Types

type ChannelHandler

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

ChannelHandler implements slog.Handler to send logs to a channel

func NewChannelHandler

func NewChannelHandler(logChan chan LogRecord) *ChannelHandler

NewChannelHandler creates a new handler that sends logs to the provided channel

func (*ChannelHandler) Enabled

func (h *ChannelHandler) Enabled(_ context.Context, level slog.Level) bool

func (*ChannelHandler) Handle

func (h *ChannelHandler) Handle(_ context.Context, r slog.Record) error

Handle implements slog.Handler

func (*ChannelHandler) WithAttrs

func (h *ChannelHandler) WithAttrs(attrs []slog.Attr) slog.Handler

func (*ChannelHandler) WithGroup

func (h *ChannelHandler) WithGroup(name string) slog.Handler

type Clock

type Clock interface {
	Now() time.Time
	// AfterFunc calls f once, d from now.
	AfterFunc(d time.Duration, f func()) ClockTimer
	// Every calls tick once per interval until ctx is done. It returns at
	// once; ticks never overlap.
	Every(ctx context.Context, interval time.Duration, tick func())
}

Clock is the source of time for code that must be testable without sleeping: the scheduler's capacity path and the provisioner. Production code takes a Clock and runs on the wall clock; tests and the scheduler simulator use a FakeClock and move time themselves.

func ClockOrReal

func ClockOrReal(c Clock) Clock

ClockOrReal returns c, or the wall clock when c is nil.

type ClockTimer

type ClockTimer interface {
	// Stop prevents the timer from firing. It reports whether it did.
	Stop() bool
}

ClockTimer is a call that AfterFunc has yet to make.

type ConfigFormat

type ConfigFormat string
var (
	JSONConfigFormat ConfigFormat = ".json"
	YAMLConfigFormat ConfigFormat = ".yaml"
	YMLConfigFormat  ConfigFormat = ".yml"
)

type ConfigLoaderFunc

type ConfigLoaderFunc func(k *koanf.Koanf) error

ConfigLoaderFunc is a function type used to load configuration into a Koanf instance. It takes a Koanf pointer 'k' as a parameter and returns an error if the loading process encounters any issues.

type ConfigManager

type ConfigManager[T any] struct {
	// contains filtered or unexported fields
}

ConfigManager is a generic configuration manager that allows handling and manipulation of configuration data for various types. It includes a Koanf instance ('kf') for managing configuration settings.

func NewConfigManager

func NewConfigManager[T any]() (*ConfigManager[T], error)

NewConfigManager creates a new instance of the ConfigManager[T]. It initializes a Koanf instance and loads the default configuration. It then loads the configuration from the /etc/beta9.d/ directory and the user-specified configuration file from CONFIG_PATH. If the CONFIG_JSON environment variable is set, it loads the configuration from the JSON string. If debug mode is enabled, it prints the current configuration.

func (*ConfigManager[T]) GetConfig

func (cm *ConfigManager[T]) GetConfig() T

GetConfig retrieves the current configuration of type 'T' from the ConfigManager. It unmarshals the configuration data and returns it. If any errors occur during unmarshaling, it logs a fatal error and exits the application.

func (*ConfigManager[T]) LoadConfig

func (cm *ConfigManager[T]) LoadConfig(format ConfigFormat, provider koanf.Provider) error

LoadConfig loads configuration data from a given provider in the specified format into the ConfigManager. It obtains a parser for the format, and then loads the configuration data. If any errors occur during the loading process, they are returned as an error.

func (*ConfigManager[T]) Print

func (cm *ConfigManager[T]) Print() string

Print returns a string representation of the current configuration state.

func (*ConfigManager[T]) UnknownKeys

func (cm *ConfigManager[T]) UnknownKeys() []UnknownConfigKey

UnknownKeys returns the keys that were loaded but that no field of the config type reads, in the order their sources were loaded.

func (*ConfigManager[T]) WarnUnknownKeys

func (cm *ConfigManager[T]) WarnUnknownKeys()

WarnUnknownKeys logs each key that was loaded but has no effect.

type ContainerCheckpointOptions

type ContainerCheckpointOptions struct {
	TerminateAfterCheckpoint bool
}

type ContainerClient

type ContainerClient struct {
	ServiceUrl string
	// contains filtered or unexported fields
}

ContainerClient calls a worker's container service. Workers don't authenticate these calls, so no credentials are sent with them.

func NewContainerClient

func NewContainerClient(serviceUrl string, existingConn net.Conn) (*ContainerClient, error)

NewContainerClient connects to serviceUrl, over existingConn when it is set.

func NewContainerClientWithDialer

func NewContainerClientWithDialer(ctx context.Context, serviceUrl string, dialer ContainerClientDialer) (*ContainerClient, error)

NewContainerClientWithDialer creates a reconnectable cached gRPC channel.

func (*ContainerClient) Archive

func (c *ContainerClient) Archive(ctx context.Context, containerId, imageId string, outputChan chan OutputMsg) error

func (*ContainerClient) Checkpoint

func (*ContainerClient) Close

func (c *ContainerClient) Close() error

func (*ContainerClient) Exec

func (c *ContainerClient) Exec(containerId, cmd string, env []string) (*pb.ContainerExecResponse, error)

func (*ContainerClient) ExecContext

func (c *ContainerClient) ExecContext(ctx context.Context, containerId, cmd string, env []string) (*pb.ContainerExecResponse, error)

func (*ContainerClient) Kill

func (c *ContainerClient) Kill(containerId string) (*pb.ContainerKillResponse, error)

func (*ContainerClient) SandboxCreateDirectory

func (c *ContainerClient) SandboxCreateDirectory(containerId, containerPath string, mode int32) (*pb.ContainerSandboxCreateDirectoryResponse, error)

func (*ContainerClient) SandboxDeleteDirectory

func (c *ContainerClient) SandboxDeleteDirectory(containerId, containerPath string) (*pb.ContainerSandboxDeleteDirectoryResponse, error)

func (*ContainerClient) SandboxDeleteFile

func (c *ContainerClient) SandboxDeleteFile(containerId, containerPath string) (*pb.ContainerSandboxDeleteFileResponse, error)

func (*ContainerClient) SandboxExec

func (c *ContainerClient) SandboxExec(containerId, cmd string, env map[string]string, cwd string) (*pb.ContainerSandboxExecResponse, error)

func (*ContainerClient) SandboxExecContext

func (c *ContainerClient) SandboxExecContext(ctx context.Context, containerId, cmd string, env map[string]string, cwd string, wait bool, bindings ...*pb.SecretBinding) (*pb.ContainerSandboxExecResponse, error)

func (*ContainerClient) SandboxExposePort

func (c *ContainerClient) SandboxExposePort(containerId string, port int32) (*pb.ContainerSandboxExposePortResponse, error)

func (*ContainerClient) SandboxExposePortContext

func (c *ContainerClient) SandboxExposePortContext(ctx context.Context, containerId string, port int32) (*pb.ContainerSandboxExposePortResponse, error)

func (*ContainerClient) SandboxFindInFiles

func (c *ContainerClient) SandboxFindInFiles(containerId, containerPath, pattern string) (*pb.ContainerSandboxFindInFilesResponse, error)

func (*ContainerClient) SandboxKill

func (c *ContainerClient) SandboxKill(containerId string, pid int32) (*pb.ContainerSandboxKillResponse, error)

func (*ContainerClient) SandboxListExposedPorts

func (c *ContainerClient) SandboxListExposedPorts(containerId string) (*pb.ContainerSandboxListExposedPortsResponse, error)

func (*ContainerClient) SandboxListFiles

func (c *ContainerClient) SandboxListFiles(containerId, containerPath string) (*pb.ContainerSandboxListFilesResponse, error)

func (*ContainerClient) SandboxListProcesses

func (c *ContainerClient) SandboxListProcesses(containerId string) (*pb.ContainerSandboxListProcessesResponse, error)

func (*ContainerClient) SandboxReadyContext

func (c *ContainerClient) SandboxReadyContext(ctx context.Context, containerId string) (*pb.ContainerSandboxStatusResponse, error)

Wait for exec readiness on the worker, avoiding repeated network probes. Older workers ignore the flag and return pending, which callers can retry.

func (*ContainerClient) SandboxReplaceInFiles

func (c *ContainerClient) SandboxReplaceInFiles(containerId, containerPath, oldString, newString string) (*pb.ContainerSandboxReplaceInFilesResponse, error)

func (*ContainerClient) SandboxStatFile

func (c *ContainerClient) SandboxStatFile(containerId, containerPath string) (*pb.ContainerSandboxStatFileResponse, error)

func (*ContainerClient) SandboxStatus

func (c *ContainerClient) SandboxStatus(containerId string, pid int32) (*pb.ContainerSandboxStatusResponse, error)

func (*ContainerClient) SandboxStatusContext

func (c *ContainerClient) SandboxStatusContext(ctx context.Context, containerId string, pid int32) (*pb.ContainerSandboxStatusResponse, error)

func (*ContainerClient) SandboxStderr

func (c *ContainerClient) SandboxStderr(containerId string, pid int32) (*pb.ContainerSandboxStderrResponse, error)

func (*ContainerClient) SandboxStderrContext

func (c *ContainerClient) SandboxStderrContext(ctx context.Context, containerId string, pid int32) (*pb.ContainerSandboxStderrResponse, error)

func (*ContainerClient) SandboxStdout

func (c *ContainerClient) SandboxStdout(containerId string, pid int32) (*pb.ContainerSandboxStdoutResponse, error)

func (*ContainerClient) SandboxStdoutContext

func (c *ContainerClient) SandboxStdoutContext(ctx context.Context, containerId string, pid int32) (*pb.ContainerSandboxStdoutResponse, error)

func (*ContainerClient) SandboxUpdateNetworkPermissions

func (c *ContainerClient) SandboxUpdateNetworkPermissions(containerId string, blockNetwork bool, allowList []string) (*pb.ContainerSandboxUpdateNetworkPermissionsResponse, error)

func (*ContainerClient) SnapshotDisks

func (c *ContainerClient) SnapshotDisks(ctx context.Context, containerId string) (*pb.ContainerSnapshotDisksResponse, error)

func (*ContainerClient) Status

func (c *ContainerClient) Status(containerId string) (*pb.ContainerStatusResponse, error)

func (*ContainerClient) StreamLogs

func (c *ContainerClient) StreamLogs(ctx context.Context, containerId string, outputChan chan OutputMsg) error

func (*ContainerClient) StreamLogsWithReady

func (c *ContainerClient) StreamLogsWithReady(ctx context.Context, containerId string, outputChan chan OutputMsg, ready func()) error

StreamLogsWithReady reports when the stream attachment attempt completes. Callers can use ready to keep exit handling from racing log backfill.

func (*ContainerClient) SyncWorkspace

func (*ContainerClient) Tunnel

type ContainerClientDialer

type ContainerClientDialer func(context.Context, string) (net.Conn, error)

type ContainerOverlay

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

func NewContainerOverlay

func NewContainerOverlay(request *types.ContainerRequest, rootPath string, overlayPath string) *ContainerOverlay

func (*ContainerOverlay) AddEmptyLayer

func (co *ContainerOverlay) AddEmptyLayer() error

func (*ContainerOverlay) AddLayer

func (co *ContainerOverlay) AddLayer(upperDir string) error

func (*ContainerOverlay) Cleanup

func (co *ContainerOverlay) Cleanup() error

func (*ContainerOverlay) OverlayPath

func (co *ContainerOverlay) OverlayPath() string

func (*ContainerOverlay) Reset

func (co *ContainerOverlay) Reset() error

Reset rebuilds the writable layer while preserving bundle state that may share the container root, such as config.json and checkpoint signal mounts.

func (*ContainerOverlay) ResetWithUpper

func (co *ContainerOverlay) ResetWithUpper(seed func(string) error) error

ResetWithUpper rebuilds the writable layer from seed while it is unmounted. Checkpoint upper directories can contain overlay whiteouts and opaque xattrs that must not be copied through the merged filesystem.

func (*ContainerOverlay) RootPath

func (co *ContainerOverlay) RootPath() string

RootPath is the immutable image root under every layer.

func (*ContainerOverlay) SetUnder

func (co *ContainerOverlay) SetUnder(dir string)

SetUnder puts dir below the root of an overlay that is not mounted yet. It applies to Setup, whose writable layer starts empty: a writable layer that outlives the mount would keep referring to a directory that the next mount may not have.

func (*ContainerOverlay) Setup

func (co *ContainerOverlay) Setup() error

func (*ContainerOverlay) SetupWithWritable

func (co *ContainerOverlay) SetupWithWritable(upperDir, workDir string) error

SetupWithWritable mounts the overlay with its writable layer on a persistent filesystem (e.g. a qcow-backed durable disk) instead of worker scratch space, so the container's entire root filesystem delta survives snapshots and restores. Cleanup never removes upper or work.

func (*ContainerOverlay) TopLayerPath

func (co *ContainerOverlay) TopLayerPath() string

func (*ContainerOverlay) TopLayerUpperDir

func (co *ContainerOverlay) TopLayerUpperDir() string

TopLayerUpperDir returns the writable upper directory of the top layer, which may live on a persistent disk rather than beside the merged path.

type ContainerOverlayLayer

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

type ContainerSchedulingFailure

type ContainerSchedulingFailure struct {
	TaskID       string
	ContainerID  string
	PoolSelector string
	Reason       types.ContainerSchedulingFailureReason
}

func ParseContainerSchedulingFailure

func ParseContainerSchedulingFailure(event *Event) (ContainerSchedulingFailure, bool)

type Event

type Event struct {
	Type          EventType      `json:"type"`
	Args          map[string]any `json:"args"`
	LockAndDelete bool           `json:"lock_and_delete"`
	Retries       uint           `json:"retries"`
}

func NewContainerSchedulingFailedEvent

func NewContainerSchedulingFailedEvent(failure ContainerSchedulingFailure) *Event

type EventBus

type EventBus struct {
	EventCallbacks map[string]func(*Event) bool
	Subscribers    []EventBusSubscriber
	// contains filtered or unexported fields
}

func NewEventBus

func NewEventBus(rdb *RedisClient, subscribers ...EventBusSubscriber) *EventBus

Create a new event bus

func (*EventBus) Claim

func (eb *EventBus) Claim(eventId string) (*Event, *RedisLock, bool)

Claim an event for processing

func (*EventBus) Delete

func (eb *EventBus) Delete(eventId string) error

Remove an event by ID

func (*EventBus) ReceiveEvents

func (eb *EventBus) ReceiveEvents(ctx context.Context)

Receive all subscribed events (blocking)

func (*EventBus) Send

func (eb *EventBus) Send(event *Event) (string, error)

Send an event over the bus

type EventBusSubscriber

type EventBusSubscriber struct {
	Type     EventType
	Callback func(*Event) bool
}

type EventType

type EventType string
const (
	EventTypeStopContainer             EventType = "STOP_CONTAINER"
	EventTypeStopBuild                 EventType = "STOP_BUILD"
	EventTypeReloadInstance            EventType = "RELOAD_INSTANCE"
	EventTypeContainerSchedulingFailed EventType = "CONTAINER_SCHEDULING_FAILED"
)

func StopBuildEventType

func StopBuildEventType(containerId string) EventType

type ExecWriter

type ExecWriter struct {
	*slog.Logger
}

func (*ExecWriter) Write

func (c *ExecWriter) Write(p []byte) (n int, err error)

type FakeClock

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

FakeClock is a clock that only moves when Advance is called. Timers and ticks that come due run on the goroutine that called Advance, in time order, so a test that advances the clock sees every loop body run deterministically.

func NewFakeClock

func NewFakeClock(start time.Time) *FakeClock

func (*FakeClock) Advance

func (f *FakeClock) Advance(d time.Duration)

Advance moves the clock forward by d, running everything that comes due on the way. A timer added by a callback runs in the same call if it is due.

func (*FakeClock) AfterFunc

func (f *FakeClock) AfterFunc(d time.Duration, fn func()) ClockTimer

func (*FakeClock) Every

func (f *FakeClock) Every(ctx context.Context, interval time.Duration, tick func())

func (*FakeClock) Now

func (f *FakeClock) Now() time.Time

func (*FakeClock) OnStep

func (f *FakeClock) OnStep(fn func(time.Duration))

OnStep registers fn to run each time the clock moves, with the distance moved, before any timer due at the new time fires. The simulator uses it to keep Redis key expiry in step with the clock.

type ImageMetadata

type ImageMetadata struct {
	Name          string         `json:"Name"`
	Digest        string         `json:"Digest"`
	Created       time.Time      `json:"Created"`
	DockerVersion string         `json:"DockerVersion"`
	Labels        map[string]any `json:"Labels"`
	Architecture  string         `json:"Architecture"`
	Os            string         `json:"Os"`
	Layers        []string       `json:"Layers"`
	LayersData    []struct {
		MIMEType    string `json:"MIMEType"`
		Digest      string `json:"Digest"`
		Size        int    `json:"Size"`
		Annotations any    `json:"Annotations"`
	} `json:"LayersData"`
	Env []string `json:"Env"`
}

type KeyEvent

type KeyEvent struct {
	Key       string
	Operation string
}

type KeyEventManager

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

func NewKeyEventManager

func NewKeyEventManager(rdb *RedisClient) *KeyEventManager

func (*KeyEventManager) ListenForContainerPattern

func (kem *KeyEventManager) ListenForContainerPattern(ctx context.Context, containerPrefix string, keyEventChan chan KeyEvent) error

ListenForContainerPattern replays active container state from its explicit index instead of scanning the entire Redis keyspace.

func (*KeyEventManager) ListenForKey

func (kem *KeyEventManager) ListenForKey(ctx context.Context, key string, keyEventChan chan KeyEvent) error

ListenForKey watches one exact key without scanning the database. Subscribing before checking existence ensures a write cannot be missed between the two.

func (*KeyEventManager) ListenForPatternEvents

func (kem *KeyEventManager) ListenForPatternEvents(ctx context.Context, patternPrefix string, keyEventChan chan KeyEvent) error

ListenForPatternEvents watches future keyspace events without replaying existing keys. Use it when only expiry/delete events are meaningful.

func (*KeyEventManager) ListenForPublishedKey

func (kem *KeyEventManager) ListenForPublishedKey(ctx context.Context, key string, keyEventChan chan KeyEvent) error

type LogBuffer

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

LogBuffer spools logs locally so readers can reattach at their own offset. The unlinked file belongs to the container and is released by Dispose.

func NewLogBuffer

func NewLogBuffer() *LogBuffer

func (*LogBuffer) Close

func (lb *LogBuffer) Close()

func (*LogBuffer) Dispose

func (lb *LogBuffer) Dispose()

func (*LogBuffer) Read

func (lb *LogBuffer) Read(p []byte) (int, error)

func (*LogBuffer) ReadAt

func (lb *LogBuffer) ReadAt(p []byte, offset int64) (int, error)

func (*LogBuffer) Write

func (lb *LogBuffer) Write(data []byte) bool

type LogRecord

type LogRecord struct {
	Level   slog.Level
	Message string
	Attrs   map[string]any
}

type OutputMsg

type OutputMsg struct {
	Msg       string
	Done      bool
	Success   bool
	Archiving bool
	Warning   bool

	ImageId       string
	PythonVersion string
}

type OutputWriter

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

func NewOutputWriter

func NewOutputWriter(outputCallback func(string)) *OutputWriter

func (*OutputWriter) Write

func (w *OutputWriter) Write(p []byte) (n int, err error)

type ParserFunc

type ParserFunc func() (koanf.Parser, error)

type PhaseTimer

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

PhaseTimer records how long each phase of a multi-step operation took, so a slow attach or shutdown can be blamed on one phase from its log line alone.

A nil timer is inert: callers create one only when debug instrumentation is on and use it unconditionally, so production paths carry no bookkeeping.

func NewPhaseTimer

func NewPhaseTimer() *PhaseTimer

func (*PhaseTimer) Fields

func (t *PhaseTimer) Fields(event *zerolog.Event) *zerolog.Event

Fields adds one duration field per recorded phase to a log event.

func (*PhaseTimer) Mark

func (t *PhaseTimer) Mark(name string)

Mark closes the phase that began at the previous Mark (or at creation) and records it under name.

type RedisClient

type RedisClient struct {
	redis.UniversalClient
}

func NewRedisClient

func NewRedisClient(config types.RedisConfig, options ...func(*redis.UniversalOptions)) (*RedisClient, error)

func (*RedisClient) Keys

func (r *RedisClient) Keys(ctx context.Context, pattern string) ([]string, error)

Keys gets all keys using a pattern. Prefer explicit indexes for hot paths.

func (*RedisClient) LRange

func (r *RedisClient) LRange(ctx context.Context, key string, start, stop int64) ([]string, error)

func (*RedisClient) PSubscribe

func (r *RedisClient) PSubscribe(ctx context.Context, channels ...string) (<-chan *redis.Message, <-chan error, func())

func (*RedisClient) Publish

func (r *RedisClient) Publish(ctx context.Context, channel string, message interface{}) *redis.IntCmd

func (*RedisClient) Scan

func (r *RedisClient) Scan(ctx context.Context, pattern string) ([]string, error)

func (*RedisClient) Subscribe

func (r *RedisClient) Subscribe(ctx context.Context, channels ...string) (<-chan *redis.Message, <-chan error)

func (*RedisClient) ToSlice

func (r *RedisClient) ToSlice(v interface{}) []interface{}

func (*RedisClient) ToStruct

func (r *RedisClient) ToStruct(m map[string]string, out interface{}) error

type RedisLock

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

func NewRedisLock

func NewRedisLock(client *RedisClient, opts ...RedisLockOption) *RedisLock

func (*RedisLock) Acquire

func (l *RedisLock) Acquire(ctx context.Context, key string, opts RedisLockOptions) error

func (*RedisLock) Refresh

func (l *RedisLock) Refresh(ctx context.Context, key string, ttl time.Duration) error

func (*RedisLock) Release

func (l *RedisLock) Release(key string) error

func (*RedisLock) ReleaseWithToken

func (l *RedisLock) ReleaseWithToken(key string, token string) error

func (*RedisLock) Token

func (l *RedisLock) Token(key string) (string, error)

func (*RedisLock) WithLease

func (l *RedisLock) WithLease(ctx context.Context, key string, opts RedisLockOptions, fn func(context.Context) error) error

type RedisLockOption

type RedisLockOption func(*RedisLock)

type RedisLockOptions

type RedisLockOptions struct {
	TtlS          int
	Retries       int
	RetryInterval time.Duration
}

type SafeBuffer

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

func (*SafeBuffer) StringAndReset

func (b *SafeBuffer) StringAndReset() string

func (*SafeBuffer) Write

func (b *SafeBuffer) Write(p []byte) (int, error)

type SafeMap

type SafeMap[V any] struct {
	// contains filtered or unexported fields
}

func NewSafeMap

func NewSafeMap[V any]() *SafeMap[V]

NewSafeMap initializes a new SafeMap with the specified value type.

func (*SafeMap[V]) Delete

func (m *SafeMap[V]) Delete(key string)

func (*SafeMap[V]) Get

func (m *SafeMap[V]) Get(key string) (V, bool)

func (*SafeMap[V]) Len

func (m *SafeMap[V]) Len() int

func (*SafeMap[V]) Range

func (m *SafeMap[V]) Range(f func(key string, value V) bool)

Range calls f sequentially for each key and value present in the map. If f returns false, range stops the iteration.

func (*SafeMap[V]) Removed

func (m *SafeMap[V]) Removed() <-chan struct{}

Removed returns a channel that is closed the next time any entry is deleted or Wake is called. Callers re-check their condition and call Removed again to keep waiting.

func (*SafeMap[V]) Set

func (m *SafeMap[V]) Set(key string, value V)

func (*SafeMap[V]) Update

func (m *SafeMap[V]) Update(key string, value V) bool

Update stores value under key only while key is present and reports whether it did. Writing back an entry read earlier must use this rather than Set: another goroutine may have deleted the entry in between, and Set would silently re-create it.

func (*SafeMap[V]) Wake

func (m *SafeMap[V]) Wake()

Wake closes the channel Removed returned without deleting an entry, for waiters whose condition changed while their entry stays.

type SkopeoClient

type SkopeoClient interface {
	Inspect(ctx context.Context, sourceImage string, creds string, overrideLogger *slog.Logger) (ImageMetadata, error)
	InspectSizeInBytes(ctx context.Context, sourceImage string, creds string) (int64, error)
	Copy(ctx context.Context, sourceImage string, dest string, creds string, overrideLogger *slog.Logger) error
}

func NewSkopeoClient

func NewSkopeoClient(config types.AppConfig) SkopeoClient

type SubdomainBackendRepo

type SubdomainBackendRepo interface {
	GetStubByExternalId(ctx context.Context, externalId string, queryFilters ...types.QueryFilter) (*types.StubWithRelated, error)
	GetDeploymentBySubdomain(ctx context.Context, subdomain string, version uint) (*types.DeploymentWithRelated, error)
}

type SubdomainFields

type SubdomainFields struct {
	Name        string
	Version     uint
	StubId      string
	ContainerId string
	Subdomain   string
	Port        uint32
}

func ParseSubdomain

func ParseSubdomain(subdomain string, baseDomain string) (*SubdomainFields, error)

func ParseSubdomainFields

func ParseSubdomainFields(subdomain string) (*SubdomainFields, error)

type Tracer

type Tracer struct {
	Ctx context.Context

	Span _trace.Span
	// contains filtered or unexported fields
}

func TraceFunc

func TraceFunc(ctx context.Context, tracerName, spanName string, attributes ...attribute.KeyValue) *Tracer

func (*Tracer) End

func (t *Tracer) End()

type UnknownConfigKey

type UnknownConfigKey struct {
	// Source is where the key was set: a file path, "CONFIG_JSON", or
	// "defaults" for the built-in config.
	Source string
	// Key is the key's path, such as "worker.pools[default].gpuTyp".
	Key string
}

UnknownConfigKey is a key in a config source that no field of the config type reads, so setting it has no effect. It is usually a typo or a setting that has since been removed.

type WorkerNetworkScope

type WorkerNetworkScope struct {
	ClusterName string
	NodeName    string
}

func ParseWorkerNetworkPrefix

func ParseWorkerNetworkPrefix(prefix string) (WorkerNetworkScope, bool)

type ZerologIOWriter

type ZerologIOWriter struct {
	LogFn func() *zerolog.Event
}

func (*ZerologIOWriter) Write

func (w *ZerologIOWriter) Write(p []byte) (n int, err error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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