Skip to content

context #

Context

This module defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes.

Incoming requests to a server should create a Context, and outgoing calls to servers should accept a Context. The chain of function calls between them must propagate the Context, optionally replacing it with a derived Context created using with_cancel, with_deadline, with_timeout, or with_value. When a Context is canceled, all Contexts derived from it are also canceled.

The with_cancel, with_deadline, and with_timeout functions take a Context (the parent) and return a derived Context (the child). Calling the cancel function cancels the child and its children, removes the parent's reference to the child, and stops any associated timers.

Programs that use Contexts should follow these rules to keep interfaces consistent across different modules.

Do not store Contexts inside a struct type; instead, pass a Context explicitly to each function that needs it. The Context should be the first parameter, typically named ctx, just to make it more consistent.

Examples

In this section you can see some usage examples for this module

Context With Cancellation

import time
import context

// This example demonstrates the use of a cancelable context to prevent a
// routine leak. By the end of the example function, the routine started
// by gen will return without leaking.
fn main() {
// gen generates integers in a separate routine and
// sends them to the returned channel.
// The callers of gen need to cancel the context once
// they are done consuming generated integers not to leak
// the internal routine started by gen.
gen := fn (mut ctx context.Context) chan int {
dst := chan int{}
spawn fn (mut ctx context.Context, dst chan int) {
mut v := 0
ch := ctx.done()
for {
select {
_ := <-ch {
// returning not to leak the routine
eprintln('> go thread returns because ctx was canceled/done')
return
}
dst <- v {
v++
}
}
}
}(mut ctx, dst)
return dst
}

mut background := context.background()
mut ctx, cancel := context.with_cancel(mut background)
defer {
cancel()
time.sleep(2 * time.millisecond) // give a small time window, in which the go thread routine has a chance to return
}

mut mut_ctx := ctx
mut ctx2 := &mut_ctx
ch := gen(mut ctx2)
for i in 0 .. 5 {
v := <-ch
println('> received value: ${v}')
assert i == v
}
println('> main is finished here')
}

Context With Deadline

import time
import context

const short_duration = 2 * time.millisecond // a reasonable duration to block in an example

// This example passes a context with an arbitrary deadline to tell a blocking
// function that it should abandon its work as soon as it gets to it.
fn main() {
dur := time.now().add(short_duration)
mut background := context.background()
mut ctx, cancel := context.with_deadline(mut background, dur)

defer {
// Even though ctx will be expired, it is good practice to call its
// cancellation function in any case. Failure to do so may keep the
// context and its parent alive longer than necessary.
cancel()
time.sleep(short_duration) // give a small time window, in which the go thread routine has a chance to return
eprintln('> defer block finishes')
}

ctx_ch := ctx.done()
select {
_ := <-ctx_ch {
println('>> read from ctx_ch succeeded')
}
1 * time.second {
panic('This should not happen')
}
}
eprintln('> main finishes')
}

Context With Timeout

import time
import context

const short_duration = 2 * time.millisecond // a reasonable duration to block in an example

// This example passes a context with a timeout to tell a blocking function that
// it should abandon its work after the timeout elapses.
fn main() {
// Pass a context with a timeout to tell a blocking function that it
// should abandon its work after the timeout elapses.
mut background := context.background()
mut ctx, cancel := context.with_timeout(mut background, short_duration)
defer {
cancel()
eprintln('> defer finishes')
}

ctx_ch := ctx.done()
select {
_ := <-ctx_ch {
eprintln('> reading from ctx_ch succeeded')
}
1 * time.second {
panic('This should not happen')
}
}
eprintln('> main finishes')
}

Context With Value

import context

const not_found_value = &Value{
val: 'key not found'
}

struct Value {
val string
}

// This example demonstrates how a value can be passed to the context
// and also how to retrieve it if it exists.
fn main() {
f := fn (ctx context.Context, key context.Key) &Value {
if value := ctx.value(key) {
match value {
Value {
return value
}
else {}
}
}
return not_found_value
}

key := 'language'
value := &Value{
val: 'VAL'
}
ctx := context.with_value(context.background(), key, value)

assert value == dump(f(ctx, key))
assert not_found_value == dump(f(ctx, 'color'))
}

fn background #

fn background() Context

background returns an empty Context. It is never canceled, has no values, and has no deadline. It is typically used by the main function, initialization, and tests, and as the top-level Context for incoming requests.

fn todo #

fn todo() Context

todo returns an empty Context. Code should use todo when it's unclear which Context to use or it is not yet available (because the surrounding function has not yet been extended to accept a Context parameter).

fn with_cancel #

fn with_cancel(mut parent Context) (Context, CancelFn)

with_cancel returns a copy of parent with a new done channel. The returned context's done channel is closed when the returned cancel function is called or when the parent context's done channel is closed, whichever happens first.

Canceling this context releases resources associated with it, so code should call cancel as soon as the operations running in this Context complete.

fn with_deadline #

fn with_deadline(mut parent Context, d time.Time) (Context, CancelFn)

with_deadline returns a copy of the parent context with the deadline adjusted to be no later than d. If the parent's deadline is already earlier than d, with_deadline(parent, d) is semantically equivalent to parent. The returned context's Done channel is closed when the deadline expires, when the returned cancel function is called, or when the parent context's Done channel is closed, whichever happens first.

Canceling this context releases resources associated with it, so code should call cancel as soon as the operations running in this Context complete.

fn with_timeout #

