context

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2023 License: BSD-3-Clause Imports: 6 Imported by: 727

Documentation

Overview

Package context provides an implementation of context.Context with additional functionality used within the Vanadium code base. The functions in this package mirror those from the go library's context package with two key differences as documented below.

  1. context.T provides the concept of a 'root' context that is typically created by the runtime and made available to the application code. The WithRootCancel function creates a context from the root context that is detached from all of its parent contexts, except for the root, in terms of cancelation (both explicit and time based cancelation) but otherwise inherits all other state from its parent. Such contexts are used for asynchronous operations that persist past the return of the function tha created function. A typical use case would be a goroutine listening for new network connections. Canceling the immediate parent of these contexts has no effect on them; canceling the root context will lead to their cancelation and is therefore a convenient mechanism for the runtime to terminate all asynchronous/background processing when it is shutdown This gives these background processes the opportunity to clean up any external state.
  2. context.T provides access to logging functions and thus allows for different packages or code paths to be configured to use different loggers.

Note that since context.T implements context.Context (it embeds the interface) it can be passed in to code that expects context.Context. In addition APIs that do not manipulate the context using the functions in this package should be written to expect a context.Context rather than *context.T.

Application code receives contexts in two main ways:

1) A context.T is returned from v23.Init(). This will generally be used to set up servers in main, or for stand-alone client programs.

func main() {
  ctx, shutdown := v23.Init()
  defer shutdown()

  doSomething(ctx)
}

2) A context.T is passed to every server method implementation as the first parameter.

func (m *myServer) Method(ctx *context.T, call rpc.ServerCall) error {
  doSomething(ctx)
}

Once you have a context you can derive further contexts to change settings. for example to adjust a deadline you might do:

func main() {
  ctx, shutdown := v23.Init()
  defer shutdown()
  // We'll use cacheCtx to lookup data in memcache
  // if it takes more than a second to get data from
  // memcache we should just skip the cache and perform
  // the slow operation.
  cacheCtx, cancel := WithTimeout(ctx, time.Second)
  if err := FetchDataFromMemcache(cacheCtx, key); err != nil {
    // Here we use the original ctx, not the derived cacheCtx
    // so we aren't constrained by the 1 second timeout.
    RecomputeData(ctx, key)
  }
}

Index

Constants

This section is empty.

Variables

View Source
var Canceled = context.Canceled

Canceled is returned by contexts which have been canceled.

View Source
var DeadlineExceeded = context.DeadlineExceeded

DeadlineExceeded is returned by contexts that have exceeded their deadlines and therefore been canceled automatically.

Functions

func LoggerFromContext added in v0.1.10

func LoggerFromContext(ctx context.Context) logging.Logger

LoggerFromContext returns the implementation of the logger associated with this context. It should almost never need to be used by application code.

func LoggingPrefix added in v0.1.10

func LoggingPrefix(ctx *T) interface{}

LoggingPrefix returns the value set by the most recent call of WithLoggingPrefix.

func RootContext

func RootContext() (*T, CancelFunc)

RootContext creates a new root context with no data attached. A RootContext is cancelable (see WithCancel). Typically you should not call this function, instead you should derive contexts from other contexts, such as the context returned from v23.Init or the result of the Context() method on a ServerCall. This function is sometimes useful in tests, where it is undesirable to initialize a runtime to test a function that reads from a T.

func WithCancel

func WithCancel(parent *T) (*T, CancelFunc)

WithCancel returns a child of the current context along with a function that can be used to cancel it. After cancel() is called the channels returned by the Done() methods of the new context (and all context further derived from it) will be closed.

func WithDeadline

func WithDeadline(parent *T, deadline time.Time) (*T, CancelFunc)

WithDeadline returns a child of the current context along with a function that can be used to cancel it at any time (as from WithCancel). When the deadline is reached the context will be automatically cancelled. Contexts should be cancelled when they are no longer needed so that resources associated with their timers may be released.

func WithRootCancel

func WithRootCancel(parent *T) (*T, CancelFunc)

WithRootCancel returns a context derived from parent, but that is detached from the deadlines and cancellation hierarchy so that this context will only ever be canceled when the returned CancelFunc is called, or the RootContext from which this context is ultimately derived is canceled.

func WithTimeout

func WithTimeout(parent *T, timeout time.Duration) (*T, CancelFunc)

WithTimeout is similar to WithDeadline except a Duration is given that represents a relative point in time from now.

Types

type CancelFunc

type CancelFunc context.CancelFunc

CancelFunc is the signature of the function used to cancel a context.

type Logger added in v0.1.10

type Logger interface {
	// InfoDepth logs to the INFO log. depth is used to determine which call frame to log.
	InfoDepth(ctx *T, depth int, args ...interface{})

	// InfoStack logs the current goroutine's stack if the all parameter
	// is false, or the stacks of all goroutines if it's true.
	InfoStack(ctx *T, all bool)

	// VDepth returns true if the configured logging level is greater than or equal to its parameter. depth
	// is used to determine which call frame to test against.
	VDepth(ctx *T, depth int, level int) bool

	// VIDepth is like VDepth, except that it returns nil if there level is greater than the
	// configured log level.
	VIDepth(ctx *T, depth int, level int) Logger

	// Flush flushes all pending log I/O.
	FlushLog()
}

