Skip to content

context.onecontext #

onecontext

A library to merge existing V contexts.

Overview

Have you ever faced the situation where you have to merge multiple existing contexts? If not, then you might, eventually.

For example, we can face the situation where we are building an application using a library that gives us a global context. This context expires once the application is stopped.

Meanwhile, we are exposing a service like this:

fn (f Foo) get(ctx context.Context, bar Bar) ?Baz {
    . . .
}

Here, we receive another context provided by the service.

Then, in the get implementation, we want for example to query a database and we must provide a context for that.

Ideally, we would like to provide a merged context that would expire either:

  • When the application is stopped
  • Or when the received service context expires

This is exactly the purpose of this library.

In our case, we can now merge the two contexts in a single one like this:

ctx, cancel := onecontext.merge(ctx1, ctx2)

This returns a merged context that we can now propagate

Constants #

const canceled = error('canceled context')

canceled is the error returned when the cancel function is called on a merged context

fn merge #

fn merge(ctx context.Context, ctxs ...context.Context) (context.Context, context.CancelFn)

merge allows to merge multiple contexts it returns the merged context

fn (OneContext) deadline #

fn (octx OneContext) deadline() ?time.Time

deadline returns the earliest deadline among all merged contexts, or none if no context has a deadline set.

fn (OneContext) done #

fn (octx OneContext) done() chan int

done returns the done channel, which is closed when the merged context is canceled.

fn (OneContext) err #

fn (mut octx OneContext) err() IError

err returns the error from the merged context, or none if not yet canceled.

fn (OneContext) value #

fn (octx OneContext) value(key context.Key) ?context.Any

value looks up a value by key across all merged contexts, returning the first match found or none if no context holds the key.

fn (OneContext) run #

fn (mut octx OneContext) run()

run starts listening for cancellation signals from all merged contexts.

fn (OneContext) str #

fn (octx OneContext) str() string

str returns a string representation of the OneContext.

fn (OneContext) cancel #

fn (mut octx OneContext) cancel(err IError)

cancel cancels the merged context with the given error, closing the done channel and propagating cancellation to the underlying context.

fn (OneContext) run_two_contexts #

fn (mut octx OneContext) run_two_contexts(mut ctx1 context.Context, mut ctx2 context.Context)

run_two_contexts spawns a listener that cancels the merged context when either of the two given contexts is done.

fn (OneContext) run_multiple_contexts #

fn (mut octx OneContext) run_multiple_contexts(mut ctx context.Context)

run_multiple_contexts spawns a listener that cancels the merged context when the given context is done.