utils

package
v2.8.1 Latest Latest
Warning

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

Go to latest
Published: Aug 19, 2026 License: BSD-3-Clause Imports: 22 Imported by: 0

Documentation

Index

Constants

View Source
const (
	HeaderAgentBootstrap  = "X-Arcane-Agent-Bootstrap"
	HeaderAgentToken      = "X-Arcane-Agent-Token" // #nosec G101: header name, not a credential
	HeaderApiKey          = "X-Api-Key"            // #nosec G101: header name, not a credential
	HeaderActivityBatchID = "X-Arcane-Batch-Id"
	// HeaderIconCatalog carries the requesting user's icon catalog preference to
	// remote environments. Agents authenticate proxied calls as a synthetic user
	// with no preferences, so without it every remote environment would resolve
	// container/project icons against the default catalog.
	HeaderIconCatalog  = "X-Arcane-Icon-Catalog"
	AgentPairingPrefix = "/api/environments/0/agent/pair"
)

Auth header names and path prefixes shared between the Echo middleware (WebSocket/diagnostics) and the Huma auth bridge (REST). Keep these in one place so a change to a header name applies to every route type at once.

Variables

View Source
var (
	FilePerm os.FileMode = 0o644
	DirPerm  os.FileMode = 0o755
)

Functions

func ActivityBatchIDFromContext added in v2.5.0

func ActivityBatchIDFromContext(ctx context.Context) string

ActivityBatchIDFromContext returns the batch ID attached by WithActivityBatchID, or "" when none is set.

func ActivityRuntimeContext

func ActivityRuntimeContext(requestCtx context.Context, appCtx context.Context) context.Context

ActivityRuntimeContext returns a context suitable for activity-backed work.

func ApplyChanged added in v2.6.0

func ApplyChanged[T comparable](target *T, value mo.Option[T]) bool

ApplyChanged updates target when value is present and differs from the current value.

func ApplyNullable added in v2.6.0

func ApplyNullable[T comparable](target **T, value mo.Option[T]) bool

ApplyNullable updates target to the optional value when it differs from the current value.

func ApplySliceChanged added in v2.7.0

func ApplySliceChanged[S ~[]E, E comparable](target *S, value mo.Option[S]) bool

ApplySliceChanged updates target when value is present and its elements differ from the current slice. Nil and empty slices are treated as equal.

func AsStringMap

func AsStringMap(value any) mo.Option[map[string]any]

AsStringMap attempts to convert any map-like interface to map[string]any.

func BoolOrDefault

func BoolOrDefault(value string, defaultValue bool) bool

BoolOrDefault parses value as a bool, falling back to defaultValue when empty or unparseable.

func CamelCaseToSnakeCase

func CamelCaseToSnakeCase(str string) string

func CapitalizeFirstLetter

func CapitalizeFirstLetter(str string) string

func Collect

func Collect[T any](value any, mapper func(any) T) []T

Collect transforms a value (single item or slice) into a slice of T using a mapper.

func ExtractCategoryMetadata

func ExtractCategoryMetadata(model any, categoryIDsInOrder []string) map[string]map[string]string

ExtractCategoryMetadata extracts category metadata from struct fields with catmeta tags Returns a map of category ID to category metadata in field order

func FilePathMatches added in v2.8.0

func FilePathMatches(relativePath, rootPath string) bool

func FingerprintOf added in v2.6.0

func FingerprintOf[T any](items []T, write func(*Fingerprint, *T)) uint64

FingerprintOf hashes a slice of items with a per-item writer, including the slice length so resizing or reordering changes the result. The writer receives a pointer so large structs are not copied per item.

func FirstNonEmpty

func FirstNonEmpty(values ...string) string

FirstNonEmpty returns the first non-empty string in a list of values.

func GenerateRandomString

func GenerateRandomString(length int) string

func GetStringOrDefault

func GetStringOrDefault(m map[string]any, key, defaultValue string) string

func IntOrDefault

func IntOrDefault(value string, defaultValue int) int

IntOrDefault parses value as an int, falling back to defaultValue when empty or unparseable.

func IsAppLifecycleContext

func IsAppLifecycleContext(ctx context.Context) bool

IsAppLifecycleContext reports whether ctx is tied to the application lifecycle.

func NormalizeRelativePath added in v2.8.0

func NormalizeRelativePath(input string) (string, error)

NormalizeRelativePath validates and normalizes a slash-delimited path rooted at a managed file tree. The returned path never begins with a slash.

func ParseKeywords

func ParseKeywords(keywordsStr string) []string

ParseKeywords parses a comma-separated keywords string into a slice Returns an empty slice if the input is empty or contains only whitespace

func ParseMetaTag

func ParseMetaTag(tag string) map[string]string

ParseMetaTag parses a struct tag meta value formatted as `k=v;other=val;...` Returns a map of key-value pairs extracted from the tag

func RecoverToError added in v2.6.0

func RecoverToError(errPtr *error, label string, args ...any)

RecoverToError converts a panic in the calling goroutine into an error and logs it. x/sync's errgroup does not recover worker panics — they crash the whole process — so every worker defers this as its first statement:

g.Go(func() (workerErr error) {
	defer utils.RecoverToError(&workerErr, "image list worker")
	...
})

It must be deferred directly (not wrapped in another closure) for recover() to observe the panic. errPtr may be nil when the caller has no error to report into (e.g. a fire-and-forget goroutine); the panic is still logged. args are extra slog attributes appended to the log record.

func SanitizeBrowsePath added in v2.6.0

func SanitizeBrowsePath(input string) (string, error)

SanitizeBrowsePath normalizes a path within a rooted file browser.

func StringOrDefault

func StringOrDefault(value, defaultValue string) string

