util

package
v0.0.0-...-c32f71b Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: AGPL-3.0 Imports: 37 Imported by: 0

Documentation

Overview

Utilities

Module wide utilities, at the moment only shared grpc constants for healthcheck.

Index

Constants

View Source
const NameLength = 5

/ Generate a random name inspired by https://stackoverflow.com/a/46909816

Variables

View Source
var (
	Enable  = true
	Disable = false
)
View Source
var (
	// static HealthCheckResponse{Status: health.HealthCheckResponse_SERVING}
	HealthyResp = &health.HealthCheckResponse{Status: health.HealthCheckResponse_SERVING}
	// static HealthCheckResponse{Status: health.HealthCheckResponse_NOT_SERVING}
	DegradedResp = &health.HealthCheckResponse{Status: health.HealthCheckResponse_NOT_SERVING}
	// error for unsupported HealthServices
	ErrServiceNotFound = status.Error(codes.NotFound, "service not found")
	ErrLogicRace       = status.Error(codes.Internal, "unexpected state encountered")
	// error for env removal suppressed by config
	ErrEnvRemovalUnsupported = status.Error(codes.FailedPrecondition, "environment removal is not supported")
)
View Source
var (
	ErrConnectionTimeout = status.Error(codes.DeadlineExceeded, "timeout during initial connection")
)
View Source
var ErrEmptyName = errors.New("empty span name supplied for samples")
View Source
var ErrInvalidParameters = errors.New("neither window nor size may be <= 1")
View Source
var ErrRetriesExceeded = errors.New("write retries were exceeded")
View Source
var ISMRev = func() string {
	info, ok := debug.ReadBuildInfo()
	if ok && info.Main.Version != "" {
		rev := "ism"

		for _, val := range info.Settings {
			switch val.Key {
			case "vcs.revision":
				rev += "-" + val.Value
			case "vcs.modified":
				rev += "-dirty"
			}
		}

		if rev == "ism" {
			return "(devel)"
		} else {
			return rev
		}
	} else {
		return "(devel)"
	}
}()

build info for identification flags

Functions

func Clamp

func Clamp[X cmp.Ordered](x, lowerBound, upperBound X) X

clamp value to x \in [lowerBound, upperBound]

func HashPath

func HashPath(path []byte) string

hash path with fnv.64a hash to hex string

func MapMount

func MapMount(dir string, mounts MountMap) (string, bool)

helper for Executor.MapMount on a static mount map

func NewSampler

func NewSampler(
	conf *config.OtelDropSamplingConfig,
	next sdktrace.Sampler,
) (sdktrace.Sampler, error)

func ParseAddrPort

func ParseAddrPort(
	ctx context.Context, logger log.Logger,
	configCheck bool, rawAddrPort string,
) (netip.AddrPort, error)

parse a string of `[host]:[port]`

func RandomName

func RandomName() (string, error)

a random, 5 char name

func SSVString

func SSVString(ssv ServerStateValue) string

func SameStatus

func SameStatus(err, target error) bool

checks if a gRPC error and golang error have the same contents

func ValidatePrefix

func ValidatePrefix(prefix string) bool

check if container prefix matches [a-zA-Z0-9-_]+

Types

type ComponentState

type ComponentState struct {
	Ready chan struct{} // channel for awaiting component startup, if nil == component is disables
}

state of individual component, like broker or api

func (*ComponentState) Enabled

func (cs *ComponentState) Enabled() bool

type HealthService

type HealthService = string

supported grpc healthcheck services

var (
	BrokerHealthService   HealthService = "broker" // the broker, effectively the pool status
	ActiveInstanceService HealthService = "active" // the active instance
	BackupInstanceService HealthService = "backup" // the backup/replicate instance

	// collection of supported grpc healthcheck services
	HealthServices = []HealthService{
		BrokerHealthService,
		ActiveInstanceService,
		BackupInstanceService,
	}
)

type MountMap

type MountMap = map[string]string

map of path prefixes -> replacement prefixes

func ValidateMounts

func ValidateMounts(mountRefs []string, logger log.Logger) (MountMap, error)

type NotifierChan

type NotifierChan = chan struct{}

type OffsetTime

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

provider that passes through time.Now with a fixed offset

func (*OffsetTime) Now

func (ot *OffsetTime) Now() time.Time

equivalent of time.Time.Now

func (*OffsetTime) Reset

func (ot *OffsetTime) Reset()

resets timer offset to `0`

func (*OffsetTime) Skip

func (ot *OffsetTime) Skip(offset time.Duration)

increments internal timer offset

func (*OffsetTime) Unix

func (ot *OffsetTime) Unix() int64

equivalent of time.Time.Unix

type ReadyNotifier

type ReadyNotifier = chan<- struct{}

type ReadyReceiver

type ReadyReceiver = <-chan struct{}

type RoleState

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

container for state of each component

func NewRoleState

func NewRoleState(enabledRoles []config.ISMRole) *RoleState