fn with_timeout(mut parent Context, timeout time.Duration) (Context, CancelFn)

with_timeout returns with_deadline(parent, time.now().add(timeout)).

Canceling this context releases resources associated with it, so code should call cancel as soon as the operations running in this Context complete

fn with_value #

fn with_value(parent Context, key Key, value Any) Context

with_value returns a copy of parent in which the value associated with key is val.

Use context Values only for request-scoped data that transits processes and APIs, not for passing optional parameters to functions.

The provided key must be comparable and should not be of type string or any other built-in type to avoid collisions between packages using context. Users of with_value should define their own types for keys

interface Any #

interface Any {}

Any represents a generic type for the ValueContext

interface Canceler #

interface Canceler {
	id string
mut:
	cancel(remove_from_parent bool, err IError)
	done() chan int
}

interface Context #

interface Context {
	deadline() ?time.Time
	value(key Key) ?Any
mut:
	done() chan int
	err() IError
}

Context is an interface that defined the minimum required functionality for a Context.

deadline() returns the time when work done on behalf of this context should be canceled. deadline returns none when no deadline is set. Successive calls to deadline return the same results.

value(key) returns an Optional that wraps the value associated with this context for key. It returns none if no value is associated with key. Successive calls to Value with the same key returns the same result.

Use context values only for request-scoped data that transits processes and API boundaries, not for passing optional parameters to functions.

A key identifies a specific value in a Context. Functions that wish to store values in Context typically allocate a key in a global variable then use that key as the argument to context.with_value and Context.value. A key can be any type that supports equality; modules should define keys as an unexported type to avoid collisions.

done() returns a channel that's closed when work done on behalf of this context should be canceled. done may return a closed channel if this context can never be canceled. Successive calls to done return the same value. The close of the done channel may happen asynchronously, after the cancel function returns.

with_cancel arranges for done to be closed when cancel is called; with_deadline arranges for done to be closed when the deadline expires; with_timeout arranges for done to be closed when the timeout elapses.

err() returns an IError based on some conditions If done is not yet closed, err returns none. If done is closed, err returns a non-none error explaining why: canceled if the context was canceled or deadline_exceeded if the context's deadline passed. After err returns a non-none error, successive calls to err return the same error.

fn (Context) str #

fn (ctx &Context) str() string

str returns the str method of the corresponding Context struct

fn (BackgroundContext) str #

fn (ctx &BackgroundContext) str() string

str returns a string describing the Context.

type CancelFn #

type CancelFn = fn ()

type Key #

type Key = bool | f32 | f64 | i16 | i64 | i8 | int | string | u16 | u32 | u64 | u8 | voidptr

Key represents the type for the ValueContext key

fn (TodoContext) str #

fn (ctx &TodoContext) str() string

str returns a string describing the Context.

struct CancelContext #

struct CancelContext {
	id string
mut:
	context  Context
	mutex    &sync.Mutex = sync.new_mutex()
	done     chan int
	children map[string]Canceler
	err      IError = none
}

A CancelContext can be canceled. When canceled, it also cancels any children that implement Canceler.

fn (CancelContext) deadline #

fn (ctx &CancelContext) deadline() ?time.Time

fn (CancelContext) done #

fn (mut ctx CancelContext) done() chan int

fn (CancelContext) err #

fn (mut ctx CancelContext) err() IError

fn (CancelContext) value #

fn (ctx &CancelContext) value(key Key) ?Any

fn (CancelContext) str #

fn (ctx &CancelContext) str() string

struct EmptyContext #

struct EmptyContext {}

An EmptyContext is never canceled, has no values.

fn (EmptyContext) deadline #

fn (ctx &EmptyContext) deadline() ?time.Time

fn (EmptyContext) done #

fn (ctx &EmptyContext) done() chan int

fn (EmptyContext) err #

fn (ctx &EmptyContext) err() IError

fn (EmptyContext) value #

fn (ctx &EmptyContext) value(key Key) ?Any

fn (EmptyContext) str #

fn (ctx &EmptyContext) str() string

struct TimerContext #

struct TimerContext {
	id string
mut:
	cancel_ctx CancelContext
	deadline   time.Time
}

A TimerContext carries a timer and a deadline. It embeds a CancelContext to implement done and err. It implements cancel by stopping its timer then delegating to CancelContext.cancel

fn (TimerContext) deadline #

fn (ctx &TimerContext) deadline() ?time.Time

fn (TimerContext) done #

fn (mut ctx TimerContext) done() chan int

fn (TimerContext) err #

fn (mut ctx TimerContext) err() IError

fn (TimerContext) value #

fn (ctx &TimerContext) value(key Key) ?Any

fn (TimerContext) cancel #

fn (mut ctx TimerContext) cancel(remove_from_parent bool, err IError)

fn (TimerContext) str #

fn (ctx &TimerContext) str() string

struct ValueContext #

struct ValueContext {
	key   Key
	value Any
mut:
	context Context
}

A ValueContext carries a key-value pair. It implements Value for that key and delegates all other calls to the embedded Context.

fn (ValueContext) deadline #

fn (ctx &ValueContext) deadline() ?time.Time

fn (ValueContext) done #

fn (mut ctx ValueContext) done() chan int

fn (ValueContext) err #

fn (mut ctx ValueContext) err() IError

fn (ValueContext) value #

fn (ctx &ValueContext) value(key Key) ?Any

fn (ValueContext) str #

fn (ctx &ValueContext) str() string