ctx

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 22, 2020 License: GPL-3.0 Imports: 16 Imported by: 0

Documentation

Overview

Package ctx provides project-agnostic utility code for Go projects

Index

Constants

View Source
const (

	// ClientInactive reflects that a client session is ending because the client side has been inactive
	ClientInactive = "client inactive"

	// HostShuttingDown means that a client session is ending because the host machine/server is shutting down.
	HostShuttingDown = "host shutting down"

	// SessionTokenKey is the string name used to key the session token string (i.e. "session_token")
	SessionTokenKey = "session_token"
)

Variables

View Source
var (
	// File system related
	DirAlreadyExists = &ctxErr{"for safety, dir must not already exist"}

	// ctx.Context
	ErrCtxNotRunning = &ctxErr{"context not running"}

	// session/tokens
	ErrSessTokenMissing  = &ctxErr{"session token was not found in the request context"}
	ErrSessTokenNotValid = &ctxErr{"session token was not valid"}
)

Errors

Functions

func ApplyTokenOutgoingContext

func ApplyTokenOutgoingContext(ctx context.Context, inToken []byte) context.Context

ApplyTokenOutgoingContext applies the given binary string to the given context, encoding it into a base64 string.

func ExtractSessionToken

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

ExtractSessionToken extracts the session_token from the given context

func Fatalf

func Fatalf(inFormat string, args ...interface{})

Fatalf -- see Fatalf (above)

func Go

func Go(
	inHost Ctx,
	inProcess func(inHost Ctx),
)

Go starts inProcess() in its own go routine while preventing inHostCtx from stopping until inProcess has completed.

In effect, CtxGo(inHostCtx, inProcess) replaces:

	go inProcess(inHostCtx)

The presumption here is that inProcess will exit from some trigger *other* than inHost.CtxWait()

func TransferSessionToken

func TransferSessionToken(ctx context.Context, md metadata.MD) (context.Context, error)

TransferSessionToken extracts and transfers the session token from the given context and returns a replacement with it appended to the metadata

Types

type ClientSession

type ClientSession struct {

	// SessionToken is handed back to remote pnode clients during authentication and used to retrieve a ClientSession
	//     in O(1) given a matching token string at later times.
	SessionToken string

	// PrevActivityTime says when this session was last accessed, used to know how long a session has been idle.
	PrevActivityTime int64

	// OnEndSession performs any closing/cleanup associated with the given session.
	// Note: this is called via goroutine, so concurrency considerations should be made.
	OnEndSession func(session *ClientSession, reason string)

	// Used to store an impl specific info
	Cookie interface{}
}

ClientSession represents a client session over gRPC

type Context

type Context struct {
	Logger

	Ctx        context.Context
	FaultLog   []error
	FaultLimit int
	// contains filtered or unexported fields
}

Context is a service helper.

func (*Context) AttachGrpcServer

func (C *Context) AttachGrpcServer(
	inNetwork string,
	inNetAddr string,
	ioServer *grpc.Server,
) error

AttachGrpcServer opens a new net.Listener for the given netwok params and then serves ioServer.

Appropriate calls are set up so that:

  1. ioServer exiting will trigger CtxStop().
  2. When this Context is about to stop, ioServer.GracefulStop is called.

func (*Context) AttachInterruptHandler

func (C *Context) AttachInterruptHandler()

AttachInterruptHandler creates a new interupt handler and fuses it w/ the given context

func (*Context) BaseContext

func (C *Context) BaseContext() *Context

BaseContext allows the holder of a Ctx to get the raw/underlying Context.

func (*Context) CtxAddChild

func (C *Context) CtxAddChild(
	inChild Ctx,
	inID []byte,
)

CtxAddChild adds the given Context as a "child", where C will initiate CtxStop() on each child before C carries out its own stop.

func (*Context) CtxGetChildByID

func (C *Context) CtxGetChildByID(
	inChildID []byte,
) Ctx

CtxGetChildByID returns the child Context with the match ID (or nil if not found).

func (*Context) CtxGo

func (C *Context) CtxGo(
	inProcess func(),
)