create new role states from config values for roles NOTE: will panic if any role is not a valid ISMRole

func (*RoleState) AwaitStartup

func (rs *RoleState) AwaitStartup(ctx context.Context, logger log.Logger) bool

await startup of all roles and try to invoke sd_notify

func (*RoleState) Enabled

func (rs *RoleState) Enabled(role config.ISMRole) bool

check if role is enabled NOTE: will panic if role is not a valid ISMRole

func (*RoleState) Notifier

func (rs *RoleState) Notifier(role config.ISMRole) ReadyNotifier

return channel that will reflect readiness of role

func (*RoleState) NotifyStop

func (rs *RoleState) NotifyStop(logger log.Logger)

try use sd_notify to inform of shutdown

func (*RoleState) Ready

func (rs *RoleState) Ready(role config.ISMRole) ReadyReceiver

return channel that will reflect readiness of role

func (*RoleState) String

func (rs *RoleState) String() string

type RollingCounter

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

rolling counter that records success/failure for configurable window of `window` seconds

func NewRollingCounter

func NewRollingCounter(provider TimeProvider, size, window int64) (*RollingCounter, error)

func (*RollingCounter) Percentage

func (rc *RollingCounter) Percentage() (uint, float32)

return number of results and percentage of failed results in current window

func (*RollingCounter) Record

func (rc *RollingCounter) Record(result bool)

record a new result for the current window

func (*RollingCounter) Reset

func (rc *RollingCounter) Reset()

reset all counters

type Server

type Server struct {
	ID            string            // internal identifier
	Password      []byte            // isabelle password
	Addr          netip.AddrPort    // server address for clients
	ClientCount   atomic.Int32      // number of connected clients
	State         ServerState       // state of the server
	MonitorClient *isync.SyncClient // client for active monitoring
	LogMessages   chan string       // channel where log messages are forwarded
	CreationTime  time.Time         // time of container creation (unix timestamp)
}

reference to service instance

func (*Server) AttachClient

func (server *Server) AttachClient(
	ctx context.Context,
	logger log.Logger,
	client *isalink.IsaClient,
	connectionTimeout time.Duration,
) error

direct attach client (only viable when network is already setup)

func (*Server) Ready

func (srv *Server) Ready() bool

return whether server state == ServerReady, will return false if *Server is nil

type ServerState

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

Internal server state, formerly known as ready and healthy flags

func (*ServerState) CompareAndSwap

func (s *ServerState) CompareAndSwap(old ServerStateValue, new ServerStateValue) (swapped bool)

func (*ServerState) Load

func (s *ServerState) Load() ServerStateValue

func (*ServerState) Store

func (s *ServerState) Store(newValue ServerStateValue)

func (*ServerState) String

func (s *ServerState) String() string

type ServerStateValue

type ServerStateValue = byte
const (
	ServerUnknown   ServerStateValue = iota // server state not known
	ServerStarting                          // server is starting but not ready to accept connections
	ServerReady                             // server is ready to accept new connections
	ServerUnhealthy                         // server should not accept new connections and be terminated
	ServerShutdown                          // server has been shutdown, should only be used as part of ServerUpdate
)

type ServerUpdate

type ServerUpdate struct {
	ID    string           // server id, should correspond to a known Server.ID
	State ServerStateValue // new state of server
}

unit status update, should be received on rcfg.Updates after a call to Executor.Refresh

type StaticProvider

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

static provider with fixed time.Time, guaranteed to be monotonically increasing

func NewStaticProvider

func NewStaticProvider(now time.Time) *StaticProvider

func (*StaticProvider) Now

func (sp *StaticProvider) Now() time.Time

equivalent of time.Time.Now

func (*StaticProvider) Step

func (sp *StaticProvider) Step(step time.Duration)

advance internal timer by `step`, will panic if `step` is negative

func (*StaticProvider) Unix

func (sp *StaticProvider) Unix() int64

equivalent of time.Time.Unix

type SystemTime

type SystemTime struct{}

system provider that passes through time.Now

func (*SystemTime) Now

func (*SystemTime) Now() time.Time

equivalent of time.Time.Now

func (*SystemTime) Unix

func (*SystemTime) Unix() int64

equivalent of time.Time.Unix

type TimeProvider

type TimeProvider interface {
	// equivalent of [time.Time.Unix]
	Unix() int64
	// equivalent of [time.Time.Now]
	Now() time.Time
}

proxy for time.Time helper functions, all functions are goroutine safe

type Tracer

type Tracer struct {
	trace.Tracer
	// contains filtered or unexported fields
}

func InitTracer

func InitTracer(
	ctx context.Context,
	logger log.Logger,
	conf *config.OtelConfig,
	module string,
) (*Tracer, error)

Source Files

  • containers.go
  • counter.go
  • grpc.go
  • info.go
  • logger.go
  • net.go
  • otel.go
  • server.go
  • time.go

Jump to

Keyboard shortcuts

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