shared

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Jan 6, 2026 License: Apache-2.0 Imports: 21 Imported by: 0

Documentation

Overview

Package shared provides configuration, logging, error helpers, and constants used across dployrd. Shared, cross-cutting utilities live here to avoid duplication in other packages, including config for sync intervals and task deduplication TTLs.

Index

Constants

View Source
const (
	ServerHome string = "/usr/local/bin/dployr"
)

Variables

View Source
var Errors = struct {
	Request struct {
		MissingParams    ErrorDescriptor
		BadRequest       ErrorDescriptor
		MethodNotAllowed ErrorDescriptor
	}
	Auth struct {
		Unauthorized ErrorDescriptor
		Forbidden    ErrorDescriptor
	}
	Resource struct {
		NotFound ErrorDescriptor
	}
	Instance struct {
		RegistrationFailed ErrorDescriptor
	}
	Runtime struct {
		InternalServer ErrorDescriptor
	}
}{
	Request: struct {
		MissingParams    ErrorDescriptor
		BadRequest       ErrorDescriptor
		MethodNotAllowed ErrorDescriptor
	}{
		MissingParams:    ErrorDescriptor{Code: ErrorRequestMissingParams, HTTPStatus: http.StatusBadRequest, Message: "Missing required parameters"},
		BadRequest:       ErrorDescriptor{Code: ErrorRequestBadRequest, HTTPStatus: http.StatusBadRequest, Message: "Bad request"},
		MethodNotAllowed: ErrorDescriptor{Code: ErrorRequestMethodNotAllowed, HTTPStatus: http.StatusMethodNotAllowed, Message: "Method not allowed"},
	},
	Auth: struct {
		Unauthorized ErrorDescriptor
		Forbidden    ErrorDescriptor
	}{
		Unauthorized: ErrorDescriptor{Code: ErrorAuthUnauthorized, HTTPStatus: http.StatusUnauthorized, Message: "Unauthorized"},
		Forbidden:    ErrorDescriptor{Code: ErrorAuthForbidden, HTTPStatus: http.StatusForbidden, Message: "Forbidden"},
	},
	Resource: struct {
		NotFound ErrorDescriptor
	}{
		NotFound: ErrorDescriptor{Code: ErrorResourceNotFound, HTTPStatus: http.StatusNotFound, Message: "Resource not found"},
	},
	Runtime: struct {
		InternalServer ErrorDescriptor
	}{
		InternalServer: ErrorDescriptor{Code: ErrorRuntimeInternalServer, HTTPStatus: http.StatusInternalServerError, Message: "Internal server error"},
	},
	Instance: struct {
		RegistrationFailed ErrorDescriptor
	}{
		RegistrationFailed: ErrorDescriptor{Code: ErrorInstanceRegistrationFailed, HTTPStatus: http.StatusInternalServerError, Message: "Instance registration failed"},
	},
}

Errors is a structured catalog of application errors that are currently used across the HTTP handlers.

Functions

func ConvertMapToStrings added in v0.5.0

func ConvertMapToStrings(m map[string]any) map[string]string

ConvertMapToStrings converts a map[string]any to map[string]string. This is useful for environment variables and secrets which must be strings. Supports string, number (int, int64, float64), and boolean values.

func EnrichContext

func EnrichContext(ctx context.Context) context.Context

func Exec

func Exec(ctx context.Context, cmd string, workDir string) error

func ExecWithOptions added in v0.4.11

func ExecWithOptions(ctx context.Context, cmd string, workDir string, useVfox bool) error

func GetToken

func GetToken() (string, error)

func LoadTomlFile

func LoadTomlFile(path string) error

func LogErrF

func LogErrF(name, dir string, err error) error

func LogInfoF

func LogInfoF(name, dir, message string) error

func LogWarnF

func LogWarnF(name, dir, message string) error

func RequestFromContext

func RequestFromContext(ctx context.Context) (string, error)

func RequestID

func RequestID(ctx context.Context) string

func SanitizeSyncInterval

func SanitizeSyncInterval(v time.Duration) time.Duration

SanitizeSyncInterval clamps a duration to safe sync bounds.

func TraceFromContext

func TraceFromContext(ctx context.Context) (string, error)

func TraceID

func TraceID(ctx context.Context) string

func User

func User(ctx context.Context) *store.User

func UserFromContext

func UserFromContext(ctx context.Context) (*store.User, error)

func WithRequest

func WithRequest(ctx context.Context, id string) context.Context

func WithTrace

func WithTrace(ctx context.Context, id string) context.Context

func WithUser

func WithUser(ctx context.Context, id string) context.Context

func WriteError

func WriteError(w http.ResponseWriter, status int, code, message string, details any)

func WriteJSON

func WriteJSON(w http.ResponseWriter, status int, v any)

Types