StringOrDefault returns the trimmed value if non-empty, otherwise defaultValue.

func ToString

func ToString(v any) string

ToString converts any value to a trimmed string.

func TrimQuotes

func TrimQuotes(s string) string

func UniqueNonEmptyStrings

func UniqueNonEmptyStrings(items []string) []string

UniqueNonEmptyStrings returns unique, non-empty, trimmed strings.

func ValidActivityBatchID added in v2.5.0

func ValidActivityBatchID(id string) bool

ValidActivityBatchID reports whether id is safe to persist as a batch ID.

func ValidateFileName added in v2.8.0

func ValidateFileName(name string) (string, error)

ValidateFileName validates a single file-tree path segment.

func WaitGroup added in v2.7.0

func WaitGroup(ctx context.Context, group *sync.WaitGroup) error

WaitGroup waits for all work or returns when ctx ends. After a timeout, its waiter goroutine remains until the group eventually completes.

func WithActivityBatchID added in v2.5.0

func WithActivityBatchID(ctx context.Context, batchID string) context.Context

WithActivityBatchID attaches a client-supplied batch ID that groups the activities spawned by one logical user action (e.g. a bulk container update). Invalid IDs are ignored.

func WithAppLifecycleContext

func WithAppLifecycleContext(ctx context.Context) context.Context

WithAppLifecycleContext marks ctx as the application lifecycle context.

func WriteFileTreeRevisionEntry added in v2.8.0

func WriteFileTreeRevisionEntry(h hash.Hash, relativePath, kind string, size, modTimeUnixNano int64, mode string, protected bool)

Types

type Fingerprint added in v2.6.0

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

Fingerprint accumulates an order-sensitive 64-bit hash of arbitrary field values. It exists for change detection: a poller that must decide "did anything change since the last tick?" can hash the fields it cares about instead of marshalling the whole payload to JSON and retaining the bytes just to compare them on the next tick.

Every method returns the receiver so a struct's fields read as one chain. Opt* variants tag presence, keeping nil distinct from the zero value so clearing a field is observed as a change.

It is a change detector, not a checksum. FNV-1a is not collision resistant and must never back a security or correctness decision.

func NewFingerprint added in v2.6.0

func NewFingerprint() *Fingerprint

func (*Fingerprint) Bool added in v2.6.0

func (f *Fingerprint) Bool(b bool) *Fingerprint

func (*Fingerprint) Int added in v2.6.0

func (f *Fingerprint) Int(v int64) *Fingerprint

func (*Fingerprint) OptBool added in v2.6.0

func (f *Fingerprint) OptBool(b *bool) *Fingerprint

func (*Fingerprint) OptInt added in v2.6.0

func (f *Fingerprint) OptInt(v *int) *Fingerprint

func (*Fingerprint) OptString added in v2.6.0

func (f *Fingerprint) OptString(s *string) *Fingerprint

func (*Fingerprint) OptTime added in v2.6.0

func (f *Fingerprint) OptTime(t *time.Time) *Fingerprint

func (*Fingerprint) Present added in v2.6.0

func (f *Fingerprint) Present(ok bool) *Fingerprint

Present tags whether an optional nested value follows. Hash its fields only when it reports true.

func (*Fingerprint) String added in v2.6.0

func (f *Fingerprint) String(s string) *Fingerprint

String hashes s followed by a separator, so adjacent fields cannot be re-split ("ab"+"c" must not match "a"+"bc").

func (*Fingerprint) Strings added in v2.6.0

func (f *Fingerprint) Strings(items []string) *Fingerprint

Strings hashes a string slice including its length, so resizing or reordering changes the result.

func (*Fingerprint) Sum added in v2.6.0

func (f *Fingerprint) Sum() uint64

func (*Fingerprint) Time added in v2.6.0

func (f *Fingerprint) Time(t time.Time) *Fingerprint

type KeyedMutex added in v2.6.0

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

KeyedMutex hands out one mutex per key, so unrelated keys proceed concurrently while work on the same key is serialized.

Entries are reference counted and dropped once nobody holds or awaits them. The naive version of this — a sync.Map of *sync.Mutex — either grows one entry per key ever seen, or, if entries are deleted on release, hands two callers different mutexes for the same key and silently loses mutual exclusion. The reference count is taken under the map lock, so a key with waiters is never removed.

The zero value is ready to use.

func (*KeyedMutex) Lock added in v2.6.0

func (k *KeyedMutex) Lock(key string) func()

Lock blocks until the key's mutex is held and returns its unlock function. Intended to be deferred at the point of acquisition:

defer locks.Lock(id)()

func (*KeyedMutex) RLock added in v2.8.0

func (k *KeyedMutex) RLock(key string) func()

RLock blocks until the key's mutex is held for reading and returns its unlock function. Multiple readers for the same key may proceed concurrently.

func (*KeyedMutex) TryLock added in v2.6.0

func (k *KeyedMutex) TryLock(key string) (func(), bool)

TryLock acquires the key's mutex without blocking. It reports whether the lock was taken; the unlock function is only valid when it was.

Directories

Path Synopsis
Package acfs maps ACFS protocol types to Arcane workspace contracts.
Package acfs maps ACFS protocol types to Arcane workspace contracts.
Package dbutil provides small generic helpers around GORM that consolidate repetitive single-row lookup and transaction boilerplate found across services.
Package dbutil provides small generic helpers around GORM that consolidate repetitive single-row lookup and transaction boilerplate found across services.
Package iconcatalog resolves Arcane icon metadata into catalog URLs.
Package iconcatalog resolves Arcane icon metadata into catalog URLs.
Package imageref contains shared image-reference parsing operations.
Package imageref contains shared image-reference parsing operations.

Jump to

Keyboard shortcuts

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