ballerina/runtime module

Module overview

This module includes functions to interact with the runtime, the invocation context and to manage errors.

Invocation Context

The Invocation Context is a data holder that is created per request and preserved for a single request-response flow. The Invocation Context comprises of a unique ID, a UserPrincipal instance that includes user details and an AuthenticationContext instance that has the authentication related details if available.

Errors

The runtime module includes the NullReferenceException and IllegalStateException error types. These two error types wrap the error type defined in the ballerina/runtime module. Furthermore, there are utility methods to retrieve the current call stack and the particular call stack frame for an error.

Additionally, the runtime module also contains utility methods to halt a worker (sleep) for a given period of time and to look up properties from the runtime context.

Samples

The following sample shows how to access the Invocation Context, set data to it and access the same.

import ballerina/io;
import ballerina/runtime;

// Set data to the Invocation Context.

// Set the username as ‘tom’.
runtime:getInvocationContext().principal.username = "tom";

// Set claims.
map<any> claims = { email: "tom@ballerina.com", org: "wso2" };
runtime:getInvocationContext().principal.claims = claims;

// Set scopes.
string[] scopes = ["email", "profile"];
runtime:getInvocationContext().principal.scopes = scopes;

// Set auth scheme.
runtime:getInvocationContext().authenticationContext.scheme = "jwt";

// Set auth token.
runtime:getInvocationContext().authenticationContext.authToken = "abc.pqr.xyz";

// Retrieve data from the invocation context.

// Retrieve user name.
string userName = runtime:getInvocationContext().principal.username;
io:println(userName);

// Retrieve claims.
map<any> retrievedClaims = runtime:getInvocationContext().principal.claims;
io:println(retrievedClaims);

// Retrieve scopes.
string[] retrievedScopes = runtime:getInvocationContext().principal.scopes;
io:println(retrievedScopes);

// retrieve auth scheme.
string authScheme = runtime:getInvocationContext().authenticationContext.scheme;
io:println(authScheme);

// Retrieve auth token.
string token = runtime:getInvocationContext().authenticationContext.authToken;
io:println(token);

The following sample shows how to halt the current worker for a given time period.

import ballerina/runtime;

// Sleep the current worker for 5 seconds.
runtime:sleep(5000);

The following sample shows how to access properties from the runtime.

import ballerina/runtime;

// Retrieve the property ‘ballerina version’ from the runtime.
runtime:getProperty("ballerina.version");

The following sample shows how to access the call stack and how to trap an error.

import ballerina/io;
import ballerina/runtime;

public function main() {
    // Print the current call stack.
    io:println(runtime:getCallStack());
    var errorMessage = trap getError();
    if (errorMessage is error) {
        io:println(errorMessage.reason());
    }
}

function getError() {
    panicWithError();
}

function panicWithError() {
    // Create an error with a reason.
    error e = error("error occured");
    panic e;
}

Module Detail

Records

Record Description
AuthenticationContext Represents the AuthenticationContext, populated with authenticated information.
CallStackElement Representation of `CallStackElement`
InvocationContext Represents the InvocationContext.
Principal Represents the Principal, populated with authenticated user information.

Functions

Function Description
getCallStack

Retrieves the Call Stack

getErrorCallStackFrame

Retrieves the Call Stack Frame for a particular error

getInvocationContext

Creates a InvocationContext instance.

getProperty

Returns the value associated with the specified property name.

sleep

Halts the current worker for a predefined amount of time.

timeout

Gives a timeout to the current worker for a predefined amount of time.

public type AuthenticationContext

Represents the AuthenticationContext, populated with authenticated information.

Field Name Data Type Default Value Description
scheme string

Authentication token type. e.g: JWT etc.

authToken string

Relevant token for the schema.

public type CallStackElement

Representation of `CallStackElement`

Field Name Data Type Default Value Description
callableName string

Callable name

moduleName string

Module name

fileName string

File name

lineNumber int

Line number

public type InvocationContext

Represents the InvocationContext.

Field Name Data Type Default Value Description
id string

Unique id generated when initiating the invocation context.

principal runtime:Principal

User principal instance.

authenticationContext runtime:AuthenticationContext

Authentication context instance.

attributes map

Context attributes.

public type Principal

Represents the Principal, populated with authenticated user information.

Field Name Data Type Default Value Description
userId string

User Id of the authenticated user.

username string

Username of the authenticated user.

claims map

Claims of the authenticated user.

scopes string[]

Authenticated user scopes.

public function getCallStack() returns (CallStackElement[])

Retrieves the Call Stack

Return Type Description
CallStackElement[]

Array of CallStackElement elements

public function getErrorCallStackFrame(error? e) returns (CallStackElement[])

Retrieves the Call Stack Frame for a particular error

Parameter Name Data Type Default Value Description
e error?

optional error instance

Return Type Description
CallStackElement[]

Array of CallStackElement elements

public function getInvocationContext() returns (InvocationContext)

Creates a InvocationContext instance.

Return Type Description
InvocationContext

InvocationContext instance

public function getProperty(string name) returns (string)

Returns the value associated with the specified property name.

Parameter Name Data Type Default Value Description
name string

Name of the property

Return Type Description
string

Value of the property if the property exists, an empty string otherwise

public function sleep(int millis)

Halts the current worker for a predefined amount of time.

Parameter Name Data Type Default Value Description
millis int

Amount of time to sleep in milliseconds

public function timeout(int millis) returns (future<null>)

Gives a timeout to the current worker for a predefined amount of time.

Parameter Name Data Type Default Value Description
millis int

Amount of time needed for the timeout in milliseconds

Return Type Description
future

Future to be invoked after the timeout