Logger is a logger that uses a passed in T to configure the logging behavior; it is called by the correspoding logging methods of *T.

type T

type T struct {
	context.Context
	// contains filtered or unexported fields
}

T carries deadlines, cancellation and data across API boundaries. It is safe to use a T from multiple goroutines simultaneously. The zero-type of context is uninitialized and will panic if used directly by application code. It also implements v23/logging.Logger and hence can be used directly for logging (e.g. ctx.Infof(...)).

func FromGoContext

func FromGoContext(ctx context.Context) *T

FromGoContext creates a Vanadium Context object from a generic Context. If the implementation of ctx is a *T it will be returned, if not, a new *T will be created with a default logger that discards its output.

func FromGoContextWithValues added in v0.1.10

func FromGoContextWithValues(ctx context.Context, peer *T) *T

FromGoContextWithValues is like FromGoContext except that it will copy values from the specified 'peer' *T to a newly created *T. Note that if the supplied context is already a *T it will returned directly and no values will be copied to it.

func WithContextLogger

func WithContextLogger(parent *T, logger Logger) *T

WithContextLogger returns a child of the current context that embeds the supplied context logger.

func WithLogger

func WithLogger(parent *T, logger logging.Logger) *T

WithLogger returns a child of the current context that embeds the supplied logger.

func WithLoggingPrefix added in v0.1.10

func WithLoggingPrefix(parent *T, prefix interface{}) *T

WithLoggingPrefix returns a child of the current context that embeds the supplied prefix. The prefix will be prepended to all log output, both formated and unformatted.

func WithValue

func WithValue(parent *T, key interface{}, val interface{}) *T

WithValue returns a child of the current context that will return the given val when Value(key) is called.

func (*T) Error

func (t *T) Error(args ...interface{})

Error immplements and calls logging.ErrorLog; it calls the registered Logger and then the registered ContextLogger.

func (*T) ErrorDepth

func (t *T) ErrorDepth(depth int, args ...interface{})

ErrorDepth immplements and calls logging.ErrorLog; it calls the registered Logger and then the registered ContextLogger.

func (*T) Errorf

func (t *T) Errorf(format string, args ...interface{})

Errorf immplements and calls logging.ErrorLog; it calls the registered Logger and then the registered ContextLogger.

func (*T) Fatal

func (t *T) Fatal(args ...interface{})

Fatal implements logging.FatalLog; it calls the registered Logger but not the ContextLogger.

func (*T) FatalDepth

func (t *T) FatalDepth(depth int, args ...interface{})

FatalDepth implements logging.FatalLog; it calls the registered Logger but not the ContextLogger.

func (*T) Fatalf

func (t *T) Fatalf(format string, args ...interface{})

Fatalf implements logging.FatalLog; it calls the registered Logger but not the ContextLogger.

func (*T) FlushLog

func (t *T) FlushLog()

Flush flushes all pending log I/O.

func (*T) Info

func (t *T) Info(args ...interface{})

Info implements logging.InfoLog, it calls the registered Logger and then the registered ContextLogger.

func (*T) InfoDepth

func (t *T) InfoDepth(depth int, args ...interface{})

InfoDepth implements logging.InfoLog; it calls the registered Logger and then the registered ContextLogger.

func (*T) InfoStack

func (t *T) InfoStack(all bool)

InfoStack implements logging.InfoLog; it calls the registered Logger and then the registered ContextLogger.

func (*T) Infof

func (t *T) Infof(format string, args ...interface{})

Infof implements logging.InfoLog; it calls the registered Logger and then the registered ContextLogger.

func (*T) Initialized

func (t *T) Initialized() bool

Initialized returns true if this context has been properly initialized by a runtime.

func (*T) Panic

func (t *T) Panic(args ...interface{})

Panic implements logging.PanicLog; it calls the registered Logger but not the ContextLogger.

func (*T) PanicDepth

func (t *T) PanicDepth(depth int, args ...interface{})

PanicDepth implements logging.PanicLog; it calls the registered Logger but not the ContextLogger.

func (*T) Panicf

func (t *T) Panicf(format string, args ...interface{})

Panicf implements logging.PanicLog; it calls the registered Logger but not the ContextLogger.

func (*T) V

func (t *T) V(level int) bool

V implements logging.Verbosity; it returns the 'or' of the values returned by the register Logger and ContextLogger.

func (*T) VDepth

func (t *T) VDepth(depth int, level int) bool

VDepth implements logging.Verbosity; it returns the 'or' of the values returned by the register Logger and ContextLogger.

func (*T) VI

func (t *T) VI(level int) interface {
	Info(args ...interface{})
	Infof(format string, args ...interface{})
	InfoDepth(depth int, args ...interface{})
	InfoStack(all bool)
}

VI implements logging.Verbosity.

func (*T) VIDepth

func (t *T) VIDepth(depth int, level int) interface {
	Info(args ...interface{})
	Infof(format string, args ...interface{})
	InfoDepth(depth int, args ...interface{})
	InfoStack(all bool)
}

VIDepth implements logging.Verbosity.

func (*T) Value

func (t *T) Value(key interface{}) interface{}

Value implements context.Value.

Jump to

Keyboard shortcuts

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