CtxGo is lesser more convenient variant of Go().

func (*Context) CtxOnFault

func (C *Context) CtxOnFault(inErr error, inDesc string)

CtxOnFault is called when the given error has occurred an represents an unexpected fault that alone doesn't justify an emergency condition. (e.g. a db error while accessing a record). Call this on unexpected errors.

If inErr == nil, this call has no effect.

THREADSAFE

func (*Context) CtxRunning

func (C *Context) CtxRunning() bool

CtxRunning returns true has been started and has not stopped. See also CtxStopped(). This is typically used to detect if/when a dependent workflow should cease.

THREADSAFE

func (*Context) CtxStart

func (C *Context) CtxStart(
	onStartup func() error,
	onAboutToStop func(),
	onChildAboutToStop func(inChild Ctx),
	onStopping func(),
) error

CtxStart blocks until the given onStartup proc is complete started up or stopped (if an err is returned).

See notes for CtxInitiateStop()

func (*Context) CtxStatus

func (C *Context) CtxStatus() error

CtxStatus returns an error if this Context has not yet started, is stopping, or has stopped.

THREADSAFE

func (*Context) CtxStop

func (C *Context) CtxStop(
	inReason string,
	inReleaseOnComplete *sync.WaitGroup,
) bool

CtxStop initiates a stop of this Context, calling inReleaseOnComplete.Done() when this context is fully stopped (if provided).

If C.CtxStop() is being called for the first time, true is returned. If it has already been called (or is in-flight), then false is returned and this call effectively is a no-op (but still honors in inReleaseOnComplete).

The following are equivalent:

		initiated := c.CtxStop(reason, waitGroup)

		initiated := c.CtxStop(reason, nil)
		c.CtxWait()
		if waitGroup != nil {
			waitGroup.Done()
		}

When C.CtxStop() is called (for the first time):

  1. C.onAboutToStop() is called (if provided to C.CtxStart)
  2. if C has a parent, C is detached and the parent's onChildAboutToStop(C) is called (if provided to C.CtxStart).
  3. C.CtxStopChildren() is called, blocking until all children are stopped (recursive)
  4. C.Ctx is cancelled, causing onStopping() to be called (if provided) and any <-CtxStopping() calls to be unblocked.
  5. C's onStopping() is called (if provided to C.CtxStart)
  6. After the last call to C.CtxGo() has completed, C.CtxWait() is released.

func (*Context) CtxStopChildren

func (C *Context) CtxStopChildren(inReason string)

CtxStopChildren initiates a stop on each child and blocks until complete.

func (*Context) CtxStopReason

func (C *Context) CtxStopReason() string

CtxStopReason returns the reason provided by the stop initiator.

func (*Context) CtxStopped

func (C *Context) CtxStopped() bool

CtxStopped returns true if CtxStop() is currently in flight (or has completed).

Warning: this is NOT the opposite of CtxRunning(). C.CtxStopped() will return true when C.CtxStop() is called vs C.CtxRunning() will return true until all of C's children have stopped.

THREADSAFE

func (*Context) CtxStopping

func (C *Context) CtxStopping() <-chan struct{}

CtxStopping allows callers to wait until this context is stopping.

func (*Context) CtxWait

func (C *Context) CtxWait()

CtxWait blocks until this Context has completed stopping (following a CtxInitiateStop). Returns true if this call initiated the shutdown (vs another cause)

THREADSAFE

type Ctx

type Ctx interface {
	BaseContext() *Context
}

Ctx is an abstraction for a context that can stopped/aborted.

Ctx serves as a vehicle between a Content expressed as *struct or as an interface (which can be upcast).

type Logger

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

Logger is an aid to logging and provides convenience functions

func (*Logger) Error

func (l *Logger) Error(args ...interface{})

Error logs to the ERROR, WARNING, and INFO logs. Arguments are handled like fmt.Print(); a newline is appended if missing.

Errors are reserved for situations that indicate an implementation deficiency, a corruption of data or resources, or an issue that if not addressed could spiral into deeper issues. Logging an error reflects that correctness or expected behavior is either broken or under threat.

func (*Logger) Errorf