type AppError

type AppError string
const (
	BadRequest   AppError = "bad_request"
	Unavailable  AppError = "unavailable"
	RuntimeError AppError = "runtime_error"
)

type Config

type Config struct {
	Address          string
	Port             int
	MaxWorkers       int
	BaseURL          string
	InstanceID       string
	SyncInterval     time.Duration
	WSCertPath       string
	WSMaxMessageSize int64
	TaskDedupTTL     time.Duration

	// Log streaming configuration
	LogMaxChunkBytes     int64         // Max bytes per chunk (default: 8MB)
	LogBatchSize         int           // Max entries per batch (default: 50)
	LogBatchTimeout      time.Duration // Batch flush timeout (default: 250ms)
	LogMaxBatchTimeout   time.Duration // Max batch timeout with backoff (default: 2s)
	LogPollInterval      time.Duration // File poll interval for tailing (default: 100ms)
	LogMaxFileReadBytes  int64         // Max bytes to read in one operation (default: 100MB)
	LogMaxStreams        int           // Max concurrent streams (default: 100)
	LogEntryJSONOverhead int64         // Estimated JSON overhead per entry (default: 200 bytes)
}

func LoadConfig

func LoadConfig() (*Config, error)

type ContextKey

type ContextKey string
const (
	CtxUserIDKey    ContextKey = "user_id"
	CtxRequestIDKey ContextKey = "request_id"
	CtxTraceIDKey   ContextKey = "trace_id"
)

type ContextMeta

type ContextMeta struct {
	RequestID string
	TraceID   string
	User      *store.User
}

func Meta

func Meta(ctx context.Context) *ContextMeta

type ErrorCode

type ErrorCode string

ErrorCode is an identifier for an error that can be surfaced to clients and logged across services.

const (
	// Request-level errors
	ErrorRequestMissingParams    ErrorCode = "request.missing_params"
	ErrorRequestBadRequest       ErrorCode = "request.bad_request"
	ErrorRequestMethodNotAllowed ErrorCode = "request.method_not_allowed"

	// Auth errors
	ErrorAuthUnauthorized ErrorCode = "auth.unauthorized"
	ErrorAuthForbidden    ErrorCode = "auth.forbidden"

	// Resource errors
	ErrorResourceNotFound ErrorCode = "resource.not_found"

	// Runtime / internal errors
	ErrorRuntimeInternalServer      ErrorCode = "runtime.internal_server_error"
	ErrorInstanceRegistrationFailed ErrorCode = "instance.registration_failed"
)

type ErrorDescriptor

type ErrorDescriptor struct {
	Code       ErrorCode
	HTTPStatus int
	Message    string
}

ErrorDescriptor defines a specific error, with its code, HTTP status and human-readable message. It's the source of truth for HTTP responses and OpenAPI error objects.

type ErrorResponse

type ErrorResponse struct {
	Error   string `json:"error"`
	Code    string `json:"code,omitempty"`
	Details any    `json:"details,omitempty"`
}

type Logger

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

Logger wraps slog with multi-sink (stdout + file) and context-aware logging.

func LogWithContext

func LogWithContext(ctx context.Context) *Logger

LogWithContext is a legacy helper; use logger.WithContext(ctx) instead. Kept for backward compatibility during migration.

func NewLogger

func NewLogger() *Logger

NewLogger creates a unified logger that writes structured JSON to both stdout and a file. Log files are rotated every 24 hours or when they exceed 300MB, whichever comes first.

func (*Logger) Debug

func (l *Logger) Debug(msg string, args ...any)

Debug logs a debug-level message.

func (*Logger) Error

func (l *Logger) Error(msg string, args ...any)

Error logs an error-level message.

func (*Logger) Info

func (l *Logger) Info(msg string, args ...any)

Info logs an info-level message.

func (*Logger) Warn

func (l *Logger) Warn(msg string, args ...any)

Warn logs a warning-level message.

func (*Logger) With

func (l *Logger) With(args ...any) *Logger

With returns a logger with additional fields.

func (*Logger) WithContext

func (l *Logger) WithContext(ctx context.Context) *Logger

WithContext returns a logger enriched with context fields (request_id, trace_id, user_id, instance_id).

type Semaphore added in v0.5.0

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

Semaphore provides context-aware concurrency limiting.

func NewSemaphore added in v0.5.0

func NewSemaphore(max int) *Semaphore

NewSemaphore creates a new semaphore with the given max concurrent acquisitions.

func (*Semaphore) Acquire added in v0.5.0

func (s *Semaphore) Acquire(ctx context.Context) error

Acquire blocks until a semaphore slot is available or context is cancelled.

func (*Semaphore) Release added in v0.5.0

func (s *Semaphore) Release()

Release returns a semaphore slot.

Jump to

Keyboard shortcuts

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