func (l *Logger) Errorf(inFormat string, args ...interface{})

Errorf logs to the ERROR, WARNING, and INFO logs. Arguments are handled like fmt.Print; a newline is appended if missing.

See comments above for Error() for guidelines on errors vs warnings.

func (*Logger) Fatalf

func (l *Logger) Fatalf(inFormat string, args ...interface{})

Fatalf logs to the FATAL, ERROR, WARNING, and INFO logs, Arguments are handled like fmt.Printf(); a newline is appended if missing.

func (*Logger) GetLogLabel

func (l *Logger) GetLogLabel() string

GetLogLabel returns the label last set via SetLogLabel()

func (*Logger) GetLogPrefix added in v0.0.3

func (l *Logger) GetLogPrefix() string

GetLogPrefix returns the the text that prefixes all log messages for this context.

func (*Logger) Info

func (l *Logger) Info(inVerboseLevel int32, args ...interface{})

Info logs to the INFO log. Arguments are handled like fmt.Print(); a newline is appended if missing.

Verbose level conventions:

  1. Enabled during production and field deployment. Use this for important high-level info.
  2. Enabled during testing and development. Use for high-level changes in state, mode, or connection.
  3. Enabled during low-level debugging and troubleshooting.

func (*Logger) Infof

func (l *Logger) Infof(inVerboseLevel int32, inFormat string, args ...interface{})

Infof logs to the INFO log. Arguments are handled like fmt.Printf(); a newline is appended if missing.

See comments above for Info() for guidelines for inVerboseLevel.

func (*Logger) LogV

func (l *Logger) LogV(inVerboseLevel int32) bool

LogV returns true if logging is currently enabled for log verbose level.

func (*Logger) SetLogLabel

func (l *Logger) SetLogLabel(inLabel string)

SetLogLabel sets the label prefix for all entries logged.

func (*Logger) Warn

func (l *Logger) Warn(args ...interface{})

Warn logs to the WARNING and INFO logs. Arguments are handled like fmt.Print(); a newline is appended if missing.

Warnings are reserved for situations that indicate an inconsistency or an error that won't result in a departure of specifications, correctness, or expected behavior.

func (*Logger) Warnf

func (l *Logger) Warnf(inFormat string, args ...interface{})

Warnf logs to the WARNING and INFO logs. Arguments are handled like fmt.Printf(); a newline is appended if missing.

See comments above for Warn() for guidelines on errors vs warnings.

type SessionGroup

type SessionGroup struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

SessionGroup takes a session token (a string) and hands back a ClientSession while ensuring concurrency safety.

func NewSessionGroup

func NewSessionGroup() SessionGroup

NewSessionGroup sets up a new SessionGroup for use

func (*SessionGroup) EndAllSessions

func (group *SessionGroup) EndAllSessions(inReason string)

EndAllSessions ends all sessions

func (*SessionGroup) EndInactiveSessions

func (group *SessionGroup) EndInactiveSessions(inExpirationTime int64)

EndInactiveSessions removes alls sessions inactive longer than the given time index -- THREADSAFE

func (*SessionGroup) EndSession

func (group *SessionGroup) EndSession(inSessionToken string, inReason string)

EndSession removes the given session from this SessionGroup -- THREADSAFE

func (*SessionGroup) FetchSession

func (group *SessionGroup) FetchSession(ctx context.Context) (*ClientSession, error)

FetchSession extracts the session token string from the context, performs a session lookup, and returns the ClientSession object.

func (*SessionGroup) InsertSession

func (group *SessionGroup) InsertSession(inSession *ClientSession)

InsertSession inserts the given session into this SessionGroup -- THREADSAFE

func (*SessionGroup) LookupSession

func (group *SessionGroup) LookupSession(inSessionToken string, inBumpActivity bool) *ClientSession

LookupSession returns the ClientSession having the given session token.

func (*SessionGroup) NewSession

func (group *SessionGroup) NewSession(
	ctx context.Context,
	inTokenOverride []byte,
) *ClientSession

NewSession creates a new ClientSession and inserts the session token into the given context

Jump to

Keyboard shortcuts

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